Context-Free Grammars (CFG)

Context-Free Grammars (CFG) Visually

Master the foundation of syntax analysis and parsing

Visual Simulation Step Execution CFG Constructor Performance Analysis

What are Context-Free Grammars?

A Context-Free Grammar (CFG) is a formal grammar used to generate context-free languages. CFGs are essential in compiler design, natural language processing, and defining the syntax of programming languages.

A CFG is formally defined as a 4-tuple G = (V, T, P, S) where:

  • V: Finite set of variables (non-terminals)
  • T: Finite set of terminals (alphabet)
  • P: Finite set of production rules
  • S: Start symbol (S ∈ V)

Production rules have the form A → α, where A is a non-terminal and α is a string of terminals and non-terminals.

Example CFG

Grammar for balanced parentheses

S → (S)
S → SS
S → ε

Components:

  • Variables (V): {S}
  • Terminals (T): {(, )}
  • Start Symbol: S

Generated Language: All strings of balanced parentheses

Examples: ε, (), (()), ()(), (()())

Parse Tree Example

Parse tree for string "(())"

S
(
S
)
(
S
)
ε

Derivation:

S ⇒ (S) ⇒ ((S)) ⇒ ((ε)) ⇒ (())

Common CFG Examples

Arithmetic Expressions
E → E + T | T
T → T * F | F
F → (E) | id
Generates: id + id * id, (id + id) * id
If-Then-Else Statements
S → if E then S else S
S → if E then S
S → other
Generates conditional statements
Palindromes
S → aSa | bSb
S → a | b | ε
Generates: aba, bab, ababa, babab
Equal a's and b's
S → aSb | bSa
S → SS | ε
Generates: ab, ba, aabb, abab

Interactive Grammar Builder

Create and test your own Context-Free Grammar

Define Grammar Rules
Comma-separated list
Comma-separated list
One rule per line. Use 'ε' for epsilon
Grammar Presets
Current Grammar:
S → (S)
S → SS
S → ε

String Derivation Tester

Quick Test Examples:

Interactive Parse Tree Visualizer

Visualize the parse tree for your derivations

Tree Controls
1 = Slow, 5 = Fast

Parse tree will appear here

Grammar Analysis

String Generator

Generate random strings from your grammar