سؤال

I am writing a compiler with antlr and java. I have writen parser in antlr and it generates code. 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? how should I implement this tree in antlr?

هل كانت مفيدة؟

المحلول

Yes and no, its true that antlr generates code for lexer and parser that can parse the input according to the grammar. So yes, antlr allows to generate a parse tree and allows to traverse it. 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. So this is where antlr stops and your application starts.

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. So you should extend the antlr listener (in antlr 4 there are also visitors for better control over traversing process), and override methods like

"onFirstNumber(int number)"

"onPlus" and

"onSecondNumber(int number)"

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.

Hope this helps,

Mark

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top