A systematic way to generate ANTLR tree grammar?

I have a slightly large ANTLR parser grammar file and you want to create a tree grammar for it. But, as far as I know, this job of generating a grammar of a tree cannot be done automatically, i.e. I have to generate it manually, copying the parser grammar, deleting unnecessary code, etc. I want to know if there is a systematic way to generate a tree grammar file from a parser grammar file.

PS I read an article stating that β€œ β€œ Manual tree movement is better than tree grammars . ” Is this reliable information? If so, it would be better if I did a tree walk manually than wrote a tree grammar file ANTLR? And then, how do I make a manual trainer with my ANTLR grammar parser file (it does AST using rewrite rules)?

Thanks in advance.

+6
source share
1 answer

sky wrote:

I want to know if there is a systematic way to generate a tree grammar file from a parser grammar file

You already described a systematic way to do this: copy the parser / production rules in the grammar of the tree and leave the rewrite rules in it. This will probably handle most of your rules, but with other parser rules (using AST's built-in rewrite rules), it might look a little different. Because of this, there is no automatic way to generate a tree grammar.

sky wrote:

PS I read an article that insists that "Manual tree movement is better than tree-like . " Is this reliable information?

Yes it is. Note that Terence Parr (creator of ANTLR) has published an article about the ANTLR wiki itself, so its author (Andy Tripp) raises valid points.

sky wrote:

If so, would it be better if I made a manual walk on a tree than writing an ANTLR tree grammar file?

As Andy mentioned in his conclusion: β€œThe decision about whether to use theβ€œ Tree Grammar ”approach to translation, and not justβ€œ do it manually, ”is a matter of taste." So, if you think that writing a grammar of a tree is too much trouble, go by hand. It is up to you: there is no better way.

sky wrote:

And then, how do I make a manual walker tree with my ANTLR parser grammar file (it does AST using rewrite rules)?

Your parser will create an AST, which by default is of type CommonTree (API-doc) . You can use this tree to get children, parent, marker type, etc .: all you need to manually go through the tree.

EDIT

Please note that in the next version of ANTLR (version 4) it is possible (most likely) to automatically generate a tree walker using a combined or parser grammar.

Cm:

+5
source

Source: https://habr.com/ru/post/895563/


All Articles