0
votes

expr ::= let ID : TYPE [ <- expr ] [[, ID : TYPE [ <- expr ]]]∗ in expr

I was trying to implement this rule in Bison.

So expr is the non-terminal while [[, ID : TYPE [ <- expr ]]]∗ describes a regex and I thought that the only way to describe has using a combination of a few rules

express: COMMA ID COL TYPE OSB ASSIGN expr CSB express  
    ;
expr : LET ID COL TYPE OSB ASSIGN expr CSB IN expr

where COL represents a colon (:), OSB and CSB are [ and ] respectively, ASSIGN is <-, TYPE is int/char.

I felt that adding a production made sense intuitively as it allowed me to have zero or more occurrences of the expression [, ID : TYPE [ <- expr ]]. I applied this logic to other rules as well. However, I got a bunch of shift-reduce conflicts now and I am fairly sure that this is to blame. But I am not sure how to fix this.

Here's the code using Bison and Flex. The grammar is on page 16 of 30.

1
You are reading that grammar incorrectly. See the paragraph at the top of page 17: "Items in square brackets […] are optional." The square brackets are not part of the program.rici
Also, I suppose you are taking the Stanford compiler-writing course, or equivalent. You might be doing something similar to this assignment. Please read section 7 of that document. But first try to get it working without let expressions. You'll need to review Bison precedence declarations, described in the Dragon book and in the bison manual.rici
Would adding the precedence declarations fix it ?@riclAnshuman Kumar
Precedence declarations are part of a solution, although it can be solved without them as well. It is important to understand how bison uses precedence declarations.rici
I did try and fix a lot of the errors involving the square brackets. It does work for a lot of the test cases, except for the one involving precedence of operators. @riclAnshuman Kumar

1 Answers

0
votes

In case anyone sees this ever, the GitHub repo linked contains the correct code. Otherwise you can just search for Compiler using Cool and you will find dozens of other implementations of the same thing.