Skip to content

Instantly share code, notes, and snippets.

@hakxcore
Created May 9, 2022 02:41
Show Gist options
  • Select an option

  • Save hakxcore/97ab639894db96da2a6576f9a05f912c to your computer and use it in GitHub Desktop.

Select an option

Save hakxcore/97ab639894db96da2a6576f9a05f912c to your computer and use it in GitHub Desktop.
## arith.l
/* lex program*/
%{
/* Definition section */
#include<stdio.h>
#include "y.tab.h"
//extern int yylval;
%}
/* Rule Section */
%%
[0-9]+ { yylval = atoi(yytext); /* yylval global variable used to pass the semantic value associated with a token from the lexer to the parser*/
return NUMBER;
}
[\t] ;
[\n] return 0;
. return yytext[0];
%%
int yywrap()
{
return 1;
}
## arith.y
//Parser Source Code :
%{
/* Definition section */
#include<stdio.h>
int flag=0;
%}
%token NUMBER /* %token used for terminal and token and %type can be used for Nonterminal name */
%left '+' '-'
%left '*' '/' '%'
%left '(' ')'
/* Rule Section */
%%
S: E { printf("\nResult=%d\n", $$);
return 0;
};
E: E'+'E {$$=$1+$3;}
| E'-'E {$$=$1-$3;}
| E'*'E {$$=$1*$3;}
| E'/'E {$$=$1/$3;}
| E'%'E {$$=$1%$3;}
| '('E')' {$$=$2;}
| NUMBER {$$=$1;}
;
%%
//driver code
void main()
{
printf("\nEnter Any Arithmetic Expression Modulus and Round brackets:\n");
yyparse();
if(flag==0)
printf("\nEntered arithmetic expression is Valid\n\n");
}
void yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
flag=1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment