Last active
March 7, 2017 19:34
-
-
Save tyzoid/c8144513963078a6ccd9b06cfe36776b to your computer and use it in GitHub Desktop.
Four-Function Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern int yyparse(void); | |
int main() { | |
yyparse(); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%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] ; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%{ | |
#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