【问题标题】:ANTLR Tree Grammar and StringTemplate Code TranslationANTLR 树语法和 StringTemplate 代码翻译
【发布时间】:2010-12-21 11:50:12
【问题描述】:

我正在使用示例 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 Code Translation with String Templates,但似乎这种方法在树语法中充分利用了交错代码。是否也可以在字符串模板中尽可能just做到这一点?

解决方案,我根据特伦斯的建议添加解决方案:

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> {}
>>

【问题讨论】:

    标签: antlr antlr3 stringtemplate


    【解决方案1】:

    试试

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

    【讨论】:

    • 非常感谢。其实正确的形式是:decls={$d}
    猜你喜欢
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多