SlideShare a Scribd company logo
MATRUSRI ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
SUBJECT NAME: Compiler Design
FACULTY NAME:
MATRUSRI
ENGINEERING COLLEGE
Compiler Design
COURSE OBJECTIVES:
➢To introduce the steps in language translation pipeline and runtime data structures used
in translation
➢ To learn about Scanning (lexical analysis) process using regular expressions and use
of LEX to generate scanner
➢ To introduce different Parsing strategies including top-down (e.g., recursive descent,
Early parsing, or LL) and bottom-up (e.g., backtracking or LR) techniques
➢ Describe semantic analyses using an attribute grammar
➢ To learn how to build symbol tables and generate intermediate code.
➢ To introduce techniques of program analysis and code optimization
MATRUSRI
ENGINEERING COLLEGE
22-06-2023 Compiler Construction 2
COURSE OUTCOMES:
After completing this course, the student will be able to
1. Create lexical rules and grammars for a given language
2. Generate scanners and parsers from declarative specifications.
3. Describe an abstract syntax tree for a small language.
4. Use program analysis techniques for code optimization
5. Develop the compiler for a subset of a given language
Unit-III
Syntax-Directed Translation: Syntax-Directed Definitions,
Evaluation Orders for SDD’s, Applications of Syntax-Directed
Translation.
Symbol Table: Structure, Operations, Implementation and
Management.
MATRUSRI
ENGINEERING COLLEGE
Outline
• Syntax Directed Definitions
• Evaluation Orders of SDD’s
• Syntax Directed Translation Schemes
• Applications of Syntax Directed Translation
• Symbol Table: Structure, Operations,
• Implementation and Management.
MATRUSRI
ENGINEERING COLLEGE
Introduction
Syntax-directed translation is done by attaching rules or program
fragments to productions in a grammar
• A syntax directed definition specifies the values of attributes by
associating semantic rules with the grammar productions.
• Concepts related to syntax-directed translation are
– Attributes
– Translation schemes
• An attribute is any quantity associated with a programming
construct.
– Data types of expression, number of instructions, location of
the instruction, non-terminals and terminal symbols.
• A translation scheme is a notation for attaching program fragments
to the productions of a grammar
MATRUSRI
ENGINEERING COLLEGE
Example
Production Semantic Rule
E->E1+T E.code=E1.code + T.code
MATRUSRI
ENGINEERING COLLEGE
If X is a symbol and a is one of its attributes, then we write X.a to
denote the value of a at a particular parse-tree node labelled X.
This production has two non-terminals, E1 and T. E1 and T have a
string-valued attribute code. The semantic rule species that the string
E:code is formed by concatenating E1:code, T:code,
and the character ‘+’.
We may alternatively insert the semantic actions inside the grammar.
E -> E1+T {print ‘+’}
By convention, semantic actions are enclosed within curly braces.
Syntax Directed Definitions
A SDD is a context free grammar with attributes and rules
• A syntax directed definition specifies the values of attributes
by associating semantic rules with the grammar productions.
• Attributes are associated with grammar symbols and rules
with productions.
• Attributes may be of many kinds: numbers, types, table
references, strings, etc.
• Rules describe how the attributes are computed at those
nodes of the parse tree.
Definition: SDD is a generalization of CFG in which each
production rule X->α is associated with a set of semantic rules
of the form a:=f(b1, b2,……bk), where a is an attribute
obtained from the function f.
MATRUSRI
ENGINEERING COLLEGE
Synthesized and Inherited
Synthesized attributes
– A synthesized attribute for a nonterminal A at a parse-tree node N is
defined by a semantic rule associated with the production at N.
– Note that the production must have A as its head.
– A synthesized attribute at node N is defined only in terms of attribute
values of children of N and at N itself.
Inherited attributes
– An inherited attribute for a nonterminal B at a parse-tree node N is
defined by a semantic rule associated with the production at the
parent of N.
– Note that the production must have B as a symbol in its body.
– An inherited attribute at node N is defined only in terms of attribute
values at N’s parent, N itself and N’s siblings.
• Terminals can have synthesized attributes, but not inherited attributes.
• Attributes for terminals have lexical values that are supplied by the
lexical analyzer, there are no semantic rules in the SDD itself for
computing the value of an attribute for a terminal.
MATRUSRI
ENGINEERING COLLEGE
Example
An inherited attribute at node N cannot be defined in terms of
attribute values at the children of node N, but a synthesized attribute
at node N can be defined in terms of inherited attribute values at node
N itself.
PRODUCTION SEMANTIC RULES
A -> B A.s := B.i;
B.i := A.s + 1
MATRUSRI
ENGINEERING COLLEGE
A and B, have s and i as attributes.
Here s is synthesized and i is
inherited, because s is evaluated from
its children and i is evaluated from its
parent
S-attributed SDD
An SDD that involves only synthesized attributes is called S-
attributed.
In an S-attributed SDD, each rule computes an attribute for the
nonterminal at the head of a production from attributes taken from
the body of the production.
An S-attributed SDD can be implemented naturally in conjunction
with an LR parser.
An S-attributed definition, is suitable for use during bottom-up
parsing.
An SDD without side effects is sometimes called an attribute
grammar. The rules in an attribute grammar define the value of an
attribute purely in terms of the values of other attributes and
constants.
To visualize the translation specified by an SDD, it helps to work
with parse Trees.
A parse tree, showing the value(s) of its attribute(s) is called an
annotated parse tree.
MATRUSRI
ENGINEERING COLLEGE
Example of S-attributed SDD
Production
1) L -> E n
2) E -> E1 + T
3) E -> T
4) T -> T1 * F
5) T -> F
6) F -> (E)
7) F -> digit
Semantic Rules
L.val = E.val
E.val = E1.val + T.val
E.val = T.val
T.val = T1.val * F.val
T.val = F.val
F.val = E.val
F.val = digit.lexval
MATRUSRI
ENGINEERING COLLEGE
• In the above SDD, each of the non-terminals has a single synthesized attribute, called val.
• Terminal digit has a synthesized attribute lexval, which is an integer value returned by the
lexical analyzer.
• For production 1, L -> E n, sets L.val to E.val, which we shall see is the numerical value of
the entire expression.
• For production 2, E -> E1 + T, also has one rule, which computes the val attribute for the
head E as the sum of the values at E1 and T. At any parse tree node N labeled E, the value
of val for E is the sum of the values of val at the children of node N labeled E and T.
Example of S-attributed SDD MATRUSRI
ENGINEERING COLLEGE
Annotated parse tree for 3 * 5 + 4
L-attributed SDD
If an SDD uses both synthesized attributes and inherited attributes
with a restriction that inherited attribute can inherit values from left
siblings only, it is called as L-attributed SDT.
• Attributes in L-attributed SDTs are evaluated by depth-first and
left-to-right parsing manner.
• Semantic actions are placed anywhere in RHS.
L-attributed, is suitable for use during top-down parsing.
Example:
A -> XYZ {Y.S = A.S, Y.S = X.S, Y.S = Z.S}
is not an L-attributed grammar since Y.S = A.S and Y.S = X.S are
allowed but Y.S = Z.S violates the L-attributed SDT definition as
attributed is inheriting the value from its right sibling.
Note – If a definition is S-attributed, then it is also L-attributed but
NOT vice-versa.
MATRUSRI
ENGINEERING COLLEGE
L-Attributed definitions MATRUSRI
ENGINEERING COLLEGE
Production Semantic Rules
T —> FT’ T’.inh = F.val
T’ —> *FT1’ T’1.inh =T’.inh x F.val
In production 1, the inherited attribute T’ is computed
from the value of F which is to its left. In production 2,
the inherited attributed Tl’ is computed from
T’. inh associated with its head and the value of F which
appears to its left in the production. i.e., for computing
inherited attribute, it must either use from the
above or from the left information of SDD.
SDD-Inherited attributes MATRUSRI
ENGINEERING COLLEGE
Production Semantic Rules
D —>TL L.inh = T.type
T —> int T.type =integer
T —> float T.type = float
L —> L1, id L1.inh = L.inh
addType (id.entry, Linh)
L —> id addType (id.entry, L.inh)
SDD-Inherited attributes MATRUSRI
ENGINEERING COLLEGE
Dependency graph for a declaration float id1, id2, id3
L-Attributed definitions
• A SDD is L-Attributed if the edges in dependency
graph goes from Left to Right but not from Right to
Left.
• More precisely, each attribute must be either
– Synthesized
– Inherited,
• but if there is a production A->X1X2…Xn and there is an
inherited attribute Xi.a computed by a rule associated with
this production, then the rule may only use:
– Inherited attributes associated with the head A
– Either inherited or synthesized attributes associated with the
occurrences of symbols X1,X2,…,Xi-1 located to the left of Xi
– Inherited or synthesized attributes associated with this occurrence of
Xi itself, but in such a way that there is no cycle in the graph
MATRUSRI
ENGINEERING COLLEGE
Syntax tree for L-attributed definition
Production
1) E -> TE’
2) E’ -> + TE1’
3) E’ -> -TE1’
4) E’ -> 
5) T -> (E)
6) T -> id
7) T -> num
Semantic Rules
E.node=E’.syn
E’.inh=T.node
E1’.inh=new node(‘+’, E’.inh,T.node)
E’.syn=E1’.syn
E1’.inh=new node(‘+’, E’.inh,T.node)
E’.syn=E1’.syn
E’.syn = E’.inh
T.node = E.node
T.node=new Leaf(id,id.entry)
T.node = new Leaf(num,num.val)
MATRUSRI
ENGINEERING COLLEGE
Evaluation orders for SDD’s
Dependency graphs are a useful tool for determining an
evaluation order for the attribute instances in parse tree.
• Annotated parse tree shows the values of attributes, a
dependency graph helps us determine how those values can
be computed.
• A dependency graph depicts the flow of information among
the attribute instances in a particular parse tree.
• An edge from one attribute instance to another means that the
value of the first is needed to compute the second.
• Edges express constraints implied by the semantic rules.
Dependency Graph : Directed graph indicating interdependencies
among the synthesized and inherited attributes of various nodes in a
parse tree.
MATRUSRI
ENGINEERING COLLEGE
Dependency Graph
Dependency graph
– For each parse tree node X, the dependency graph has a node
for each attribute associated with the node X.
– For a production p, if a semantic rule defines the value of
synthesized attribute A.b in terms of the value of X.c then the
dependency graph has an edge from X.c to A.b
– For a production p, if a semantic rule defines the value of
inherited attribute B.c in terms of the value of X.a then the
dependency graph has an edge from X.a to B.c
MATRUSRI
ENGINEERING COLLEGE
Ordering the evaluation of
attributes
• If dependency graph has an edge from M to N then M
must be evaluated before the attribute of N
• Thus, the only allowable orders of evaluation are those
sequence of nodes N1,N2,…,Nk such that if there is an
edge from Ni to Nj then i<j
• Such an ordering is called a topological sort of a graph.
• If there is any cycle in the graph, then there are no
topological sorts; that is, there is no way to evaluate the
SDD on this parse tree.
MATRUSRI
ENGINEERING COLLEGE
S-Attributed SDD Example MATRUSRI
ENGINEERING COLLEGE
Evaluation Order: Semantic rules in a S-Attributed Definition can be
evaluated by a bottom-up, or PostOrder, traversal of the parse-tree.
Example. The annotated parse-tree for the input 3*5+4n is:
L-Attributed SDD Example
Production
1) T -> FT’
2) T’ -> *FT’1
3) T’ -> ε
1) F -> digit
Semantic Rules
T’.inh = F.val
T.val = T’.syn
T’1.inh = T’.inh*F.val
T’.syn = T’1.syn
T’.syn = T’.inh
F.val = F.val = digit.lexval
MATRUSRI
ENGINEERING COLLEGE
Annotated parse
tree for expression:
3 * 5
MATRUSRI
ENGINEERING COLLEGE
Dependency Graph for the expression: 3 * 5
• Nodes 1 and 2 represent the attribute lexval associated with the two leaves labeled
digit.
• Nodes 3 and 4 represent the attribute val associated with the two nodes labeled F. The
edges to node 3 from 1 and to node 4 from 2 result from the semantic rule that
defines F.val in terms of digit.lexval. In fact, F.val equals digit.lexval, but the edge
represents dependence, not equality.
• Nodes 5 and 6 represent the inherited attribute T’.inh associated with each of the
occurrences of nonterminal T’.
• Nodes 7 and 8 represent the synthesized attribute syn associated with the occurrences
of T’.
Order: 1,3,5,2,4,6,7,8,9
Syntax Directed Translation (SDT)
An SDT is a Context Free grammar with program fragments
embedded within production bodies
• Those program fragments are called semantic actions
• They can appear at any position within production body, must be
placed in { }
• Any SDT can be implemented by first building a parse tree and
then performing the actions in a left-to-right depth first order
• Typically, SDT’s are implemented during parsing without building
a parse tree
MATRUSRI
ENGINEERING COLLEGE
Example of SDT
Production Semantic Rules
S → E { printE.VAL }
E → E + E {E.VAL := E.VAL + E.VAL }/{print(‘+’);}
E → E * E {E.VAL := E.VAL * E.VAL }/print(‘*’);}
E → (E) {E.VAL := E.VAL }
E → I {E.VAL := I.VAL }
I → I digit {I.VAL := 10 * I.VAL + LEXVAL }
I → digit { I.VAL:= LEXVAL}
MATRUSRI
ENGINEERING COLLEGE
A common way of syntax-directed translation is translating a string
into a sequence of actions by attaching one such action to each
grammar rule.
example of an arithmetic expression 2*(4+5).
A common way of syntax-directed translation is translating a string into a sequence
of actions by attaching one such action to each grammar rule.
MATRUSRI
ENGINEERING COLLEGE
Applications of SDT
• Primary application of SDT is construction of Syntax Trees
• Since some compilers use the syntax trees as an intermediate representation,
a common form of SDD(Syntax Directed Definition) turns its input string
into a tree.
• SDT is used for Executing Arithmetic Expression.
• In the conversion from infix to postfix expression.
• In the conversion from infix to prefix expression.
• It is used for Binary to decimal conversion.
• In counting number of Reduction.
• SDT is used to generate intermediate code.
• In storing information into symbol table.
• SDT is used for type checking also.
MATRUSRI
ENGINEERING COLLEGE
Abstract Syntax Tree
Abstract Syntax Tree: It is a condensed form of parse trees.
Normally operators and keywords appear as leaves in parse tree, but
in an abstract syntax tree they are associated with the interior nodes
that would be the parent of those leaves in the parse tree.
• useful for representing language constructs
MATRUSRI
ENGINEERING COLLEGE
Chain of single production are collapsed into one node with the operators moving
up to become the node.
Constructing Abstract Syntax tree for
expression
Each node in an abstract syntax tree can be implemented as a record
with several fields.
operators : one field for operator, remaining fields are ptr’s to
operands
mknode( op, left, right )
identifier : one field with label id and another is ptr to symbol table
mkleaf(id, entry)
number : one field with label num and another is to keep the value
of the number.
mkleaf(num, val)
MATRUSRI
ENGINEERING COLLEGE
Example of Abstract Syntax Tree MATRUSRI
ENGINEERING COLLEGE
Production
1) E -> E1 + T
2) E -> E1 - T
3) E -> T
4) T -> (E)
5) T -> id
6) T -> num
Semantic Rules
E.node=new node(‘+’, E1.node,T.node)
E.node=new node(‘-’, E1.node,T.node)
E.node = T.node
T.node = E.node
T.node = new Leaf(id,id.entry)
T.node = new Leaf(num,num.val)
the following Sequence of function calls create a
syntax tree for a – 4 + c
P 1 = mkleaf(id, entry.a)
P 2 = mkleaf(num, 4)
P 3 = mknode(-, P 1 , P 2 )
P 4 = mkleaf(id, entry.c)
P 5 = mknode(+, P 3 , P 4 )
A syntax directed definition for constructing syntax tree
Compiler Design UNIT III PPT (SDD, SDT).pdf
Syntax Directed Definition Syntax Directed Translation
It is a context-free grammar where
attributes and rules are combined and
associated with grammar symbols and
productions, respectively.
It refers to the translation of a string into an array
of actions. This is done by adding an action to a
rule of context-free grammar. It is a type of
compiler interpretation.
Attribute Grammar Translation Schemes
SDD: Specifies the values of attributes by
associating semantic rules with the
productions
SDT: embeds program fragments (also called
semantic actions) within production bodies
E -> E + T { E.val := E1.val + T.val } E -> E + T { print(‘+’); }
Always written at the end of body of
production
The position of the action defines the order in
which the action is executed (in the middle of
production or end)
More Readable More Efficient
Used to specify the non-terminals Used to implement S-Attributed SDD and L-
Attributed SDD
Specifies what calculation is to be done at
each production
Specifies what calculation is to be done at each
production and at what time they must be done
Left to right evaluation Left to right evaluation
Used to know the value of non-terminals Used to generate Intermediate Code
Postfix translation schemes
• Simplest SDDs are those that we can parse the grammar bottom-
up and the SDD is s-attributed
• For such cases we can construct SDT where each action is placed
at the end of the production and is executed along with the
reduction of the body to the head of that production
• SDT’s with all actions at the right ends of the production bodies
are called postfix SDT’s
MATRUSRI
ENGINEERING COLLEGE
SDT schemes
Example of postfix SDT
1) L -> E n {print(E.val);}
2) E -> E1 + T {E.val=E1.val||T.val||+;}
3) E -> T {E.val = T.val;}
4) T -> T1 * F {T.val=T1.val||F.val||*;}
5) T -> F {T.val=F.val;}
6) F -> (E) {F.val=E.val;}
7) F -> digit {F.val=digit.lexval;}
MATRUSRI
ENGINEERING COLLEGE
Parse-Stack implementation of postfix SDT’s
• In a shift-reduce parser we can easily implement semantic
action using the parser stack
• For each nonterminal (or state) on the stack we can associate a
record holding its attributes
• Then in a reduction step we can execute the semantic action at
the end of a production to evaluate the attribute(s) of the non-
terminal at the leftside of the production
• And put the value on the stack in replace of the rightside of
production
MATRUSRI
ENGINEERING COLLEGE
Example
L -> E n {print(stack[top-1].val);
top=top-1;}
E -> E1 + T {stack[top-2].val=stack[top-2].val+stack.val;
top=top-2;}
E -> T
T -> T1 * F {stack[top-2].val=stack[top-2].val+stack.val;
top=top-2;}
T -> F
F -> (E) {stack[top-2].val=stack[top-1].val
top=top-2;}
F -> digit
MATRUSRI
ENGINEERING COLLEGE
SDT’s with actions inside productions
• For a production B->X {a} Y
– If the parse is bottom-up then we perform action “a”
as soon as this occurrence of X appears on the top of
the parser stack
– If the parser is top down we perform “a” just before
we expand Y
• Sometimes we cant do things as easily as explained
above
• One example is when we are parsing this SDT with
a bottom-up parser 1) L -> E n
2) E -> {print(‘+’);} E1 + T
3) E -> T
4) T -> {print(‘*’);} T1 * F
5) T -> F
6) F -> (E)
7) F -> digit {print(digit.lexval);}
MATRUSRI
ENGINEERING COLLEGE
SDT’s with actions inside productions (cont)
• Any SDT can be
implemented as follows
1. Ignore the actions and
produce a parse tree
2. Examine each interior
node N and add actions as
new children at the correct
position
3. Perform a postorder
traversal and execute
actions when their nodes
are visited
L
E
+
E
{print(‘+’);}
T
F
digit
{print(4);}
T
T F
*
digit
{print(5);}
F
digit
{print(3);}
{print(‘*’);}
MATRUSRI
ENGINEERING COLLEGE
SDT’s for L-Attributed definitions
• We can convert an L-attributed SDD into an SDT
using following two rules:
– Embed the action that computes the inherited attributes for
a nonterminal A immediately before that occurrence of A. if
several inherited attributes of A are dpendent on one
another in an acyclic fashion, order them so that those
needed first are computed first
– Place the action of a synthesized attribute for the head of a
production at the end of the body of the production
MATRUSRI
ENGINEERING COLLEGE
Example
S -> while (C) S1 L1=new();
L2=new();
S1.next=L1;
C.false=S.next;
C.true=L2;
S.code=label||L1||C.code||label||L2||S1.code
S -> while ( {L1=new();L2=new();C.false=S.next;C.true=L2;}
C) {S1.next=L1;}
S1{S.code=label||L1||C.code||label||L2||S1.code;}
MATRUSRI
ENGINEERING COLLEGE
Ad

