ast-grep-core 0.45.2

Search and Rewrite code at large scale using precise AST pattern
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
mod match_node;
mod strictness;

use match_node::match_root_node_impl;
use strictness::MatchOneNode;
pub use strictness::MatchStrictness;

use crate::meta_var::{MetaVarEnv, MetaVariable};
use crate::{Doc, Node, Pattern};

use std::borrow::Cow;

// the Clone bound is for matching multi-metavar like $$$A
// since the next node in pattern determines how many nodes to bind to $$$A
// we need to clone the aggregator to test each node in candidate
// preferably, Aggregator should be cheap to clone, like Cow or a small struct
// See https://github.com/ast-grep/ast-grep/pull/2670
trait Aggregator<'t, D: Doc>: Clone {
  fn match_terminal(&mut self, node: &Node<'t, D>) -> Option<()>;
  fn match_meta_var(&mut self, var: &MetaVariable, node: &Node<'t, D>) -> Option<()>;
  fn match_ellipsis(
    &mut self,
    var: Option<&str>,
    nodes: Vec<Node<'t, D>>,
    skipped_anonymous: usize,
  ) -> Option<()>;
}

#[derive(Clone)]
struct ComputeEnd(usize);

impl<'t, D: Doc> Aggregator<'t, D> for ComputeEnd {
  fn match_terminal(&mut self, node: &Node<'t, D>) -> Option<()> {
    self.0 = node.range().end;
    Some(())
  }
  fn match_meta_var(&mut self, _: &MetaVariable, node: &Node<'t, D>) -> Option<()> {
    self.0 = node.range().end;
    Some(())
  }
  fn match_ellipsis(
    &mut self,
    _var: Option<&str>,
    nodes: Vec<Node<'t, D>>,
    _skipped: usize,
  ) -> Option<()> {
    let n = nodes.last()?;
    self.0 = n.range().end;
    Some(())
  }
}

pub fn match_end_non_recursive(goal: &Pattern, candidate: Node<impl Doc>) -> Option<usize> {
  let mut end = ComputeEnd(0);
  match match_root_node_impl(&goal.node, &candidate, &mut end, &goal.strictness) {
    MatchOneNode::MatchedBoth => Some(end.0),
    _ => None,
  }
}

fn match_leaf_meta_var<'tree, D: Doc>(
  mv: &MetaVariable,
  candidate: &Node<'tree, D>,
  env: &mut Cow<MetaVarEnv<'tree, D>>,
) -> Option<()> {
  use MetaVariable as MV;
  match mv {
    MV::Capture(name, named) => {
      if *named && !candidate.is_named() {
        None
      } else {
        env.to_mut().insert(name, candidate.clone())?;
        Some(())
      }
    }
    MV::Dropped(named) => {
      if *named && !candidate.is_named() {
        None
      } else {
        Some(())
      }
    }
    // Ellipsis will be matched in parent level
    MV::Multiple => {
      debug_assert!(false, "Ellipsis should be matched in parent level");
      Some(())
    }
    MV::MultiCapture(name) => {
      env.to_mut().insert_multi(name, vec![candidate.clone()])?;
      Some(())
    }
  }
}

impl<'t, D: Doc> Aggregator<'t, D> for Cow<'_, MetaVarEnv<'t, D>> {
  fn match_terminal(&mut self, _: &Node<'t, D>) -> Option<()> {
    Some(())
  }
  fn match_meta_var(&mut self, var: &MetaVariable, node: &Node<'t, D>) -> Option<()> {
    match_leaf_meta_var(var, node, self)
  }
  fn match_ellipsis(
    &mut self,
    var: Option<&str>,
    nodes: Vec<Node<'t, D>>,
    skipped_anonymous: usize,
  ) -> Option<()> {
    if let Some(var) = var {
      let mut matched = nodes;
      let skipped = matched.len().saturating_sub(skipped_anonymous);
      drop(matched.drain(skipped..));
      self.to_mut().insert_multi(var, matched)?;
    }
    Some(())
  }
}

pub fn match_node_non_recursive<'tree, D: Doc>(
  goal: &Pattern,
  candidate: Node<'tree, D>,
  env: &mut Cow<MetaVarEnv<'tree, D>>,
) -> Option<Node<'tree, D>> {
  match match_root_node_impl(&goal.node, &candidate, env, &goal.strictness) {
    MatchOneNode::MatchedBoth => Some(candidate),
    _ => None,
  }
}

pub fn does_node_match_exactly<D: Doc>(goal: &Node<D>, candidate: &Node<D>) -> bool {
  // return true if goal and candidate are the same node
  if goal.node_id() == candidate.node_id() {
    return true;
  }
  // gh issue #1087, we make pattern matching a little bit more permissive
  // compare node text if at least one node is leaf
  if goal.is_named_leaf() || candidate.is_named_leaf() {
    return goal.text() == candidate.text();
  }
  if goal.kind_id() != candidate.kind_id() {
    return false;
  }
  let goal_children = goal.children();
  let cand_children = candidate.children();
  if goal_children.len() != cand_children.len() {
    return false;
  }
  goal_children
    .zip(cand_children)
    .all(|(g, c)| does_node_match_exactly(&g, &c))
}

