I would like to write an interpreter in haskell for a simple imperative language. To do that, I first wrote gramar of that language for the tool BNFC (http://bnfc.digitalgrammars.com/).
Part of that grammar is dedicated to arithmetic expressions, such as:
EAdd. Expr ::= Expr "+" Expr ;
EMinus. Expr ::= Expr "-" Expr ;
EMul. Expr ::= Expr "*" Expr ;
ENum. Expr ::= Integer ;
Having just that, I can run the BNFC tool and test it by provided script. It parses arithmetic operations succesfully.
However, if I add another section (let's say with types):
Tint. Type ::= "int" ;
And then put the expr secion, arithmetic operations no longer parse (when testing on 1 + 2 it says "Parse failed... [some tokens here] syntax error at line 1 before 1 + 2")
Why does it happen? How to fix it?
To rephrase:
Why such gramar:
TInt. Type ::= "int" ;
EAdd. Expr ::= Expr "+" Expr ;
ENum. Expr ::= Integer ;
does not parse correctly 1 + 1
using bnfc?
In the absence of an entrypoint
declaration, bnfc will use the first category defined in the grammar as entry point in the test script.
I.e. if you add Tint. Type ::= "int" ;
at the top of your file, the script generated by bnfc will try to parse a Type
, not an Expr
.