LEVIATHAN vd52e79c4 · d52e79c486

Types

Generics

Generic classes and functions, how type arguments are inferred or given explicitly with ::<T>, invariance, how each instantiation is checked, T::member and type constructors.

since 0.1.0-alpha.1linuxwindowswasm

Description

A class, a function or a method can take type parameters: class Box<T>, R identity<R>(R x), U map<U>(...). In a type, an instantiation is written Name<T1, ...>, as in Box<int>.

The compiler infers type arguments, in this order:

  1. from the types of the constructor or call arguments, including through containers (an Array<U> parameter against an Array<int> argument gives U = int) and through inheritance (a Box<U> parameter against an argument whose class derives from Box<int>, such as class IntBox : Box<int>, gives U = int);
  2. from the target type of the initializer, assignment or return that receives the result.

When inference is not enough, or you want to state the types, give them at the call with ::<...>: Box::<int>(), identity::<string>("x"), items.remap::<string>(fn).

Generic class and functions

use io::console;

class Box<T> {
    T item;
    T get() => this.item;
    U map<U>((T) => U f) => f(this.item);
}

R identity<R>(R x) => x;

Box<int> a = Box(5);
console.writeln(a.get());
console.writeln(a.map((n) => "n=${n}"));
Box<string> b = Box::<string>("hi");
console.writeln(b.get());
console.writeln(identity(41) + 1);
console.writeln(identity::<string>("x"));
void demo() {
    var f = identity::<int>;
    console.writeln(f(7));
}
demo();
5
n=5
hi
42
x
7

Rules

Writing and inferring type arguments.

  • A static member of a generic class is shared by every instantiation and is written with the bare class name (Box::count); it cannot use the class's type parameters (lang.static-members).
  • A type position uses angle brackets: Name<T1, T2>. Instantiations nest: Array<Array<int>>.
  • A generic class is always written with its type arguments, in every type position: a variable, a parameter, a return type, a field, a function type, a base clause, a catch, an is test and a match pattern. Array xs, catch (Box b) and class Sub : Box { } are compile errors, and so is a wrong count (Map<int>) or arguments on a class that takes none (P<int>):
error: 'Array' is generic: write its type arguments, as in 'Array<int>'
error: 'Map' takes 2 type arguments, not 1
error: 'P' is not generic
  • A call uses the turbofish, callee::<T1, ...>(args). f<T>(x) written without :: is a comparison, never a generic call.
  • That comparison is then rejected. A type name as an operand of <, >, <= or >= is a compile error that names the turbofish, because a type is not a value and has no order. Box<int>(4) parses as (Box < int) > (4). The error says that Box is a type, not a value, so it cannot be an operand of <, and it names the turbofish (Box::<T>(...)). A note gives the construction, Box::<int>(...).
    • Spellings that do not parse get the same note: a ? in the type arguments (Box<P?>(p)), two or more of them (Map<string, int>()), or a nested list.
    • This changes behaviour for existing programs: var n = Box<Box<int>>(b); used to compile with n a bool, and f(Two<int, string>(1)) used to compile as two bool arguments.
    • The same holds for == and !=: a bare type name is not a value in operand position, so no operator resolves on it. int == string is a compile error with the same message (it used to be true on --run and not lowerable on --ir). x is int is unchanged; equality of types is left to the planned Type objects.
  • The turbofish with no argument list, identity::<int>, is a pinned reference to the generic function as a value. An unpinned reference, var f = identity;, is a compile error that suggests the turbofish.
  • An explicit list is all-or-nothing and exact. Its length must equal the generic arity of the constructor, function or method: Box::<int, int>(1) and a one-argument list for a two-parameter function are errors.
  • An explicit list needs a declared function, method or constructor. It cannot be applied to a closure or another function value.
  • Receiver class arguments are independent of a method's explicit list: items.remap::<string>(fn) supplies only the method's parameter.
  • A call binds a generic method's type parameters once: from the receiver's type arguments, from an inherited method's base clause (class K : G<int> binds G's T := int for every G method called on a K, through any chain of clauses), from explicit ::<...> arguments, and then from the value arguments, a lambda argument's declared parameter types and its return type. A lambda's written return type binds exactly, as ::<...> does: xs.map(string (x) => "n" + x) binds U to string; without one, the type its body returns binds it. This holds in method and constructor calls. Every argument, every typed lambda parameter and the return type are checked against that one binding. When several value arguments determine the same type parameter, it binds to the single most specific common supertype of all of them, and their order never matters: with void eq<T>(T a, T b) and a string? v, both eq(v, "x") and eq("x", v) bind T to string?; a Dog and an Animal bind Animal, and so do a Dog and a Cat whose one common base is Animal. Bindings from explicit ::<...> arguments, the receiver and base clauses come first and are never widened. The same rule types a conditional, a match, an array literal, ?? and a lambda's returns (lang.merged-types).
  • An optional argument lifts: None is set aside, the common supertype of the rest is taken, and the result is optional again. A Dog? and an Animal bind Animal?. No other union is formed.
  • A bare literal argument beside a typed argument does not decide the binding. It takes the binding the typed argument gives, the way a literal takes a declared type: with a float f, pick(f, 0) and pick(0, f) bind float; with a byte b, pick(b, 1) binds byte, and pick(b, 300) is the usual out-of-range error; with a char c, pick(c, 'x') binds char. A float literal never becomes an integer, so with an int i, pick(i, 2.5) is an error.
  • Inference never widens a number otherwise: int and float have no common supertype, so two typed numbers of different types, or two literals of different kinds (pick(1, 2.5)), are an error. Inside a generic body, a number beside a value of the body's own type parameter takes that parameter: U bump<U>(U x) => pick(x, x + 1); binds U, and the number is the contextual numeric boundary described below. A non-numeric value there is an error.
  • When the arguments have no common supertype, or more than one equally specific (two base classes, two interfaces), the call is a compile error; write the binding explicitly, as in pick::<float>(1, 2.5):