#[cfg(test)]
mod test {
  use super::*;
  use crate::language::Tsx;
  use crate::matcher::KindMatcher;
  use crate::meta_var::MetaVarEnv;
  use crate::tree_sitter::StrDoc;
  use crate::{Node, Root};
  use std::collections::HashMap;

  fn find_node_recursive<'tree>(
    goal: &Pattern,
    node: Node<'tree, StrDoc<Tsx>>,
    env: &mut Cow<MetaVarEnv<'tree, StrDoc<Tsx>>>,
  ) -> Option<Node<'tree, StrDoc<Tsx>>> {
    match_node_non_recursive(goal, node.clone(), env).or_else(|| {
      node
        .children()
        .find_map(|sub| find_node_recursive(goal, sub, env))
    })
  }

  fn test_match(s1: &str, s2: &str) -> HashMap<String, String> {
    let goal = Pattern::new(s1, Tsx);
    let cand = Root::str(s2, Tsx);
    let cand = cand.root();
    let mut env = Cow::Owned(MetaVarEnv::new());
    let ret = find_node_recursive(&goal, cand.clone(), &mut env);
    assert!(
      ret.is_some(),
      "goal: {goal:?}, candidate: {}",
      cand.get_inner_node().to_sexp(),
    );
    HashMap::from(env.into_owned())
  }

  fn test_non_match(s1: &str, s2: &str) {
    let goal = Pattern::new(s1, Tsx);
    let cand = Root::str(s2, Tsx);
    let cand = cand.root();
    let mut env = Cow::Owned(MetaVarEnv::new());
    let ret = find_node_recursive(&goal, cand, &mut env);
    assert!(ret.is_none());
  }

  #[test]
  fn test_simple_match() {
    test_match("const a = 123", "const a=123");
    test_non_match("const a = 123", "var a = 123");
  }

  #[test]
  fn test_root_metavar_matches_comment() {
    let goal = Pattern::new("$COMMENT", Tsx);
    let cand = Root::str(
      "class MyClass { /** @memberof MyClass.prototype */ get myProp() { return 1; } }",
      Tsx,
    );
    let comment = cand
      .root()
      .find(KindMatcher::new("comment", Tsx))
      .expect("should find comment")
      .get_node()
      .clone();
    assert!(comment.is_extra(), "test requires an extra comment node");
    assert_eq!(
      match_end_non_recursive(&goal, comment.clone()),
      Some(comment.range().end)
    );

    let mut env = Cow::Owned(MetaVarEnv::new());
    let matched = match_node_non_recursive(&goal, comment.clone(), &mut env);
    assert!(matched.is_some(), "root metavariable should match comment");
    assert_eq!(
      env
        .get_match("COMMENT")
        .expect("should capture comment")
        .text(),
      "/** @memberof MyClass.prototype */"
    );

    let dropped = Pattern::new("$_", Tsx);
    let mut env = Cow::Owned(MetaVarEnv::new());
    assert!(match_node_non_recursive(&dropped, comment.clone(), &mut env).is_some());

    let relaxed = Pattern::new("$COMMENT", Tsx).with_strictness(MatchStrictness::Relaxed);
    let mut env = Cow::Owned(MetaVarEnv::new());
    assert!(match_node_non_recursive(&relaxed, comment, &mut env).is_none());
  }

  #[test]
  fn test_nested_smart_metavar_skips_comment() {
    let env = test_match("$A($B)", "foo(/* before */ bar /* after */)");
    assert_eq!(env["B"], "bar");
  }

  #[test]
  fn test_nested_match() {
    test_match("const a = 123", "function() {const a= 123;}");
    test_match("const a = 123", "class A { constructor() {const a= 123;}}");
    test_match(
      "const a = 123",
      "for (let a of []) while (true) { const a = 123;}",
    );
  }

  #[test]
  fn test_should_exactly_match() {
    test_match(
      "function foo() { let a = 123; }",
      "function foo() { let a = 123; }",
    );
    test_non_match(
      "function foo() { let a = 123; }",
      "function bar() { let a = 123; }",
    );
  }

  #[test]
  fn test_match_inner() {
    test_match(
      "function bar() { let a = 123; }",
      "function foo() { function bar() {let a = 123; }}",
    );
    test_non_match(
      "function foo() { let a = 123; }",
      "function foo() { function bar() {let a = 123; }}",
    );
  }

  #[test]
  fn test_single_ellipsis() {
    test_match("foo($$$)", "foo(a, b, c)");
    test_match("foo($$$)", "foo()");
  }
  #[test]
  fn test_named_ellipsis() {
    test_match("foo($$$A, c)", "foo(a, b, c)");
    test_match("foo($$$A, b, c)", "foo(a, b, c)");
    test_match("foo($$$A, a, b, c)", "foo(a, b, c)");
    test_non_match("foo($$$A, a, b, c)", "foo(b, c)");
  }

  #[test]
  fn test_leading_ellipsis() {
    test_match("foo($$$, c)", "foo(a, b, c)");
    test_match("foo($$$, b, c)", "foo(a, b, c)");
    test_match("foo($$$, a, b, c)", "foo(a, b, c)");
    test_non_match("foo($$$, a, b, c)", "foo(b, c)");
  }
  #[test]
  fn test_trailing_ellipsis() {
    test_match("foo(a, $$$)", "foo(a, b, c)");
    test_match("foo(a, b, $$$)", "foo(a, b, c)");
    // test_match("foo(a, b, c, $$$)", "foo(a, b, c)");
    test_non_match("foo(a, b, c, $$$)", "foo(b, c)");
  }

  #[test]
  fn test_meta_var_named() {
    test_match("return $A", "return 123;");
    test_match("return $_", "return 123;");
    test_non_match("return $A", "return;");
    test_non_match("return $_", "return;");
    test_match("return $$A", "return;");
    test_match("return $$_A", "return;");
  }

  #[test]
  fn test_meta_var_multiple_occurrence() {
    test_match("$A($$$)", "test(123)");
    test_match("$A($B)", "test(123)");
    test_non_match("$A($A)", "test(aaa)");
    test_non_match("$A($A)", "test(123)");
    test_non_match("$A($A, $A)", "test(123, 456)");
    test_match("$A($A)", "test(test)");
    test_non_match("$A($A)", "foo(bar)");
  }

  #[test]
  fn test_string() {
    test_match("'a'", "'a'");
    test_match("'abcdefg'", "'abcdefg'");
    test_match("`abcdefg`", "`abcdefg`");
    test_non_match("'a'", "'b'");
    test_non_match("'abcdefg'", "'gggggg'");
  }

  #[test]
  fn test_skip_trivial_node() {
    test_match("foo($A, $B)", "foo(a, b,)");
    test_match("class A { b() {}}", "class A { get b() {}}");
  }

  #[test]
  fn test_trivia_in_pattern() {
    test_match("foo($A, $B,)", "foo(a, b,)");
    test_non_match("foo($A, $B,)", "foo(a, b)");
    test_match("class A { get b() {}}", "class A { get b() {}}");
    test_non_match("class A { get b() {}}", "class A { b() {}}");
  }

  fn find_end_recursive(goal: &Pattern, node: Node<StrDoc<Tsx>>) -> Option<usize> {
    match_end_non_recursive(goal, node.clone()).or_else(|| {
      node
        .children()
        .find_map(|sub| find_end_recursive(goal, sub))
    })
  }

  fn test_end(s1: &str, s2: &str) -> Option<usize> {
    let goal = Pattern::new(s1, Tsx);
    let cand = Root::str(s2, Tsx);
    let cand = cand.root();
    find_end_recursive(&goal, cand.clone())
  }

  #[test]
  fn test_match_end() {
    let end = test_end("return $A", "return 123 /* trivia */");
    assert_eq!(end.expect("should work"), 10);
    let end = test_end("return f($A)", "return f(1,) /* trivia */");
    assert_eq!(end.expect("should work"), 12);
  }

  // see https://github.com/ast-grep/ast-grep/issues/411
  #[test]
  fn test_ellipsis_end() {
    let end = test_end(
      "import {$$$A, B, $$$C} from 'a'",
      "import {A, B, C} from 'a'",
    );
    assert_eq!(end.expect("must match"), 25);
  }

  #[test]
  fn test_gh_1087() {
    test_match("($P) => $F($P)", "(x) => bar(x)");
  }

  // A leading `$$$` followed by a metavar-bearing anchored statement must not
  // leak partial bindings from the ellipsis-end lookahead probe. Here the probe
  // of `let $P = g()` against the leading `let a = 0` would bind `$P = a` and
  // then fail on the right-hand side, poisoning the real bind `$P = p`.
  #[test]
  fn test_leading_ellipsis_metavar_anchor() {
    // No trailing `;` after `$$$A`/`$$$B` so they parse as statement-list
    // ellipses (a bare `$$$A;` would be wrapped in an expression_statement).
    let env = test_match(
      "function _() {\n  $$$A\n  let $P = g()\n  let $Q = h()\n  $$$B\n}",
      "function _() { let a = 0; let p = g(); let q = h(); let b = 1; }",
    );
    assert_eq!(env["P"], "p");
    assert_eq!(env["Q"], "q");
    assert_eq!(env["A"], "[let a = 0;]");
    assert_eq!(env["B"], "[let b = 1;]");
  }
}