Explanation:
This program checks whether a variable is valid or not.
Lex:
%{
#include "y.tab.h"
%}
Declaration section. Include y.tab.h for making lexer read the input symbol so that it can send tokens to Yacc parser.
%%
[a-zA-z_] {return ALPHA;}
[0-9]+ {return NUMBER;}
"\n" { return ENTER;}
. {return ER;}
%%
yywrap()
{}
return proper tokens in this lexer part.
Yacc:
%{
#include <stdio.h>
#include<stdlib.h>
%}
%token ALPHA NUMBER ENTER ER
define header files and tokens which are returned from lexer.
%%
var:v ENTER {printf("Valid Variable\n");exit(0);}
v:ALPHA exp1
exp1:ALPHA exp1
|NUMBER exp1
| ;
%%
Its a grammar.
yyerror()
{
printf("Invalid Variable\n");
}
main()
{
printf("Enter the expression:");
yyparse();
}
yyerror() is called when v was not valid in the previous snippet.
main() function scans for the variable. Note that "Valid" was displayed in the previous snippet if v was valid.
This program checks whether a variable is valid or not.
Lex:
%{
#include "y.tab.h"
%}
Declaration section. Include y.tab.h for making lexer read the input symbol so that it can send tokens to Yacc parser.
%%
[a-zA-z_] {return ALPHA;}
[0-9]+ {return NUMBER;}
"\n" { return ENTER;}
. {return ER;}
%%
yywrap()
{}
return proper tokens in this lexer part.
- if character is encountered, return ALPHA token to parser.
- similarly, if number is encoutered, return NUMBER token, if newline character, then return ENTER token, and if any other character, return ER token.
yywrap() function is responsible for checking whether there are any more inputs. If no, then yywrap() tells program to end.
Yacc:
%{
#include <stdio.h>
#include<stdlib.h>
%}
%token ALPHA NUMBER ENTER ER
define header files and tokens which are returned from lexer.
%%
var:v ENTER {printf("Valid Variable\n");exit(0);}
v:ALPHA exp1
exp1:ALPHA exp1
|NUMBER exp1
| ;
%%
Its a grammar.
- var is the grammar which defines, if v is followed by ENTER token, and if v is valid, we print "Valid" and then exit.
- v is defined as an alphabet, folllowed by and exp1.(variable should start with alphabet or underscore only. and ALPHA token represents those two as you can see in lexer).
- exp1 is defined multiple ways. as you can see above.(a character/number followed by exp1. Or nothing.)
- This way, input is rcursively checked against grammar. If its successfully matched, v is valid. and we display "Valid" message.
yyerror()
{
printf("Invalid Variable\n");
}
main()
{
printf("Enter the expression:");
yyparse();
}
yyerror() is called when v was not valid in the previous snippet.
main() function scans for the variable. Note that "Valid" was displayed in the previous snippet if v was valid.
3 comments
Write commentsPlease add the explanations as soon as possible ... These are very helpful and I have lab on 5th Dec :). Thank you so much for all these btw.
ReplyThanks for the review :)
ReplyAll explanations are published now. Hope you like it!
-CodeShuffle
Thanks a lot! really helpful!
ReplyShare your views about this article!