parsinglemon

Lemon Parser - Parsing conflict between rules for a.b.c & a.b[0].c


typename ::= typename DOT ID.
typename ::= ID.

lvalue ::= lvalue DOT lvalue2.
lvalue ::= lvalue2.
lvalue2 ::= ID LSQB expr RSQB. // LSQB & RSQB: left & right square bracket. i.e. [ ].
lvalue2 ::= ID.

typename is a rule for the names of types. It matches the following code:

ClassA
package_a.ClassA

while lvalue is a rule for left values. It matches the following code:

varA
varB.C
varD.E[i].F

Now the 2 rules conflicts with each other. Maybe it is because lvalue can also match package_a.ClassA? How can I solve this?


Solution

  • You can't resolve this issue grammatically because your syntax is ambiguous. a.b = 3 is valid if a.b is a member of a, and invalid if a.b is a type, but the semantics of a.b cannot be determined by the syntax.

    You could resolve this in a fairly messy way if you have some way to figure that out in the lexer (which will probably involve some kind of lexical feedback, since the lexer would presumably need access to the symbol table in order to provide that information). Then the lexer could use two different token types for IDs, based on whether or not they are type names.

    But probably the best option is to either abandon the idea of distinguishing grammatically between lvalues and rvalues, and or to assume that all selection operations (a.b) produce lvalues, and then to validate the use of an expression as an lvalue in the semantic action or some subsequent semantic analysis.