Search code examples
debuggingf#fsyacc

Bug in a simple parser specification in F#


I wonder where the parser specification below went wrong. The parser aims to parse and evaluate an expression like 2+3*4 to 14. It is to be run with FsLexYacc.

%{
%}

%token <int> CSTINT
%token PLUS MINUS MUL
%token LPAR RPAR
%token EOF

%left MINUS PLUS        /* lowest precedence  */
%left TIMES DIV         /* highest precedence */

%start Main
%type int Main 

%%

Main:
    Expr EOF                            { $1 }
;

Expr:
  | CSTINT                              { $1           }
  | MINUS CSTINT                        {  - $2       }
  | LPAR Expr RPAR                      { $2 }
  | Expr MUL Expr                     {  $1 * $3 }
  | Expr PLUS  Expr                     {  $1+$3 }  
  | Expr MINUS Expr                     {  $1-$3 } 
;

I got the error

ExprPar.fsy(18,0): error: Unexpected character '%'%

The line 18 refers to the line up before "Main". Where is the bug?


Solution

  • I believe the type specified by %type should be in angle brackets:

    %type <int> Main