More Related Content

Similar to Compiler Design UNIT III PPT (SDD, SDT).pdf (20)

Syntax Directed Definition and its applications
Syntax Directed Definition and its applicationsSyntax Directed Definition and its applications
Syntax Directed Definition and its applications
ShivanandManjaragi2
 
syntax-directed-translation.ppt syntax-directed-translation.ppt
syntax-directed-translation.ppt syntax-directed-translation.pptsyntax-directed-translation.ppt syntax-directed-translation.ppt
syntax-directed-translation.ppt syntax-directed-translation.ppt
dejusertse
 
L14 Semantic analysis This process is crucial in various applications such a...
L14 Semantic analysis  This process is crucial in various applications such a...L14 Semantic analysis  This process is crucial in various applications such a...
L14 Semantic analysis This process is crucial in various applications such a...
CodingChamp1
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
Iffat Anjum
 
chp2sds.pdfgh
chp2sds.pdfghchp2sds.pdfgh
chp2sds.pdfgh
KamranAli649587
 
lect-05.pdf
lect-05.pdflect-05.pdf
lect-05.pdf
KamranAli649587
 
unit 3 modules intermediate code generation
unit 3 modules intermediate code generationunit 3 modules intermediate code generation
unit 3 modules intermediate code generation
ElakkiaU
 
