ANTLR树语法和StringTemplate代码翻译
我正在开发一个代码翻译项目,其示例 ANTLR 树语法如下:
start: ^(PROGRAM declaration+) -> program_decl_tmpl();
declaration: class_decl | interface_decl;
class_decl: ^(CLASS ^(ID CLASS_IDENTIFIER))
-> class_decl_tmpl(cid={$CLASS_IDENTIFIER.text});
它的组模板文件如下所示:
group My;
program_decl_tmpl() ::= <<
*WHAT?*
>>
class_decl_tmpl(cid) ::= <<
public class <cid> {}
>>
基于此,我有以下问题:
- 除了我应该在
WHAT 中表达的内容之外,一切都正常工作?
是说程序只是一个类声明列表以获得最终生成的输出? - 这种方法平均适合不太高级的语言吗?
- 我还研究了 使用字符串模板进行 ANTLR 代码翻译< /a>,但这种方法似乎充分利用了树语法中交错代码的优势。是否也可以在字符串模板中尽可能地做到这一点?
解决方案,我根据 Terence 的建议添加解决方案:
start: ^(PROGRAM d+=declaration+) -> program_decl_tmpl(decls={$d});
declaration: cd = class_decl -> decl_tmpl(decl={$cd.st})
| id = interface_decl -> decl_tmpl(decl={$id.st});
class_decl: ^(CLASS ^(ID CLASS_IDENTIFIER))
-> class_decl_tmpl(cid={$CLASS_IDENTIFIER.text});
模板如下:
group My;
program_decl_tmpl(decls) ::= <<
<decls>
>>
decl_tmpl(decl) ::= <<
<decl>
>>
class_decl_tmpl(cid) ::= <<
public class <cid> {}
>>
I am working on a code translation project with a sample ANTLR tree grammar as:
start: ^(PROGRAM declaration+) -> program_decl_tmpl();
declaration: class_decl | interface_decl;
class_decl: ^(CLASS ^(ID CLASS_IDENTIFIER))
-> class_decl_tmpl(cid={$CLASS_IDENTIFIER.text});
The group template file for it looks like:
group My;
program_decl_tmpl() ::= <<
*WHAT?*
>>
class_decl_tmpl(cid) ::= <<
public class <cid> {}
>>
Based on this, I have these questions:
- Everything works fine apart from that what I should express in
WHAT?
to say that a program is simply a list of class declarations to get the final generated output? - Is this approach averagely suitable for not so a high-level language?
- I have also studied ANTLR Code Translation with String Templates, but it seems that this approach takes much advantage of interleaving code in tree grammar. Is it also possible to do it as much as possible just in String Templates?
SOLUTION, I add the solution based on what Terence proposed:
start: ^(PROGRAM d+=declaration+) -> program_decl_tmpl(decls={$d});
declaration: cd = class_decl -> decl_tmpl(decl={$cd.st})
| id = interface_decl -> decl_tmpl(decl={$id.st});
class_decl: ^(CLASS ^(ID CLASS_IDENTIFIER))
-> class_decl_tmpl(cid={$CLASS_IDENTIFIER.text});
And the templates would be:
group My;
program_decl_tmpl(decls) ::= <<
<decls>
>>
decl_tmpl(decl) ::= <<
<decl>
>>
class_decl_tmpl(cid) ::= <<
public class <cid> {}
>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试
Try