This program is a basic way to calculate the "Nested If-Else" in a program. This takes input from Console and puts that into a buffer, however you can take input from a file as : yyin();
Initial : Lex and Yacc are pre-installed in Linux. If you haven't install Flex and Bison in Windows, refer to This Tutorial - How to Compile Lex and Yacc
Step -1: Make a file named as if_else.l. Copy the below code and paste it in that file.
IF ELSE.L
Initial : Lex and Yacc are pre-installed in Linux. If you haven't install Flex and Bison in Windows, refer to This Tutorial - How to Compile Lex and Yacc
Step -1: Make a file named as if_else.l. Copy the below code and paste it in that file.
IF ELSE.L
1: %{
2: #include"y.tab.h"
3: %}
4: %%
5: "if" {return IF;} //Token for If statements
6: "else" {return ELSE;} //Token for Else Statements
7: [sS][0-9]* {return S;} //Statement symbol token
8: "<"|">"|"="|"!="|"<="|">=" {return RELOP;} //Relational Operator
9: [0-9]+ {return NUMBER;} //Number
10: [a-zA-Z][a-zA-Z0-9_]* {return ID;} //Ids
11: \n {;}
12: . {return yytext[0];} //Character Not Desfined
13: %%
Step-2: After completing step 1, you've to create a file in yacc readable format i.e. if_else.y and copy and paste the below code.
IF ELSE.Y
1: %token IF RELOP S NUMBER ID ELSE
2: %{
3: int count=0;
4: %}
5: %%
6: stmt:if_stmt {printf("Nested : %d\n",count);};
7: if_stmt:IF'('cond')'if_stmt {count++;}
8: |IF'('cond')'S' 'ELSE' 'if_stmt {count++;}
9: |IF'('cond')'ELSE' 'if_stmt {count++;}
10: |S;
11: cond:x RELOP x;
12: x:ID
13: |NUMBER
14: ;
15: %%
16: int yywrap(){return 1;}
17: int yyerror(char *ch)
18: {
19: return 1;
20: }
21: int main(){
22: printf("Enter the Statement : \n");
23: yyparse();
24: return 1;
25: }
Now as you've got lex and yacc files, let's compile a compiler.
root@user~:#lex if_else.l
root@user~:#yacc -d if_else.y
root@user~:#gcc lex.yy.c y.tab.c
root@user~:#./a.out
These code will help you in achieving result.
Enter the input as:
if(----)S
if(----)S else S
if(----)S else if(----)S
...........and so on.
How it works:
Consider an input:
if(----)S else if(----)S
now,
we have :
1:stmt:if_stmt {printf("Nested : %d\n",count);};
2:if_stmt:IF'('cond')'if_stmt {count++;}
3: |IF'('cond')'S' 'ELSE' 'if_stmt {count++;}
4: |IF'('cond')'ELSE' 'if_stmt {count++;}
5: |S;
6: cond:x RELOP x;
7: x:ID
8: |NUMBER
Starting from "stmt":
stmt //start symbol
if_stmt //rule 1
IF'('cond')'S' 'ELSE' 'if_stmt //rule 3
IF'('cond')'S' 'ELSE' 'IF'('cond')'if_stmt //rule 1
IF'('cond')'S' 'ELSE' 'IF'('cond')'S //rule 5
IF'('x RELOP x')'S' 'ELSE' 'IF'('x RELOP x')'S //rule 6
IF'('ID RELOP ID')'S' 'ELSE' 'IF'('ID RELOP ID')'S //rule 7
Now, we have got tokens at the input places, that means our derivation is correct.
0 comments:
Post a Comment