A Level Computer Science · Chapter 4 · Component 01: Computer systems
Programs are written in languages people can read, so translators turn them into machine code, and different programming paradigms offer different ways of describing a solution.
This chapter teaches how assemblers, compilers and interpreters work, and the stages a compiler goes through, from lexical analysis to optimisation. It then teaches how linkers and libraries assemble a finished program, and how procedural, object-oriented, functional and declarative paradigms compare.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- distinguish low-level and high-level languages, and explain the job of an assembler, a compiler and an interpreter
- compare compiling and interpreting, and calculate when compiling saves time overall
- describe lexical analysis, split a line of code into tokens and build a symbol table
- describe syntax analysis, code generation and optimisation, including constant folding
- explain the roles of linkers, loaders and libraries, and compare static and dynamic linking
- compare the procedural, object-oriented, functional and declarative paradigms
- use map, filter and reduce to describe a computation functionally
Time: three sessions, about 4 hours, plus the programming task.
You need first: assembly language from Assembly language and addressing modes, and programming constructs from Programming constructs.
The big picture
The big picture
A processor runs only machine code, long sequences of binary instructions. People find machine code almost impossible to write or read, so they write programs in languages designed for humans. Something must bridge the gap. That something is a translator.
There are three kinds. An assembler translates assembly language, one line to one instruction. A compiler translates a whole high-level program into machine code before it runs. An interpreter translates and runs a high-level program one statement at a time. Each suits different situations.
A compiler works in stages. Lexical analysis breaks the source text into tokens, such as names, numbers and operators. Syntax analysis checks that the tokens follow the rules of the language and builds a tree that shows the program's structure. Code generation turns that tree into machine code, and optimisation makes the code faster or smaller without changing what it does.
Few programs are written entirely from scratch. They call on libraries of code that someone else has written and tested, such as routines for maths, graphics or networking. A linker joins the program and its libraries together, and a loader puts the result into memory to run.
Languages also differ in their whole approach, called their paradigm. Procedural languages describe a sequence of steps. Object-oriented languages describe objects that hold data and act on it. Functional languages describe a computation as functions applied to values. Declarative languages describe what result is wanted and leave the computer to work out how.
Think of translating a recipe from one language to another. A careful translator first picks out the individual words, then checks that each sentence makes sense, then writes the new version, and finally tidies it so it reads well. A compiler follows the same order: words become tokens, sentences become a syntax tree, and the tree becomes tidy machine code.
None of this is visible to most programmers, who simply press a button to run their code. But knowing what happens explains a great deal. It explains why a missing bracket is reported before any code runs, and why a compiled game starts faster than an interpreted script. It also explains why a program can fail on a computer that lacks a library it needs.
The chapter moves from the lowest level upwards. It starts with the languages themselves and the translators that handle them, then follows a program through each stage of compilation. After that it looks at how the finished pieces are joined and loaded, and ends by comparing the main styles in which programs are written.
Section 1
Levels of language and translators
Low-level and high-level languages
Machine code and assembly language are low-level languages: they work directly with a particular processor's instructions, registers and memory addresses. A program written in them runs only on that family of processors. High-level languages, such as Python, Java and C#, describe a solution in terms closer to the problem, using variables, loops and functions.
High-level code is shorter, easier to read and portable: the same program can be translated for many different processors. Low-level code gives exact control over the hardware and can be faster and smaller, which matters for device drivers and embedded systems.
Languages are sometimes grouped into generations. The first generation is machine code itself, written directly in binary. The second is assembly language, which replaces each binary instruction with a short mnemonic, such as LDA or ADD, and each address with a name. High-level languages make up the third generation and beyond, where a single statement can stand for many machine instructions.
Each step up the generations makes programs quicker to write and easier to maintain, but moves the programmer further from the hardware. A programmer writing a game in a high-level language never needs to know which register holds a value. A programmer writing a driver for a new graphics card may need exactly that knowledge.
Worked example 1: one statement, several instructions
The high-level statement total = total + price is translated into assembly language for an accumulator machine. How many instructions are needed, and what are they?
| Working | Reason |
|---|---|
| LDA total loads the current total into the accumulator | The accumulator must hold the value first |
| ADD price adds the price to it | The ALU works on the accumulator |
| STA total stores the result back in total | The new value must be saved in memory |
| 3 instructions for 1 statement | High-level code hides these details |
The three translators
An assembler translates assembly language into machine code. Each assembly instruction becomes exactly one machine instruction, so the translation is direct. A compiler translates a whole high-level program into machine code, producing an executable file that can be run later without the compiler. An interpreter translates each high-level statement and runs it immediately, then moves to the next.
How an assembler works
An assembler does more than swap mnemonics for numbers. Programs use labels, such as loop or end, to name the lines that branches jump to. A branch near the top of a program may jump to a label that appears further down, which the assembler has not reached yet.
So most assemblers make two passes through the code. On the first pass, the assembler counts the instructions and records the address of every label in a symbol table. On the second pass, it translates each instruction, looking up any labels in the table to fill in their addresses. The result is one machine code instruction for each line of assembly language.
Common mistake: thinking an assembler translates high-level code. An assembler only translates assembly language, where each line is one machine instruction. High-level languages need a compiler or an interpreter, because a single high-level statement may become many machine instructions.
Check yourself. Why can the same Python program run on a laptop and on a phone, but an assembly language program usually cannot?
Show the answer
Python is a high-level language, so it can be translated for each processor separately. Assembly language is written for one processor's instruction set, so it only runs on processors that understand those exact instructions.
Section 2
Compiling and interpreting
Compilers
A compiler reads the whole source program, checks it for errors and translates it into machine code in one go. The result is an executable file. Once compiled, the program runs at full speed, the source code is not needed to run it, and users cannot easily read the original code. But every change means compiling again, and all the errors are reported together at the end.
Interpreters
An interpreter translates and runs one statement at a time. It stops at the first error and reports exactly where it is, which makes testing and debugging easy. But the program runs more slowly, because every statement is translated again each time it runs, and the interpreter must be present on every computer that runs the program.
Errors from each translator
The two translators report errors in different ways. A compiler checks the whole program first, so it can list every syntax error in one go, but nothing runs until they are all fixed. An interpreter runs the program until it meets an error, so the first half of a program may run perfectly before a mistake in the second half stops it.
Some errors only appear while a program runs, whichever translator is used. Dividing by zero, or reading past the end of a list, cannot always be spotted in advance, because they depend on the data. These are called run-time errors, and they are found by testing.
Protecting and distributing code
A compiled program can be given to customers as an executable alone, so the source code stays private. This protects the work of the programmers and makes the program harder to copy or alter. An interpreted program must be distributed as source code, because the interpreter needs it on every run.
An executable is specific to one kind of processor and operating system. A program compiled for a Windows laptop will not run on a phone, so a company must compile a separate version for each platform. A cross-compiler runs on one kind of computer but produces machine code for another, which is how software for phones and embedded devices is usually built.
Common mistake: thinking an interpreter produces an executable file. An interpreter runs the program directly, translating as it goes, and keeps no translated copy. Only a compiler produces an executable file that can later run on its own.
Intermediate code
Some languages combine the two. Java and Python first compile source code into an intermediate form called bytecode, which is not tied to any processor. A virtual machine then interprets or compiles the bytecode on each computer. The same bytecode runs anywhere a virtual machine exists, and the virtual machine can compile frequently used parts to machine code as the program runs.
Compiling parts of a program while it runs is called just-in-time compilation. The virtual machine watches which parts of the bytecode run most often, such as the body of a busy loop, and compiles just those parts into machine code. Rarely used parts are simply interpreted. This gives much of the speed of a compiled program while keeping the portability of bytecode.
Choosing a translator
The right choice depends on the situation. A short script that a teacher runs once to rename a folder of files gains nothing from being compiled, because it will run only a handful of times. A game engine that millions of players run every day must be compiled and heavily optimised, because every saved millisecond is multiplied many times over.
Development and release often use different approaches for the same program. While the program is being written, the programmers want quick feedback after every small change. Once it is finished, the users want it to start quickly and run smoothly, and the company wants its source code kept private.
When compiling pays off
Compiling costs time once, but saves time on every run afterwards. Suppose a program takes c seconds to compile and then r seconds per run. The interpreted version takes i seconds per run. After enough runs, the compiled version becomes quicker.
Derivation: when compiling saves time
After n runs, the compiled program has cost one compilation plus n fast runs. The interpreted program has cost n slow runs.
Compiling is quicker once c + n r < n i. Rearranging gives the number of runs after which compiling wins.
With c = 30, r = 1 and i = 4, n must exceed 30 ÷ 3 = 10, so compiling is quicker from the 11th run. If i is no more than r, compiling never pays off.
Figure 4.1 plots the total time for both approaches as the number of runs grows. Move the runs and see where the lines cross. Then switch on the wrong model, which recompiles the program on every run.
Compiling against interpreting
- Compiled total
- 38 s
- Interpreted total
- 32 s
- Compiling wins from run
- 11
Common mistake: thinking a compiled program is recompiled every time it runs. A compiler produces an executable once. Every later run uses that executable directly, with no further translation, until the source code is changed. Counting a compilation on every run makes compiling look far more expensive than it is.
Worked example 2: ten runs
A program takes 30 s to compile and then 1 s per run, or 4 s per run when interpreted. Compare the totals after 10 runs, and find when compiling becomes quicker.
| Working | Reason |
|---|---|
| Compiled: 30 + 10 × 1 = 40 s | One compilation, then ten fast runs |
| Interpreted: 10 × 4 = 40 s | Every run is translated again |
| They are equal after 10 runs | Both total exactly 40 seconds |
| From the 11th run, compiling is quicker | Because n must exceed 30 ÷ (4 − 1) = 10 |
Worked example 3: a hundred runs
For the same program, compare the totals after 100 runs.
| Working | Reason |
|---|---|
| Compiled: 30 + 100 × 1 = 130 s | The compilation cost is now small |
| Interpreted: 100 × 4 = 400 s | The slow runs add up |
| Compiling saves 400 − 130 = 270 s | The saving grows with every run |
| For a program run often, compiling clearly wins | Interpreting suits development and testing |
Check yourself. A program takes 120 s to compile and 2 s per run, or 5 s per run interpreted. From which run is compiling quicker?
Show the answer
Compiling wins once n > 120 ÷ (5 − 2) = 40. At exactly 40 runs the totals are equal, at 200 seconds each, so compiling is quicker from the 41st run.
Section 3
Lexical analysis
Tokens
The first stage of compilation is lexical analysis. The lexer, or scanner, reads the source code character by character and groups the characters into tokens, the smallest meaningful units of the language. Each token is labelled with its type: a keyword such as if, an identifier such as score, a number, a string, an operator or punctuation.
Lexical analysis also removes everything the later stages do not need. White space, such as spaces and tabs, and comments are discarded. If a character cannot belong to any token, such as a stray symbol, the lexer reports an error.
How a lexer reads characters
A lexer behaves like a finite state machine. It starts in a waiting state and reads one character. A letter moves it into a state for reading names, where it stays while further letters, digits or underscores arrive. A digit moves it into a state for reading numbers, and a quotation mark into a state for reading strings.
When a character arrives that cannot continue the current token, the token is finished. The lexer records it, returns to the waiting state and starts again with that character. This is why area=width*height splits correctly without spaces: the = cannot continue the name area, so the name ends there.
The lexer always takes the longest token it can. When it meets >, it looks at the next character before deciding. If that character is =, the two together form the single operator >=; otherwise > stands alone. The same rule makes count10 a single name rather than the name count followed by the number 10.
Figure 4.2 runs the lexer on three lines of code. Step through the tokens and read the type of each. Then switch on the wrong model, which simply splits the line at its spaces.
Lexical analysis
- Tokens
- 7
- Symbol table
- total, price
Common mistake: thinking tokens are just words separated by spaces. Splitting at spaces would make area=width*height a single piece, and would keep comments as if they were code. A lexer recognises operators, numbers and names wherever they appear, whether or not there are spaces between them.
Worked example 4: tokenising a statement
Split total = total + price * 2 // add into tokens, and give the type of each.
| Working | Reason |
|---|---|
| total, =, total, +, price, *, 2 | Each name, operator and number is one token |
| total and price are identifiers; =, + and * are operators | Each token is labelled with its type |
| 2 is a number token | Digits form a numeric literal |
| // add is a comment and is discarded: 7 tokens | Comments are not part of the program |
The symbol table
As the lexer finds identifiers, it records them in a symbol table. The table holds each name once, with information gathered during compilation. That includes its data type, whether it is a variable or a function, its scope and, later, its memory address. Every later stage looks names up in this table.
The lexer hands its output to the parser as a stream of tokens, one at a time. From this point on, the compiler never looks at the original characters again. This makes the later stages simpler: the parser deals with a short list of labelled tokens rather than a long string of letters, spaces and symbols.
Names are looked up very often, so the symbol table is usually stored as a hash table. Each look-up then takes about the same time, however many names there are. A language may allow the same name in different scopes, such as a local total inside a function and a global total outside it. The table then records each scope separately.
Worked example 5: keywords and identifiers
Tokenise if score >= 50 then print("Pass"), and give the symbol table entries.
| Working | Reason |
|---|---|
| if, score, >=, 50, then, print, (, "Pass", ) | Nine tokens in total |
| if, then and print are keywords of the language | Keywords are reserved words |
| >= is one operator, not two | The lexer takes the longest valid token |
| Only score goes in the symbol table | It is the only identifier the programmer made up |
Check yourself. How many tokens does area=width*height produce, and how many pieces would splitting at spaces give?
Show the answer
It produces 5 tokens: area, =, width, * and height. Splitting at spaces gives only 1 piece, because the line contains no spaces at all.
Section 4
Syntax analysis, code generation and optimisation
Syntax analysis
Syntax analysis, or parsing, checks that the tokens are arranged according to the grammar of the language. The grammar can be written in Backus-Naur form, which defines each part of the language in terms of smaller parts. For example, an assignment is an identifier, then =, then an expression.
The parser builds an abstract syntax tree, which shows how the tokens group together. In total = total + price * 2, the tree puts price * 2 lower down than the +, because multiplication is done first. If the tokens do not fit the grammar, such as a missing bracket, the parser reports a syntax error.
A small piece of grammar shows how this works. An assignment might be defined as an identifier, then =, then an expression. An expression might be defined as a term, or an expression followed by + and a term. A term might be a factor, or a term followed by * and a factor, and a factor might be a number or an identifier.
Because multiplication is defined inside a term, deeper than addition, the parser groups price * 2 before it adds total. The grammar itself sets the order of operations. A missing operand, as in total = total +, fails because nothing follows the +, though the grammar demands a term there.
Semantic checks and code generation
Next, the compiler checks meaning: for example, that every variable has been declared and that types are used correctly, such as not adding a number to a list. Then code generation walks the syntax tree and produces machine code, or an intermediate code, for each part. Names from the symbol table are given memory addresses.
For an accumulator machine, the tree for total = total + price * 2 might become five instructions. The processor loads price, multiplies it by 2, adds total and stores the result in total. The order of the instructions follows the tree from the bottom upwards, so the deepest operation is done first.
Optimisation
Optimisation improves the generated code without changing what it does. It might remove instructions that have no effect, reuse a value instead of calculating it twice, or move a calculation out of a loop if its result never changes. The program runs faster or uses less memory, but gives exactly the same results.
Two more optimisations are common. Dead code removal deletes instructions that can never run, such as the body of an if statement whose condition is always false. Loop-invariant code motion moves a calculation that gives the same answer on every pass, such as working out the length of a fixed list, to just before the loop.
Optimisation has a cost of its own. A highly optimising compiler takes longer to compile, and the code it produces can be harder to match up with the source when debugging. So compilers usually offer a quick setting for development and a thorough one for the final release.
Code generation can target an intermediate code instead of real machine code. Bytecode is one example. Many compilers translate first into a simple intermediate form, optimise that, and only then produce machine code for each processor. The same front end, which handles lexing and parsing, can then be shared by many back ends for different hardware.
Common mistake: thinking optimisation changes what a program does. Optimisation only changes how the result is reached, never the result itself. An optimised program must give the same output as the original for every input. A change that altered the output would be a bug.
One simple optimisation is constant folding. Where an expression combines only constant values, the compiler works out the answer during compilation and stores the result. The calculation then never has to happen while the program runs.
Worked example 6: folding constants
Apply constant folding to x = 60 * 60 * 24, and say what the program saves.
| Working | Reason |
|---|---|
| 60 * 60 = 3600, then 3600 * 24 = 86400 | Every value in the expression is a constant |
| The compiler stores x = 86400 | The result is known before the program runs |
| Two multiplications are removed from the program | They would otherwise run every time |
| The output is unchanged: x is still 86400 | Optimisation never changes the result |
Worked example 7: partial folding
Fold z = 3 + 4 * 5 and w = a + 2 * 3.
| Working | Reason |
|---|---|
| In z, 4 * 5 = 20 is folded first | Multiplication comes before addition |
| Then 3 + 20 = 23, so z = 23 | The whole expression is constant |
| In w, 2 * 3 = 6 is folded, giving w = a + 6 | Only the constant part can be folded |
| a + 6 must still be worked out at run time | a is a variable, so its value is not yet known |
Check yourself. What does constant folding turn s = 1024 * 8 into, and why can it not fold s = n * 8?
Show the answer
It becomes s = 8192, because both values are constants. In s = n * 8, the value of n is only known when the program runs, so the multiplication cannot be done during compilation.
Section 5
Linkers, loaders and libraries
Libraries
A library is a collection of tested, compiled routines that programs can use, such as functions for maths, file handling, graphics or networking. Using libraries saves time, because the code does not need to be written again. It is also more reliable, because widely used libraries have been tested by many people.
Linkers and loaders
A large program is often compiled in separate pieces, and it calls routines from libraries. The linker joins the compiled pieces and the library routines into one executable, connecting each call to the address of the routine it uses. The loader is part of the operating system. When the program is run, it copies the executable into memory, adjusts addresses for where it was placed, and starts it.
Common mistake: confusing the linker with the loader. The linker joins compiled code and library routines into one executable, before the program is run. The loader copies that executable into memory and starts it, each time the program is run. One builds the program; the other launches it.
The loader cannot know in advance exactly where in memory a program will be placed, because other programs may already be using part of it. So compiled code is usually relocatable: addresses inside it are stored relative to the start of the program. When the loader places the program, it adds the real starting address to each of these, or the processor does so using a base register.
Static and dynamic linking
With static linking, the library code is copied into the executable. The program is self-contained and will run even if the library is missing, but it is larger, and every program that uses the library carries its own copy. With dynamic linking, the executable holds only a reference, and the library is loaded when the program runs. Many programs can then share one copy in memory.
Derivation: memory for static and dynamic linking
Suppose k programs, each of p kilobytes, all use the same library of L kilobytes. With static linking, every program carries its own copy of the library.
With dynamic linking, the programs share a single copy of the library, loaded once.
The saving is (k − 1) L, which grows with every extra program. The cost is that each program depends on the shared library being present and the right version.
Worked example 8: sharing a library
Five programs of 200 KB each use an 800 KB library. Compare the memory needed with static and with dynamic linking.
| Working | Reason |
|---|---|
| Static: 5 × (200 + 800) = 5 × 1000 = 5000 KB | Each program includes the whole library |
| Dynamic: 5 × 200 + 800 = 1800 KB | The library is loaded only once |
| Saving = 5000 − 1800 = 3200 KB | One library copy is saved per extra program |
| Dynamic linking saves memory but needs the library present | Static programs are larger but self-contained |
Dynamic libraries also make updates easier. Fixing a bug in a shared library fixes it for every program that uses it, without recompiling them. But if an update changes how the library behaves, programs that depended on the old behaviour can break.
Problems like this are common enough to have a name: dependency conflicts. Two programs may need different versions of the same shared library, and installing one version breaks the other program. Modern systems reduce the problem by keeping several versions side by side, or by packaging each program with the exact libraries it was tested with.
Libraries are not only compiled code. In Python, a line such as import math gives a program access to a library of tested functions, such as square roots and trigonometry. Programmers can also write their own libraries of useful routines and share them between projects, which saves rewriting and testing the same code twice.
Check yourself. Give one advantage of static linking over dynamic linking.
Show the answer
A statically linked program is self-contained, so it runs even on a computer that does not have the library, and an update to the library cannot break it.
Section 6
Programming paradigms
Procedural programming
A programming paradigm is a style or approach to programming. In the procedural paradigm, a program is a sequence of instructions, organised into procedures and functions that act on data. Variables change as the program runs. C, Pascal and much of Python are procedural. It is a natural way to describe a step-by-step process.
Object-oriented programming
In the object-oriented paradigm, a program is built from objects that combine data with the methods that act on it, organised into classes that can inherit from one another. Java, C# and Python support it. It suits large programs built by teams, as Object-oriented programming explains in detail.
Encapsulation keeps each object's data private, so that other parts of the program can only change it through the object's methods. Inheritance lets a new class reuse and extend an existing one, and polymorphism lets objects of different classes respond to the same method call in their own way. Together these make large programs easier to divide between programmers.
Functional programming
In the functional paradigm, a program is built from functions that take inputs and return outputs without changing anything else. Values are not changed in place; instead, new values are created. Functions can be passed to other functions. Haskell is purely functional, and Python and JavaScript support the style.
Three functions do much of the work. Map applies a function to every item of a list. Filter keeps only the items that pass a test. Reduce combines all the items into one value, such as a total. A whole computation can be written as a chain of these, with no loops and no changing variables.
A function that takes another function as an input, or returns one, is called a higher-order function. Map, filter and reduce are all higher-order functions: map takes the function to apply, and filter takes the test to use. Functional languages treat functions as first-class values, which means they can be stored in variables and passed around like numbers.
Functional languages often use recursion where a procedural language would use a loop. To add up a list, a function adds the first item to the sum of the rest, and the sum of an empty list is zero. Nothing is changed along the way; each call simply returns a new value.
Common mistake: thinking functional programs change variables in place. In functional programming, a function returns a new value instead of changing an old one. Map creates a new list; it does not alter the original. Because nothing changes behind the scenes, functional code is easier to test and to run in parallel.
Worked example 9: map, filter and reduce
Find the sum of the squares of the even numbers in [1, 2, 3, 4, 5, 6], using filter, map and reduce.
| Working | Reason |
|---|---|
| filter even gives [2, 4, 6] | Only items passing the test are kept |
| map square gives [4, 16, 36] | The function is applied to every item |
| reduce add gives 4 + 16 + 36 = 56 | The items are combined into one value |
| The original list is unchanged | Each step returns a new list |
Declarative and logic programming
In the declarative paradigm, the programmer describes what result is wanted, not how to get it. SQL is declarative: a query states which records to return, and the database decides how to find them. Logic programming, as in Prolog, states facts and rules, and the computer searches for answers that follow from them.
A logic program might state the facts that Ann is the parent of Ben and Ben is the parent of Cara. It then states a rule that X is a grandparent of Z if X is a parent of Y and Y is a parent of Z. Asked who is a grandparent of Cara, the computer searches the facts and answers Ann, though no step-by-step method was ever written.
Many modern languages are multi-paradigm. Python supports procedural code, classes and objects, and functional tools such as map, filter and lambda expressions. Programmers can choose the style that suits each part of a program, rather than forcing the whole program into one paradigm.
Worked example 10: the same task in two paradigms
Count the pupils in a class who scored at least 50, first procedurally and then declaratively.
| Working | Reason |
|---|---|
| Procedural: count = 0; for each pupil, if score >= 50 then count = count + 1 | The steps are spelt out one by one |
| Declarative, in SQL: SELECT COUNT(*) FROM Pupils WHERE Score >= 50 | Only the wanted result is described |
| Both give the same count | The paradigms differ in style, not in results |
| The database chooses how to search in the declarative version | The programmer does not say how |
Choosing a paradigm
Each paradigm suits different problems. Procedural code suits simple step-by-step tasks. Object-oriented code suits large systems with many interacting parts. Functional code suits data processing and parallel work, because functions without side effects can run at the same time safely. Declarative code suits querying data and solving problems described by rules.
Worked example 11: functional steps on new data
Apply the same pipeline to [3, 4, 5, 8], and give the result of each step.
| Working | Reason |
|---|---|
| filter even gives [4, 8] | 3 and 5 are odd, so they are removed |
| map square gives [16, 64] | Each remaining item is squared |
| reduce add gives 16 + 64 = 80 | The squares are added together |
| The pipeline works on any list without being changed | The steps describe the computation, not the data |
Check yourself. Is SQL procedural or declarative? Explain.
Show the answer
SQL is declarative. A query describes which data is wanted, such as all pupils with a score of at least 50. The database decides the steps needed to find it.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Assembler | Translates assembly language to machine code | STA 6 becomes 306 | One line, one instruction |
| Compiler | Translates a whole program to an executable | C, C++ | Compile once; c + n r in total |
| Interpreter | Translates and runs one statement at a time | Python in a shell | n i in total; easy debugging |
| Bytecode | Processor-independent intermediate code | Java, Python | Run by a virtual machine |
| Lexical analysis | Groups characters into tokens | total, =, total | Removes spaces and comments |
| Symbol table | Records every identifier and its details | score: variable | Used by every later stage |
| Syntax analysis | Checks grammar and builds a syntax tree | Missing bracket error | Grammar written in BNF |
| Optimisation | Makes code faster or smaller, same results | Constant folding | Never changes the output |
| Linker and loader | Joins code and libraries; loads and starts it | Static or dynamic linking | k(p + L) against k p + L |
| Paradigms | Procedural, object-oriented, functional, declarative | map, filter, reduce; SQL | Choose the style that fits the problem |
Programming task
Programming task: a simple lexer
Aim
Write a Python program that performs lexical analysis on a line of code. It must split the line into tokens and label each one as a keyword, identifier, number, string, operator or punctuation. It must also remove comments and white space, and build a symbol table of the identifiers.
Design
A list of keywords and a set of operators define the language. The lexer moves through the line one character at a time. Letters start a name, which becomes a keyword or an identifier; digits start a number; a quotation mark starts a string. Two-character operators, such as >=, are checked before one-character ones, so that the longest valid token is taken.
The symbol table is a list that gains each identifier the first time it appears. Anything after // is a comment, so the line is cut there before lexing begins.
Code
KEYWORDS = {"if", "then", "else", "while", "for", "print", "and", "or", "not"}
OPERATORS = ["==", "!=", "<=", ">=", "=", "<", ">", "+", "-", "*", "/"]
def tokenise(line):
line = line.split("//")[0]
tokens, symbols, i = [], [], 0
while i < len(line):
ch = line[i]
if ch.isspace():
i += 1
elif ch.isalpha() or ch == "_":
j = i
while j < len(line) and (line[j].isalnum() or line[j] == "_"):
j += 1
word = line[i:j]
kind = "keyword" if word in KEYWORDS else "identifier"
if kind == "identifier" and word not in symbols:
symbols.append(word)
tokens.append((kind, word)); i = j
elif ch.isdigit():
j = i
while j < len(line) and line[j].isdigit():
j += 1
tokens.append(("number", line[i:j])); i = j
elif ch == '"':
j = line.index('"', i + 1) + 1
tokens.append(("string", line[i:j])); i = j
else:
op = next((o for o in OPERATORS if line.startswith(o, i)), None)
if op:
tokens.append(("operator", op)); i += len(op)
elif ch in "(),":
tokens.append(("punctuation", ch)); i += 1
else:
raise ValueError(f"unexpected character {ch!r}")
return tokens, symbols
print(tokenise("total = total + price * 2 // add"))
The list of operators puts the two-character operators first, so that >= is read as one token rather than > followed by =. Raising an error for an unexpected character is the lexer's way of reporting a lexical error.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | total = total + price * 2 // add | 7 tokens; symbols total, price | Matches worked example 4 |
| 2 | if score >= 50 then print("Pass") | 9 tokens; symbols score | Matches worked example 5 |
| 3 | area=width*height | 5 tokens; symbols area, width, height | Works with no spaces at all |
| 4 | while count < 10 | 4 tokens | A keyword, a name, an operator and a number |
| 5 | // only a comment | 0 tokens | A comment produces nothing |
| 6 | x = 5 @ 2 | ValueError | An illegal character is reported |
| 7 | a>=b | 3 tokens, with >= as one operator | The longest operator is taken |
Evaluation
The lexer handles every test correctly, including lines with no spaces and the two-character operator in test 7. Test 6 shows that it reports characters that cannot belong to any token, which is exactly the job of the lexical analysis stage.
The lexer does not handle decimal numbers or strings that contain quotation marks. An improvement would extend the number rule to allow a decimal point, and pass the tokens to a simple parser that checks an assignment statement against a grammar.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. Describe the difference between a compiler and an interpreter.
Worked solution to Q1
A compiler translates the whole program into machine code before it runs, producing an executable file. An interpreter translates and runs the program one statement at a time, producing no executable, and stops at the first error.
Q2. Name the four main stages of compilation in order.
Worked solution to Q2
The stages are lexical analysis, then syntax analysis, then code generation, and finally optimisation. Each stage takes the output of the one before it, from tokens to a syntax tree to machine code.
Q3. Explain what a library is and give one benefit of using one.
Worked solution to Q3
A library is a collection of tested, compiled routines that programs can call, such as maths or graphics functions. Using one saves development time, because the code does not need to be written and tested again.
Rung 2: Application
Q4. A program takes 60 s to compile and 2 s per run, or 5 s per run interpreted. Find the totals after 15 runs.
Worked solution to Q4
The compiled version costs one compilation plus fifteen runs: 60 + 15 × 2 = 90 seconds. The interpreted version costs fifteen slow runs: 15 × 5 = 75 seconds. So after 15 runs, interpreting is still quicker.
Q5. Split while count < 10 into tokens and give each token's type.
Worked solution to Q5
There are four tokens. The first is while, a keyword, and the second is count, an identifier. Then comes <, an operator, and finally 10, a number. Only count goes into the symbol table.
Q6. Apply constant folding to t = 2 * 3.5 + r.
Worked solution to Q6
The constant part, 2 * 3.5, is worked out during compilation and gives 7. The variable r is only known at run time, so the statement becomes t = 7 + r, and the addition is left until the program runs.
Q7. Apply filter even, then map square, then reduce add to the list [3, 4, 5, 8].
Worked solution to Q7
Filtering for even numbers keeps [4, 8]. Squaring each gives [16, 64]. Adding them together gives 16 + 64 = 80, and the original list is not changed by any of the steps.
Rung 3: Analysis
Q8. Use the break-even formula to find from which run compiling is quicker for c = 60, r = 2 and i = 5.
Worked solution to Q8
Compiling wins once n is greater than c ÷ (i − r), which is 60 ÷ 3 = 20. At exactly 20 runs the totals are equal, at 100 seconds each, so compiling is quicker from the 21st run.
Q9. Explain why developers often use an interpreter while writing a program but compile it before releasing it.
Worked solution to Q9
An interpreter stops at the first error and shows exactly where it is, which makes testing quick during development. Compiling the finished program produces a fast executable that users can run without the source code or an interpreter.
Q10. Explain why a lexer must read >= as one token rather than two.
Worked solution to Q10
The symbols > and = together mean "greater than or equal to", a single operator. Reading them as two tokens would give > followed by =, which the parser would reject as invalid syntax. The lexer always takes the longest valid token.
Q11. Eight programs of 150 KB each use a 600 KB library. Find the memory saved by dynamic linking.
Worked solution to Q11
Static linking needs 8 × (150 + 600) = 6,000 KB, because each program has its own copy of the library. Dynamic linking needs 8 × 150 + 600 = 1,800 KB. The saving is 4,200 KB, which equals (8 − 1) × 600.
Rung 4: Stretch
Q12. Explain why functional programs are well suited to running on many cores at once.
Worked solution to Q12
Functional code does not change shared values; each function only uses its inputs and returns new values. So two functions can run at the same time on different cores without interfering, and map can process every item of a list in parallel.
Q13. Show that, with dynamic linking, the memory saved compared with static linking is (k − 1)L.
Worked solution to Q13
Static linking needs k(p + L) = kp + kL, and dynamic linking needs kp + L. Subtracting gives kp + kL − kp − L = kL − L, which is (k − 1)L. Every program after the first saves one copy of the library.
Q14. Fold y = x * (4 − 1), and explain why x * 4 − x * 1 might not be folded the same way.
Worked solution to Q14
The bracket (4 − 1) contains only constants, so it folds to 3, giving y = x * 3. In x * 4 − x * 1, each product involves the variable x, so no part is purely constant. A simple folder cannot fold it, although a cleverer optimiser could rewrite it.
Exam practice
Exam technique and worked answer workshop
When comparing translators, give advantages and disadvantages of each, linked to a situation. "An interpreter is good for debugging, because it stops at the first error and shows where it is" earns marks; "interpreters are easier" does not.
For the stages of compilation, name each stage and say what it takes in and what it produces. Lexical analysis takes characters and produces tokens; syntax analysis takes tokens and produces a syntax tree; code generation produces machine code; optimisation improves it.
For paradigms, describe the approach and give a language or an example. A short code fragment, such as a map or an SQL query, is often the clearest way to show the difference.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
(a) State what an assembler is used for. [1]
(b) Give two differences between a compiler and an interpreter. [2]
(c) State one advantage of a compiler for the user of a finished program. [1]
Mark scheme for exam question 1
- B1 it translates assembly language into machine code
- B1 a compiler translates the whole program before it runs; an interpreter translates one statement at a time as it runs
- B1 a compiler produces an executable file; an interpreter does not
- B1 the executable runs quickly, without the source code or a translator
Exam question 2 (5 marks · Paper 01 · about 7 minutes)
A program takes 30 s to compile and 1 s per run, or 4 s per run interpreted.
(a) Calculate the total time for each approach after 10 runs. [2]
(b) Calculate the number of runs after which compiling is quicker. [2]
(c) State one reason a developer might still interpret the program. [1]
Mark scheme for exam question 2
- M1 30 + 10 × 1 and 10 × 4
- A1 both 40 seconds
- M1 30 ÷ (4 − 1)
- A1 from the 11th run
- B1 errors are reported one at a time where they occur, which makes debugging easier
Exam question 3 (5 marks · Paper 01 · about 7 minutes)
The line if score >= 50 then print("Pass") is passed to the lexical analyser.
(a) State how many tokens are produced. [1]
(b) Give the type of the tokens if, score, >= and "Pass". [3]
(c) State what is placed in the symbol table. [1]
Mark scheme for exam question 3
- B1 9 tokens
- B1 if is a keyword
- B1 score is an identifier
- B1 >= is an operator and "Pass" is a string
- B1 the identifier score
Exam question 4 (5 marks · Paper 01 · about 7 minutes)
Describe the stages of compilation.
Mark scheme for exam question 4
- B1 lexical analysis groups characters into tokens and removes white space and comments
- B1 identifiers are recorded in the symbol table
- B1 syntax analysis checks the tokens against the grammar and builds a syntax tree
- B1 code generation turns the syntax tree into machine code
- B1 optimisation makes the code faster or smaller without changing its results
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A company is developing a new app. Discuss the use of a compiler and an interpreter during development and when the app is released to customers.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced discussion of both translators at both stages, covering error reporting, speed, protection of the source code and portability. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct comparison of the two translators with some link to development or release. The conclusion is limited.
Level 1 (1–2 marks): some relevant points, such as that compilers are faster, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- during development, code is changed and tested many times
- an interpreter runs code at once and stops at the first error, showing where it is
- so an interpreter makes testing and debugging quick
- for release, a compiler produces an executable that runs at full speed
- customers do not need the source code or a translator to run it
- compiling protects the source code, so it is harder to copy
- an executable is specific to one processor and operating system, so it must be compiled for each
- bytecode with a virtual machine gives portability with some of the speed of compiling
- conclusion: interpret or use quick builds while developing; compile for release
Annotated model answer: exam question 5
"During development, the code is changed and tested constantly. An interpreter runs code straight away and stops at the first error, showing exactly where it is, so mistakes are found and fixed quickly." (Interpreter for development, justified.)
"For release, a compiler produces an executable that runs at full speed. Customers need neither the source code nor a translator, and the company's source code is protected from copying." (Compiler for release, with two benefits.)
"An executable only runs on the processor and operating system it was compiled for, so the app must be compiled separately for each platform. Compiling to bytecode for a virtual machine is an alternative that runs anywhere." (A drawback and an alternative.)
"So the company should use an interpreter, or fast test builds, while developing, and compile the finished app for each platform it supports." (A justified conclusion.)
This answer reaches Level 3 and scores 6 marks. It weighs both translators at both stages and reaches a clear recommendation.
Exam question 6 (5 marks · Paper 01 · about 7 minutes)
(a) Explain what is meant by code optimisation. [2]
(b) Apply constant folding to x = 60 * 60 * 24 and to w = a + 2 * 3. [3]
Mark scheme for exam question 6
- B1 the generated code is changed to run faster or use less memory
- B1 without changing the results the program gives
- B1 x = 86400
- M1 2 * 3 folded to 6
- A1 w = a + 6, with the addition left for run time because a is a variable
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
(a) Explain the role of a linker and of a loader. [2]
(b) Give one advantage and one disadvantage of dynamic linking. [2]
Mark scheme for exam question 7
- B1 a linker joins compiled modules and library routines into one executable
- B1 a loader copies the executable into memory and starts it running
- B1 advantage: programs share one copy of a library, saving memory and disk space
- B1 disadvantage: the program fails if the library is missing or an incompatible version
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
Write a function sumSquaredEvens(list) that returns the sum of the squares of the even numbers in a list. State what it returns for [1, 2, 3, 4, 5, 6].
Mark scheme for exam question 8
- B1 a function header taking the list
- B1 a total starting at 0, or a reduce with a starting value
- B1 each item is checked for being even, using MOD 2
- B1 even items are squared
- M1 the squares are added to the total
- A1 the total is returned, and the result for [1, 2, 3, 4, 5, 6] is 56
Annotated model answer: exam question 8
function sumSquaredEvens(list)
total = 0
for i = 0 to list.length - 1
if list[i] MOD 2 == 0 then
total = total + list[i] * list[i]
endif
next i
return total
endfunction
The header and the total starting at 0 earn the first two marks. The test with MOD 2 earns the third, and squaring the item earns the fourth. Adding each square to the total earns the method mark, and returning it, 56 for the example list, earns the last. A functional answer using filter, map and reduce earns the same marks.
Connections
Synoptic link
Assemblers translate the Little Man Computer programs of Assembly language and addressing modes. The object-oriented paradigm is taught fully in Object-oriented programming, and the declarative style of SQL in SQL and transaction processing.
Lexical analysis uses the string handling of Programming constructs, and syntax analysis checks against grammars written in Backus-Naur form, which Computational thinking introduces alongside abstraction. The trade-off between compiling once and interpreting each time is the same kind of reasoning as the performance calculations in Processor architecture and performance.
Synoptic question 1. A loop runs 1,000,000 times and contains x = 60 * 60 * 24. Each multiplication takes 1 ns. How much time does constant folding save?
Answer to synoptic question 1
Without folding, each pass does 2 multiplications, costing 2 ns. Over 1,000,000 passes that is 2,000,000 ns, or 2 ms. Folding replaces the expression with 86,400, so all 2 ms are saved.
Recap
Recap and next step
- Low-level languages work directly with one processor; high-level languages are portable and easier to read. An assembler, a compiler and an interpreter each translate code to machine code.
- A compiler produces an executable once; an interpreter translates on every run. Compiling saves time once n > c ÷ (i − r).
- Lexical analysis groups characters into tokens, removes spaces and comments, and records identifiers in the symbol table.
- Syntax analysis checks grammar and builds a syntax tree; code generation produces machine code; optimisation, such as constant folding, improves it without changing results.
- Libraries provide tested routines; a linker joins them into an executable and a loader runs it. Dynamic linking saves (k − 1)L of memory.
- Procedural, object-oriented, functional and declarative paradigms describe solutions differently; map, filter and reduce build functional pipelines.
Next chapter: Assembly language and addressing modes looks closely at the lowest-level language, using the Little Man Computer to write and trace real programs.
For your exam board
OCR A Level Computer Science (H446): this chapter covers translators, the stages of compilation, linkers, loaders and libraries in section 1.2.2, Applications generation, and programming paradigms in section 1.2.4, Types of programming language, in Component 01.
AQA A Level Computer Science (7517): the classification of programming languages, the types of program translator, and the role of the assembler, compiler and interpreter appear in the fundamentals of computer systems section, and programming paradigms, including functional programming, in its own section, assessed on Paper 2 and, for functional programming, Paper 1.