ANTLR树语法和StringTemplate代码翻译

发布于 2024-10-08 18:40:55 字数 1524 浏览 6 评论 0原文

我正在开发一个代码翻译项目,其示例 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> {}
>>

基于此,我有以下问题:

解决方案,我根据 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笙痞 2024-10-15 18:40:55

尝试

start: ^(PROGRAM d+=declaration+) -> program_decl_tmpl(decls=$d)

WHAT? = <decls>

Try

start: ^(PROGRAM d+=declaration+) -> program_decl_tmpl(decls=$d)

WHAT? = <decls>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文