Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introduction to YACC
Wei Zhu
wxz094120@utdallas.edu
1
3/17/2016
Architecture
2
3/17/2016
YACC Specifications
• Similar structure to LEX
– Declaration Section
– Translation Rules
– Supporting C/C++ code
Declaration
%%
Translation rules
%%
Supporting C/C++ code
YACC Declaration
• Declaration Section
– C/C++ Code
%{
……..
………….
%}
– YACC definition
• %token
• %start
• Others
3
3/17/2016
YACC Specifications
• Similar structure to LEX
– Declaration Section
– Translation Rules
– Supporting C/C++ code
Declaration
%%
Translation rules
%%
Supporting C/C++ code
YACC Rules
• The rules section represents a grammar. The
left-hand side of a production is followed by
a colon.
• Actions associated with a rule are entered in
braces.
4
3/17/2016
YACC Rules
• Prog -> SS
%%
programs:
statements
;
• SS -> S SS | ε
statements: /*empty*/
| statement
statements
;
Actions
• Actions: associated with a rule are entered in
braces.
• Similar with the LEX
statements:
| statement statements
{
printf(" statements
founded”);
}
;
5
3/17/2016
Symbol Values
• $1, $2….$n can be refer to the values associated with
symbols
• $$ refer to the value of the left
• Every symbol have a value associated with it
(including token and non-terminals)
6
3/17/2016
Actions
• Inherited Attributes
– { fn id PP }
– How to transfer the value of fn and id to PP?
• $0
• $-1
Symbol Types
• Declaring Symbol Types
%union {
int dval;
char *sval;
}%
……………………………
%token <dval> NUMBER
%token <sval> IDENTIFIER
%type <dval> statement
7
3/17/2016
YACC Specifications
• Similar structure to LEX
– Declaration Section
– Translation Rules
– Supporting C/C++ code
Declaration
%%
Translation rules
%%
Supporting C/C++ code
C/C++ Codes
• Supporting C/C++ code
• Token
– In the Lex: return (TOKEN)
– In the Parser:
» %token TOKEN
» // then TOKEN can be used in your yacc code
8
3/17/2016
Feedback
• Feed Information back to the LEX
– YACC
%{
int top_layer = 1;
}%
……………………………
%%
Program:
statement
{
top_layer = 0;
}
;
Feedback
• LEX
%{
extern int top_layer;
}%
……………………………
9
3/17/2016
Make
• Make file
– yacc –d FP.yacc # create y.tab.h, y.tab.c
– lex FP.lex # create lex.yy.c
– cc lex.yy.c y.tab.c –o FP # compile/link
How to Debug
• Add the following into your YACC file
%%
extern int yy_flex_debug;
int main(void) {
yy_flex_debug = 1;
yyparse();
}
10
3/17/2016
How to Debug
11