antlr / grammars-v4

Grammars written for ANTLR v4; expectation that the grammars are free of actions.
MIT License
10.25k stars 3.72k forks source link

Grammar in calculator.g4 can not be easily parsed #2816

Open sleagon opened 2 years ago

sleagon commented 2 years ago
expression
   : multiplyingExpression ((PLUS | MINUS) multiplyingExpression)*
   ;

The grammars in Calculator.g4 can not be easily parsed unless modifying it to this:

expression
   : multiplyingExpression (plusMinus multiplyingExpression)*
   ;
plusMinus: PLUS | MINUS;

Here is a simple example, I have searched over google and post a question in stackoverflow, but it seems like that adding a extra rule definition is the best choice.

KvanTTT commented 2 years ago

I don't think it's a problem, the rewritten rule doesn't simplify grammar. Also, you can use Rule Element Labels to archive the same goal:

 expression
   : multiplyingExpression (operator+=(PLUS | MINUS) multiplyingExpression)*
   ;
sleagon commented 2 years ago

I don't think it's a problem, the rewritten rule doesn't simplify grammar. Also, you can use Rule Element Labels to archive the same goal:

 expression
   : multiplyingExpression (operator+=(PLUS | MINUS) multiplyingExpression)*
   ;

Of cause we can use Rule Element Labels o arrchive the same goal. What I want to say is that we should replace them with another plusMinus rule or another label as you mentioned upside, both of them are better than the original one.

sleagon commented 2 years ago

The original grammar definition is quite confusing especially for the beginnerrs who just finished reading cookbook somewhere and want to do some practice using "official" cases here.