error: cannot infer type argument 'T' for 'pick': 'int' and 'float' have no common supertype; write the type arguments explicitly, e.g. 'pick::<...>(...)'
  • Inside a generic body its own type parameters are rigid. A value of type T converts to T itself, to a union that holds T (such as T?), and to a type parameter of a generic function being called, which then binds to T. It converts to no other type: with a field T keep, int y = this.keep;, takeInt(this.keep), int f() => this.keep; and U other<U>() => this.keep; are compile errors, whatever T is instantiated to. The same holds where the conversion is less visible: arithmetic with a number gives a T (this.keep + 1 and 0 + this.keep are Ts, so int a = 0 + this.keep; and acc += this.keep; into an int are errors, while T t = this.keep + 1; is fine); a construction typed by its target (Box<int> b = Box(this.keep);) is checked like Box::<int>(this.keep); a condition or an operand of &&, || or ! (if (this.keep)) must be a bool; and a conditional with a T arm (c ? this.keep : 0) is a T, so it is an error into an int. The one exception is a call to an overloaded free or namespace function, inside a generic function, that passes a value of the function's own type parameter: with overloads enc(int) and enc(string), enc(x) inside arr<T> is resolved again for each instantiation, and an instantiation that no overload accepts is a compile error at that call. A typed lambda parameter must name the same parameter. A non-numeric concrete value ("s", None, true) is never known to be T, wherever the T sits in the target and whatever brings the value there: with T g(T x), void put(Array<T> a) and T? h(T? x), the calls this.g("s"), this.put(["a"]) and this.h("a") are compile errors, and so are Array<T> xs = ["a"];, this.xs = ["a"];, a Box<string> or a K : Box<string> passed for a Box<T>, and a lambda body that gives a string where a T is expected. A number in any of those places is a contextual numeric boundary, and the next rule decides it.
  • A number converts to a type parameter only where the parameter is bound to a number. Inside a generic body T z() => 0;, c ? this.keep : 0, T x = 0;, this.g(5), this.put([1]) and vs.add(aFloat) on an Array<T> are accepted, and each binding is checked: on Box<float> the 0 is a float, on Box<string> the call or construction that binds T is a compile error whose note points at the 0. A member nothing calls on a Box<string> binds nothing, so it is not checked there.
  • None is not a value of a type parameter: T may be instantiated with a type that does not admit None (string), so inside the generic body None, and a value that may be None (a T?, any union holding None), does not convert to T. return None; from a function returning T, T f<T>(T? x) => x; and v = None; into a field T v are compile errors (cannot return 'None' as 'T', cannot assign 'None' to 'T'). A T? reaches T only by narrowing: after if (x != None), or after an early exit such as if (x == None) { return d; }, x is a T. Write T? where the value may be absent.

