使用ANTLR4、Graphviz和Python生成Go代码CFG时解析树为空的问题排查求助
ANTLR4、Graphviz和Python生成Go代码CFG时解析树为空的问题排查求助
大家好,我最近在尝试用ANTLR4、Graphviz和Python来生成Go代码的控制流图(CFG),但遇到了一个卡住进度的问题——解析树输出始终是空的[],完全没法进行后续的CFG提取工作,想请各位帮忙排查一下。
我用到的文件包括cfg_from_stdin.py、cfg_extractor_visitor.py、GoLexer.g4以及测试用的test.go(test.go结构简单,内容是正确的)。我怀疑问题出在GoLexer.g4里,可能需要修正或者补充一些规则,但暂时没找到具体的问题点。
以下是我代码里的关键片段:
获取解析树的函数
def get_parse_tree(input_stream): lexer = GoLexer(input_stream) stream = CommonTokenStream(lexer) # 打印词法分析后的详细Token信息 print("Lexed Tokens:") for token in lexer.getAllTokens(): print(f"Token: {token.type}, Text: '{token.text}', Line: {token.line}, Column: {token.column}") # 再次打印词法Token print("Lexed Tokens:") for token in stream.tokens: print(token) parser = GoParser(stream) return parser.sourceFile()
提取CFG的核心函数
def extract(input_stream): cfg_extractor = CFGExtractorVisitor() parse_tree = get_parse_tree(input_stream) print("Parse Tree:", parse_tree) # 新增打印解析树的语句 graph = cfg_extractor.extract(parse_tree) return graph
保存与绘制CFG的辅助函数
def save_graphs(graphs, output_dir): import os import networkx as nx import matplotlib.pyplot as plt print(f"Total graphs to process: {len(graphs)}") for i, graph in enumerate(graphs): print(f"Processing graph {i}") try: output_path = os.path.join(output_dir, f"graph_{i}.png") nx.draw(graph, with_labels=True, font_weight='bold', node_color='skyblue') plt.show() # 显示图像 plt.savefig(output_path) plt.close() print(f"Graph {i} saved to {output_path}") except Exception as e: print(f"Error processing graph {i}: {e}") print(f"All graphs processed and saved to {output_dir}") def draw_CFG(graph, output_path, verbose=False): if isinstance(graph, list): print("Error: Received a list of functions instead of a graph.") return
目前运行代码后,解析树打印出来是空的[],这说明词法或语法分析环节肯定出了问题,导致没有生成有效的解析树。我已经加了Token打印的语句,试图排查词法分析是否正常,但还是没理清头绪。
有没有大佬能帮我看看哪里可能出问题了?比如Lexer的规则是不是有遗漏,或者解析树生成的逻辑哪里出错了?
备注:内容来源于stack exchange,提问作者Suraj Maity
相关产品推荐
相关产品推荐

