Search code examples
compiler-constructionbisonflex-lexer

While working on a compiler for a project, I had a problem with a certain type of production


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.


Solution

  • 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.