问题
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