1
votes

I am making a compiler for the Cool: the Classroom Object-Oriented Language. I followed the manual Cool-manual.pdf to create a grammar and using PLY 3.10 in python 3.5.2 I managed to create a lexer and a parser, but somehow it found a Shift-Reduce conflict on this production:

expr : LET ID COLON TYPE assign_optional let_assignments IN expr

expr is a Non-terminal symbol that produces several things, among them is the "LET...." above but, as this LET production ends with "...IN expr" that means that the LALR(1) parser from yacc do not know if it should SHIFT after that last expr with what comes after or REDUCE that expr.

For instance:

That last expr could be something like:

a + 2

and as COOL allows I could also do this:

expr : expr + expr #that means expr produces expr PLUS expr

and therefore, after that last expr in the LET I could have a + (or anything allowed). For instance, in this line

LET a:Int <- 3 IN a + 2 + c

could mean to add a + 2 + c as the expression inside of the LET or to add c to the result of the LET expression.

My main issue is:

Should I redo the grammar to avoid this conflict? If i should, how would I do it? cause I think I am not doing anything wrong following the COOL specifications.

Else, Should I handle this on the Semantic Analysis Phase? Any thoughts on how to do it?

Thanks in advance. I hope I explained myself. If not, please let me know and I will try to explain better.

1
ply implements the same kind of precedence based choice to shift vs reduce: dabeaz.com/ply/ply.html#ply_nn27torek

1 Answers

0
votes

I don't know why let is not in the list of expression precedences in section 11 of the manual, but section 7 says

The <expr> of a let extends as far (encompasses as many tokens) as the grammar allows.

which is tantamount to saying that it has the lowest possible precedence (the same as assignment).

I presume you are using precedence declarations for your expr rules, so just add let to the list.