6

I am trying to construct a translator that could convert PL/SQL code to Java using Antlr 4 and StringTemplate 4. I have the grammar of PL/SQl and have already build a parser for PL/SQL but i have no idea how to approach the problem further. I found many articles of language translation using antlr and stringtemplate but they all use ANTLR 3 or ANTLR 2 . So is there any difference when using Antlr 4 to translate along with Stringtemplate as the parser for PL/SQL using Antlr 4 had some differences than Antlr3

I am completely new to Programming language translation and don't know if there is any better way to approach the problem.

4

1 回答 1

10

v4 之前的 ANTLR 对 StringTemplate 具有内在支持(您可以指定您的语法输出为 ST)。从 v4 开始,这种支持似乎已被放弃。

一种选择是使用 Listener 或 Visitor 接口手动构建您的模板。在这种情况下,访客可能更有用。

我目前正在研究的另一个选项是将 ParseTree(解析结果)作为参数分配给模板。我为 ParserRuleContext 使用自定义 ModelAdapter,因此我可以从模板访问子上下文。

示例:我假设您正在使用 PL/SQL 语法。然后你可以有一个模板组,如:

plsql_block(block)   ::= <<{  
   <declarations(block.declare_section)>
   <body(block.body)> 
}>>

declarations(ds)     ::= "<ds.item_declaration:itemDecl()>"
itemDecl(id)         ::= "<id.variable_declaration:varDecl()>" 
varDecl(vd)          ::= "<vd.datatype.text> <vd.ID>;"

body(b)              ::= "<b.text>"

您还需要为 ParserRuleContext 提供 ModelAdapter(这只是其中唯一方法的一个示例):

    @Override
public Object getProperty(Interpreter interpreter, ST seld, Object o, Object property, String propertyName) throws STNoSuchPropertyException
{
    Method m = null;
    try {
        String mn = "get" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
        m = o.getClass().getMethod(mn);
    } catch (Exception e) {
    }
    if (m == null) 
        try {
            m = o.getClass().getDeclaredMethod(propertyName);
        } catch (Exception e) {
        }

    if (m != null) try {
        return m.invoke(o);
    } catch (Exception e) {
        throw new STNoSuchPropertyException(e, property, propertyName);
    }
    else 
        throw new STNoSuchPropertyException(null, property, propertyName);
}

现在您可以执行以下操作:

ANTLRInputStream input = new ANTLRInputStream(new FileInputStream("block_test.sql"));
PLSQLLexer lexer = new PLSQLLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
PLSQLParser parser = new PLSQLParser(tokens);
parser.setBuildParseTree(true);
ParseTree tree = parser.plsql_block();

STGroupFile stg = new STGroupFile("test.stg");
stg.registerModelAdaptor(ParserRuleContext.class, new ContextModelAdapter());
ST t = stg.getInstanceOf("plsql_block");
t.add("block", tree);
System.out.println(t.render());

希望这可以帮助!

于 2014-02-17T23:20:12.260 回答