Skip to content

Instantly share code, notes, and snippets.

@Justasic
Created May 27, 2014 08:20
Show Gist options
  • Save Justasic/b100daac2af9339bdef5 to your computer and use it in GitHub Desktop.
Save Justasic/b100daac2af9339bdef5 to your computer and use it in GitHub Desktop.
Basic (probably not working) calculator using flex/bison
%option noyywrap
%option outfile="scanner.c" header-file="scanner.h"
%{
#include "calculator.tab.h"
int yylval;
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Unknown character: %s\n", yytext); }
%%
#if 0
int main(int argc, char **argv)
{
int tok;
while ((tok = yylex()))
{
printf("%d", tok);
if (tok == NUMBER)
printf(" = %d", yylval);
printf("\n");
}
return 0;
};
#endif
#if 0
int main(int argc, char **argv)
{
if (argc > 1)
{
if (!(yyin = fopen(argv[1], "r")))
{
perror(argv[1]);
return 1;
}
}
yylex();
return 0;
}
#endif
%{
#include <stdio.h>
#include "scanner.h"
extern int yyerror(const char *s);
%}
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* Determine the expression grammar as <beginning of line> <expression> <end of line> */
| calclist exp EOL { printf("= %d\n", $1); }
;
/* Determine the expressions ADD and SUB and calculate them */
exp: factor
| exp ADD factor { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
;
/* Determine the expressions MUL and DIV and calculate them as well */
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
/* Determine an absolute value and calculate it */
term: NUMBER
| ABS term { $$ = $2 >= 0 ? $2 : - $2; }
;
%%
int main(int argc, char **argv)
{
yyparse();
}
int yyerror(const char *s)
{
fprintf(stderr, "Expression error: %s\n", s);
}
CC=clang
CFLAGS=-Wall
LDFLAGS=-lfl
all:
bison -d calculator.y
flex calculator.l
$(CC) $(CFLAGS) -c scanner.c -o scanner.o
$(CC) $(CFLAGS) -c calculator.tab.c -o calculator.tab.o
$(CC) *.o -o calc $(LDFLAGS)
clean:
rm -f lex.yy.c calculator.tab.c calc calculator.tab.h scanner.c scanner.h *.o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment