📑 Contents

Chapter 16.2: Translation Software

9618 Computer Science

📚 Learning Objectives
📋 Prior Knowledge Required
🌟 Did You Know?

Translation software is the bridge between human-readable code and machine-executable instructions. Without translators like compilers and interpreters, programmers would need to write programs directly in binary machine code!

1. Interpreter vs Compiler

A translator is system software that converts source code written in a high-level programming language into machine code. There are two main types: compilers and interpreters.

1.1 What is a Compiler?

📖 Definition: Compiler

A compiler is a computer program that transforms code written in a high-level programming language into machine code. It translates the entire source code before the program runs.

📝 How a Compiler Works
  1. Source code is input to the compiler
  2. Compiler translates entire program into object code
  3. Object code (machine code) is produced and saved
  4. Object code can be executed without recompilation
  5. Any syntax errors are reported after complete analysis

1.2 What is an Interpreter?

📖 Definition: Interpreter

An interpreter is a computer program that executes high-level code line by line. It does not produce a separate translated version - it directly executes the source code.

📝 How an Interpreter Works
  1. Source code is read one statement at a time
  2. Each statement is analysed and translated
  3. Statement is executed immediately if no errors
  4. Control returns to interpreter for next statement
  5. If error found, execution stops and error reported immediately
COMPILER: Source Code Object Code Output INTERPRETER: Source Code line by line Output

2. Compiler vs Interpreter Comparison

FeatureCompilerInterpreter
TranslationTranslates entire program at once before executionTranslates and executes one line at a time
Output FileProduces object code (.exe) fileNo object code produced
Execution SpeedCompiled code runs fasterInterpreted code runs slower
Error ReportingReports all errors after compilationReports errors line by line immediately
Error CorrectionMust recompile after fixing errorsCan correct errors and continue execution
Memory UsageObject code saved - can run without sourceInterpreter needed every time program runs
Use CasesProduction software, large applicationsDevelopment, debugging, rapid prototyping
💡 Exam Tip

Remember the key difference: Compiler = Complete translation before execution, Interpreter = Line-by-line translation during execution. Compilers produce object code that can be run independently; interpreters need to be present every time the program runs.

🧠 Memory Trick

2.1 Example Use Cases

Compiler Use Cases: C, C++, Java (compiles to bytecode), production software, embedded systems.
Interpreter Use Cases: Python, JavaScript, BASIC, educational tools, rapid prototyping, debugging environments.

3. Stages in Compilation

A compiler has a 'front-end analysis' and a 'back-end synthesis'. The process of translating source code into object code can be divided into four stages:

📖 Four Stages of Compilation
  1. Lexical Analysis - Converts source code into tokens
  2. Syntax Analysis - Checks grammar rules and creates parse tree
  3. Code Generation - Produces object code in machine-readable form
  4. Optimisation - Refines code to run more efficiently
1. Lexical Analysis 2. Syntax Analysis 3. Code Generation 4. Optimisation Front-End Analysis Back-End Synthesis
🌟 Front-End vs Back-End

The front-end performs analysis of source code and produces intermediate code. The back-end takes this intermediate code and performs synthesis of object code optimised for the target machine.

4. Lexical Analysis

Lexical analysis is the first stage in compilation. It studies the "words" or vocabulary of the programming language and converts the source program into tokens.

4.1 What Happens During Lexical Analysis?

📝 Tasks in Lexical Analysis

4.2 What is a Token?

📖 Definition: Token

A token is a sequence of characters that can be treated as a unit in the grammar of the programming language. A lexeme is the actual sequence of alphanumeric characters that forms a token.

Token TypeExamples
Keywordsvar, const, function, for, while, if, return, DECLARE, INTEGER
IdentifiersVariable names, function names (e.g., x, Count, max)
Operators+, -, *, /, =, ++, --
Separators, ; { } ( ) [ ]
💡 Exam Tip

Statement: Var Count : integer ; contains 5 tokens (Var, Count, :, integer, ;). Statement: PercentMark[Count] := Score * 10 contains 8 tokens.

5. Keyword Table and Symbol Table

