文档

tree-sitter 引擎

使用 tree-sitter 为 18 种编程语言提供 AST 驱动的签名提取。

v1.5.0 起,LeanCTX 使用 tree-sitter 进行签名提取,替代逐行正则匹配。tree-sitter 将源代码解析为完整的抽象语法树(AST),能准确提取正则无法处理的多行签名、箭头函数、装饰器和嵌套定义。

为什么选择 tree-sitter?

能力正则(旧版)tree-sitter(新版)
多行签名遗漏完整解析
箭头函数遗漏完整解析
嵌套类/方法缩进启发式AST 作用域追踪
装饰器/属性忽略与定义关联
支持的语言418
准确性~85%~99%

支持的语言

每种语言都有专用的 tree-sitter 查询来提取以下定义类型:

语言扩展名提取的定义
TypeScript.ts, .tsxfunction, class, abstract class, interface, type alias, method, arrow function
JavaScript.js, .jsxfunction, class, method, arrow function
Rust.rsfn, struct, enum, trait, impl, type, const
Python.pydef, class, async def
Go.gofunc, method, type (struct/interface)
Java.javaclass, interface, enum, method, constructor
C.c, .hfunction, struct, enum, typedef
C++.cpp, .cc, .hppfunction, class, struct, enum, namespace
Ruby.rbclass, module, method, singleton_method
C#.csclass, struct, interface, method, property, record
Kotlin.kt, .ktsclass, object, fun, property, interface
Swift.swiftclass, struct, enum, func, protocol, extension
PHP.phpclass, function, interface, trait, namespace
Bash / Shell.sh, .bashfunction
Dart.dartclass, mixin, extension, function, method, enum
Scala.scala, .scclass, object, trait, def, val
Elixir.ex, .exsdefmodule, def, defp, defmacro
Zig.zigfn, struct, enum, union

Svelte(.svelte)、Vue(.vue)和其他不支持的扩展名会自动回退到基于正则表达式的 TS/JS 类语法提取器。

工作原理

当您使用 ctx_read--mode signatures--mode map 时:

  1. LeanCTX 检测文件扩展名并加载对应的 tree-sitter 语法。
  2. 源代码在单次遍历中被解析为 AST。
  3. 预编译的 SCM 查询匹配定义节点(函数、类、结构体等)。
  4. 每个匹配项被转换为紧凑的 Signature 对象,包含名称、参数、返回类型、可见性和异步状态。
  5. 签名使用紧凑表示法(或启用时使用 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 种语言。

另请参阅