自 v1.5.0 起,LeanCTX 使用 tree-sitter 进行签名提取,替代逐行正则匹配。tree-sitter 将源代码解析为完整的抽象语法树(AST),能准确提取正则无法处理的多行签名、箭头函数、装饰器和嵌套定义。
为什么选择 tree-sitter?
| 能力 | 正则(旧版) | tree-sitter(新版) |
|---|---|---|
| 多行签名 | 遗漏 | 完整解析 |
| 箭头函数 | 遗漏 | 完整解析 |
| 嵌套类/方法 | 缩进启发式 | AST 作用域追踪 |
| 装饰器/属性 | 忽略 | 与定义关联 |
| 支持的语言 | 4 | 18 |
| 准确性 | ~85% | ~99% |
支持的语言
每种语言都有专用的 tree-sitter 查询来提取以下定义类型:
| 语言 | 扩展名 | 提取的定义 |
|---|---|---|
| TypeScript | .ts, .tsx | function, class, abstract class, interface, type alias, method, arrow function |
| JavaScript | .js, .jsx | function, class, method, arrow function |
| Rust | .rs | fn, struct, enum, trait, impl, type, const |
| Python | .py | def, class, async def |
| Go | .go | func, method, type (struct/interface) |
| Java | .java | class, interface, enum, method, constructor |
| C | .c, .h | function, struct, enum, typedef |
| C++ | .cpp, .cc, .hpp | function, class, struct, enum, namespace |
| Ruby | .rb | class, module, method, singleton_method |
| C# | .cs | class, struct, interface, method, property, record |
| Kotlin | .kt, .kts | class, object, fun, property, interface |
| Swift | .swift | class, struct, enum, func, protocol, extension |
| PHP | .php | class, function, interface, trait, namespace |
| Bash / Shell | .sh, .bash | function |
| Dart | .dart | class, mixin, extension, function, method, enum |
| Scala | .scala, .sc | class, object, trait, def, val |
| Elixir | .ex, .exs | defmodule, def, defp, defmacro |
| Zig | .zig | fn, struct, enum, union |
Svelte(.svelte)、Vue(.vue)和其他不支持的扩展名会自动回退到基于正则表达式的 TS/JS 类语法提取器。
工作原理
当您使用 ctx_read 的 --mode signatures 或 --mode map 时:
- LeanCTX 检测文件扩展名并加载对应的 tree-sitter 语法。
- 源代码在单次遍历中被解析为 AST。
- 预编译的 SCM 查询匹配定义节点(函数、类、结构体等)。
- 每个匹配项被转换为紧凑的
Signature对象,包含名称、参数、返回类型、可见性和异步状态。 - 签名使用紧凑表示法(或启用时使用 TDD 表示法)格式化输出。
示例:多行 Rust 签名
正则表达式提取器会遗漏这个多行函数。tree-sitter 能正确处理:
// Source (Rust)
pub fn complex_function<T: Display + Debug>(
first_arg: &str,
second_arg: Vec<T>,
third_arg: Option<HashMap<String, Vec<u8>>>,
) -> Result<(), Box<dyn Error>> {
Ok(())
}
// signatures mode output:
fn ⊛ complex_function(first_arg:&str, second_arg:Vec<T>, third_arg:Option<HashMap<String, Vec<u8>>>) → Result<(), Box<dyn Error>> 示例:箭头函数(TypeScript)
// Source (TypeScript)
export const fetchData = async (url: string): Promise<Response> => {
return fetch(url);
};
// signatures mode output:
fn ⊛ fetchData(url:s) → Promise<Response> 二进制大小
tree-sitter 语法包含编译后的 C 解析器,会将二进制大小从 ~5.7 MB 增加到 ~17 MB。如果大小至关重要,可以在不包含 tree-sitter 的情况下构建:
# Build from source without tree-sitter (regex-only, 4 languages)
cargo install lean-ctx --no-default-features 默认的 Homebrew formula 和 cargo install lean-ctx 包含 tree-sitter 及所有 18 种语言。