
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
NITK SURATHKAL
CS 304 โ COMPILER DESIGN LAB
V Semester B-Tech S1 Section
Week โ 6 Exercises
Date: 03. 09. 2024
Time: 2:15 pm to 4:15 pm Max Marks: 30
1. Consider the following expression:
n = n>6+3 || !2+3 || n = !c.n*!3 || 1+3==4
To ensure correct evaluation of this expression, the declaration of precedence
directives (such as '%left', '%nonassoc', and '%right') is essential. For example, the
DOT operator should have the highest precedence, while the ASSIGN operator,
which is right-associative, should have the lowest precedence. The PLUS and MINUS
operators, which are left-associative, should share equal precedence. Additionally, the
EQUALITY and GREATER operators, which are non-associative, should also have
equal precedence, though their precedence levels differ from those of PLUS and
MINUS. Although the NOT operator is unary, for precedence ordering purposes, it
can be treated as right-associative.
Tasks: a) Write a Context-Free Grammar (CFG) for the above expression. b)
Implement a Lex and Yacc program to recognize the above expression using the CFG
from (a). The grammar should be transformed as necessary to eliminate conflicts. The
output should indicate whether the expression is valid or invalid based on the given
CFG.
2. Consider the syntax of a programming language construct, such as a while-loop:
while (condition)
begin
statement;
โฆ
end
In this construct, 'while', 'begin', and 'end' are keywords. The 'condition' is a single
comparison expression (e.g., 'x == 20'), and the 'statement' represents an assignment
to a location with the result of a single arithmetic operation (e.g., 'a = 10 * b').
Tasks: a) Write a CFG for the above construct. b) Implement a Lex and Yacc
program to recognize the above construct using the CFG from (a). The grammar
should be transformed as necessary to eliminate conflicts. The output should indicate
whether the test case is valid or invalid based on the given CFG.