3 个不稳定版本
0.2.1 | 2023年4月22日 |
---|---|
0.2.0 | 2023年4月22日 |
0.1.0 | 2023年4月21日 |
#49 在 #code
每月 下载 33 次
17KB
309 代码行
代码形状
代码形状是一个使用 Tree-sitter 从源代码文件中提取代码定义形状的工具。该工具使用与 Tree-sitter CLI 安装的相同语言解析器。
安装
要安装 code-shape
CLI,可以使用 Rust 的 Cargo 软件包管理器
cargo install code-shape
用法
要开始使用此工具,需要做一些准备工作。
先决条件
- 安装 Tree-sitter CLI。
- 运行
tree-sitter init-config
以创建一个配置文件,如 Tree-sitter 的 配置目录 中的~/.config/tree-sitter/config.json
。 - 创建一个目录,用于存放已安装的解析器,并将其添加到 Tree-sitter 配置文件中的
"parser-directories"
列表中。 - 将所需语言的 Tree-sitter 解析器 克隆到解析器目录中。
定义提取查询
为了能够从某些源代码文件中提取某种语言的定义形状,需要定义一个 查询。要定义一个新的查询,在 Code-shape 的语言 配置目录 ~/.config/code-shape/languages/
中创建一个以 .scm
为后缀的文件,例如 ~/.config/code-shape/languages/c.scm
,并放置一系列 Tree-sitter 查询 模式,如下所示:
; C language function declarations
(declaration
[
(function_declarator
declarator: (identifier) @fn.declaration.name
)
(_
(function_declarator
declarator: (identifier) @fn.declaration.name
)
)
]
)
; C language function pointer declarations
(declaration
[
(init_declarator
(function_declarator
(_ (_ declarator: (identifier) @fn.pointer.declaration.name))
)
)
(init_declarator
(_
(function_declarator
(_ (_ declarator: (identifier) @fn.pointer.declaration.name))
)
)
)
]
)
; C language function definitions
(function_definition
[
(function_declarator
declarator: (identifier) @fn.name
)
(_
(function_declarator
declarator: (identifier) @fn.name
)
)
]
body: (_) @fn.scope
)
需要定义具有特殊名称的捕获
<type>.name
是一个捕获,其中type
可以是,例如,fn
、class
或其他任何匹配代码实体的名称。<type>.scope
是一种特殊的捕获,允许工具捕获实体上下文,通常是由定义实体主体的标记组成的,例如 函数体。
工具输出的示例
# code-shape --scope source.c tree-sitter/lib/src/alloc.c
fn ts_malloc_default
fn ts_calloc_default
fn ts_realloc_default
fn.pointer.declaration ts_current_malloc
fn.pointer.declaration ts_current_calloc
fn.pointer.declaration ts_current_realloc
fn.pointer.declaration ts_current_free
fn ts_set_allocator
# code-shape examples/foo.c
fn.declaration ts_malloc_default
fn.declaration ts_calloc_default
fn.declaration ts_realloc_default
fn.pointer.declaration ts_current_malloc
fn.pointer.declaration ts_current_calloc
fn.pointer.declaration ts_current_realloc
fn.pointer.declaration ts_current_free
fn foo
fn bar
# code-shape examples/foo.py
class Foo
def foo
def bar
def inner
def one
def two
def wrap
class Baz
class Bar
class Foo
def func1
def func2
def three
def four
嵌入式形状查询
目前,该工具为以下语言解析器提供了内置的形状查询
依赖项
~9–23MB
~282K SLoC