Last active
August 29, 2015 13:58
-
-
Save vaskaloidis/10015863 to your computer and use it in GitHub Desktop.
Some YACC grammar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%{ | |
#include <stdio.h> | |
%} | |
%% | |
command : expr '\n' { printf("The result is: %d\n",$1); } | |
; | |
expr : | |
expr '+' term | |
{ $$ = $1 + $3; } | |
| | |
term | |
{ $$ = $1; } | |
| | |
expr '%' term | |
{ $$ = $1 % $3; } | |
| | |
expr '/' term | |
{ $$ = $1 / $3; } | |
| | |
expr '-' term | |
{ $$ = $1 - $3; } | |
; | |
term : | |
term '*' factor | |
{ $$ = $1 * $3; } | |
| | |
factor | |
{ $$ = $1; } | |
; | |
factor : number { $$ = $1; } | |
| '(' expr ')' { $$ = $2; } | |
; | |
number : number digit { $$ = 10 * $1 + $2; } | |
| digit { $$ = $1; } | |
; | |
digit : '0' { $$ = 0; } | |
| '1' { $$ = 1; } | |
| '2' { $$ = 2; } | |
| '3' { $$ = 3; } | |
| '4' { $$ = 4; } | |
| '5' { $$ = 5; } | |
| '6' { $$ = 6; } | |
| '7' { $$ = 7; } | |
| '8' { $$ = 8; } | |
| '9' { $$ = 9; } | |
; | |
%% | |
main() | |
{ yyparse(); | |
return 0; | |
} | |
int yylex(void) | |
{ static int done = 0; /* flag to end parse */ | |
int c; | |
if (done) return 0; /* stop parse */ | |
c = getchar(); | |
if (c == '\n') done = 1; /* next call will end parse */ | |
return c; | |
} | |
int yyerror(char *s) | |
/* allows for printing error message */ | |
{ printf("%s\n",s); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment