ast-grep (sg) is a command-line tool for structural search, linting, and rewriting across many programming languages. It matches abstract syntax tree patterns instead of plain text.
Overview
ast-grep searches and replaces code using patterns written like ordinary source code. Wildcards such as $MATCH stand in for single AST nodes, similar in role to regex dots but syntax-aware. The engine is built on tree-sitter parsing and is implemented in Rust for parallel execution across large codebases.
Beyond one-off search and replace, ast-grep can scan projects as a linter with YAML-defined rules and readable error output. A Node.js binding exposes syntax trees with jQuery-style traversal for programmatic use, with optional type safety. The project also documents interactive codemods, a language server, and testing utilities.
Dozens of languages are supported out of the box, and custom tree-sitter parsers can be registered via dynamic loading. Install paths include npm, pip, cargo, Homebrew, Scoop, Mise, and MacPorts, with an online playground for trying patterns. Typical roles include library migration codemods, team style enforcement, and security rule authoring.
Key features
- AST pattern search and replace
- YAML lint rule configuration
- Multi-language tree-sitter parsing
- Parallel Rust execution
- CLI scan and rewrite modes
- Node.js programmatic API
- Wildcard metavariable patterns
- Custom parser registration
Use cases
- Large-scale codemods
- Custom lint rules
- Breaking API migration assists
- Security pattern matching
- Interactive structural rewrites