以下是针对LL(1)文法判断的主要步骤的一些代码实现示例:
- 消除左递归,将文法变为A->Bb|c的形式。
def eliminate_left_recursion(grammar):
# 在每个左递归的非终结符号中,加入新的非终止符号和产生式来消除左递归
new_grammar = grammar
for non_terminal in grammar:
productions = grammar[non_terminal]
alpha_productions = []
beta_productions = []
for production in productions:
if production[0] == non_terminal:
alpha_productions.append(production[1:])
else:
beta_productions.append(production)
if len(alpha_productions) > 0:
new_non_terminal = non_terminal + '_' # 新的非终止符号
while new_non_terminal in new_grammar:
new_non_terminal += '_'
new_grammar[new_non_terminal] = [alpha + new_non_terminal for alpha in alpha_productions] + ['ε'] # 新的产生式
new_grammar[non_terminal] = [beta + new_non_terminal for beta in beta_productions]
return new_grammar
- 提取左公因子,将文法变为A->aB|aC等形式。
def extract_left_factor(grammar):
# 对于每个非终止符,找出其所有产生式中的最长公共前缀,然后提取出来作为新的非终止符和产生式
new_grammar = grammar
for non_terminal in grammar:
productions = grammar[non_terminal]
groups = {} # 找到具有相同前缀的产生式
for production in productions:
key = production[0]
if key in groups:
groups[key].append(production[1:])
else:
groups[key] = [production[1:]]
for key in groups:
if len(groups[key]) > 1: # 对有多个产生式的,提取左公因子
new_non_terminal = non_terminal + '_' # 新的非终止符号
while new_non_terminal in new_grammar:
new_non_terminal += '_'
new_grammar[new_non_terminal] = []
prefix = [key] + [new_non_terminal] # 新的前缀
for production in groups[key]:
if len(production) > 0:
new_grammar[new_non_terminal].append(production)
else:
new_grammar[new_non_terminal].append(['ε']) # 处理空串
if len(new_grammar[new_non_terminal]) == len(groups[key]):
new_grammar[new_non_terminal] = [prefix + production for production in new_grammar[new_non_terminal]]
else:
new_grammar[new_non_terminal] = prefix + ['' if production == ['ε'] else production for production in new_grammar[new_non_terminal]]
for production in new_grammar[non_terminal]:
if len(production) > 0 and production[0] == key:
new_production = [new_non_terminal] + production[1:]
new_grammar[non_terminal].append('' if new_production == ['ε'] else new_production)
new_grammar[non_terminal] = [production for production in new_grammar[non_terminal] if production[0] != key]
return new_grammar
- 构建First集,计算文法符号的First集。
def calc_first(grammar, symbols, first_sets):
for symbol in symbols:
if symbol in first_sets: # 已计算过的跳过
continue
first_sets[symbol] = set()
if symbol in grammar: # 对于一个文法符号X,如果X属于N,直接将First(X)中的所有元素加入First(X)中
productions = grammar[symbol]
for production in productions:
first_sets[symbol] |= calc_first(grammar, production, first_sets)
elif symbol: # 如果X不是非终止符,而是一个终止符且X不为"ε",则First(X) = {X}
first_sets[symbol].add(symbol)
return first_sets[symbol]
- 构建Follow集,计算文法符号的Follow集。
def calc_follow(grammar, non_terminal, follow_sets, first_sets):
if non_terminal in follow_sets: # 已计算过的跳过
return follow_sets[non_terminal]
follow_sets[non_terminal] = set()
if non_terminal == get_start_symbol(grammar): # 如果文法符号是文法的开始符号
follow_sets[non_terminal].add('$') # Follow(S) = {$}
for symbol in grammar:
productions = grammar[symbol]
for production in productions:
for i, item in enumerate(production):
if item == non_terminal: # 对A->αBβ,其中B为非终止符
if i == len(production) - 1: # 如果文法符号是最后一个,即β为空,Follow(B) = Follow(A)
follow_sets[non_terminal] |= calc_follow(grammar, symbol, follow_sets, first_sets)
else:
remains = production[i+1:] # β中剩下的符号
first_set = get_first_set_of_production(grammar, remains, first_sets)
follow_sets[non_terminal] |= first_set
if 'ε' in first_set: # 如果First(β)中包含"ε",Follow(B) = Follow(A) ∪ Follow(α)
follow_sets[non_terminal] |= calc_follow(grammar, symbol, follow_sets, first_sets)
return follow_sets[non_terminal]
- 构建预测分析表,填充分析表中的内容,并判断是否冲突。
def build_predictive_table(grammar, first_sets, follow_sets):
predictive_table = {}
for non_terminal in grammar:
productions = grammar[non_terminal]
for i, production in enumerate(productions):
first_set = get_first_set_of_production(grammar, production, first_sets) # 计算First集
if 'ε' in first_set:
follow_set = follow_sets[non_terminal] # 如果产生式包含“ε”,加入Follow集
for symbol in follow_set:
if symbol not in predictive_table:
predictive_table[symbol] = {}
else:
if non_terminal in predictive_table[symbol]:
raise ValueError(f'Error found! Conflict occurs with {symbol} and {non_terminal}.')
predictive_table[symbol][non_terminal] = i
else:
for symbol in first_set:
if symbol not in predictive_table:
predictive_table[symbol] = {}
else:
if non_terminal in predictive_table[symbol]:
raise ValueError(f'Error found! Conflict occurs with {symbol} and {non_terminal}.')
predictive_table[symbol][non_terminal] = i
return predictive_table
- 对文法进行验证,进行推导和分析,检查是否符合LL1文法的规则。
def parse(grammar, predictive_table, source_code):
stack = ['#', get_start_symbol(grammar)]
terminals = get_terminals(grammar)
current_symbol = stack[-1]
i = 0
while current_symbol != '#' and i < len(source_code):
if current_symbol in grammar:
if source_code[i] in terminals:
try:
production_index = predictive_table[source_code[i]][current_symbol]
production = grammar[current_symbol][production_index]
stack.pop()
for j in reversed(range(len(production))):
if production[j] != 'ε':
stack.append(production[j])
except KeyError:
raise ValueError(f"Error found at position {i+1}! Unexpected token '{source_code[i]}'.")
else:
raise ValueError(f"Error found at position {i+1}! Unexpected token '{source_code[i]}'.")
elif current_symbol == source_code[i]:
stack.pop()
i += 1
else:
raise ValueError(f"Error found at position {i+1}! Unexpected token '{source_code[i]}'.")
current_symbol = stack[-1]
if current_symbol == '#' and i == len(source_code):
return 'pass'
elif current_symbol != '#' and i == len(source_code):
raise ValueError(f"Error found at end of input! Missing '{current_symbol}'.")
else:
raise ValueError(f"Error found at position {i+1}! Unexpected end of input.")
注意:以上代码仅是一些示例,实现方式可能存在差异,具体实现需根据具体情况进行调整。