First, we need to construct the LL(1) parsing table based on the grammar above:
+-------+-----+-----+-----+-----+-----+-----+
| | d | + | * | ( | ) | $ |
+-------+-----+-----+-----+-----+-----+-----+
| E | 1 | | | 1 | | |
+-------+-----+-----+-----+-----+-----+-----+
| E' | | 2 | | | 3 | 3 |
+-------+-----+-----+-----+-----+-----+-----+
| T | 4 | | | 4 | | |
+-------+-----+-----+-----+-----+-----+-----+
| T' | | 6 | 5 | | 6 | 6 |
+-------+-----+-----+-----+-----+-----+-----+
| F | 8 | | | 7 | | |
+-------+-----+-----+-----+-----+-----+-----+
Next, we will implement the parse algorithm:
define the LL(1) parsing table
table = {
('E', 'd'): ['T', 'E''],
('E', '('): ['T', 'E''],
('E'', '+'): ['+', 'T', 'E''],
('E'', ')'): ['λ'],
('E'', ''): ['λ'],
('T', 'd'): ['F', 'T\''],
('T', '('): ['F', 'T\''],
('T\'', '+'): ['λ'],
('T\'', '*'): ['*', 'F', 'T\''],
('T\'', ')'): ['λ'],
('T\'', ''): ['λ'],
('F', 'd'): ['d'],
('F', '('): ['(', 'E', ')']
}
define stack and input sequence
stack = ['$']
input_seq = input()
function to print current stack and input sequence
def print_stack_and_input():
print('Stack: ', stack)
print('Input Sequence: ', input_seq)
start parsing
while True:
print_stack_and_input()
top = stack[-1]
curr_input = input_seq[0]
if top == '′andcurrinput==′':
print('Parsing complete')
break
elif top == curr_input:
stack.pop()
input_seq = input_seq[1:]
elif top in table and curr_input in table[top]:
# replace top of stack with production rule
stack.pop()
for symbol in reversed(table[top][curr_input]):
if symbol != 'λ':
stack.append(symbol)
else:
print('Error: Invalid input sequence')
break
If the input string is correct, the program should output the derivation steps. For example, for the input string "d+d*d", the program should output:
Stack: ['′]InputSequence:d+d∗d', 'E']
Input Sequence: d+dd
Stack: ['', 'E'', 'T'']
Input Sequence: +dd
Stack: ['', 'E'', 'T', '(', 'E', ')', 'd', 'E'', 'T', 'F', 'd', 'E'', 'T', 'T'', 'F', 'd', 'E'', 'T'', 'F', 'd', 'E'', 'T'', 'd', 'E'']
Input Sequence: +dd', 'E'', 'T']
Input Sequence: +dd', 'E'', 'T'', 'd']
Input Sequence: ']
Input Sequence: ']
Input Sequence: *d
Stack: ['
Stack: ['
Stack: ['
Stack: ['
Stack: ['
Stack: ['
Stack: ['
Stack: ['
Stack: ['
Parsing complete
In this case, the final derivation is:
E -> E' -> T E' -> T' F E' -> F T' F E' -> d T' F E' -> d F E' -> d + T F E' -> d + ( E ) F E' -> d + ( E ) * F E' -> d + ( d ) * F E' -> d + ( d ) * d E' -> d + ( d ) * d