Skip to content

Instantly share code, notes, and snippets.

@vaskaloidis
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaskaloidis/10015863 to your computer and use it in GitHub Desktop.
Save vaskaloidis/10015863 to your computer and use it in GitHub Desktop.
Some YACC grammar
%{
#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