tree-sitter
在线体验网站
https://tree-sitter.github.io/tree-sitter/playground
在通过python使用tree-sitter之后,我们可以通过上面的网站熟悉一下tree-sitter的功能和性能。
step1 创建环境
首先我们创建一个conda环境,并激活
例如我创建的是名称为treesitter
的conda环境,python版本是3.9
conda create -n treesitter python=3.9
conda activate treesitter
step2 安装依赖
使用pip
安装tree-sitter
的依赖,等待完成即可
pip install tree-sitter
step3 新建项目
我们新建一个 python 的项目,使用刚刚创建好的环境。
(1) 克隆解析器
首先我们到根目录下,创建一个名为vendor
的文件夹。
然后将我们需要解析的源代码语言的对应解析器项目代码给 git clone
下来。
例如,我想用tree-sitter
来解析 C 语言和 C++ 语言的源代码,那么我就需要从github上克隆下来tree-sitter-c
和 tree-sitter-cpp
这两个库
git clone https://github.com/tree-sitter/tree-sitter-c.git
git clone https://github.com/tree-sitter/tree-sitter-cpp.git
(2)创建build.py
完成克隆后,我们在根目录创建一个名为build.py
的文件,里面写入:
from tree_sitter import Language
Language.build_library(
# Store the library in the `build` directory
'build/my-languages.so',
# Include one or more languages
[
'vendor/tree-sitter-c',
'vendor/tree-sitter-cpp'
# 'vendor/tree-sitter-java',
# 'vendor/tree-sitter-python',
# 'vendor/tree-sitter-cpp',
]
)
注意,在上面的数组[]里,我们写上需要的解析器项目的路径,我需要解析c和cpp语言,那么我就写了 'vendor/tree-sitter-c'
和 'vendor/tree-sitter-cpp'
这两个,当然如果需要其他语言,就换成对应语言的解析器的地址就行啦。
我们 运行 写好的build.py
文件,会生成一个名为build/
的文件夹。
4. 测试
然后,我们在根目录创建一个main.py
文件,填入以下内容
代码部分参考自👉 python环境解析任意语言tree-sitter的使用方法
from tree_sitter import Language, Parser
# 注意C++对应cpp,C#对应c_sharp(!这里短横线变成了下划线)
# 看仓库名称
CPP_LANGUAGE = Language('build/my-languages.so', 'cpp')
#CS_LANGUAGE = Language('build/my-languages.so', 'c_sharp')
# 举一个CPP例子
cpp_parser = Parser()
cpp_parser.set_language(CPP_LANGUAGE)
# 这是b站网友写的代码,解析看看
cpp_code_snippet = '''
int mian{
piantf("hell world");
remake O;
}
'''
# 没报错就是成功
tree = cpp_parser.parse(bytes(cpp_code_snippet, "utf8"))
# 注意,root_node 才是可遍历的树节点
root_node = tree.root_node
print(root_node)
print('ok')
如果跑起来有显示,说明环境成功了~