用于多种语言生成的Antlr [英] Antlr for multiple language generation

查看:82
本文介绍了用于多种语言生成的Antlr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关antlr简单示例的帖子显示了如何创建以及我们Java的语法.

This post about the antlr simple example shows how to create and us a grammar for java.

但是,这将语法和Java源代码混合在Exp.g源代码中.

However, this intermixes the grammar and the Java source code in the Exp.g source.

我的问题是,是否可以将语法文件与目标语言解耦,以便一个语法文件可用于生成多个Java,Scala,C ++等Lexers/Parsers?

My Question is, Is it possible to decouple the grammar file from the target language, so that the one grammar file can be used for generating multiple Java, Scala, C++, etc Lexers/Parsers?

推荐答案

主要取决于语法中使用目标代码的原因.

It depends mostly on the reason why target code is used in the grammar. Is it only action code to do something with the found tokens (e.g. building a symbol table or alternative tree representation) then is indeed no problem do remove such native code and do the processing afterwards (using a parse tree walker or visitor).

仅是动作代码对找到的标记进行处理(例如,建立符号表或替代树表示形式),然后删除此类本机代码并随后进行处理(使用解析树遍历器或访问者)确实是没有问题的.

但是,谓词是不同的.它们用于指导解析器,并且还需要本机代码.您可以做的是将所有本机代码移动到生成的解析器所源自的基类中.然后,您只需要用目标语言重新编写此基类,并使语法基本上不受本机代码的影响(单个函数调用除外,该调用会调用本机代码).

However, predicates are a different. They are used to guide the parser and also require native code. What you can do is to move all the native code into a base class from which your generated parser derives. You then only need to re-write this base class in your target language and keep the grammar mostly free of native code (except for a single function call, which invokes the native code).

这种方法的优点是不需要附加的库引用(在C/C ++中为#include,以其他语言导入),这也是防止多个目标使用的本机代码.

This approach has the advantage that no additional library reference is necessary (#include in C/C++, import in other languages), which also is native code preventing use for multiple targets.

这篇关于用于多种语言生成的Antlr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