name: ast-grep description: Guides ccusage structural code searches with ast-grep. Use when finding Rust or TypeScript syntax patterns, validating migrations, or writing AST-based search commands.
ast-grep
Use ast-grep when a search needs syntax structure rather than plain text. Prefer rg for simple text search.
Tooling
This repo provides ast-grep through flake.nix. Run commands from the Nix dev shell, or use direnv exec . when the shell is not already active:
direnv exec . ast-grep run --lang rust --pattern 'println!($$$ARGS)' rust
direnv exec . ast-grep run --lang ts --pattern '/$P/' --json=stream apps packages
If direnv is unavailable and this is a one-off search, use comma as a fallback:
, ast-grep run --lang rust --pattern 'println!($$$ARGS)' rust
, ast-grep run --lang ts --pattern '/$P/' --json=stream apps packages
Workflow
- Describe the syntax shape you need to find.
- Start with a small pattern and test it against the repo.
- Use
--debug-querywhen the pattern does not match the AST shape you expected. - Only move to YAML rules when
run --patterncannot express the search.
Commands
For quick pattern searches:
ast-grep run --lang rust --pattern 'pub fn $NAME($$$ARGS) -> $RET { $$$BODY }' rust
ast-grep run --lang ts --pattern 'console.log($ARG)' apps packages
For JSON output that scripts can consume:
ast-grep run --lang rust --pattern 'String::from($ARG)' --json=stream rust
ast-grep run --lang ts --pattern '/$P/' --json=stream apps packages
Rule Tips
- Use
run --patternfor simple single-node matches. - Use
scan --ruleorscan --inline-rulesfor relational rules such asinsideorhas. - Add
stopBy: endto relational rules so ast-grep searches the full direction. - Use
--debug-query=ast,--debug-query=cst, or--debug-query=patternwhen a rule does not match the code shape you expected.