How to use the FIRST and FOLLOW Calculator
- 1. Type the grammarOne rule per line, like E -> T E', with | between alternatives and ε for empty.
- 2. Run itThe first rule's left side is the start symbol. Every other symbol not on a left side is a terminal.
- 3. Read the setsSee FIRST and FOLLOW tables, FIRST of each production, and the rule behind each FOLLOW entry.
Rules for FIRST and FOLLOW
FIRST(α) is the set of terminals that can begin a string derived from α, plus ε if α can derive the empty string.
- For a terminal a, FIRST(a) = {a}.
- For A → X1 X2 … Xn, add FIRST(X1) − {ε}. If X1 can derive ε, also add FIRST(X2) − {ε}, and so on. If every Xi can derive ε, add ε.
FOLLOW(A) is the set of terminals that can come right after A in some sentential form.
- Put $ in FOLLOW(start symbol).
- For B → α A β, add FIRST(β) − {ε} to FOLLOW(A).
- If β is empty or can derive ε, add FOLLOW(B) to FOLLOW(A).
Repeat both rules until no set changes. ε never goes into a FOLLOW set.
Worked example: expression grammar
Take E → T E', E' → + T E' | ε, T → F T', T' → * F T' | ε and F → ( E ) | id.
- FIRST(F) = FIRST(T) = FIRST(E) = { (, id }.
- FIRST(E') = { +, ε } and FIRST(T') = { *, ε }.
- FOLLOW(E) = FOLLOW(E') = { ), $ }. $ comes from E being the start symbol, and ) comes from F → ( E ).
- FOLLOW(T) = FOLLOW(T') = { +, ), $ }, because E' follows T and E' can vanish.
- FOLLOW(F) = { *, +, ), $ }.
These sets are what you need to build the LL(1) parsing table.
Input tips
Separate symbols with spaces to be safe. Without spaces, each character is read as one symbol, except non-terminal names like E' and the word id. Write ε, eps, epsilon or # for the empty string. FIRST and FOLLOW are defined even for left-recursive grammars, but such grammars are never LL(1). For more practice, try the compiler design MCQ quiz.
Frequently asked questions
Why is there no ε in FOLLOW sets?
FOLLOW lists terminals that can appear after a non-terminal. The end of input is shown as $, so ε is never needed.
Which symbol is the start symbol?
The left side of the first line. Put your start rule first.
Does it work with left-recursive grammars?
Yes, the sets are still correct. You need to remove left recursion only when building an LL(1) parser.
How do I write multi-letter terminals like num?
Separate symbols with spaces, for example F -> ( E ) | num. Each word is then one symbol.