Cambridge: Computer Science Tripos Part Ib
Cambridge: Computer Science Tripos Part Ib
Cambridge: Computer Science Tripos Part Ib
CAMBRIDGE
Computer Laboratory
Compiler Construction
http://www.cl.cam.ac.uk/Teaching/0910/CompConstr/
David J Greaves
djg@cl.cam.ac.uk
2
Acknowledgments
Various parts of these notes are due to or based on material developed by Martin Richards of the
Computer Laboratory. Gavin Bierman provided the call-by-value lambda-form for Y . Tim Grif-
fin’s course in 2006/07 has been a source of ideas, and has a good set of alternative notes covering
much of the same material from slightly difference perspective—find them on the “information for
current students” part of the CL web site.
Additional Notes
The course web site contains auxiliary course notes. The material in these auxiliary notes is not
examinable, but may provide useful background (or alternative techniques from those given here).
The notes are:
1. A.C. Norman “Compiler Construction—Supplementary Notes”. These notes explain how to
use JLex and cup which are Java-oriented tools which replaces lex and yacc discussed in
this course.
2. Neil Johnson “Compiler Construction for the 21st Century”. These notes (funded by Mi-
crosoft Research’s “Curriculum Development” project) introduce the tool antlr—an alter-
native to lex and yacc which combines their functionality. One particularly useful aspect
is that antlr can output code for C, C++, Java and C♯. The notes also contain various
longer exercises.
If there is enough demand (ask Jennifer or your student representative) then I will print copies.
3
Teaching and Learning Guide
The lectures largely follow the syllabus for the course which is as follows.
• Lexical analysis and syntax analysis. Recall regular expressions and finite state machine
acceptors. Lexical analysis: hand-written and machine-generated. Recall context-free gram-
mars. Ambiguity, left- and right-associativity and operator precedence. Parsing algorithms:
recursive descent and machine-generated. Abstract syntax tree; expressions, declarations
and commands. [2 lectures]
• Simple type-checking. Type of an expression determined by type of subexpressions;
inserting coercions. [1 lecture]
• Code generation. Typical machine codes. Code generation from intermediate code. Sim-
ple peephole optimisation. [1 lecture]
• Object Modules and Linkers. Resolving external references. Static and dynamic linking.
[1 lecture]
A good source of exercises is the past 20 or 30 years’ (sic) Tripos questions in that most
of the basic concepts of block-structured languages and their compilation to stack-oriented code
were developed in the 1960s. The course ‘Optimising Compilation’ in CST (part II) considers
more sophisticated techniques for the later stages of compilation and the course ‘Comparative
Programming Languages’ considers programming language concepts in rather more details.
Note: the course and these notes are in the process of being re-structured. I would be grateful
for comments identifying errors or readability problems.
4
Contents
1 Introduction and Overview 7
1.1 The structure of a typical multi-pass compiler . . . . . . . . . . . . . . . . . . . . . 7
1.2 The lexical analyser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3 The syntax analyser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 The translation phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 The code generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.6 Compiler Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7 The linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8 Compilers and Interpreters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.9 Machine code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.10 Typical JVM instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.11 Variables, Stacks and Stack Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.12 Overall address space use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.13 Stack frames in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.14 Reading compiler output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3 Lexical analysis 23
3.1 Regular expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Example: floating point tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4 Syntax analysis 26
4.1 Grammar engineering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.2 Forms of parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3 Recursive descent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.4 Data structures for parse trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.5 Automated parser generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.6 A note on XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5 Type checking 32
5
9 Foundations 45
9.1 Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
9.2 Lambda calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
9.3 Object-oriented languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
9.4 Mechanical evaluation of lambda expressions . . . . . . . . . . . . . . . . . . . . . 48
9.5 Static and dynamic scoping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.6 A more efficient implementation of the environment . . . . . . . . . . . . . . . . . 51
9.7 Closure Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
9.8 Landin’s Principle of Correspondence Non-examinable 09/10 . . . . . . . . . . . . 53
13 Phrase-structured grammars 71
13.1 Type 2 grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
13.2 Type 0 grammars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
13.3 Type 1 grammars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
13.4 Type 3 grammars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
13.5 Grammar inclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6
1 Introduction and Overview
Never put off till run-time what you can do at compile-time. [David Gries]
A compiler is a program which translates the source form of a program into a semantically equiv-
alent target form. Traditionally this was machine code or relocatable binary form, but nowadays
the target form may be a virtual machine (e.g. JVM) or indeed another language such as C.
For many CST students, the idea of writing a compiler is liable to be rather daunting. Indeed to
be able to do so requires total understanding of all the dark corners of the programming language
(for example references to outer method arguments from methods defined in a Java inner class, or
exactly which ML programs type-check). Moreover, a compiler writer needs to know how best to
exploit instructions, registers and idioms in the target machine—after all we often judge a compiler
by how quickly compiled programs run. Compilers can therefore be very large. In 20041 the Gnu
Compiler Collection (GCC) was noted to “[consist] of about 2.1 million lines of code and has been
in development for over 15 years”.
On the other hand, the core principles and concepts of compilation are fairly simple (when seen
in the correct light!) so the first part of this course explains how to construct a simple compiler for
a simple language—here essentially just the features common to all three of C, Java and ML. This
need not require significantly more than 1000–2000 lines of code. The standard conceptual problem
is “where do I even start?”. For example, deciding which version of an overloaded operator to use
is hard enough, but doing it alongside determining when an inner expression finishes and choosing
the appropriate x86, ARM or MIPS instruction to implement it seems at first require a brain
the size of a planet. The (time-established) solution is to break down a compiler into phases or
passes. Each pass does a relatively simple transformation on its input to yield its output, and the
composition of the passes is the desired compiler (even GCC follows this model). This solution
is called a multi-pass compiler and is ubiquitous nowadays. An analogy: juggling 5 balls for 1
minute is seriously hard, but juggling one ball for one minute, followed by another for one minute,
and so on until all 5 balls have been juggled is much easier.
As an aside, note that many modern languages require a multi-pass compiler: in both the two
programs below, it is rather hard to emit code for function f() until the definition of g() is found.
In Java
class A {
public int f() { return g(1); } // i.e. g(1.0)
// ... many lines before we find ...
public int g(double x) { ... }
}
or in ML:
val g = 3;
fun f(x) = ... g ...
and g(x) = ...;
character - token - parse - intermediate - target
stream stream tree code
syn
cg
code
lex trans
1 http://www.redhat.com/magazine/002dec04/features/gcc/.
7
1.2 The lexical analyser
The lexical analyser reads the characters of the source program and recognises the basic syntactic
components that they represent. It will recognise identifiers, reserved words, numbers, string
constants and all other basic symbols (or tokens) and throw away all other ignorable text such
as spaces, newlines and comments. For example, the result of lexical analysis of the following
program phrase:
{ let x = 1;
x := x + y;
}
might be:
LBRACE LET ID/x EQ NUM/1 SEMIC ID/x ASS ID/x PLUS ID/y SEMIC RBRACE
Lexical tokens are often represented in a compiler by small integers; for composite tokens such as
identifiers, numbers, etc. additional information is passed by means of pointers into appropriate
tables; for example calling a routine lex() might return the next token while setting a global vari-
able lex aux string to the string form of an identifier when ID is returned, similarly lex aux int
might be set to the binary representation of an integer when NUM is returned.
This is perhaps a rather old-fashioned and non-modular approach to returning multiple values
from a function (return one and leave the additional values lying around), but it is often used in
C and forms the model used by lex and yacc—see later. Of course, if you prefer a functional
style, then an ML datatype for tokens is just what is required, or in Java a class Token which is
extended to give classes Token_Id or Token_Int as required.
definition exp
declaration command
block
and it might be represented within the compiler by the following tree structure:
LET EQDEF
ID
NUMB x
1
ASS
PLUS
ID
y
where the tree operators (e.g. LET and EQDEF) are represented as small integers.
In order that the tree produced is not unnecessarily large it is usually constructed in a condensed
form as above with only essential syntactic features included. It is, for instance, unnecessary to
8
represent the expression x occurring as part of x+y as an <exp> which is a <factor> which is a
<primary> which is an <identifier>. This would take more tree space and would also make
later processing less convenient. Similarly, nodes representing identifiers are often best stored
uniquely—this saves store and reduces the problem of comparing whether identifiers are equal to
simple pointer equality. The phrase ‘abstract syntax tree’ refers to the fact the only semantically
important items are incorporated into the tree; thus a+b and ((a)+(((b))) might have the same
representation, as might while (e) C and for(;e;) C.
iload 4 ineg
A
iload 4 iconst 3 if icmpgt A istore 7 -
A
Aiload 4
9
we can easily produce (simple if inefficient) MIPS code of the form using the traditional downwards-
growing MIPS stack:3
Or on ARM
(x86 code would be very similar, if spelt differently—see Section 7.) This code has the property
that it can simply be generated from the above JVM code on an instruction-by-instruction basis
(which explains why I have not hand-optimised the PUSHes and POPs away).
When compilers produce textual output in a file (for example gcc) it is necessary to have a
separate program (usually called an assembler) to convert this into an object file. An assembler
is effectively a simple compiler which reads an instruction at a time from the input stream and
writes the binary representation of these into the object file output. One might well argue that
this is a separate pass, which separates the formatting of the binary file from the issue of deciding
which code to generate.
corresponds to ‘-4($fp)’.
10
is required. Examples might be separating the type-checking phase from the translation phase
(for example as code which replaces source-level types in the syntax tree with more machine-
oriented type information), or by adding additional phases to optimise the intermediate code
structures (e.g. common sub-expression elimination which reworks code to avoid re-calculating
common subexpressions).
The advantages of the multi-pass approach can be summarised as:
1. It breaks a large and complicated task into smaller, more manageable pieces. [Anyone can
juggle with one ball at a time, but juggling four balls at once is much harder.]
2. Modifications to the compiler (e.g. the addition of a synonym for a reserved word, or a minor
improvement in compiler code) often require changes to one pass only and are thus simple
to make.
6. The job of writing the compiler can be shared between a number of programmers each
working on separate passes. The interface between the passes is easy to specify precisely.
11
analogous to the input data-structure of one of the above compiler phases. For example, some
Basic interpreters will decode lexical items whenever a statement is executed (thus syntax errors
will only be seen at run-time); others will represent each Basic statement as a parse tree and refuse
to accept syntactically invalid programs (so that run-time never starts). What perhaps enables
Java to claim to be a compiled language is that compilation proceeds far enough that all erroneous
programs are rejected at compile-time. Remaining run-time problems (e.g. de-referencing a NULL
pointer) are treated as exceptions which can be handled within the language.
I will present a rather revisionist view on compilers and interpreters at the end of the course
(§11.3).
• load and store register-sized values to and from memory; these need to support two address-
ing modes—(i) absolute addressing (accessing a fixed location in memory) and (ii) indexed
addressing (add a fixed offset to a register and use that as the address to access). Note
that many instruction sets effectively achieve (i) by first loading a constant representing an
address into a register and then use (ii) to complete the operation. [MIPS lw, sw].
• perform conditional branches, jump (possibly saving a return address) to fixed locations (or
to a location specified in a register). [MIPS beq/bne, j/jal,jr/jalr].
Students are reminded of last term’s ‘Computer Design’ course which introduced both MIPS
and JVM code.
Reminder: the MIPS has 32 registers; registers $a0–$a3 are used for arguments and local
temporaries in a procedure; $zero always holds zero; $fp holds a pointer (“stack frame”) in which
the local variables can be found. Global variables are allocated to fixed memory locations. The
exact locations (absolute addresses for global variables, offsets from $fp for locals) have been
selected by the compiler (see later in these notes as to how this can be done).
Instructions are fetched from pc; this is not a user-visible register (unlike ARM), but is stored
in $ra by subroutine jump instructions jal/jalr, a return from a subroutine can be effected by
jr $ra.
So, for simple primitives
movhi $a0,0x1234
ori $a0,$a0,0x5678
lw $a0,<nn>($fp)
sw $a0,<nn>($fp)
12
movhi $a3,0x00be
lw $a0,0x3f04($a3)
sw $a0,0x3f04($a3)
add $a2,$a0,$a1
• function calling is again more complicated (particularly on the MIPS or ARM where the
first four arguments to a function are passed in registers $a0–$a3 and subsequent ones left
at the top of the callers’ stack). We will ignore this here and assume a JVM-like convention:
a caller pushes the arguments to a function on the stack and leaves register $sp pointing
to the most recently pushed. The callee then makes a new stack frame by pushing the old
value of $fp (and the return address—pc following caller) on the stack and then setting $fp
to $sp to form the new stack frame.
• function return is largely the opposite of function call; on the MIPS place the result in $v0
then de-allocate the locals by copying $fp into $sp, finally pop the caller’s FP into $fp and
pop the return address and branch (jr on MIPS) to it. On the MIPS there is a caller-
removes-arguments convention (unlike the JVM) where the caller is responsible for popping
arguments immediately after return.
iconst hni push integer n onto the stack. Because the JVM was designed to be interpreted,
there are special opcodes iconst 0, iconst 1 and variants taking 8-bit, 16-bit and 32-bit
operands (widened to 32 bits). These make only efficiency differences and we will treat them
as a single instruction.
iload hki push the kth local variable onto the stack. This is also used to push arguments—for a
n argument function when 0 ≤ k < n − 1 then an argument is pushed, for n > k a local.
istore hki pop the stack into the kth local variable.
getstatic hclass:fieldi push a static field (logically a global variable) onto the stack. One
might wonder why it is not igetstatic; the answer is that the type ‘int’ is encoded in
the hclass:fieldi descriptor.
putstatic hclass:fieldi pop the stack into a static field (logically a global variable).
if icmpeq ℓ, also if icmpgt, etc. pop two stack items, compare them and perform a conditional
branch on the result.
label ℓ not an instruction: just declares a label. In assembly code form (human readable) labels
ℓ are strings, but in the binary form conditional branches have numeric offsets and label
pseudo-instructions are not represented.
13
One of the reasons for selecting JVM code as intermediate code in our simple compiler is the
simple way the above subset may be translated to MIPS code. The Microsoft language C# has a
very close resemblance to Java and their .NET (or CLR) virtual machine code a similar relationship
to JVM code. Their divergence owes more to commercial reasons than to technological ones (one
person’s “minimal change to keep this side of IPR law” is another person’s “doing it properly after
failing to agree commercial terms”!)
out), but sometimes as here (and Operating Systems) it abbreviates ‘stack segment’ and means a block of memory
in which stack frames are allocated and sometimes (JVM) it abbreviates ‘operand stack’ which is used to evaluate
expressions within a stack frame.
5 Unlike the heap, introduced later, where there is no expectation at compile time of when the store will become
free.
6 This is a downward-growing stack in which the stack grows from higher addresses to lower addresses.
7 Arguably, ‘stack fringe pointer’ might be a better name but sadly both ‘fringe’ and ‘frame’ begin with ‘f’ !
14
Hence, on a procedure call, allocating a new stack frame is simply a matter of copying $sp
into $fp. But, we need to be able to return from the procedure too. Hence, before we corrupt
$fp, we first need to save the old value of $fp and also the return address—$pc value immediately
after the call site (on the MIPS this is stored in $31, also known as $ra, by the jal instruction).
Together, this pair (old FP, RA) constitute the linkage information which now forms part of a
stack frame. So, on entry to a procedure, we expect to see instructions such as
There are many ways to achieve a similar effect: I have chosen one which draws nicely pictorially
($fp points to linkage information).8 Local variables are allocated by decrementing $sp, and
deallocated by incrementing $sp. A frame now looks like:
6 6HH HH
6 6
stack H H
$sp $fp
Finally, we need to deal with parameter passing. Because passing parameters in registers is
much faster than passing them in memory, the MIPS procedure calling standard mandates that
first first four arguments to a procedure are passing in registers $a0–$a3. For simplicity in this
course (and also compatibility with JVM and traditional x86 calling standards) we ignore this and
pass all parameters on the stack. The mechanism works like this: to call a procedure:
• the caller and callee agree that the parameters are left in memory cells at $sp, $sp+4, etc.
This is achieved by:
• the caller evaluates each argument in turn,9 pushing it onto $sp—i.e. decrementing $sp and
storing the argument value at the newly allocated cell.
• the callee stores the linkage information contiguous with the received parameters, and so they
can be addressed as $fp+8, $fp+12, etc. (assuming 2-word linkage information pointed at
by $fp).
8 In practice, debuggers will expect to see stack frames laid out in a particular manner (and the defined layout for
the MIPS has a few quaintnesses), but to achieve maximum compatibility it is necessary to follow the tool-chain’s
ABI (application binary interface), part of the API (application programming interface).
9 In Java this is done left-to-right; in C (and indeed for the MIPS calling standard) the convention (which will
ignore in this course, but which is useful if you have real MIPS code to read) is that the arguments are pushed
right-to-left which means, with a downward-growing stack, that they appear first-argument in lowest memory.
15
In a sense the caller allocates arguments to a call in memory in its stack frame but the callee
regards this memory as being part of its stack frame. So here are the two views (both valid!):
With this setup, local variables and (received) parameters are both addressed as local variables—
parameters as positive offsets from $fp, and locally declared variables as negative offsets. Argu-
ment lists being formed are evaluated and pushed on $sp.
There remains one significant issue: a dichotomy as what to do on return from a procedure—is
the callee or caller responsible for removing the arguments from the stack? For MIPS, the caller
is responsible, on the JVM the callee.
... code ... static data ... stack ... heap ...
0x00000000 0xffffffff
The items listed above are often called segments: thus the code segment or the stack segment. We
will only discuss the heap segment in Part C of these notes.
class fntest {
public static void main(String args[]) {
System.out.println("Hello World!" + f(f(1,2),f(3,4)));
}
static int f(int a, int b) { int y = a+b; return y*a; }
}
f:
iload 0 ; load a
iload 1 ; load b
iadd
istore 2 ; store result to y
iload 2 ; re-load y
iload 0 ; re-load a
imul
ireturn ; return from fn with top-of-stack value as result
16
and the series of calls in the println in main as:
iconst 1
iconst 2
invokestatic f
iconst 3
iconst 4
invokestatic f
invokestatic f
Note how two-argument function calls just behave like binary operators in that they remove two
items from the stack and replace them with one; the instructions invokestatic and ireturn both
play their part in the conspiracy to make this happen. You really must work through the above
code step-by-step to understand the function call/return protocol.
I have omitted some subtleties here—such fine detail represents ‘accidental’ implementation
artifacts and is neither examinable nor helpful to understanding (unless you actually need to build
a JVM implementation following Sun’s standard). These include:
• There is no stack management code shown at entry to f; this is stored as meta-data in the
JVM file, in particularly there are two magic numbers associated with f: these are (np , nv ).
The meta-data np is the number of parameters to f (this is used by ireturn to remove
parameters and at entry to setup fp. The meta-data nv is the number of local variables of f
and is used on entry to decrement SP to make space for local variables (on JVM these are all
allocated on entry, even if this “wastes space” for local variable only in-scope for part of the
function body). Note also that knowing nv at entry makes for simple convenient checking
the stack has not overflowed the space allocated.
• Local variable access and parameter access both use iload with operand (0..np + nv − 1);
when its operand is (0..np − 1) it references parameters and when it is (np ..np + nv − 1)
it references locals—hence in the interpreter fp points to an offset from where it would be
placed on the MIPS.
• As a consequence, the JVM linkage information cannot obviously be placed between param-
eters and locals (as done on most systems including MIPS). In an interpreter this can easily
be resolved by placing linkage information on a separate (parallel) stack held in the inter-
preter; on a JIT compiler then the k in “iload hki” can be adjusted (according to whether
or not k < np ) to leave a gap for linkage information.
gcc -S foo.c
will write a file foo.s containing assembly instructions. Otherwise, use a disassembler to convert
the object file back into assembler level form, e.g. in Java
javac foo.java
javap -c foo
Using .net languages on linux, the mondis tool can be applied to an executable bytecode file
to generate a disassembly of the contents.
17
Part A: A simple language and
interpreters for it
2 A simple language and its execution structures
This course attempts to be language neutral (both source language and implementation language).
As said before, a compiler can be written in a language of your choice, e.g. Java, C or ML. However,
as we will see in Part C of the course, certain language features pose significant implementation
problems, or at least require significant implementation effort in representing these features in
terms of the simpler features we use here (examples are function definitions nested within other
functions, non-static methods—dealing with the this pointer, exceptions and the like).
Accordingly for the first part of the course we consider a source language with
• only 32-bit integer variables (declared with int), constants and operators;
Although we do not introduce the formal notation used below until later in the course, our
source language has: expressions, declarations and commands of the following form.
We will assume many things normally specified in detail in a language manual, e.g. that <var> and
<fnname> are distinct, that the <cmd> of a function body must be a ({}-enclosed) ‘block’ and that
<decl>s appearing within a <cmd> may not define functions. (When you come to re-read these
notes, you’ll realise that this specifies the abstract syntax of our language, and the concrete syntax
can be used to enforce many of these requirements as well as specifying operator precedence.)
The language given above is already a subset of C. Moreover, it is also a subset of ML modulo
spelling.10 It can also be considered as a subset of Java (wrap the program within a single class
with all functions declared static). Note that static class members are the nearest thing Java has
to a ‘global’ or ‘top-level’ variable—one accessible from all functions and typically created before
any function is called.
Sometimes, even such a modest language is rather big for convenient discussion in lectures. It
can then help to look at a functional ‘subset’: we skip the need to consider <cmd> and <decl>
by requiring the <cmd> forming a function body to be of the form { return e; }. Because this
makes the language rather too small (we have lost the ability to define local variables) it is then
useful to include an ‘let’ form declaring a variable local to an <expr> as in ML:
10 Care needs to be taken with variables; a <var> declaration needs to use ML’s ‘ref’, the <var> at the left of an
assignment is unchanged and all <var>s in <expr>s need an explicit ‘!’ to dereference.
18
<expr> ::= <number>
| ...
| let <var> = <expr> in <expr>
For the moment, we’re going to assume that we already have a compiler and to consider how
the various intermediate outputs from stages in the compiler may be evaluated. This is called
interpretation. Direct interpretation by hardware is usually called execution. But of course, it is
possible that our compiler has generated code for an obsolete machine, and we wish to interpret
that on our shiny new machine. So, let us consider interpreting a program in:
character-stream form: while early Basic interpreters would have happily re-lexed and re-
parsed a statement in Basic whenever it was encountered, the runtime overhead of doing so
(even for our minimal language) makes this no longer sensible;
token-stream form: again this is very slow, memory is now so abundant and parsing so fast that
it can be done when a program is read; historically BBC Basic stored programs in tokenised
form, rather than storing the syntax tree (this was for space reasons)
syntax-tree form: this is a natural and simple form to interpret (the next section gives an
example for our language). It is noteworthy (linking ideas between courses) to note that op-
erational semantics are merely a form of interpreter. Syntax tree interpreters are commonly
used for PHP or Python.
intermediate-code form the suitability of this for interpretation depends on the choice of in-
termediate language; in this course we have chosen JVM as the intermediate code—and
historically JVM code was downloaded and interpreted. See subsequent sections for how to
write a JVM interpreter.
target-code form if the target code is identical to our hardware then (in principle) we just load
it and branch to it! Otherwise we can write an interpreter (normally interpreters for another
physical machine are called instruction set simulators or emulators) in the same manner as
we might write a JVM interpreter.
(a fuller set of type definitions are given in Section 6.2). To evaluate an expression we need
to be able to get the values of variables it uses (its environment). We will simply use a list of
(name,value) pairs. Because our language only has integer values, it suffices to use the ML type
env with interpreter function lookup:
11 I’ve cheated a little by introducing let, but at this point I do not wish to spell out an interpreter for Cmd and
Decl so let provides an easy way of showing how local variables can be dealt with.
19
type env = (string * int) list
fun lookup(s:string, []) = raise UseOfUndeclaredVar
| lookup(s, (t,v)::rest) = if s=t then v else lookup(s,rest);
Now the interpreter for Expr (interpreters for expressions are traditionally called eval even if
Interpret Expr would be more appropriate for large-scale software engineering) is:
You’ll see I have skipped the apply case. This is partly because function call with parameters
is one of the more complicated operations in a compiler or interpreter, and partly because (as
we’ll see later) there are subtleties with nested functions. In our mini-language, we only have two
forms of variables: global (defined at top level), and local (and these are local to the procedure
being executed).12 Parameters and local variables treated equivalently—a good understanding
for execution models (and indeed for many languages) is that a parameter is just a local variable
initialised by the caller, rather than explicitly within a function body. For understanding function
calls in such simple language (and indeed for understanding local versus global variables), it is
convenient to think of the interpreter having two environments—one (rg) holding the name and
values of global variables, the other (rl) of local variables. Then the code for apply might be
(assuming zip takes a pair of lists and forms a list of pairs—here a new environment):
Again, I have cheated—I’ve assumed the function body is just an Expr whereas for my mini-
language it should be a Cmd—and hence the call to eval should really be a call to Interpret Cmd.
However, I did warn in the introduction that for simplicity I will sometimes only consider the func-
tional subset of our mini-language (where the Cmd in a function is of the form { return e; } and
lookupfun() now merely returns e and the function’s parameter list. Extending to Interpret Cmd
and Interpret Decl opens additional cans of worms, in that Interpret Cmd needs to be able to
assign to variables, so (at least in ML) environments now need to have modifiable values:
These notes have attempted to keep the structure clear; see the course web page for a full inter-
preter.
12 Subtleties later include access to local variables other than those in the procedure being executed, and access
20
At this point it is appropriate to compare (non-examinably) this idea of a “syntax tree
interpreter” for a given language with that of an “operational semantics” for the same
language (as per the Part Ib course of the same name).
At some level an interpreter is exactly an operational semantics (and vice versa). Both are
written in a formal language (a program in one case and mathematical rules in the other)
and precisely specify the meaning of a program (beware: care needs to be taken here if the
source language contains non-deterministic constructs, such as race conditions, which an
interpreter might resolve by always taking one possible choice of the many possible allowed
by the semantics).
The essential difference in usage is that: an interpreter is written for program execution
(and typically for efficient execution, but sometimes also for semantic explanation), while an
operational semantics aims at simplicity in explanation and ability to reason about programs
without necessarily being executable. This difference often leads to divergence in style; for
example the simplest operational semantics for the lambda-calculus uses substitution of one
term for a variable within another. However, our eval function uses an environment which
effectively eliminates the need to do substitution on syntax trees by deferring it to variable
access where it is a trivial lookup operation. Substitution is often relatively expensive
and creates new syntax trees at run-time (hence also pretty incompatible with compilation
which relies on having a fixed program). On the other hand the correctness of using an
environment rather than substitution can best be established by exhibiting two operational
semantics—one close to our interpreter (a ‘big-step’ operational semantics in addition to
using an environment) and one using substitution—and then to prove them equivalent using
mathematical techniques.
The structure of a JVM interpreter is of the form (note that here we use a downwards growing
stack):
void interpret()
{ byte [] imem; // instruction memory
int [] dmem; // data memory
int PC, SP, FP; // JVM registers
int T; // a temporary
...
for (;;) switch (imem[PC++])
{
case OP_iconst_0: dmem[--SP] = 0; break;
case OP_iconst_1: dmem[--SP] = 1; break;
case OP_iconst_B: dmem[--SP] = imem[PC++]; break;
13 Java post-version 1.5 now supports type-safe enum types.
21
case OP_iconst_W: T = imem[PC++]; dmem[--SP] = T<<8 | imem[PC++]; break;
Note that, for efficiency, many JVM instructions come in various forms, thus while iconst w is
perfectly able to load the constant zero to the stack (taking 3 bytes of instruction), a JVM compiler
will prefer to use the 1-byte form iconst 0.
Java bytecode can be compiled to real machine code at execution time by a JIT-ing virtual
machine. This might compile the whole program to native machine code before commencing
execution, but such an approach would give a start-up delay. Instead, a lightweight profiling
system can detect frequently-executed subroutines or basic blocks and selectively compile them.
On a modern multicore machine, the compilation need not slow down the interpreting stage since
it is done by another core.
22
Part B: A Simple Compiler
3 Lexical analysis
Lexical analysis, also known as lexing or tokenisation is an important part of a simple compiler
since it can account for more than 50% of the compile time. While this is almost irrelevant for
a compiler on a modern machine, the painful wait for many a program to read XML-formatted
input data shows that lessons are not always learnt! The reason lexing can be slow is because:
2. there are a large number of characters in a program compared with the number of lexical
tokens.
Nowadays it is pretty universally the case that programming language tokens are defined as
regular expressions on the input character set. Lexical tokens are amenable to definition with
regular expressions since they have no long-range or nested structure. This compares with general
syntax analysis that requires parenthesis matching and so on.
d
abd cd
ababd abcd cabd ccd
etc.
Given any regular expression, there is a finite state automaton which will accept exactly those
strings generated by the regular expression. A (deterministic) finite state automaton is a 5-tuple
(A, Q, q0 , δ, F ) where A is a alphabet (a set of symbols), Q is a set of states, q0 ∈ Q is the start
state, δ : Q × A → Q is a transition function and F ⊆ Q is the set of accepting states. It is
often simpler first to construct a non-deterministic finite automaton which is as above, but the
transition function is replaced by a transition relation δ ⊆ Q × A × Q.
When such an automaton is drawn diagrammatically we often refer to it as a transition diagram.
Constructing the finite state automaton from a regular expression can be then seen as starting
with a single transition labelled (rather illegally for our definition of finite state automaton) with
the regular expression; and then repeatedly applying the re-write rules in Fig. 1 to the transition
diagram (this gives a FSA, not necessarily the minimal one!): The transition diagram for the
expression “(a b | c)* d” is:
a b
A finite state automaton can be regarded as a generator of strings by applying the following
algorithm:
23
E* => E
E1
E1|E2 =>
E2
E1 E2 => E1 E2
(E) => E
1. Follow any path from the starting point to any accessible box.
2. Output the character in the box.
3. Follow any path from that box to another box (possibly the same) and continue from step
(2). The process stops when an exit point is reached (exit points correspond to accepting
states).
We can also use the transition diagram as the basis of a recogniser algorithm. For example, an
analyser to recognise :=, :, <numb> and <id> might have the following transition diagram:
yes yes
: = ASS
no no COLON
yes
digit digit NUMB
no no
yes
letter letter
no no
digit
etc no
ID
Optimisation is possible (and needed) in the organisation of the tests. This method is only
satisfactory if one can arrange that only one point in the diagram is active at any one time (i.e.
the finite state automaton is deterministic).
Note that finite state automata are alternatively (and more usually) written as a directed graph
with nodes representing states and labelled edges representing the transition function or relation.
For example, the graph for the expression “(a b | c)* d” can also be drawn as follows:
d
1 3
b 2
With state 3 designated an accepting state, this graph is a finite state automaton for the given
regular expression. The automaton is easily implemented using a transition matrix to represent
the graph.
24
(non-recursively!) named regular expressions to be defined and used (this is harmless as they can
be thought of as macros to be expanded away, but it does help human readability). First, some
named regular expressions for basic constructs:
s = +|− sign
e = E exponent symbol
p = . decimal point
d = 0|1|2|3|4|5|6|7|8|9 digit
I’ve used lower case here not for any strong formal reason, but because s, e, p, d all represent exactly
one character and hence when hand-implementing a lexer it is often convenient to see them as a
character class (cf. isdigit()). So, now let’s define a floating point number F step by step:
J = d d∗ unsigned integer
I = sJ | J signed integer
H = J | pJ | J pJ digits maybe with ‘.’
G = H | eI | H eI H maybe with exponent
F = G | sG G optionally signed
Note that some of the complexity is due to expressing things precisely, e.g. H allows three cases: a
digit string, a digit string preceded a point, or a point with digits either side, but disallows things
like “3.”.14
With some thought we can represent regular expression F as the following deterministic finite-
state automaton (this can be automated but requires significant effort to get this minimal FSA):
p p d d d
1 2 3 4 5 6 7 8
s d p d e s d
d e e e d
with states S3, S5 and S8 being accepting states. Formally, the need to recognise the longest string
matching the input (e.g. ‘3.1416’ rather than ‘3.1’ leaving ‘416’ unread; since 3.1416 and 3.1 both
result in state 8) means that we only accept when we find a character other than one which can
form part of the number. The corresponding matrix is as follows:
s d p e other
S1 S2 S3 S4 S6 .
S2 . S3 S4 S6 .
S3 . S3 S4 S6 acc
S4 . S5 . . .
S5 . S5 . S6 acc
S6 S7 S8 . . .
S7 . S8 . . .
S8 . S8 . . acc
In a program that uses this technique each matrix entry might also specify the address of some
code to deal with the transition15 and note the next matrix row to be used. The entry acc would
point to the code that processes a complete floating point number. Blank entries correspond to
syntactic error conditions.
In general, this technique is fast and efficient, but if used on a large scale it requires some
effort to keep the size of the matrix under control (note for example that treating characters
14 There are other oddities in the syntax given, such as an integer without ‘.’ or ‘E’ being allowed, and a string
25
{+, −, E, ·, 0, . . . , 9} as separate entries rather than character groups {s, e, p, d} would have made
the table several times larger.
As an aside, it is worth noting that for human-engineering reasons we rely on having names for
regular expressions: while theoretically these can just be macro-expanded to give a large regular
expression (you should note that none of my names, like F , I or d were recursively used), in
practice this regular expression is exponentially larger than using named regular expressions and
a good deal harder for humans to understand.
Later we will look at an automated tool (lex) for producing such tables from regular expressions.
4 Syntax analysis
Programming languages have evolved by-and-large to have syntax describable with a context-free
grammar (introduced in the Part Ia course Regular Languages and Finite Automata).
A context-free grammar is a four-tuple (N, T, S, R) where T and N are disjoint sets of respec-
tively terminal and non-terminal symbols16 , S ∈ N is the start (or sentence) symbol, and R is a
finite set of productions. The unqualified word symbol is used to mean any member of N ∪ T . In
a context-free grammar the productions are of the form
U −→ A1 A2 · · · Ak
• S is a sentential form;
• Backus-Naur Form (BNF): non-terminals are written between angle brackets (e.g. <expr>)
while everything else stands for a terminal. (Informally: “non-terminals are quoted”.) The
text ‘::=’ is used instead of ‘−→’
• Parser generators like yacc assume the convention were all terminal symbols are writ-
ten within quotes (”) or otherwise named, and alphanumeric sequences are used for non-
terminals. (Informally: “terminals are quoted”.)
16 In the context of this course terminal symbols are simply tokens resulting from lexing.
26
These differences are inessential to understanding, but vital to writing machine-readable gram-
mars. Because context-free grammars typically have several productions having the same terminal
on the left-hand side, the notation
U −→ A1 A2 · · · Ak | · · · | B1 B2 · · · Bℓ
is used to abbreviate
U −→ A1 A2 · · · Ak
···
U −→ B1 B2 · · · Bℓ .
But beware when counting: there are still multiple productions for U , not one.
Practical tools which read grammars often include additional meta-characters to represent
shorthands in specifying grammars (such as the ‘*’ used for repetition in in Section 2). For further
information see BNF and EBNF (‘extended’) e.g. via
http://en.wikipedia.org/wiki/Backus-Naur_form.
While the definition of grammars focusses on generating sentences, a far more important use
in compiler technology is that of recognising whether a given symbol string is a sentence of a given
grammar. More importantly still, we wish to know what derivation (sequence of re-writes using
production-rules) resulted in the string. It turns out that this corresponds to a parse tree of the
string. This process of taking a symbol string and returning a parse term corresponding to it if it
is a sentence of a given grammar and otherwise rejecting it is unsurprisingly called syntax analysis
or parsing.
Before explaining how to make parsers from a grammar we first need to understand them a
little more.
b) S −→ a T b | T T
T −→ a b | b a
27
This may appear academic, but the derivation determines the grouping and the former corre-
sponds to 1-(1-1) while the latter corresponds to (1-1)-1. Note these have different values when
interpreted as ordinary mathematics.
To avoid this we re-write the grammar to ensure there is only one derivation17 for each sentence.
Two possibilities are:
E −→ 1 | E-1
which yields a left-associative ‘-’ operator (i.e. 1-1-1 parses as (1 − 1) − 1); and
E −→ 1 | 1-E
E −→ 1 | 1-1
E −→ E + F | F
F −→ F ∗ P | P
P −→ 2 | 3 | 4
E −→ E ∗ F | F
F −→ F + P | P
P −→ 2 | 3 | 4
gives ‘+’ higher precedence than ‘*’. Exercise 2: are + and ∗ left- or right- associative in these
examples? Can you change them individually?
28
4.3 Recursive descent
In this method the syntax is converted into transition diagrams for some or all of the syntac-
tic categories of the grammar and these are then implemented by means of recursive functions.
Consider, for example, the following syntax:
P −→ ( T ) | n
F −→ F * P | F / P | P
T −→ T + F | T - F | F
where the terminal symbol n represents name or number token from the lexer. The corresponding
transition diagrams are:
P ( T )
F P * P
/ P
T F + F
- F
Notice that the original grammar has been modified to avoid left recursion18 to avoid the possibility
of a recursive loop in the parser. The recursive descent parsing functions are outlined below
(implemented in C):
void RdP()
{ switch (token)
{ case ’(’: lex(); RdT();
if (token != ’)’) error("expected ’)’");
lex(); return;
case ’n’: lex(); return;
default: error("unexpected token");
}
}
void RdF()
{ RdP();
for (;;) switch (token)
{ case ’*’: lex(); RdP(); continue;
case ’/’: lex(); RdP(); continue;
default: return;
}
}
void RdT()
{ RdF();
for (;;) switch (token)
{ case ’+’: lex(); RdF(); continue;
18 By effectively replacing the production F −→F * P | F / P | P with F −→P * F | P / F | P which has
no effect on the strings accepted, although it does affect their parse tree—see later.
29
case ’-’: lex(); RdF(); continue;
default: return;
}
}
30
struct E *RdP()
{ struct E *a;
switch (token)
{ case ’(’: lex(); a = RdT();
if (token != ’)’) error("expected ’)’");
lex(); return a;
case ’n’: a = mkE_Numb(lex_aux_int); lex(); return a;
/* do names by
** case ’i’: a = mkE_Name(lex_aux_string): lex(); return a;
*/
default: error("unexpected token");
}
}
struct E *RdF()
{ struct E *a = RdG();
for (;;) switch (token)
{ case ’*’: lex(); a = mkE_Mult(a, RdG()); continue;
case ’/’: lex(); a = mkE_Div(a, RdG()); continue;
default: return a;
}
}
struct E *RdT()
{ struct E *a = RdF();
for (;;) switch (token)
{ case ’+’: lex(); a = mkE_Add(a, RdF()); continue;
case ’-’: lex(); a = mkE_Sub(a, RdF()); continue;
default: return a;
}
}
31
4.5 Automated parser generation
Tools which generate parsers (and lexers) are covered later in the course: Section 12.2 explains
their practical use and Section 14 explains how they work and how their tables are constructed.
In general, almost all modern programming languages have their syntax structured in a two-
level fashion: characters are first lexed into tokens—defined by regular expressions—and then
tokens are then parsed into trees—defined by context-free grammars. Sometimes there are warts
on this structure, e.g. C’s typedef can make an identifier behave like a keyword. Sticking rigidly
to the two-level pattern is therefore over-constraining, and allowing decl ::= <id> <id>; instead
of decl ::= <type> <id>; could introduce significant parsing difficulties (even for the advanced,
mechanically-generated parsers introduced in §12.2). Therefore it is common to cheat, in that
output from the syntax analyser that has noted a user-defined type, or similar construct, is fed
backwards into the lexical analyser to alter the token returned next time that identifier is encoun-
tered. This works if the lexer is a subroutine of the syntax analyser so that is has not already run
ahead in the input stream.
5 Type checking
Our simple language from Section 2 requires no type checking at all; we have arranged that all
variables and expressions are of type int and arranged that variable name <var> and function
names <fnname> are syntactically distinguished—at worst we just need to check the constraint
that the number of arguments in a function call match its definition. As such the lex/syn/trans/cg
phase structure made no provision for type-checking.
However, in a real compiler, type-checking generally has to take place after syntax analysis—
consider the examples on page 7. For a typed intermediate code like JVM code which has separate
fadd and iadd operations, then type information has to be resolved before translation to inter-
mediate code. In Java code like
the two addition operations must compile into different operations; moreover, the integer result of
i+1 must be converted to a floating value with the i2f JVM opcode—the Java code has a implicit
conversion which the compiler must make explicit as if the code were:
32
In a production compiler one would therefore expect to see a typecheck phase between syn
and trans which takes an (abstract) syntax tree and either rejects it (“ill-typed”) or produces an
adjusted syntax tree (typically annotated with types and with implicit operations mapped into
explicit tree nodes). Some compiler-writers prefer to see type-checking as re-writing the parse tree
in-place (e.g. writing to fields left initialised when the tree was created), while others prefer to
have separate data-types for “parse tree” and “typed parse tree” (this is largely a matter of taste).
Note that, by consideration of the program above, type-checking must include determining which
identifier use (e.g. f in f+2) is associated with each identifier declaration (e.g. f in (int i, float
f) rather than any other declaration of the name f).
Nevertheless, under the minimalist philosophy of this course, these notes will incorporate the
type-checking phase (including name resolution) phase as part of the translation phase, which we
now turn to.
are generated by translation phase of the compiler invoking a series of calls such as:
gen2(OP_iload, 0);
gen2(OP_iload, 1);
gen1(OP_iadd);
gen2(OP_istore, 2);
The enumeration constants (OP iload etc.) can correspond directly to the bit patterns in a .class
file, or can be decoded in the geni routines into readable strings. Alternatively successive instruc-
tions can be stored in memory ready to be translated into native machine instructions in the CG
phase.
33
| Cond of Expr * Expr * Expr;
datatype Cmd = Assign of string * Expr
| If3 of Expr * Cmd * Cmd
| While of Expr * Cmd
| Block of Decl list * Cmd list
| Seq of Cmd * Cmd (* redundant special case of Block *)
(* (useful for exercises) *)
| Return of Expr;
datatype Decl = Vardef of string * Expr
| Fndef of string * (string list) * Cmd;
type Prog = Decl list; (* shorthand for ’program’ *)
A program in this language essentially consists of an interleaved sequence of initialised variable
definitions let x = e and function definitions let f (x1 , . . . , xk ) {c}.
We will translate programs in this language using routines
void trexp(Expr e) translate an expression
void trcmd(Cmd c) translate a command
void trdecl(Decl d) translate a declaration
which have the side-effect of emitting JVM code which, when executed, causes the expression (or
command, or declaration) to be computed.
static variable, but clearly further variations are needed when objects are introduced in part C.
34
"g" static variable
"n" class variable 0
"m" class variable 1
"f" method
"x" local variable 0
"y" local variable 1
when compiling the call to foo, but just the first four items when merely in the scope of A. In
more detail, the symbol table will be extended by the entry (x, loc, 0) when f’s parameters (x) are
scanned, and then by (y, loc, 1) when the local definition of y is encountered.
fun trexplist[] = ()
| trexplist(e::es) = (trexp(e); trexplist(es));
manipulated. If the optimisations mentioned at the end of §7 are implemented it may also return the storage class
of the expression (e.g. compile-time constant, in a register, in run-time memory, etc.).
21 We have adopted an ML-like syntax to describe this code since we can exploit pattern matching to make the
code more concise than C or Java would be. For ML experts there are still things left undone, like defining the ++
and -- operators of type int ref -> int.
35
if (i>=0 && A[i]==42) { ... }
If i>=0 is false then we are forbidden to evaluate A[i] as it may give rise to an exception. Therefore
we cannot extend the above code for trexp for And and Or by
Instead we have to treat e||e′ as e?1:(e′ ?1:0) and e&&e′ as e?(e′ ?1:0):0. One lazy way to do
this is just to call trexp recursively with the equivalent code above (which does not use And and
Or):
Translation of relational operators (Eq, Ne, Lt, Gt, Le, Ge) is also slightly tricky. The ‘obvious’
and otherwise correct code (and this is acceptable for exams on this course) is just to do:
etc. But the JVM does not have an eq operation—instead it has conditional branches if icmpeq
and the like. So similar code to that for Cond in trexp is needed:
// note we reverse the sense e.g. Eq -> CmpNe etc for trboolop:
| trexp(Eq(x,y)) = trboolop(OP_if_icmpne, x, y)
| trexp(Ne(x,y)) = trboolop(OP_if_icmpeq, x, y)
| trexp(Le(x,y)) = trboolop(OP_if_icmpgt, x, y)
| trexp(Lt(x,y)) = trboolop(OP_if_icmpge, x, y)
| trexp(Ge(x,y)) = trboolop(OP_if_icmplt, x, y)
| trexp(Gt(x,y)) = trboolop(OP_if_icmple, x, y);
fun trboolop(brop,x,y) =
let val p = ++label; // Allocate two labels
val q = ++label in
trexp(x); // load operand 1
trexp(y); // load operand 2
gen2(brop, p); // do conditional branch
trexp(Num(1)); // code to put true on stack
gen2(OP_goto,q); // jump to common point
gen2(OP_Lab,p);
trexp(Num(0)); // code to put false on stack
gen2(OP_Lab,q) // common point; result on stack
end;
The interested reader might note that this technique produces dreadful (but correct) code for:
because it computes booleans corresponding to x>0 and y<9, then computes a boolean representing
whether both are true, and finally compares that with zero. To do things better, it would help
if the Cond case of trexp peeked inside its operand to see if it was a case like And, Or, Eq, . . . Ge
and generated special case code if so. This is very easy to implement using the pattern-matching
constructs of ML, but cumbersome in other languages. It is left as an exercise to the interested
reader (beyond the scope of the taught and examinable) course).
36
6.6 Translation of declarations and commands
Again this is left as an exercise, but one which you are encouraged to sketch out, as it uses
simple variants of ideas occurring in trexp and is therefore not necessarily beyond the scope of
examinations.
Hint: start with
iload 0
iload 1
if_icmpge label6
iconst 1
goto label7
label6: // this was written "Lab 6" earlier
iconst 0
label7: // this was written "Lab 7" earlier
ireturn
0: iload_0
1: iload_1
2: if_icmpge 9
5: iconst_1
6: goto 10
9: iconst_0
10: ireturn
So, my explanation was wrong? No, but I did elide a few details. The actual JVM code has
numeric addresses for instructions (printed to the left by javap -c) and if icmpge and goto use
the address of destination instructions as their operands instead of a label. A separate pass of the
compiler determines the size of each JVM instruction—to calculate the address of each instruction
(relative to the start of the procedure) which then determines the numeric address for each of
the labels. Each use of a label in a if icmpge and goto instruction can now be substituted by a
numeric offset and the labels deleted.
This process (of converting symbolic JVM code to binary JVM code) is called assembly and
the program which does it an assembler. A corresponding pass (either as part of the compiler or
as a stand-along assembler program) is used to convert data structures (often strings) representing
target instructions into their binary form in an object file.
Assembly needs to be performed at the end of compilation—if we are intending to use the JVM
code to generate further code (as we do in subsequent sections below) then we will want to keep
the symbolic ‘label nnn’ form. Indeed, if we download a Java .class file which contains binary
JVM code with the intention of JIT’ing it (compiling it to native binary code), the first thing we
need to do is to identify all binary branch offsets and turn them to symbolic labels.
37
6.8 Type checking revisited
So far in this section we have ignored type information (or rather, just assumed every variable
and operator is of type int—hence the integer operators iadd, ineg, iload etc).
In ML, type checking is performed by a large-scale unification algorithm that infers a most
general type for the subroutine at large. In most other languages, types are inferred locally and
the type of an expression is determined compositionally from the types of its sub-expressions.
Current thinking is that it is most convenient if typing is fully-automatic at a fine grain, such as
within expressions or sequences of statements/commands, but explict at large module boundaries.
In a language like Java, every variable and function name is given an explicit type when it is
declared. This can be added to the symbol table along with other (location and name) attributes.
The language specification then gives a way of determining the type of each sub-expression of the
program. For example, the language would typically specify that e + e′ would have type float if
e had type int and e′ had type float.
This is implemented as follows. Internally, we have a data type representing language types
(e.g. Java types), with elements like T float and T int (and more structured values representing
things like function and class types which we will not discuss further here). A function typeof
gives the type of an expression. It might be coded:
So, when presented with an expression like e + e′ , the compiler first determines (using typeof)
the type t of e and t′ of e′ . The function arith tells us the type of e + e′ . Knowing this latter
type enables us to output either an iadd or a fadd JVM operation. Now consider an expression
x+y, say, with x of type int and y of type float. It can be seen that the type of x differs from the
type of x+y; hence a coercion, represented by a cast in Java, is applied to x. Thus the compiler
(typically in trexp or in an earlier phase which only does type analysis) effectively treats x+y as
((float)x)+y. These type coercions are also elementary instructions in intermediate code, for
example in Java, float f(int x, float y) { return x+y; } generates
iload 0
i2f
fload 1
fadd
freturn
Overloading (having two simultaneous active definitions for the same name, but distinguished
by type) of user defined names can require careful language design and specification. Consider the
C++ class definition
class A
{ int f(int, int) { ... }
float f(float, char) { ... }
void main() { ... f(1,’a’); ... }
}
38
The C++ rules say (roughly) that, because the call (with arguments of type char and int) does
not match any declaration of f exactly, the closest in type variant of f is selected and appropriate
coercions are inserted, thus the definition of main() corresponds to one of the following:
Which is a matter of fine language explanation, and to avoid subtle errors I would suggest that
you do not make your programs depend on such fine details.
39
7 Code Generation for Target Machine
Note: The part II course, ‘Optimising Compilers’, will cover code generation in an alternative
manner dispensing with the stack-based intermediate code. However, let us note that translating
JVM code to native code is exactly what a browser using JIT compilation technology does when an
applet .class file is downloaded.
In fitting with our cheap-and-cheerful approach to compilation let us for now merely observe
that each intermediate instruction listed above can be mapped into a small number of MIPS,
ARM or x86 instructions, essentially treating JVM instructions as a macro for a sequence of x86
instructions. Doing this naı̈vely will produce very unpleasant code, for example recalling the
y := x<=3 ? -x : x
example and its intermediate code with
iload 4 load x (4th load variable)
iconst 3 load 3
if_icmpgt L36 if greater (i.e. condition false) then jump to L36
iload 4 load x
ineg negate it
goto L37 jump to L37
label L36
iload 4 load x
label L37
istore 7 store y (7th local variable)
could expand to the following x8622 code (note that x86 conventionally uses %ebp for FP):
movl %eax,-4-16(%ebp) ; iload 4
pushl %eax ; iload 4
movl %eax,#3 ; iconst 3
pushl %eax ; iconst 3
popl %ebx ; if icmpgt
popl %eax ; if icmpgt
cmpl %eax,%ebx ; if icmpgt
bgt L36 ; if icmpgt
movl %eax,-4-16(%ebp) ; iload 4
...
However, delaying output of PUSHes to stack by caching values in registers and having the compiler
hold a table representing the state of the cache can improve the code significantly:
movl %eax,-4-16(%ebp) ; iload 4 stackpend=[%eax]
movl %ebx,#3 ; iconst 3 stackpend=[%eax,%ebx]
cmpl %eax,%ebx ; if icmpgt stackpend=[]
bgt L36 ; if icmpgt stackpend=[]
movl %eax,-4-16(%ebp) ; iload 4 stackpend=[%eax]
negl %eax ; ineg stackpend=[%eax]
pushl %eax ; (flush/goto) stackpend=[]
b L37 ; goto stackpend=[]
L36: movl %eax,-4-16(%ebp) ; iload 4 stackpend=[%eax]
pushl %eax ; (flush/label) stackpend=[]
L37: popl %eax ; istore 7 stackpend=[]
movl -4-28(%ebp),%eax ; istore 7 stackpend=[]
22 It is part of the general philosophy of this course that the exact language and exact target machine do not
matter for presentation; a good exercise for the reader is to rephrase this in MIPS machine code—this is not a
difficult task, requiring little more than replacing %eax and %ebx with $a0 and $a1 and adjusting opcode names.
40
I would claim that this code is near enough to code one might write by hand, especially when
we are required to keep to the JVM allocation of local variables to %fp-address storage locations.
The generation process is sufficiently simple to be understandable in an introductory course such
as this one; but in general we would not seek to produce ‘optimised’ code by small adjustments
to the instruction-by-instruction algorithm we used as a basis. (For more powerful techniques see
the Part II course “Optimising Compilers”).
However, were one to seek to improve this scheme a little, then the code could be extended to
include the concept that the top of stack cache can represent integer constants as well as registers.
This would mean that the movl #3 could fold into the cmpl. Another extension is to check jumps
and labels sufficiently to allow the cache to be preserved over a jump or label (this is quite an effort,
by the way). Register values could also be remembered until the register was used for something
else (we have to be careful about this for variables accessible by another thread or volatile in
C). These techniques would jointly give code like:
; stackpend=[], regmem=[]
movl %eax,-4-16(%ebp) ; iload 4 stackpend=[%eax], regmem=[%eax=local4]
; iconst 3 stackpend=[%eax,3], regmem=[%eax=local4]
cmpl %eax,#3 ; if icmpgt stackpend=[], regmem=[%eax=local4]
bgt L36 ; if icmpgt stackpend=[], regmem=[%eax=local4]
; iload 4 stackpend=[%eax], regmem=[%eax=local4]
negl %eax ; ineg stackpend=[%eax], regmem=[]
b L37 ; goto stackpend=[%eax], regmem=[]
L36: ; (label) stackpend=[], regmem=[%eax=local4]
; iload 4 stackpend=[%eax], regmem=[%eax=local4]
L37: ; (label) stackpend=[%eax], regmem=[]
movl -4-28(%ebp),%eax ; istore 7 stackpend=[], regmem=[%eax=local7]
This is now about as good as one can do with this strategy.
23 If you are interested (i.e. non-examinable) in knowing more, then a technique for generating CISC-like code
directly from a tree based on tree matching and rewriting techniques is given in:
Aho, A.V., Ganapathi, M. and Tjiang, S.W.K. Code Generation Using tree matching and Dynamic programming”.
ACM Transactions on Programming Languages and Systems, Vol 11, No 4, October 1989.
41
8 Object Modules and Linkers
We have shown how to generate assembly-style code for a typical programming language using
relatively simple techniques. What we have still omitted is how this code might be converted
into a state suitable for execution. Usually a compiler (or an assembler, which after all is only
the word used to describe the direct translation of each assembler instruction into machine code)
takes a source language and produces an object file or object module (.o on Unix and .OBJ on
Windows). These object files are linked (together with other object files from program libraries)
to produce an executable file (.EXE on Windows) which can then be loaded directly into memory
for execution. Here we sketch briefly how this process works.
Consider the C source file:
int m = 37;
extern int h(void);
int f(int x) { return x+1; }
int g(int x) { return x+m+h(); }
Such a file will produce a code segment (called a text segment on Unix) here containing code for
the functions f and g and a data segment containing static data (here m only).
The data segment will contain 4 bytes probably [0x25 00 00 00].
The code for f will be fairly straightforward containing a few bytes containing bit-patterns
for the instruction to add one to the argument (maybe passed in a register like %eax) and return
the value as result (maybe also passed in %eax). The code for g is more problematic. Firstly it
invokes the procedure h() whose final location in memory is not known to g so how can we compile
the call? The answer is that we compile a ‘branch subroutine’ instruction with a dummy 32-bit
address as its target; we also output a relocation entry in a relocation table noting that before the
module can be executed, it must be linked with another module which gives a definition to h().
Of course this means that the compilation of f() (and g()) cannot simply output the code
corresponding to f; it must also register that f has been defined by placing an entry to the effect
that f was defined at (say) offset 0 in the code segment for this module.
It turns out that even though the reference to m within g() is defined locally, we will still need
the linker to assist by filling in its final location. Hence a relocation entry will be made for the
‘add m’ instruction within g() like that for ‘call h’ but for ‘offset 0 of the current data segment’
instead of ‘undefined symbol h’.
A typical format of an object module is shown in Figure 3. This is for the format ELF (we
only summarise the essential features of ELF).
42
Header information; positions and sizes of sections
.text segment (code segment): binary data
.data segment: binary data
.rela.text code segment relocation table:
list of (offset,symbol) pairs showing which offset within
.text is to be relocated by which symbol (described
as an offset in .symtab)
.rela.data data segment relocation table:
list of (offset,symbol) pairs showing which offset within
.data is to be relocated by which symbol (described
as an offset in .symtab)
.symtab symbol table:
List of external symbols used by the module:
each is listed together with attribute
1. undef: externally defined;
2. defined in code segment (with offset of definition);
3. defined in data segment (with offset of definition).
Symbol names are given as offsets within .strtab
to keep table entries of the same size.
.strtab string table:
the string form of all external names used in the module
by program fetch; this is the process by which the code and data segments are read into virtual
memory at their predetermined locations and branching to the entry point which will also have
been marked in the executable module.
43
fread(p, n, 1, f); /* read code */
realsin = (double (*)(double))p; /* remember code address */
}
return (*realsin)(x);
}
Essentially, the first time the sin stub is called, it allocates space and loads the current version
of the object file (SIN.DLL here) into memory. The loaded code is then called. Subsequent calls
essentially are only delayed by two or three instructions.
In this scheme we need to distinguish the stub file (SIN.OBJ) which is small and statically linked
to the user’s code and the dynamically loaded file (SIN.DLL) which is loaded in and referenced
at run-time. (Some systems try to hide these issues by using different parts of the same file or
generating stubs automatically, but it is important to understand the principle that (a) the linker
does some work resolving external symbols and (b) the actual code for the library is loaded (or
possibly shared with another application—given a sensible virtual memory system!) at run-time.)
Dynamic libraries have extension .DLL (dynamic link library) on Microsoft Windows and
.so (shared object file) on Linux. Note that they should incorporate a version number so that an
out-of-date DLL file cannot be picked up accidentally by a program which relies on the features
of a later version.
The principal disadvantage of dynamic libraries is the management problem of ensuring that a
program has access to acceptable versions of all DLL’s which it uses. It is sadly not rare to try to
run a Windows .EXE file only to be told that given DLL’s are missing or out-of-date because the
distributor forgot to provide them or assumed that you kept your system up to date by loading
newer versions of DLL’s from web sites! Linux gives even less helpful messages and the ldd
command must be used to find the name of the missing library. Probably static linking is more
reliable for executables which you wish still to work in 10 years’ time—even if you cannot find the
a hardware form of the processor you may be able to find an emulator.
44
Part C: Implementing Language Features
In earlier sections of the course we showed how to translate a subset of Java into both JVM-style
code and to native machine code and how such latter code can be linked to form an executable.
The subset of Java considered was a single class containing static methods and variables—this is
very similar in expressiveness to the language C.
In this part of the course we will try to crystallise various notions which appeared informally
in the first part into formal concepts. We break this into two main aspects: first investigate some
of the interactions or equivalences which occur in a simple language and how these are reflected
in a simple interpreter. Then we consider how other aspects of programming languages might be
implemented on a computer, in particular we focus on: how free variables (used by a function but
not defined in it) are accessed, how exceptions and inheritance are implemented, and how types
and storage allocation interact.
9 Foundations
First we look at foundational issues and how these are important for properly understanding the
fine details of a programming language.
Although everyone is familiar with ML and Java (and learning C/C++), it helps first to explore
the idea of assignment and aliasing in a language-neutral manner.
Given an assignment e = e′ we:
To avoid the overtones and confusion that go with the terms address and value we will use the
more neutral words Lvalue and Rvalue (first coined by C. Strachey); this is useful for languages
like C where addresses are just one particular form of value. An Lvalue (left hand value) is the
address (or location) of an area of store capable of holding the Rvalue. An Rvalue (right hand
value) is a bit pattern used to represent an object (such as an integer, a floating point number, a
function, etc.). In general, both Lvalues and Rvalues require work to be done when they are being
evaluated, consider A[f()] = B[g()];.
Note that in Java, the above description of e:=e′ ; is precise, but other languages (such as C
and C++) say that the exact ordering and possible interleaving of evaluation of e and e′ is left to
the implementation; this matters if expressions contain side-effects, e.g.
A[x] = f();
9.1 Aliasing
We see situations where multiple names refer to the same variable or storage location—this is
called aliasing. In C and C++, there are obvious sources of aliases arising from the support of
unrestricted pointers and unions. In a language with call-by-reference, aliasing commonly occurs
when the same variable is passed twice into the same function.
Consider the following C/C++/Java code:
45
float p = 3.4;
float q = p;
This causes a new storage cell to be allocated, initialised with the value 3.4 and associated with
the name p. Then a second new storage cell (identified by q) is initialised with the (Rvalue)
contents of p (clearly also 3.4). Here the defining operator = is said to define by value. One can
also imagine language constructs permitting definition by reference (also called aliasing) where
the defining expression is evaluated to give an Lvalue which is then associated with the identifier
instead of a new storage cell being allocated, e.g.
float r ≃ p;
Since p and r have the same Lvalue they share the same storage cell and so the assignments:
p := 1.63 and r := 1.63 will have the same effect, whereas assignments to q happen without
affecting p and r. In C/C++, definition by reference is written:
float &r = p;
whereas in ML mutable storage cells are defined explicitly so the above example would be ex-
pressed:
val p = ref 3.4;
val q = ref (!p);
val r = p;
One reason for making such a fuss about this is to be able to discuss the effects of Java (and
C♯ ) inner classes.
class A {
void f(int x) {
class B {
int get() { return x; }
// void inc() { x++; } // should this be allowed?
}
B p = new(B);
x++;
B q = new(B);
if (p.get() != q.get()) println("x != x??");
};
The question is whether x is copied or a whether a single storage cell is used for it is often best
thought of as whether x’s Lvalue or Rvalue is used in class B. The choice is a matter of language
design.
Finally, note that defining a new variable is quite different from assigning to a pre-existing
variable. Consider the Java programs:
int a = 1; int a = 1;
int f() { return a; } int f() { return a; }
void g() { a = 2; println(f()); } void g() { int a = 2; println(f()); }
One adds a new entry to the environment while the other modifies a cell already present in the
environment.
46
lambda-calculus subset of ML); The second, related reason, is that it provides the archetypical no-
tion of variable binding—which we need to understand well to write an interpreter for a language
like ML.
Let’s first recall that the ML let and fun (non-recursive—see below for how to fix this) forms
are expressible just using lambda.
let f x = e ⇒ let f = λx.e
let y = e in e′ ⇒ (λy.e′ ) e
So, for example,
let f(y) = y*2
in let x = 3
in f(x+1)
can be simplified to
(λf. (λx. f(x+1)) (3)) (λy. y*2)
This translation does not encode recursion (ML’s fun f x = e implicitly expands to let rec
f = λx.e) and the above simplifying translation does not say how to represent rec. For example,
without rec
let f(n) = n=0 ? 1 : n*f(n-1) in f(4)
translates to
(λf. f(4)) (λn. n=0 ? 1 : n*f(n-1) )
in which the right-most use of f is unbound rather than recursive.
One might think that recursion must inevitably require an additional keyword, but note that
it is possible to call a function recursively without defining it recursively:
let f(g,n) = ... g(g,n-1) ... // f does not appear in the body of f
in f(f, 5)
Here the call g(g,n-1) makes a recursive call of (non-recursive) f!
Exercise 3: complete the body of f so that the call yields 5! = 120.
By generalising this idea it is possible to represent a recursive definition let rec f = e as the
non-recursive form let f = Y (λf.e) which at least binds all the variables to the right places.
The question is whether Y needs to be a piece of magic built in to the system or whether it can
itself be a term (expression) of the lambda-calculus. For instance, in computation theory, one
learns that the primitive recursive functions need to be extended with the µ operator to become
Turing powerful.
The remarkable answer is that Y can be expressed purely in lambda-calculus. It is called the
fixed-point combinator.
One can write25
Y = λf. (λg. (f (λa. (gg)a)))(λg. (f (λa. (gg)a))).
(Please note that learning this lambda-definition for Y is not examinable for this course!) For
those entertained by the “Computation Theory” course, this (and a bit more argument) means
that the lambda-calculus is “Turing powerful”.
Finally, an alternative implementation of Y (there seen as a primitive rather as the above
arcane lambda-term) suitable for an interpreter is given in Section 9.4. This is also useful since
neither form for Y (nor indeed the f(f,5) trick) passes the ML type system even though they are
well formed in most other senses.
25 The alternate form
Y = λf. (λg. gg)(λg. f (gg))
is usually quoted, but (for reasons involving the fact that our lambda-evaluator uses call-by-value and the above
definition requires call-by-name) will not work on the lambda-evaluator presented in the course supplemental
material.
47
9.3 Object-oriented languages
The view that lambda-calculus provides a fairly complete model for binding constructs in pro-
gramming languages has generally been well-accepted. However, notions of inheritance in object-
oriented languages seem to require a generalised notion of binding. Consider the following C++
program:
const int i = 1;
class A { const int i = 2; };
class B : A { int f(); };
int B::f() { return i; }
There are two i variables visible to f(): one being i=1 by lexical scoping, the other i=2 visible
via inheritance. Which should win? C++ defines that the latter is visible (because the definition
of f() essentially happens in the scope of B which is effectively nested within A). The i=1 is only
found if the inheritance hierarchy has no i. Note this argument still applies if the const int
i=1; were moved two lines down the page. The following program amplifies that the definition of
the order of visibility of variables is delicate:
const int i = 1;
class A { const int j = 2; };
void g()
{ const int i = 2;
class B : A { int f() { return i; }; }
// which i does f() see?
}
For years, the lambda-calculus provided a neat understanding of scoping that language designers
could follow simply; now such standards committees have to use their (not generally reliable!)
powers of decision.
Note that here we have merely talked about (scope) visibility of identifiers; languages like
C/Java also have declaration qualifiers concerning accessibility (public, private, etc.). It is for
standards bodies to determine whether, in the first example above, changing the declaration of
i in A to be private should invalidate the program or merely cause the private i to become
invisible so that the i=1 declaration becomes visible within B::f(). (Actually ISO C++ checks
accessibility after determining scoping.)
We will later return to implementation of objects and methods in terms of data and procedures
using source-to-source translations.
later wish to translate the programs into machine code and this is only possible if we have a fixed set of expressions
rather than dynamically re-writing potentially new expressions during evaluation.
48
The expression: (λx. (λn. n+x)(4)) (3) would be written in ML (or C, assuming appropri-
ate (constructor) functions like Apply, Fn etc. were defined to allocated and initialise structures)
as:
Plus
When we evaluate such an Expr we expect to get a value which is either an integer or a function
(note this is an example of dynamic typing—see Section 10.13). In ML we write this concisely as
(the justification for why functions consist of more than simply their text will become apparent
when we study the evaluator ‘eval’ below). In languages without disjoint union types (such as
Java) we have again to write it cumbersomely as an abstract parent class with two instantiable
extensions.
We will represent the environment of defined names (names in scope) as a linked list with the
following structure:
(I.e. an Env value is either Empty or is a 3-tuple giving the most recent binding of a name to a
value and the rest of the environment.) The function to look up a name in an environment27 could
be defined in ML as follows.
‘expression’.
49
of IntVal(i) => raise oddity("apply of non-function")
| FnVal(bv, body, r_fromdef) =>
let val arg = eval(e’, r)
in eval(body, Defn(bv, arg, r_fromdef))
end;
The immediate action of eval depends on the leading operator of the expression it is evaluating. If
it is Name, the bound variable is looked up in the current environment using the function lookup. If
it is Numb, the value can be obtained directly from the node (and tagged as an IntVal). If it is Plus,
the two operands are evaluated by (recursive) calls of eval using the current environment and
their values summed (note the slightly tedious code to check both values correspond to numbers
else to report an error). The value of a lambda expression (tagged as a FnVal) is called a closure
and consists of three parts: the bound variable, the body and the current environment. These
three components are all needed at the time the closure is eventually applied to an argument.
To evaluate a function application we first evaluate both operands in the current environment
to produce (hopefully) a closure (FnVal(bv, body, r_fromdef)) and a suitable argument value
(arg). Finally, the body is evaluated in an environment composed of the environment held in the
closure (r fromdef) augmented by (bv, arg), the bound variable and the argument of the call.
At this point it is appropriate to mention that recursion via the Y operator can be simply
incorporated into the interpreter. Instead of using the gory definition in terms of λ, we can
implement the recursion directly by
| eval(Y(Fn(f,e)), r) =
let val fv = IntVal(999);
val r’ = Defn(f, fv, r);
val v = eval(e, r’)
in
fv := v; (* updates value stored in r’ *)
v
end;
This first creates an extended closure r’ for evaluating e which is r extended by the (false)
assumption that f is bound to 999. e (which should really be an expression of the form λx. e′
to ensure that the false value of f is not used) is then evaluated to yield a closure, which serves
as result, but only after the value for f stored in the closure environment has been updated to
its proper, recursive, value fv. This construction is sometimes known as “tying the knot [in the
environment]” since the closure for f is circular in that its environment contains the closure itself
(under name f).
Note that, in ML, the assignment to fv requires it to actually be a ref cell or for some other
mechanism to be really used. A more detailed working evaluator including Y and let) can be
found in the supplemental material.
let a = 1;
let f() = a;
let g(a) = f();
print g(2);
50
Exercise 4: Check your understanding of static and dynamic scoping by observing that this prints
1 under the former and 2 under the latter.
You might be tempted to believe that rebinding a variable like ‘a’ in dynamic scoping is
equivalent to assigning to ‘a’. This is untrue, since when the scope ends (in the above by g being
exited) the previous binding of ‘a’ (of value one) again becomes visible, whereas assignments are
not undone on procedure exit.
allocation and deallocation does not follow a stack discipline for languages like ML, so to make the lambda-evaluator
work these need to be heap-allocated—see later.
51
For an example of this 2D addressing, consider variables bound in the following contrived
program (we ignore function names f, g, h, k for simplicity):
let f(a,b,c) =
( let g(x,y,z) = (let h(t) = E in ...)
in g((let k(u,v) = E ′ in ...), 12, 63)
)
in f(1,6,3)
and suppose the environments (here just variable names, we will not know values until run-time)
at the start of the bodies of f, g, h, k are respectively ρ1 , ρ2 , ρ3 , ρ4 . The environment structure
can be represented as a tree as follows (note that here the tree is in some sense backwards from
usual in that each node has a single edge to its parent, rather than each node having an edge to
its children):
ρ1 :(a,b,c)
k
Q
Q
ρ2 :(x,y,z) Q
ρ4 :(u,v)
6
ρ3 :(t)
We can associate with any name used an ‘address’ consisting of a pair of numbers, namely, a level
number and a position within that level. For example:
ρ1 a:(1,1) b:(1,2) c:(1,3) level 1
ρ2 x:(2,1) y:(2,2) z:(2,3) level 2
ρ3 t:(3,1) level 3
ρ4 u:(2,1) v:(2,2) also level 2
Note that from E only the first lines’ variables are visible, while from E ′ only the first and last lines’
variable are visible—hence the fact that (e.g.) x and u have the same 2D-address is unimportant.
Now, given an access to a variable x (with 2D address (i, j) from a point at function nesting
level d, instead of accessing x by name we can instead use 2D index (relative address) of (d − i, j).
For example, access to c (whose 2D address (1, 3)) is (2, 3) in E (in environment ρ3 of depth 3) is
(2, 3), whereas access to the same variable in E ′ (in ρ4 of depth 2) is (1, 3).
Exercise 5: replace all variables in the above sample code by their indices (relative 2D ad-
dresses).
Logically, the move from environments as a list of name-value pairs to environments as chained
arrays is just a matter of changing the abstract data-type for environments. It is a good exercise
to code this for the lambda evaluator; however the full benefit is only achieved when the tree is
more fully adjusted to make a single allocation site (at procedure entry) for all the let bindings
within a procedure rather than an interpreter coming across let statements one at a time.
Note particularly that the idea of “function values are closures” is unaffected by this change
of representation of environment; a compiled form of function value will be a pair consisting of a
pointer to the code for the function together with an environment (a pointer to array of arrays
holding variable values or a pointer to the stack frame of its definer).
fun f(x) {
let a = ...;
fun h(y) {
52
let b = ...;
fun g(w) {
let c = ...;
if ...
then return a;
else return h(c)
}
return b + g(y);
}
return x + h(a);
}
fun main() { return f(17); }
is transformed into
fun g’(w, x, a, y, b) {
let c = ...;
if ...
then return a;
else return h’(c, x, a )
}
fun h’(y, x, a) {
let b = ...;
return b + g’(y, x, a, y, b);
}
fun f’(x) {
let a = ...;
return x + h(a, x, a);
}
53
10 Machine Implementation of Various Interesting Things
In this section we address how various concepts in high-level languages can be implemented in
terms of data structures and instructions of on a typical modern CPU, e.g. MIPS, ARM or x86.
Thus t is accessed relative to FP in one instruction, access to variables in ρ2 first load the S field
from the linkage information and then access x, y or z from that (two instructions), and variables
in ρ1 use three instructions first chaining twice down the S chain and then accessing the variable.
Hence the instruction effecting a call to a closure (now represented by a pair of the function
entry point and the stack frame pointer in which it was defined) now merely copies this latter
environment pointer from the closure to the S field in the linkage information in addition to the
work detailed for the JVM.
Exercise 7: give a simple example in which S and FP’ pointers differ.
An example
Consider the following function (we wrap all example code in this section within a main function
to ensure variables are not seen as top-level variables which use absolute addressing):
let main() =
( let a, b = 1, 2
let f(x, y) = a*x + b*y
let c = 3
c := f(4,5)
...
)
29 Note that the similarity to static linking is totally accidental.
54
At the moment when f is just about to be entered the stack frame for main is as follows (in this and
subsequent diagrams I have labelled the linkage information FP1 FP2 etc. instead of confusingly
using FP’ several times):
- Code for f
arguments c f b a ?
5 4 3 2 1 FP1 RA1 S1
6
FP
At the moment just after f has been entered (when a*x+b*y is about to be evaluated) the state is
as follows (SP points to the same location as FP as f has not (yet) allocated any local variables):
- Code for f
y x c f b a ?
??
FP2 RA2 S2 5 4 3 2 1 FP1 RA1 S1
6 - -
FP frame for f frame for main
We see that f can now access x and y from FP (at offsets +4 and +3, recall parameters appear
higher in memory than a frame, and locals below a frame), and a and b from the definer’s stack
frame (offsets −1 and −2) which is available as S2. Beware: we cannot access a and b as a constant
offset from FP since f may be called twice (or more) from within main (or even from a further
function to which it was passed as a parameter) and so the stack frame for main() may or may
not be contiguous with x as it is in the example. Similarly, it is vital to follow the static chain
(S2 here) rather than the dynamic chain (FP2 here) even though in the example these point to
the same place; a general explanation was given earlier, but here just consider what happens if f
calls itself recursively—the FP3, FP4 (etc.) pointers chain down the stack each to the next previous
frame, while the S3 and S4 (etc.) pointers all point to the frame for f.
You might wonder why we allocated f, or more properly its closure, to a local variable when
we knew that it was constant. The answer was that we treated the local definition of f as if it
were
let f = λ(x,y). a*x + b*y
and further that f was an updatable variable. This can help you see how first-class function-valued
variables can be represented. In practice, if we knew that the call to f was calling a given piece of
code—here λ(x, y).a ∗ x + b ∗ y—with a given environment pointer—here the FP of the caller—then
the calling sequence can be simplified.
55
The result of f is a pointer to the local variable a but unfortunately when we return from the call
this variable no longer exists and p is initialised to hold a pointer which is no longer valid and
if used may cause an extremely obscure runtime error. Many languages (e.g. Pascal, Java) avoid
this problem by only allowing pointers into the heap.
Some other objects such as functions and arrays contain implicit pointers to the stack and so
have to be restricted if a stack implementation is to work. Consider:
let main() = {
let f(x) = let g(t) = x+t // i.e. g = λt.x+t
in g
let add1 = f(1)
...
}
The result of f(1) should be a function which will add one to its argument. Thus one might hope
that add1(23) would yield 24. It would, however, fail if implemented using a simple stack. We
can demonstrate this by giving the state of the stack at various stages of the evaluation. Just after
the f has been declared the stack (for main) is as follows:
( - Code for f
((((
?
FP0 RA0 S0
f 6
FP
At the time when g has just been declared in the evaluation of f(1) the stack (for main and f)
is as follows (SLIGHT ERROR: In the next two diagrams I’ve put x, an argument to f, on the
‘wrong’ side of FP1,RA1,S1 as if x were a local variable of f—this is not quite consistent with the
JVM model I presented, but the story is unchanged, so don’t worry):
( - Code for(g ( - Code for f
(((( (( (
g x ? f ?
1 FP1 RA1 S1 FP0 RA0 S0
A
6 6A 6
A
SP FP
After the deallocation of the frame for f and declaration of add1 in the stack frame of main the
stack would be as follows:
Code for g (( - Code for f
( ((
where x used to be 6
? add1 f ?
FP0 RA0 S0
6 6 6
SP FP
Thus if we now try to use add1 it will fail since its implicit reference to x will not work (note its
dangling pointer to a de-allocated frame). If g had free variables which were also free variables
of f then failure would also result since the static chain for g is liable to be overwritten (and has
been in this example–by add1).
The simple safe rule that many high-level languages adopt to make a stack implementation
possible is that no object with implicit pointers into the stack (functions, arrays or labels) may
be assigned or returned as the result of a procedure call. Algol-60 first coined these restrictions
(functions, stack-allocated arrays etc. can be passed into functions but not returned from them)
56
as enabling a stack-based implementation to work and they still echo in many current languages.
Languages like Java avoid this issue at the cost of heap-allocating all objects.
ML clearly does allow function values to be returned from function calls. We can see that the
problem in such languages is that the above implementation would forbid stack frames from being
deallocated on return from a function, instead we have to wait until the last use of any of its bound
variables.30 This implementation is called a “Spaghetti stack” and stack-frame deallocation is
handled by a garbage collector. However, the overhead of keeping a whole stack-frame for possibly
a single variable might seem excessive (but see Appel’s “Compiling with Continuations” book)
and we now turn to a common, efficient implementation.
During the evaluation of a function call, two pointers are needed: the FP pointer, as before,
to address the arguments and local variables, and a pointer FV to point to the free variable
list (although note that the FV pointer could be treated as an additional hidden argument to
functions—this would be appropriate for expressing the translation as C code rather than machine
code).
This mechanism requires more work at function definition time but less work within the call
since all free variables can be accessed via a simple indirection. It is used in the Edinburgh SML
implementation. (An additional trick is to store a pointer to the function code in offset 0 of the
free variable list as if it were the first free variable. A pointer to the free variable list can then
represent the whole closure as a single word.)
Note that this works most effectively when free variables are Rvalues and hence can be copied
freely. When free variables are Lvalues we need to enter a pointer to the actual aliased location
in the free variable list of each function which references it. It is then necessary also to allocate
the location itself on the heap. (For ML experts: because of standard ML’s use of ref, there are
no updatable variables in ML—only updateable ref cells. Therefore the values (ordinary values
or (pointers to) ref cells can be copied without unaliasing anything.)
57
Thus if a simple variable may be defined (see Section 9.1) to be either a copy or an alias of an
existing variable, then so should a parameter passing mechanism. To put this another way, should
parameter passing communicate the Lvalue of a parameter (if it exists) or the Rvalue?
Many languages (e.g. Pascal, Ada) allow the user to specify which is to be used. For example:
might declare a function whose argument is an Rvalue. The parameter is said to be called by
value. Alternatively, the declaration:
might declare a function whose argument is an Lvalue. The parameter is said to be called by
reference. The difference in the effect of these two modes of calling is demonstrated by the
following example.
INTEGER a,i,b;
PROCEDURE f(x) INTEGER;
BEGIN a := x;
i := i+1;
b := x
END;
a:=i:=b:=10;
f(i+2);
COMMENT a=12, i=11 and b=13;
ML and C/C++ have no call-by-name mechanism, but the same effect can be achieved by passing
a suitable function by value. The following convention works:
exploited in so-called ‘lazy’ languages and the Part II course looks at optimisations which select the most appropriate
calling mechanism for each definition in such languages.
58
3. Replace the actual parameter expression by a parameterless function whose body is that
expression.
The above Algol example then transforms into the following C program:
[C experts might care to note that this trick only works for C when all variables free to the thunk
are declared at top level; Java cannot even express passing a function as a parameter to another
function.]
as
It is a good exercise (and a frequent source of Tripos questions) to write a program which prints
different numbers based on which (unknown) parameter passing mechanism a sample language
uses.
Incidentally while call-by-value-result (IN OUT) parameter passing fell out of favour after
Ada, it has significant advantages for a concurrent call to another processor on a shared-memory
multi-core processor compared to using aliasing. Each write to a common location from a given
processor invalidates the corresponding cache line in other processors, hence taking a copy and
writing back can be significantly more efficient.
59
10.7 Labels and jumps
Many languages, like C and Java, provide the ability to label a statement. In C one can branch to
such statements from anywhere in the current routine using a ‘goto’ statement. (In Java this is
achieved by the ‘break’ statement which has rather more restrictions on its placement). In such
situations the branch only involves a simple transfer of control (the goto instruction in JVM);
note that because only goto is a statement and one can only label statements, the JVM operand
stack will be empty at both source and destination of the goto—this rather implicitly depends on
the fact that statements cannot be nested within expressions.
However, if the destination is in a outermore procedure (either by static nesting or passing a
label-valued variable) then the branch will cause an exit from one or more procedures. Consider:
{ let r(lab) = { ...
... goto lab;
...
}
...
r(M);
...
M: ...
}
In terms of the stack implementation it is necessary to reset the FP pointer to the value it had
at the moment when execution entered the body of M. Notice that, at the time when the jump is
about to be made, the current FP pointer may differ. One way to implement this kind of jump
is to represent the value of a label as a pair of pointers—a pointer to compiled code and a FP
pointer (note the similarity to a function closure—we need to get to the correct code location and
also to have the correct environment when we arrive). The action to take at the jump is then:
1. reset the FP pointer,
2. transfer control.
Such a jump is called a long jump.
We should notice that the value of a label (like the value of a function) contains an implicit
frame pointer and so some restrictions must be imposed to avoid nonsensical situations. Typically
labels (as in Algol) may not be assigned or returned as results of functions. This will ensure that
all jumps are jumps to activations that dynamically enclose the jump statement. (I.e. one cannot
jump back into a previously exited function!33 )
10.8 Exceptions
ML and Java exceptions and their handlers are a form of long jump where the destination depends
on the program dynamics and that can pass an argument.
This leads to the following implementation: a try (Java) or handle (ML) construct effectively
places a label on the handler code. Entering the try block pushes the label value (recall a
label/frame-pointer pair) onto a stack (H) of handlers and successful execution of the try block
pops H. When an exception occurs its argument is stored in a reserved variable (just like a procedure
argument) and the label at the top of H is popped and a goto executed to it. The handler code
then checks its argument to see if it matches the exceptions intended to be caught. If there is no
match the exception is re-raised therefore invoking the next (dynamically) outermore handler. If
the match succeeds the code continues in the handler and then with the statement following the
try-except block.
For example given exception foo; we would implement
33 When compiling Prolog (beyond this course), note that backtracking has a good deal in common with branching
60
try C1 except foo => C2 end; C3
as
push(H, L2);
C1
pop(H);
goto L3:
L2: if (raised_exc != foo) doraise(raised_exc);
C2;
L3: C3;
and the doraise() function looks like
void doraise(exc)
{ raised_exc = exc;
goto pop(H);
}
An alternative implementation of ‘active exception handlers’, which avoids using a separate ex-
ception stack, is to implement H as a linked list of handlers (label-value, next) and keep a
pointer to its top item. This has the advantage that each element can be stored in the stack frame
which is active when the try block is entered; thus a single stack suffices for function calls and
exception handlers.
Finally, sadly ISO C labels cannot be used as values as indicated above, and so code shown
above would have to be implemented using the library function setjmp() instead.
10.9 Arrays
When an array is declared space must be allocated for its elements. In most languages the
lifetime of an array is the same as that of a simple variable declared at the same point, and so it
would be natural to allocate space for the array on the runtime stack. This is indeed what many
implementations do. However, this is not always convenient for various reasons. Consider, for
example, the following function with ‘obvious’ storage layout on a descending stack:
void f()
{ int x=1, y=2;
int v[n]; // an array from 0 to n-1
int a=3, b=4;
...
}
Within its body its stack frame might look like the following:
elements of v
b a ? ?y x
4 3 2 1 FPRA
6 0 1 n-1 6
subscripts
SP FP
In this example, n may be large and so the variables a and b may be a great distance from FP.
On some machines access to such variables is less efficient. Moreover, if n is not a compile-time
constant,34 the position of a and b relative to FP will not be known until runtime, again causing
inefficiency.
For this reason, large or compile-time-unknown size arrays are normally allocated on the heap.35
34 C requires n to be a compile-time constant.
35 Experts might care to look at the (non-ISO) Linux C function alloca() for an interesting trick of allocating
such arrays in the current stack frame between the received formal parameters and the out-going actual parameters.
I am not recommending its use as not all implementations provide it and there is the hidden cost of the waste of a
register on many implementations.
61
10.10 Object-oriented language storage layout
Declarations (in C++) like
class A { int a1,a2; } x;
allocate storage for two integers and record the fact that a1 is at offset zero, and a2 is at offset 4
(assuming ints are 4 bytes wide). Now after
class B : A { int b; };
objects of type B have 3 integer fields a1 and a2 (by inheritance) normally stored at offsets 0 and 4
so that (pointers to) objects of type B can be passed to functions expecting objects of type A with
no run-time cost. The member b would then be at offset 8. The following definition is similar.
class C : A { int c; };
[Note that Java uses the word ‘extends’ instead of ‘:’.]
The above details only dealt with ordinary members and inheritance. Suppose we now add
member functions (methods). Firstly consider the implementation of a method like:
class C {
int a;
static int b;
int f(int x) { return a+b+x;}
};
How is f() to access its variables? Recall that a static variable is per-class, and a non-static one
per-instance. Hence the code could be re-written as:
int unique_name_for_b_of_C;
class C {
int a;
int f(int x) { return a + unique_name_for_b_of_C + x;}
};
Now consider a call to f() such as c.f(x) where c is of type C. This is typically implemented as
an ordinary procedure call unique name for f of C(c,x) and the definition of f() implemented
as:
int unique_name_for_f_of_C(C hidden, int x)
{ return hidden.a // fixed offset within ‘hidden’
+ unique_name_for_b_of_C // global variable
+ x; // argument
};
Note that hidden is usually called this (modulo the fact that my hidden is a value of type C
while this is a pointer to a C)—the idea here is merely to emphasis its implicit nature as a ‘hidden
parameter’.
Let us now turn to how inheritance affects this model of functions, say in Java:
class A { void f() { printf("I am an A"); }};
class B:A { void f() { printf("I am a B"); }};
A x;
B y;
void g(A p) { p.f(); }
main() { x.f(); // gives: I am an A
y.f(); // gives: I am a B
g(x); // gives I am an A
g(y); // gives what?
}
62
There are two cases to be made; should the fact that in the call p.f(); we have that p is of type A
cause A::f(); to be activated, or should the fact that the value of p, although now an A was
originally a B cause B::f(); to be activated and hence “I am a B” to be printed? In Java the
latter happens; by default in C++ the former happens, to achieve the arguably more useful Java
effect it is necessary to use the virtual keyword:
So how is this implemented? Although it appears that objects of type A have no data, they
need to represent that fact that one or other f is to be called. This means that their underlying
implementation is of a record containing a storage cell containing the address of the function to
be called. Using C as a representation language, objects a of class A and b of class B would be
represented by:
(Aside: in practice, since there may be many virtual functions, in practice a virtual function
table is often used whereby a class which has one or more virtual functions has a single additional
cell which points to a table of functions to be called when methods of this object are invoked. This
can be shared among all objects declared of that type, although each type inheriting the given
type will in general need its own table).
For more details on this topic the interested reader is referred to Stroustrup “The C++ Pro-
gramming Language (3rd Edition)” or to the C++ standard (ISO/IEC 14882:2003 “Programming
languages—C++”).
(Example, a car and a boat both inherit from class vehicle, so think about an amphibious craft.)
Firstly there is the observation that passing an object of type D to a routine expecting C must
involve a run-time cost of an addition so that element c still can be accessed at byte offset 8 in
the received C. (This assumes that B is stored at offset zero in D, and C follows contiguously.)
There is also the more fundamental question as to what are the members of objects of type D.
Does it have 7 (3 in both B and C and also d)? Or maybe 5 (a1, a2, b, c, d)? C++ by default
has 7, i.e. the two copies of A are separate. In C++ we can cause the two copies of A to share by
replacing the definitions for B and C by
But now the need to treat objects of type D as objects of type B or C means that the storage layout
for D is likely to be implemented in the language C as
63
int d;
A x; // the shared object in class A
} s =
{ &s.x, 0, // the B object shares a pointer ...
&s.x, 0, // with the C object to the A base object
0, // the d
{ 0, 0 } // initialise A’s fields to zero.
};
I.e. there is a single A object (stored as ‘x’ above) and both the p field of the logical B object
(containing p and b) and the q field of the logical C object (containing q and c) point to it.
This is necessary so that a D object can be passed to routines which expect a B or a C object—but
note that is causes declarations like B x to be of 16 bytes: 8 for the A, 4 for the indirect pointer
(after all, routines need to be compiled which access the elements of a B not knowing whether is
it a ‘true’ B or actually a D).
Such arguments are one reason why Java omits multiple inheritance. Its interface facility
provides somewhat similar facilities, but components of the interface must be freshly implemented,
rather than being inherited from a parent.
within an array”.
64
hold non-pointer data, then it is possible to move (contiguify, improving both cache and virtual
memory performance) used data so that after garbage collection the unused data forms a single
block of store which can be allocated sequentially. The moving process can be achieved by com-
paction (squeezing in the same space, like a disc de-fragmenter), or by copying from an old heap
into a new heap (the rôles of these are reversed in the next garbage collection). This latter process
is called a two-space garbage collector and generally works better than a conservative collector
with respect to cache and virtual memory.
There are many exotic types of garbage collectors, including generational garbage collectors
(exploiting the fact that allocated data tends to be quite short-lived or last for a significant time)
and concurrent garbage collectors (these run in a separate thread, preferably using a separate
CPU and are a significantly challenge to program, especially if minimising time wasted on locking
concurrently accessed date is an issue).
float x;
double d;
int i;
1. It helps the compiler to allocate space efficiently, (ints take less space than doubles).
2. It allows for overloading. That is the ability to use the same symbol (e.g. +) to mean different
things depending on the types of the operands. For instance, i+i performs integer addition
while d+d is a double operation.
4. Automatic type checking is possible. This improves error diagnostics and, in many cases,
helps the compiler to generate programs that are incapable of losing control. For example,
goto L will compile into a legal jump provided L is of type label. Nonsensical jumps such
as goto 42 cannot escape the check. Similar considerations apply to procedure calls.
Overloading, automatic type conversions and type checking are all available to a language with
dynamic types but such operations must be handled at runtime and this is likely to have a drastic
effect on runtime efficiency. A second inherent inefficiency of such languages is caused by not
knowing at compile time how much space is required to represent the value of an expression. This
leads to an implementation where most values are represented by pointers to where the actual
65
value is stored. This mechanism is costly both because of the extra indirection and the need for a
garbage collecting space allocation package. In implementation of this kind of language the type
of a value is often packed in with the pointer.
One advantage of dynamic typing over static typing is that it is easy to write functions which
take a list of any type of values and applies a given function to it (usually called the map function).
Many statically typed languages render this impossible (one can see problems might arise if lists of
(say) characters were stored differently from lists of integers). Some languages (most notably ML)
have polymorphic types which are static types37 but which retain some flexibility expressed as
parameterisation. For example the above map function has ML type
(α -> β) -> (α list) -> (β list)
If one wishes to emphasise that a statically typed system is not polymorphic one sometimes says
it is a monomorphic type system.
Polymorphic type systems often allow for type inference, often called nowadays type recon-
struction in which types can be omitted by the user and reconstructed by the system. Note that
in a monomorphic type system, there is no problem in reconstructing the type of λx. x+1 nor
λx. x ? false:true but the simpler λx. x causes problems, since a wrong ‘guess’ by the type
reconstructor may cause later parts of code to fail to type-check.
We observe that overloading and polymorphism do not always fit well together: consider writing
in ML λx. x+x. The + function has both type
(int * int -> int) and (real * real -> real)
so it is not immediately obvious how to reconstruct the type for this expression (ML rejects it).
Finally, sometimes languages are described as typeless. BCPL (a forerunner of C) is an exam-
ple. The idea here is that we have a single data type, the word (e.g. 32-bit bit-pattern), within
which all values are represented, be they integers, pointers or function entry points. Each value
is treated as required by the operator which is applied to it. E.g. in f(x+1,y[z]) we treat
the values in f, x, y, z as function entry point, integer, pointer to array of words, and integer
respectively. Although such languages are not common today, one can see them as being in the
intersection of dynamically and statically type languages. Moreover, they are often effectively
used as intermediate languages for typed languages whose type information has been removed by
a previous pass (e.g. in intermediate code in a C compiler there is often no difference between a
pointer and an integer, whereas there is a fundamental difference in C itself).
values will still need to have type-determining tags (like dynamic typing above) to allow garbage collection.
66
11 Compilation Revisited and Debugging
11.1 Correctness
These notes have just presented compilation as a program which takes source code and produces
target code justified by “it looks plausible and the lecturer says it’s OK”. But for more complicated
languages, and more sophisticated translation techniques, we can be left thinking “I wonder if
that trick works when features X and Y interact. . . ”. A nice example is static members in generic
classes: when given
class List<Elt>
{ List <Elt> Cons(Elt x) { number_of_conses++; ... }
static int number_of_conses = 0;
}
then should there be one counter for each Elt type, or just one counter of all conses? Entertain-
ingly the languages Java and C♯ differ on this. So writing a correct compiler demands complete
understanding of source and target languages.
Semantics courses provide a proper formal answer to the question of compiler correctness.
Suppose S, T are source and target languages of a compiler f . For simplicity we assume f is a
mathematical function f : S → T (in practice f is implemented by a compiler program C written
in an implementation language L, but in order to avoid worrying recursively about whether the
implementation of L is correct and whether C terminates, we will just think of f as a function).
Now we need semantics of S and T (semantics are just precise language specifications which
of course include explanation of whether things like number_of_conses are one-per-system or
one-per-class). Let’s write these semantics as [[ · ]]S : S → M and [[ · ]]T : T → M for some set of
meanings M . To avoid nasty issues we will assume the semantics give the “final value”, or output,
of a program (of course we expect internal behaviour of evaluation of terms in S and T to differ)
and moreover M is something simple like an integer or string (to facilitate comparison).
We can now say that f is a correct compiler provided that
There are two subtleties. One concerns non-determinism: if S has non-deterministic features (like
races), then is it acceptable for a compiler to reduce this (making a run-time choice at compile
time)? This course has only considered deterministic languages, so we leave this issue to others.
A second is termination: either we need to see [[ · ]]S and [[ · ]]T as partial functions (and equality
to be “both yield the same value or both are undefined”), or we need to introduce a distinguished
element ⊥ to the set M which explicitly represents non-termination (and let equality be the natural
operation on this larger set). The semantics courses here explore some of these issues more.
A semantics for L now turns a program in L into a function, in particular it now also has
L
type [[ · ]]L : (S T ) → (S → T ). We are now going to consider the machine code of our host
architecture as a language H and, by some extent abuse of concepts, regard [[ · ]]H as meaning
“execute a program in language H”.
67
H
Clearly the only practically useful compilers are of the form S H, since we need them to be
both executable and to produce executable code. But we can use composition to produce other
H H
compilers: we’ve already seen how a compiler S T can be composed with one T H to give
H
a usable compiler S H. But these ‘compilation types’ can also be ‘vertically’ composed: use a
H L H
L H compiler to compile a S H one to yield a usable compiler S H
One problem is that people typically write a compiler for a new language U in the language
itself (because it’s a great new perfect language!). Suppose they are kind enough to make it
U
generate H code, so we have a compiler U H, but we still have the so-called ‘bootstrapping
problem’ that until we have a compiler or other execution mechanism for U we have no composition
H
to make the compiler useful (i.e. of the form U H). The trick is to somehow make some sort
H U
of prototype compiler of the form U H and then use that to compile the U H compiler to
H
produce (hopefully a better) compiler U H. This bootstrapping processes can be repeated.
But, one might ask various interesting questions, such as: do the sequence compilers eventually
become equal? Can the original prototype compiler leave some form of footprint? In particular,
U
if the U H compiler is correct, does that mean that the bootstrapped compiler is correct?
The latter question is answered in the negative, and has entertaining security implications. It
is possible to write a compiler which miscompiles one piece of code (e.g. the login program) but
which correctly compiles every other piece of code apart from itself, because it compiles this to a
compiler which miscompiles the login program and itself. Moreover this compiler is correct when
U
seen as a program U H (it compiles the login program correctly) but (of course) incorrect as is
H
the program in U H resulting from bootstrapping. So the security attack cannot be discovered
by source code inspection. See http://cm.bell-labs.com/who/ken/trust.html for details (the
1984 Turing Award classic by Ken Thompson).
iload 3
we execute
iload(3);
where the procedure iload() merely performs the code that the interpreter would have performed.
Similarly, does parsing our simple expression language into trees before interpreting them cause
us to have a compiler, and should we reserve the word ‘interpreter’ for a system which interprets
text (like some BASIC systems)?
So, we conclude there is no line-in-the-sand difference between a compiled system and and an
interpreted system. Instead there is a spectrum whose essential variable is how much work is done
statically (i.e. before input data is available and execution starts) and how much is done during
execution.
68
In typical implementations of Python and PHP, and in our simple lambda evaluator earlier in
the notes, we do assume that the program-reading phase has arranged the expression as a tree and
faulted any mismatched brackets etc. However, we still arrange to search for names (see lookup)
and check type information (see the code for e1 + e2 ) at run-time.
Designing a language (e.g. its type system) so that as much work as possible can be done before
execution starts clearly helps one to build efficient implementations by allowing the compiler to
generate good code.
11.4 Debugging
One aspect of debugging is to allow the user to set a ‘breakpoint’ to stop execution when control
reaches a particular point. This is often achieved by replacing the instruction at the breakpointed
instruction with a special trap opcode.
Often extra information is stored the ELF object file and/or in a stack frame to allow for
improved runtime diagnostics. Similarly, in many languages it is possible to address all variables
with respect to SP and not use a FP register at all; however then giving a ‘back-trace’ of currently
active procedures at a debugger breakpoint can be difficult.
The design of debuggers involves a difficult compromise between space efficiency, execution
efficiency and the effectiveness of the debugging aids. The unix utility strip and and the gcc
option -g and -fomit-frame-pointer reflect this. Exercise 8: Find out why.
12.1 Lex
Lex takes as input a file (e.g. calc.l) specifying the syntax of the lexical tokens to be recognised
and it outputs a C program (normally lex.yy.c) to perform the recognition. The syntax of each
token is specified by means of a regular expression and the corresponding action when that token
is found is supplied as a fragment of C program that is incorporated into the resulting lexical
analyser. Consider the lex program calc.l in Figure 4. The regular expressions obey the usual
Unix conventions allowing, for instance, [0-9] to match any digit, the character + to denote
repetition of one or more times, and dot (.) to match any character other than newline. Next to
each regular expression is the fragment of C program for the specified token. This may use some
predefined variables and constants such as yylval, yytext and NUMBER. yytext is a character
vector that holds the characters of the current token (its length is held in yyleng). The fragment
69
%%
[ \t] /* ignore blanks and tabs */ ;
Figure 4: calc.l
of code is placed in the body of a synthesised function called lex, and thus a return statement
will cause a return from this function with a specified value. Certain tokens such as NUMBER return
auxiliary information in suitably declared variables. For example, the converted value of a NUMBER
is passed in the variable lexlval. If a code fragment does not explicitly return from lex then
after processing the current token the lexical analyser will start searching for the next token.
In more detail, a Lex program consists of three parts separated by %%s.
declarations
%%
translation rules
%%
auxiliary C code
The declarations allows a fragment of C program to be placed near the start of the resulting lexical
analyser. This is a convenient place to declare constants and variables used by the lexical analyser.
One may also make regular expression definitions in this section, for instance:
ws [ \t\n]+
letter [A-Za-z]
digit [0-9]
id {letter}({letter}|{digit})*
These named regular expressions may be used by enclosing them in braces ({ or }) in later
definitions or in the translation rules.
The translation rules are as above and the auxiliary C code is just treated as a text to be
copied into the resulting lexical analyser.
12.2 Yacc
Yacc (yet another compiler compiler) is like Lex in that it takes an input file (e.g. calc.y) speci-
fying the syntax and translation rule of a language and it output a C program (usually y.tab.c)
to perform the syntax analysis.
Like Lex, a Yacc program has three parts separated by %%s.
declarations
%%
translation rules
%%
auxiliary C code
Within the declaration one can specify fragments of C code (enclosed within special brackets %{
and %}) that will be incorporated near the beginning of the resulting syntax analyser. One may
also declare token names and the precedence and associativity of operators in the declaration
section by means of statements such as:
70
%token NUMBER
%left ’*’ DIV MOD
The translation rules consist of BNF-like productions that include fragments of C code for
execution when the production is invoked during syntax analysis. This C code is enclosed in
braces ({ and }) and may contain special symbols such as $$, $1 and $2 that provide a convenient
means of accessing the result of translating the terms on the right hand side of the corresponding
production.
The auxiliary C code section of a Yacc program is just treated as text to be included at the
end of the resulting syntax analyser. It could for instance be used to define the main program.
An example of a Yacc program (that makes use of the result of Lex applied to calc.l) is
calc.y listed in Figure 5.
Yacc parses using the LALR(1) technique. It has the interesting and convenient feature that
the grammar is allowed to be ambiguous resulting in numerous shift-reduce and reduce-reduce
conflicts that are resolved by means of the precedence and associativity declarations provided by
the user. This allows the grammar to be given using fewer syntactic categories with the result
that it is in general more readable.
The above example uses Lex and Yacc to construct a simple interactive calculator; the trans-
lation of each expression construct is just the integer result of evaluating the expression. Note
that in one sense it is not typical in that it does not construct a parse tree—instead the value of
the input expression is evaluated as the expression is parsed. The first two productions for ‘expr’
would more typically look like:
where mkbinop() is a C function which takes two parse trees for operands and makes a new one
representing the addition of those operands.
13 Phrase-structured grammars
The concept of the phrase-structured grammar was formalised by Chomsky.
We start with an alphabet, Σ, of symbols (think of these as input characters to lexing or tokens
resulting from lexing that are input to the syntax analyser). A string over this alphabet is just a
finite sequence σ1 · · · σn of symbols from Σ. A language is then merely a defined set of such strings.
(Using the ‘star’ notation from regular expressions earlier, we can hence say that a language L
over an alphabet Σ is a defined subset of Σ∗ , i.e. L ⊆ Σ∗ .
To make the definition we need a rule (or rules) that defines those strings in the language. For
a rather boring language, consider the alphabet to be set of all letters {a ... z} and the rule to
be “all strings of length three” then we would have the language whose strings are:
Note that this is a finite language, but some languages may be infinite (e.g. “all strings of even
length”). Such informal rules (specified by English) are not terribly useful to Computer Science
(e.g. think of the rule “all valid Java programs”), so we turn to grammars.
Informally a grammar (more precisely a phrase structured grammar) has additional symbols
(non-terminals) which are not part of the language we wish to describe. The ‘rule’ for determining
which strings are part of the language is then a two-part process: strings containing such non-
terminals can be re-written to other strings (perhaps also containing other non-terminals) using
production rules; strings containing no non-terminal symbols are considered part of the language.
A grammar can then be defined to be a 4-tuple (T, N, S, R) where T and N are disjoint sets of
respectively terminal and non-terminal symbols, S ∈ N is the start (or sentence) symbol, and R
71
%{
#include <stdio.h>
%}
%token NUMBER
%%
comm: comm ’\n’
| /* empty */
| comm expr ’\n’ { printf("%d\n", $2); }
| comm error ’\n’ { yyerrok; printf("Try again\n"); }
;
%%
#include "lex.yy.c"
yyerror(s)
char *s;
{ printf("%s\n", s);
}
main()
{ return yyparse();
}
Figure 5: calc.y
72
is a set of productions. T performs the rôle of Σ above, but now it is convenient to use the word
‘symbol’ to mean any symbol in T ∪ N . The most general form of a production is:
A1 A2 · · · Am −→ B1 B2 · · · Bn
where the Ai and Bi are symbols and A1 A2 · · · Am contains at least one non-terminal.
The above rule specifies that if A1 A2 · · · Am occurs in a string generated by the grammar then
the string formed by replacing A1 A2 · · · Am by B1 B2 · · · Bn is also generated by the grammar
(note that the symbol ‘::=’ is sometimes used as an alternative to ‘−→’). The string consisting of
just the start symbol S is defined to be trivially generated by the grammar. Any string that can
be formed by the application of productions to S is called a sentential form. A sentential form
containing no non-terminals is called a sentence. The language generated by a grammar is the set
of sentences it generates. The problem of syntax analysis is to discover which series of applications
of productions that will convert the sentence symbol into the given sentence.
It is important not to confuse T and N . Elements of T occur in programs, in examples terminal
symbols may be a, b, c as in the length-3 string example above and occur in input text. Non-
terminals like Term or Declaration do not occur in input text but instead are place holders for
other sequences of symbols.
It is useful to impose certain restrictions on A1 A2 · · · Am and B1 B2 · · · Bn and this has been
done by Chomsky to form four different types of grammar. The most important of these is the
Chomsky Type 2 grammar (commonly known as a context-free grammar for reasons which will
become clear below).
S −→ A B
A −→ a
A −→ A B b
B −→ b c
B −→ B a
S −→ A B
A −→ a | A B b
B −→ b c | B a
The alphabet for this grammar is {S, A, B, a, b, c, d}. The non-terminals are S, A, B being
the symbols occurring on the left-hand-side of productions, with S being identified as the start
symbol. The terminal symbols are a, b, c, d, these being the characters that only appear on
the right hand side. Sentences that this grammar generates include, for instance:
abc
abcbbc
abcbca
abcbbcaabca
Where the last sentence, for instance, is generated from the sentence symbol by means of the
following productions:
73
S
|
A---------------B
| |
A-------B-----b B---a
| | | | |
A-B---b B---a | b-c |
| | | | | | | | |
a b-c | b-c | | | | |
| | | | | | | | | | |
a b c b b c a b b c a
For completeness, the other grammars in the Chomsky classification are as follows.
74
As a final remark on type 0 grammars, it should be clear that one can write a grammar
which essentially specifies the behaviour of a Turing machine, and syntax analysis in this case is
equivalent to deciding whether a given string is the answer to some program. This is undecidable
and syntax analysis of type 0 grammars is thus, in general, undecidable.
U −→ a
U −→ a V
That is, the right hand side must consist of a single terminal symbol possibly followed by a single
non-terminal.
Type 3 grammars can clearly be parsed using a finite state recogniser, and for this reason
they are often called regular grammars. [To get precise correspondence to regular languages it
is necessary also to allow the empty production S −→ǫ otherwise the regular language consist-
ing of the empty string (accepted by an automaton whose initial state is accepting, but any
non-empty input sequence causes it to move to a non-accepting state) cannot be represented
as a type 3 grammar; more information on topics like this can be found on Wikipedia, e.g.
http://en.wikipedia.org/wiki/Regular_grammar
S −→ a
S −→ S a
S −→ a
S −→ a S
clearly generates the same set of strings (is equivalent to G) and is Type 3.
75
14 How parser generators work
As mentioned earlier, given a relatively large grammar, it is more convenient to supply the grammar
to a tool (a ‘parser generator’) and allow it to generate a parser rather than hand-writing a
parser. Such tools tend not to generate a parser in code form; rather they derive a table from
the grammar and attach a fixed table-driven parsing algorithm to it. Parser generators do not
accept an arbitrary context-free grammar, but instead accept a restricted form, of which the most
common form for practical tools (e.g. yacc, mlyacc, CUP) is the LALR(1) grammar (although
antlr uses LL(k) parsing).
Rather than explain how a LALR(1) parser generator works, I will explain so-called SLR(k)
parsers work; these use the the same underlying parsing algorithm, but generate less compact (but
easier to understand) tables.
The basic idea is that the currently-consumed input could potentially be parsed in various
ways and we keep all feasible possibilities alive using a non-deterministic automaton. However, we
convert the NDA to a deterministic one at compile time (inside the yacc tool or whatever) (using
the subset construction) so we only need to run the deterministic machine at run time.
To exemplify this style of syntax analysis, consider the following grammar (here E, T, P ab-
breviate ‘expression’, ‘term’ and ‘primary’—an alternative notation would use names like <expr>,
<term> and <primary> instead):
#0 S −→ E eof
#1 E −→ E + T
#2 E −→ T
#3 T −→ P ** T
#4 T −→ P
#5 P −→ i
#6 P −→ ( E )
The form of production #0 is important. It defines the sentence symbol S and its RHS consists of
a single non-terminal followed by the special terminal symbol eof which must not occur anywhere
else in the grammar. (When you revisit this issue you will note that this ensures the value parsed
is an E and what would be a reduce transition using rule #0 is used for the acc accept marker.)
We first construct what is called the characteristic finite state machine or CFSM for the
grammar. Each state in the CFSM corresponds to a different set of items where an item consists
of a production together with a position marker (represented by .) marking some position on the
right hand side. Items are also commonly known as configurations. There are, for instance, four
possible items involving production #1, as follows:
E −→ .E + T
E −→ E .+ T
E −→ E + .T
E −→ E + T .
If the marker in an item is at the beginning of the right hand side then the item is called an
initial item. If it is at the right hand end then the item is called a completed item. In forming item
sets a closure operation must be performed to ensure that whenever the marker in an item of a set
precedes a non-terminal, E say, then initial items must be included in the set for all productions
with E on the left hand side.
The first item set is formed by taking the initial item for the production defining the sentence
symbol (S −→.E eof ) and then performing the closure operation, giving the item set:
1: { S −→ .E eof
E −→ .E + T
E −→ .T
T −→ .P ** T
T −→ .P
76
P −→ .i
P −→ .( E )
}
States have successor states formed by advancing the marker over the symbol it precedes. For
state 1 there are successor states reached by advancing the marker over the symbols ‘E’, ‘T’, ‘P’, ‘i’
or ‘(’. Consider, first, the E successor (state 2), it contains two items derived from state 1 and the
closure operation adds no more (since neither marker precedes a non terminal). State 2 is thus:
2: { S −→ E . eof
E −→ E .+ T
}
The other successor states are defined similarly, except that the successor of eof is always the
special state accept. If a new item set is identical to an already existing set then the existing set
is used. The successor of a completed item is a special state represented by $ and the transition
is labelled by the production number (#i) of the production involved. The process of forming the
complete collection of item sets continues until all successors of all item sets have been formed.
This necessarily terminates because there are only a finite number of different item sets.
For the example grammar the complete collection of item sets given in Figure 6. Note that for
completed items the successor state is reached via the application of a production (whose number
is given in the diagram).
The CFSM can be represented diagrammatically as follows:
E eof
1 2 accept
T #2 + T #1
5 $ 3 4 $
P #4
6 $
**
T #3
7 8 $
i #5
9 $
( E ) #6
10 11 12 $
1. If there is a transition from state i to state j under the terminal symbol k, then set
action[i, k] to Sj.
2. If there is a transition under a non-terminal symbol A, say, from state i to state j, set
goto[i, A] to Sj.
4. If there is a reduce transition #p from state i, set action[i, k] to #p for all terminals k.
77
1: { S -> .E eof \
E -> .E + T / E => 2
E -> .T T => 5
T -> .P ** T \
T -> .P / P => 6
P -> .i i => 9
P -> .( E ) ( => 10
}
2: { S -> E .eof eof => accept
E -> E .+ T + => 3
}
3: { E -> E + .T T => 4
T -> .P ** T \
T -> .P / P => 6
P -> .i i => 9
P -> .( E ) ( => 10
}
4: { E -> E + T . #1 => $
}
5: { E -> T . #2 => $
}
6: { T -> P .** T ** => 7
T -> P . #4 => $
}
7: { T -> P ** .T T => 8
T -> .P ** T \
T -> .P / P => 6
P -> .i i => 9
P -> .( E ) ( => 10
}
8: { T -> P ** T . #3 => $
}
9: { P -> i . #5 => $
}
10:{ P -> ( .E ) \
E -> .E + T / E => 11
E -> .T T => 5
T -> .P ** T \
T -> .P / P => 6
P -> .i i => 9
P -> .( E ) ( => 10
}
11:{ P -> ( E .) ) => 12
E -> E .+ T + => 3
}
12:{ P -> ( E ) . #6 => $
}
78
action goto
state eof ( i ) + ** P T E
S1 - S10 S9 - - - S6 S5 S2
S2 acc - - - S3 - - - -
S3 - S10 S9 - - - S6 S4 -
S4 #1 #1 #1 #1 #1 #1 - - -
S5 #2 #2 #2 #2 #2 #2 - - -
S6 #4 #4 #4 #4 #4 XXX - - -
S7 - S10 S9 - - - S6 S8 -
S8 #3 #3 #3 #3 #3 #3 - - -
S9 #5 #5 #5 #5 #5 #5 - - -
S10 - S10 S9 - - - S6 S5 S11
S11 - - - S12 S3 - - - -
S12 #6 #6 #6 #6 #6 #6 - - -
and so therefore is not SLR(0)—because (state S6, symbol ‘∗∗’) is marked ‘XXX’ to indicate that
it admits both a shift transition (S7) and a reduce transition (#4) for the terminal ∗∗. In general
right associative operators do not give SLR(0) grammars.
The key idea is to determine whether to shift or reduce according to the next terminal in the
input stream—i.e. to use a 1-token lookahead to determine whether it is appropriate to perform
reduce transition. This leads to the idea of an SLR(1) grammar to which we now turn.
3. For each production U −→ B1 · · · Bn where B1 is also a non-terminal enter all the elements
of Left(B1 ) into Left(U )
The sets FOLLOW(U ) can now be formed using the following rules.38
in any production) case 2 of this construction is never exercised—thanks to Tom Stuart for pointing this out. A
production such as U −→ xV W y with x and y terminals and U , V and W non-terminals would exercise this case.
79
2. If, moreover, B is a non-terminal then also put all symbols in Left(B) into FOLLOW(V ).
3. If there is a production of the form U −→ · · · V put all symbols in FOLLOW(U ) into FOLLOW(V ).
We are assuming here that no production in the grammar has an empty right hand side. For our
example grammar, the FOLLOW sets are as follows:
U FOLLOW(U )
E eof + )
T eof + )
P eof + ) **
The action and goto matrices are formed from the CFSM as in the SLR(0) case, but with
rule 4 modified:
4’ If there is a reduce transition #p from state i, set action[i, k] to #p for all terminals k
belonging to FOLLOW(U ) where U is the subject of production #p.
If any entry is multiply defined then the grammar is not SLR(1). Blank entries are represented
by dash (-).
action goto
state eof ( i ) + ** P T E
S1 - S10 S9 - - - S6 S5 S2
S2 acc - - - S3 - - - -
S3 - S10 S9 - - - S6 S4 -
S4 #1 - - #1 #1 - - - -
S5 #2 - - #2 #2 - - - -
S6 #4 - - #4 #4 S7 - - -
S7 - S10 S9 - - - S6 S8 -
S8 #3 - - #3 #3 - - - -
S9 #5 - - #5 #5 #5 - - -
S10 - S10 S9 - - - S6 S5 S11
S11 - - - S12 S3 - - - -
S12 #6 - - #6 #6 #6 - - -
Here a ... f are state numbers, A ... E are grammar symbols (either terminal or non-terminal)
and u ... z are the terminal symbols of the text still to be parsed. If the original text was
syntactically correct, then
A B C D E u v w x y z
will be a sentential form.
The parsing algorithm starts in state S1 with the whole program, i.e. configuration
1 | hthe whole program upto eof i
and then repeatedly applies the following rules until either a syntactic error is found or the parse
is complete.
39 The stack can also be coded as a stack of pairs with minor changes. This is more amenable to modern,
strongly-typed languages. The pairs are instead triples when a parse tree is being generated, which is the normal
case.
80
1. If action[f, u] = Si, then transform
a A b B c C d D e E f | u v w x y z eof
to
a A b B c C d D e E f u i | v w x y z eof
a A b B c C d D e E f | u v w x y z eof
will transform to
a A b B c P g | u v w x y z eof
Notice that the symbols in the stack corresponding to the right hand side of the production
have been replaced by the subject of the production and a new state chosen using the goto
table. This is called a reduce transition.
3. If action[f, u] = acc then the situation will be as follows:
a Q f | eof
and the parse will be complete. (Here Q will necessarily be the single non-terminal in the
start symbol production (#0) and u will be the symbol eof .)
4. If action[f, u] = - then the text being parsed is syntactically incorrect.
Note again that there is a single program for all grammars; the grammar is coded in the action
and goto matrices.
As an example, the following steps are used in the parsing of i+i:
Stack text production to use
1 i + i eof
1 i 9 + i eof P −→ i
1 P 6 + i eof T −→ P
1 T 5 + i eof E −→ T
1 E 2 + i eof
1 E 2 + 3 i eof
1 E 2 + 3 i 9 eof P −→ i
1 E 2 + 3 P 6 eof T −→ P
1 E 2 + 3 T 4 eof E −→ E + T
1 E 2 eof acc (E is result)
In practice a tree will be produced and stored attached to terminals and non-terminals on the
stack. Thus the final E will in reality be a pair of values: the non-terminal E along with a tree
representing i+i.
Note that the above parse is an LR-parse: look at the productions used (backwards, starting
at the bottom of the page since we are parsing, not deriving strings from the start symbol).
We see
E −→ E+T −→ E+P −→ E+i −→ T+i −→ P+i −→ i+i
i.e. a rightmost derivation.
81
14.4 Errors
A syntactic error is detected by encountering a blank entry in the action or goto tables. If this
happens the parser can recover by systematically inserting, deleting or replacing symbols near the
current point in the source text, and choosing the modification that yields the most satisfactory
recovery. A suitable error message can then be generated.
[The end]
82