LL(1)预测表实战:下一项已经是后面的词元,为什么此时反而应该选择空产生式
规则S推出A再接b,而A可以推出任意多个a或空串。输入第一个词元就是b时,解析器仍应选择S的这条规则,再让A消失。只看右侧第一个符号名字,既不知道输入会以什么开头,也不知道何时该选空产生式。
LL(1)把这些决定提前编译进预测表。行是当前非终结符,列是下一个输入词元,每格最多放一条产生式。本文自动计算FIRST与FOLLOW、拒绝表格冲突,再用一个显式栈识别完整词元序列。
AI模型生成的概念示意:前方词元照亮空白格并引向栈,透明薄片表达空规则;格子、片数与连线不是实际预测表。
完整程序与实际输出
将以下完整源码保存为demo.py,执行python3 demo.py。本次在Linux、CPython 3.12.14实际运行,退出码0、标准错误为空;只使用标准库与本地教学数据。
from itertools import product
class LL1:
def __init__(self, grammar, start, terminals):
if type(grammar) is not dict or not 1 <= len(grammar) <= 16:
raise ValueError("one to sixteen nonterminals required")
if type(terminals) not in (set, tuple, list) or len(terminals) > 32:
raise ValueError("bounded terminal collection required")
names = list(grammar) + list(terminals)
if any(type(s) is not str or not s or s == "$" for s in names):
raise ValueError("nonempty names required; dollar is reserved")
if start not in grammar or set(grammar) & set(terminals):
raise ValueError("start and disjoint symbol classes required")
self.start, self.terminals = start, set(terminals)
self.rules = []
for lhs, alternatives in grammar.items():
if type(alternatives) not in (list, tuple):
raise ValueError("rule alternatives must be a sequence")
for rhs in alternatives:
if (type(rhs) is not tuple or len(rhs) > 8
or any(type(s) is not str or s not in names for s in rhs)):
raise ValueError("right-hand side has an unknown symbol")
self.rules.append((lhs, rhs))
if len(self.rules) > 64:
raise ValueError("rule budget exceeded")
self.first = {name: set() for name in grammar}
self.first.update({name: {name} for name in terminals})
def first_of(sequence):
result = set()
for symbol in sequence:
result |= self.first[symbol] - {None}
if None not in self.first[symbol]:
return result
return result | {None}
changed = True
while changed:
changed = False
for lhs, rhs in self.rules:
additions = first_of(rhs) - self.first[lhs]
changed |= bool(additions)
self.first[lhs] |= additions
self.follow = {name: set() for name in grammar}
self.follow[start].add("$")
changed = True
while changed:
changed = False
for lhs, rhs in self.rules:
for i, symbol in enumerate(rhs):
if symbol not in grammar:
continue
suffix = first_of(rhs[i+1:])
wanted = suffix - {None}
if None in suffix:
wanted |= self.follow[lhs]
additions = wanted - self.follow[symbol]
changed |= bool(additions)
self.follow[symbol] |= additions
self.table = {}
for lhs, rhs in self.rules:
starts = first_of(rhs)
lookaheads = starts - {None}
if None in starts:
lookaheads |= self.follow[lhs]
for token in sorted(lookaheads):
cell = lhs, token
if cell in self.table and self.table[cell] != rhs:
raise ValueError("LL(1) conflict at " + repr(cell))
self.table[cell] = rhs
def accepts(self, tokens):
if (type(tokens) is not tuple or len(tokens) > 128
or any(type(t) is not str or t not in self.terminals for t in tokens)):
raise ValueError("at most 128 declared tokens required")
incoming, stack, cursor = tokens + ("$",), ["$", self.start], 0
for unused in range(10000):
if not stack:
return cursor == len(incoming)
top, lookahead = stack.pop(), incoming[cursor]
if top in self.terminals or top == "$":
if top != lookahead:
return False
cursor += 1
else:
rhs = self.table.get((top, lookahead))
if rhs is None:
return False
stack.extend(reversed(rhs))
raise RuntimeError("parse step budget exhausted")
grammar = {"S": (("A", "b"),), "A": (("a", "A"), ())}
parser = LL1(grammar, "S", {"a", "b"})
print("FIRST(S):", sorted(parser.first["S"]))
print("FOLLOW(A):", sorted(parser.follow["A"]))
print("table at (S,b):", parser.table["S", "b"])
print("table at (A,b):", parser.table["A", "b"])
for text in ("b", "aaab", "", "aba", "bb"):
print(repr(text), parser.accepts(tuple(text)))
checks = 0
for size in range(9):
for chars in product("ab", repeat=size):
text = "".join(chars)
expected = text.endswith("b") and set(text[:-1]) <= {"a"}
assert parser.accepts(chars) == expected
checks += 1
print("independent a-star-then-b comparisons:", checks)
balanced = LL1({"S": (("(", "S", ")", "S"), ())}, "S", {"(", ")"})
checks = 0
for size in range(9):
for chars in product("()", repeat=size):
depth, expected = 0, True
for char in chars:
depth += 1 if char == "(" else -1
expected &= depth >= 0
expected &= depth == 0
assert balanced.accepts(chars) == expected
checks += 1
print("independent bracket-depth comparisons:", checks)
chain = LL1({"S": (("A", "B", "c"),), "A": (("a",), ()), "B": (("b",), ())},
"S", {"a", "b", "c"})
checks = 0
for size in range(6):
for chars in product("abc", repeat=size):
assert chain.accepts(chars) == ("".join(chars) in {"c", "ac", "bc", "abc"})
checks += 1
print("nullable-prefix chain comparisons:", checks)
for grammar in ({"S": (("a", "b"), ("a", "c"))},
{"S": (("A", "a"),), "A": (("a",), ())}):
try:
LL1(grammar, "S", {"a", "b", "c"})
except ValueError as error:
print("grammar rejected:", error)
else:
raise AssertionError("conflicting table accepted")
try:
parser.accepts(("$",))
except ValueError as error:
print("input rejected:", error)下面是这份程序的实际标准输出,不是需要另行执行的命令:
FIRST(S): ['a', 'b']
FOLLOW(A): ['b']
table at (S,b): ('A', 'b')
table at (A,b): ()
'b' True
'aaab' True
'' False
'aba' False
'bb' False
independent a-star-then-b comparisons: 511
independent bracket-depth comparisons: 511
nullable-prefix chain comparisons: 364
grammar rejected: LL(1) conflict at ('S', 'a')
grammar rejected: LL(1) conflict at ('A', 'a')
input rejected: at most 128 declared tokens required空产生式写成空元组,不是一个空白词元
grammar字典键是非终结符,terminals显式列出终结符,两类名字不能重叠。右侧是符号元组,空元组()表示不产生任何输入;如果把它写成含一个空字符串的元组,就已经变成另一种对象。
美元符号保留作输入结束标记,调用方不能把它声明为普通符号或作为实际输入提交。这个约定保证栈底标记与输入末尾只能在内部统一出现。
FIRST从左往右穿过全部可空前缀
FIRST描述某个符号或符号串能够产生的首个终结符。本文用None额外表示可推出空串;引用讲义把NULLABLE单独保存,二者是同一份信息的不同组织。
first_of遍历右侧,把当前符号的非空FIRST加入结果。如果当前符号不能推出空,就停下;如果能空,继续看后面的符号。走到末尾才加入None,因此空右侧自然可空。
集合只增加,反复传播到稳定
每个非终结符的FIRST起初为空,终结符的FIRST只含自己。对每条产生式计算右侧FIRST,并合入左侧集合,直到没有任何新增元素。
本轮更新可以被后面的规则立即使用,也可能等下一轮才沿其他规则传播;只要持续迭代到不再变化,结果不会因为字典顺序而停在半路。有限符号集合和只增加的更新保证终止。
FOLLOW追踪的是某个非终结符之后能出现什么
在X推出αAβ中,β能产生的非空首符号都可以跟在A后面。若β还可以全空,A后面也可以直接跟X后面允许的符号,所以FOLLOW(X)必须传播给FOLLOW(A)。
开始符号的FOLLOW先加入结束标记。其余集合从空开始反复合并;FOLLOW里不放None,因为“没有下一个词元”由结束标记表达,而不是把空串当作实际输入。
填表时,可空规则要看FOLLOW
对产生式X推出γ,把它放到γ所有非空FIRST对应的列。如果γ可空,还要放到FOLLOW(X)里的各列。后一条才解释解析器为什么看到某个后续词元时,可以选择不读任何内容。
样本FIRST(S)为a、b,FOLLOW(A)只有b。表格(S,b)放的是(A,b),而(A,b)放的是空元组。解析器没有跳过S,也没有提前消耗b,只是先按表让A展开为空。
表格冲突必须保留为冲突,不能后写覆盖前写
两条不同右侧都想占同一个单元格,说明仅看一个词元无法决定。代码在插入第二条时抛出包含行列的ValueError,绝不让字典赋值静默覆盖。
S推出ab或ac时,两个FIRST都含a;这是FIRST/FIRST冲突。S推出Aa,A推出a或空时,A的普通规则和空规则都会占(A,a),这是FIRST/FOLLOW冲突。程序分别构造并拒绝两类情况。
不属于LL(1),不等于一定有歧义
ab与ac这两个不同字符串各自只有一条推导,但刚看到a时仍选不出规则。可把共同前缀提出来,改成S推出aT、T推出b或c,让下一步再决定。
有冲突时,不能仅凭文法文本无歧义就强行选第一条。也不能把“当前文法不是LL(1)”说成整个语言不可能用某种LL(1)文法描述;改写文法与换解析算法是不同选择。
栈顶符号决定匹配还是展开
栈最初保存结束标记与开始符号,右端是栈顶。弹出终结符时要求它等于当前输入词元,然后向前读一项;弹出非终结符时只按行列查表,把右侧倒序压栈。
倒序压栈使右侧最左符号下一次先被处理。空元组什么都不压,但查表返回None才表示缺项,所以代码用is None,不能把合法空元组的假值误认成语法错误。
栈空与输入结束必须同时成立
一个合法前缀已经匹配,不代表后面的多余词元也合法。结束标记参与普通匹配,最后还检查游标确实超过内部结束项;样本aba和bb都会被拒绝。
本文只返回布尔识别结果,不创建AST,也没有词法器。输入tuple中的每个字符串已经是一个终结符词元,多字符词元名是允许的;对原始源码的分词、位置与错误恢复需要在外层另行设计。
三个语言裁判都不读取预测表
a的任意次重复后恰接一个b,用字符串末尾及前缀集合检查,穷尽长度零到八共511份。配对括号语言也穷尽511份,由独立深度计数判断所有前缀非负且最终归零。
第三套可空链S推出ABc,A与B分别可以空或产生a、b,语言恰为c、ac、bc、abc。枚举三字母长度零到五共364份,直接与这四个字符串的集合比较,覆盖连续多个可空前缀。
建表成本与解析成本分开理解
FIRST与FOLLOW是在有限集合上做固定点传播,朴素实现每轮扫描全部规则及后缀,适合这里的小文法。解析阶段每次只查询一个格子,不回溯尝试其他产生式。
对固定的良构LL(1)文法,解析工作与展开的语法树规模同阶;通常按输入长度线性分析,但不能把构建文法集合的成本也算作常数。示例限制十六个非终结符、六十四条规则、128个词元和一万步解析预算。
预算耗尽抛RuntimeError,与语法拒绝的False分开。本实现不自动消除左递归、提取左因子或处理含冲突文法;这些都是改变语法或采用另一类解析器的工作。
参考资料
资料与运行核查日期:2026年10月7日。源码、解释及教学测试由本文独立组织;有限测试不等于生产性能评测。
Cornell CS4120作者讲义:Top-down parsing、NULLABLE/FIRST/FOLLOW及预测表冲突


