GATE / CS ARCHIVE

GATE CSE 1997 / QUESTION 22

Unambiguous grammar for a Pascal subset

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

GATE 1997, Q22 5 marks · Descriptive
Report issue

Parsing & Syntax Analysis

Question 22, GATE 1997: A language L is a subset of Pascal with expressions using only + and <, assignment statements, while statements, and compound statements begin ... end. Give an unambiguous grammar. The source does not specify lexical details, empty statements, or a trailing-semicolon convention.
Tap to enlarge
Answer & solution

Answer: Use separate addition/comparison levels, one comparison per expression, and explicit statement/block productions. (no official key was published)

Here is one unambiguous grammar under the conventional choices that + binds more tightly than <, + associates to the left, and < is nonassociative. The lexer supplies tokens id and num; reserved words are distinct tokens, and := is assignment. Start symbol S denotes one statement.

S → id := E | while E do S | begin L end
L → S R
R → ; S R | ε
E → A | A < A
A → A + P | P
P → id | num | ( E )

The grammar deliberately uses nonempty compound statements with semicolons between statements, not after the last one. If empty blocks are required, add the separate production S→begin end. If an optional trailing semicolon is required, replace R by R→ε | ; T and T→ε | S R. These are explicit syntax extensions, not facts supplied by the question.

The expression hierarchy enforces a unique outer operator structure. An unparenthesized < must be the single comparison at the E level, so a+b<c+d parses as (a+b)<(c+d), and a<b<c is rejected unless parentheses explicitly group a comparison. Left recursion at A gives (a+b)+c, not a+(b+c). Parentheses delimit a complete nested expression. At statement level, id, while and begin select disjoint alternatives. The keyword do separates a while condition from its body; matching begin/end delimit a compound body, and semicolons separate its statements. There is no if/else construct and hence no dangling-else ambiguity.

For example, while x<y+1 do begin x:=x+1; y:=y+2 end has a unique parse: its loop body is the entire block, containing two assignments. Static type rules, such as requiring a Boolean while condition and compatible assignment types, belong to semantic analysis rather than this context-free grammar. The source does not uniquely determine every optional Pascal syntax feature; the stated conventions make this proposed grammar precise.

Original paper, page 9