Context-free languages and parsing theory
Introducido
5:58
Teoría de la computación y compiladores
This course asks what machines can decide, and how text becomes meaning. The first three units are theory: automata and regular languages, context-free…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| context-free grammar/ˈkɒntekst friː ˈɡræmə/ | rules that rewrite one nonterminal at a time; they describe most programming-language syntax |
| nonterminals/ˌnɒnˈtɜːmɪnlz/ | grammar symbols that are rewritten by rules, as opposed to the tokens of the input |
| derivation/ˌderɪˈveɪʃn/ | derivación |
| parse tree/pɑːs triː/ | árbol de análisis sintáctico |
| ambiguity/ˌæmbɪˈɡjuːɪti/ | a grammar giving some string two or more different parse trees |
| pushdown automaton/ˈpʊʃdaʊn ɔːˈtɒmətn/ | A finite automaton plus a stack, and it recognises exactly the context-free languages. |
Gramáticas anidadas
- Las gramáticas libres de contexto reescriben no terminales: $E \to E + T \mid T$, $T \to T \times F \mid F$, $F \to (E) \mid \mathbf{id}$. Una derivación expande; un árbol de análisis registra la expansión.


In the layered grammar, id + id * id has — parse tree(s)
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Layering enforces precedence: x binds under T, deeper than +.
Ambigüedad y precedencia
- Con la gramática en capas,
id + id * idtiene UN solo árbol de análisis: × se une bajo T, más profundo que +. La gramática sin capas $E \to E + E \mid E \times E \mid \mathbf{id}$ da DOS árboles para la misma cadena — la ambigüedad se resuelve mediante el diseño de la gramática. - La derivación izquierda más cercana de
id + id * id: $E \Rightarrow E + T \Rightarrow T + T \Rightarrow \mathbf{id} + T \Rightarrow \mathbf{id} + T \times F \Rightarrow \mathbf{id} + \mathbf{id} \times F \Rightarrow \mathbf{id} + \mathbf{id} \times \mathbf{id}$ — seis pasos, verificada con suite.
With E → E + T | T, T → T * F | F and F → id, the leftmost derivation of id + id * id takes — steps
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
E, E+T, T+T, F+T, id+T, id+TF, id+FF, id+idF, id+idid - eight steps, one rule each.
El siguiente límite
- $\{a^n b^n c^n\}$ necesita dos conteos independientes: las CFG bombean uno, por lo que se requiere una máquina de contexto sensible — el siguiente nivel de la jerarquía de Chomsky, y la razón por la que los verificadores de tipos viven por encima de los analizadores sintácticos.
- Confundir el orden de derivación (izquierda más cercana/derecha más cercana) con la forma del árbol es la trampa clásica: la propia cadena debe elegir el árbol.
The language a^n b^n c^n requires —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Two independent counts: CFGs pump one, not both.
For an unambiguous grammar, the leftmost and rightmost derivations of a string give different parse trees.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
They expand the nonterminals in a different order but build the same tree. Only an ambiguous grammar lets one string have two trees.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
The stack machine
- A pushdown automaton 下推自动机 is a finite automaton plus a stack, and it recognises exactly the context-free languages. For $\{a^n b^n\}$: push on each $a$, pop on each $b$, and accept if the stack is empty when the input ends. After
aaabthe stack holds $2$ symbols. - Any CFG in Chomsky normal form can be parsed by CYK in $\Theta(n^3)$ time. Real compilers use restricted grammars, LL or LR, that parse in linear time.
The PDA for a^n b^n reads aaaabb. How many symbols are on the stack?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Four pushes and two pops leave 2; the input is not accepted yet.
Which machine recognises exactly the context-free languages?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
A finite control plus one stack matches the nesting that CFGs describe.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
The CYK table
- CYK fills a triangle that records, for each substring, which nonterminals 非终结符 can derive it. A string of length $n$ has $n(n+1)/2$ substrings, so $n = 5$ gives $\mathbf{15}$ cells.
- Each cell tries every split point, so the work is $\Theta(n^3)$. The string is in the language if the start symbol is in the top cell.
How many cells does the CYK table have for a string of length 6?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
$6 \times 7/2 = 21$.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Worked example: balanced brackets
- $S \to (S)S \mid \varepsilon$ generates every balanced bracket string. For
(())():
- The first bracket and its partner split the string into "inside" and "after", which is why the grammar has no ambiguity 二义性. No regular language can do this, because the nesting depth has no limit.
Which grammar generates exactly the balanced bracket strings?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
The second allows unbalanced strings; the last two miss strings like (())().
Every regular language is context-free.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
A DFA converts to a right-linear grammar.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Marks that slip away
- The unlayered grammar for expressions. $E \to E + E \mid E \times E \mid \mathbf{id}$ gives
id + id * idtwo trees; layering by precedence gives one. - Expecting a CFG to keep two counts. $\{a^n b^n c^n\}$ is not context-free.
- Forgetting the stack. Nested brackets need a pushdown automaton 下推自动机; a finite automaton cannot match them.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Recap
- A CFG rewrites nonterminals 非终结符; a parse tree records the derivation.
- The layered grammar gives
id + id * idone tree; $E \to E + E \mid E \times E$ gives two. - $\{a^n b^n c^n\}$ is not context-free: it needs two independent counts.
| Language | Example | Machine |
|---|---|---|
| Regular | identifiers, numbers | finite automaton |
| Context-free | $a^n b^n$, nested brackets | finite automaton + a stack |
| Context-sensitive | $a^n b^n c^n$ | linear-bounded automaton |
¿Qué salió mal? Solo el equipo del sitio ve esta información.