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

查看:30
本文介绍了使用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.

我的目标基本上是用

推荐答案

一个函数名——看起来是一个标识符"——将被表示为一个 TerminalNode(扩展 ParseTree,它是基本的解析树节点).因此,在适当的上下文中,

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天全站免登陆