Skip to content

Instantly share code, notes, and snippets.

@tyzoid
Last active March 7, 2017 19:34
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 tyzoid/c8144513963078a6ccd9b06cfe36776b to your computer and use it in GitHub Desktop.
Save tyzoid/c8144513963078a6ccd9b06cfe36776b to your computer and use it in GitHub Desktop.
Four-Function Calculator
extern int yyparse(void);
int main() {
yyparse();
return 0;
}
%option noinput
%{
#include "mycalc.tab.h"
#include <stdlib.h>
%}
%option nounput
%%
[0-9]+ { yylval.value = strtod(yytext, 0); return T_FLOAT; }
"+" return T_PLUS_OPERATOR;
"-" return T_MINUS_OPERATOR;
"*" return T_MULTIPLICATION_OPERATOR;
"/" return T_DIVISION_OPERATOR;
[\n] { yylineno++; return T_STATEMENT_SEP; }
[ \t] ;
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int yylex(void);
int yyerror(const char *);
%}
%union {
float value;
}
%token <value> T_FLOAT
%type <value> expression
%left T_MINUS_OPERATOR T_PLUS_OPERATOR
%left T_DIVISION_OPERATOR T_MULTIPLICATION_OPERATOR
%left T_STATEMENT_SEP
%start statements
%%
expression: T_FLOAT { $$ = $1; }
| expression T_PLUS_OPERATOR expression { $$ = $1 + $3; }
| expression T_MINUS_OPERATOR expression { $$ = $1 - $3; }
| expression T_MULTIPLICATION_OPERATOR expression { $$ = $1 * $3; }
| expression T_DIVISION_OPERATOR expression { $$ = $1 / $3; }
;
statement: expression T_STATEMENT_SEP { printf("%lf\n", $1); }
| T_STATEMENT_SEP {}
;
statements: statements statement
| statement
;
%%
int yyerror(const char *s)
{
extern int yylineno;
extern char *yytext;
const char *text = yytext;
if (strcmp(yytext, "\n") == 0) text = "\\n";
fprintf(stderr, "Error: %s at '%s' on line %d\n", s, text, yylineno);
exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment