Compilation and interpretation · Compilación e interpretación
| English | Español |
|---|---|
| compiler/kəmˈpaɪlə/ | compilador |
| interpreter/ɪnˈtɜːprɪtə/ | intérprete |
| lexical analysis/ˈleksɪkl əˈnæləsɪs/ | análisis léxico |
| tokens/ˈtəʊkənz/ | tokens |
| syntax analysis/ˈsɪntæks əˈnæləsɪs/ | análisis sintáctico |
| abstract syntax tree/ˈæbstrækt ˈsɪntæks triː/ | árbol de sintaxis abstracta |
| syntax error/ˈsɪntæks ˈerə/ | error de sintaxis |
| semantic analysis/səˈmæntɪk əˈnæləsɪs/ | análisis semántico |
| code generation/kəʊd ˌdʒenəˈreɪʃn/ | generación de código |
| code optimisation/kəʊd ˌɒptɪmaɪˈzeɪʃn/ | optimización de código |
The bug that cost a spacecraft, found by a comma
- NASA's Mariner 1 was destroyed 293 seconds after launch in 1962. The failure is often blamed on a single wrong character in the guidance software.
- The story is retold so often because it is the fear every programmer knows: a compiler happily translating a program that says something you did not mean.
- A compiler is not one process but five, and each one catches a different class of mistake. Knowing which stage catches what tells you where any given error comes from.
- This lesson is how an interpreter 解释器 runs a program without producing anything, and the five stages a compiler 编译器 goes through.
El error que costó una nave espacial, detectado por una coma
- La Mariner 1 de la NASA se destruyó 293 segundos después del lanzamiento en 1962. Este fallo suele atribuirse a un único carácter incorrecto en el software de guía.
- La historia se relata con tanta frecuencia porque representa el miedo que todo programador conoce: un compilador traduce felizmente un programa que dice algo que no deseaba decir.
- Un compilador no es un solo proceso, sino cinco, y cada uno captura una clase diferente de error. Saber qué etapa captura qué tipo de error te indica de dónde proviene cualquier error dado.
- Esta lección explica cómo un interpreter (intérprete) ejecuta un programa sin producir nada, y las cinco etapas por las que pasa un compiler (compilador).
How an interpreter runs a program
- An interpreter translates and runs the source at the same time, one statement at a time.
- For each statement it reads the line, analyses it, checks the types, then executes the action immediately, and moves to the next.
- It produces no executable file: the translation exists only in memory and is thrown away. That is the syllabus's exact point, that it can execute a program without producing a translated version.
- It reports an error the moment it reaches the offending line and usually stops, which gives quick feedback while developing. Every run re-translates, so it is slower, and both the source and the interpreter must be present.
Translate once and keep it, or translate and run and forget
Cómo ejecuta un intérprete un programa
- Un intérprete traduce y ejecuta el código fuente al mismo tiempo, una instrucción a la vez.
- Para cada instrucción, lee la línea, la analiza, verifica los tipos y luego ejecuta la acción inmediatamente, pasando a la siguiente.
- No produce un archivo ejecutable: la traducción existe únicamente en la memoria y se descarta. Ese es el punto exacto del temario: puede ejecutar un programa sin producir una versión traducida.
- Informa de un error en el momento en que llega a la línea ofensiva y generalmente se detiene, lo que proporciona retroalimentación rápida durante el desarrollo. Cada ejecución vuelve a traducir, por lo que es más lento, y tanto el código fuente como el intérprete deben estar presentes.

Traduce una vez y guárdalo, o traduce, ejecuta y olvida
An interpreter: · Un intérprete:
It works line by line, reporting errors as it reaches them; nothing is saved as an executable, and it is generally slower. · Funciona línea por línea, reportando errores a medida que los encuentra; no se guarda nada como ejecutable, y generalmente es más lento.
An interpreter can execute a program without producing a translated version of it. · Un intérprete puede ejecutar un programa sin producir una versión traducida de este.
The translation exists only in memory, statement by statement, and is discarded. That is why the interpreter must be present every time the program runs. · La traducción existe solo en memoria, línea por línea, y se descarta. Por eso el intérprete debe estar presente cada vez que se ejecuta el programa.
Stage 1: lexical analysis
- Lexical analysis 词法分析 groups the individual characters of the source into tokens 词法单元: keywords, identifiers, operators and literals.
- Whitespace and comments are discarded, since they have no meaning to the compiler, and identifiers are entered into a symbol table.
- So
total ← count * 2becomes the token sequence identifier, assignment, identifier, operator, literal. The lexer does not know or care whether that makes sense.
Etapa 1: análisis léxico
- El análisis léxico agrupa los caracteres individuales del código fuente en tokens: palabras clave, identificadores, operadores y literales.
- Los espacios en blanco y los comentarios son descartados, ya que no tienen significado para el compilador, y los identificadores se introducen en una tabla de símbolos.
- Así,
total ← count * 2se convierte en la secuencia de tokens: identificador, asignación, identificador, operador, literal. El analizador léxico no sabe ni le importa si eso tiene sentido.
Lexical analysis (the lexer) turns: · El análisis léxico (el lexer) convierte:
The lexer groups characters into tokens and discards whitespace/comments; parsing then builds the tree. · El lexer agrupa caracteres en tokens y descarta espacios en blanco/comentarios; el análisis sintáctico construye luego el árbol.
Lexical analysis groups the source characters into ____ and discards whitespace and comments. · El análisis léxico agrupa los caracteres del código fuente en ____ y descarta espacios en blanco y comentarios.
Keywords, identifiers, operators and literals. The lexer makes no judgement about whether the sequence is a valid program. · Palabras clave, identificadores, operadores y literales. El lexer no juzga si la secuencia es un programa válido.
Stage 2: syntax analysis
- Syntax analysis 语法分析, or parsing, checks that the sequence of tokens fits the language's grammar, and builds an abstract syntax tree 抽象语法树 representing the structure.
- A missing bracket, a missing
ENDIFor a keyword in the wrong place is caught here: that is what a syntax error 语法错误 is, and it is why the compiler can report one without ever running the program.
The grammar the parser checks against
Etapa 2: análisis sintáctico
- El análisis sintáctico, también llamado parsing, verifica que la secuencia de tokens se ajuste a la gramática del lenguaje y construye un árbol de sintaxis abstracta que representa la estructura.
- Falta un paréntesis, falta un
ENDIFo hay una palabra clave en el lugar equivocado: aquí se detecta eso. Eso es lo que constituye un error de sintaxis, y es por eso que el compilador puede reportarlo sin haber ejecutado nunca el programa.

La gramática contra la que verifica el parser
Stage 3: semantic analysis
- Semantic analysis 语义分析 checks that a syntactically valid program actually makes sense: every variable is declared before use, the types on each side of an assignment are compatible, a function is called with the right number of arguments.
total ← "seven" * 2is perfectly good syntax and complete nonsense. Only this stage catches it.- This is the distinction the exam tests: syntax is form, semantics is meaning.
Etapa 3: análisis semántico
- El análisis semántico verifica que un programa sintácticamente válido tenga realmente sentido: cada variable está declarada antes de su uso, los tipos en ambos lados de una asignación son compatibles, una función es llamada con el número correcto de argumentos.
total ← "seven" * 2es una sintaxis perfectamente buena y un completo sinsentido. Solo esta etapa lo detecta.- Esta es la distinción que prueba el examen: la sintaxis es la forma, la semántica es el significado.
Which of these is checked by semantic analysis rather than syntax analysis? · ¿Cuál de estos es verificado por el análisis semántico en lugar del análisis sintáctico?
Brackets are grammar, so syntax; whitespace is the lexer; registers are code generation. Declarations and types are meaning. · Las llaves son gramática, por lo tanto sintaxis; los espacios en blanco corresponden al lexer; los registros son generación de código. Las declaraciones y tipos son semántica.
Stages 4 and 5: code generation and optimisation
- Code generation 代码生成 walks the tree and emits the target machine code, choosing registers and laying out the data.
- Code optimisation 代码优化 improves that code without changing what it does: removing redundant work, computing constant expressions at compile time, and reordering instructions to suit the pipeline.
- The output is a stand-alone executable that runs without the compiler present.
Five stages, and each one catches something the last could not
Etapas 4 y 5: generación de código y optimización
- La generación de código recorre el árbol y emite el código máquina objetivo, eligiendo registros y distribuyendo los datos.
- La optimización de código mejora ese código sin cambiar lo que hace: elimina trabajos redundantes, calcula expresiones constantes en tiempo de compilación y reordena instrucciones para adaptarse al pipeline.
- La salida es un ejecutable autónomo que se ejecuta sin que esté presente el compilador.

