使用ANTLR4生成修改后的代码 [英] Using ANTLR4 to generate modified code

查看:464
本文介绍了使用ANTLR4生成修改后的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用antlr4通过 C.g4 语法.

I'm trying to use antlr4 to parse C files using the C.g4 grammar.

我想知道是否有一种方法可以更改分析树节点内的文本,然后从编辑后的树开始生成一个新的.c文件.

I was wondering if there's a way to change the text inside a parse tree node and then generate a new .c file starting from the edited tree.

我的目标基本上是将所有函数名称替换为<FUNC>

My goal is basically to replace all the function names with <FUNC>

推荐答案

函数名称-看起来像是标识符"-将被表示为TerminalNode(扩展了ParseTree,这是基本的parse-tree节点) .因此,在适当的情况下

A function name -- looks to be an 'Identifier' -- will be represented as a TerminalNode (extends ParseTree, which is the basic parse-tree node). So, in the proper context,

TerminalNode id = (TerminalNode) node;
CommonToken token = (CommonToken) id.getSymbol();
token.setText("<FUNC>");

要在保留原始令牌文本的同时记录简单的更改,请使用所需的任何其他字段创建一个自定义令牌类型(扩展CommonToken).在词法分析器上设置自定义标记工厂以使用自定义标记.参见 TokenFactory .

To record simple changes while preserving the original token text, create a custom token type (extends CommonToken) with whatever additional fields are desired. Set a custom token factory on the lexer to use the custom tokens. See, TokenFactory.

一旦创建了一个解析树,就可以遍历它来分析和更新自定义标记字段.然后,在解析树中创建新的".c"文件时,请根据上下文写出适当的字段.

Once a parse-tree is created, walk it to analyze and update the custom token fields. Then, when walking the parse-tree to create the new '.c' file, write out whatever fields are appropriate depending on context.

这篇关于使用ANTLR4生成修改后的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