赞
踩
1. 安装tree_sitter包
pip install tree_sitter
2. 下载语言支撑包
在当前工程目录下新建vendor目录用于存放语言支撑包,tree_sitter支持大部分主流语言,可以参考官网:Tree-sitter|Introduction
如何需要支持java、python、C、C++、C#和javascript,需要在vendor目录下下载以下依赖包:
- git clone https://github.com/tree-sitter/tree-sitter-java
- git clone https://github.com/tree-sitter/tree-sitter-python
- git clone https://github.com/tree-sitter/tree-sitter-c
- git clone https://github.com/tree-sitter/tree-sitter-cpp
- git clone https://github.com/tree-sitter/tree-sitter-c-sharp
- git clone https://github.com/tree-sitter/tree-sitter-javascript
依赖包下载完毕后,需要根据依赖包生成语法解析器my-languages.so,此处创建build.py文件,文件内容如下:
- #coding=utf-8
- from tree_sitter import Language,Parser
- import warnings
- warnings.simplefilter('ignore', FutureWarning)
-
- 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-python'
- ]
- )
需要注意由于Language.build_library方法在tree_sitter的后期版本中将被替换,因此会出现以下告警信息:
- tree_sitter/__init__.py:36: FutureWarning: Language(path, name) is deprecated. Use Language(ptr, name) instead.
- warn("{} is deprecated. Use {} instead.".format(old, new), FutureWarning)
为了消除以上告警,在文件中添加以下语句:
- import warnings
- warnings.simplefilter('ignore', FutureWarning)
在build目录中生成my-languages.so后,可以验证语法解析器的功能,定义main.py文件代码如下:
- #coding=utf-8
- 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')
输出语法树节点信息说明ok,语法树的详细解析可以参考官网的tree格式按需解析。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。