## Lab 6 (en): parser generators - priorities, error handling, BNF Converter

### Bison

Discuss an example of handling operator priorities e.g.

%token NUM
%left '-' '+'
%left '*' '/'
%left NEG     /* phantom lexeme: unary minus */
%right '^'    /* exponentiation       */
%%
exp:      NUM                { $$= 1; } | exp '+' exp {$$ = $1 +$3;    }
| exp '-' exp        { $$= 1 - 3; } | exp '*' exp {$$ = $1 *$3;    }
| exp '/' exp        { $$= 1 / 3; } | '-' exp %prec NEG {$$ = -$2; } | exp '^' exp { $$= pow (1,3);} | '(' exp ')' {$$ =$2;         }
;
%%

Discuss an example of error handling, e.g.

exp:      NUM                { $$= 1; } | exp '+' exp {$$ = $1 +$3;    }
| exp '-' exp        { $$= 1 - 3; } | exp '*' exp {$$ = $1 *$3;    }
| exp '/' exp        { $$= 1 / 3; } | '-' exp %prec NEG {$$ = -$2; } | exp '^' exp { $$= pow (1,3);} | '(' exp ')' {$$ =$2;         }
| '(' error ')'
{ printf("Error in expression\n"); = 0;}
;

The students should implement above examples in their code; apart from that thay write their Latte parsers.

### Java Cup

Priorities:

precedence left PLUS, MINUS;
precedence left TIMES, DIVIDE, MOD;
precedence left UMINUS;

expr ::=  MINUS expr:e
{: RESULT = new Integer(0 - e.intValue()); :}
%prec UMINUS

Error handling:

stmt ::= expr SEMI | while_stmt SEMI | if_stmt SEMI | ... |
error SEMI
;

### Happy

Similar to Bison, e.g.

%left '+' '-'
%left '*' '/'
%left NEG
%%

Exp   :
| Exp '+' Exp             { Plus $1$3 }
| Exp '-' Exp             { Minus $1$3 }
| Exp '*' Exp             { Times $1$3 }
| Exp '/' Exp             { Div $1$3 }
| '(' Exp ')'             { Brack $2 } | '-' Exp %prec NEG { Negate$2 }
| int                     { Int \$1 }

## BNFC

Discuss an example, e.g.

entrypoints Exp;

EAdd.  Exp  ::= Exp "+" Exp1 ;
EMul.  Exp1 ::= Exp1 "*" Exp2 ;
ENum.  Exp2 ::= Integer ;
coercions Exp 2;

Students should

• compile and run this example in the chosen programming language
• analyse the BNFC-generated code
• extend the example with more operatros, parentheses, etc..
• try to modify the generated parser