Skip to content

Commit

Permalink
core
Browse files Browse the repository at this point in the history
  • Loading branch information
seren5240 committed Aug 12, 2024
1 parent 4f46014 commit 91c0b5a
Show file tree
Hide file tree
Showing 76 changed files with 941 additions and 693 deletions.
30 changes: 16 additions & 14 deletions crates/core/src/analysis.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use anyhow::{anyhow, Result};
use grit_util::{traverse, Ast, AstNode, Order};
use grit_util::{
error::{GritPatternError, GritResult},
traverse, Ast, AstNode, Order,
};
use marzano_language::grit_parser::MarzanoGritParser;
use marzano_util::{cursor_wrapper::CursorWrapper, node_with_source::NodeWithSource};
use std::collections::BTreeMap;
Expand All @@ -23,8 +25,8 @@ fn walk_call_tree(
node: &NodeWithSource,
libs: &BTreeMap<String, String>,
grit_parser: &mut MarzanoGritParser,
predicate: &dyn Fn(&NodeWithSource) -> Result<bool>,
) -> Result<bool> {
predicate: &dyn Fn(&NodeWithSource) -> GritResult<bool>,
) -> GritResult<bool> {
let cursor = node.walk();
for n in traverse(cursor, Order::Pre) {
if predicate(&n)? {
Expand All @@ -35,7 +37,7 @@ fn walk_call_tree(
}
let name = n
.child_by_field_name("name")
.ok_or_else(|| anyhow!("missing name of nodeLike"))?;
.ok_or_else(|| GritPatternError::new("missing name of nodeLike"))?;
let name = name.text()?;
let name = OsStr::new(name.trim());
let maybe_call = libs
Expand All @@ -53,15 +55,15 @@ pub fn is_multifile(
root: &NodeWithSource,
libs: &BTreeMap<String, String>,
grit_parser: &mut MarzanoGritParser,
) -> Result<bool> {
) -> GritResult<bool> {
walk_call_tree(root, libs, grit_parser, &|n| Ok(n.node.kind() == "files"))
}

pub fn has_limit(
root: &NodeWithSource,
libs: &BTreeMap<String, String>,
grit_parser: &mut MarzanoGritParser,
) -> Result<bool> {
) -> GritResult<bool> {
walk_call_tree(root, libs, grit_parser, &|n| {
Ok(n.node.kind() == "patternLimit")
})
Expand All @@ -72,29 +74,29 @@ pub fn is_async(
root: &NodeWithSource,
libs: &BTreeMap<String, String>,
grit_parser: &mut MarzanoGritParser,
) -> Result<bool> {
) -> GritResult<bool> {
walk_call_tree(root, libs, grit_parser, &|n| {
if n.node.kind() != "nodeLike" {
return Ok(false);
}
let name = n
.child_by_field_name("name")
.ok_or_else(|| anyhow!("missing name of nodeLike"))?;
.ok_or_else(|| GritPatternError::new("missing name of nodeLike"))?;
let name = name.text()?;
Ok(name == "llm_chat")
})
}

/// Return true if the pattern attempts to define itself
pub fn defines_itself(root: &NodeWithSource, root_name: &str) -> Result<bool> {
pub fn defines_itself(root: &NodeWithSource, root_name: &str) -> GritResult<bool> {
let cursor = root.node.walk();
for n in traverse(CursorWrapper::new(cursor, root.source), Order::Pre) {
if n.node.kind() != "patternDefinition" {
continue;
}
let name = n
.child_by_field_name("name")
.ok_or_else(|| anyhow!("missing name of patternDefinition"))?;
.ok_or_else(|| GritPatternError::new("missing name of patternDefinition"))?;
let name = name.text()?;
let name = name.trim();
if name == root_name {
Expand All @@ -114,7 +116,7 @@ pub fn get_dependents_of_target_patterns_by_traversal_from_src(
src: &str,
parser: &mut MarzanoGritParser,
target_patterns: &[&String],
) -> Result<Vec<String>> {
) -> GritResult<Vec<String>> {
let mut dependents = <Vec<String>>::new();
let node_like = "nodeLike";
let predicate_call = "predicateCall";
Expand Down Expand Up @@ -146,7 +148,7 @@ pub fn get_dependents_of_target_patterns_by_traversal_from_src(
}) {
let name = n
.child_by_field_name("name")
.ok_or_else(|| anyhow!("missing name of nodeLike"))?;
.ok_or_else(|| GritPatternError::new("missing name of nodeLike"))?;
let name = name.text()?;
let name = name.trim().to_string();

Expand Down Expand Up @@ -178,7 +180,7 @@ fn find_child_tree_definition(
libs: &BTreeMap<String, String>,
traversed_stack: &mut Vec<String>,
name: &str,
) -> Result<Option<marzano_language::language::Tree>> {
) -> GritResult<Option<marzano_language::language::Tree>> {
if !traversed_stack.contains(&name.to_string()) {
if let Some(file_body) = libs.get(file_name) {
traversed_stack.push(name.to_owned());
Expand Down
49 changes: 30 additions & 19 deletions crates/core/src/api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{fs, problem::Problem, tree_sitter_serde::tree_sitter_node_to_json};
use anyhow::{bail, Result};
use grit_pattern_matcher::file_owners::FileOwner;
use grit_util::error::{GritPatternError, GritResult};
pub use grit_util::ByteRange;
use grit_util::{AnalysisLog as GritAnalysisLog, Ast, Position, Range, VariableMatch};
use im::Vector;
Expand Down Expand Up @@ -115,9 +115,9 @@ impl MatchResult {

pub(crate) fn file_to_match_result(
file: &Vector<&FileOwner<Tree>>,
) -> Result<Option<MatchResult>> {
) -> GritResult<Option<MatchResult>> {
if file.is_empty() {
bail!("cannot have file with no versions")
return Err(GritPatternError::new("cannot have file with no versions"));
} else if file.len() == 1 {
let file = file.last().unwrap();
if file.new {
Expand Down Expand Up @@ -288,7 +288,7 @@ pub fn is_match(result: &MatchResult) -> bool {

pub trait FileMatchResult {
fn file_name(&self) -> &str;
fn content(&self) -> Result<&str>;
fn content(&self) -> GritResult<&str>;
fn ranges(&mut self) -> &Vec<Range>;
// A verb representing the action taken on the file
fn action() -> &'static str;
Expand Down Expand Up @@ -395,13 +395,13 @@ impl FileMatchResult for Match {
fn action() -> &'static str {
"matched"
}
fn content(&self) -> Result<&str> {
fn content(&self) -> GritResult<&str> {
let Some(content) = self.content.as_deref() else {
bail!("No content in match")
return Err(GritPatternError::new("No content in match"));
};

if content.is_empty() {
bail!("No content in match")
return Err(GritPatternError::new("No content in match"));
} else {
Ok(content)
}
Expand Down Expand Up @@ -437,7 +437,7 @@ impl EntireFile {
}

/// Create an entire file from a file owner, including handling source maps and byte ranges
fn from_file(file: &FileOwner<Tree>) -> Result<Self> {
fn from_file(file: &FileOwner<Tree>) -> GritResult<Self> {
let mut basic = if let Some(source_map) = &file.tree.source_map {
let outer_source = source_map.fill_with_inner(&file.tree.source)?;

Expand Down Expand Up @@ -483,7 +483,7 @@ impl Rewrite {
fn file_to_rewrite(
initial: &FileOwner<Tree>,
rewritten_file: &FileOwner<Tree>,
) -> Result<Self> {
) -> GritResult<Self> {
let original = EntireFile::from_file(initial)?;
let rewritten = EntireFile::from_file(rewritten_file)?;
Ok(Rewrite::new(original, rewritten, None))
Expand All @@ -500,12 +500,12 @@ impl FileMatchResult for Rewrite {
fn action() -> &'static str {
"rewritten"
}
fn content(&self) -> Result<&str> {
fn content(&self) -> GritResult<&str> {
self.rewritten.content.as_deref().ok_or_else(|| {
anyhow::anyhow!(
GritPatternError::new(format!(
"No content in rewritten file {}",
self.rewritten.source_file
)
))
})
}
}
Expand Down Expand Up @@ -535,14 +535,19 @@ pub enum EnforcementLevel {
}

impl FromStr for EnforcementLevel {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
type Err = GritPatternError;
fn from_str(s: &str) -> GritResult<Self> {
match s {
"none" => Ok(EnforcementLevel::None),
"info" => Ok(EnforcementLevel::Info),
"warn" => Ok(EnforcementLevel::Warn),
"error" => Ok(EnforcementLevel::Error),
_ => bail!("'{}' is not a valid level", s),
_ => {
return Err(GritPatternError::new(format!(
"'{}' is not a valid level",
s
)))
}
}
}
}
Expand Down Expand Up @@ -628,9 +633,12 @@ impl FileMatchResult for CreateFile {
fn action() -> &'static str {
"created"
}
fn content(&self) -> Result<&str> {
fn content(&self) -> GritResult<&str> {
self.rewritten.content.as_deref().ok_or_else(|| {
anyhow::anyhow!("No content in created file {}", self.rewritten.source_file)
GritPatternError::new(format!(
"No content in created file {}",
self.rewritten.source_file
))
})
}
}
Expand Down Expand Up @@ -661,9 +669,12 @@ impl FileMatchResult for RemoveFile {
fn action() -> &'static str {
"removed"
}
fn content(&self) -> Result<&str> {
fn content(&self) -> GritResult<&str> {
self.original.content.as_deref().ok_or_else(|| {
anyhow::anyhow!("No content in removed file {}", self.original.source_file)
GritPatternError::new(format!(
"No content in removed file {}",
self.original.source_file
))
})
}
}
Expand Down
18 changes: 12 additions & 6 deletions crates/core/src/ast_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate::{
marzano_context::MarzanoContext, marzano_resolved_pattern::MarzanoResolvedPattern,
problem::MarzanoQueryContext,
};
use anyhow::{anyhow, Result};

use grit_pattern_matcher::{
binding::Binding,
Expand All @@ -11,7 +10,10 @@ use grit_pattern_matcher::{
ResolvedPattern, State,
},
};
use grit_util::{AnalysisLogs, AstNode, Language};
use grit_util::{
error::{GritPatternError, GritResult},
AnalysisLogs, AstNode, Language,
};
use marzano_language::language::{FieldId, LeafEquivalenceClass, MarzanoLanguage, SortId};
use marzano_util::node_with_source::NodeWithSource;

Expand Down Expand Up @@ -58,7 +60,7 @@ impl Matcher<MarzanoQueryContext> for ASTNode {
init_state: &mut State<'a, MarzanoQueryContext>,
context: &'a MarzanoContext,
logs: &mut AnalysisLogs,
) -> Result<bool> {
) -> GritResult<bool> {
let Some(binding) = binding.get_last_binding() else {
return Ok(false);
};
Expand Down Expand Up @@ -137,10 +139,14 @@ pub struct AstLeafNode {
}

impl AstLeafNode {
pub fn new<'a>(sort: SortId, text: &str, language: &impl MarzanoLanguage<'a>) -> Result<Self> {
pub fn new<'a>(
sort: SortId,
text: &str,
language: &impl MarzanoLanguage<'a>,
) -> GritResult<Self> {
let equivalence_class = language
.get_equivalence_class(sort, text)
.map_err(|e| anyhow!(e))?;
.map_err(|e| GritPatternError::new(e))?;
let text = text.trim();
Ok(Self {
sort,
Expand Down Expand Up @@ -169,7 +175,7 @@ impl Matcher<MarzanoQueryContext> for AstLeafNode {
_state: &mut State<'a, MarzanoQueryContext>,
_context: &'a MarzanoContext<'a>,
_logs: &mut AnalysisLogs,
) -> Result<bool> {
) -> GritResult<bool> {
let Some(node) = binding.get_last_binding().and_then(Binding::singleton) else {
return Ok(false);
};
Expand Down
Loading

0 comments on commit 91c0b5a

Please sign in to comment.