Skip to content

Commit

Permalink
feat: rename fixer to TemplateFix
Browse files Browse the repository at this point in the history
part of #656
  • Loading branch information
HerringtonDarkholme committed Dec 3, 2023
1 parent eb432ae commit 5b53ce0
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 35 deletions.
4 changes: 2 additions & 2 deletions crates/cli/src/print/colored_print/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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

Expand Down Expand Up @@ -156,7 +156,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 = Fixer::try_new(rewrite, &lang).expect("should work");
let fixer = TemplateFix::try_new(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
8 changes: 4 additions & 4 deletions crates/cli/src/print/interactive_print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ fn open_in_editor(path: &Path, start_line: usize) -> Result<()> {
mod test {
use super::*;
use ast_grep_config::{from_yaml_string, GlobalRules};
use ast_grep_core::replacer::Fixer;
use ast_grep_core::replacer::TemplateFix;
use ast_grep_core::traversal::Visitor;
use ast_grep_core::{AstGrep, Matcher, StrDoc};
use ast_grep_language::SupportLang;
Expand All @@ -267,7 +267,7 @@ language: TypeScript
fn make_diffs<'a>(
grep: &'a AstGrep<StrDoc<SgLang>>,
matcher: impl Matcher<SgLang>,
fixer: &Fixer<String>,
fixer: &TemplateFix<String>,
) -> Vec<Diff<'a>> {
let root = grep.root();
Visitor::new(&matcher)
Expand Down Expand Up @@ -302,7 +302,7 @@ fix: ($B, lifecycle.update(['$A']))",
let diffs = make_diffs(
&root,
"Some($A)",
&Fixer::try_new("$A", &SupportLang::TypeScript).expect("fixer must compile"),
&TemplateFix::try_new("$A", &SupportLang::TypeScript).expect("fixer must compile"),
);
let ret = apply_rewrite(diffs);
assert_eq!("Some(1)", ret);
Expand All @@ -315,7 +315,7 @@ fix: ($B, lifecycle.update(['$A']))",
let diffs = make_diffs(
&root,
"Some($A)",
&Fixer::try_new("$A", &SupportLang::TypeScript).expect("fixer must compile"),
&TemplateFix::try_new("$A", &SupportLang::TypeScript).expect("fixer must compile"),
);
let ret = apply_rewrite(diffs);
assert_eq!("\n\n\n1", ret);
Expand Down
4 changes: 2 additions & 2 deletions crates/cli/src/print/json_print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ impl<W: Write> Printer for JSONPrinter<W> {
mod test {
use super::*;
use ast_grep_config::{from_yaml_string, GlobalRules};
use ast_grep_core::replacer::Fixer;
use ast_grep_core::replacer::TemplateFix;
use ast_grep_language::{Language, SupportLang};

struct Test(String);
Expand Down Expand Up @@ -428,7 +428,7 @@ mod test {
let lang = SgLang::from(SupportLang::Tsx);
let grep = lang.ast_grep(source);
let matches = grep.root().find_all(pattern);
let fixer = Fixer::try_new(replace, &lang).expect("should work");
let fixer = TemplateFix::try_new(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
4 changes: 2 additions & 2 deletions crates/cli/src/print/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod json_print;

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

use anyhow::Result;
Expand Down Expand Up @@ -69,7 +69,7 @@ impl<'n> Diff<'n> {
pub fn generate(
node_match: NodeMatch<'n, SgLang>,
matcher: &impl Matcher<SgLang>,
rewrite: &Fixer<String>,
rewrite: &TemplateFix<String>,
) -> 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::Fixer;
use ast_grep_core::replacer::TemplateFix;
use ast_grep_core::{Matcher, Pattern as SgPattern, StrDoc};
use ast_grep_language::Language;
use clap::Parser;
Expand Down Expand Up @@ -168,7 +168,7 @@ impl<P: Printer + Sync> Worker for RunWithInferredLang<P> {
for (match_unit, lang) in items {
let rewrite = rewrite
.as_ref()
.map(|s| Fixer::try_new(s, &lang))
.map(|s| TemplateFix::try_new(s, &lang))
.transpose();
match rewrite {
Ok(r) => match_one_file(printer, &match_unit, &r)?,
Expand Down Expand Up @@ -224,7 +224,7 @@ impl<P: Printer + Sync> Worker for RunWithSpecificLang<P> {
println!("Pattern TreeSitter {:?}", self.pattern);
}
let rewrite = if let Some(s) = &arg.rewrite {
Some(Fixer::try_new(s, &lang).context(EC::ParsePattern)?)
Some(TemplateFix::try_new(s, &lang).context(EC::ParsePattern)?)
} else {
None
};
Expand Down Expand Up @@ -258,7 +258,7 @@ impl<P: Printer + Sync> StdInWorker for RunWithSpecificLang<P> {
fn match_one_file(
printer: &impl Printer,
match_unit: &MatchUnit<impl Matcher<SgLang>>,
rewrite: &Option<Fixer<String>>,
rewrite: &Option<TemplateFix<String>>,
) -> Result<()> {
let MatchUnit {
path,
Expand Down
16 changes: 10 additions & 6 deletions crates/config/src/rule_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub use crate::constraints::{
use ast_grep_core::language::Language;
use ast_grep_core::meta_var::MetaVarMatchers;
use ast_grep_core::replacer::Replacer;
use ast_grep_core::replacer::{Fixer, FixerError};
use ast_grep_core::replacer::{TemplateFix, TemplateFixError};
use ast_grep_core::{NodeMatch, StrDoc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -130,13 +130,17 @@ pub struct SerializableRuleConfig<L: Language> {
type RResult<T> = std::result::Result<T, RuleConfigError>;

impl<L: Language> SerializableRuleConfig<L> {
fn get_fixer(&self) -> RResult<Option<Fixer<String>>> {
fn get_fixer(&self) -> RResult<Option<TemplateFix<String>>> {
if let Some(fix) = &self.fix {
if let Some(trans) = &self.transform {
let keys: Vec<_> = trans.keys().cloned().collect();
Ok(Some(Fixer::with_transform(fix, &self.language, &keys)))
Ok(Some(TemplateFix::with_transform(
fix,
&self.language,
&keys,
)))
} else {
Ok(Some(Fixer::try_new(fix, &self.language)?))
Ok(Some(TemplateFix::try_new(fix, &self.language)?))
}
} else {
Ok(None)
Expand Down Expand Up @@ -169,15 +173,15 @@ pub enum RuleConfigError {
#[error("Rule is not configured correctly.")]
Rule(#[from] RuleSerializeError),
#[error("fix pattern is invalid.")]
Fixer(#[from] FixerError),
Fixer(#[from] TemplateFixError),
#[error("constraints is not configured correctly.")]
Constraints(#[from] SerializeConstraintsError),
}

pub struct RuleConfig<L: Language> {
inner: SerializableRuleConfig<L>,
pub matcher: RuleWithConstraint<L>,
pub fixer: Option<Fixer<String>>,
pub fixer: Option<TemplateFix<String>>,
}

impl<L: Language> RuleConfig<L> {
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/replacer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ mod structural;
mod template;

pub use indent::IndentSensitive;
pub use template::{Fixer, FixerError};
pub use template::{TemplateFix, TemplateFixError};

/// Replace meta variable in the replacer string
pub trait Replacer<D: Doc> {
Expand Down
32 changes: 18 additions & 14 deletions crates/core/src/replacer/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,26 @@ use crate::source::{Content, Doc};
use std::borrow::Cow;
use thiserror::Error;

pub enum Fixer<C: IndentSensitive> {
pub enum TemplateFix<C: IndentSensitive> {
// no meta_var, pure text
Textual(Vec<C::Underlying>),
WithMetaVar(Template<C>),
}

#[derive(Debug, Error)]
pub enum FixerError {}
pub enum TemplateFixError {}

impl<C: IndentSensitive> Fixer<C> {
pub fn try_new<L: Language>(template: &str, lang: &L) -> Result<Self, FixerError> {
Ok(create_fixer(template, lang.meta_var_char(), &[]))
impl<C: IndentSensitive> TemplateFix<C> {
pub fn try_new<L: Language>(template: &str, lang: &L) -> Result<Self, TemplateFixError> {
Ok(create_template(template, lang.meta_var_char(), &[]))
}

pub fn with_transform<L: Language>(tpl: &str, lang: &L, trans: &[String]) -> Self {
create_fixer(tpl, lang.meta_var_char(), trans)
create_template(tpl, lang.meta_var_char(), trans)
}
}

impl<C, D> Replacer<D> for Fixer<C>
impl<C, D> Replacer<D> for TemplateFix<C>
where
C: IndentSensitive,
D: Doc<Source = C>,
Expand All @@ -50,7 +50,11 @@ pub struct Template<C: IndentSensitive> {
vars: Vec<(MetaVarExtract, Indent)>,
}

fn create_fixer<C: IndentSensitive>(tmpl: &str, mv_char: char, transforms: &[String]) -> Fixer<C> {
fn create_template<C: IndentSensitive>(
tmpl: &str,
mv_char: char,
transforms: &[String],
) -> TemplateFix<C> {
let mut fragments = vec![];
let mut vars = vec![];
let mut offset = 0;
Expand All @@ -74,23 +78,23 @@ fn create_fixer<C: IndentSensitive>(tmpl: &str, mv_char: char, transforms: &[Str
offset = offset + i + 1;
}
if fragments.is_empty() {
Fixer::Textual(C::decode_str(&tmpl[len..]).into_owned())
TemplateFix::Textual(C::decode_str(&tmpl[len..]).into_owned())
} else {
fragments.push(C::decode_str(&tmpl[len..]).into_owned());
Fixer::WithMetaVar(Template { fragments, vars })
TemplateFix::WithMetaVar(Template { fragments, vars })
}
}

fn replace_fixer<D: Doc>(
fixer: &Fixer<D::Source>,
fixer: &TemplateFix<D::Source>,
env: &MetaVarEnv<D>,
) -> Vec<<D::Source as Content>::Underlying>
where
D::Source: IndentSensitive,
{
let template = match fixer {
Fixer::Textual(n) => return n.to_vec(),
Fixer::WithMetaVar(t) => t,
TemplateFix::Textual(n) => return n.to_vec(),
TemplateFix::WithMetaVar(t) => t,
};
let mut ret = vec![];
let mut frags = template.fragments.iter();
Expand Down Expand Up @@ -151,7 +155,7 @@ pub fn gen_replacement<D: Doc>(template: &str, nm: &NodeMatch<D>) -> Underlying<
where
D::Source: IndentSensitive,
{
let fixer = create_fixer(template, nm.lang().meta_var_char(), &[]);
let fixer = create_template(template, nm.lang().meta_var_char(), &[]);
fixer.generate_replacement(nm)
}

Expand Down

0 comments on commit 5b53ce0

Please sign in to comment.