Detailed SDT with Postfix Output and DAG Construction:
Below are the grammar productions augmented with semantic rules:
1. Production: E → E + T
E → E1 + T
{
// Check if a '+' node with E1.node and T.node already exists
key = ("+", E1.node, T.node)
if (symbol_table.contains(key)) {
E.node = symbol_table.get(key)
} else {
// Create a new '+' node
E.node = new DAGNode("+", E1.node, T.node)
symbol_table.put(key, E.node)
}
// Postfix output: E1 T +
emit(E1.node, T.node, "+")
}
2. Production: E → T
E → T
{
E.node = T.node
}
3. Production: T → T * F
T → T1 * F
{
// Check if a '*' node with T1.node and F.node already exists
key = ("*", T1.node, F.node)
if (symbol_table.contains(key)) {
T.node = symbol_table.get(key)
} else {
// Create a new '*' node
T.node = new DAGNode("*", T1.node, F.node)
symbol_table.put(key, T.node)
}
// Postfix output: T1 F *
emit(T1.node, F.node, "*")
}
4. Production: T → F
T → F
{
T.node = F.node
}
5. Production: F → ( E )
F → ( E )
{
F.node = E.node
}
6. Production: F → id
F → id
{
// Create a leaf node for the identifier
F.node = new DAGNode(id)
// Postfix output: id
emit(id)
}
7. Production: F → num
F → num
{
// Create a leaf node for the number
F.node = new DAGNode(num)
// Postfix output: num
emit(num)
}