0% found this document useful (0 votes)
56 views53 pages

Compiler Design CS - 5

The document outlines the concepts of syntax analysis and parsing in compiler design, focusing on top-down parsing and LL(1) grammars. It explains the importance of context-free grammars and the role of parsers in analyzing programming language structures. Additionally, it discusses predictive parsing techniques and provides examples of parsing methods and their implementation.

Uploaded by

aryanvarshney782
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views53 pages

Compiler Design CS - 5

The document outlines the concepts of syntax analysis and parsing in compiler design, focusing on top-down parsing and LL(1) grammars. It explains the importance of context-free grammars and the role of parsers in analyzing programming language structures. Additionally, it discusses predictive parsing techniques and provides examples of parsing methods and their implementation.

Uploaded by

aryanvarshney782
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

COMPILER DESIGN

BITS Pilani
Pilani Campus
BITS Pilani
Pilani Campus

Contact Session - 5
M3 – Syntax Analysis
IMP Note to Self
IMP Note to Students
➢ It is important to know that just login to the session does not
guarantee the attendance.
➢ Once you join the session, continue till the end to consider
you as present in the class.
➢ IMPORTANTLY, you need to make the class more interactive
by responding to Professors queries in the session.
➢ Whenever Professor calls your number / name ,you need
to respond, otherwise it will be considered as ABSENT
Objectives

To Understand
▪ Top-down parsing
▪ LL(1) Grammars
▪ Implementing LL(1) Parser
▪ Examples on LL(1) Parser
▪ Parser Generator using YACC

BITS Pilani, Pilani Campus


Syntax Analysis and Parsing
1. Syn-tax
The way in which words are stringed together to form
phrases, clauses and sentences

2. Syntax analysis:
The task concerned with fitting a sequence of tokens
into a specified syntax.

3. Parsing:
To break a sentence down into its component parts of
speech with an explanation of the form, function, and
syntactical relationship of each part

BITS Pilani, Pilani Campus


Syntax Analysis
• The step two of Front end in Compilation
• Every programming Language has RULES that prescribe the
syntactic structure (i.e. the way in which words and phrases can
be organized to form sentences.)
• These rules can be formally specified using :

CONTEXT FREE GRAMMARS


( or GRAMMAR for Short)
A.k.a
BACKUS – NAUR FORM ( BNF)

BITS Pilani, Pilani Campus


Intro to Context Free Grammar
(CFG)
• Essential formalism for describing the structure of the programs in
a programming Language
• A recipe for constructing elements of a set of strings of symbols (
or tokens)
• Consists of a set production rules and a start symbol
• Each production rule:
– Defines a named syntactic construct using Two parts
1. An LHS (with a syntactic Construct) and
2. An RHS (showing the possible form of the construct)
– Connected by an Arrow symbol ( meaning “ is defined as” )

sentence → subject predicate ‘.’


BITS Pilani, Pilani Campus
Importance of the Grammar
Grammar offers significant advantages to both language
Designers and Compiler writers:
1. Gives precise, yet easy-to-understand, syntactic
specification of Programming Languages
2. Helps construct efficient parsers automatically ( not in
all cases – of course)
3. Provides a good structure to the language which in
turn helps generate correct object code
4. Makes language open ended easily amenable to add
additional constructs at a later date

BITS Pilani, Pilani Campus


Syntax Analysis
Problem Statement:
• To find a derivation sequence in a grammar G for the
input token stream
or
• To conclude that none exists

