SDT for Control statements:
Syntax Directed Translation (SDT) for control flow statements using a
simple grammar that includes if-else statements and while loops. Here's
the grammar
S → if (expr) S else S { print("if (expr)") }
| while (expr) S { print("while (expr)") }
| other_statement { print("other_statement") }
In this grammar:
if and while are control flow keywords.
expr represents an expression that evaluates to a boolean value.
S represents a statement, which can be an if-else statement, a while loop,
or another statement.
Now, let's associate semantic actions with each production:
1.if (expr) S else S { print("if (expr)") }:
Semantic Action: Generate code for an if-else statement.
Example: if (expr) S1 else S2 would translate to generate_code(expr);
generate_code(S1); generate_code(S2); print("if (expr)");
while (expr) S { print("while (expr)") }:
Semantic Action: Generate code for a while loop.
Example: while (expr) S would translate to generate_code(expr);
generate_code(S); print("while (expr)");
other_statement { print("other_statement") }:
Semantic Action: Generate code for any other statement.
Example: other_statement would simply translate to
print("other_statement");
if (x > 0) {
print("x is positive");
} else {
print("x is non-positive");
}
while (x > 0) {
x = x - 1;
print("Decremented x: " + x);
}
Parsing this sequence according to the grammar produces a parse tree.
During the parsing process, semantic actions associated with each
production rule are executed.
Parse Tree:
S
/ / \
if while other_statement
/ \ | |
expr S expr "other_statement"
/ \ |
"x > 0" S other_statement
/ \
"x is positive" "x is non-positive"
Semantic Actions Execution:
generate_code("x > 0");
generate_code(S1); print("if (expr)");
generate_code("x > 0");
generate_code(S2); print("while (expr)");
print("x is positive");
print("x is non-positive");
print("Decremented x: " + x)