Chapter 5 - Syntax Directed Translation.ppt
Chapter 5 - Syntax Directed Translation.pptChapter 5 - Syntax Directed Translation.ppt
Chapter 5 - Syntax Directed Translation.ppt
MulugetaGebino
 
Chapter_5_Syntax_Directed_Translation.ppt
Chapter_5_Syntax_Directed_Translation.pptChapter_5_Syntax_Directed_Translation.ppt
Chapter_5_Syntax_Directed_Translation.ppt
JigarThummar1
 
Chapter 5 Syntax Directed Translation
Chapter 5   Syntax Directed TranslationChapter 5   Syntax Directed Translation
Chapter 5 Syntax Directed Translation
Radhakrishnan Chinnusamy
 
Chapte - Syntax Directed Translation.ppt
Chapte - Syntax Directed Translation.pptChapte - Syntax Directed Translation.ppt
Chapte - Syntax Directed Translation.ppt
PraveenaFppt
 
Chapter _4_Semantic Analysis .pptx
Chapter _4_Semantic Analysis .pptxChapter _4_Semantic Analysis .pptx
Chapter _4_Semantic Analysis .pptx
ArebuMaruf
 
Module 3 - Semantic Analysis(Compiler Design).pptx
Module 3 - Semantic Analysis(Compiler Design).pptxModule 3 - Semantic Analysis(Compiler Design).pptx
Module 3 - Semantic Analysis(Compiler Design).pptx
muralidharanm2022
 
Syntax Directed Translation PPTs for Third Year CSE
Syntax Directed Translation PPTs for Third Year CSESyntax Directed Translation PPTs for Third Year CSE
Syntax Directed Translation PPTs for Third Year CSE
DrRajurkarArchanaMil
 
Chapter_5_Syntax_Directed_Translation.ppt
Chapter_5_Syntax_Directed_Translation.pptChapter_5_Syntax_Directed_Translation.ppt
Chapter_5_Syntax_Directed_Translation.ppt
SatyamVerma61
 
Semantics analysis
Semantics analysisSemantics analysis
Semantics analysis
Bilalzafar22
 
RMM CD LECTURE NOTES UNIT-3 ALL.pdf
RMM CD LECTURE NOTES UNIT-3 ALL.pdfRMM CD LECTURE NOTES UNIT-3 ALL.pdf
RMM CD LECTURE NOTES UNIT-3 ALL.pdf
RishikeshPathak10
 
CSE-303 Chapter-05 compiler bison flex syntax
CSE-303 Chapter-05 compiler bison flex syntaxCSE-303 Chapter-05 compiler bison flex syntax
CSE-303 Chapter-05 compiler bison flex syntax
Arik98
 
Syntaxdirected
SyntaxdirectedSyntaxdirected
Syntaxdirected
Royalzig Luxury Furniture
 
