Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteA context-free grammar (CFG) is a formal system for describing the hierarchical syntax of a language. It uses nonterminals, terminals, production rules, and a start symbol to generate valid strings. CFGs describe structures such as balanced parentheses, nested blocks, and arithmetic expressions; parsers then analyze input according to those rules.
Formally, a grammar is written as G = (V, Σ, P, S). The language it generates is L(G), the set of terminal-only strings derivable from S.
What problem does a context-free grammar solve?
A CFG describes syntax: which symbols may appear, in what order, and how structures may nest. It does not by itself determine meaning or runtime behavior.
- Matching opening and closing delimiters
- Representing nested blocks and lists
- Defining arithmetic-expression structure
- Specifying portions of programming languages and data formats
In a compiler pipeline, lexical analysis turns characters into tokens, a CFG-based parser checks hierarchical syntax, semantic analysis checks declarations and types, and later stages translate or execute the result.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware match#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
The four components of a CFG
| Component | Meaning |
|---|---|
| V | A finite set of variables, also called nonterminals. These represent structural categories such as Expression or Statement. |
| Σ | A finite set of terminals: the symbols that may appear in completed strings. Textbooks may use T instead of Σ. |
| P | A finite set of productions. Each rule has one nonterminal on the left: A → α, where α is a string of terminals and nonterminals, possibly ε. |
| S | The start symbol, which must be a member of V. |
The left side contains exactly one nonterminal. “Context-free” means that this nonterminal can be replaced without examining neighboring symbols.
Formal definitions are given in the University of Florida notes and Virginia Tech OpenDSA.
Worked example: generating equal numbers of as and bs
Consider:
S → aSb | ε
- Nonterminal:
S - Terminals:
aandb - Start symbol:
S - Productions:
S → aSbandS → ε
The grammar generates:
ε, ab, aabb, aaabbb, …
Its language is L(G) = {anbn | n ≥ 0}. One derivation is:
S ⇒ aSb ⇒ aaSbb ⇒ aaaSbbb ⇒ aaabbb
A single arrow denotes one production application. ⇒* means zero or more applications, and ⇒+ means one or more. Any intermediate mixture of terminals and nonterminals is a sentential form; a terminal-only result is a sentence.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Balanced parentheses and nesting
A common grammar for balanced parentheses is:
S → SS | (S) | ε
It can generate ε, (), ()(), (()), and ()(()). Arbitrarily deep nesting requires unbounded memory, which is why a finite-state regular expression is not a natural general model. A stack can record unmatched opening parentheses and remove a marker when a closing parenthesis arrives.
This particular grammar’s S → SS rule can permit more than one structural derivation for some strings; it should not be assumed unambiguous.
Parse trees and abstract syntax trees
A parse tree records how a grammar derives a string:
- The root is the start symbol.
- Internal nodes are nonterminals.
- Children spell the right side of the production used.
- Leaves are terminals or
ε. - Reading terminal leaves from left to right yields the sentence.
For aabb under S → aSb | ε, the tree has an outer a ... b pair containing another a ... b pair and then ε. Parsers often build a related abstract syntax tree (AST), which removes grammatical scaffolding such as parentheses, separators, and helper nonterminals that later compiler stages do not need.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
A grammar specifies possible structures; a parser is the algorithm or program that checks input and constructs one or more such structures. Writing productions alone does not create an executable parser.
Ambiguous grammars
A grammar is ambiguous if at least one generated string has two distinct parse trees (equivalently, distinct leftmost or rightmost derivations under the standard definition). Ambiguity is not invalidity; it means the rules allow multiple interpretations.
This grammar does not encode arithmetic precedence:
E → E + E | E * E | (E) | id
The input id + id * id may represent (id + id) * id or id + (id * id).
Precedence can be represented with separate nonterminals:
E → E + T | T
T → T * F | F
F → (E) | id
Here multiplication is nested inside T, giving it higher precedence than addition. A language may have an ambiguous grammar even when another grammar for the same language is unambiguous. Some context-free languages are inherently ambiguous, meaning every CFG for them is ambiguous; this is an advanced result discussed in the University of Pennsylvania notes.
CFG versus context-free language
A CFG is the rule system. A context-free language (CFL) is the set of terminal strings generated by at least one CFG:
L is context-free if and only if there exists a grammar G such that L = L(G).
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Different grammars can generate the same language, so the grammar and the language should not be treated as interchangeable terms.
Where CFGs fit in the Chomsky hierarchy
CFGs are Type-2 grammars. Their languages sit in the proper containment chain:
regular ⊊ context-free ⊊ context-sensitive ⊊ recursively enumerable
- Every regular language is context-free.
{anbn | n ≥ 0}is context-free but not regular.{anbncn | n ≥ 0}is not context-free; proofs commonly use the context-free pumping lemma or Ogden’s lemma.
The pumping lemma can establish non-context-freeness when a contradiction is proved; failing to find one is not a proof that a language is context-free.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Relationship to pushdown automata
A language is context-free if and only if some pushdown automaton (PDA) recognizes it. A CFG generates structure from a start symbol; a PDA reads input while using a stack. The stack supplies the memory needed for nested dependencies.
For parentheses, a PDA can push a marker for each opening parenthesis and pop one for each closing parenthesis. It rejects an unmatched closing parenthesis or a nonempty stack at the end. CFG-to-PDA and PDA-to-CFG constructions prove expressive equivalence, but the formalisms are not identical implementations. JFLAP provides educational transformations between grammars and automata.
What CFGs can and cannot express
Good fits
- Recursive and nested constructs
- Matching delimiters
- Expression trees
- Blocks, lists, and hierarchical documents
Limits of a CFG alone
- Independent equality of three sections, such as
anbncn - Whether an identifier has been declared
- Type compatibility and scope rules
- Runtime behavior and resource constraints
- Arbitrary symbol-table-dependent predicates
Indentation-sensitive syntax can still be handled if a lexer emits indentation tokens or an additional mechanism processes indentation. Lexical rules also usually belong in a lexer rather than the parser grammar.
Closure properties
Context-free languages are closed under union, concatenation, Kleene star and plus, reversal, homomorphism, inverse homomorphism, and substitution. They are not generally closed under intersection, complement, or difference. They are, however, closed under intersection with a regular language.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
For example, both L = {aibicj | i,j ≥ 0} and M = {aibjcj | i,j ≥ 0} are context-free, but their intersection is {anbncn | n ≥ 0}, which is not.
Normal forms
Chomsky normal form
Under the usual convention, productions in Chomsky normal form (CNF) are A → BC or A → a, with a possible special start-symbol rule S → ε. Definitions vary slightly between textbooks.
Conversion commonly removes ε-productions, unit productions such as A → B, and useless symbols. CNF is useful for proofs and CYK parsing, but it usually makes a grammar less readable and does not preserve its original parse-tree shape.
See the OpenDSA CYK material.
Greibach normal form
In Greibach normal form, productions generally begin with a terminal, A → aα, where α contains nonterminals, with special handling when the language contains ε. It is mainly useful in theory courses.
Parsing algorithms and parser strategies
Recognition versus parsing
Recognition asks whether an input belongs to L(G). Parsing constructs one or more derivations, parse trees, or equivalent representations. An ambiguous input may be recognized successfully while still having several possible trees.
CYK
Cocke–Younger–Kasami (CYK) is a dynamic-programming recognizer for grammars in CNF. It examines substrings of increasing length and has standard O(n3) time complexity for a fixed grammar in its basic form. It is valuable for general theory, though production language parsers usually use grammar-specific methods.
Earley parsing
Earley parsing handles general CFGs, including grammars outside LL or LR restrictions. Its worst-case complexity is cubic, with better behavior for many practical grammars, and it can represent ambiguity instead of forcing one interpretation.
Top-down parsing
Recursive descent and predictive LL parsers are often straightforward to write and can produce intuitive error locations. They may require left-recursion removal and left factoring.
Recommended Free Tools
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
For example, naïve recursive descent cannot directly use:
E → E + T | T
because expanding E immediately calls E again. A suitable transformation is:
E → T E'
E' → + T E' | ε
Bottom-up parsing
LR(0), SLR(1), LALR(1), canonical LR(1), and GLR parsers recognize a broad class of grammars and naturally support left-recursive expression rules. Typical problems include shift/reduce conflicts, reduce/reduce conflicts, and error recovery that postpones failure until a later token. Precedence declarations can resolve conflicts operationally, but they do not necessarily make the underlying grammar mathematically unambiguous.
GNU Bison generates deterministic LR-family or generalized LR parsers from annotated grammar specifications.
Free tools Windows power users keep installed
One-click scans. No signup required.
BNF, EBNF, and parser-generator grammars
Programming-language specifications commonly use BNF or EBNF notation. EBNF adds shorthand for optional parts, repetition, and grouping; these conveniences can usually be expanded into ordinary CFG productions. Tool-specific extensions may add semantic predicates, lexical modes, actions, or other behavior beyond a bare CFG.
Real grammar files often combine productions with token declarations, precedence rules, semantic actions, lexer definitions, and error-handling directives. Consequently, an ANTLR or Bison file is not necessarily just the mathematical four-tuple.
Practical tools
| Tool | Best use | Trade-off |
|---|---|---|
| JFLAP | Visualizing grammars, parse procedures, PDA conversions, CNF, and coursework | Educational rather than deployment-oriented |
| ANTLR | Generating lexers and parsers for multiple target languages | Grammar notation includes practical features beyond a bare CFG; verify the current release at the download page |
| GNU Bison | LR-family and GLR parsers in traditional compiler toolchains | Requires understanding conflicts, parser modes, and tool-specific directives |
For a small lesson, hand derivations or JFLAP are sufficient. For a multi-language application, ANTLR may be convenient. For C/C++-centered LR or GLR compiler work, Bison is a common choice. Check each project’s current release and license terms before deployment.
Quick Recap
Common mistakes
- Confusing terminals with nonterminals.
- Forgetting to state whether
εis generated. - Calling a grammar invalid merely because it is ambiguous.
- Using left recursion in naïve recursive descent.
- Assuming every CFG has a deterministic parser.
- Confusing syntax rules with declarations, types, scope, or other semantics.
- Treating parser-generator notation as identical to a pure CFG.
CFG checklist
- Can you identify
V,Σ,P, andS? - Which terminal strings are derivable?
- Does the grammar generate
ε? - Can a string have multiple parse trees?
- Does the intended parser support this grammar, or must it be transformed?
- Which semantic constraints must be checked outside the grammar?
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.

