GATE / CS ARCHIVE

GATE CSE 1993 / QUESTION 25(b)

Parse a for-loop block

Compiler Design · Parsing & Syntax Analysis · Full GATE CSE 1993 paper

GATE 1993, Q25(b) Descriptive
Report issue

Parsing & Syntax Analysis

Question 25(b), GATE 1993: Using S→id:=E | for id:=E to E do S | begin L end and L→S | S;L, draw the parse tree for: for j:=2 to 10 do begin x:=expr1; y:=expr2 end.
Question 25(b), GATE 1993: Using S→id:=E | for id:=E to E do S | begin L end and L→S | S;L, draw the parse tree for: for j:=2 to 10 do begin x:=expr1; y:=expr2 end.
Question 25(b), GATE 1993: Using S→id:=E | for id:=E to E do S | begin L end and L→S | S;L, draw the parse tree for: for j:=2 to 10 do begin x:=expr1; y:=expr2 end.
Tap to enlarge
Answer & solution

Answer: Root loop S, body block S, two assignment statements linked by L→S;L. (no official key was published)

The outermost construct is the for production, not a sequencing block. Its body is one statement S expanded as begin L end. Inside that block the list has two assignments, so its first L uses S;L and its final L uses S.

S
├─for
├─id(j)
├─:=
├─E(2)
├─to
├─E(10)
├─do
└─S
  ├─begin
  ├─L
  │ ├─S
  │ │ ├─id(x)
  │ │ ├─:=
  │ │ └─E(expr1)
  │ ├─;
  │ └─L
  │   └─S
  │     ├─id(y)
  │     ├─:=
  │     └─E(expr2)
  └─end

Reading leaves left to right gives exactly the requested token sequence. The E subtrees are abbreviated because the expression grammar was stipulated as already defined; 2 and 10 are constant expressions and expr1/expr2 stand for their expression subtrees. The semicolon separates the two assignments, while begin/end make both assignments part of a single loop body.

Original paper, page 14