1. Tree-sitter
tree_sitter是一个解析器生成器工具和增量解析库。它可以为源代码文件构建具体的语法树,并在编辑源文件时高效地更新语法树。它支持多种编程语言的解析,包括python, java, c等。同时支持多种编程语言的使用。
tree_sitter的优点:
1.足够通用,可以解析任何编程语言
2.足够快,可以在文本编辑器中对每次击键进行解析
3.足够健壮,即使在出现语法错误的情况下也能提供有用的结果
4.无依赖性,因此运行库(用纯C编写)可以嵌入到任何应用程序中
tree_sitter官网:https://tree-sitter.github.io/tree-sitter/
python版本tree_sitter的github:https://github.com/tree-sitter/py-tree-sitter
二、使用
from tree_sitter import Language, Parser
# 中括号内的是clone下来的文件夹地址
Language.build_library(
'build/my-languages.so',
[
'../tree-sitter-cpp'
]
)
CPP_LANGUAGE = Language('build/my-languages.so', 'cpp')
parser = Parser()
parser.set_language(CPP_LANGUAGE)
code = self.read_cpp(filename)
tree = parser.parse(bytes(code,"utf-8"))
root_node = tree.root_node
comments = []
functions = []
# 为了确定起始行
code = code.split("\n")
for child_node in root_node.children:
if child_node.type == "function_definition":
function_start_line = child_node.start_point[0]
function_end_line = child_node.end_point[0]
# 不在同一行
if function_start_line != function_end_line:
function_code = code[function_start_line:function_end_line+1]
function_code = "\n".join(function_code)
else:
function_code = code[function_start_line]
# 起始行列 终止行列 函数代码 仓库名 文件名(绝对路径)
functions.append([child_node.start_point,child_node.end_point,function_code,filename])
版权声明:本文为qq_41938789原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。