要判断一个文法是否是 LL(1) 文法,需要进行以下步骤:
- 对于文法中的每个产生式,计算其 FIRST 集。
- 对于文法中的每个非终结符,计算其 FOLLOW 集。
- 对于每个产生式 A -> α,计算 FOLLOW(A) 与 FIRST(α) 是否有交集,如果有,则这个文法不是 LL(1) 文法。
- 如果文法中出现了空产生式,则需将其处理后再进行判断(例如使用 FOLLOW 集替换空产生式),否则可能导致得到不正确的结果。
下面是一个 Python 实现示例:
def compute_first_set(symbol, productions, first_sets):
if symbol in first_sets:
return first_sets[symbol]
first_set = set()
for production in productions[symbol]:
first_set |= get_first_set(production, productions, first_sets)
first_sets[symbol] = first_set
return first_set
def get_first_set(production, productions, first_sets):
first_set = set()
if production == 'ε':
first_set.add('ε')
elif production[0].isupper():
first_set |= compute_first_set(production[0], productions, first_sets)
i = 1
while i < len(production) and ('ε' in first_sets[production[i - 1]]):
first_set |= (first_sets[production[i - 1]] - {'ε'})
i += 1
if i == len(production) and ('ε' in first_sets[production[i - 1]]):
first_set.add('ε')
else:
first_set.add(production[0])
return first_set
def compute_follow_set(symbol, productions, first_sets, follow_sets, start_symbol):
if symbol in follow_sets:
return follow_sets[symbol]
follow_set = set()
if symbol == start_symbol:
follow_set.add('$')
for non_terminal, production_list in productions.items():
for production in production_list:
if symbol in production:
symbol_index = production.index(symbol)
if symbol_index == len(production) - 1:
if non_terminal != symbol:
follow_set |= compute_follow_set(non_terminal, productions, first_sets, follow_sets, start_symbol)
else:
follow_set |= get_first_set(production[symbol_index + 1:], productions, first_sets)
if 'ε' in follow_set:
follow_set.remove('ε')
follow_set |= compute_follow_set(non_terminal, productions, first_sets, follow_sets, start_symbol)
follow_sets[symbol] = follow_set
return follow_set
def is_LL1_grammar(productions, start_symbol):
# Calculate FIRST sets for each symbol
first_sets = {}
follow_sets = {}
for non_terminal in productions:
compute_first_set(non_terminal, productions, first_sets)
follow_sets[non_terminal] = set()
follow_sets[start_symbol].add('$')
for non_terminal in productions:
compute_follow_set(non_terminal, productions, first_sets, follow_sets, start_symbol)
# Check each production for LL(1) conflict
for non_terminal, production_list in productions.items():
prod_dict = {}
for production in production_list:
first_set = get_first_set(production, productions, first_sets)
for terminal in first_set:
if terminal in prod_dict:
return False
prod_dict[terminal] = production
if 'ε' in first_set:
for terminal in follow_sets[non_terminal]:
if terminal in prod_dict:
return False
prod_dict[terminal] = production
return True
代码中,输入参数 productions 是如下形式的字典(键为非终结符,值为对应的产生式列表):
{
'S': ['AC', 'BC'],
'A': ['aA', 'b'],
'B': ['bB', 'cB', 'ε'],
'C': ['cC', 'd'],
}
函数会返回一个布尔值,表示文法是否是 LL(1) 文法。
注意,这里的实现假设输入的文法符合以下要求:
- 所有非终结符都是大写字母;
- 所有终结符要么是小写字母,要么是
ε;
- 每个非终结符的所有产生式都用 list 表示;
- 如果存在
ε 产生式,则 ε 在每个非终结符的产生式中必须独立成一项(即不能出现 A -> εAB 这样的形式)。