Skip to content

9618 · Unit 19 · Paper 3: Advanced theory

Translation, grammar and expression evaluation.

9618 · Unit 19 · Translation, grammar and expression evaluation
Revisionbyexamplicity

Interpreters and compilers

§16.2 · Translation and expression evaluation

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.

Compiler: translate, then runSource programall statements checkedTranslated programsaved for repeated executionProcessor executessource and compiler not needed

Interpret one statement, then continue

1
Read the next source statement and check it.
2
Execute it if valid; report an error and halt if it is invalid.
3
Repeat for the next statement. A loop revisits its statements; another run interprets them again.
  • 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.

AspectCompilerInterpreter
Preparing a runChecks and translates the whole source first.Can execute valid statements before a later error is reached.
Running againReuses the saved executable; translation is not repeated.Needs source and interpreter; repeats interpretation.
Changing sourceTranslate the changed program again.Try a changed part during development.
Execution speedUsually 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.
Your turn

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?

  1. 1
    a compiler
  2. 2
    an interpreter: it executes each valid statement before it reaches the error
  3. 3
    compile once, then run the saved executable
Tick what you can do now
Practise with s25/31 Q6 (older paper)
1 / 8
9618 · Unit 19 · Translation, grammar and expression evaluation
Revisionbyexamplicity

Lexical analysis

§16.2 · Translation and expression evaluation

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.

(STOCK - 4) / (BAYS + 2) // batch share

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.

