Created
September 22, 2020 05:23
-
-
Save blacksmithop/e134ade8d0d0ad4b1bbf5e264a2961c1 to your computer and use it in GitHub Desktop.
Arithmetic Expression Evaluation with lex, yacc
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
%{ | |
/* 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"); | |
} |
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
%{ | |
/* 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