Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java8 and C# grammar: Tree structure of a variable that is initialized with a literal during declaration #3998

Open
PawanKartikS opened this issue Mar 4, 2024 · 2 comments
Labels
csharp target:java Grammars for Java target, https://github.com/antlr/antlr4/blob/master/doc/java-target.md

Comments

@PawanKartikS
Copy link

Hi,

I have a question regarding the tree that's generated for the following Java8 code:

class C {
    public void m() {
        int i = 0;
    }
}

The tree for the initialisation in the declaration looks like:
Screenshot 2024-03-04 at 3 09 16 PM

Why is the initialization so convoluted? Why are inclusive* and shift* nodes involved here when the RHS is a simple literal? Do I have to go through all those nodes to access the literal? I see that this happens for other languages like C# as well.

@kaby76
Copy link
Contributor

kaby76 commented Mar 4, 2024

The parse tree describes the rules in the parse. It is not an abstract syntax tree. The parse tree for the literal is caused by implementing operator precedence using a chain of parser rules.

In an "optimized Antlr grammar", the expression syntax will be implemented using one rule with "alt-ordering". (See the java grammar expression syntax.) This alternative implementation eliminates the long chains of parse tree nodes, and makes for a faster parse. However, it takes a lot of work to develop an alt-ordered rule to implement precedence. Most language specs, like that for C# and C, define operator precedence using a precedence chain of rules.

Yes you will need to "go through" all nodes to get the literal value if you use visitors or listeners. But, working with visitors and listeners are like programming in assembly language. There are better ways to work with trees, e.g., XPath.

@KvanTTT KvanTTT added csharp target:java Grammars for Java target, https://github.com/antlr/antlr4/blob/master/doc/java-target.md labels Mar 5, 2024
@PawanKartikS
Copy link
Author

That explains it! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
csharp target:java Grammars for Java target, https://github.com/antlr/antlr4/blob/master/doc/java-target.md
Projects
None yet
Development

No branches or pull requests

3 participants