find_code_by_rule
Search codebases using advanced AST pattern matching with YAML rules to locate complex code structures like nested or related syntax elements.
Instructions
Find code using ast-grep's YAML rule in a project folder.
YAML rule is more powerful than simple pattern and can perform complex search like find AST inside/having another AST.
It is a more advanced search tool than the simple find_code.
Tip: When using relational rules (inside/has), add stopBy: end to ensure complete traversal.
Internally calls: ast-grep scan --inline-rules [--json] <project_folder>
Output formats:
text (default): Compact text format with file:line-range headers and complete match text Example: Found 2 matches:
src/models.py:45-52 class UserModel: def init(self): self.id = None self.name = None
src/views.py:12 class SimpleView: pass
json: Full match objects with metadata including ranges, meta-variables, etc.
The max_results parameter limits the number of complete matches returned (not individual lines). When limited, the header shows "Found X matches (showing first Y of Z)".
Example usage: find_code_by_rule(yaml="id: x\nlanguage: python\nrule: {pattern: 'class $NAME'}", max_results=20) find_code_by_rule(yaml="...", output_format="json") # For full metadata
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| project_folder | Yes | The absolute path to the project folder. It must be absolute path. | |
| yaml | Yes | The ast-grep YAML rule to search. It must have id, language, rule fields. | |
| max_results | No | Maximum results to return | |
| output_format | No | 'text' or 'json' | text |