1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- /*
- Syntax analyser
- for `bison`
- */
- %{
- #include <stdio.h>
- /* Prototypes */
- int yylex (void);
- void yyerror (const char *);
- /* Variable from lexical analysis */
- extern char* yytext;
- %}
- %defines /* Geneates eval.tab.h */
- %token number
- %start EXPR_CALCS /* Axiom */
- %%
- EXPR_CALCS : EXPR_CALC
- | EXPR_CALCS EXPR_CALC
- ;
- EXPR_CALC : EXPR '=' { printf("%d\n", $1); }
- ;
- EXPR : EXPR '+' FACTOR {$$ = $1 + $3;}
- | EXPR '-' FACTOR {$$ = $1 - $3;}
- | FACTOR
- ;
- FACTOR : FACTOR '*' ATOM {$$ = $1 * $3;}
- | FACTOR '/' ATOM {if ($3 == 0) $$ = $1; else $$ = $1 / $3;}
- | ATOM
- ;
- ATOM : number {$$ = $1;}
- | '(' EXPR ')' {$$ = $2;}
- ;
- %%
- #include <stdio.h>
- #include "eval.tab.h"
- void yyerror (const char * error)
- {
- fprintf (stderr, "Error detected : %s\n for expression\n%s\n", error, yytext);
- }
- int main() {
- if ( yyparse() != 0 ) {
- fprintf(stderr, "Error detected : syntax error\n");
- return 1;
- }
- else
- return 0;
- }
|