Skip to content

Instantly share code, notes, and snippets.

@blacksmithop
Last active September 22, 2020 05:24
Show Gist options
  • Save blacksmithop/4ab8fc8781970fea2a4eb2afe44d1b8e to your computer and use it in GitHub Desktop.
Save blacksmithop/4ab8fc8781970fea2a4eb2afe44d1b8e to your computer and use it in GitHub Desktop.
if-else with lex, yacc (ToDo: Add support for nested if-else)
%{
#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;
}
%{
#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