Skip to content
PostCompiler Construction / Lecture

Compiler-solution for First set, Follow set and LL(1) Parsing table

2024-11-28
Back to Blog

Compiler-Solution for First set, Follow set and LL(1) Parsing table ​

Solution for First Set ​

To compute FIRST(X) for all grammar symbols X, apply the following rules until no more terminals or ε can be added to any FIRST set.

  1. If X is a terminal, then FIRST(X)={X}.

  2. If X is a nonterminal and X→Y1Y2...Yk is a production for some k≥1, then place ϵ in FIRST(X) if for some i, ϵ is in FIRST(Yi), and ϵ is in all of FIRST(Y1),⋯,FIRST(Yi−1). If ϵ is in FIRST(Yi) for all i=1,2,...,k, then add ϵ to FIRST(X). For example, everything in FIRST(Yi) is surely in FIRST(X). If Yi does not derive ϵ, then we add nothing more to FIRST(X), but if Yi⇒ϵ, then we add FIRST(Yi+1), and so on.

  3. If X→ϵ is a production, then add ϵ to FIRST(X).

Now, we can compute FIRST for any string X+1X2⋯Xnas follows. Add to FIRST(X1X2⋯Xn) all non-ϵ symbols of FIRST(X1). Also add the non-ϵ symbols of FIRST(X2), if ϵ is in FIRST(X1); the non-ϵ symbols of FIRST(X3), if ϵ is in FIRST(X1) and FIRST(X2); and so on. Finally, add ϵ to FIRST(X1X2⋯Xn) if, for all i, ϵ is in FIRST(Xi).

Solution for Follow Set ​

To compute FOLLOW(A) for all nonterminals A, apply the following rules until nothing can be added to any FOLLOW set:

  1. Place $ in FOLLOW(S), where S is the start symbol, and $ is the input right end marker.

  2. If there is a production A→αBβ, then everything in FIRST(β) except ϵ is in FOLLOW(B).

  3. If there is a production A→αB, or a production A→αBβ, where FIRST(β) contains ϵ, then everything in FOLLOW(A) is in FOLLOW(B).


  1. 对于文法的开始符号S,置 $ 于Follow(S)中;
  2. 若A→αBβ是一个产生式,则把First(β)/{ε}加入到Follow(B)中
  3. 若A→αB是一个产生式,或A→αBβ是一个产生式且β⇒ϵ ,则把Follow(A)加入到Follow(B)中

(α可以是终结符或者非终结符(包括ϵ),β可以是终结符或者非终结符)

Solution for LL(1) Parsing Table ​

Suppose the parsing table M is n×m, where n is the number of nonterminals and m is the number of terminals. The table is initialized to be empty.

The entry M[A,α] is a production rule that parser will apply when the current nonterminal is A and the next input symbol is α.

For each production A→α in the (left factored, non-left recursive) grammar, do the following:

  1. Foe each token α in FIRST(α), add the grammar production A→α to M[A,α].
  2. If ϵ is in FIRST(α) then, for each token b in the FOLLOW(A), add A→α to M[A,b].
  3. All other entries in the table are left blank and correspond to a syntax error.

流程:

遍历两次 Production Rule

第一次遍历,对每个 Production Rule 检查 Rule-1

  • 如果 α 是终结符,则把 A→α 加入到 M[A,α] 中
  • 如果 α 是非终结符,则把 A→α 加入到M[A,b]∀b∈FIRST(α)

第二次遍历,对每个 Production Rule 检查 Rule-2

查看Production Rule 中所有可以产生 ϵ 的非终结符 对这些非终结符把 A→ϵ 加入到 M[A,b]∀b∈FOLLOW(A)