Download presentation
Presentation is loading. Please wait.
1
Introduction to YACC Panfeng Xue pxx101020@utdallas.edu
2
LEX and YACC LEX – Split the source file into tokens YACC – Find the hierarchical structure of the program
3
LEX and YACC
4
Architecture
5
YACC Specifications Similar structure to LEX – Declaration Section – Translation Rules – Supporting C/C++ code Declaration % Translation rules % Supporting C/C++ code
6
YACC Declaration Declaration Section – C/C++ Code – YACC definition %token %start Others %{ #include #define MAXSTRINGLENGTH 128 int TotalParaNo=0; …. %} %token TOK_constants TOK_functions
7
YACC Specifications Similar structure to LEX – Declaration Section – Translation Rules – Supporting C/C++ code Declaration % Translation rules % Supporting C/C++ code
8
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. statements: | statement statements { printf(" statements founded”); } ;
9
YACC Rules Prog -> SS SS -> S SS | ε % programs: statements ; statements: /*empty*/ | statement statements ;
10
Actions Actions: associated with a rule are entered in braces. Similar with the LEX statements: | statement statements { printf(" statements founded”); } ;
11
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) Default action: – $$ = $1 statement: identifier '+' identifier { $$ = $1 + $3; } | identifier '-' identifier { $$ = $1 - $3; } ;
12
Actions Inherited Attributes – { fn id PP } – How to transfer the value of fn and id to PP? Using the stack information $1 designates the first term on the right-hand side. We can index backwards, using $0, $-1, and so on.
13
Symbol Types Declaring Symbol Types %union{ int dval; char *sval; }% …………………………… %token NUMBER %token IDENTIFIER %type statement
14
YACC Specifications Similar structure to LEX – Declaration Section – Translation Rules – Supporting C/C++ code Declaration % Translation rules % Supporting C/C++ code
15
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
16
Feedback Feed Information back to the LEX – YACC – Lex %{ int top_layer = 1; }% …………………………… % Program: statement { top_layer = 0;} ; %{ extern int top_layer; }% ……………………………
17
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
18
How to Debug Add the following into your YACC file Add –-debug into your makefile % extern int yy_flex_debug; int main(void) { yy_flex_debug = 1; yyparse(); }
19
How to Debug
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.