Instead of writing complex YAML, you can use structural-intent parameters to constrain where a pattern matches. These map directly to YAML constraints.
| Parameter | Description |
|---|
insideKind | Only match inside an ancestor of this node kind (searches ALL ancestors, stopBy: end). |
hasKind | Only match nodes whose immediate child has this kind (stopBy: neighbor). |
hasDescendantKind | Only match nodes containing this kind anywhere in their descendants (stopBy: end). |
follows | Only match nodes preceded by a sibling matching this pattern |
precedes | Only match nodes followed by a sibling matching this pattern |
Warning: hasKind and hasDescendantKind are mutually exclusive. Also, insideKind can escalate past the intended enclosing function if not scoped with paths or a specific stopBy boundary.
# console.log only inside functions
ast_grep_search pattern="console.log($MSG)" lang="typescript" insideKind="function_declaration"
# replace var with let, scoped to functions only
ast_grep_replace pattern="var $X" rewrite="let $X" lang="javascript" insideKind="function_declaration"