Solution
◼ Build parse tree for the string ( of tokens) based on
grammar rules
◼ The process is known as P A R S I N G
BITS Pilani, Pilani Campus
PARSING
Constructs the syntax tree for a given sequence of tokens
using grammar rules and productions such that:
1. The top node is labeled with the start symbol of the
grammar
2. Leaf nodes are labeled with terminals and inner
nodes with nonterminals
3. the children of the inner node labeled N correspond
to the members of an alternative of N, in the same
order as they occur in that alternative
4. The terminals labeling the leaf nodes correspond to
the sequence of tokens, in the same order they occur
in the input
BITS Pilani, Pilani Campus
The Role of a Parser
Lexical Rest of the
PARSER
analysis front end
Symbol Table
• The parser continues the process of translation and
validation started by the Lexical Analyzer:
1. Analyzing the phrase structure of the program,
2. Adding hierarchical (tree) structure to the flat stream
of tokens produced by the lexical Analyzer,
3. Outputting a data structure conveying the program's
syntax to subsequent compile phases, AND
4. Reporting errors when the program does not match
the syntactic structure of the source language
BITS Pilani, Pilani Campus
Parsing Methods
• Three Types of parsing methods in Vogue
1. Universal Parsing method
– Too inefficient to use in any practical compilers ( hence
not discussed any further)
– EX: Coocke–Younger–Kasami (CYK) algorithm
2. Top – Down Parsing
– Can be generated automatically or written manually
– Ex: : Left-to-Right –Top –Down Parser ( A.k.a. LL parser)
3. Bottom – Up parsing
– Can only be generated automatically
– Ex : Left-to-Right –Bottom-Up Parser ( A.k.a. LR Parser)
BITS Pilani, Pilani Campus
Top – Down & Bottom – Up
Methods
• While they are efficient;
• They can work only on restricted classes of Grammars,
( such as LL and LR Grammars )
BUT
• They are expressive enough to describe most syntactic
constructs in Programming Languages.
SO
• Care must be taken while defining the grammar for the
language to make sure that the grammar is unambiguous

BITS Pilani, Pilani Campus


TOP – DOWN Parsing
• An attempt to construct a parse tree for an input string from the root
and creating the nodes in PRE-ORDER (i.e. the top of the tree is
constructed before its nodes)
• Can also be viewed as an attempt to find a leftmost derivation for an
input string
• The way it works:
1. The process starts at root node say N
2. Repeat until the fringe of the parse tree matches the input string
1. Determine the correct alternative for N The key Step
2. Parser then proceeds to construct the left child of N
3. The process of determining the correct alternative for the
leftmost child continues till the left most child is a terminal

BITS Pilani, Pilani Campus


Top Down parsing example
String to be parsed :array [ num dotdot num] of integer
type

array [ simple ] of type

num dotdot num simple


Consider the Grammar:
type → simple | id | array [simple] of type
simple → integer integer
| char Token dotdot “..” is used to
| num dotdot num stress that character
sequence is treated as unit
BITS Pilani, Pilani Campus
Top Down Parsing – Another Case
• Consider the grammar : S → cAd A → ab | a
• String to be parsed : W = c a d s
◼Parse tree Construction would be:
c A d
1. Start with a single node S
2. Use first production to expand S
a b
3. Expand the nonterminal A using the
first alternative from rule 2 as we s
have a match for input token a
4. But b does not match d ; c A d
5. We have to BACKTRACK to step 3 and
try second alternative from rule 2
aBITS Pilani, Pilani Campus
Top Down Parsing - Observations
• In general,
1. The selection of a production for a nonterminal may
involve trial – and – error
2. We may have to try a production and backtrack to try
another production if the first is found to be unsuitable.
(A production is unsuitable ,if after using the production, we
can not complete the tree to match the input string )
• If we can make the correct choice by looking at just the
next input symbol, we can build a Predictive Parser that
can perform a top-down parse without backtracking

BITS Pilani, Pilani Campus


Top Down Parsing - Observations
• In general,
1. The selection of a production for a nonterminal may involve
trial – and – error
2. We may have to try a production and backtrack to try
another production if the first is found to be unsuitable.
(A production is unsuitable ,if after using the production, we
can not complete the tree to match the input string )
• If we can make the correct choice by looking at just the next
input symbol, we can build a Predictive Parser that can
perform a top-down parse without backtracking

BITS Pilani, Pilani Campus


Predictive Parsing

• Most common technique used in parsers (Particularly


TRUE in case of Parsers written manually)
• Use grammars that are carefully written to eliminate
left recursion
• Further, if many alternatives exist for a nonterminal,
the grammar is so defined that the input token will
uniquely define the one and only one alternative and
that will lead to correct parsing or Error.
• No question of backtracking and trying another
alternative

BITS Pilani, Pilani Campus


Predictive Parsing Example
Consider the grammar: stmt → if expr then stmt else stmt
| while expr do stmt
| begin stmt_list end
A parser for this grammar can be
written with the following simple switch(gettoken())
{
structure: case if:
….
Based only on the first token, the parser break;
knows which rule to use to derive a case while:
….
statement, because all the three break;
outcomes are unique even at the first case begin:
….
letter. break;
default:
Therefore this is called a reject input;
Predictive Parser. }
BITS Pilani, Pilani Campus
Parsing Table
• Represents a Grammar as
• A two dimensional array M [ A,α ], where: Grammar:
– A is the nonterminal and E → TE’
– α is the input symbol E’ → +TE’ | 
T → FT’
• Used in Parser as the reference table to
T’ → FT’ | 
decide the possible values ( thereby the F → ( E ) | id
choice of production to be used)

