CAL1.l---------------------------------------------------------------------- %{ #include <stdlib.h> #include <stdio.h> #include "y.tab.h" void yyerror(char*); %} %% [ \t]+ ; [0-9]+\.[0-9]+ {yylval.fval=atof(yytext);return FLOAT;} [0-9]+ {yylval.ival=atoi(yytext);return INTEGER;} [-+*/] {return *yytext;} "(" {return *yytext;} ")" {return *yytext;} \n {return *yytext;} . {printf("invalid character: %c",*yytext);} CAL1.Y-------------------------------------------------------------------------------------------------- %{ #include <stdlib.h> #include <stdio.h> int yylex(void); %} %union {int ival; float fval;} %token <ival> INTEGER %token <fval> FLOAT %type <fval> expr %type <fval> mulex %type <fval> term %% program: line program | line line: expr '\n' { printf("%f\n",$1); } | '\n' expr: expr '+' mulex { $$ = $1 + $3; } | expr '-' mulex { $$ = $1 - $3; } | mulex { $$ = $1; } mulex: mulex '*' term { $$ = $1 * $3; } | mulex '/' term { $$ = $1 / $3; } | term { $$ = $1; } term: '(' expr ')' { $$ = $2; } | INTEGER { $$ = $1; } | FLOAT {$$ = $1;} %% void yyerror(char *s) { fprintf(stderr,"%s\n",s); return; } int main(void) { yyparse(); return 0; }
How to run it?
$lex cal.l
$yacc -d cal.y
$gcc -o cal lex.yy.c y.tab.c -ll
$./cal