Past exam question: 2082 Chaitra (Regular), Q16
Open in the Padhaiko appHow syntax analyzer helps to check whether the particular block of code is syntactically correct or not. Explain with suitable example.
Solution
Mechanism of Syntax Checking Using CFG: The syntax analyzer (parser) takes the token stream generated by the lexical analyzer and verifies whether it conforms to the structural rules of the programming language defined by a Context-Free Grammar (CFG):
- Grammar Verification: The parser attempts to construct a derivation or parse tree from the grammar's start symbol to the token sequence.
- Validation: If a complete parse tree can be successfully built using top-down (e.g., LL) or bottom-up (e.g., LR/LALR) parsing, the code block is deemed syntactically correct.
- Error Reporting and Recovery: If an unexpected token occurs that cannot be reduced or expanded according to the parsing table, the parser reports a syntax error with line/column coordinates and applies error recovery strategies (panic mode or phrase-level recovery).
Concrete Example with Expression Grammar: Consider a simple statement grammar:
Case 1: Syntactically Correct Statement ():
- Token stream:
id(=x) assign id(=a) plus id(=b) mult num(=2) semi. - The parser successfully derives:
- All tokens match grammar productions respecting precedence ( over ), confirming syntactic validity.
Case 2: Syntactically Incorrect Statement ():
- Token stream:
id(=x) assign id(=a) plus mult id(=b) semi. - After parsing
a +, the grammar expects an operand (such asid,num, or(), but encounters the operator*. - Because no production allows two consecutive binary operators , the parsing table hits an error entry and flags: "Syntax error: unexpected token '' after '+' at line N"*.
The syntax analyzer verifies code against a Context-Free Grammar by constructing a parse tree. For valid statements like x = a + b * 2;, complete derivations succeed; for invalid constructs like x = a + * b;, unexpected token transitions trigger syntax error diagnosis.