Created
March 27, 2018 07:19
-
-
Save celestialphineas/dd4a389dd27c4df9ab432d16ba4398ac to your computer and use it in GitHub Desktop.
Yacc program for generating a simple infix calculator
This file contains hidden or 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
| %{ | |
| /* Example of a Yacc calculator */ | |
| #define YYSTYPE double | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <math.h> | |
| %} | |
| %token OPERAND | |
| %left '+' '-' | |
| %left '*' '/' | |
| %right '^' | |
| %left UMINUS | |
| %% /* Grammar rules */ | |
| in : | |
| | line in | |
| ; | |
| line : '\n' | |
| | expr '\n' { printf("%lf\n", $1); } | |
| ; | |
| expr : OPERAND { $$ = $1; } | |
| | expr '+' expr { $$ = $1 + $3; } | |
| | expr '-' expr { $$ = $1 - $3; } | |
| | expr '*' expr { $$ = $1 * $3; } | |
| | expr '/' expr { $$ = $1 / $3; } | |
| | expr '^' expr { $$ = pow($1, $3); } | |
| | '-' expr %prec UMINUS { $$ = - $2; } | |
| | '(' expr ')' { $$ = $2; } | |
| ; | |
| %% | |
| int main(void) | |
| { | |
| return yyparse(); | |
| } | |
| int yylex(void) | |
| { | |
| int c; | |
| while((c = getchar()) == ' '); | |
| if(isdigit(c) || c == '.') { | |
| ungetc(c, stdin); | |
| scanf("%lf", &yylval); | |
| return OPERAND; | |
| } | |
| return c; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Task Four
Build
Content of the shell script
build.sh:Generated files:
y.tab.ccalexecutableTest
Result: