Last active
September 22, 2020 05:24
-
-
Save blacksmithop/4ab8fc8781970fea2a4eb2afe44d1b8e to your computer and use it in GitHub Desktop.
if-else with lex, yacc (ToDo: Add support for nested if-else)
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
%{ | |
#include "y.tab.h" | |
%} | |
%% | |
"if" {return IF;} | |
"else" {return ELSE;} | |
"&&" {return AND;} | |
"||" {return OR;} | |
"<=" {return LE;} | |
">=" {return GE;} | |
"==" {return EQ;} | |
"<" {return LT;} | |
">" {return GT;} | |
"!=" {return NE;} | |
[a-z]+ {return alpha;} | |
[0-9]+ {return num;} | |
[\t] ; | |
[\n] {return 0;} | |
. {return yytext[0];} | |
%% | |
int yywrap() | |
{ | |
return 1; | |
} |
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
%{ | |
#include <stdio.h> | |
int yylex(); | |
void yyerror(); | |
%} | |
%token num alpha LT GT EQ LE GE NE AND OR | |
%left '+''-' | |
%left '*''/' | |
%right '^' | |
%right '=' | |
%nonassoc UMINUS | |
%nonassoc IF | |
%nonassoc ELSE | |
%left GE NE LT GT LE EQ | |
%left AND OR | |
%% | |
S:ST {printf("ACCEPTED\n");} | |
ST:IF'('F')''{'ST'}' %prec IF | |
|IF '('F')''{'ST'}'ELSE'('ST')' | |
|E';' | |
F:C LO C | |
|C | |
LO:AND | |
|OR | |
C:E RELOP E | |
E:alpha'='E | |
|E'+'E | |
|E'-'E | |
|E'*'E | |
|E'/'E | |
|E'^'E | |
|'-'E %prec UMINUS | |
|alpha | |
|num | |
RELOP:LT | |
|GT | |
|EQ | |
|LE | |
|GE | |
|NE | |
; | |
%% | |
void yyerror (char const *s) { | |
fprintf (stderr, "%s\n", s); | |
} | |
#include <stdio.h> | |
int main(){ | |
printf("Enter the expression\n"); | |
yyparse(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment