0% found this document useful (0 votes)
12 views12 pages

LEARNING MATERIALS, CD, UNIT-4 (Syntax Directed Translation)

Ok , syt , computer

Uploaded by

banakumar ghosh
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)
12 views12 pages

LEARNING MATERIALS, CD, UNIT-4 (Syntax Directed Translation)

Ok , syt , computer

Uploaded by

banakumar ghosh
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/ 12

DH SIRS CLASSROOM

LEARNING MATERIALS
Department : Computer Science & Technology Semester : 5TH

Subject : COMPILER DESIGN

UNIT : (4) Syntax directed translation Course Code : Contact Periods : 04 Hrs

Teacher : Debasish Hati Date :


____________________

__________________________________________________________________________
Content:
Syntax director definitions, Construction of syntax trees, Bottom-up evaluation of S attributed definitions, L
attributed definitions, Bottom-up evaluation of inherited attributes.
…………………………………………………………………………………………………………………..

Semantic Analysis in Compiler Design


Semantic Analysis is the third phase of Compiler. Semantic Analysis makes sure that declarations
and statements of program are semantically correct. It is a collection of procedures which is called
by parser as and when required by grammar. Both syntax tree of previous phase and symbol table
are used to check the consistency of the given code. Type checking is an important part of seman-
tic analysis where compiler makes sure that each operator has matching operands.
Semantic Analyzer:
It uses syntax tree and symbol table to check whether the given program is semantically consistent

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


with language definition. It gathers type information and stores it in either syntax tree or symbol
table. This type information is subsequently used by compiler during intermediate-code genera-
tion.
Semantic Errors:
Errors recognized by semantic analyzer are as follows:
 Type mismatch
 Undeclared variables
 Reserved identifier misuse
Functions of Semantic Analysis:
1. Type Checking –
Ensures that data types are used in a way consistent with their definition.
2. Label Checking –
A program should contain labels references.
3. Flow Control Check –
Keeps a check that control structures are used in a proper manner.(example: no break state-
ment outside a loop)
Example:

float x = 10.1;
float y = x*30;
In the above example integer 30 will be typecasted to float 30.0 before multiplication, by semantic
analyzer.
Static and Dynamic Semantics:
1. Static Semantics –
It is named so because of the fact that these are checked at compile time. The static semantics
and meaning of program during execution, are indirectly related.
2. Dynamic Semantic Analysis –
It defines the meaning of different units of program like expressions and statements. These are
checked at runtime unlike static semantics.

SDT
In syntax directed translation, along with the grammar we associate some informal notations and these
notations are called as semantic rules.

So we can say that

1. Grammar + semantic rule = SDT (syntax directed translation)


o In syntax directed translation, every non-terminal can get one or more than one attribute or sometimes 0 at-
tribute depending on the type of the attribute. The value of these attributes is evaluated by the semantic rules
associated with the production rule.
o In the semantic rule, attribute is VAL and an attribute may hold anything like a string, a number, a memory
location and a complex record

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


o In Syntax directed translation, whenever a construct encounters in the programming language then it is trans-
lated according to the semantic rules define in that particular programming language.

Example

Production Semantic Rules

E→E+T E.val := E.val + T.val

E→T E.val := T.val

T→T*F T.val := T.val + F.val

T→F T.val := F.val

F → (F) F.val := F.val

F → num F.val := num.lexval

E.val is one of the attributes of E.

num.lexval is the attribute returned by the lexical analyzer.

Syntax directed translation scheme


o The Syntax directed translation scheme is a context -free grammar.
o The syntax directed translation scheme is used to evaluate the order of semantic rules.
o In translation scheme, the semantic rules are embedded within the right side of the productions.
o The position at which an action is to be executed is shown by enclosed between braces. It is written within the
right side of the production.

Example

Production Semantic Rules

S→E$ { printE.VAL }

E→E+E {E.VAL := E.VAL + E.VAL }

E→E*E {E.VAL := E.VAL * E.VAL }

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}

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


Implementation of Syntax directed translation
Syntax direct translation is implemented by constructing a parse tree and performing the actions in a left to
right depth first order.

SDT is implementing by parse the input and produce a parse tree as a result.

Example

Production Semantic Rules

S→E$ { printE.VAL }

E→E+E {E.VAL := E.VAL + E.VAL }

E→E*E {E.VAL := E.VAL * E.VAL }

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}

Parse tree for SDT:

Fig: Parse tree

Problem:01

Consider the following grammer and its corresponding Syntax directed Translation(SDT):
E->E+T { printf(“+”); }

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


| T {}
T->T*F { printf(“*”); }
|F {}
F->num { printf(num.lvalue) }

What will be the output if we carry out this SDT on an input string “2+3*4” using –
i) Top down parser ii) Bottom up parser
Draw and explain the parse tree in each case.

Solution:

Let’s take a string to see how semantic analysis happens – S = 2+3*4. Parse tree corresponding to
S would be

Above diagram shows how semantic analysis could happen. The flow of information happens bottom-up and all the
children attributes are computed before parents, as discussed above. Right hand side nodes are sometimes annotated
with subscript 1 to distinguish between children and parent.

Syntax Directed Definitions (SDD) are formal methods of attaching semantic


information to the syntactic structure of a programming language. SDDs improve the
means of context-free high-level by instances, adding a semantic rule set for every
production of the grammar. The rules described in these definitions state how to
derive values such as types, memory locations, or fragments of code from the
structure of an input object.
Syntax Directed Translation (SDT) is the action of translating a high-level language
program into an intermediate language or machine language according to the

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


semantic rules imposed by SDDs. Semantic actions in SDT, act in coordination with
the parsing process in order to provide the translation of the input code. These actions
are declarative and they are triggered during the parsing phase of the message to
yield the result.
What is Syntax Directed Translation?
Syntax Directed Translation (SDT), is a technical manner utilized in semantics and
language translation whereby a source language is translated into an intermediate
language or a target language through semantic actions, and attributes attached to
the grammar. The translation process follows the structure of the grammar, besides
the performance of semantic actions is interwoven with the processes of input
parsing.
The semantic actions are normally included in the grammatical rules and can be either
performed synchronously or asynchronously with the parsing actions. Integrated
development systems such as SDT offer tools to compilers such as code generation,
lexical analysis, evaluation of expressions, definition, grammar, and checking of
types among other services.
What are Annotated Parse Trees?
The parse tree containing the values of attributes at each node for given input string is
called annotated or decorated parse tree.
Features of Annotated Parse Trees
 High level specification
 Hides implementation details
 Explicit order of evaluation is not specified
Types of Attributes
There are two types of attributes:
1. Synthesized Attributes: These are those attributes which derive their values from
their children nodes i.e. value of synthesized attribute at node is computed from the
values of attributes at children nodes in parse tree.
Example:
E --> E1 + T { E.val = E1.val + T.val}
In this, E.val derive its values from E1.val and T.val
Computation of Synthesized Attributes
 Write the SDD using appropriate semantic rules for each production in given
grammar.
 The annotated parse tree is generated and attribute values are computed in bot-
tom up manner.
 The value obtained at root node is the final output.
Example: Consider the following grammar
S --> E
E --> E1 + T
E --> T
T --> T1 * F
T --> F
F --> digit
The SDD for the above grammar can be written as follow

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


Let us assume an input string 4 * 5 + 6 for computing synthesized attributes. The
annotated parse tree for the input string is

For computation of attributes we start from leftmost bottom node. The rule F –> digit is
used to reduce digit to F and the value of digit is obtained from lexical analyzer which
becomes value of F i.e. from semantic action F.val = digit.lexval. Hence, F.val = 4 and
since T is parent node of F so, we get T.val = 4 from semantic action T.val = F.val.

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


Then, for T –> T1 * F production, the corresponding semantic action is T.val = T1.val *
F.val . Hence, T.val = 4 * 5 = 20
Similarly, combination of E1.val + T.val becomes E.val i.e. E.val = E1.val + T.val = 26.
Then, the production S –> E is applied to reduce E.val = 26 and semantic action
associated with it prints the result E.val . Hence, the output will be 26.
2. Inherited Attributes: These are the attributes which derive their values from their
parent or sibling nodes i.e. value of inherited attributes are computed by value of
parent or sibling nodes.
Example:
A --> BCD { C.in = A.in, C.type = B.type }
Computation of Inherited Attributes
 Construct the SDD using semantic actions.
 The annotated parse tree is generated and attribute values are computed in top
down manner.
Example: Consider the following grammar
S --> T L
T --> int
T --> float
T --> double
L --> L1, id
L --> id
The SDD for the above grammar can be written as follow

Let us assume an input string int a, c for computing inherited attributes. The
annotated parse tree for the input string is

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


The value of L nodes is obtained from T.type (sibling) which is basically lexical value
obtained as int, float or double. Then L node gives type of identifiers a and c. The
computation of type is done in top down manner or preorder traversal. Using function
Enter_type the type of identifiers a and c is inserted in symbol table at corresponding
id.entry.

Frequently Asked Questions on Syntax Directed Definition – FAQs

What is the difference between SDD and SDT?


SDD is a relatively simple method that targets at defining attribute grammar values by
associating them with rules of the grammar given. SDTs expand SDDs by
incorporating operations to do which are carried out to transform a high-level
language to an intermediate or target language.
What is the role of semantic actions in SDT?
Semantic actions are a part of a code put within grammar rules. They run during
parsing to produce translations or perform other such operations as type or memory
address computations.
What are synthesized attributes?
Synthesized attributes obtain their values from child nodes from a parse tree. They
are performed in bottom-up manner meaning that they are calculated starting from the
terminal symbols of the parse tree.
What are inherited attributes?

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


Inherited attributes are calculated based on parent or other sibling nodes; They are
normally checked during the process of top-down analysis of the parse tree or a top-
down analysis of the parse tree.
How are SDDs used in compiler design?
SDDs are used to elaborate how semantic information (for instance, type checking or
code generation) relates to the syntactic constructs, on which construction of
compilers and interpreters depended on.

DESCRIPTIVE TYPES QUESTIONS AND ANSWER

1. Define Syntax-Directed Definitions (SDDs) and explain their role in compiler design.

Answer: Syntax-Directed Definitions (SDDs) are formal systems used to define the syntax and semantics of
programming languages. An SDD associates each production rule of a context-free grammar with a set of
semantic rules that describe how to compute attributes for the non-terminals. These attributes can be used to
capture various aspects of the language's semantics, such as type information, values, or context.

In compiler design, SDDs serve several purposes:

 Semantic Analysis: They facilitate the semantic analysis phase, ensuring that the code adheres to the rules
of the language.
 Attribute Evaluation: They define how attributes are computed during parsing, allowing for the construction
of semantic information along with the syntax tree.
 Modularity: By separating syntax from semantics, SDDs enhance the modularity and clarity of compiler de-
sign.

2. Explain the construction of syntax trees and their significance in compilers.

Answer: A syntax tree, or parse tree, is a hierarchical tree structure that represents the syntactic structure of
a source code based on a given grammar. Each internal node of the tree represents a non-terminal symbol,
while the leaves represent terminal symbols (tokens). The structure of the tree reflects the derivation of the
string in accordance with the grammar's production rules.

Significance of Syntax Trees in Compilers:

 Visual Representation: Syntax trees provide a visual representation of the source code, making it easier to
understand its structure.
 Facilitate Semantic Analysis: They serve as the foundation for semantic analysis, allowing for the evaluation
of expressions, scope resolution, and type checking.
 Code Generation: Syntax trees are often used as input for code generation, where the compiler translates
the high-level constructs into lower-level code or intermediate representations.
 Optimizations: They can be used for various optimizations during the compilation process, such as simplify-
ing expressions or eliminating unnecessary computations.

3. Describe Bottom-Up Evaluation of Synthesized Attributes in Syntax-Directed


Definitions.

Answer: Bottom-Up Evaluation of synthesized attributes involves computing attribute values during the
parsing process, starting from the leaves (terminal symbols) of the syntax tree and moving up towards the
root. This method is often used in conjunction with bottom-up parsing techniques like LR parsing.

Steps in Bottom-Up Evaluation:

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


1. Initialization: At the leaf nodes, the attributes are initialized with the values of the corresponding terminal
symbols.
2. Reduction: As the parser reduces production rules, the semantic rules associated with these rules are exe-
cuted to compute the attributes for the non-terminal on the left-hand side of the production.
3. Aggregation: Synthesized attributes are typically computed from the attributes of the child nodes. For ex-
ample, the attribute of a non-terminal might be computed as a function of its children’s attributes.

4. Define L-Attributed Definitions and discuss their importance.

Answer: L-Attributed Definitions are a specific type of syntax-directed definitions where synthesized
attributes are evaluated in a manner that respects the left-to-right order of the parse tree. In L-attributed
definitions, attributes can be defined in such a way that:

1. Synthesized Attributes: These can depend on the attributes of the children of a node.
2. Inherited Attributes: These can depend on the attributes of the parent and siblings, but must be evaluated
in a left-to-right order.

Importance of L-Attributed Definitions:

 Ease of Implementation: L-attributed definitions can be easily implemented in a single pass over the syntax
tree, which is useful for top-down parsers.
 Semantic Constraints: They provide a structured way to impose semantic constraints and ensure correct
evaluation of attributes.
 Enhanced Clarity: By clearly defining the flow of information between nodes, L-attributed definitions con-
tribute to better clarity and maintainability of compiler implementations.

5. Explain the Bottom-Up Evaluation of Inherited Attributes.

Answer: Bottom-Up Evaluation of inherited attributes is a technique used in syntax-directed definitions


where attributes are passed down from parent nodes to their children during the parsing process. In contrast
to synthesized attributes, which are computed from child nodes, inherited attributes are derived from their
parent or sibling nodes.

Steps in Bottom-Up Evaluation:

1. Initialization: Inherited attributes are often initialized at the root of the parse tree or through semantic rules
applied during parsing.
2. Propagation: As the parser reduces production rules, it computes inherited attributes based on the values of
the parent and sibling nodes. For example, the inherited attribute for a child node might be calculated from
an attribute of the parent.
3. Use Cases: This technique is useful for handling scope information, type propagation, or controlling visibility
rules in programming languages.

Example: Consider a production rule A→ where B inherits an attribute from A:

 If A.scope is the scope in which BBB is defined, then the inherited attribute for B can be defined as:
B.scope=A.scope During the parsing process, as the attributes of A are determined, they are propagated
down to B based on the rules defined.

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST


6. Discuss the significance of Syntax Trees in Bottom-Up Parsing.

Answer: In bottom-up parsing, syntax trees play a crucial role in the evaluation of syntactic constructs as
the parser builds the tree from the leaves up to the root. The significance of syntax trees in this context
includes:

 Structure Representation: They represent the structure of the input source code, allowing the parser to sys-
tematically handle reductions based on grammar rules.
 Semantic Evaluation: As the tree is constructed, attribute values can be computed, enabling semantic
checks to occur alongside parsing.
 Facilitating Reductions: The structure of the syntax tree guides the parser in determining which production
rules can be applied at each step, aiding in the proper reduction of input symbols.
 Integration with Code Generation: Once the parse tree is constructed, it serves as a foundation for generat-
ing intermediate code or target code, making it a vital component of the compilation process.

Compiler Design | UNIT-4 | Prepared By: Debasish Hati, In-charge, DCST

You might also like