Using ANTLR4 to generate modified code

半城伤御伤魂 提交于 2019-12-13 08:47:57

问题


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

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.

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


回答1:


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>");

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.

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.



来源:https://stackoverflow.com/questions/32520813/using-antlr4-to-generate-modified-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!