Formal Languages
Context-Free Grammars (CFG)
Every time you write `if (x > 0) { return x * 2; }`, the compiler parses that string using the rules of a grammar. That grammar is context-free. Without CFG there would be no programming language, no calculator, and no HTML parser.
- **Compilers and interpreters** - parsing code in C, Python, JavaScript relies on CFG
- **HTML/XML parsers** - nested tags `<div><p>...</p></div>` are described by a context-free grammar
- **Mathematical expressions** - calculators use CFG for correct operator precedence
- **NLP (natural language processing)** - parsing sentences: subject + predicate + object
Предварительные знания
What Is a Context-Free Grammar?
**Regular expressions are powerless** when it comes to checking nested brackets. The string `((()))` is valid, `(()` is not. Regex cannot "count" nesting depth. For such languages a more powerful tool is needed - a **context-free grammar (CFG)**.
A **CFG** is a set of substitution rules that describe how to generate strings of a language from the start symbol. Unlike regular grammars, the right-hand side of a rule may contain **any** combination of terminals and non-terminals.
Formally, **G = (V, Σ, R, S)** is a 4-tuple, where:
| Component | Notation | What it is |
|---|---|---|
| Variables (non-terminals) | V |