NON- INPUT SYMBOL


TERMINAL id + * ( ) $
E E → TE’ E → TE’
Parsing E’ E’ → +TE’ E’ →  E’ → 
T T → FT’ T → FT’
Table: T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E)
BITS Pilani, Pilani Campus
A Table Driven Predictive
Parser Program
• An input Buffer (containing string to be parsed with $ in the
end)
• A stack ( containing a sequence of grammar symbols with $ at
the bottom)
• A Parsing table and id + id  id $
INPUT:
• An Output stream OUTPUT:

Predictive Parsing E
STACK: E
T
E’
$ Program T E’
$

NON- INPUT SYMBOL


TERMINAL id + * ( ) $
PARSING E E → TE’ E → TE’
E’ E’ → +TE’ E’ →  E’ → 
TABLE: T T → FT’ T → FT’
T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E)
BITS Pilani, Pilani Campus
A Predictive Parser
▪ The Working of the Table driven Predictive Parser

INPUT: id + id  id $ OUTPUT:
E
STACK: T E’
Predictive Parsing
TE Program
$
E’
$
NON- INPUT SYMBOL
NON- INPUT SYMBOL
TERMINAL
TERMINAL id id + +* (* ) ( $ ) $
PARSING E E
E → TE’ E → TE’ E → TE’ E → TE’
E’ E’ E’ → +TE’E’ → +TE’ E’ →  E’ →E’ →  E’ → 
TABLE: T T → FT’ T → FT’
T T → FT’ T → FT’
T’ T’→  T’ → *FT’ T’ →  T’ → 
T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E)
F F → id F → (E)
BITS Pilani, Pilani Campus
A Predictive Parser
▪ The Working of the Table driven Predictive Parser

INPUT: id + id  id $ OUTPUT:
E
STACK: T E’
Predictive Parsing
F
T Program F T’
T’
E’
E’
$
$ NON- INPUT SYMBOL
NON- INPUT SYMBOL
TERMINAL
TERMINAL id id + + * * ( ( ) )$ $
PARSING EE E→E→TE’TE’ E → TE’
E → TE’
E’ E’ E’ → → +TE’
E’+TE’ E’ →  E’E’→→ E’ → 
TABLE: TT T→T→FT’ FT’ T → FT’
T → FT’
T’ T’→  T’ → *FT’ T’ →  T’ → 
T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E)
F F → id F → (E)
BITS Pilani, Pilani Campus
A Predictive Parser
▪ The Working of the Table driven Predictive Parser
Action when Top(Stack) = input  $ : Pop stack, advance input.
INPUT: id + id  id $ OUTPUT:
E
STACK: T E’
Predictive Parsing
id
F Program F T’
T’
E’ id
$ NON- INPUT SYMBOL
NON- INPUT SYMBOL
TERMINAL
TERMINAL id id + + * * ( ( ) )$ $
PARSING EE E→E→TE’TE’ E → TE’
E → TE’
E’ E’ E’ → → +TE’
E’+TE’ E’ →  E’E’→→ E’ → 
TABLE: TT T→T→FT’ FT’ T → FT’
T → FT’
T’ T’→  T’ → *FT’ T’ →  T’ → 
T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E)
F F → id F → (E)
BITS Pilani, Pilani Campus
A Predictive Parser
▪ The Working of the Table driven Predictive Parser
Action when Top(Stack) = ε : Pop stack
INPUT: id + id  id $ OUTPUT:
E
STACK: T E’
Predictive Parsing
ε
T’ Program F T’
E’
$ id ε
NON- INPUT SYMBOL
NON- INPUT SYMBOL
TERMINAL
TERMINAL id id + + * * ( ( ) )$ $
PARSING EE E→E→TE’TE’ E → TE’
E → TE’
E’ E’ E’ → → +TE’
E’+TE’ E’ →  E’E’→→ E’ → 
TABLE: TT T→T→FT’ FT’ T → FT’
T → FT’
T’ T’→  T’ → *FT’ T’ →  T’ → 
T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E)
F F → id F → (E)
BITS Pilani, Pilani Campus
A Predictive Parser
▪ The Working of the Table driven Predictive Parser
Action when Top(Stack) = input  $ : Pop stack, advance input.
INPUT: id + id  id $ OUTPUT:
E
STACK: T E’
Predictive Parsing
E’
+ F T’ + T E’
Program
T$
E’ id ε
$ NON- INPUT SYMBOL
NON- INPUT SYMBOL
TERMINAL
TERMINAL id id + + * * ( ( ) )$ $
PARSING EE E→E→TE’TE’ E → TE’
E → TE’
E’ E’ E’ → → +TE’
E’+TE’ E’ →  E’E’→→ E’ → 
TABLE: TT T→T→FT’ FT’ T → FT’
T → FT’
T’ T’→  T’ → *FT’ T’ →  T’ → 
T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E)
F F → id F → (E)
BITS Pilani, Pilani Campus
A Predictive Parser

