简体   繁体   English

在Antlr中制作解析树

[英]Make Parse tree in antlr

I am writing a compiler with antlr and java. 我正在用antlr和java编写编译器。 I have writen parser in antlr and it generates code. 我已经在antlr中编写了解析器,它会生成代码。 now I should make a parse tree I think. 现在我应该创建一个解析树。 can anyone help me how can I do that? 谁能帮助我该怎么做? this generating java code is not a parse tree? 这个生成的Java代码不是解析树吗? how should I implement this tree in antlr? 我应该如何在antlr中实现这棵树?

Yes and no, its true that antlr generates code for lexer and parser that can parse the input according to the grammar. 是的,不是,antlr会为词法分析器和解析器生成可根据语法分析输入的代码,这是事实。 So yes, antlr allows to generate a parse tree and allows to traverse it. 所以是的,antlr允许生成解析树并允许遍历它。 But whan should be done once it met the production rule/token? 但是一旦符合生产规则/令牌,就应该进行处理吗? This part depends on your own logic and antlr can't really help out with this. 这部分取决于您自己的逻辑,而antlr对此无能为力。 So this is where antlr stops and your application starts. 因此,这是antlr停止并且您的应用程序开始的地方。

For example (too simplified): let's say there is a calculator that can add two numbers. 例如(过于简化):假设有一个可以将两个数字相加的计算器。 So we define our grammar and it builds a parser that will allow to "hook up our code" when we see the first number, the second number and a sign "+" between them. 因此,我们定义了语法,并构建了一个解析器,当我们看到第一个数字,第二个数字以及它们之间的符号“ +”时,将允许“连接代码”。

But antlr doesn't know what do you want to do with these numbers, maybe just add one to another, maybe memorize for some future execution, maybe transfer this data to the server that will execute this action very fast, who knows. 但是antlr不知道您要如何使用这些数字,也许只是相加,也许要记住一些将来的执行,也许将这些数据传输到将很快执行此操作的服务器,谁知道。 So you should extend the antlr listener (in antlr 4 there are also visitors for better control over traversing process), and override methods like 因此,您应该扩展antlr侦听器(在antlr 4中,还有访问者可以更好地控制遍历过程),并覆盖类似

"onFirstNumber(int number)" “ onFirstNumber(整数)”

"onPlus" and “ onPlus”和

"onSecondNumber(int number)" “ onSecondNumber(整数)”

the exact format depends on your grammar. 确切的格式取决于您的语法。

Now antlr will call the methods in the needed order (again this is resolved from the grammar) but you should specify what to do as I've described above. 现在,antlr将按所需的顺序调用方法(再次从语法中解决),但是您应该按照上面的描述指定要执行的操作。

Hope this helps, 希望这可以帮助,

Mark 标记

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM