Tool which will produce a parser for a given grammar.
YACC (Yet Another Compiler Compiler) is a program designed to compile a LALR(1) grammar and to produce the source code of the syntactic analyzer of the language produced by this grammar.
YACC TOOL
Whatis YACC ?
Tool which will produce a parser for a given
grammar.
YACC (Yet Another Compiler Compiler) is a
program designed to compile a LALR(1) grammar
and to produce the source code of the syntactic
analyzer of the language produced by this
grammar
2
3.
yacc
How YACC Works
(1)Parser generation time
YACC source (*.y)
y.tab.h
y.tab.c
C compiler/linker
(2) Compile time
y.tab.c a.out
a.out
(3) Run time
input output
y.output
3
Input toyacc is divided into three sections.
... definitions ...
%%
... rules ...
%%
... subroutines ...
5
6.
YACC File Format
6
%{
Cdeclarations
%}
yacc declarations
%%
Grammar rules
%%
Additional C code
Comments enclosed in /* ... */ may appear
in any of the sections.
7.
YACC Declaration Summary
7
`%start'
Specifythe grammar's start symbol
`%union'
Declare the collection of data types that semantic values may
have
`%token'
Declare a terminal symbol (token type name) with no
precedence or associativity specified
`%type'
Declare the type of semantic values for a nonterminal
symbol
8.
YACC Declaration Summary
8
`%right'
Declarea terminal symbol (token type name) that is
right-associative
`%left'
Declare a terminal symbol (token type name) that is
left-associative
`%nonassoc'
Declare a terminal symbol (token type name) that is
nonassociative
9.
The firstnon-terminal specified in the grammar
specification section.
To overwrite it with %start declaraction.
%start non-terminal
9
10.
Rules
10
• Rule format:E -> E+T|T
• E: E ‘+’ T { }
|T {}
• ;
nonterminal : alt 1 {action 1}
| alt 2 {action 2}
. . .
| alt n {action n)
;
Actions are optional; they are C code.
• Actions are usually at the end of a body, but
grammar part is the same as:
nonterminal alt 1 | alt 2 | ... | alt
n
Yacc specification ofsimple calculator
%{
# include<stdio.h>
%}
%token digit
%%
S :S E 'n' {printf("ans=%dn",$2);}
| E 'n' {printf("ans=%dn",$1);}
;
E : E '+' T {$$ = $1+$3;}
|T
;
T : T '*' F {$$ = $1 * $3;}
| F
;
F : '(' E ')' {$$ = $2;}
| digit
;
%% 13
main()
{
yyparse();
}
int yyerror(char *msg)
{
printf("%sn",msg);
return 1;
}
yylex()
{
int c;
c=getchar();
while(c==' '||c=='t');
if(isdigit(c))
{
yylval = c-'0';
return digit;
}
return c;
}
14.
Main => yyparse=> yylex
2 + 5 n
C(50) => yylval=2, digit =>parser
Digit 2
F 2
T 2
E 2
Yyparse => yylex => ‘+’ =>parser
E ‘+’ 2 _
Yyparse => yylex => ‘5’ => yylval = 5, digit =>yyparse
E ‘+’digit 2 _ 5
E ‘+’ F 2_5
E ‘+’ T 2_5
E 7
Yyparse => yylex => n
E ‘n’ 7
S print(7)
3+5*7 n