▪ The Working of the Table driven Predictive Parser


INPUT: id + id  id $ OUTPUT:
E
STACK: T E’
Predictive Parsing
T F T’ + T E’
E’ Program
$ id ε
NON- INPUT SYMBOL
NON- INPUT SYMBOL
TERMINAL
TERMINAL id id + + * * ( ( ) )$ $
PARSING EE E→E→TE’TE’ E → TE’
E → TE’
E’ E’ E’ → → +TE’
E’+TE’ E’ →  E’E’→→ E’ → 
TABLE: TT T→T→FT’ FT’ T → FT’
T → FT’
T’ T’→  T’ → *FT’ T’ →  T’ → 
T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E)
F F → id F → (E)
BITS Pilani, Pilani Campus
A Predictive Parser
The predictive parser proceeds in this fashion emitting the
following productions:
T → FT’ E
T E’
F → id
F T’ + T E’
T’ →  FT’
id  F T’

F → id
id  F T’
T’ → 
id 
E’ → 

When Top(Stack) = input = $ the parser halts & accepts the input
string – ( id + id * id ) BITS Pilani, Pilani Campus
Algorithm for Predictive parser
• The program execution is controlled by TWO inputs
– The input symbol a and the symbol on the top of the stack
X
• There are THREE possibilities for the parser
– If X = a = $ : halt & announce the successful completion of
parsing
– If X = a ≠ $ : Pop X off the stack and advance the input
pointer to next input symbol
– If X is a nonterminal : Consult entry M [ X, a ] in the Parsing
table M and replace X on top of the stack with the RHS of
the production
• If M [ X, a ] is error call error routine BITS Pilani, Pilani Campus
Algorithm for Predictive parser
• The program execution is controlled by TWO inputs
– The input symbol a and the symbol on the top of the stack X
• There are THREE possibilities for the parser
– If X = a = $ : halt & announce the successful completion of
parsing
– If X = a ≠ $ : Pop X off the stack and advance the input pointer
to next input symbol
– If X is a nonterminal : Consult entry M [ X, a ] in the Parsing
table M and replace X on top of the stack with the RHS of the
production
• If M [ X, a ] is error call error routine

BITS Pilani, Pilani Campus


FIRST & FOLLOW
• The two functions represent a set of terminal symbols,that aid us
in constructing Predictive parser by helping us fill the Parsing
Table with valid entries
• Set of terminal symbols yielded by FOLLOW function can also be
used in error recovery
• FIRST – if α is the string of grammar symbols then FIRST (α) is the
set of terminals that begin the strings derived from α
(If α * >ε , then ε is also in FIRST (α))
• FOLLOW (A) – the set of terminals a that can appear immediately
to the right of A such that there exists a derivation of the form
S *> α A a β for some α and β

BITS Pilani, Pilani Campus


FIRST & FOLLOW (Contd.)

• The set of terminal symbols ( including ε )that can appear


at the far left of any parse tree derived from a particular
nonterminal is the FIRST set of that nonterminal
• The set of terminal symbols ( including ε ) That can follow
a nonterminal in some derivation or the other, is called
the FOLLOW set of that nonterminal
• A set of rules are followed to compute the FIRST and
FOLLOW set
• These sets will be used in creating Parsing table

BITS Pilani, Pilani Campus


Rules to Create FIRST
FIRST rules: GRAMMAR:
1. If X is a terminal, FIRST(X) = {X}
2. If X →  , then   FIRST(X)
E → TE’
3. If X → aABC , then a  FIRST(X)
E’ → +TE’ | 
T → FT’
4. If X →ABCD, then FIRST (A)  FIRST (X).
4a. Further, If A →  , in the above production, then
T’ → FT’ | 
FIRST (B)  FIRST (X)........ [& so on recursively]
F → ( E ) | id

FIRST(id) = {id} FIRST(E’) = {}{+, }


FIRST() = {} FIRST(T’) = {}{, }
SETS: FIRST(+) = {+} FIRST(F) = {(, id}
FIRST(() = {(} FIRST(T) = FIRST(F) = {(, id}
FIRST()) = {)} FIRST(E) = FIRST(T) = {(, id}
BITS Pilani, Pilani Campus
FIRST(E’) = {+, }
FIRST(T’) = { , } Rules to Create FOLLOW
FIRST(F) = {(, id} FOLLOW rules:
FIRST(T) = {(, id}
FIRST(E) = {(, id} 1. If S is the start symbol, then $  FOLLOW(S)

GRAMMAR: 2. If there is a production A → B, then,


E → TE’ EVERYTHING in FIRST() except  is placed
E’ → +TE’ |  in FOLLOW(B)
T → FT’
3. If there is a production A → B then,
T’ → FT’ | 
EVERYTHING in FOLLOW(A) is in FOLLOW(B)
F → ( E ) | id
SETS:
FOLLOW(E) = {$} { ), $} 3a. If there is a production A → B where
FOLLOW(E’) = { ), $} FIRST() contains  ( i.e.  
*  ) then,

FOLLOW(T) = { ), $} {+, ), $} EVERYTHING in FOLLOW(A) is in FOLLOW(B)


FOLLOW(T’) = { +, ), $}
FOLLOW(F) = {+, ), $} A and B are non-terminals,
{+, , ), $}  and  are strings of grammar symbols
BITS Pilani, Pilani Campus
FOLLOW
Rules to Build Parse Table SETS:
E → TE’ FIRST(E’) = {+, } FOLLOW(E) = {), $}
FIRST FIRST(T’) = { , }
GRAMMAR: E’ → +TE’ |  FOLLOW(E’) = { ), $}
T → FT’ SETS: FIRST(F) = {(, id} FOLLOW(T) = {+, ), $}
T’ → FT’ |  FIRST(T) = {(, id}
FOLLOW(T’) = {+, ), $}
F → ( E ) | id FIRST(E) = {(, id}
Rules FOLLOW(F) = {+, , ), $}

1. If A → , :if a  FIRST(), add A →  to M[A, a]


2. If A → , if   FIRST(), add A →  to M[A, b] for each terminal
b  FOLLOW(A),
3.If A → , if   FIRST(), and $  FOLLOW(A), A →  to M[A, $]
NON- INPUT SYMBOL
TERMINAL id + * ( ) $
PARSING E E → TE’ E → TE’
E’ E’ → +TE’ E’ →  E’ → 
TABLE: T T → FT’ T → FT’
T’ T’→  T’ → *FT’ T’ →  T’ → 
F F → id F → (E) BITS Pilani, Pilani Campus
Predictive Parsing
• A top down method of parsing (Recursive descent parsing )
in which a set of procedures are executed recursively to
process the input.
• The speciality of predictive parsing is that :
The look ahead symbol unambiguously determines the
procedure selected for each nonterminal
(No Prediction in fact !!!)
• Hence:
The sequence of procedures called implicitly defines a
parse tree for the input.

BITS Pilani, Pilani Campus


procedure match (c : token);
{
if ( lookahead ==c) then lookahead := nexttoken;
else error;
}
procedure type;
{if ( lookahead is [ integer, char, num ] ) then simple;
else if (lookahead == ‘ ‘ ) { match (‘‘); match (id); }
else if ( lookahead == array )
then { match (array); match(‘[‘); simple;
match(‘]’); match(of); type; }
else error; }
………. Contd.
BITS Pilani, Pilani Campus
procedure simple;
{
if ( lookahead == integer ) match (integer);
else if ( lookahead == char ) match (char );
else if ( lookahead == num)
{ match (num ); match (dotdot); match( num
);}
else error;
}
BITS Pilani, Pilani Campus
Error recovery in Predictive
parsing
• Error is encountered by Predictive Parser when:
– The terminal on the stack does not match the next input
symbol
– The nonterminal A is on the top of the stack, A is the input
symbol and the parsing table is empty for entry M [A, a]
• Two methods used for recovery
1. Panic – Mode error recovery
– Skip symbols on the input until a token in a selected set of
synchronizing tokens appears
– Effectiveness depends on set of synchronizing tokens chosen
2. Phased – level recovery
– Fill empty slots of parsing table with pointers to error
Routines
BITS Pilani, Pilani Campus
LL (1) Parsing
• Grammars whose predictive parsing tables contain
no multiple entries are called LL(1).
• LL(1)
● Left-to-right parse of input string
● Leftmost derivation of grammar
● 1 symbol look ahead (we know only what the next
token is)
• LL (k) : we know what the next k tokens are
• Every LL(1) grammar is an LL(2) grammar and so on
BITS Pilani, Pilani Campus
More Examples on LL(1)