Syntaxdirected
SyntaxdirectedSyntaxdirected
Syntaxdirected
Royalzig Luxury Furniture
 
Syntax Directed Definition and its applications
Syntax Directed Definition and its applicationsSyntax Directed Definition and its applications
Syntax Directed Definition and its applications
ShivanandManjaragi2
 
syntax-directed-translation.ppt syntax-directed-translation.ppt
syntax-directed-translation.ppt syntax-directed-translation.pptsyntax-directed-translation.ppt syntax-directed-translation.ppt
syntax-directed-translation.ppt syntax-directed-translation.ppt
dejusertse
 
L14 Semantic analysis This process is crucial in various applications such a...
L14 Semantic analysis  This process is crucial in various applications such a...L14 Semantic analysis  This process is crucial in various applications such a...
L14 Semantic analysis This process is crucial in various applications such a...
CodingChamp1
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
Iffat Anjum
 
unit 3 modules intermediate code generation
unit 3 modules intermediate code generationunit 3 modules intermediate code generation
unit 3 modules intermediate code generation
ElakkiaU
 
Chapter 5 - Syntax Directed Translation.ppt
Chapter 5 - Syntax Directed Translation.pptChapter 5 - Syntax Directed Translation.ppt
Chapter 5 - Syntax Directed Translation.ppt
MulugetaGebino
 
Chapter_5_Syntax_Directed_Translation.ppt
Chapter_5_Syntax_Directed_Translation.pptChapter_5_Syntax_Directed_Translation.ppt
Chapter_5_Syntax_Directed_Translation.ppt
JigarThummar1
 
Chapte - Syntax Directed Translation.ppt
Chapte - Syntax Directed Translation.pptChapte - Syntax Directed Translation.ppt
Chapte - Syntax Directed Translation.ppt
PraveenaFppt
 
Chapter _4_Semantic Analysis .pptx
Chapter _4_Semantic Analysis .pptxChapter _4_Semantic Analysis .pptx
Chapter _4_Semantic Analysis .pptx
ArebuMaruf
 
Module 3 - Semantic Analysis(Compiler Design).pptx
Module 3 - Semantic Analysis(Compiler Design).pptxModule 3 - Semantic Analysis(Compiler Design).pptx
Module 3 - Semantic Analysis(Compiler Design).pptx
muralidharanm2022
 
Syntax Directed Translation PPTs for Third Year CSE
Syntax Directed Translation PPTs for Third Year CSESyntax Directed Translation PPTs for Third Year CSE
Syntax Directed Translation PPTs for Third Year CSE
DrRajurkarArchanaMil
 
Chapter_5_Syntax_Directed_Translation.ppt
Chapter_5_Syntax_Directed_Translation.pptChapter_5_Syntax_Directed_Translation.ppt
Chapter_5_Syntax_Directed_Translation.ppt
SatyamVerma61
 
Semantics analysis
Semantics analysisSemantics analysis
Semantics analysis
Bilalzafar22
 
RMM CD LECTURE NOTES UNIT-3 ALL.pdf
RMM CD LECTURE NOTES UNIT-3 ALL.pdfRMM CD LECTURE NOTES UNIT-3 ALL.pdf
RMM CD LECTURE NOTES UNIT-3 ALL.pdf
RishikeshPathak10
 
CSE-303 Chapter-05 compiler bison flex syntax
CSE-303 Chapter-05 compiler bison flex syntaxCSE-303 Chapter-05 compiler bison flex syntax
CSE-303 Chapter-05 compiler bison flex syntax
Arik98
 

Recently uploaded (20)

Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Ad

