Cal11 calculator

Calculate Follow Compiler Design

Reviewed by Calculator Editorial Team

Follow sets are a fundamental concept in compiler design, particularly in the construction of parsing tables for top-down parsers like LL(1). They help determine which terminals can appear immediately after a non-terminal in any valid sentence of the grammar. This calculator helps you compute follow sets for your grammar rules.

What is a Follow Set?

A follow set for a non-terminal A in a grammar is the set of terminals that can appear immediately to the right of A in any valid sentence derived from the grammar's start symbol. Follow sets are crucial for:

  • Constructing LL(1) parsing tables
  • Determining when to reduce in shift-reduce parsing
  • Identifying syntax errors during parsing

Follow sets are distinct from first sets, which identify terminals that can appear immediately to the right of a non-terminal in any derivation.

How to Calculate Follow Sets

The follow set for a non-terminal A is calculated using these rules:

  1. If A is the start symbol, add $ (end marker) to FOLLOW(A)
  2. For each production B → αAβ:
    • If β is non-empty, add FIRST(β) to FOLLOW(A)
    • If β can derive ε (empty string), add FOLLOW(B) to FOLLOW(A)

FOLLOW(A) = { t | S ⇒* αAtβ, t ∈ FIRST(β) } ∪ { t | S ⇒* αA, t ∈ FOLLOW(S) }

This process is typically repeated until no more terminals can be added to any follow set.

Example Calculation

Consider the following grammar:

Non-terminal Production Rules
S aA | bB
A cA | d
B eB | f

Calculating FOLLOW(S):

  1. Since S is the start symbol, FOLLOW(S) = {$}
  2. For production A → cA, add FOLLOW(A) to FOLLOW(A)
  3. For production B → eB, add FOLLOW(B) to FOLLOW(B)

The complete follow sets for this grammar would be:

Non-terminal Follow Set
S {$}
A {$, a, b}
B {$, a, b}

FAQ

What's the difference between first and follow sets?

First sets identify terminals that can appear immediately after a non-terminal in any derivation, while follow sets identify terminals that can appear immediately after a non-terminal in any valid sentence of the grammar.

When are follow sets used in compiler design?

Follow sets are primarily used in the construction of LL(1) parsing tables to determine when to reduce during parsing. They help identify which terminals can legally follow a non-terminal in the input.

How do I know when to stop calculating follow sets?

You stop when no more terminals can be added to any follow set during an iteration of the calculation process. This typically happens when the follow sets stabilize.