Skip to content

Instantly share code, notes, and snippets.

@blacksmithop
Created September 22, 2020 05:23
Show Gist options
  • Save blacksmithop/e134ade8d0d0ad4b1bbf5e264a2961c1 to your computer and use it in GitHub Desktop.
Save blacksmithop/e134ade8d0d0ad4b1bbf5e264a2961c1 to your computer and use it in GitHub Desktop.
Arithmetic Expression Evaluation with lex, yacc
%{
/* Definition section */
#include<stdio.h>
int yylex();
void yyerror();
%}
%token NUMBER ID
// setting the precedence
// and associativity of operators
%left '+' '-'
%left '*' '/'
/* Rule Section */
%%
E : T
{
printf("Result = %d\n", $$);
return 0;
}
T : T '+' T { $$ = $1 + $3; }
| T '-' T { $$ = $1 - $3; }
| T '*' T { $$ = $1 * $3; }
| T '/' T { $$ = $1 / $3; }
| '-' NUMBER { $$ = -$2; }
| '-' ID { $$ = -$2; }
| '(' T ')' { $$ = $2; }
| NUMBER { $$ = $1; }
| ID { $$ = $1; };
%%
int main()
{
printf("Enter the expression\n");
yyparse();
}
/* For printing error messages */
void yyerror(char* s)
{
printf("\nExpression is invalid\n");
}
%{
/* Definition section*/
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {
yylval=atoi(yytext);
return NUMBER;
}
[a-zA-Z]+ { return ID; }
[\t] ;
\n { return 0; }
. { return yytext[0]; }
%%
int yywrap()
{
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment