What is Syntax Tree?


Tree in which each leaf node describes an operand & each interior node an operator. The syntax tree is shortened form of the Parse Tree.

Example1 − Draw Syntax Tree for the string a + b ∗ c − d.

Rules for constructing a syntax tree

Each node in a syntax tree can be executed as data with multiple fields. In the node for an operator, one field recognizes the operator and the remaining field includes a pointer to the nodes for the operands. The operator is known as the label of the node. The following functions are used to create the nodes of the syntax tree for the expressions with binary operators. Each function returns a pointer to the recently generated node.

  • mknode (op, left, right) − It generates an operator node with label op and two field including pointers to left and right.

  • mkleaf (id, entry) − It generates an identifier node with label id and the field including the entry, a pointer to the symbol table entry for the identifier.

  • mkleaf (num, val) − It generates a number node with label num and a field including val, the value of the number. For example, construct a syntax tree for an expression a − 4 + c. In this sequence, p1, p2, … . . p5are pointers to the symbol table entries for identifier 'a' and 'c' respectively.

p1− mkleaf (id, entry a);
p2− mkleaf (num, 4);
p3− mknode ( ′−′, p1, p2)
p4− mkleaf(id, entry c)
p5− mknode(′+′, p3, p4);

The tree is generated in a bottom-up fashion. The function calls mkleaf (id, entry a) and mkleaf (num 4) construct the leaves for a and 4. The pointers to these nodes are stored using p1and p2. The call mknodes (′−′, p1, p2 ) then make the interior node with the leaves for a and 4 as children. The syntax tree will be

Syntax Directed Translation of Syntax Trees

ProductionSemantic Action
E → E(1) + E(2){E. VAL = Node (+, E(1). VAL, E(2). VAL)}
E → E(1) ∗ E(2){E. VAL = Node (∗, E(1). VAL, E(2). VAL)})
E → (E(1)){E. VAL = E(1). VAL}
E → E(1){E. VAL = UNARY (−, E(1). VAL}
E → id{E. VAL = Leaf (id)}

Node (+, 𝐄(𝟏), 𝐕𝐀𝐋, 𝐄(𝟐). 𝐕𝐀𝐋) will create a node labeled +.

E(1). VAL &E(2). VAL are left & right children of this node.

Similarly, Node (∗, E(1). VAL, E(2). VAL) will make the syntax as −

Function UNARY (−, E(1). VAL)will make a node – (unary minus) & E(1). VAL will be the only child of it.

Function LEAF (id) will create a Leaf node with label id.

Example2 − Construct a syntax tree for the expression.

a = b ∗ −c + d

Solution

Example3 − Construct a syntax tree for a statement.

If a = b then b = 2 * c

Solution

Example4 − Consider the following code. Draw its syntax Tree

If x > 0 then x = 2 * (a + 1) else x = x + 1.

Example5 − Draw syntax tree for following arithmetic expression a * (b + c) – d /2. Also, write given expression in postfix form.

Postfix Notation

a b c + * d 2 / -

Updated on: 26-Oct-2023

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements