CFG (Context Free Grammar) Simulator
Interactive Context-Free Grammar parser and derivation visualizer
About This Simulation
This context-free grammar simulator lets you enter production rules, derive strings step by step and see the parse tree that the derivation builds.
Features
- Enter variables, terminals and production rules
- Step-by-step leftmost derivations
- Parse tree built alongside the derivation
- Check whether a string can be generated by the grammar
Explanation
A context-free grammar (CFG) describes a language using production rules that replace a single variable with a string of variables and terminals. Starting from the start variable and applying rules until only terminals remain generates the strings of the language.
How it works
- A CFG is a 4-tuple (V, Σ, R, S): variables, terminals, rules and the start variable.
- Start with S. At each step choose a variable in the current string and replace it using one of its rules, for example S → aSb | ε.
- In a leftmost derivation, always replace the leftmost variable.
- Stop when the string contains only terminals; that string is in the language.
- The parse tree shows the same derivation as a tree: each variable's children are the symbols it was replaced with.
Why it matters
CFGs define the syntax of programming languages and are used by compiler parsers, XML and JSON parsers and natural language processing. They are studied in CSE331 and in compiler design.
Frequently Asked Questions
What is an ambiguous grammar?
A grammar is ambiguous if some string has two or more different parse trees (or leftmost derivations). For example, E → E + E | E × E | id is ambiguous for id + id × id.
What is the difference between leftmost and rightmost derivation?
In a leftmost derivation you always replace the leftmost variable; in a rightmost derivation you always replace the rightmost one. Both produce the same parse tree for an unambiguous grammar.
Can a CFG generate aⁿbⁿ?
Yes: S → aSb | ε generates aⁿbⁿ for n ≥ 0. This language is context-free but not regular, so no DFA can recognise it.
What machine recognises context-free languages?
A pushdown automaton (PDA): a finite automaton with a stack. Every CFG has an equivalent PDA and vice versa.
Topics covered
- Context-Free Grammar (CFG)
- Production Rules
- Derivations
- Parse Trees
- Ambiguity
- Context-Free Languages
Tags
- cfg
- context free grammar
- derivation
- parse tree
Related Simulations
Theory of Computation: Automata and Computability
DFA Simulator
Build, edit, and simulate strings in a DFA visualizer
Theory of Computation: Automata and Computability
State Transition Diagram
Create, edit, and test state machines interactively.
Theory of Computation: Automata and Computability
NFA Simulator
Build, edit, and simulate strings in an NFA visualizer
Theory of Computation: Automata and Computability
TM (Turing Machine) Simulator
Design, edit, and run computations in an interactive Turing Machine simulator