Variance.

  • Generics are invariant: a Box<int> is not a Box<float>, even though int converts to float.
  • Inside a generic class, this has the class's type at its own type parameters: inside class Self<T> : Box<T>, this is a Self<T> and therefore a Box<T>. It converts to Box<T>, but not to Box<string> or Self<string>.
  • Invariance holds across inheritance too. A subclass, or a class implementing an interface, converts to its base only at the instantiation its base clause names, read with the value's own type arguments. With class SubBox<T> : Box<T>, a SubBox<int> is a Box<int> and converts to it, but not to Box<string>. With class IntBox : Box<int>, an IntBox is a Box<int> and nothing else. The rule is the same through interfaces (class Cell<T> : IGet<T> makes a Cell<int> an IGet<int>), through an interface that extends another, and across any number of base levels.

Type tests.

  • Type arguments are erased at run time, so a test can check only the class. An is test or a match pattern naming a generic class is legal only when the subject's static type already fixes its arguments, and the arguments written must be those: with x : Array<int> | string, x is Array<int> narrows x to Array<int>. With v : IShape (where class Cup<T> : IShape) nothing fixes T, and with c : Cup<int> | Cup<string> the members disagree; both are compile errors. A test that can never be true is one too: x is Array<string> with x : Array<int> | int, or s is Cup<int> with s : string.
error: cannot test for 'Cup<int>' at run time: generics are erased and 'IShape' does not fix the type arguments of 'Cup'
error: 'Array<string>' can never match 'Array<int> | int'
  • A subject whose class derives from the tested class fixes its arguments through the base clause (class IntBox : Box<int>: an IntBox tests as a Box<int>), and so does a base or interface the tested class's own clause names (class Jar<T> : IHolder<T>: an IHolder<string> tests as a Jar<string>).
  • A test against a generic function's own type parameter (match (m) { E => … } inside E castTo<E>(Model m)) is exact: the function is compiled once per concrete binding, and each copy tests that class. A class-level type parameter cannot be tested:
error: cannot test for 'T' at run time: 'T' is a type parameter of class 'Holder' and generics are erased

Members of a type-parameter value.

  • Generics have no bounds, so a member read or a method call on a value of type T (or on a value computed from one) is not checked in the generic body itself: x.name() with x : T compiles there, and its result has no checkable type in the body; a var initialized with it depends on the type parameter in the same way, and a type test on it that names a generic class is a compile error, because nothing fixes the class's arguments.
  • Instead every instantiation is checked, as C++ checks a template: each use of a value of type T is a demand on T, and every type bound to T must meet the demands of the members the program uses with that binding. A demand is a field read or store, a method call (its name, its number of arguments and their types), indexing, a call of the value, an operator (+, <, unary -, ...), for … in, and string interpolation ("${x}" calls toString()). == and != are met by every type, except one that (itself or through a base) declares a user (==): then the use is checked as a == b with that type is, so a (==)(int) rejects same(D(), D()) just as it rejects D() == D(). A string + stringifies its other operand and is no demand on it.
  • A binding is the bound type itself, not its spelling: two classes named D in different namespaces are two bindings. A type parameter the call does not fix takes the argument's own static type (all([D()]) binds T to D; nn(D()) for a parameter T? x binds T to D). When no concrete type follows from the arguments and the body uses the parameter, the call is an error: "cannot check type parameter 'T' of 'all': it is not inferred here; write the type arguments (::<...>)".
  • A binding meets a demand exactly as non-generic code with that type would: a union or optional type has no members until narrowed (it does have ==), a function type has none, an interface has its declared members, < needs a number, string, char or a class declaring (<), and toString is not universal.
  • The check is lazy, per member: Array<D> demands nothing of D, while calling joinToString on an Array<D> demands D.toString(). A binding is checked against the member it is used with and everything that member reaches with it: a generic that passes its T to another generic, or a class member that calls another member of its class, inherits the callee's demands, and a class bound through a base clause (class IntBox : Box<int>, class Sub<T> : Box<T>) is checked the same way. Because a dispatched call can run another body than the one it names, the program is treated as closed: a call that binds a method's own type parameters binds those of every override and implementation of that method too, and constructing a class binds the members it overrides or implements (a member of an interface or base), for a class without parameters of its own through its generic base (class DBox : Box<D>). Forming a function value binds as a call does: rd::<D>, or Box::show typed as (Box<D>) => string.
  • Where a demand's result flows into a concrete type (int first<A>(A a) => a.xs[0];), the bound type must produce a compatible one.
  • A method call or an operator on a value of type T is chosen at run time by its name and number of arguments alone. When the bound type has two or more methods of that name and count (m(string s) and m(int x), (==)(Money) and (==)(int)), the one declared first runs, inherited ones before the class's own, whatever the argument types. The binding therefore depends on the declaration order: it compiles when the overload the use needs is the first one, and fails when it is another, with or without an override: type 'B' bound to 'T' of 'callInt' has two methods 'm' taking 1 argument, m(string) and m(int): the use needs m(int), but it runs the first of them, m(string). The standard library's own generic equality follows the same rule. Array.contains, Array.indexOf and Pair/Triple == compile for an element type whose (==)(Money) is declared before its (==)(int), and fail for one declared the other way round. The operators a match arm on a T value calls (== for a value arm, >= and <= for a range arm) are checked for this rule only; an arm is no other demand on T.
  • A use guarded by a type test that narrows the value to a concrete class (match (x) { C => x.s }, if (x is C)) is checked against that class and is no demand. A use guarded only by a run-time condition is still a demand.
  • A failing binding is a compile error at the call, construction or base clause that binds T, with notes at the use and at the calls that reach it:
error: type 'D' bound to 'T' of 'rd' has no field 's'
note: required by 'x.s' at main.lev:3
  • Checking a binding re-checks what it reaches with that binding. A chain of distinct generics has no length limit, but polymorphic recursion -- a generic reaching itself again with a growing binding, w<T> calling w<W<T>> -- is rejected after 32 re-entries, as C++ rejects an infinite instantiation: "generic instantiation check exceeded the depth limit (32); this instantiation graph may be unbounded".
  • Generics stay erased at run time: one compiled body serves every binding.

T::member.

  • Inside a generic function, the left side of :: may be one of that function's own type parameters: A::FromInt(n) calls the labeled constructor FromInt of whatever type A is at the call.
  • The member is checked for each concrete type used. If the type lacks the member, the error names the type and points to both the A::member use and the call that instantiated it.
  • T:: works only for type parameters of the function. A class-level parameter is rejected: "'T' is a class-level type parameter".

Type constructors.

  • A type parameter may stand for a generic type that takes an argument, written F<A>. Inference binds F to the generic name: F<A> against Array<int> gives F = Array and A = int, and the result type F<B> keeps the container. When several arguments determine F, it takes the common supertype of their whole types: a Sub<int> and a Base<int>, where Sub<T> : Base<T>, give F = Base in either order.
  • This is an advanced idiom. Prefer ordinary methods for everyday code.

Examples

T::member and a type constructor:

T::member and a type constructor

use io::console;

class Meters {
    int n = 0;
    new FromInt(int v) { this.n = v; }
}

class Wrapper<T> {
    T item;
    new Of(T v) { this.item = v; }
}

A decode<A>(A witness, int n) => A::FromInt(n);
F<B> mapIt<F, A, B>(F<A> c, (A) => B fn) => c.map(fn);

Meters m = decode(Meters(), 12);
console.writeln(m.n);
Wrapper<string> w = Wrapper::Of::<string>("lab");
console.writeln(w.item);
Array<int> d = mapIt([1, 2, 3], (n) => n * 2);
console.writeln(d);
12
lab
[2, 4, 6]

Checked instantiations:

Checked instantiations

use io::console;

class Named {
    string name;
    new Named(string n) { name = n; }
    string toString() => "Named(" + name + ")";
}
class Plain { int n = 1; }

string describe<T>(T x) => x.name + " is " + "${x}";
string guarded<T>(T x) {
    match (x) {
        Named => { return x.name; }
        else => { return "not named"; }
    }
}

console.writeln(describe(Named("a")));
console.writeln(guarded(Named("b")) + ", " + guarded(Plain()));
Array<Plain> ps = [Plain()];   // a type mention demands nothing
console.writeln(ps.length());
a is Named(a)
b, not named
1

describe(Plain()) in the program above is a compile error, because Plain has neither the field name that describe reads nor the toString() its interpolation calls:

error: type 'Plain' bound to 'T' of 'describe' has no field 'name'
note: required by 'x.name' at main.lev:10

Notes

Not supported: using T::member where T is a class-level type parameter.

See also

  • Type expressions — How a type is written: names, qualified names, generic instantiations, unions, optionals and function types.