From d38f5c6575d5774d4508bdc4aea099280e139ad7 Mon Sep 17 00:00:00 2001 From: "Arend van Beelen jr." Date: Mon, 29 Apr 2024 10:11:24 +0200 Subject: [PATCH] Drop DEFAULT_FILE_NAME --- crates/cli/src/result_formatting.rs | 13 ++++--- .../snapshots/apply__terraform_complex.snap | 5 ++- .../plumbing__checks_invalid_patterns.snap | 2 +- crates/core/src/analysis.rs | 5 +-- crates/core/src/built_in_functions.rs | 14 ++++++-- crates/core/src/constants.rs | 2 -- crates/core/src/paths.rs | 20 +++-------- .../core/src/pattern_compiler/as_compiler.rs | 3 +- crates/core/src/pattern_compiler/compiler.rs | 30 ++++++++-------- .../core/src/pattern_compiler/not_compiler.rs | 4 +-- .../src/pattern_compiler/regex_compiler.rs | 2 +- .../src/pattern_compiler/rewrite_compiler.rs | 2 +- .../src/pattern_compiler/snippet_compiler.rs | 4 +-- .../src/pattern_compiler/step_compiler.rs | 4 +-- ...zano_core__test__compile_time_logging.snap | 5 ++- ...no_core__test__warning_rewrite_in_not.snap | 5 ++- ...gainst_snippet_regex_without_metavars.snap | 5 ++- ...warns_against_snippet_useless_rewrite.snap | 5 ++- crates/core/src/variables.rs | 12 +++---- crates/grit-pattern-matcher/src/constants.rs | 2 -- crates/grit-pattern-matcher/src/errors.rs | 5 +-- .../src/pattern/variable.rs | 36 ++++++++++--------- crates/grit-util/src/analysis_logs.rs | 2 +- crates/language/src/grit_parser.rs | 6 ++-- crates/language/src/language.rs | 2 +- 25 files changed, 92 insertions(+), 103 deletions(-) diff --git a/crates/cli/src/result_formatting.rs b/crates/cli/src/result_formatting.rs index 8d2b6d511..9520cf02c 100644 --- a/crates/cli/src/result_formatting.rs +++ b/crates/cli/src/result_formatting.rs @@ -7,7 +7,6 @@ use marzano_core::api::{ AllDone, AnalysisLog, CreateFile, DoneFile, FileMatchResult, InputFile, Match, MatchResult, PatternInfo, RemoveFile, Rewrite, }; -use marzano_core::constants::DEFAULT_FILE_NAME; use marzano_messenger::output_mode::OutputMode; use std::fmt::Display; use std::fs::read_to_string; @@ -76,7 +75,7 @@ fn print_all_done(item: &AllDone, f: &mut fmt::Formatter<'_>) -> fmt::Result { } fn print_error_log(log: &AnalysisLog, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let file_prefix = if log.file.is_empty() || log.file == DEFAULT_FILE_NAME { + let file_prefix = if log.file.is_empty() { "".to_owned() } else { format!("{}: ", log.file) @@ -87,8 +86,12 @@ fn print_error_log(log: &AnalysisLog, f: &mut fmt::Formatter<'_>) -> fmt::Result } else if log.level == 310 { style(log.message.to_string()).dim().fmt(f) } else if log.level == 441 { - let title = format!("Log in {}", log.file).bold(); - writeln!(f, "{}: {}", title, log.message)?; + if log.file.is_empty() { + writeln!(f, "{}", log.message)?; + } else { + let title = format!("Log in {}", log.file).bold(); + writeln!(f, "{}: {}", title, log.message)?; + } let empty_string = String::new(); let range = match log.range.as_ref() { Some(range) => indent( @@ -120,7 +123,7 @@ fn print_error_log(log: &AnalysisLog, f: &mut fmt::Formatter<'_>) -> fmt::Result /// Implement some log overrides to make CLI usage more friendly fn humanize_log(log: &mut AnalysisLog, input_pattern: &str) { if log.level == 299 - && (log.file.is_empty() || log.file == DEFAULT_FILE_NAME) + && log.file.is_empty() && (input_pattern.ends_with(".yaml") || input_pattern.ends_with(".yml")) { log.message = format!( diff --git a/crates/cli_bin/tests/snapshots/apply__terraform_complex.snap b/crates/cli_bin/tests/snapshots/apply__terraform_complex.snap index 06cc046f5..9ca12fc10 100644 --- a/crates/cli_bin/tests/snapshots/apply__terraform_complex.snap +++ b/crates/cli_bin/tests/snapshots/apply__terraform_complex.snap @@ -1,8 +1,8 @@ --- -source: apps/marzano/cli/tests/apply.rs +source: crates/cli_bin/tests/apply.rs expression: "String::from_utf8(output.stdout)?" --- -Log in PlaygroundPattern: Warning: sequential matches at the top of the file. If a pattern matched outside of a sequential, but no longer matches, it is likely because naked patterns are automatically wrapped with `contains bubble ` +Warning: sequential matches at the top of the file. If a pattern matched outside of a sequential, but no longer matches, it is likely because naked patterns are automatically wrapped with `contains bubble ` - Range: 47:5 - 47:20 - Source: engine marzano(0.1) @@ -91,4 +91,3 @@ Log in PlaygroundPattern: Warning: sequential matches at the top of the file. If Processed 4 files and found 4 matches - diff --git a/crates/cli_bin/tests/snapshots/plumbing__checks_invalid_patterns.snap b/crates/cli_bin/tests/snapshots/plumbing__checks_invalid_patterns.snap index 68a9164ac..95e5816f2 100644 --- a/crates/cli_bin/tests/snapshots/plumbing__checks_invalid_patterns.snap +++ b/crates/cli_bin/tests/snapshots/plumbing__checks_invalid_patterns.snap @@ -3,7 +3,7 @@ source: crates/cli_bin/tests/plumbing.rs expression: "String::from_utf8(result.stderr)?" --- Error: Failed to compile pattern `console.lo: engine_id: Some("marzano(0.1)") -file_name: Some("PlaygroundPattern") +file_name: None level: Some(299) message: "Pattern syntax error at 1:1. If you hit this error while running grit apply on a pattern from the Grit standard library, try running grit init. If you are running a custom pattern, check out the docs at https://docs.grit.io/ for help with writing patterns." position: Some(Position { line: 1, column: 1 }) diff --git a/crates/core/src/analysis.rs b/crates/core/src/analysis.rs index 26e9b9270..555f2f5fc 100644 --- a/crates/core/src/analysis.rs +++ b/crates/core/src/analysis.rs @@ -150,10 +150,7 @@ mod tests { "# .to_string(); let mut libs = BTreeMap::new(); - libs.insert( - "async_foo.grit".to_string(), - "llm_chat(messages=[])".to_string(), - ); + libs.insert("async_foo.grit".into(), "llm_chat(messages=[])".to_string()); let mut parser = MarzanoGritParser::new().unwrap(); let parsed = parser .parse_file(&src_code, Some(Path::new("test.grit"))) diff --git a/crates/core/src/built_in_functions.rs b/crates/core/src/built_in_functions.rs index 7d43b5868..03db49454 100644 --- a/crates/core/src/built_in_functions.rs +++ b/crates/core/src/built_in_functions.rs @@ -17,7 +17,10 @@ use im::Vector; use itertools::Itertools; use rand::prelude::SliceRandom; use rand::Rng; -use std::collections::BTreeMap; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; // todo we can probably use a macro to generate a function that takes a vec and // and calls the input function with the vec args unpacked. @@ -163,9 +166,14 @@ fn resolve_path_fn<'a>( None => return Err(anyhow!("No path argument provided for resolve function")), }; - let resolved_path = resolve(target_path, current_file.into())?; + let resolved_path = match ¤t_file { + Some(current_file) => resolve(Path::new(target_path.as_ref()), current_file)?, + None => PathBuf::from(target_path.as_ref()), + }; - Ok(ResolvedPattern::from_string(resolved_path)) + Ok(ResolvedPattern::from_string( + resolved_path.to_string_lossy().to_string(), + )) } fn capitalize(s: &str) -> String { diff --git a/crates/core/src/constants.rs b/crates/core/src/constants.rs index da384a6d5..8f0d9e016 100644 --- a/crates/core/src/constants.rs +++ b/crates/core/src/constants.rs @@ -1,3 +1 @@ -pub use grit_pattern_matcher::constants::DEFAULT_FILE_NAME; - pub const MAX_FILE_SIZE: usize = 1_000_000; diff --git a/crates/core/src/paths.rs b/crates/core/src/paths.rs index 086a1c978..8b2ccd009 100644 --- a/crates/core/src/paths.rs +++ b/crates/core/src/paths.rs @@ -1,7 +1,6 @@ use anyhow::anyhow; use anyhow::Result; use path_absolutize::Absolutize; -use std::borrow::Cow; use std::path::{Path, PathBuf}; #[cfg(feature = "absolute_filename")] @@ -16,23 +15,14 @@ pub(crate) fn absolutize(path: &Path) -> Result { Ok(path.to_owned()) } -pub(crate) fn resolve<'a>(target_path: Cow<'a, str>, from_file: Cow<'a, str>) -> Result { - let source_path = Path::new(from_file.as_ref()).parent().ok_or_else(|| { +pub(crate) fn resolve(target_path: &Path, from_file: &Path) -> Result { + let source_path = from_file.parent().ok_or_else(|| { anyhow!( "could not get parent directory of file name {}", - from_file.as_ref() + from_file.display() ) })?; - let our_path = Path::new(target_path.as_ref()); - let absolutized = our_path.absolutize_from(source_path)?; + let absolutized = target_path.absolutize_from(source_path)?; // path.push(target_path); - Ok(absolutized - .to_str() - .ok_or_else(|| { - anyhow!( - "could not build absolute path from file name {}", - target_path - ) - })? - .to_owned()) + Ok(absolutized.to_path_buf()) } diff --git a/crates/core/src/pattern_compiler/as_compiler.rs b/crates/core/src/pattern_compiler/as_compiler.rs index 9bb13f836..05eb31704 100644 --- a/crates/core/src/pattern_compiler/as_compiler.rs +++ b/crates/core/src/pattern_compiler/as_compiler.rs @@ -7,6 +7,7 @@ use anyhow::{anyhow, Result}; use grit_pattern_matcher::pattern::{Container, Match, Pattern, Predicate, Where}; use grit_util::{traverse, AnalysisLogBuilder, AstNode, Language, Order}; use marzano_util::{cursor_wrapper::CursorWrapper, node_with_source::NodeWithSource}; +use std::path::Path; pub(crate) struct AsCompiler; @@ -37,7 +38,7 @@ impl NodeCompiler for AsCompiler { let range = node.range(); let log = AnalysisLogBuilder::default() .level(441_u16) - .file(context.compilation.file) + .file(context.compilation.file.map(Path::to_owned)) .source(node.source) .position(range.start) .range(range) diff --git a/crates/core/src/pattern_compiler/compiler.rs b/crates/core/src/pattern_compiler/compiler.rs index 525b8cb44..66b1b5ffb 100644 --- a/crates/core/src/pattern_compiler/compiler.rs +++ b/crates/core/src/pattern_compiler/compiler.rs @@ -16,9 +16,7 @@ use crate::{ }; use anyhow::{anyhow, bail, Result}; use grit_pattern_matcher::{ - constants::{ - ABSOLUTE_PATH_INDEX, DEFAULT_FILE_NAME, FILENAME_INDEX, NEW_FILES_INDEX, PROGRAM_INDEX, - }, + constants::{ABSOLUTE_PATH_INDEX, FILENAME_INDEX, NEW_FILES_INDEX, PROGRAM_INDEX}, pattern::{ GritFunctionDefinition, PatternDefinition, PredicateDefinition, VariableSourceLocations, }, @@ -41,7 +39,7 @@ use std::{ use tracing::instrument; pub(crate) struct CompilationContext<'a> { - pub file: &'a str, + pub file: Option<&'a Path>, pub built_ins: &'a BuiltIns, pub lang: &'a TargetLanguage, pub pattern_definition_info: &'a BTreeMap, @@ -300,7 +298,7 @@ fn get_definitions( .sorted_by(|x, y| Ord::cmp(x.1, y.1)) .map(|x| VariableSourceLocations { name: x.0.clone(), - file: context.file.to_owned(), + file: context.file.map(Path::to_owned), locations: BTreeSet::new(), }) .collect(), @@ -308,7 +306,10 @@ fn get_definitions( for (file, pattern) in libs.iter() { let mut node_context = NodeCompilationContext { - compilation: &CompilationContext { file, ..*context }, + compilation: &CompilationContext { + file: Some(Path::new(file)), + ..*context + }, // We're not in a local scope yet, so this map is kinda useless. // It's just there because all node compilers expect one. vars: &mut BTreeMap::new(), @@ -488,7 +489,7 @@ fn filter_libs( ) -> Result> { let node_like = "nodeLike"; let predicate_call = "predicateCall"; - let tree = parser.parse_file(src, Some(Path::new(DEFAULT_FILE_NAME)))?; + let tree = parser.parse_file(src, None)?; let DefsToFilenames { patterns: pattern_file, predicates: predicate_file, @@ -500,10 +501,9 @@ fn filter_libs( let mut stack: Vec = if will_autowrap { let before_each_file = "before_each_file()"; - let before_tree = - parser.parse_file(before_each_file, Some(Path::new(DEFAULT_FILE_NAME)))?; + let before_tree = parser.parse_file(before_each_file, None)?; let after_each_file = "after_each_file()"; - let after_tree = parser.parse_file(after_each_file, Some(Path::new(DEFAULT_FILE_NAME)))?; + let after_tree = parser.parse_file(after_each_file, None)?; vec![tree, before_tree, after_tree] } else { @@ -559,7 +559,7 @@ fn find_definition_if_exists( if let Some(file_name) = files.get(name) { if !filtered.contains_key(file_name) { if let Some(file_body) = libs.get(file_name) { - filtered.insert(file_name.to_owned(), file_body.to_owned()); + filtered.insert(file_name.clone(), file_body.clone()); let tree = parser.parse_file(file_body, Some(Path::new(file_name)))?; return Ok(Some(tree)); } @@ -587,7 +587,7 @@ pub fn src_to_problem_libs( injected_limit: Option, ) -> Result { let mut parser = MarzanoGritParser::new()?; - let src_tree = parser.parse_file(&src, Some(Path::new(DEFAULT_FILE_NAME)))?; + let src_tree = parser.parse_file(&src, None)?; let lang = TargetLanguage::from_tree(&src_tree).unwrap_or(default_lang); src_to_problem_libs_for_language( src, @@ -616,7 +616,7 @@ pub fn src_to_problem_libs_for_language( let error = ". never matches and should not be used as a pattern. Did you mean to run 'grit apply .'?"; bail!(error); } - let src_tree = grit_parser.parse_file(&src, Some(Path::new(DEFAULT_FILE_NAME)))?; + let src_tree = grit_parser.parse_file(&src, None)?; let root = src_tree.root_node(); let mut built_ins = BuiltIns::get_built_in_functions(); @@ -641,7 +641,7 @@ pub fn src_to_problem_libs_for_language( } = get_definition_info(&libs, &root, grit_parser)?; let context = CompilationContext { - file: DEFAULT_FILE_NAME, + file: None, built_ins: &built_ins, lang: &lang, pattern_definition_info: &pattern_definition_indices, @@ -731,7 +731,7 @@ impl VariableLocations { let mut variables = vec![]; for (i, scope) in self.locations.iter().enumerate() { for (j, var) in scope.iter().enumerate() { - if var.file == DEFAULT_FILE_NAME { + if var.file.is_none() { variables.push(VariableMatch { name: var.name.clone(), scoped_name: format!("{}_{}_{}", i, j, var.name), diff --git a/crates/core/src/pattern_compiler/not_compiler.rs b/crates/core/src/pattern_compiler/not_compiler.rs index c3b1984b4..a73d1bd5d 100644 --- a/crates/core/src/pattern_compiler/not_compiler.rs +++ b/crates/core/src/pattern_compiler/not_compiler.rs @@ -32,7 +32,7 @@ impl NodeCompiler for NotCompiler { }) { let log = AnalysisLogBuilder::default() .level(441_u16) - .file(context.compilation.file) + .file(context.compilation.file.map(Into::into)) .source(node.source) .position(range.start) .range(range) @@ -68,7 +68,7 @@ impl NodeCompiler for PrNotCompiler { }) { let log = AnalysisLogBuilder::default() .level(441_u16) - .file(context.compilation.file) + .file(context.compilation.file.map(Into::into)) .source(node.source) .position(range.start) .range(range) diff --git a/crates/core/src/pattern_compiler/regex_compiler.rs b/crates/core/src/pattern_compiler/regex_compiler.rs index 211865e81..485f33257 100644 --- a/crates/core/src/pattern_compiler/regex_compiler.rs +++ b/crates/core/src/pattern_compiler/regex_compiler.rs @@ -56,7 +56,7 @@ impl NodeCompiler for RegexCompiler { ); let log = AnalysisLogBuilder::default() .level(441_u16) - .file(context.compilation.file) + .file(context.compilation.file.map(Into::into)) .source(node.source) .position(range.start) .range(range) diff --git a/crates/core/src/pattern_compiler/rewrite_compiler.rs b/crates/core/src/pattern_compiler/rewrite_compiler.rs index 46f829cd2..f57ee760d 100644 --- a/crates/core/src/pattern_compiler/rewrite_compiler.rs +++ b/crates/core/src/pattern_compiler/rewrite_compiler.rs @@ -43,7 +43,7 @@ impl NodeCompiler for RewriteCompiler { let range = node.range(); let log = AnalysisLogBuilder::default() .level(441_u16) - .file(context.compilation.file) + .file(context.compilation.file.map(Into::into)) .source(node.source) .position(range.start) .range(range) diff --git a/crates/core/src/pattern_compiler/snippet_compiler.rs b/crates/core/src/pattern_compiler/snippet_compiler.rs index 2b54c5dea..70a70ca83 100644 --- a/crates/core/src/pattern_compiler/snippet_compiler.rs +++ b/crates/core/src/pattern_compiler/snippet_compiler.rs @@ -10,7 +10,7 @@ use crate::{ use crate::{pattern_compiler::compiler::NodeCompilationContext, split_snippet::split_snippet}; use anyhow::{anyhow, bail, Result}; use grit_pattern_matcher::{ - constants::{DEFAULT_FILE_NAME, GLOBAL_VARS_SCOPE_INDEX}, + constants::GLOBAL_VARS_SCOPE_INDEX, pattern::{DynamicPattern, DynamicSnippet, DynamicSnippetPart, Pattern, Variable}, }; use grit_util::{AstNode, Language, Position, Range}; @@ -118,7 +118,7 @@ pub(crate) fn dynamic_snippet_from_source( *var, ))); } else if let Some(var) = context.global_vars.get(var.as_ref()) { - if context.compilation.file == DEFAULT_FILE_NAME { + if context.compilation.file.is_none() { context.vars_array[GLOBAL_VARS_SCOPE_INDEX][*var] .locations .insert(range); diff --git a/crates/core/src/pattern_compiler/step_compiler.rs b/crates/core/src/pattern_compiler/step_compiler.rs index 8c4378c0a..b316ae9c0 100644 --- a/crates/core/src/pattern_compiler/step_compiler.rs +++ b/crates/core/src/pattern_compiler/step_compiler.rs @@ -77,7 +77,7 @@ impl NodeCompiler for StepCompiler { let range = node.range(); let log = AnalysisLogBuilder::default() .level(441_u16) - .file(context.compilation.file) + .file(context.compilation.file.map(Into::into)) .source(node.source) .position(range.start) .range(range) @@ -100,7 +100,7 @@ impl NodeCompiler for StepCompiler { let range = node.range(); let log = AnalysisLogBuilder::default() .level(441_u16) - .file(context.compilation.file) + .file(context.compilation.file.map(Into::into)) .source(node.source) .position(range.start) .range(range) diff --git a/crates/core/src/snapshots/marzano_core__test__compile_time_logging.snap b/crates/core/src/snapshots/marzano_core__test__compile_time_logging.snap index cc6d2f8ea..97c8c3010 100644 --- a/crates/core/src/snapshots/marzano_core__test__compile_time_logging.snap +++ b/crates/core/src/snapshots/marzano_core__test__compile_time_logging.snap @@ -1,10 +1,9 @@ --- -source: apps/marzano/core/src/test.rs +source: crates/core/src/test.rs expression: res --- engine_id: None -file_name: Some("PlaygroundPattern") +file_name: None level: Some(441) message: "Warning: it is usually incorrect to redefine a variable $foo using as" position: Some(Position { line: 2, column: 5 }) - diff --git a/crates/core/src/snapshots/marzano_core__test__warning_rewrite_in_not.snap b/crates/core/src/snapshots/marzano_core__test__warning_rewrite_in_not.snap index 11721be33..09faa5566 100644 --- a/crates/core/src/snapshots/marzano_core__test__warning_rewrite_in_not.snap +++ b/crates/core/src/snapshots/marzano_core__test__warning_rewrite_in_not.snap @@ -1,10 +1,9 @@ --- -source: apps/marzano/core/src/test.rs +source: crates/core/src/test.rs expression: cr.compilation_warnings --- engine_id: None -file_name: Some("PlaygroundPattern") +file_name: None level: Some(441) message: "Warning: rewrites inside of a not will never be applied" position: Some(Position { line: 2, column: 18 }) - diff --git a/crates/core/src/snapshots/marzano_core__test__warns_against_snippet_regex_without_metavars.snap b/crates/core/src/snapshots/marzano_core__test__warns_against_snippet_regex_without_metavars.snap index 6835b13c9..cfa8bbc91 100644 --- a/crates/core/src/snapshots/marzano_core__test__warns_against_snippet_regex_without_metavars.snap +++ b/crates/core/src/snapshots/marzano_core__test__warns_against_snippet_regex_without_metavars.snap @@ -1,10 +1,9 @@ --- -source: apps/marzano/core/src/test.rs +source: crates/core/src/test.rs expression: res --- engine_id: None -file_name: Some("PlaygroundPattern") +file_name: None level: Some(441) message: "Warning: unnecessary use of metavariable snippet syntax without metavariables. Replace r`[a-zA-Z]*` with r\"[a-zA-Z]*\"" position: Some(Position { line: 3, column: 17 }) - diff --git a/crates/core/src/snapshots/marzano_core__test__warns_against_snippet_useless_rewrite.snap b/crates/core/src/snapshots/marzano_core__test__warns_against_snippet_useless_rewrite.snap index 18ed29597..c5f03014f 100644 --- a/crates/core/src/snapshots/marzano_core__test__warns_against_snippet_useless_rewrite.snap +++ b/crates/core/src/snapshots/marzano_core__test__warns_against_snippet_useless_rewrite.snap @@ -1,10 +1,9 @@ --- -source: apps/marzano/core/src/test.rs +source: crates/core/src/test.rs expression: res --- engine_id: None -file_name: Some("PlaygroundPattern") +file_name: None level: Some(441) message: "Warning: This is rewriting `export type {$types}` into the identical string `export type {$types}`, will have no effect." position: Some(Position { line: 2, column: 5 }) - diff --git a/crates/core/src/variables.rs b/crates/core/src/variables.rs index c5350b284..fae637910 100644 --- a/crates/core/src/variables.rs +++ b/crates/core/src/variables.rs @@ -1,11 +1,11 @@ use crate::pattern_compiler::compiler::NodeCompilationContext; use anyhow::Result; use grit_pattern_matcher::{ - constants::{DEFAULT_FILE_NAME, GLOBAL_VARS_SCOPE_INDEX}, + constants::GLOBAL_VARS_SCOPE_INDEX, pattern::{Variable, VariableSourceLocations}, }; use grit_util::Range; -use std::collections::BTreeSet; +use std::{collections::BTreeSet, path::Path}; pub(crate) fn variable_from_name( name: &str, @@ -43,7 +43,7 @@ pub(crate) fn register_variable( } struct FileLocation<'a> { - file_name: &'a str, + file_name: Option<&'a Path>, range: Range, } @@ -69,7 +69,7 @@ fn register_variable_optional_range( if let Some(i) = global_vars.get(name) { if let Some(FileLocation { range, file_name }) = location { - if file_name == DEFAULT_FILE_NAME { + if file_name.is_none() { vars_array[GLOBAL_VARS_SCOPE_INDEX][*i] .locations .insert(range); @@ -93,11 +93,11 @@ fn register_variable_optional_range( } else { // this currently only comes up with the $match variable which we autowrap, and is not // usually used by the user, but feels like this could potentially be a source of bugs - (BTreeSet::new(), DEFAULT_FILE_NAME.to_owned()) + (BTreeSet::new(), None) }; scope.push(VariableSourceLocations { name: name.to_owned(), - file, + file: file.map(Path::to_owned), locations, }); Ok(Variable::new(scope_index, index)) diff --git a/crates/grit-pattern-matcher/src/constants.rs b/crates/grit-pattern-matcher/src/constants.rs index 1c42d0c4c..b62b44c0c 100644 --- a/crates/grit-pattern-matcher/src/constants.rs +++ b/crates/grit-pattern-matcher/src/constants.rs @@ -7,5 +7,3 @@ pub const GLOBAL_VARS_SCOPE_INDEX: usize = 0; pub const MATCH_VAR: &str = "$match"; pub const GRIT_RANGE_VAR: &str = "$grit_range"; - -pub const DEFAULT_FILE_NAME: &str = "PlaygroundPattern"; diff --git a/crates/grit-pattern-matcher/src/errors.rs b/crates/grit-pattern-matcher/src/errors.rs index 7c020de2a..bda433cf7 100644 --- a/crates/grit-pattern-matcher/src/errors.rs +++ b/crates/grit-pattern-matcher/src/errors.rs @@ -13,12 +13,9 @@ pub fn debug<'a, Q: QueryContext>( ) -> Result<()> { let mut builder = AnalysisLogBuilder::default(); builder.level(501_u16); + builder.file(get_file_name(state, lang)?); builder.message(message); - if let Ok(file) = get_file_name(state, lang) { - builder.file(file); - } - let log = builder.build(); match log { Ok(log) => analysis_logs.push(log), diff --git a/crates/grit-pattern-matcher/src/pattern/variable.rs b/crates/grit-pattern-matcher/src/pattern/variable.rs index 349cf7c43..69da6ea22 100644 --- a/crates/grit-pattern-matcher/src/pattern/variable.rs +++ b/crates/grit-pattern-matcher/src/pattern/variable.rs @@ -12,7 +12,7 @@ use crate::{ use anyhow::{bail, Result}; use core::fmt::Debug; use grit_util::{constants::GRIT_METAVARIABLE_PREFIX, AnalysisLogs, Language, Range}; -use std::{borrow::Cow, collections::BTreeSet}; +use std::{borrow::Cow, collections::BTreeSet, path::PathBuf}; #[derive(Clone, Debug, Copy)] pub struct Variable { @@ -23,7 +23,7 @@ pub struct Variable { #[derive(Debug, Clone)] pub struct VariableSourceLocations { pub name: String, - pub file: String, + pub file: Option, pub locations: BTreeSet, } @@ -202,27 +202,31 @@ impl Matcher for Variable { pub fn get_absolute_file_name<'a, Q: QueryContext>( state: &State<'a, Q>, lang: &Q::Language<'a>, -) -> Result { - let file = state.bindings[GLOBAL_VARS_SCOPE_INDEX].last().unwrap()[ABSOLUTE_PATH_INDEX] +) -> Result, anyhow::Error> { + let Some(file) = state.bindings[GLOBAL_VARS_SCOPE_INDEX].last().unwrap()[ABSOLUTE_PATH_INDEX] .value - .as_ref(); - let file = file - .map(|f| f.text(&state.files, lang).map(|s| s.to_string())) - .unwrap_or(Ok("No File Found".to_string()))?; - Ok(file) + .as_ref() + else { + return Ok(None); + }; + + let file = file.text(&state.files, lang)?; + Ok(Some(PathBuf::from(file.as_ref()))) } pub fn get_file_name<'a, Q: QueryContext>( state: &State<'a, Q>, lang: &Q::Language<'a>, -) -> Result { - let file = state.bindings[GLOBAL_VARS_SCOPE_INDEX].last().unwrap()[FILENAME_INDEX] +) -> Result, anyhow::Error> { + let Some(file) = state.bindings[GLOBAL_VARS_SCOPE_INDEX].last().unwrap()[FILENAME_INDEX] .value - .as_ref(); - let file = file - .map(|f| f.text(&state.files, lang).map(|s| s.to_string())) - .unwrap_or(Ok("No File Found".to_string()))?; - Ok(file) + .as_ref() + else { + return Ok(None); + }; + + let file = file.text(&state.files, lang)?; + Ok(Some(PathBuf::from(file.as_ref()))) } pub fn is_reserved_metavariable(var: &str, lang: Option<&impl Language>) -> bool { diff --git a/crates/grit-util/src/analysis_logs.rs b/crates/grit-util/src/analysis_logs.rs index ac7b716b4..d4adff1e5 100644 --- a/crates/grit-util/src/analysis_logs.rs +++ b/crates/grit-util/src/analysis_logs.rs @@ -11,7 +11,7 @@ use std::path::PathBuf; pub struct AnalysisLog { #[builder(setter(into, strip_option), default)] pub engine_id: Option, - #[builder(setter(into, strip_option), default)] + #[builder(default)] pub file: Option, #[builder(setter(into, strip_option), default)] pub level: Option, diff --git a/crates/language/src/grit_parser.rs b/crates/language/src/grit_parser.rs index 4fa0a93e7..3d1bae450 100644 --- a/crates/language/src/grit_parser.rs +++ b/crates/language/src/grit_parser.rs @@ -61,10 +61,8 @@ fn grit_parsing_errors(tree: &Tree, path: Option<&Path>) -> Result }; log_builder .level(level) - .engine_id("marzano(0.1)".to_owned()); - if let Some(path) = path { - log_builder.file(path.to_owned()); - } + .engine_id("marzano(0.1)".to_owned()) + .file(path.map(Into::into)); let root = tree.root_node(); let cursor = root.walk(); diff --git a/crates/language/src/language.rs b/crates/language/src/language.rs index 6354ed807..8188e850d 100644 --- a/crates/language/src/language.rs +++ b/crates/language/src/language.rs @@ -305,7 +305,7 @@ fn file_parsing_error( log_builder .level(level) .engine_id("marzano(0.1)".to_owned()) - .file(file_name.to_owned()); + .file(Some(file_name.to_owned())); for n in traverse(CursorWrapper::new(cursor, body), Order::Pre) { if n.node.is_error() || n.node.is_missing() {