5.1 Keyword Table

The keyword table contains all the reserved words and symbols that can be used in the programming language. Every program being compiled uses the same keyword table.

Symbol/KeywordToken (Hex)
=01
+02
-03
*04
DECLARE31
INTEGER32
INPUT33
OUTPUT34

5.2 Symbol Table

The symbol table is built for every program during compilation. It contains all identifiers (variables, constants) found in the source code.

📖 Symbol Table Contents
⚠️ Important

At lexical analysis stage, only variable names are noted in the symbol table. Other details like data type and scope are entered in the next stage (syntax analysis). The symbol table is used in later stages of compilation.

6. Syntax Analysis

Syntax analysis (also known as parsing) is the second stage of compilation. The tokenised output from lexical analysis is checked against the language's grammar rules.

6.1 Tasks in Syntax Analysis

📝 What Happens During Syntax Analysis
📖 Parse Tree

A parse tree is a tree data structure made up of nodes and branches that represents the syntactic structure of the input based on the grammar of the language.

Parse Tree for: z = x + y = z + x y
💡 Error Handling

If errors are found, each statement and associated error are output. Code generation will NOT be attempted if there are syntax errors. The compilation process finishes after this stage if errors exist.

7. Code Generation

During the code generation stage, the compiler transforms the tokenised form into code that can be understood by the computer's processor.

📖 Object Code

The object program is in machine-readable form (binary). It is no longer designed to be read by humans. The program must be syntactically correct for object code to be produced.

📝 Intermediate Code

Intermediate code lies between high-level language and machine code. It can support:

8. Optimisation

The optimisation stage creates an efficient object program. Optimised programs perform tasks using minimum resources (time, storage space, memory, CPU use).

Optimisation TypeDescriptionExample
Redundant Instruction EliminationRemove duplicate or unnecessary calculationsx = a + b; y = a + b → calculate once, use twice
Unreachable Code RemovalRemove code that will never executeCode after unconditional return statement
Flow/Control OptimisationSimplify control structuresRemove unnecessary jumps or branches
Loop OptimisationMove invariant code outside loopsCalculations that don't change inside loop
🌟 Benefits of Optimisation

9. Backus-Naur Form (BNF)

BNF is a meta-language - a way of writing rules that define the syntax of programming languages. It is a formal mathematical way to describe a language's grammar.

9.1 BNF Symbols

SymbolMeaningExample
::="is defined as" - separates name from definition<digit> ::= 0 | 1 | 2 | ...
< >Encloses a non-terminal element (needs further definition)<integer>, <digit>
|"OR" - indicates a choice between alternatives0 | 1 | 2 | 3
;Marks the end of a ruleEnd of definition
📖 Terminal vs Non-Terminal

9.2 BNF Examples

Example 1: Defining a digit
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Example 2: Defining an integer (single digit)
<integer> ::= <digit>
Example 3: Defining an integer (multiple digits using recursion)
<integer> ::= <digit> | <digit><integer>
💡 Understanding Recursion in BNF

For the number 1524: It's a digit (1) followed by an integer (524). Then 524 is a digit (5) followed by integer (24), and so on. The recursion stops when we reach a single digit.

10. More BNF Examples

10.1 Unsigned Integer

<unsigned integer> ::= <digit> | <digit><unsigned integer>
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

10.2 Signed Integer

<signed integer> ::= <sign><unsigned integer>
<sign> ::= + | -

10.3 Letter and Variable

Defining a letter:
<letter> ::= A | B | C | D | E | ... | Z | a | b | c | ... | z
Variable (letter followed by digit):
<variable> ::= <letter><digit>
Variable (letter followed by letter or any number of digits):
<variable> ::= <letter> | <letter><letter> | <letter><digit> | <letter><variable>

10.4 Assignment Statement

<assignment> ::= <variable> = <expression>;
<expression> ::= <variable> | <variable><operator><variable>
<operator> ::= + | - | * | /
🧠 Remember the Pattern

11. Syntax Diagrams

Syntax diagrams are graphical notations that use shapes and symbols to represent different elements of a language. They are a visual alternative to BNF.

