Skip to content

Instantly share code, notes, and snippets.

@bhargavkulk
Last active October 3, 2021 07:37
Show Gist options
  • Save bhargavkulk/5ea3100031a2563cf9a9c586c8244bc3 to your computer and use it in GitHub Desktop.
Save bhargavkulk/5ea3100031a2563cf9a9c586c8244bc3 to your computer and use it in GitHub Desktop.
#include "test.tab.h"
int main()
{
yyparse();
return 0;
}
main: test.y test.l
bison -d test.y
flex test.l
gcc -o $@ main.c test.tab.c lex.yy.c -lfl
@echo "Compiled main."
%{
#include "test.tab.h"
%}
%%
"+" { return ADD; }
"-" { return SUB; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore white space */ }
. { yyerror("Mystery character %c\n", *yytext); }
%%
%{
#include <stdio.h>
%}
%token NUMBER
%token ADD SUB
%token EOL
%%
stmt: /* nil */
| stmt exp EOL { printf("= %d\n> ", $2); }
;
exp: term
| exp ADD term { $$ = $1 + $3; }
| exp SUB term { $$ = $1 - $3; }
;
term: NUMBER
;
%%
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment