Skip to content

Instantly share code, notes, and snippets.

@alandipert
Created April 17, 2009 15:11
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 alandipert/97079 to your computer and use it in GitHub Desktop.
Save alandipert/97079 to your computer and use it in GitHub Desktop.
%{
#include <ctype.h>
#include <stdio.h>
#define YYSTYPE double
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%left UNARYMINUS
%left UNARYPLUS
%%
list:
| list '\n'
| list expr '\n' { printf("\t%.8g\n", $2); }
;
expr: NUMBER { $$ = $1; }
| '-' expr %prec UNARYMINUS { $$ = -$2; }
| '+' expr %prec UNARYMINUS { $$ = +$2; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| '(' expr ')' { $$ = $2; }
;
%%
char *progname;
int lineno = 1;
main(int argc, char **argv) {
progname = argv[0];
yyparse();
}
yylex() {
int c;
while((c = getchar()) == ' ' || c == '\t')
;
if(c == EOF)
return 0;
if(c == '.' || isdigit(c)) {
ungetc(c, stdin);
scanf("%lf", &yylval);
return NUMBER;
}
if(c == '\n')
lineno++;
return c;
}
yyerror(char *s) {
warning(s, (char *) 0);
}
warning(char *s, char *t) {
fprintf(stderr, "%s: %s", progname, s);
if(t)
fprintf(stderr, " %s", t);
fprintf(stderr, " near line %d\n", lineno);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment