Professional Documents
Culture Documents
Yacc
Yacc
yacc
a tool for automatically generating a parser given a grammar
• Production Rules:
%%
production1 : symbol1 symbol2 … { action }
symbol3 symbol4 … { action } |
…|
Production2 : symbol1 symbol2 { action }
%%
Example
%%
statement : expression { printf (" = %g\n", $1); }
expression : expression '+' expression { $$ = $1 + $3; }
| expression '-' expression { $$ = $1 - $3; }
| NUMBER { $$ = $1; }
%%
According these two productions,
5 + 4 – 3 + 2 is parsed into:
Defining Values
expr : expr '+' term { $$ = $1 + $3; }
| term { $$ = $1; }
;
term : term '*' factor { $$ = $1 * $3; }
| factor { $$ = $1; }
;
factor : '(' expr ')' { $$ = $2; }
| ID
| NUM
;
• $1
• expr : expr '+' term { $$ = $1 + $3; }
• | term { $$ = $1; }
• ;
• term : term '*' factor { $$ = $1 * $3; }
• | factor { $$ = $1; }
• ;
• factor : '(' expr ')' { $$ = $2; }
• | ID
• | NUM
• ;
Example 1:
{%
"include"y.tab.h#
}%
%%
};return A{ ]aA[
};return B{ ]bB[
n {return NL;}\
};return yytext[0]{ .
%%
Yacc part : file second.y
{%
>include<stdio.h#
}%
token A B NL%
%%
stmt : A A A A A A A A A A s B NL
{
;printf("Valid\n")
;exit(0)
}
;
s:sA
|
;
%%
Yacc part : file second.y
int yyerror(char *msg)
{
;printf("Invalid String\n")
;exit(0)
}
int main(void)
{
;printf("Enter the String\n")
;)(yyparse
int yywrap(void) }
{
;return 0
}
Compilation :
• Compiling & running the yacc program
lex first.l
yacc −d second.y
cc lex.yy.c y.tab.c
a.out/.
Example 2
Implementation of calculator using LEX and YACC
{%
>include<stdio.h#
"include "y.tab.h#
}%
%%
{ +]0-9[
;yylval=atoi(yytext)
;return NUMBER
; ]t\[
;return 0 ]n\[
;return yytext[0] .
%%
int yywrap()
return 1;
}
YACC PART:
%{
#include<stdio.h>
int flag=0;
%}
%token NUMBER
%%
ArithmeticExpression: 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;}
%%
void main()
printf("\nEnter Any Arithmetic Expression which can have operations Addition, Subtraction, Multiplication, Divison, Modulus and Round
brackets:\n");
yyparse();
if(flag==0)
void yyerror()
flag=1;