Example2:
S->AaAb / BbBa First and Follow
A->ε Pdn First Follow
S->AaAb /BbBa a,b $
B-> ε A->ε ε a,b
B-> ε ε a,b

LL(1) Parsing Table :


a b $
S S->AaAb S->BbBa
A A->ε A->ε
B B-> ε B-> ε

*Whether the above grammar can be used for LL(1) Parsing?


BITS Pilani, Pilani Campus
More Examples on LL(1)

Example3: Example5:
S->A/a S->aABb
A->a A->c / ε
B->d / ε
Example4: Example6:
S->aB / ε S->aSa / ε
B->bC / ε A->c / ε
C->cS / ε
Write the First and Follow and also the parsing table for
the above examples to check the suitability of the
grammar for LL(1) BITS Pilani, Pilani Campus
Parser generators

Yet Another Compiler Compiler ( YACC ).

Yacc specification Yacc y.tab.c


translate.y compiler

C
y.tab.c a.out
compiler

input a.out output

BITS Pilani, Pilani Campus


Sample program for Parser using
Yacc
Lex Program: ( ar.l)
%{
/* Definition section */
#include<stdio.h>
#include "y.tab.h"
extern int yylval;
%}
/* Rule Section */
%%
[0-9]+ {
yylval=atoi(yytext);
return NUMBER;

}
[\t] ; [\n] return 0;
return yytext[0];
%%
int yywrap()
{ return 1; }
BITS Pilani, Pilani Campus
Sample program for Parser using
Yacc
Yacc Program: ( prog.y)
%{
/* Definition section */
#include<stdio.h>
int flag=0;
%}
%token NUMBER
%left '+' '-'
%left '*' '/' '%'
%left '(' ')'

BITS Pilani, Pilani Campus


Sample program for Parser using
Yacc
/* Rule Section */
%%
ArithmeticExpression: E{
printf("\nResult=%d\n", $$);
return 0;
};
E:E'+'E {$$=$1+$3;}
|E'-'E {$$=$1-$3;}
|E'*'E {$$=$1*$3;}
|E'/'E {$$=$1/$3;}
|E'%'E {$$=$1%$3;}
|'('E')' {$$=$2;}
| NUMBER {$$=$1;}
;
%% BITS Pilani, Pilani Campus
Sample program for Parser using
Yacc
//driver code
void main()
{
printf("\nEnter Any Arithmetic Expression which have operations
Addition,Subtraction, Multiplication, Division, Modulus and
Round brackets:\n");
yyparse();
if(flag==0)
printf("\nEntered arithmetic expression is Valid\n\n");
}
void yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
flag=1;
} BITS Pilani, Pilani Campus
Sample program for Parser using
Yacc
Compile and Run:
We have to compile both lex and yacc files as given below:
lex ar.l
yacc -d prog.y // this produces y.tab.h,y.tab.c which should be
used in compilation as shown below
cc lex.yy.c y.tab.c -ll
./a.out
Enter Any Arithmetic Expression which have operations
Addition,Subtraction, Multiplication, Division, Modulus and
Round brackets:
1+5
Result=6
Entered arithmetic expression is Valid

BITS Pilani, Pilani Campus


In Summary

• LL Parsing ( A.k.a Recursive Descent parsing )


• LL stands for Left-to-right scan of input & Leftmost
derivation
• Start by expanding the start symbol and then expand out
nonterminals based on the input, building the parse tree
from the top down
• Works only on grammars with some restrictions. ( LL
Grammars with no left recursion and the first token
uniquely identifies the Production)
• Can be easily built manually
BITS Pilani, Pilani Campus
Click to edit Master title style

BITS Pilani, Pilani Campus


Click to edit Master title style

Thank you

Slide 53 BITS Pilani, Pilani Campus

You might also like