thread-ast-engine
Core AST engine for Thread: parsing, matching, and transforming code using AST patterns.
Overview
thread-ast-engine provides powerful tools for working with Abstract Syntax Trees (ASTs). Forked from ast-grep-core, it offers language-agnostic APIs for code analysis and transformation.
What You Can Do
- Parse source code into ASTs using tree-sitter
- Search for code patterns using flexible meta-variables (like
$VAR) - Transform code by replacing matched patterns with new code
- Navigate AST nodes with intuitive tree traversal methods
Perfect for building code linters, refactoring tools, and automated code modification systems.
Quick Start
Add to your Cargo.toml:
[]
= { = "0.1.0", = ["parsing", "matching", "replacing"] }
Basic Example: Find and Replace Variables
use Language;
use LanguageExt;
// Parse JavaScript/TypeScript code
let mut ast = Tsx.ast_grep;
// Replace all 'var' declarations with 'let'
ast.replace?;
// Get the transformed code
println!;
// Output: "let a = 1; let b = 2;"
Finding Code Patterns
use MatcherExt;
let ast = Tsx.ast_grep;
let root = ast.root;
// Find all function declarations
if let Some = root.find
// Find all return statements
for ret_stmt in root.find_all
Working with Meta-Variables
Meta-variables capture parts of the matched code:
$VAR- Captures a single AST node$$$ITEMS- Captures multiple consecutive nodes (ellipsis)$_- Matches any node but doesn't capture it
let ast = Tsx.ast_grep;
let root = ast.root;
if let Some = root.find
Core Components
Node - AST Navigation
Navigate and inspect AST nodes with methods like children(), parent(), and find().
Pattern - Code Matching
Match code structures using tree-sitter patterns with meta-variables.
MetaVarEnv - Variable Capture
Store and retrieve captured meta-variables from pattern matches.
Replacer - Code Transformation
Replace matched code with new content, supporting template-based replacement.
Language - Language Support
Abstract interface for different programming languages via tree-sitter grammars.
Feature Flags
parsing- Enables tree-sitter parsing (includes tree-sitter dependency)matching- Enables pattern matching and node transformation engine.
Use default-features = false to opt out of all features and enable only what you need:
[]
= { = "0.1.0", = false, = ["matching"] }
Advanced Examples
Custom Pattern Matching
use Op;
// Combine multiple patterns with logical operators
let pattern = either
.or
.or;
let ast = Tsx.ast_grep;
let root = ast.root;
if let Some = root.find
Tree Traversal
let ast = Tsx.ast_grep;
let root = ast.root;
// Traverse all descendants
for node in root.dfs
// Check relationships between nodes
if let Some = root.find
License
Original ast-grep code is licensed under the MIT license. All changes introduced in this project are licensed under AGPL-3.0-or-later.
See VENDORED.md for details about our fork, changes, and licensing.