Professional Documents
Culture Documents
YACC
Yacc
specification
yacc.y
Yacc or Bison
compiler
y.tab.c
C
compiler
a.out
a.out
output
stream
input
stream
y.tab.c
YACC
1. First, a file translate.y (containing
Yacc specification of translator) is
prepared.
2. UNIX system command
Yacc translate.y
transforms the file translate.y into
C Program called y.tab.c
( y.tab.c is representation of LALR
parser written in C and contains
other C Routines)
Yacc Specification
A yacc specification consists of three parts:
Yacc declarations, and C declarations within
%{ %}
%%
translation rules
%%
user-defined auxiliary procedures
The translation rules are productions with actions:
production1 { semantic action1 }
production2 { semantic action2 }
Supporting C-routines:
Contains error recovery routines
Produces token and attribute values
;
Tokens that are single characters can be
used directly within productions, e.g. +
Named tokens must be declared first in
the declaration part using
%token TokenName
8
Solution:
%{ #include <ctype.h> %}
#define DIGIT xxx
%token DIGIT
%%
line
: expr \n
{ printf(%d\n, $1); }
;
expr
: expr + term
{ $$ = $1 + $3; }
| term
{ $$ = $1; }
;
term
: term * factor { $$ = $1 * $3; }
| factor
{ $$ = $1; }
;
factor : ( expr )
{ $$ = $2; }
| DIGIT
{ $$ = $1; }
Attribute of factor
;
Attribute of
%%
int yylex()
term (parent)
Attribute of token
{ int c = getchar();
(stored in yylval)
if (isdigit(c))
{ yylval = c-0;
Example of a very crude lexical
return DIGIT;analyzer invoked by the parser
}
return c;
}
(child)
10