Skip to content

Commit

Permalink
feat: change get_fixer to return Fixer
Browse files Browse the repository at this point in the history
BREAKING CHANGE: get_fixer used to return TemplateFix but now it returns Fixer

this enables advanced operations like tweaking fix range.
  • Loading branch information
HerringtonDarkholme committed Jan 8, 2024
1 parent 79d5b31 commit 07c5363
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 28 deletions.
5 changes: 2 additions & 3 deletions crates/cli/src/print/colored_print/test.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#![cfg(test)]

use super::*;
use ast_grep_config::{from_yaml_string, GlobalRules};
use ast_grep_core::replacer::TemplateFix;
use ast_grep_config::{from_yaml_string, Fixer, GlobalRules};
use ast_grep_language::{Language, SupportLang};
use codespan_reporting::term::termcolor::Buffer;

Expand Down Expand Up @@ -156,7 +155,7 @@ fn test_print_diffs() {
// heading is required for CI
let printer = make_test_printer().heading(Heading::Always);
let lang = SgLang::from(SupportLang::Tsx);
let fixer = TemplateFix::try_new(rewrite, &lang).expect("should work");
let fixer = Fixer::from_str(rewrite, &lang).expect("should work");
let grep = lang.ast_grep(source);
let matches = grep.root().find_all(pattern);
let diffs = matches.map(|n| Diff::generate(n, &pattern, &fixer));
Expand Down
9 changes: 4 additions & 5 deletions crates/cli/src/print/interactive_print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,7 @@ fn open_in_editor(path: &Path, start_line: usize) -> Result<()> {
#[cfg(test)]
mod test {
use super::*;
use ast_grep_config::{from_yaml_string, GlobalRules};
use ast_grep_core::replacer::TemplateFix;
use ast_grep_config::{from_yaml_string, Fixer, GlobalRules};
use ast_grep_core::traversal::Visitor;
use ast_grep_core::{AstGrep, Matcher, StrDoc};
use ast_grep_language::SupportLang;
Expand All @@ -267,7 +266,7 @@ language: TypeScript
fn make_diffs<'a>(
grep: &'a AstGrep<StrDoc<SgLang>>,
matcher: impl Matcher<SgLang>,
fixer: &TemplateFix<String>,
fixer: &Fixer<String, SgLang>,
) -> Vec<Diff<'a>> {
let root = grep.root();
Visitor::new(&matcher)
Expand Down Expand Up @@ -302,7 +301,7 @@ fix: ($B, lifecycle.update(['$A']))",
let diffs = make_diffs(
&root,
"Some($A)",
&TemplateFix::try_new("$A", &SupportLang::TypeScript).expect("fixer must compile"),
&Fixer::from_str("$A", &SupportLang::TypeScript.into()).expect("fixer must compile"),
);
let ret = apply_rewrite(diffs);
assert_eq!("Some(1)", ret);
Expand All @@ -315,7 +314,7 @@ fix: ($B, lifecycle.update(['$A']))",
let diffs = make_diffs(
&root,
"Some($A)",
&TemplateFix::try_new("$A", &SupportLang::TypeScript).expect("fixer must compile"),
&Fixer::from_str("$A", &SupportLang::TypeScript.into()).expect("fixer must compile"),
);
let ret = apply_rewrite(diffs);
assert_eq!("\n\n\n1", ret);
Expand Down
5 changes: 2 additions & 3 deletions crates/cli/src/print/json_print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,7 @@ impl<W: Write> Printer for JSONPrinter<W> {
#[cfg(test)]
mod test {
use super::*;
use ast_grep_config::{from_yaml_string, GlobalRules};
use ast_grep_core::replacer::TemplateFix;
use ast_grep_config::{from_yaml_string, Fixer, GlobalRules};
use ast_grep_language::{Language, SupportLang};

struct Test(String);
Expand Down Expand Up @@ -428,7 +427,7 @@ mod test {
let lang = SgLang::from(SupportLang::Tsx);
let grep = lang.ast_grep(source);
let matches = grep.root().find_all(pattern);
let fixer = TemplateFix::try_new(replace, &lang).expect("should work");
let fixer = Fixer::from_str(replace, &lang).expect("should work");
let diffs = matches.map(|m| Diff::generate(m, &pattern, &fixer));
printer.before_print().unwrap();
printer.print_diffs(diffs, "test.tsx".as_ref()).unwrap();
Expand Down
5 changes: 2 additions & 3 deletions crates/cli/src/print/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ mod interactive_print;
mod json_print;

use crate::lang::SgLang;
use ast_grep_config::RuleConfig;
use ast_grep_core::replacer::TemplateFix;
use ast_grep_config::{Fixer, RuleConfig};
use ast_grep_core::{Matcher, NodeMatch as SgNodeMatch, StrDoc};

use anyhow::Result;
Expand Down Expand Up @@ -69,7 +68,7 @@ impl<'n> Diff<'n> {
pub fn generate(
node_match: NodeMatch<'n, SgLang>,
matcher: &impl Matcher<SgLang>,
rewrite: &TemplateFix<String>,
rewrite: &Fixer<String, SgLang>,
) -> Self {
let edit = node_match.make_edit(matcher, rewrite);
let replacement = String::from_utf8(edit.inserted_text).unwrap();
Expand Down
8 changes: 4 additions & 4 deletions crates/cli/src/run.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use ast_grep_core::replacer::TemplateFix;
use ast_grep_config::Fixer;
use ast_grep_core::{Matcher, Pattern};
use ast_grep_language::Language;
use clap::Parser;
Expand Down Expand Up @@ -154,7 +154,7 @@ impl<P: Printer + Sync> Worker for RunWithInferredLang<P> {
for (match_unit, lang) in items {
let rewrite = rewrite
.as_ref()
.map(|s| TemplateFix::try_new(s, &lang))
.map(|s| Fixer::from_str(s, &lang))
.transpose();
match rewrite {
Ok(r) => match_one_file(printer, &match_unit, &r)?,
Expand Down Expand Up @@ -214,7 +214,7 @@ impl<P: Printer + Sync> Worker for RunWithSpecificLang<P> {
println!("Pattern TreeSitter {:?}", self.pattern);
}
let rewrite = if let Some(s) = &arg.rewrite {
Some(TemplateFix::try_new(s, &lang).context(EC::ParsePattern)?)
Some(Fixer::from_str(s, &lang).context(EC::ParsePattern)?)
} else {
None
};
Expand Down Expand Up @@ -261,7 +261,7 @@ impl<P: Printer + Sync> StdInWorker for RunWithSpecificLang<P> {
fn match_one_file(
printer: &impl Printer,
match_unit: &MatchUnit<impl Matcher<SgLang>>,
rewrite: &Option<TemplateFix<String>>,
rewrite: &Option<Fixer<String, SgLang>>,
) -> Result<()> {
let MatchUnit {
path,
Expand Down
29 changes: 22 additions & 7 deletions crates/config/src/fixer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,16 +80,30 @@ where
fixer: &SerializableFixer,
env: &DeserializeEnv<L>,
transform: &Option<HashMap<String, Transformation>>,
) -> Result<Option<TemplateFix<C>>, TemplateFixError> {
) -> Result<Option<Self>, TemplateFixError> {
let SerializableFixer::Str(fix) = fixer else {
return Ok(None);
};
if let Some(trans) = transform {
let template = if let Some(trans) = transform {
let keys: Vec<_> = trans.keys().cloned().collect();
Ok(Some(TemplateFix::with_transform(fix, &env.lang, &keys)))
TemplateFix::with_transform(fix, &env.lang, &keys)
} else {
Ok(Some(TemplateFix::try_new(fix, &env.lang)?))
}
TemplateFix::try_new(fix, &env.lang)?
};
Ok(Some(Self {
template,
expand_end: None,
expand_start: None,
}))
}

pub fn from_str(src: &str, lang: &L) -> Result<Self, TemplateFixError> {
let template = TemplateFix::try_new(src, lang)?;
Ok(Self {
template,
expand_start: None,
expand_end: None,
})
}
}

Expand Down Expand Up @@ -150,8 +164,9 @@ mod test {
let config = SerializableFixer::Str("abcd".to_string());
let env = DeserializeEnv::new(TypeScript::Tsx);
let ret = Fixer::<String, _>::parse(&config, &env, &Some(Default::default())).unwrap();
assert!(ret.is_some());
assert!(matches!(ret, Some(TemplateFix::Textual(_))));
let ret = ret.unwrap();
assert!(ret.expand_end.is_none());
assert!(ret.expand_start.is_none());
Ok(())
}
}
1 change: 1 addition & 0 deletions crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use serde_yaml::{with::singleton_map_recursive::deserialize, Deserializer, Error
use ast_grep_core::language::Language;

pub use combined::CombinedScan;
pub use fixer::Fixer;
pub use rule::referent_rule::GlobalRules;
pub use rule::DeserializeEnv;
pub use rule::{Rule, RuleSerializeError, SerializableRule};
Expand Down
6 changes: 3 additions & 3 deletions crates/config/src/rule_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ pub use crate::constraints::{
};
use ast_grep_core::language::Language;
use ast_grep_core::meta_var::MetaVarMatchers;
use ast_grep_core::replacer::TemplateFixError;
use ast_grep_core::replacer::{IndentSensitive, Replacer};
use ast_grep_core::replacer::{TemplateFix, TemplateFixError};
use ast_grep_core::{NodeMatch, StrDoc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -129,7 +129,7 @@ pub struct SerializableRuleConfig<L: Language> {
type RResult<T> = std::result::Result<T, RuleConfigError>;

impl<L: Language> SerializableRuleConfig<L> {
pub fn get_fixer<C: IndentSensitive>(&self) -> RResult<Option<TemplateFix<C>>> {
pub fn get_fixer<C: IndentSensitive>(&self) -> RResult<Option<Fixer<C, L>>> {
let transform = &self.transform;
if let Some(fixer) = &self.fix {
let env = self.get_deserialize_env(&Default::default())?;
Expand Down Expand Up @@ -173,7 +173,7 @@ pub enum RuleConfigError {
pub struct RuleConfig<L: Language> {
inner: SerializableRuleConfig<L>,
pub matcher: RuleWithConstraint<L>,
pub fixer: Option<TemplateFix<String>>,
pub fixer: Option<Fixer<String, L>>,
}

impl<L: Language> RuleConfig<L> {
Expand Down

0 comments on commit 07c5363

Please sign in to comment.