Download Parsing Homework Solutions: While Loop Grammar and LR(1) Parse Table - Prof. Qing Yi and more Assignments Computer Science in PDF only on Docsity! Homework 3: Parsing (30pts) solution 1. Write a context-free grammar describing the syntax of the while loop in the C lan- guage. In particular, each while loop should start with the โwhileโ keyword, followed by a conditional expression surrounded by a pair of โ()โ, and then followed by the body of the while loop. The terminals of your grammar include WHILE (the "while" keyword) ID ( variable names) VALUE (integer/floating point values) ( ) { } (parentheses and braces) && || ! (the boolean operators) < <= > >= == (the comparison operators) = (the assignment operator) ; (semicolon) + - * / (the arithmetic operators) Using the above terminals, you should define nonterminals that model the concepts of while loops, assignment statements, and expressions respectively. As a test case, your grammar should accept while (!(a == b)) { a = a - 1; b = b + 1; c = (a > b); } but should reject 3 = n + b; (not a while loop) or while (3) (missing body of the loop) Solution: <whilestmt> ::= WHILE ( <exp> ) <stmt> <exp> ::= <exp> && <exp> | <exp> || <exp> | ! <exp> | <exp < <exp> | <exp> <= <exp> | <exp> > <exp> | <exp> >= <exp> | <exp> == <exp> | <exp> * <exp> | <exp> / <exp> | <exp> + <exp> | <exp> - <exp> | <exp> = <exp> 1 | ( <exp> ) | ID | VALUE <stmt> ::= โ;โ | <exp> โ;โ | โ{โ <stmts> โ}โ | <whilestmt> <stmts> ::= epsilon | <stmts> <stmt> 2. (Sec3.3, Problem1) The following grammar is not suitable for a top-down predictive parser. Identify the problem and correct it by rewriting the grammar. Show that your grammar satisfies LL(1) condition by building a LL(1) parse table for it. L ::= R a | Q b a R ::= a b a | c a b a | R b c Q ::= b b c | b c Solution: In the above grammar, the productions for non-terminal R are left-recursive, and the productions for non-terminal Q have a common prefix that need to be fac- tored. After eliminating left-recursion and left-factoring transformation, we obtain the following grammar. L ::= R a | Q b a R ::= a b a Rโ | c a b a Rโ Rโ ::= b c Rโ | Q ::= b Qโ Qโ ::= b c | c The following lists the set of terminals that can start a string derived from each non- terminal. In the final LL(1) parse table, a non-terminal N should be have at least one production under the colume of each terminal that is a member of First(N). First(L) {a,b,c} First(R) {a, c} First(Rโ) {b, } First(Q) { b } First(Qโ) { b,c } The following lists the set of terminals that can start each production. In the final LL(1) parse table, a production P should be placed under the colume of each terminal that is a member of First(P). First(L ::= R a) {a, c} First(L ::= Q b a) { b } First(R ::= a b a Rโ) { a } First(R ::= c a b a Rโ) { c } First(Rโ ::= b c Rโ) { b } First(Q ::= b Qโ) { b } First(Qโ ::= b c) { b } First(Qโ ::= c) { c } 2