11.1 How to Read Syntax Diagrams

📖 Syntax Diagram Symbols
Syntax Diagram for <digit>: 0 or 1 . . . 9 Syntax Diagram for <integer>: digit
💡 Reading Tip

Always start reading from the left and follow the flow to the right. Rectangles mean "see another diagram"; circles are final values.

12. More Syntax Diagram Examples

12.1 IF Statement Syntax Diagram

IF condition THEN statement ELSE statement (optional)

12.2 Operator Syntax Diagram

<operator>: + - * / (any one)
❌ Common Mistake

Don't confuse the shapes! Circles/Ovals = Terminal symbols (actual values), Rectangles = Non-terminal symbols (need another diagram). IF, THEN, ELSE are terminals - they appear in circles!

13. Reverse Polish Notation (RPN)

RPN (also called postfix notation) is a method of representing expressions where the operator comes after the operands. It eliminates the need for brackets and precedence rules.

13.1 Infix vs Postfix (RPN)

NotationExampleDescription
Infix (standard)A + BOperator between operands
Postfix (RPN)A B +Operator after operands
Prefix (Polish)+ A BOperator before operands
📖 Why Use RPN?

13.2 Converting Infix to RPN

Example 1: a + b * c
Apply precedence: multiplication first → (a + (b * c))
RPN: a b c * +
Example 2: (a + b) * c
Brackets indicate addition first → ((a + b) * c)
RPN: a b + c *
Example 3: (7 - 2 + 8) / (9 - 5)
Left side: 7 2 - 8 +
Right side: 9 5 -
RPN: 7 2 - 8 + 9 5 - /
💡 Conversion Tip

Work from inside brackets out. Convert each sub-expression, then add the operator after its operands. RPN follows evaluation order naturally!

14. Evaluating RPN Using a Stack

RPN expressions are evaluated using a stack data structure. The stack follows LIFO (Last In, First Out) principle.

📝 Stack Evaluation Method
  1. Read expression from left to right
  2. If value encountered → PUSH onto stack
  3. If operator encountered:
    • POP top two values from stack
    • Apply operator (second popped ⊕ first popped)
    • PUSH result back onto stack
  4. Repeat until end of expression
  5. Final result is the single value remaining on stack

14.1 Example: Evaluate A B C * - (where A=2, B=3, C=4)

Evaluating: 2 3 4 * - Step 1: 2 PUSH 2 Step 2: 3 2 PUSH 3 Step 3: 4 3 2 PUSH 4 Step 4: * 12 2 3*4=12 Step 5: - -10 2-12=-10 Result: -10
⚠️ Important: Order of Operations

When applying operators: second popped ⊕ first popped. For subtraction: if stack has [2, 12] (top=12), we calculate 2 - 12 = -10, NOT 12 - 2!

15. Exam-Style Questions

1. Explain the difference between a compiler and an interpreter. [4 marks]

Answer:

  • A compiler translates the entire source code into object code before execution, producing a standalone executable file
  • An interpreter executes source code line by line without producing object code
  • Compiled code runs faster as translation happens once; interpreted code is slower as translation happens each time
  • Compilers report all errors after compilation; interpreters stop and report errors immediately when encountered
2. Describe the four stages of compilation. [8 marks]

Answer:

  • Lexical Analysis: Removes unnecessary characters (whitespace, comments); converts source code into tokens; builds symbol table
  • Syntax Analysis: Checks tokens against grammar rules; creates parse tree; reports syntax errors
  • Code Generation: Produces object code in machine-readable binary form; uses symbol table information
  • Optimisation: Removes redundant code; improves efficiency; reduces memory usage and execution time
3. What is the purpose of a symbol table in lexical analysis? [4 marks]

Answer:

  • Symbol table stores all identifiers (variables, constants) found in source code
  • Records the data type of each identifier
  • Records the role (variable, constant, array, procedure)
  • Assigns a unique token to each identifier for use in later compilation stages
4. Write BNF rules to define a positive integer (one or more digits). [4 marks]

Answer:

<integer> ::= <digit> | <digit><integer>
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

Explanation: The first rule says an integer is either a single digit OR a digit followed by another integer (recursion). This allows integers of any length.

5. Convert the infix expression (A + B) * (C - D) to RPN. [4 marks]

Answer:

A B + C D - *

Explanation: Work from inside brackets out. First (A + B) → A B +, then (C - D) → C D -, finally multiply → place * after both results.

15. Exam-Style Questions (Continued)

6. Evaluate the RPN expression: 5 3 2 * + 4 - using a stack. [6 marks]

Answer:

  1. Read 5: PUSH 5 → Stack: [5]
  2. Read 3: PUSH 3 → Stack: [5, 3]
  3. Read 2: PUSH 2 → Stack: [5, 3, 2]
  4. Read *: POP 2, 3 → 3*2=6 → PUSH 6 → Stack: [5, 6]
  5. Read +: POP 6, 5 → 5+6=11 → PUSH 11 → Stack: [11]
  6. Read 4: PUSH 4 → Stack: [11, 4]
  7. Read -: POP 4, 11 → 11-4=7

Final Result: 7

7. Explain what happens during optimisation. Give two examples. [6 marks]

Answer:

Optimisation creates an efficient object program that executes faster and uses fewer resources.

Examples:

  • Redundant instruction elimination: Remove duplicate calculations - if x = a + b appears twice, calculate once and reuse
  • Unreachable code removal: Remove code that will never execute (e.g., after unconditional return)
  • Loop optimisation: Move calculations that don't change outside loops
8. What is the difference between terminal and non-terminal symbols in BNF? [4 marks]

Answer:

  • Terminal symbols are actual values that cannot be broken down further. They appear without angle brackets (e.g., 0, 1, +, if, while)
  • Non-terminal symbols are elements that need to be defined by other rules. They are enclosed in angle brackets < > (e.g., <digit>, <integer>)
  • Example: <digit> ::= 0 | 1 | 2 — <digit> is non-terminal, 0-9 are terminals
9. Why do compilers use Reverse Polish Notation? [5 marks]

Answer:

  • RPN can be processed left to right without backtracking
  • No need for brackets - order determined by position
  • No need for precedence rules - evaluation order is explicit
  • RPN is unambiguous - one valid interpretation only
  • Can be evaluated efficiently using a stack-based algorithm
10. Draw a syntax diagram for a signed integer. [4 marks]

Answer:

+ - integer

Start with either + or -, followed by an integer (defined in another diagram).

16. Glossary

TermDefinition
CompilerSystem software that translates entire source code into object code before execution
InterpreterSystem software that executes source code line by line without producing object code
TokenA sequence of characters treated as a unit in programming language grammar
Lexical AnalysisFirst compilation stage that converts source code to tokens
Syntax AnalysisSecond compilation stage that checks tokens against grammar rules
Parse TreeTree structure representing the syntactic structure of a program
Code GenerationThird compilation stage that produces machine-readable object code
OptimisationFourth compilation stage that refines code for efficiency
Symbol TableData structure storing all identifiers with their attributes
BNFBackus-Naur Form - meta-language for defining syntax rules
Terminal SymbolA symbol that cannot be broken down further (actual value)
Non-terminal SymbolA symbol that needs to be defined by other rules
Syntax DiagramGraphical representation of grammar rules using shapes
RPNReverse Polish Notation - postfix notation with operator after operands
Object CodeMachine-readable code produced by a compiler

17. Exam Success Tips

💡 Compiler vs Interpreter
💡 Compilation Stages Order

Memory trick: "Little Students Create Objects"
L = Lexical, S = Syntax, C = Code Generation, O = Optimisation

💡 BNF Symbols
💡 Syntax Diagrams
❌ Common Mistakes to Avoid

18. Key Takeaways

📌 Summary Points

Compiler vs Interpreter

Compilation Stages

BNF and Syntax Diagrams

Reverse Polish Notation

🌟 Final Reminder

Remember: Read questions carefully, check mark allocations, use technical terms (token, parse tree, BNF, RPN), show your working for RPN stack evaluation, and manage your time effectively!