(bracketSTOCKidentifier→ symbol table−operator4integer)bracket/operator(bracketBAYSidentifier→ symbol table+operator2integer)bracketSpaces and the comment // batch share are not tokens: removed
Token sequenceCategories
( · 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.

IdentifierTypeStorage location
STOCKINTEGER400
BAYSINTEGER401

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 fragmentWhat the analyser finds
STOCK @ 4@ is not a token in this language: a lexical error.
STOCK − / 4Every token is recognised. Their order must be checked by syntax analysis.
Your turn

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?

  1. 1
    TOTAL1, +, 25: three tokens; the comment is removed
  2. 2
    TOTAL1 and RATE, once each
  3. 3
    an identifier must begin with a letter, so 9 is read as an integer and X as a separate identifier
Tick what you can do now
Practise with s25/32 Q8; w25/31 Q8(a) (older papers)
2 / 8
9618 · Unit 19 · Translation, grammar and expression evaluation
Revisionbyexamplicity

Syntax analysis

§16.2 · Translation and expression evaluation

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

<expression> ::= <term> | <expression> + <term> | <expression> - <term>
<term> ::= <factor> | <term> * <factor> | <term> / <factor>
<factor> ::= <integer> | <identifier> | ( <expression> )
  • 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.

/−+STOCK4BAYS2
  1. 1
    The operation branches show the accepted structure: divide the entire difference by the entire sum.
  2. 2
    Each leaf is an operand.
  3. 3
    Grammar-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 streamReason
STOCK − / 4After −, a term must begin with a factor; / cannot begin one.
( STOCK − 4The factor opened with ( needs a closing ).
STOCK 4Two 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.

Your turn

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?

  1. 1
    yes: a term times a bracketed factor
  2. 2
    no: the factor opened with ( has no closing )
  3. 3
    the multiplication: 4 × 2 forms a term before the subtraction joins it
Tick what you can do now
Practise with s25/33 Q8 (older paper)
3 / 8
9618 · Unit 19 · Translation, grammar and expression evaluation
Revisionbyexamplicity

Code generation and optimisation

§16.2 · Translation and expression evaluation

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.

  1. 1
    LOAD pushes a variable’s value; PUSH pushes a literal.
  2. 2
    An arithmetic instruction pops the right operand, then the left, and pushes the result.
  3. 3
    These are this stack target’s defined operations, not processor mnemonics.

One row per generated instruction. Follow the stack after each one runs.

Stack · bottom → topWhat it does
LOAD STOCK28Push 28
Push 28
PUSH 4284Push 4
Push 4
SUB24Pop 4, then 28; 28 − 4 = 24; push 24
Pop 4, then 28; 28 − 4 = 24; push 24
LOAD BAYS244Push 4
Push 4
PUSH 22442Push 2
Push 2
ADD246Pop 2, then 4; 4 + 2 = 6; push 6
Pop 2, then 4; 4 + 2 = 6; push 6
DIV4Pop 6, then 24; 24 / 6 = 4; push 4
Pop 6, then 24; 24 / 6 = 4; push 4
Generated target instructionStack after execution · bottom → top
LOAD STOCK28
PUSH 428, 4
SUB24
LOAD BAYS24, 4
PUSH 224, 4, 2
ADD24, 6
DIV4

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

STOCK − (2 + 2) → STOCK − 4

Amber: the instructions that constant folding removes. 2 + 2 is worked out once, during compilation.

STOCK − (2 + 2)LOAD STOCKPUSH 2PUSH 2ADDSUBSTOCK − 4LOAD STOCKPUSH 4SUB5 instructions3 instructions

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 optimisationCondition that preserves behaviour
Remove redundant operationsThey have no effect needed by later code.
Avoid repeating a calculationIts inputs have not changed.
Reorder instructionsDependencies 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.

Your turn

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?

  1. 1
    LOAD BAYS, PUSH 3, MUL, PUSH 1, ADD
  2. 2
    13
  3. 3
    5 before folding, 3 after; both give 34 when STOCK = 28
Tick what you can do now
Practise with w25/33 Q7(a); w25/32 Q8(a) (older papers: optimisation)
4 / 8
9618 · Unit 19 · Translation, grammar and expression evaluation
Revisionbyexamplicity

Syntax diagrams and BNF

§16.2 · Translation and expression evaluation

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.

identifierInputK172M3K7M acceptedUnderline = readletterletterdigit
<identifier> ::= <letter> | <identifier><letter> | <identifier><digit>
<letter> ::= A | B | … | Z
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
  • The ellipsis abbreviates the remaining capital-letter alternatives.
  • <letter> and <digit> are non-terminals; the actual characters are terminals.
  1. 1
    Read the diagram from entry to exit: consume the first letter.
  2. 2
    Then take the return route zero or more times. It runs right to left through either a letter or a digit.
  3. 3
    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.
  4. 4
    The 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

<tag> ::= <letter> | <letter><digit>
tagletterdigit
  1. 1
    Both alternatives begin with a letter: draw that box once.
  2. 2
    One route then goes through a digit; the other bypasses it. The routes rejoin before the exit.
  3. 3
    B 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.

Your turn

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>?

  1. 1
    K: yes, one letter; 7K: no, it must start with a letter
  2. 2
    B7: yes, a letter then a digit; BB: no, the second character must be a digit
  3. 3
    <identifier> ::= <letter>: a single letter, with no further call
Tick what you can do now
Practise with s25/32 Q9(a)–(d); w24/32 Q7(c)(i), (c)(ii) (older papers)
5 / 8
9618 · Unit 19 · Translation, grammar and expression evaluation
Revisionbyexamplicity

Infix and Reverse Polish Notation

§16.2 · Translation and expression evaluation

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.

(STOCK - 4) / (BAYS + 2)

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.

/7−3+6STOCK142BAYS425Numbers: the order post-order writes each node

Read the nodes in number order and the RPN builds up one part at a time:

Part of the expressionRPN
Numerator: STOCK − 4STOCK 4 −
Denominator: BAYS + 2BAYS 2 +
Divide numerator by denominatorSTOCK 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 → topWhat happens
read STOCKSTOCKoperand: push it
operand: push it
read 4STOCK4operand: 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)BAYSoperand: push it
operand: push it
read 2(STOCK − 4)BAYS2operand: 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)
ReadExpression stack · bottom → top
STOCK, then 4STOCK · 4
−(STOCK − 4)
BAYS, then 2(STOCK − 4) · BAYS · 2
+(STOCK − 4) · (BAYS + 2)
/((STOCK − 4) / (BAYS + 2))
  1. 1
    On an operator, pop the right expression first, then the left.
  2. 2
    Join them as (left operator right) and push the new expression.
  3. 3
    Outer 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:

InfixRPNResult
18 − 6 − 318 6 − 3 −9
18 − (6 − 3)18 6 3 − −15
Your turn

1 Convert (BAYS + 2) * 3 to RPN.

2 Convert STOCK − BAYS * 2 to RPN.

3 Convert the RPN 8 2 3 + * to infix.

  1. 1
    BAYS 2 + 3 *
  2. 2
    STOCK BAYS 2 * −: the multiplication is grouped first
  3. 3
    8 * (2 + 3)
Tick what you can do now
Practise with s26/31 Q7(a), (b); s26/32 Q6(a), (b); s26/33 Q7(b)
6 / 8
9618 · Unit 19 · Translation, grammar and expression evaluation
Revisionbyexamplicity

Evaluating RPN with a stack

§16.2 · Translation and expression evaluation

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.

STOCKpush284push284−pop 2push 124BAYSpush2442push2442+pop 2push 1246/pop 2push 14Each column: the stack after that token. Blue: the top.

The same run as rows, with each pop and sum written out:

Stack · bottom → topAction
STOCK28Push 28
Push 28
4284Push 4
Push 4
−24Pop 4, then 28; 28 − 4 = 24; push 24
Pop 4, then 28; 28 − 4 = 24; push 24
BAYS244Push 4
Push 4
22442Push 2
Push 2
+246Pop 2, then 4; 4 + 2 = 6; push 6
Pop 2, then 4; 4 + 2 = 6; push 6
/4Pop 6, then 24; 24 / 6 = 4; push 4
Pop 6, then 24; 24 / 6 = 4; push 4
ReadActionStack · bottom → top
STOCKPush 2828
4Push 428, 4
−Pop 4, then 28; 28 − 4 = 24; push 2424
BAYSPush 424, 4
2Push 224, 4, 2
+Pop 2, then 4; 4 + 2 = 6; push 624, 6
/Pop 6, then 24; 24 / 6 = 4; push 44

Which value popped is the left operand

For + and × the order does not matter. For − and / it decides the answer:

  1. 1
    The first value popped is the right operand; the second is the left operand.
  2. 2
    Reversing 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

(28 − 4) / (4 + 2) = 24 / 6 = 4
  • 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.
Your turn

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.

  1. 1
    2 + 3 = 5, then 6 × 5 = 30
  2. 2
    6, 2, 3
  3. 3
    4 × 2 = 8, then 28 − 8 = 20
Tick what you can do now
Exam focusShow the stack after each token, including intermediate results. Subtraction and division use the second value popped as the left operand; keeping only the final total does not show the stack process.
Practise with s26/31 Q7(c); s26/32 Q6(c); s26/33 Q7(a), (c)
7 / 8
9618 · Unit 19 · Translation, grammar and expression evaluation
Revisionbyexamplicity

Following an expression through translation

§16.2 · Translation and expression evaluation

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.

source: (STOCK − 4) / (BAYS + 2)1Lexical analysispasses on 11 tokens2Syntax analysispasses on a parse tree3Code generation and optimisationpasses on 7 target instructions4Executiongives the result 4

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 sourceEarliest relevant failure
STOCK @ 4Lexical: @ is outside the language’s tokens.
STOCK − / 4Syntax: an operator appears where a factor is required.
(STOCK − 4) / (BAYS − 4) with BAYS = 4Runtime: the legal structure evaluates its denominator to zero.

When a valid formula is still wrong

  1. 1
    STOCK − 4 / (BAYS + 2) is grammatically valid, but division binds first: it means STOCK − (4 / (BAYS + 2)), not the intended share.
  2. 2
    A compiler can translate this wrong formula successfully.
  3. 3
    Compare the structure and tested result with the requirement as well as checking that translation succeeds.
Your turn

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?

  1. 1
    lexical: # is not a token
  2. 2
    syntax: the bracket is never closed
  3. 3
    runtime: the denominator evaluates to zero
Tick what you can do now
Practise with s25/32 Q8; s25/33 Q8 (older papers: analysis stages)
8 / 8