Interpreters and compilers
A processor cannot run source code as written, so it must be translated: all at once, or a statement at a time. A compiler creates a translated program before execution. An interpreter analyses and executes the source as it is encountered, without saving a complete translated version.
Follow the compiler’s three boxes from top to bottom, then the interpreter’s three steps. The interpreter never makes the middle box.
Interpret one statement, then continue
- Take one formula:
(STOCK - 4) / (BAYS + 2). - With STOCK = 28 and BAYS = 4, either route must produce 4.
- Translation changes the route to execution, not the intended arithmetic.
Compare a compiler and an interpreter
Which route is better depends on what you are doing: still writing the program, or running it many times.
| Aspect | Compiler | Interpreter |
|---|---|---|
| Preparing a run | Checks and translates the whole source first. | Can execute valid statements before a later error is reached. |
| Running again | Reuses the saved executable; translation is not repeated. | Needs source and interpreter; repeats interpretation. |
| Changing source | Translate the changed program again. | Try a changed part during development. |
| Execution speed | Usually faster after compilation. | Translation work adds to execution time. |
- An executable is specific to its target machine or runtime.
- Neither translation route guarantees that a logically incorrect calculation gives the intended answer.
1 Which translator saves a complete translated program?
2 A program has an error on line 40. Which translator can run lines 1 to 39 first?
3 A finished program will be run a thousand times without changes. Which route avoids repeating the translation?
- 1a compiler
- 2an interpreter: it executes each valid statement before it reaches the error
- 3compile once, then run the saved executable
Lexical analysis
To a compiler, source code arrives as nothing but characters. Before it can check any meaning, it has to group them into words. Lexical analysis turns a character stream into a sequence of tokens. It identifies the category of each token and records identifiers in a symbol table.
Split the source into tokens
- An identifier begins with a capital letter and continues with capital letters or digits.
- An integer contains one or more digits.
- Spaces separate tokens but are not tokens;
//starts a comment that ends at the end of the line.
Apply those three rules to the formula. Each box is one token, with its category under it; only the identifiers go on to the symbol table.
| Token sequence | Categories |
|---|---|
( · STOCK · − · 4 · ) | Opening bracket · identifier · operator · integer · closing bracket |
/ | Operator |
( · BAYS · + · 2 · ) | Opening bracket · identifier · operator · integer · closing bracket |
The comment and unnecessary white space are removed. The remaining token stream is passed to the syntax analyser; discarding spaces must not merge two separate tokens.
What the symbol table records
Later stages need to know what each name stands for and where its value is kept.
| Identifier | Type | Storage location |
|---|---|---|
| STOCK | INTEGER | 400 |
| BAYS | INTEGER | 401 |
The entries let later stages check and locate the named data. At execution the locations contain 28 and 4. An identifier is recorded once even when it appears repeatedly.
Which errors lexical analysis finds
This stage knows words, not sentences, so it catches only some mistakes:
| Source fragment | What the analyser finds |
|---|---|
STOCK @ 4 | @ is not a token in this language: a lexical error. |
STOCK − / 4 | Every token is recognised. Their order must be checked by syntax analysis. |
1 List the tokens in TOTAL1 + 25 // sum.
2 Which identifiers go in the symbol table for TOTAL1 + RATE * TOTAL1?
3 Why is 9X not read as one identifier?
- 1TOTAL1, +, 25: three tokens; the comment is removed
- 2TOTAL1 and RATE, once each
- 3an identifier must begin with a letter, so 9 is read as an integer and X as a separate identifier
Syntax analysis
Every token in STOCK − / 4 is a real word of the language, yet together they make no sense. Syntax analysis parses the token stream against the language’s grammar. It reports syntax errors and builds a parse tree for an accepted structure.
Read the grammar and the parse tree
- A term groups multiplication and division more tightly than addition and subtraction.
- A bracketed expression is a single factor.
- Repeated operations at the same level associate to the left.
Read the tree from the bottom up. Each operator combines the two operands under it, so the root, /, is applied last.
- 1The operation branches show the accepted structure: divide the entire difference by the entire sum.
- 2Each leaf is an operand.
- 3Grammar-category nodes are omitted so the operation order stays visible.
Find where a syntax error is
An error sits at the first token that no rule of the grammar allows next:
| Token stream | Reason |
|---|---|
STOCK − / 4 | After −, a term must begin with a factor; / cannot begin one. |
( STOCK − 4 | The factor opened with ( needs a closing ). |
STOCK 4 | Two factors cannot be adjacent; an operator is needed. |
Parsing establishes a permitted structure. It does not prove that the formula solves the programmer’s problem.
1 Is STOCK * (4 + BAYS) accepted by the grammar?
2 Is (STOCK + 4 accepted? If not, which rule fails?
3 In STOCK − 4 * 2, which operation is grouped first, and why?
- 1yes: a term times a bracketed factor
- 2no: the factor opened with
(has no closing) - 3the multiplication: 4 × 2 forms a term before the subtraction joins it
Code generation and optimisation
A parse tree says what to work out; a machine needs instructions, one at a time. Code generation turns the tree into target instructions. Optimisation keeps the behaviour while cutting time or resource use.
Generate the stack instructions
Translate (STOCK − 4) / (BAYS + 2). For the execution trace, STOCK = 28 and BAYS = 4.
- 1LOAD pushes a variable’s value; PUSH pushes a literal.
- 2An arithmetic instruction pops the right operand, then the left, and pushes the result.
- 3These are this stack target’s defined operations, not processor mnemonics.
One row per generated instruction. Follow the stack after each one runs.
| Stack · bottom → top | What it does | |
|---|---|---|
| LOAD STOCK | 28 | Push 28 |
| Push 28 | ||
| PUSH 4 | 284 | Push 4 |
| Push 4 | ||
| SUB | 24 | Pop 4, then 28; 28 − 4 = 24; push 24 |
| Pop 4, then 28; 28 − 4 = 24; push 24 | ||
| LOAD BAYS | 244 | Push 4 |
| Push 4 | ||
| PUSH 2 | 2442 | Push 2 |
| Push 2 | ||
| ADD | 246 | Pop 2, then 4; 4 + 2 = 6; push 6 |
| Pop 2, then 4; 4 + 2 = 6; push 6 | ||
| DIV | 4 | Pop 6, then 24; 24 / 6 = 4; push 4 |
| Pop 6, then 24; 24 / 6 = 4; push 4 | ||
| Generated target instruction | Stack after execution · bottom → top |
|---|---|
| LOAD STOCK | 28 |
| PUSH 4 | 28, 4 |
| SUB | 24 |
| LOAD BAYS | 24, 4 |
| PUSH 2 | 24, 4, 2 |
| ADD | 24, 6 |
| DIV | 4 |
The generator emits the numerator before the denominator, then division. The target could instead use registers; its instruction set determines the actual generated code.
Optimise without changing the answer
Amber: the instructions that constant folding removes. 2 + 2 is worked out once, during compilation.
Constant folding computes 2 + 2 during compilation. The target then needs LOAD, PUSH and SUB, rather than LOAD, PUSH, PUSH, ADD and SUB: 3 operations instead of 5. With STOCK = 28 both return 24.
| Possible optimisation | Condition that preserves behaviour |
|---|---|
| Remove redundant operations | They have no effect needed by later code. |
| Avoid repeating a calculation | Its inputs have not changed. |
| Reorder instructions | Dependencies and observable effects are preserved. |
BAYS + 2 cannot be replaced by 6 merely because BAYS happened to be 4 in one run: the value may change on another run.
1 Generate the stack-target instructions for BAYS * 3 + 1.
2 With BAYS = 4, what value is left on the stack?
3 Constant folding turns STOCK + 3 * 2 into STOCK + 6. How many instructions does each need?
- 1LOAD BAYS, PUSH 3, MUL, PUSH 1, ADD
- 213
- 35 before folding, 3 after; both give 34 when STOCK = 28
Syntax diagrams and BNF
Which strings count as a name? A syntax diagram draws the valid routes. Backus–Naur Form (BNF) writes them as rules: ::= means “is defined as”; | separates alternatives.
A loop in the diagram: recursion in BNF
Step K7M through the diagram. The first box takes K; the loop back takes 7 and then M.
- The ellipsis abbreviates the remaining capital-letter alternatives.
<letter>and<digit>are non-terminals; the actual characters are terminals.
- 1Read the diagram from entry to exit: consume the first letter.
- 2Then take the return route zero or more times. It runs right to left through either a letter or a digit.
- 3BAYS2 follows letter B, returns for A, Y, S and 2, then exits. 2BAYS fails at the first box; an empty string cannot pass it.
- 4The first BNF alternative supplies the stopping case, so recursion can finish.
The ellipsis abbreviates the remaining capital-letter alternatives. <letter> and <digit> are non-terminals; the actual characters are terminals. Read the diagram from entry to exit: consume the first letter, then take the return route zero or more times. The return route runs right to left through either a letter or a digit.
BAYS2 follows letter B, returns for A, Y, S and 2, then exits. 2BAYS fails at the first box; an empty string cannot pass it. The first BNF alternative supplies the stopping case, so recursion can finish.
Turn alternatives into an optional route
- 1Both alternatives begin with a letter: draw that box once.
- 2One route then goes through a digit; the other bypasses it. The routes rejoin before the exit.
- 3B and B2 are valid tags; B22 is not. A return loop would wrongly allow unlimited digits.
Both alternatives begin with a letter: draw that box once. One route then goes through a digit; the other bypasses it. The routes rejoin before the exit. B and B2 are valid tags; B22 is not. A return loop would wrongly allow unlimited digits.
1 Is K a valid identifier? Is 7K?
2 Is B7 a valid tag? Is BB?
3 Which BNF alternative stops the recursion in <identifier>?
- 1K: yes, one letter; 7K: no, it must start with a letter
- 2B7: yes, a letter then a digit; BB: no, the second character must be a digit
- 3
<identifier> ::= <letter>: a single letter, with no further call
Infix and Reverse Polish Notation
To work out (STOCK − 4) / (BAYS + 2), you use brackets and precedence to decide what comes first. A machine would rather read straight through. Infix puts an operator between its operands. Reverse Polish Notation (RPN) puts it after both operands, so the order is explicit without brackets.
Infix → RPN: finish each operand before its operator
Build the tree first. Then write each node only once both of its children are written; the black numbers give that order.
Read the nodes in number order and the RPN builds up one part at a time:
| Part of the expression | RPN |
|---|---|
| Numerator: STOCK − 4 | STOCK 4 − |
| Denominator: BAYS + 2 | BAYS 2 + |
| Divide numerator by denominator | STOCK 4 − BAYS 2 + / |
- For an expression tree, visit the left subtree, then the right subtree, then its operator (post-order).
- Apply precedence and brackets while forming the tree; do not simply move every operator to the end.
RPN → infix: combine two complete expressions
Converting back is how you check that an RPN string means what you intended. Read the RPN left to right. One row per token; the cells are the expressions on the stack, bottom first.
| Expression stack · bottom → top | What happens | |
|---|---|---|
| read STOCK | STOCK | operand: push it |
| operand: push it | ||
| read 4 | STOCK4 | operand: push it |
| operand: push it | ||
| read − | (STOCK − 4) | operator: pop the right, then the left; push (left op right) |
operator: pop the right, then the left; push (left op right) | ||
| read BAYS | (STOCK − 4)BAYS | operand: push it |
| operand: push it | ||
| read 2 | (STOCK − 4)BAYS2 | operand: push it |
| operand: push it | ||
| read + | (STOCK − 4)(BAYS + 2) | operator: pop the right, then the left; push (left op right) |
operator: pop the right, then the left; push (left op right) | ||
| read / | ((STOCK − 4) / (BAYS + 2)) | operator: pop the right, then the left; push (left op right) |
operator: pop the right, then the left; push (left op right) | ||
| Read | Expression stack · bottom → top |
|---|---|
| STOCK, then 4 | STOCK · 4 |
| − | (STOCK − 4) |
| BAYS, then 2 | (STOCK − 4) · BAYS · 2 |
| + | (STOCK − 4) · (BAYS + 2) |
| / | ((STOCK − 4) / (BAYS + 2)) |
- 1On an operator, pop the right expression first, then the left.
- 2Join them as
(left operator right)and push the new expression. - 3Outer brackets may be removed; brackets that protect a sum or denominator must stay.
Left-to-right order and brackets
A pair of brackets can give the same numbers and operators a different answer:
| Infix | RPN | Result |
|---|---|---|
| 18 − 6 − 3 | 18 6 − 3 − | 9 |
| 18 − (6 − 3) | 18 6 3 − − | 15 |
1 Convert (BAYS + 2) * 3 to RPN.
2 Convert STOCK − BAYS * 2 to RPN.
3 Convert the RPN 8 2 3 + * to infix.
- 1
BAYS 2 + 3 * - 2
STOCK BAYS 2 * −: the multiplication is grouped first - 3
8 * (2 + 3)
Evaluating RPN with a stack
This is where RPN pays off: one stack works out the answer in a single pass, with no brackets to look ahead for. Read RPN left to right. Push each operand’s value. At an operator, pop two values, apply the operation, then push its result. The final single value is the answer.
Evaluate STOCK 4 − BAYS 2 + / with STOCK = 28 and BAYS = 4. The right-hand end of each printed stack is its top.
Follow the stack as each token arrives: an operand adds one box, and an operator takes two away and puts one back.
The same run as rows, with each pop and sum written out:
| Stack · bottom → top | Action | |
|---|---|---|
| STOCK | 28 | Push 28 |
| Push 28 | ||
| 4 | 284 | Push 4 |
| Push 4 | ||
| − | 24 | Pop 4, then 28; 28 − 4 = 24; push 24 |
| Pop 4, then 28; 28 − 4 = 24; push 24 | ||
| BAYS | 244 | Push 4 |
| Push 4 | ||
| 2 | 2442 | Push 2 |
| Push 2 | ||
| + | 246 | Pop 2, then 4; 4 + 2 = 6; push 6 |
| Pop 2, then 4; 4 + 2 = 6; push 6 | ||
| / | 4 | Pop 6, then 24; 24 / 6 = 4; push 4 |
| Pop 6, then 24; 24 / 6 = 4; push 4 | ||
| Read | Action | Stack · bottom → top |
|---|---|---|
| STOCK | Push 28 | 28 |
| 4 | Push 4 | 28, 4 |
| − | Pop 4, then 28; 28 − 4 = 24; push 24 | 24 |
| BAYS | Push 4 | 24, 4 |
| 2 | Push 2 | 24, 4, 2 |
| + | Pop 2, then 4; 4 + 2 = 6; push 6 | 24, 6 |
| / | Pop 6, then 24; 24 / 6 = 4; push 4 | 4 |
Which value popped is the left operand
For + and × the order does not matter. For − and / it decides the answer:
- 1The first value popped is the right operand; the second is the left operand.
- 2Reversing them gives 4 − 28 = −24 at subtraction and 6 / 24 = 0.25 at division. The trace keeps the required order.
Check against the original infix expression
- During evaluation, the stack contains values, not operator symbols or variable names. Replace a variable by its supplied value when it is read.
- The expression stack used for conversion has a different job: it stores expression fragments.
1 Evaluate the RPN 6 2 3 + *.
2 What is on the stack, bottom to top, just after 3 is read?
3 Evaluate STOCK BAYS 2 * − with STOCK = 28 and BAYS = 4.
- 12 + 3 = 5, then 6 × 5 = 30
- 26, 2, 3
- 34 × 2 = 8, then 28 − 8 = 20
Following an expression through translation
Put the stages together and one formula travels from the characters a programmer typed to the answer 4. A translation pipeline preserves the expression’s meaning while changing its representation. Each stage answers a different question about the same source.
Follow the formula down the four stages. Each arrow is labelled with what one stage hands to the next.
1 · Characters → tokens
(STOCK − 4) / (BAYS + 2) becomes brackets, identifiers, integers and operators. Names link to symbol-table entries; spaces and the comment disappear.
2 · Tokens → grammatical structure
The parser recognises two bracketed factors joined by division. Their internal difference and sum become separate subtrees. A misplaced operator is reported here.
3 · Structure → target operations
Generate the numerator’s operations, then the denominator’s, then DIV. Optimise only transformations that preserve the result for every permitted input.
4 · Operations → result
With STOCK = 28 and BAYS = 4, the runtime loads values, forms 24 and 6, and divides to obtain 4.
Which stage finds each error
Because each stage checks something different, each kind of mistake is caught at its own point:
| Changed source | Earliest relevant failure |
|---|---|
STOCK @ 4 | Lexical: @ is outside the language’s tokens. |
STOCK − / 4 | Syntax: an operator appears where a factor is required. |
(STOCK − 4) / (BAYS − 4) with BAYS = 4 | Runtime: the legal structure evaluates its denominator to zero. |
When a valid formula is still wrong
- 1
STOCK − 4 / (BAYS + 2)is grammatically valid, but division binds first: it means STOCK − (4 / (BAYS + 2)), not the intended share. - 2A compiler can translate this wrong formula successfully.
- 3Compare the structure and tested result with the requirement as well as checking that translation succeeds.
1 At which stage does STOCK # 2 first fail?
2 At which stage does ( BAYS + 2 first fail?
3 With BAYS = 4, at which stage does STOCK / (BAYS − 4) first fail?
- 1lexical:
#is not a token - 2syntax: the bracket is never closed
- 3runtime: the denominator evaluates to zero