Compiler Design UNIT III PPT (SDD, SDT).pdf

  • 1. MATRUSRI ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING SUBJECT NAME: Compiler Design FACULTY NAME: MATRUSRI ENGINEERING COLLEGE
  • 2. Compiler Design COURSE OBJECTIVES: ➢To introduce the steps in language translation pipeline and runtime data structures used in translation ➢ To learn about Scanning (lexical analysis) process using regular expressions and use of LEX to generate scanner ➢ To introduce different Parsing strategies including top-down (e.g., recursive descent, Early parsing, or LL) and bottom-up (e.g., backtracking or LR) techniques ➢ Describe semantic analyses using an attribute grammar ➢ To learn how to build symbol tables and generate intermediate code. ➢ To introduce techniques of program analysis and code optimization MATRUSRI ENGINEERING COLLEGE 22-06-2023 Compiler Construction 2 COURSE OUTCOMES: After completing this course, the student will be able to 1. Create lexical rules and grammars for a given language 2. Generate scanners and parsers from declarative specifications. 3. Describe an abstract syntax tree for a small language. 4. Use program analysis techniques for code optimization 5. Develop the compiler for a subset of a given language
  • 3. Unit-III Syntax-Directed Translation: Syntax-Directed Definitions, Evaluation Orders for SDD’s, Applications of Syntax-Directed Translation. Symbol Table: Structure, Operations, Implementation and Management. MATRUSRI ENGINEERING COLLEGE
  • 4. Outline • Syntax Directed Definitions • Evaluation Orders of SDD’s • Syntax Directed Translation Schemes • Applications of Syntax Directed Translation • Symbol Table: Structure, Operations, • Implementation and Management. MATRUSRI ENGINEERING COLLEGE
  • 5. Introduction Syntax-directed translation is done by attaching rules or program fragments to productions in a grammar • A syntax directed definition specifies the values of attributes by associating semantic rules with the grammar productions. • Concepts related to syntax-directed translation are – Attributes – Translation schemes • An attribute is any quantity associated with a programming construct. – Data types of expression, number of instructions, location of the instruction, non-terminals and terminal symbols. • A translation scheme is a notation for attaching program fragments to the productions of a grammar MATRUSRI ENGINEERING COLLEGE
  • 6. Example Production Semantic Rule E->E1+T E.code=E1.code + T.code MATRUSRI ENGINEERING COLLEGE If X is a symbol and a is one of its attributes, then we write X.a to denote the value of a at a particular parse-tree node labelled X. This production has two non-terminals, E1 and T. E1 and T have a string-valued attribute code. The semantic rule species that the string E:code is formed by concatenating E1:code, T:code, and the character ‘+’. We may alternatively insert the semantic actions inside the grammar. E -> E1+T {print ‘+’} By convention, semantic actions are enclosed within curly braces.
  • 7. Syntax Directed Definitions A SDD is a context free grammar with attributes and rules • A syntax directed definition specifies the values of attributes by associating semantic rules with the grammar productions. • Attributes are associated with grammar symbols and rules with productions. • Attributes may be of many kinds: numbers, types, table references, strings, etc. • Rules describe how the attributes are computed at those nodes of the parse tree. Definition: SDD is a generalization of CFG in which each production rule X->α is associated with a set of semantic rules of the form a:=f(b1, b2,……bk), where a is an attribute obtained from the function f. MATRUSRI ENGINEERING COLLEGE
  • 8. Synthesized and Inherited Synthesized attributes – A synthesized attribute for a nonterminal A at a parse-tree node N is defined by a semantic rule associated with the production at N. – Note that the production must have A as its head. – A synthesized attribute at node N is defined only in terms of attribute values of children of N and at N itself. Inherited attributes – An inherited attribute for a nonterminal B at a parse-tree node N is defined by a semantic rule associated with the production at the parent of N. – Note that the production must have B as a symbol in its body. – An inherited attribute at node N is defined only in terms of attribute values at N’s parent, N itself and N’s siblings. • Terminals can have synthesized attributes, but not inherited attributes. • Attributes for terminals have lexical values that are supplied by the lexical analyzer, there are no semantic rules in the SDD itself for computing the value of an attribute for a terminal. MATRUSRI ENGINEERING COLLEGE
  • 9. Example An inherited attribute at node N cannot be defined in terms of attribute values at the children of node N, but a synthesized attribute at node N can be defined in terms of inherited attribute values at node N itself. PRODUCTION SEMANTIC RULES A -> B A.s := B.i; B.i := A.s + 1 MATRUSRI ENGINEERING COLLEGE A and B, have s and i as attributes. Here s is synthesized and i is inherited, because s is evaluated from its children and i is evaluated from its parent
  • 10. S-attributed SDD An SDD that involves only synthesized attributes is called S- attributed. In an S-attributed SDD, each rule computes an attribute for the nonterminal at the head of a production from attributes taken from the body of the production. An S-attributed SDD can be implemented naturally in conjunction with an LR parser. An S-attributed definition, is suitable for use during bottom-up parsing. An SDD without side effects is sometimes called an attribute grammar. The rules in an attribute grammar define the value of an attribute purely in terms of the values of other attributes and constants. To visualize the translation specified by an SDD, it helps to work with parse Trees. A parse tree, showing the value(s) of its attribute(s) is called an annotated parse tree. MATRUSRI ENGINEERING COLLEGE
  • 11. Example of S-attributed SDD Production 1) L -> E n 2) E -> E1 + T 3) E -> T 4) T -> T1 * F 5) T -> F 6) F -> (E) 7) F -> digit Semantic Rules L.val = E.val E.val = E1.val + T.val E.val = T.val T.val = T1.val * F.val T.val = F.val F.val = E.val F.val = digit.lexval MATRUSRI ENGINEERING COLLEGE • In the above SDD, each of the non-terminals has a single synthesized attribute, called val. • Terminal digit has a synthesized attribute lexval, which is an integer value returned by the lexical analyzer. • For production 1, L -> E n, sets L.val to E.val, which we shall see is the numerical value of the entire expression. • For production 2, E -> E1 + T, also has one rule, which computes the val attribute for the head E as the sum of the values at E1 and T. At any parse tree node N labeled E, the value of val for E is the sum of the values of val at the children of node N labeled E and T.
  • 12. Example of S-attributed SDD MATRUSRI ENGINEERING COLLEGE Annotated parse tree for 3 * 5 + 4
  • 13. L-attributed SDD If an SDD uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT. • Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner. • Semantic actions are placed anywhere in RHS. L-attributed, is suitable for use during top-down parsing. Example: A -> XYZ {Y.S = A.S, Y.S = X.S, Y.S = Z.S} is not an L-attributed grammar since Y.S = A.S and Y.S = X.S are allowed but Y.S = Z.S violates the L-attributed SDT definition as attributed is inheriting the value from its right sibling. Note – If a definition is S-attributed, then it is also L-attributed but NOT vice-versa. MATRUSRI ENGINEERING COLLEGE
  • 14. L-Attributed definitions MATRUSRI ENGINEERING COLLEGE Production Semantic Rules T —> FT’ T’.inh = F.val T’ —> *FT1’ T’1.inh =T’.inh x F.val In production 1, the inherited attribute T’ is computed from the value of F which is to its left. In production 2, the inherited attributed Tl’ is computed from T’. inh associated with its head and the value of F which appears to its left in the production. i.e., for computing inherited attribute, it must either use from the above or from the left information of SDD.
  • 15. SDD-Inherited attributes MATRUSRI ENGINEERING COLLEGE Production Semantic Rules D —>TL L.inh = T.type T —> int T.type =integer T —> float T.type = float L —> L1, id L1.inh = L.inh addType (id.entry, Linh) L —> id addType (id.entry, L.inh)
  • 16. SDD-Inherited attributes MATRUSRI ENGINEERING COLLEGE Dependency graph for a declaration float id1, id2, id3
  • 17. L-Attributed definitions • A SDD is L-Attributed if the edges in dependency graph goes from Left to Right but not from Right to Left. • More precisely, each attribute must be either – Synthesized – Inherited, • but if there is a production A->X1X2…Xn and there is an inherited attribute Xi.a computed by a rule associated with this production, then the rule may only use: – Inherited attributes associated with the head A – Either inherited or synthesized attributes associated with the occurrences of symbols X1,X2,…,Xi-1 located to the left of Xi – Inherited or synthesized attributes associated with this occurrence of Xi itself, but in such a way that there is no cycle in the graph MATRUSRI ENGINEERING COLLEGE
  • 18. Syntax tree for L-attributed definition Production 1) E -> TE’ 2) E’ -> + TE1’ 3) E’ -> -TE1’ 4) E’ ->  5) T -> (E) 6) T -> id 7) T -> num Semantic Rules E.node=E’.syn E’.inh=T.node E1’.inh=new node(‘+’, E’.inh,T.node) E’.syn=E1’.syn E1’.inh=new node(‘+’, E’.inh,T.node) E’.syn=E1’.syn E’.syn = E’.inh T.node = E.node T.node=new Leaf(id,id.entry) T.node = new Leaf(num,num.val) MATRUSRI ENGINEERING COLLEGE
  • 19. Evaluation orders for SDD’s Dependency graphs are a useful tool for determining an evaluation order for the attribute instances in parse tree. • Annotated parse tree shows the values of attributes, a dependency graph helps us determine how those values can be computed. • A dependency graph depicts the flow of information among the attribute instances in a particular parse tree. • An edge from one attribute instance to another means that the value of the first is needed to compute the second. • Edges express constraints implied by the semantic rules. Dependency Graph : Directed graph indicating interdependencies among the synthesized and inherited attributes of various nodes in a parse tree. MATRUSRI ENGINEERING COLLEGE
  • 20. Dependency Graph Dependency graph – For each parse tree node X, the dependency graph has a node for each attribute associated with the node X. – For a production p, if a semantic rule defines the value of synthesized attribute A.b in terms of the value of X.c then the dependency graph has an edge from X.c to A.b – For a production p, if a semantic rule defines the value of inherited attribute B.c in terms of the value of X.a then the dependency graph has an edge from X.a to B.c MATRUSRI ENGINEERING COLLEGE
  • 21. Ordering the evaluation of attributes • If dependency graph has an edge from M to N then M must be evaluated before the attribute of N • Thus, the only allowable orders of evaluation are those sequence of nodes N1,N2,…,Nk such that if there is an edge from Ni to Nj then i<j • Such an ordering is called a topological sort of a graph. • If there is any cycle in the graph, then there are no topological sorts; that is, there is no way to evaluate the SDD on this parse tree. MATRUSRI ENGINEERING COLLEGE
  • 22. S-Attributed SDD Example MATRUSRI ENGINEERING COLLEGE Evaluation Order: Semantic rules in a S-Attributed Definition can be evaluated by a bottom-up, or PostOrder, traversal of the parse-tree. Example. The annotated parse-tree for the input 3*5+4n is:
  • 23. L-Attributed SDD Example Production 1) T -> FT’ 2) T’ -> *FT’1 3) T’ -> ε 1) F -> digit Semantic Rules T’.inh = F.val T.val = T’.syn T’1.inh = T’.inh*F.val T’.syn = T’1.syn T’.syn = T’.inh F.val = F.val = digit.lexval MATRUSRI ENGINEERING COLLEGE Annotated parse tree for expression: 3 * 5
  • 24. MATRUSRI ENGINEERING COLLEGE Dependency Graph for the expression: 3 * 5 • Nodes 1 and 2 represent the attribute lexval associated with the two leaves labeled digit. • Nodes 3 and 4 represent the attribute val associated with the two nodes labeled F. The edges to node 3 from 1 and to node 4 from 2 result from the semantic rule that defines F.val in terms of digit.lexval. In fact, F.val equals digit.lexval, but the edge represents dependence, not equality. • Nodes 5 and 6 represent the inherited attribute T’.inh associated with each of the occurrences of nonterminal T’. • Nodes 7 and 8 represent the synthesized attribute syn associated with the occurrences of T’. Order: 1,3,5,2,4,6,7,8,9
  • 25. Syntax Directed Translation (SDT) An SDT is a Context Free grammar with program fragments embedded within production bodies • Those program fragments are called semantic actions • They can appear at any position within production body, must be placed in { } • Any SDT can be implemented by first building a parse tree and then performing the actions in a left-to-right depth first order • Typically, SDT’s are implemented during parsing without building a parse tree MATRUSRI ENGINEERING COLLEGE
  • 26. Example of SDT Production Semantic Rules S → E { printE.VAL } E → E + E {E.VAL := E.VAL + E.VAL }/{print(‘+’);} E → E * E {E.VAL := E.VAL * E.VAL }/print(‘*’);} E → (E) {E.VAL := E.VAL } E → I {E.VAL := I.VAL } I → I digit {I.VAL := 10 * I.VAL + LEXVAL } I → digit { I.VAL:= LEXVAL} MATRUSRI ENGINEERING COLLEGE A common way of syntax-directed translation is translating a string into a sequence of actions by attaching one such action to each grammar rule.
  • 27. example of an arithmetic expression 2*(4+5). A common way of syntax-directed translation is translating a string into a sequence of actions by attaching one such action to each grammar rule. MATRUSRI ENGINEERING COLLEGE
  • 28. Applications of SDT • Primary application of SDT is construction of Syntax Trees • Since some compilers use the syntax trees as an intermediate representation, a common form of SDD(Syntax Directed Definition) turns its input string into a tree. • SDT is used for Executing Arithmetic Expression. • In the conversion from infix to postfix expression. • In the conversion from infix to prefix expression. • It is used for Binary to decimal conversion. • In counting number of Reduction. • SDT is used to generate intermediate code. • In storing information into symbol table. • SDT is used for type checking also. MATRUSRI ENGINEERING COLLEGE
  • 29. Abstract Syntax Tree Abstract Syntax Tree: It is a condensed form of parse trees. Normally operators and keywords appear as leaves in parse tree, but in an abstract syntax tree they are associated with the interior nodes that would be the parent of those leaves in the parse tree. • useful for representing language constructs MATRUSRI ENGINEERING COLLEGE Chain of single production are collapsed into one node with the operators moving up to become the node.
  • 30. Constructing Abstract Syntax tree for expression Each node in an abstract syntax tree can be implemented as a record with several fields. operators : one field for operator, remaining fields are ptr’s to operands mknode( op, left, right ) identifier : one field with label id and another is ptr to symbol table mkleaf(id, entry) number : one field with label num and another is to keep the value of the number. mkleaf(num, val) MATRUSRI ENGINEERING COLLEGE
  • 31. Example of Abstract Syntax Tree MATRUSRI ENGINEERING COLLEGE Production 1) E -> E1 + T 2) E -> E1 - T 3) E -> T 4) T -> (E) 5) T -> id 6) T -> num Semantic Rules E.node=new node(‘+’, E1.node,T.node) E.node=new node(‘-’, E1.node,T.node) E.node = T.node T.node = E.node T.node = new Leaf(id,id.entry) T.node = new Leaf(num,num.val) the following Sequence of function calls create a syntax tree for a – 4 + c P 1 = mkleaf(id, entry.a) P 2 = mkleaf(num, 4) P 3 = mknode(-, P 1 , P 2 ) P 4 = mkleaf(id, entry.c) P 5 = mknode(+, P 3 , P 4 ) A syntax directed definition for constructing syntax tree
  • 33. Syntax Directed Definition Syntax Directed Translation It is a context-free grammar where attributes and rules are combined and associated with grammar symbols and productions, respectively. It refers to the translation of a string into an array of actions. This is done by adding an action to a rule of context-free grammar. It is a type of compiler interpretation. Attribute Grammar Translation Schemes SDD: Specifies the values of attributes by associating semantic rules with the productions SDT: embeds program fragments (also called semantic actions) within production bodies E -> E + T { E.val := E1.val + T.val } E -> E + T { print(‘+’); } Always written at the end of body of production The position of the action defines the order in which the action is executed (in the middle of production or end) More Readable More Efficient Used to specify the non-terminals Used to implement S-Attributed SDD and L- Attributed SDD Specifies what calculation is to be done at each production Specifies what calculation is to be done at each production and at what time they must be done Left to right evaluation Left to right evaluation Used to know the value of non-terminals Used to generate Intermediate Code
  • 34. Postfix translation schemes • Simplest SDDs are those that we can parse the grammar bottom- up and the SDD is s-attributed • For such cases we can construct SDT where each action is placed at the end of the production and is executed along with the reduction of the body to the head of that production • SDT’s with all actions at the right ends of the production bodies are called postfix SDT’s MATRUSRI ENGINEERING COLLEGE SDT schemes
  • 35. Example of postfix SDT 1) L -> E n {print(E.val);} 2) E -> E1 + T {E.val=E1.val||T.val||+;} 3) E -> T {E.val = T.val;} 4) T -> T1 * F {T.val=T1.val||F.val||*;} 5) T -> F {T.val=F.val;} 6) F -> (E) {F.val=E.val;} 7) F -> digit {F.val=digit.lexval;} MATRUSRI ENGINEERING COLLEGE
  • 36. Parse-Stack implementation of postfix SDT’s • In a shift-reduce parser we can easily implement semantic action using the parser stack • For each nonterminal (or state) on the stack we can associate a record holding its attributes • Then in a reduction step we can execute the semantic action at the end of a production to evaluate the attribute(s) of the non- terminal at the leftside of the production • And put the value on the stack in replace of the rightside of production MATRUSRI ENGINEERING COLLEGE
  • 37. Example L -> E n {print(stack[top-1].val); top=top-1;} E -> E1 + T {stack[top-2].val=stack[top-2].val+stack.val; top=top-2;} E -> T T -> T1 * F {stack[top-2].val=stack[top-2].val+stack.val; top=top-2;} T -> F F -> (E) {stack[top-2].val=stack[top-1].val top=top-2;} F -> digit MATRUSRI ENGINEERING COLLEGE
  • 38. SDT’s with actions inside productions • For a production B->X {a} Y – If the parse is bottom-up then we perform action “a” as soon as this occurrence of X appears on the top of the parser stack – If the parser is top down we perform “a” just before we expand Y • Sometimes we cant do things as easily as explained above • One example is when we are parsing this SDT with a bottom-up parser 1) L -> E n 2) E -> {print(‘+’);} E1 + T 3) E -> T 4) T -> {print(‘*’);} T1 * F 5) T -> F 6) F -> (E) 7) F -> digit {print(digit.lexval);} MATRUSRI ENGINEERING COLLEGE
  • 39. SDT’s with actions inside productions (cont) • Any SDT can be implemented as follows 1. Ignore the actions and produce a parse tree 2. Examine each interior node N and add actions as new children at the correct position 3. Perform a postorder traversal and execute actions when their nodes are visited L E + E {print(‘+’);} T F digit {print(4);} T T F * digit {print(5);} F digit {print(3);} {print(‘*’);} MATRUSRI ENGINEERING COLLEGE
  • 40. SDT’s for L-Attributed definitions • We can convert an L-attributed SDD into an SDT using following two rules: – Embed the action that computes the inherited attributes for a nonterminal A immediately before that occurrence of A. if several inherited attributes of A are dpendent on one another in an acyclic fashion, order them so that those needed first are computed first – Place the action of a synthesized attribute for the head of a production at the end of the body of the production MATRUSRI ENGINEERING COLLEGE
  • 41. Example S -> while (C) S1 L1=new(); L2=new(); S1.next=L1; C.false=S.next; C.true=L2; S.code=label||L1||C.code||label||L2||S1.code S -> while ( {L1=new();L2=new();C.false=S.next;C.true=L2;} C) {S1.next=L1;} S1{S.code=label||L1||C.code||label||L2||S1.code;} MATRUSRI ENGINEERING COLLEGE