Algorithm查找第一集:
Given a grammar with the rules A1 → w1, ..., An → wn, we can compute the Fi(wi) and Fi(Ai) for every rule as follows:
initialize every Fi(Ai) with the empty set
set Fi(wi) to Fi(wi) for every rule Ai → wi, where Fi is defined as follows:
Fi(a w' ) = { a } for every terminal a
Fi(A w' ) = Fi(A) for every nonterminal A with ε not in Fi(A)
Fi(A w' ) = Fi(A) \ { ε } ∪ Fi(w' ) for every nonterminal A with ε in Fi(A)
Fi(ε) = { ε }
add Fi(wi) to Fi(Ai) for every rule Ai → wi
do steps 2 and 3 until all Fi sets stay the same.
语法:
A -> B C c
A -> g D B
B -> EPSILON | b C D E
C -> D a B | c a
D -> EPSILON | d D
E -> g A f | c
此website生成第一个集合,如下所示:
Non-Terminal Symbol First Set
A g, ε, b, a, c, d
B ε, b
C a, c, ε, d
D ε, d
E g, c
但算法显示Fi(A w' ) = Fi(A) for every nonterminal A with ε not in Fi(A)
,因此根据此算法的First(A)不应包含ε
。 First(A) = {g, b, a, c, d}
。
问:上述语法的第一个(A)是= First(B) - ε U First(C) U {g}
?
此video也遵循上述算法,不选择ε。
答案 0 :(得分:2)
First(B) = {ε, b}
First(D) = {ε, d}
First(E) = {g, c}
First(C) = {c, d, a}
First(A) = {b, g, c, d, a}
示例:
X -> Y a | b
Y -> c | ε
First(X) = {c, a, b}
First(Y) = {c, ε}
第一个(X)没有ε因为如果用ε代替Y,那么First(Y a)等于First(εa)= {a}
首先在我的github上设置实现。
修改:更新了链接
https://github.com/amirbawab/EasyCC-CPP/blob/master/src/syntax/grammar/Grammar.cpp#L229
计算第一组和后续组都可以在上面的新链接中找到。