CIE AS & A Level Computer Science, section 16.2 (Translation software)
Compiler and interpreter
| Compiler | Interpreter | |
|---|---|---|
| Translates | the whole program into machine code | one statement at a time, and runs it |
| Output | an executable file | no executable |
| Errors | listed after translating the whole program | stops at the first error |
| Speed | the final program runs fast | slower, translated each time |
| Use | finished software to distribute | developing and testing |
Some languages compile to bytecode which a virtual machine then interprets.
Stages of compilation
- Lexical analysis: the source code is split into tokens (keywords, identifiers, numbers, operators). Comments and spaces are removed, and identifiers are stored in a symbol table.
- Syntax analysis: the tokens are checked against the grammar rules of the language, and a parse tree is built. Syntax errors are reported here.
- Code generation: the machine code (or intermediate code) is produced.
- Optimisation: the code is improved so it is faster or smaller, for example by removing unused code or calculating constants in advance.
Example of tokens
For total = price * 2:
It gives five tokens: total (identifier), = (operator), price (identifier), * (operator) and 2 (number). total and price go into the symbol table.
Why optimise
It makes the program run quicker and use less memory, without changing what it does.
Common mistake: mixing up the stages. Lexical analysis makes tokens; syntax analysis checks the grammar and builds the parse tree. Also, a compiler produces all its error messages after translation, but an interpreter stops at the first error.
Exam tip: name each stage and say what it produces or checks. When comparing, link each feature to a consequence, such as "a compiler gives an executable, so the program runs without the source".
Check yourself
What is produced by lexical analysis?
A series of tokens, with comments and spaces removed.
Give one advantage of an interpreter during development.
It runs each statement as it goes and stops at an error, so faults are found and fixed quickly.
What is the purpose of optimisation?
To make the generated code run faster or use less memory.