You are on page 1of 10

PARSER GENERATOR

YACC

YACC( Yet Another Compiler-Compiler)


YACC is available as a command in
UNIX system
Used to implement hundreds of
compilers

Creating an input/output translator


with 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)

3. By compiling y.tab.c we obtain


a.out i.e. translation specified by
Yacc program
YACC source program has 3 parts:
A.) declaration
B.) translation rules
C.) supporting 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 }

productionn { semantic actionn }


6

Supporting C-routines:
Contains error recovery routines
Produces token and attribute values

Writing a Grammar in Yacc


Productions in Yacc are of the form
Nonterminal : tokens/nonterminals
{ action }
| tokens/nonterminals { action }

;
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

Example: PREPARE A YACC SOURCE


PROGRAM
Question: Build a calculator using
following grammar:
E E+T | T
TT*F |F
F(E) | digit
Token digit is single digit between
0 and 9

Solution:

Also results in definition of

%{ #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

You might also like