[英]Parse C++ with Python
我正在嘗試使用 python 解析 cpp。 我使用 ANTLR 為 python 生成了解析器,現在我想訪問樹並收集一些信息。
這是使用https 的語法文件://github.com/antlr/grammars-v4/blob/master/cpp/CPP14.g4
我嘗試使用以下命令獲取 CPP 解析器 java -jar antlr-4.8-complete.jar -Dlanguage=Python3./CPP14.g4 -visitor
這是我擁有的非常基本的代碼
import sys
import os
from antlr4 import *
from CPP14Lexer import *
from CPP14Parser import *
from CPP14Visitor import *
class TREEVisitor(CPP14Visitor):
def __init__(self):
pass
def visitExpressionstatement(self, ctx):
print(ctx.getText())
return self.visitChildren(ctx)
if __name__ == '__main__':
dtype = ""
input_stream = FileStream(sys.argv[1])
cpplex = CPP14Lexer(input_stream)
commtokstream = CommonTokenStream(cpplex)
cpparser = CPP14Parser(commtokstream)
print("parse errors: {}".format(cpparser._syntaxErrors))
tree = cpparser.translationunit()
tv = TREEVisitor()
tv.visit(tree)
和我試圖解析的輸入文件,
#include <iostream>
using namespace std;
int foo(int i, int i2)
{
return i * i2;
}
int main(int argc, char *argv[])
{
cout << "test" << endl;
foo(1, 3);
return 0;
}
謝謝
Function 調用由postfixexpression
表達式規則識別:
postfixexpression
: primaryexpression
| postfixexpression '[' expression ']'
| postfixexpression '[' bracedinitlist ']'
| postfixexpression '(' expressionlist? ')' // <---- this alternative!
| simpletypespecifier '(' expressionlist? ')'
| typenamespecifier '(' expressionlist? ')'
| simpletypespecifier bracedinitlist
| typenamespecifier bracedinitlist
| postfixexpression '.' Template? idexpression
| postfixexpression '->' Template? idexpression
| postfixexpression '.' pseudodestructorname
| postfixexpression '->' pseudodestructorname
| postfixexpression '++'
| postfixexpression '--'
| Dynamic_cast '<' thetypeid '>' '(' expression ')'
| Static_cast '<' thetypeid '>' '(' expression ')'
| Reinterpret_cast '<' thetypeid '>' '(' expression ')'
| Const_cast '<' thetypeid '>' '(' expression ')'
| typeidofthetypeid '(' expression ')'
| typeidofthetypeid '(' thetypeid ')'
;
因此,如果您將其添加到訪問者:
def visitPostfixexpression(self, ctx:CPP14Parser.PostfixexpressionContext):
print(ctx.getText())
return self.visitChildren(ctx)
它會被打印出來。 請注意,它現在將打印比 function 調用更多的內容,因為它匹配的內容遠不止這些。 你可以label 替代品:
postfixexpression
: primaryexpression #otherPostfixexpression
| postfixexpression '[' expression ']' #otherPostfixexpression
| postfixexpression '[' bracedinitlist ']' #otherPostfixexpression
| postfixexpression '(' expressionlist? ')' #functionCallPostfixexpression
| simpletypespecifier '(' expressionlist? ')' #otherPostfixexpression
| typenamespecifier '(' expressionlist? ')' #otherPostfixexpression
| simpletypespecifier bracedinitlist #otherPostfixexpression
| typenamespecifier bracedinitlist #otherPostfixexpression
| postfixexpression '.' Template? idexpression #otherPostfixexpression
| postfixexpression '->' Template? idexpression #otherPostfixexpression
| postfixexpression '.' pseudodestructorname #otherPostfixexpression
| postfixexpression '->' pseudodestructorname #otherPostfixexpression
| postfixexpression '++' #otherPostfixexpression
| postfixexpression '--' #otherPostfixexpression
| Dynamic_cast '<' thetypeid '>' '(' expression ')' #otherPostfixexpression
| Static_cast '<' thetypeid '>' '(' expression ')' #otherPostfixexpression
| Reinterpret_cast '<' thetypeid '>' '(' expression ')' #otherPostfixexpression
| Const_cast '<' thetypeid '>' '(' expression ')' #otherPostfixexpression
| typeidofthetypeid '(' expression ')' #otherPostfixexpression
| typeidofthetypeid '(' thetypeid ')' #otherPostfixexpression
;
然后你可以這樣做:
def visitFunctionCallPostfixexpression(self, ctx:CPP14Parser.FunctionCallPostfixexpressionContext):
print(ctx.getText())
return self.visitChildren(ctx)
然后只打印foo(1,3)
(請注意,您可能希望 label 更多規則作為postfixexpression
表達式規則中的functionCallPostfixexpression
)。
無論如何以 JSON 格式將 ANTLR 樹轉儲為 AST?
不。
但是您當然可以輕松地自己創建一些東西:每個解析器規則返回的對象,例如translationunit
,包含整個樹。 一個快速而骯臟的例子:
import antlr4
from antlr4.tree.Tree import TerminalNodeImpl
import json
# import CPP14Lexer, CPP14Parser, ...
def to_dict(root):
obj = {}
_fill(obj, root)
return obj
def _fill(obj, node):
if isinstance(node, TerminalNodeImpl):
obj["type"] = node.symbol.type
obj["text"] = node.getText()
return
class_name = type(node).__name__.replace('Context', '')
rule_name = '{}{}'.format(class_name[0].lower(), class_name[1:])
arr = []
obj[rule_name] = arr
for child_node in node.children:
child_obj = {}
arr.append(child_obj)
_fill(child_obj, child_node)
if __name__ == '__main__':
source = """
#include <iostream>
using namespace std;
int foo(int i, int i2)
{
return i * i2;
}
int main(int argc, char *argv[])
{
cout << "test" << endl;
foo(1, 3);
return 0;
}
"""
lexer = CPP14Lexer(antlr4.InputStream(source))
parser = CPP14Parser(antlr4.CommonTokenStream(lexer))
tree = parser.translationunit()
tree_dict = to_dict(tree)
json_str = json.dumps(tree_dict, indent=2)
print(json_str)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.