Cinco etapas, y cada una captura algo que la anterior no podía
The phases of compilation · Las fases de la compilación
Step through what a compiler does to your source. Each phase hands its output to the next — characters become tokens, tokens become a tree, the tree becomes optimised machine code. · Recorra paso a paso lo que hace un compilador con su código fuente. Cada fase entrega su salida a la siguiente: los caracteres se convierten en tokens, los tokens en un árbol, y el árbol en código máquina optimizado.
Match each compiler phase to what it does. · Empareje cada fase del compilador con lo que hace.
Each phase transforms the program a step further: tokens, then a tree, then checked, then optimised code. · Cada fase transforma el programa un paso más: tokens, luego un árbol, luego verificado, luego código optimizado.
Put the compiler stages in order. · Ordene las fases del compilador.
Lexical → syntax → semantic → code generation → optimisation. · Léxico → sintáctico → semántico → generación de código → optimización.
Code optimisation aims to: · La optimización de código busca:
Optimisation improves the generated code (constant folding, removing redundancy, reordering for the pipeline). · La optimización mejora el código generado (pliegue de constantes, eliminación de redundancia, reordenamiento para la tubería).
Worked example: which stage catches which error
x ← 5 +: the tokens do not fit the grammar, an operator with no right operand, so syntax analysis.x ← y + 1whereywas never declared: the form is fine but the meaning is not, so semantic analysis.IF a > b THEN OUTPUT awith noENDIF: syntax analysis again.- A program that runs and prints the wrong average: no stage catches it. That is a logic error, and only testing finds it. Name the stage and why the earlier ones let it through.
Ejemplo resuelto: qué etapa captura qué error
x ← 5 +: los tokens no se ajustan a la gramática, un operador sin operando derecho, por lo tanto análisis sintáctico.x ← y + 1dondeynunca fue declarado: la forma es correcta pero el significado no, por lo tanto análisis semántico.IF a > b THEN OUTPUT asinENDIF: nuevamente análisis sintáctico.- Un programa que se ejecuta e imprime el promedio incorrecto: ninguna etapa lo detecta. Es un error lógico, y solo las pruebas lo encuentran. Nombra la etapa y por qué las anteriores dejaron pasar el error.
Match each faulty line to the compiler stage that catches it. · Empareje cada línea defectuosa con la fase del compilador que la detecta.
Syntax is form, semantics is meaning, and a logic error is valid in both but wrong in intent. · La sintaxis es la forma, la semántica es el significado, y un error lógico es válido en ambos pero equivocado en intención.
Worked example: compare the two translators
- Give two differences between how a compiler and an interpreter handle a program. [4]
- A compiler translates the whole program before it runs and produces an executable, which then runs without the compiler; an interpreter translates and executes one statement at a time and produces no executable, so the interpreter must be present every run.
- A compiler reports all the errors together after translation; an interpreter reports the first error when it reaches that line and then stops.
- Each mark is a pairing: say what one does and what the other does instead.
Ejemplo resuelto: compara los dos traductores
- Da dos diferencias entre cómo un compilador y un intérprete manejan un programa. [4]
- Un compilador traduce el programa completo antes de ejecutarlo y produce un ejecutable, que luego se ejecuta sin el compilador; un intérprete traduce y ejecuta una instrucción a la vez y no produce un ejecutable, por lo que el intérprete debe estar presente en cada ejecución.
- Un compilador informa todos los errores juntos después de la traducción; un intérprete informa el primer error cuando llega a esa línea y luego se detiene.
- Cada marca es un par: di qué hace uno y qué hace el otro en su lugar.
Marks that slip away
- An interpreter produces no translated version. That is the phrase the syllabus uses and the mark it awards.
- The lexer produces tokens and discards whitespace and comments; it does not check whether the program is valid.
- Syntax is form, semantics is meaning. An undeclared variable is a semantic error, not a syntax error.
- Optimisation must not change what the program does, only how quickly or compactly it does it.
Puntos que se escapan
- Un intérprete no produce ninguna versión traducida. Esa es la frase que usa el temario y la que otorga la puntuación.
- El analizador léxico produce tokens y descarta espacios en blanco y comentarios; no verifica si el programa es válido.
- La sintaxis es la forma, la semántica es el significado. Una variable no declarada es un error semántico, no un error de sintaxis.
- La optimización no debe cambiar lo que hace el programa, solo la velocidad o compacidad con la que lo hace.
You've got it
- an interpreter translates and executes one statement at a time, producing no executable, reporting the first error at its line, and re-translating on every run
- lexical analysis makes tokens and discards whitespace and comments; syntax analysis checks the grammar and builds an abstract syntax tree, catching syntax errors
- semantic analysis checks meaning: declarations, types, argument counts
- code generation emits machine code and optimisation improves it without changing behaviour, giving a stand-alone executable
Lo has logrado
- un intérprete traduce y ejecuta una instrucción a la vez, no produce un ejecutable, informa el primer error en su línea y vuelve a traducir en cada ejecución
- el análisis léxico crea tokens y descarta espacios en blanco y comentarios; el análisis sintáctico verifica la gramática y construye un árbol de sintaxis abstracta, capturando errores de sintaxis
- el análisis semántico verifica el significado: declaraciones, tipos, conteo de argumentos
- la generación de código emite código máquina y la optimización lo mejora sin cambiar el comportamiento, dando un ejecutable autónomo