Skip to content

Instantly share code, notes, and snippets.

@celestialphineas
Created March 27, 2018 07:19
Show Gist options
  • Save celestialphineas/dd4a389dd27c4df9ab432d16ba4398ac to your computer and use it in GitHub Desktop.
Save celestialphineas/dd4a389dd27c4df9ab432d16ba4398ac to your computer and use it in GitHub Desktop.
Yacc program for generating a simple infix calculator
%{
/* 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;
}
@celestialphineas
Copy link
Author

Task Four

Build

./build.sh

Content of the shell script build.sh:

yacc cal.y
gcc y.tab.c -o cal -ll -ly -lm

Generated files:

  • y.tab.c
  • cal executable

Test

./cal

Result:

1+1
2.000000
2+3
5.000000
3+(4*5)
23.000000
3 + (4.2* 2)
11.400000
3.2 + (1/2)
3.700000
3+(1/2)^2
3.250000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment