Structs with Methods
Sum and product types used tuples as products: a value of type (Int, Int)
holds two integers, read back by position as .0 and .1. The program below uses that type for
two different things. A point corner is a position, with its x-coordinate first and its
y-coordinate second. A size is the width and height of a rectangle, in that order. area
multiplies the components of a size, is_tall reports whether a size is taller than it is wide,
and move_by shifts a point by an offset:
fn area(r: (Int, Int)) -> Int = r.0 * r.1;
fn is_tall(r: (Int, Int)) -> Bool = r.0 > r.1;
fn move_by(p: (Int, Int), d: (Int, Int)) -> (Int, Int) =
(p.0 + d.0, p.1 + d.1);
fn main() {
let corner = (2, 5);
let size = (3, 4);
println(area(size));
println(is_tall(size));
println(area(corner));
println(move_by(corner, size));
}
The type checker accepts the program, and it prints:
12
false
10
(5, 9)
A 3-by-4 rectangle is taller than it is wide, yet is_tall reports false, because its author
read the first component as the height. The third line is the area of a point, which has no
meaning, and the fourth moves a point by a size. Each of these is a well-typed use of a pair of
integers.
The program raises these questions:
- How does a type tell a point from a size? Both are two integers.
- How does a program say which component is which?
r.0is a width inareaand a height inis_tall, and only the author of each function knows which. - Where do the operations on a type live?
areabelongs with sizes andmove_bywith points, but both are top-level functions over(Int, Int). - How does an operation refer to the value it works on? Each function takes that value as an ordinary parameter, under whatever name its author chose.
Records, and the classes that grew from them
Tony Hoare’s “Record Handling”, published in the ALGOL Bulletin in November 1965, proposed adding records to ALGOL 60. A program would declare record classes, each listing named fields, and every record would belong to exactly one class: “It is obvious that no object can be both a cow and a table, so it is quite natural to insist that every record shall belong to one and only one class.” The class decides which questions make sense to ask of a record, and Hoare called it “absurd to ask the wrong questions about an object of a given class”, such as the number of rooms in a table. He also observed that the order of the fields carries no information: “Note that the sequence in which the fields are declared is not significant, and that exactly the same effect is achieved by declaring them in a different sequence.”
Hoare wrote field access as a function applied to a reference, age(B) or age(father(B)). In a
section of extensions he suggested that a procedure could also be declared among the fields, to
compute a value from the other fields instead of storing it: “If this procedure were parameterless,
its use as a function designator would have the same appearance as a field designator.” With
procedure fields and initial values added, he found that a record class declaration “has exactly
the same form and effect as a (function) procedure declaration, except that it delivers as its value
not a simple quantity, but a reference to the record consisting of the values of all its local
quantities at the time of exit from the procedure.”
Ole-Johan Dahl and Kristen Nygaard were building Simula in Oslo at the same time. A Simula I
simulation of road traffic declared a Car with variables for its position and speed together with
procedures that read and changed them. Dahl’s later account, “The Birth of Object Orientation: the
Simula Languages”, says of that example: “The example
shows that the idea of data objects with associated operators was under way already in 1965.” For
Simula 67 they adopted the words class and object, credited Hoare’s record classes as an
influence, and wrote attribute access with a dot. A Simula 67 class is a record whose declaration
also contains procedures, much as Hoare’s extensions had sketched. Traits vs.
inheritance covers Simula’s subclasses, and Dispatch and
encapsulation covers Smalltalk’s view of a method call as a message sent to an object.
Named products
A record type is a product whose components are identified by name. A tuple type indexes its components by position, while a record type indexes them by the labels and . Counting values works as it does for tuples, since a record chooses one value for each field independently:
With labels, the components form a set of labelled entries instead of a sequence, so
and describe the same values, as Hoare observed. Each
label also gives a function from the record type to the field’s type: in the record above,
selects a component of type and one of type . Hoare’s notation age(B) writes field
access as exactly that function.
A record type still describes the shape of its values, and two record types with the same labels and field types have the same values. A language that gives each record type a name and treats two names as different types, even when their shapes agree, can tell a point from a size. That is the choice Hoare’s record classes made, and the one Bridger makes.
Bridger’s structs
Declaring a struct
A struct declaration names a product and each of its fields. The grammar is in Appendix
B:
struct_def ::= 'struct' UpperIdent [ generics ]
'{' [ field { ',' field } [','] ] '}' ;
field ::= ident ':' type ;
Here is the opening program with a struct for each kind of pair:
struct Point { x: Int, y: Int }
struct Size { w: Int, h: Int }
fn area(s: Size) -> Int = s.w * s.h;
fn is_tall(s: Size) -> Bool = s.h > s.w;
fn main() {
let corner = Point { x: 2, y: 5 };
let size = Size { w: 3, h: 4 };
println(size);
println(area(size));
println(is_tall(size));
}
It prints:
Size { w: 3, h: 4 }
12
true
A struct literal such as Size { w: 3, h: 4 } builds a value by naming each field, and field
access s.w reads one back by name. is_tall now says which component it compares, and adding
println(area(corner)); to main makes the program fail to check:
type mismatch: expected Size, found Point
The same holds for move_by once its offset has a type of its own. With
struct Offset { dx: Int, dy: Int } and fn move_by(p: Point, d: Offset) -> Point, the call
move_by(corner, size) is rejected with type mismatch: expected Offset, found Size. The method
version later in this chapter takes the offset as two integers instead.
A struct’s name is a type, so Point and Size are different types although each holds two
integers. A struct value prints with its name and its fields, and two struct values are equal under
== when they have the same struct name and equal fields.
Evaluating a struct literal
A literal evaluates its field expressions in the order they are written, threading the store and the relation database as E-Con does. Write for the fields of in the order its declaration lists them. The literal’s field names must be those same names in some order: a permutation with for each . The value is then built in declaration order:
Size { h: 4, w: 3 } evaluates 4 before 3, and its value is Size { w: 3, h: 4 }, the same
value Size { w: 3, h: 4 } builds, so the two print alike and are equal under ==. A literal that
leaves out a declared field, names one twice, or names one the struct does not declare has no such
permutation. No rule applies, and evaluation is stuck.
Field access evaluates the struct and selects the named component:
A value without a field named , including every value that is not a struct, is stuck.
Checking structs
Writing for a struct whose field has type , the typing rules mirror the evaluation rules:
The permutation premise is the static form of E-Struct’s: every field of , each once. The checker reports each way of breaking the rules before the program runs:
Point { x: 1 } // struct literal is missing the field `y`
Point { x: 1, y: 2, x: 3 } // field `x` is given more than once
Point { x: 1, y: 2, z: 3 } // no such field `z`
Point { x: 1, y: true } // type mismatch: expected Int, found Bool
p.z // no such field `z`
p.0 // `.0` selects a component of a tuple, but
// this has type Point
T-Field needs the receiver’s type to be a struct before it can look up , so (1, 2).x is an
error as well. Field access and tuple projection share the dot, and the checker tells them apart by
what follows it: a name selects a field, and a number selects a tuple component.
A struct literal begins with a name and a brace, which is also how the head of an if, while,
for, or match ends. The parser reads that brace as the start of the trailing block, so a
literal at the top level of such a head goes in parentheses: if p == (Point { x: 1, y: 2 }) { … }.
Generic structs
A struct can take type parameters, as a type declaration can. A stack that holds values of any
one type is a list wrapped in a struct:
struct Stack<T> { items: [T] }
Stack { items: [2, 1] } has type Stack<Int>. As with a generic
constructor, the checker instantiates the declaration’s type
parameters with fresh inference variables at each literal, and the field expressions solve them.
For a generic declaration, the in T-Struct and the type of in T-Field come from the
declaration with each type parameter consistently replaced.
Taking structs apart
A struct pattern names the struct and some of its fields, and Pattern
matching already gave it its meaning: Size { w, h } binds both
fields, and a field the pattern leaves out matches anything. One arm can therefore test a struct’s
contents and bind its fields. Field access reads one field at a time, and a test on what it reads
needs an if.
Structs, tuples, and one-constructor types
Bridger has three ways to write a product of two integers. A tuple type (Int, Int) has no name,
and every pair of integers has that type. A type declaration with one constructor names a
product but not its components:
type Pt = P(Int, Int);
fn x_of(p: Pt) -> Int = match p { P(x, _) => x };
A Pt is distinct from every other type, yet its components have positions and no names, and the
only way to read one is a match. A constructor and a type share one namespace, so the constructor
needs a name of its own: type Pt = Pt(Int, Int); is rejected because Pt is already defined.
A struct names both the product and each component, and .x reads a component without a match.
The cost is length: Point { x: 2, y: 5 } is longer than P(2, 5), and every use of a field
spells its name. A struct also has exactly one shape, so a type with several alternatives needs a
type declaration. Each of its alternatives can hold a struct, as in
type Figure = Round(Disc) | Rect(Size); with a struct Disc alongside.
Methods
Impl blocks and self
A method is a function whose first parameter has the record’s type. Attaching it to the type
gives the function a place to be found, under the type’s name, and a fixed name for the record it
works on. An impl block does the attaching:
impl_def ::= 'impl' [ generics ] [ trait_ref 'for' ] type
'{' { method } '}' ;
method ::= 'fn' ident '(' [ 'self' [ ',' params ] | params ] ')'
[ '->' type ] fn_body ;
The trait_ref 'for' form belongs to Dispatch and encapsulation. An impl without
it is an inherent impl, which gives the type methods of its own. Here are the opening program’s
operations, each now attached to the type it works on:
struct Point { x: Int, y: Int }
struct Size { w: Int, h: Int }
impl Point {
fn origin() -> Point = Point { x: 0, y: 0 };
fn move_by(self, dx: Int, dy: Int) -> Point =
Point { x: self.x + dx, y: self.y + dy };
}
impl Size {
fn new(w: Int, h: Int) -> Size = Size { w: w, h: h };
fn area(self) -> Int = self.w * self.h;
fn grow(self, d: Int) -> Size = Size { w: self.w + d, h: self.h + d };
}
fn main() {
let p = Point.origin().move_by(2, 5);
let s = Size.new(3, 4).grow(1);
println(p);
println(s);
println(s.area());
}
This prints:
Point { x: 2, y: 5 }
Size { w: 4, h: 5 }
20
A method whose first parameter is self is called on a value with the dot: s.area() runs area
with self bound to s. self takes no annotation, because its type is the type the impl
extends. Inside an impl, Self also names that type, so fn new(w: Int, h: Int) -> Self would
declare the same signature. The receiver is otherwise an ordinary parameter. Recursion and
higher-order functions passed a function to itself under the name me
because self was reserved, and a method receives its value the same way, as an argument in the
first position.
A method’s name belongs to its type, so Size and Point can each have an area without a clash,
and a top-level fn area can coexist with both. A field and a method of the same type can even
share a name, since p.x reads a field and p.x() calls a method. After the dot, a name followed
by an argument list is always a method call. If a struct value op has a field f holding a
function, the call is written (op.f)(21), and op.f(21) is rejected because f names a field.
Associated functions
A method declared without self, like origin and new above, is an associated function. It
is called on the type’s name, Point.origin(), with no value of type Point involved. The
receiver in that call is the bare name Point, which evaluates to Value::Type, a value that
stands for the type. The constructor arm of Milestone M7 already produces
it: a name with no arguments that is a declared type or struct, or one of Int, Bool, and
String, evaluates to Value::Type.
The two kinds of method are not interchangeable:
Size.area() // `area` takes `self`; call it on a value of the type
s.new(1, 2) // `new` takes no `self`, so it is not called on a value
p.area() // no such method `area`
Associated functions give a type a conventional place for the functions that build its values. A generic struct uses them the same way:
impl<T> Stack<T> {
fn empty() -> Stack<T> = Stack { items: [] };
fn push(self, x: T) -> Stack<T> = Stack { items: x :: self.items };
fn top(self) -> Option<T> =
match self {
Stack { items: [] } => None,
Stack { items: h :: _ } => Some(h),
};
}
impl<T> Stack<T> gives every Stack<σ> these methods, with T standing for σ.
Stack.empty().push(1).push(2) prints as Stack { items: [2, 1] }, and its top() is
Some(2). A Stack<Int> then refuses push("three") with type mismatch: expected Int, found String, because the receiver’s type fixed T.
Checking a method call
When the receiver’s type is known, the checker finds the method in that type’s impl and checks the
call against the method’s signature:
Self in the signature stands for , and for a generic impl the type parameters are
instantiated from . An associated call T.m(…) types the same way, with T freshly
instantiated as and a method declared without self. The checker uses the static type
to choose the signature the call is checked against. Dispatch and
encapsulation shows how the evaluator finds the same method at run time, and what
happens when several types provide a method of one name.
What a method body sees
A method body runs in the program’s top-level environment, extended with self and the method’s
parameters. In this program outer reads the global border:
struct Size { w: Int, h: Int }
let border = 1;
impl Size {
fn outer(self) -> Size =
Size { w: self.w + 2 * border, h: self.h + 2 * border };
}
fn main() {
let border = 10;
println(Size { w: 3, h: 4 }.outer());
}
It prints Size { w: 5, h: 6 }. The border local to main is not visible to the method, which
behaves as a top-level fn does under static scope. An impl appears only
at the top level, so its methods have no enclosing local scope to capture, and in that respect a
method is closer to a top-level function than to a closure. A method reaches other values only
through self, its parameters, and the top-level names.
Fields cannot be assigned
Bridger has no assignment to a field: p.x := 5 is a type error, since := writes through a
reference and p.x is an Int. A method that “changes” a struct, like move_by, returns a new
one. A struct that needs a field to change holds a reference in it:
struct Counter { hits: ref<Int> }
impl Counter {
fn new() -> Counter = Counter { hits: ref(0) };
fn tick(self) { self.hits := deref self.hits + 1; }
}
fn main() {
let a = Counter.new();
let b = a;
a.tick();
b.tick();
println(deref a.hits);
}
This prints 2. let b = a copies the struct, and the copy holds the same location, so a tick
through either one is visible through both.
Building it
The parser delivers the declarations in the shapes given in The abstract syntax tree:
Struct(Generics, Vec<Field>), // struct S<T> { f: T, … }
struct Field { name: Name, ty: Ty, span: Span } // f: T
struct Impl {
generics: Generics, // impl<T> …
trait_: Option<TraitRef>, // the trait implemented, if any
ty: Ty, // the type being extended
methods: Vec<Method>,
span: Span,
head: Span, // the header, `impl<T> Tr for T`
}
struct Method { // a Sig with a body
name: Name,
has_self: bool,
params: Vec<Param>,
ret: Ty,
body: Expr,
span: Span,
sig: Span, // the signature alone, `fn m(self, x: Int) -> T`
}
The three expression forms are:
Struct(Name, Vec<(Name, Expr)>, Span), // struct literal: S { f: e, … }
Field(Box<Expr>, Name, Span), // struct field access: e.f
Method(Box<Expr>, Name, Vec<Expr>, Span), // a method call: e.m(e, …)
and Values and runtime errors already listed the two values this chapter uses:
Struct(Name, Rc<[(Name, Value)]>), // a struct value: S { f = v, … }
Type(Name), // a type name, receiver of `T.m()` (Part IX)
An associated call needs no expression form of its own. The M7 constructor arm already turns the
Point of Point.origin() into a Value::Type, so the call reaches the same Method arm as
s.area(), with its receiver evaluated.
The evaluator’s Struct arm follows E-Struct. It evaluates the field expressions in source order,
finds the struct’s declaration among the program’s declarations, and arranges the values in the
declaration’s field order, so that two literals naming the same fields in different orders build
equal values. Because the evaluator can also run unchecked programs, it reports a field named
twice (DuplicateField), a declared field the literal omits (MissingField), a field the
declaration lacks (NoSuchField), and a name that is not a struct (NotAStruct). The Field arm
evaluates the receiver and returns the named field, or reports NoSuchField when the value has no
such field or is not a struct at all.
The checker’s Struct arm looks up the declaration, makes fresh inference variables for its type
parameters, and checks each field expression against the declared field type, reporting the same
errors by the names Appendix D gives
them. Its Field arm synthesizes the receiver’s type, which must resolve to a struct
(FieldOfNonStruct otherwise), and returns the field’s type with the struct’s type arguments
substituted. Dispatch and encapsulation covers the Method arms of both, which find
the method a call runs.
The design space
Where methods are declared
In Java and C++, a class body holds the fields and the methods together, and a class is closed once
its body ends. Rust, Go, and Bridger declare a type’s data in one place and its methods in impl
blocks or method declarations elsewhere, and a type can have several such blocks. The data layout
of a type is then one short declaration. Separation also allows methods on a type the program did
not declare, as impl String { fn shout(self) -> String = self ++ "!"; } does in Bridger. Rust
and Go restrict that: a method must be declared in the same crate (Rust) or package (Go) as its
type.
The receiver
Java and C++ methods refer to their receiver through an implicit this, and a field name alone
inside a method body refers to the receiver’s field. Python and Rust make the receiver an explicit
first parameter. The Python tutorial describes
the call as plain function application, “the call x.f() is exactly equivalent to MyClass.f(x)”, and
argues for the explicit form: “There is no shorthand for referencing data attributes (or other
methods!) from within methods.” Bridger’s self.w follows Python and Rust, so a name in a method
body is always a local, a parameter, or a top-level definition.
Method calls as function calls
If x.f() is the same as f(x), a language can let either form call either kind of function. D’s
uniform function call syntax lets a free function be called with the dot when its first argument is
the receiver, and Nim’s method call syntax allows obj.methodName(args) in place of
methodName(obj, args) for any procedure. The dot then chooses only how a call is written, which
makes chains such as xs.filter(p).map(f) available for every function. Bridger keeps the two
apart: area(s) calls a top-level function and s.area() calls a method, and the method’s name is
looked up under its receiver’s type, which lets two types use the same method name.
Mutable fields and functional update
Hoare’s records and Simula’s objects had fields that could be assigned, as do C structs and Java
objects. Bridger’s fields are fixed when the value is built, and changing one means building a new
value. Languages with immutable records usually offer syntax for that, such as OCaml’s
{ p with x = 5 } and Rust’s Point { x: 5, ..p }, which copy every field not mentioned. Bridger
has no such form, so a struct with many fields is rebuilt in full. Mutability comes from a ref
field, as in Counter, and it is then visible in the field’s type.
Names and structure
Bridger’s structs are nominal: two struct types are equal only when they have the same name.
TypeScript’s object types are structural: a value of type { x: number; y: number } is
accepted wherever any type with those fields is expected, and a size with fields w and h would
be kept apart from a point only by its field names. OCaml’s object types are also structural, and a
function that calls a method on its argument accepts any object with that method. Structural record
types let unrelated code agree on a shape without a shared declaration, and nominal ones let two
types with the same shape stay distinct, as Point and Size do.
Further reading
Records: Hoare’s “Record Handling” (1965) introduces record classes, references, and field designators with a genealogy as its running example, then sketches procedure fields, array fields, initial values, and unions of record classes in its closing section. Its “Further thoughts” follow-up appeared in ALGOL Bulletin 23 (1966).
Simula: Dahl’s “The Birth of Object Orientation: the Simula Languages” is a short account of Simula I and Simula 67 by one of their designers, including the road-traffic example and the step from Simula I’s processes to Simula 67’s classes and subclasses.
Concept checks
Why does Size { h: 4, w: 3 } == Size { w: 3, h: 4 } evaluate to true, and in what order are 3 and 4 evaluated in the first literal?
A struct value holds its fields in declaration order, so both literals build the value that prints
as Size { w: 3, h: 4 }, and equality compares the struct names and then the fields. The literal’s
own order still decides evaluation, so the first literal evaluates 4 before 3. The difference is
visible only when a field expression has an effect, such as printing or writing a reference.
The opening program's is_tall read r.0 as the height. Which of Bridger's three ways of writing a product would have caught that mistake, and why?
Only the struct. A tuple and a one-constructor type both identify components by position, so
r.0 and a pattern P(h, w) are equally free to read the first component as a height. A struct
field is read by name, and s.h means the field declared as h wherever it is used.
Why is Size.area() an error when s.area() is fine, and what does the receiver evaluate to in each?
area takes self, so it needs a value of type Size to bind to self. In s.area() the
receiver evaluates to a struct value. In Size.area() it evaluates to the type itself,
Value::Type, which can only receive an associated function such as new, one declared without
self.
A method body cannot see the locals of the function that calls it. Would a language lose anything if method bodies were closures over the scope where the impl appears?
In Bridger nothing would change, since an impl appears only at the top level and its enclosing
scope is the top-level scope. In a language that allows a class or impl inside a function, such
as Java’s local classes or Python’s nested class statements, methods can capture the enclosing
function’s variables. That lets a method use a value without passing it in, at the cost of making
the method’s behaviour depend on where its type was declared as well as on its receiver and
arguments.
Suppose Bridger made struct types structural, so any struct with fields w: Int and h: Int could be passed where a Size is expected. What would the opening example's bug look like, and what would a program gain?
Point and Size have different field names, so area(corner) would still be rejected. A struct Frame { w: Int, h: Int } declared elsewhere would be accepted as a Size, though, whether or not
its author meant the same thing by w and h. The gain is that two pieces of code can share a
shape without agreeing on one declaration, which matters most when they are written separately.