Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

YACC (Parser Generator)

Muhammad Usman Azhar Danial Hussain BCSF09A025 BCSF09A027

Yacc: What is it?


The computer program yacc is a parser generator developed by Stephen C. Johnson at AT&T for the Unix operating system. The name is an acronym for Yet Another Compiler Compiler . Yacc: A tool for automatically generating a parser given a grammar written in a yacc specification (.y file). A grammar specifies a set of production rules, which define a language. A production rule specifies a sequence of symbols, sentences, which are legal in the language.

Structure of yacc File


Definition section

declarations of tokens
type of values used on parser stack Rules section

list of grammar rules with semantic routines


User code

The Production Rules Section

%%
production : symbol1 symbol2 { action } | symbol3 symbol4 { action }

|
production: symbol1 symbol2 { action }

%%

An example

%%
statement : expression { printf ( = %g\n, $1); } expression : expression + expression { $$ = $1 + $3; } | expression - expression { $$ = $1 - $3; }

| NUMBER { $$ = $1; }
%%
statement expression expression expression

According these two productions, 5 + 4 3 + 2 is parsed into:


number

expression
number

expression
expression number expression number + 2

Precedence and Associativity


%right =' %left '-' '+' %left '*' '/' %right '^'

Defining Values
expr : expr '+' term | term ; term : term '*' factor | factor ; factor : '(' expr ')' | ID | NUM ; { $$ = $1 + $3; } { $$ = $1; } { $$ = $1 * $3; } { $$ = $1; } { $$ = $2; }

Defining Values

$1
expr : expr '+' term | term ; term : term '*' factor | factor ; factor : '(' expr ')' | ID | NUM ; { $$ = $1 + $3; } { $$ = $1; } { $$ = $1 * $3; } { $$ = $1; } { $$ = $2; }

Defining Values
expr : expr '+' term | term ; term : term '*' factor | factor ; factor : '(' expr ')' | ID | NUM ; { $$ = $1 + $3; } { $$ = $1; } { $$ = $1 * $3; } { $$ = $1; } { $$ = $2; }

$2

Defining Values
expr : expr '+' term | term ; term : term '*' factor | factor ; factor : '(' expr ')' | ID | NUM ; { $$ = $1 + $3; } { $$ = $1; } { $$ = $1 * $3; } { $$ = $1; } { $$ = $2; }

$3

Ambiguous Grammars
A Grammar that produces more than one Parse Tree for the same sentences or the Production rules in a grammar is said to be ambiguous. e.g. consider a simple mathematical expression E->E*E This can have two Parse tree according to associativity of the operator '* E E / \ / \ * E E * / \ / \ E E E E Yacc also tell us that the given language is ambiguous or not.

You might also like