Stories: Generics and Type Parameters
See also:
spec/generics.md— the rules this story explains.
Types are templated functions
The first fork was whether templating is a feature bolted onto the type system or a consequence of it. Most languages take the first road: types are one kind of entity, and a separate generics sublanguage (template<...>, <T>, [T any]) is grafted on with its own scoping, its own inference, and its own corner cases. We could have done the same — a dedicated generics grammar layered on a non-value type system, the way C++, Java, and Rust do — but it duplicates machinery the rest of the language already has, and every such system grows its own scoping and inference rules that drift away from the language around them.
We had already committed to types being ordinary compile-time values that the compiler executes in an earlier stage. Once that is true, a parameterized type is just a function from parameters to a layout, and “generics” stops being a feature we add — it comes for free. Vector<Int> is not special syntax; it is applying an argument to a function and running it at compile time. The payoff is conceptual economy: one idea — types are staged functions — explains parameterization, the <>/() split, and the literal-wrapping rule that comes later. The honest cost is that the idea offers more than the spec currently delivers. If types are really functions, you would expect to run arithmetic on number parameters, Array<T, rows * cols>, and we cannot yet; the gap between that promise and the delivery is real, and the deferred-features account at the end of this story owns it.
The parameter model
The central decision of the whole document follows from that framing, and a one-line table cell did it the most damage, so it gets the long telling. A parameter has to be introduced at some position, and there were two places to put it: a <> header after the name (Foo<T Type>), the way nearly every language headers its generic functions and types alike; or inline, at the parameter’s first marked occurrence in the signature (x T Type), with no header at all. The tempting move is to pick one and impose it everywhere, for uniformity. We rejected that, because types and verbs do different jobs. A type is applied positionally by its users — Vector<Int>, Buffer<Int, 64>. The order of its parameters is part of its public interface; it is exactly what a use site fills, left to right. A public, ordered interface needs an explicit, ordered signature, and a <> header is exactly that signature, so types keep the header. A verb — function, method, constructor — is never applied positionally. Its parameters are always inferred from the value arguments or passed as ordinary values, and a caller never writes <...> on a verb at all. A header there would declare an order nobody uses, pure ceremony, so the verb introduces each parameter inline instead and references it bare elsewhere. The split is not stylistic; it tracks the real apply-versus-infer distinction — header where there is a positional interface, inline where there is not. Forcing the header onto everything, the Rust/Swift fn head<T, const N>(...) style, reads cleanly because the binders come first, but it makes verbs declare an order no call site fills and quietly reintroduces the <>-at-call-site channel we wanted to delete; forcing inline onto everything breaks a type’s positional interface, so Vector<Int> would have no signature to check against.
That leaves the subtlety the spec states mechanically (“first marked occurrence”) but never motivates: why does x T Type mean “infer T” while T Type means “pass T”? The two look almost identical — the second is the first with the value name deleted. The idea that makes it click is that every symbol has a value and a type, and a type is itself a symbol — its value is a concrete type, its type is the concept Type. Take three verbs that differ only in how they declare their one parameter:
Void func (x Int) {}
Void func2(x T Type) {}
Void func3(T Type) {}
Now call each, and draw the parameter as a tree of its value and its type, expanding any type that is itself a symbol one level further:
func(Int(3))
└─ x
├─ value: Int(3)
└─ type: Int
func2(Int(3))
└─ x
├─ value: Int(3)
└─ type: T
├─ value: Int
└─ type: Type
func3(Int)
└─ T
├─ value: Int
└─ type: Type
func2 is the whole point. The parameter x has type T, and T is itself a symbol whose value — Int — is exactly what inference recovers: the same value/type subtree as func3’s T, only reached from a value argument instead of handed over directly. So inferring is not a separate mechanism from passing. It is the same T Type symbol with its value left blank, filled from the value argument instead of given at the call. func(x Int) leaves nothing open. func3(T Type) declares the type-symbol T and the caller supplies its value, func3(Int) — explicit passing. func2(x T Type) declares x with type T but says nothing about T’s value, so the call func2(Int(3)) gives a value for x and T is just that value’s type — inference. The presence or absence of the leading value name is the whole switch: it is the answer to “do you supply a value T can be read from, or do you supply T’s value yourself?”
Seeing it this way pays off three times over. It makes the x T Type / T Type distinction legible instead of arbitrary — once T is just a symbol whose value is a type, T Type reads as the same declaration as x Int, one level up. It explains the literal-wrapping rule for free, since inferring T means reading a value’s type and a bare literal’s type is a concept rather than a concrete type (the wrapping rule is taken up later). And it turns the apparent footgun — delete one identifier, flip the meaning — into a legible edit: removing the name does not flip a mode flag, it stops supplying a value for T to be read from. Still a sharp edge, but a meaningful one.
None of this is free. A bare reference can appear before its marked introduction — in T head(arr Array<T Type, n Number>) the return T is bound by the marked occurrence later in the signature — so you cannot read a verb’s parameters strictly left to right; you scan the whole signature for the introductions. The value/type framing does not fix that; it is orthogonal to infer-versus-pass, and it is the part most likely to trip up a newcomer, the price we pay for dropping the header. The framing is also a Type story, not a Number one: a type can be the type of a value, so a type parameter’s value can be read off an argument, but a number cannot be the type of a value — x n Number is meaningless — so numbers have no value-driven inference and are recovered only structurally, from a nested type like Array<T Type, n Number> where n rides on the literal’s length. The symmetry between x T Type and T Type belongs to Type specifically, and it is worth teaching where it stops. Above all, the model is the load-bearing part, not the syntax: a reader who has been told that a type is a symbol with a value and a type finds T Type natural; a reader who has not finds a type sitting where a value should be. That is an argument for teaching the idea up front — which is why this story exists — not for changing the surface.
The parameters that model introduces still need a type of their own. Once a type handed to a constructor is just a compile-time value, its parameter needs a type like any other value — and we already had concept types (@concepts$Number and the rest) for exactly the “compile-time, parameter-position-only, never storage” role that literals occupy before lowering. So a type parameter is declared with the Type concept and a number parameter with the Number concept, reusing that machinery wholesale, with no bespoke parameter-kind keyword like typename, const, or comptime. Inventing such a keyword would only be a second spelling of “compile-time, parameter-position-only” when the concept types already carry that meaning. The scheme cleanly distinguishes exactly two kinds, Type and Number, and leans on casing — uppercase type, lowercase number — to tell them apart at reference sites. The strain it has not yet faced is a third kind of compile-time parameter; the deferred generic function value is the obvious candidate, and the two-kind casing scheme may not stretch to cover it gracefully. Noted, not solved.
No turbofish: passing types as values
That parameter model leaves the question every generics design has to answer at the call site: how a caller supplies a parameter. The answer leans on a deeper split between the two bracket pairs. <> belongs to the type system: a compile-time, structural description of what a value’s architecture is, resolved in an earlier stage. () belongs to the value system: it constructs or runs at run time. Keeping them as different mechanisms — not two syntaxes for one idea — is what keeps each simple, and the sharp consequence is that a call never carries a <> list. There is no Vector<Int>(...) turbofish; a parameter reaches a callable either by inference, reading T’s value off a value argument, or as an explicit Type/Number value argument. A parallel <> channel at the call site would be a third route for the same information, redundant with both, which is why Rust’s ::<T> and C++’s f<T>() are deliberately not available here. This is also where case-sensitive parsing pays off: Vector<Int> is a type application and a < b is a comparison, told apart purely by whether the token before < is uppercase. Most languages pay for <> generics with permanent parser pain — the >> token, the most-vexing-parse — and we do not, precisely because <> lives only in type expressions and the casing rule disambiguates them (see lexical.md §5). The downside we are choosing to eat is that, with no turbofish, a caller cannot force a type that appears only in a function’s return — parse-to-T, an empty container of T, zero or default construction. The author has to anticipate that and expose an explicit Type value parameter, so expressiveness Rust gives the caller, we give the library designer instead. The deferred “phantom type parameters” question is the visible edge of this. We judge the simplicity worth it, but it is a genuine transfer of power, not a free win — and how a caller names such a type at all, without the channel we just deleted, is the next problem.
That problem only exists because of the no-turbofish decision. Once we had decided that a call carries no <> list, inference became the only way a type reached a callable. For most calls that is enough: the type rides in on a value argument and the compiler reads it off. But not every type a call needs is sitting on a value. A function that only returns a T — a zero-initialised buffer, an empty container, a parse that turns text into an Int — has no value argument carrying the type, so there is nothing for inference to read. With the turbofish gone, the caller had no channel left to name that type at all. That is not a small gap: without an answer, zeros(Int, 1024), an empty List(String), and parse(Int, text) would simply be unwritable, and the no-turbofish decision would have quietly amputated a whole class of APIs. So we needed a mechanism for the caller to hand a type over directly. The first idea was to carve out a narrow exception — allow a turbofish only on the parameters inference cannot reach. We dropped it fast: it reintroduces the exact <>-at-the-call-site channel we had just deleted, brings back the parser ambiguity the casing rule had bought us out of, and leaves a call site that sometimes carries <> and sometimes doesn’t — the worst of both worlds, and a rule no one could hold in their head. The second idea was a dedicated marker — a keyword or sigil in the () list that flags “this argument is a type.” That was less bad, but still a bespoke mechanism, a third construct to learn, and it quietly concedes that a type is a second-class kind of argument that needs its own syntax to travel.
The answer that held needed no new channel at all, because the value/type model had already removed the need for one. A type is an ordinary compile-time value — the heart of the parameter model — a value travels in the () argument list; therefore a type can travel in the () argument list, as a value parameter whose declared type is the concept Type. That is all func3(T Type) is — a parameter named T of type Type — and the caller passes it like any other value: func3(Int), or Array(Int, 10000) handing over a type and a size side by side. Nothing was added to the language; we just noticed that the channel we already had was enough. And because the author picks infer-versus-pass purely by the parameter’s shape — a value name in front (x T Type) marks “infer me,” the bare concept (T Type) marks “pass me” — there is still exactly one calling convention, not a value channel beside a type channel. This makes “no turbofish” affordable instead of crippling, and it is the real reason passing a plain type matters: the no-turbofish decision deleted the type-argument channel, and this shows the channel was never needed, because types were values all along — so none of the APIs that decision threatened are actually lost. The residual cost is the cost the no-turbofish decision named from the other side: it falls to the library author to expose an explicit Type parameter wherever inference cannot reach, and a parameter that no path — value, receiver, or literal — can fix is simply unsupplied. That open edge is the deferred “phantom type parameters” question.
There is one place where passing a value is not enough, and it is the literal. Vector(Int(2), Int(3)) is legal; Vector(2, 3) is not. A bare 2 carries the concept type @concepts$Number, not a concrete Int or Float, and the compiler will not guess, so a bare literal must not drive inference of a type parameter. This looks like an ad-hoc restriction until you read it through the value/type idea: inferring T means taking a value and reading its type. The type of Int(3) is the concrete Int, usable as T; the type of a bare 2 is the concept @concepts$Number, which is not a concrete type, so there is nothing to assign to T. The wrapping rule is not a special case — it is simply that the type read off the argument has to be concrete, and a bare literal’s isn’t. Letting the compiler pick a default concrete type instead, 2 quietly becoming Int, would bake a silent type choice into every generic call, exactly the kind of implicit decision the language avoids elsewhere. The price is one explicit Int(...) wrap at each such call site — paid once, per literal, in exchange for deleting the whole turbofish channel everywhere else.
Size is part of the type
Parameters are not only types; sizes are parameters too, and a separate fork settles where a size lives. The tempting shortcut is to leave an array’s size out of its type — the stack pointer is just a register, an array never resizes after construction, and C99 VLAs already do this for locals, so there is prior art for “a runtime-sized local is fine.” We bake the size in anyway, because the real cost of a runtime-sized type is not stack allocation but the loss of uniform stride. If two values of one type can differ in size, then arr[i] can no longer be base + i * stride with a constant stride; embedding the type in a struct leaves the outer layout unknown; copying needs a runtime size query; and calling conventions, which depend on fixed-size parameters, break. Worse, the break propagates — an array of variable-size structs loses uniform stride, a struct containing one loses it, and so on up every containment chain. So Array<T, n> is the mechanism that guarantees every value of a given type is the same number of bytes, and that guarantee is precisely the source of cheap indexing, copying, embedding, and calling. It is the clearest case in the whole language of the general bargain: a high-level convenience is forbidden so that a low-level guarantee can hold, and the strictness is not a tax paid alongside the performance — it is the performance. This rule is cited from adt.md §4, where a directly inline self-referential type would have infinite size, which uniform stride forbids, which is why recursive types must box through &. The one loose end it leaves is that two arrays of different lengths are different types, so arithmetic on the size in a type position (Array<T, rows * cols>) becomes a type-identity question — and that is deferred, below.
That Array<T, n> is also the single storage primitive the compiler provides. One compiler-provided fixed-size base case — n contiguous T — keeps the compiler’s layout responsibility minimal. Every other fixed-size container, vectors and matrices among them, is defined in terms of Array and needs no extra compiler support, and dynamic containers, when they are specified, will be separate runtime-managed wrappers over opaque storage rather than extensions of Array. Blessing several container primitives instead would hand the compiler more layout surface to own; one base case plus library composition is smaller, and more honest about the actual primitives.
Deferred: what the model promises but does not yet deliver
What remains is the honest record of the gaps — the places the “types are executed functions” framing promises more than the current spec keeps. The biggest is type-level arithmetic on number parameters, Array<T, rows * cols>. The model says a type is a function you run at compile time, so running * on two numbers in a type position should fall out for free — except that two type expressions being “the same type” needs a type-level equality rule that canonicalizes such expressions, and that is exactly the hard part the framing papers over. It is why const-generic arithmetic took years elsewhere, and it is deferred pending that equality rule; the elegant framing oversells how much is free, and this is where the bill comes due. Close behind is constraints on type parameters. add(x T Type, y T Type) silently assumes T supports +, but nothing yet lets an author require that T is addable, comparable, or printable, nor pins down how the compiler checks it. As specified the check is structural-at-instantiation, the way C++ templates worked before concepts, so a missing capability surfaces deep in the callee’s body rather than at the signature. Bounded polymorphism is half of the reason generics are usable in practice, and it is the most important feature to design next — most likely growing out of the concept machinery rather than a new sublanguage, since concepts are already how we type compile-time parameters. Two smaller gaps round it out. A generic function value, one polymorphic over its own type or number parameters, is unspecified; the open question there is runtime representation — monomorphization versus dictionary passing — which is a memory-model decision rather than an overload-resolution one, since a generic function type is still a unique parameter shape (see functions.md §7.6). And phantom type parameters — an introduced parameter with no path from any value argument, receiver, or literal that fixes it — currently have no way to be supplied at all, which is the visible edge of the no-<>-at-calls decision above. Named lane access (.x/.y/.z/.w) and element-access bounds-checking are also deferred, but on their own merits, not for any reason rooted in the model.
A container whose size the type cannot carry
Size is part of the type settled on one container primitive and left the dynamic container as a promise: a dynamic container, when one was specified, would be a runtime-managed wrapper over opaque storage. Specifying one turned out to be the moment the promise needed a second primitive, and the reason is the one value Zane does not let a program hold.
A growable sequence is, underneath, a pointer to a heap block, a length, and a capacity, and growing it requires allocating a larger block, moving the elements, and repointing. In a language with pointers that is library code — every standard vector is written that way. Zane does not have pointers, for safety: a program reaches memory through hosts and guests, and even a guest is represented as a tether into an anchor table rather than an address (memory.md §4.2). A pointer a program can hold is a pointer it can hold past the life of what it points at, and ruling that out is what the memory model is for. So no package can write the dynamic container, and core is no exception.
Array could not be stretched to cover it either, since its length is part of its type and a length that changes at runtime would be a type that changes at runtime — exactly the loss of uniform stride we refused in that chapter. And the one road that would have kept the compiler’s container surface at a single primitive, letting core alone hold pointers in some restricted form, would have made core privileged in the one respect where privilege costs safety, in the package every program imports.
So the compiler supplies the container that needs pointers, and uses them only inside it: @primitives$List<T> is a sequence of T whose length changes at runtime (generics.md §8.3). Source sees only a fixed-size handle, with the elements behind it in the dynamic region (memory.md §3.6), and core wraps the primitive as List, as it wraps @primitives$Array<T, n> as Array. The claim that one fixed-size base case plus library composition covers every container is the part that did not survive: it holds for fixed-size containers, and it cannot hold for dynamic ones in a language without pointers.
The two primitives are also on different sides of the # axis, and we chose the difference rather than inherited it. @primitives$Array<T, n> is a value type, which is what its fixed layout was always for. @primitives$List<T> is a reference type, so that no value can hold one: a value type contains only value types (memory.md §2.10), and the container that grows at runtime stays on the side of the line where objects are moved rather than copied. It carries no #, and needs none: # is how a reference type is marked where it is defined in Zane, and the primitive is defined nowhere in Zane — the compiler supplies it. core’s List, which is written in Zane, is a # type like any other. The pairing leaves one combination without a primitive — a fixed-size container with identity — and we did not add one, because List already gives it: a wrapper over List that aborts once it holds its limit is a fixed-size reference container, with no third layout for the compiler to own.
The cost is the layout surface we wanted kept small in that chapter. The compiler and runtime now own a second container’s representation, its growth, and the relocation of its payload when a host moves, and none of that can be replaced by a library that disagrees with it. Any further dynamic structure has to be composed from List — or, if it cannot be, raises this same question again, with the same answer available and the same price attached.
Splitting integer and float literals
The wrapping rule from no turbofish rested on a quieter assumption: that every numeric literal was the same kind of literal. 2 and 2.5 both carried @concepts$Number, so as far as the type system could tell they differed only in their text. That was harmless until a literal met a destination where the difference matters. Take Vector2(1.2, 3.6) against a type whose fields are Int. The only step between the 1.2 and the Int was the conversion core declares into Int, and that conversion took @concepts$Number — every numeric literal, fractions included, because there was no narrower type for it to take. The conversion’s body determined the fate of the fraction. If it dropped it, the call was Vector2(1, 3) and nothing on the line showed that; if it rejected it, the rejection came from inside a body rather than from a signature. Either way the type system had been told “any number” and could not refuse.
The difference was already on the page. The syntax lets a programmer write a decimal point, and a literal with one is spelled differently from a literal without, so the type system was throwing away a distinction the author had drawn. We gave each spelling its own concept type: an integer literal carries @concepts$Integer and a decimal literal carries @concepts$Decimal (lexical.md §7). Int declares its conversion from the first and none from the second, so 1.2 at an Int destination is a type error before any body runs; Float declares one from the second only, so a whole-number float is written 2.0 (types.md §2.6).
The spelling determines the concept, not the value, so 3.0 is a decimal. We could have sorted literals by what they denote and let 3.0 through to an Int, since it is whole. But the concept exists to carry what the author wrote, and writing .0 is how an author says a quantity is fractional in kind even when this particular one happens to land on a whole number. Sorting by value would also make the concept depend on a little arithmetic over the digits rather than on a glance at them. The grammar around the . is tight for a different reason. A digit must follow it, so 3. is not a literal, because the . already means field access, and a literal that may end in a . puts the two meanings side by side. Nothing reaches into a literal today, but if literals ever gain members, 3.conceptName would have to be read either as a member of 3 or as a malformed decimal, and every reader and tool would need a rule to tell them apart. We did not look for the rule other languages use; requiring a digit after the . removes the question instead of answering it. A decimal literal always ends in a digit, and a field name never starts with one, so 3.0.conceptName can only be a member access and 3.0conceptName can only be an error. A leading . raises no such question — a field name never starts with a digit, so x.5 could never be read as field access — and we banned .5 anyway, for consistency: one rule, a digit on each side of the ., is easier to hold than a rule for each side, and a . easy to overlook in front of a digit is worth the one character 0.5 costs. There is also no exponent form, so a literal’s digits are written out in full.
The names took one round. The obvious pair was @concepts$Int and @concepts$Float, and it was wrong on both halves. A concept type names a kind of literal, not a storage type, and Int and Float are storage types that core, an ordinary package, declares — the language names none of them, so its concepts should not borrow their names either. And “float” names a binary storage format, while 2.5 is exact decimal digits that a Float, a fixed-point type, or a decimal type might each consume; a fixed-point type taking “@concepts$Float” would be describing its own input wrongly. Integer and Decimal name the literal’s form on the page and nothing about its destination.
Two distinct types also offered an ability the single concept could not: a verb can overload on them. The wrap the no-turbofish chapter accepted — Vector(Int(2), Int(3)) at every call — was a cost each caller paid because only the caller could choose Int. Now a library author can make that choice once, in a signature: one overload taking two @concepts$Integer and wrapping them in its body, another taking two @concepts$Decimal, and vec(2, 3) resolves in the direct phase with nothing wrapped at the call (generics.md §5.4). The rule that a bare literal never drives inference did not move. An integer literal could still become an Int or any other type whose package accepts one, so the compiler still does not choose; what changed is who is allowed to choose, and how many times.
The split then answered a question about number parameters. The n in Array<T, n> had its own concept, Number, which carried almost the same meaning as the literal concept and said less: nothing in it ruled out Array<Int, 2.5>. Once there was a concept for exactly the integers, a second one for sizes was redundant, so we dropped Number and declare a number parameter with @concepts$Integer directly. The 64 in Buffer<Int, 64> is an integer literal filling a slot of its own type, and a value of that concept is a compile-time integer whether it arrives in a type expression or as a literal passed to a verb (generics.md §3.3). An explicit number parameter and a verb that accepts an integer literal turn out to be one mechanism. That is one case of a broader rule: a value of any leaf concept — one with no parameters, such as Type, @concepts$Integer, @concepts$Decimal, or @concepts$Text — is a compile-time value, because a leaf literal is nothing but what is written on the page. An array or map literal is not a leaf; its entries are ordinary expressions, and their values may be unknown until the program runs.
It also settled why integers are the only kind of parameter besides types, and it is not a matter of taste. Generics in Zane is plain substitution: a parameter’s value is substituted into the body it parameterizes, and wherever it goes, it ends in a slot of a type the compiler provides — @primitives$Array<T, n> takes a type and an integer. A package’s type cannot add a parameter kind, because a new parameter kind would have nothing to be substituted into except slots that already exist. So the kinds of parameter are exactly the kinds of value those slots accept, and a parameter’s concept is simply the concept of its slot’s argument. That turns the loose end the parameter model left — a third kind of compile-time parameter, and whether the two-kind scheme would stretch to it — into a path rather than a worry. A new kind arrives with a new compiler-provided type whose slot accepts it, an intrinsic taking a Bool, say, and such a parameter is declared with the slot’s concept. No parameter machinery has to be invented for it.
The costs are small and visible. Every header that takes a size spells n @concepts$Integer where it used to spell n Number, while T Type stays bare, so type parameters and number parameters look lopsided side by side. We kept the lopsidedness on purpose. Type sits on a different meta level from the literal concepts: it is the concept of types themselves, one level above the concepts that give literals their types, so it never belonged in @concepts$ beside them, and type parameters and number parameters look different because they are different. core’s Float takes decimals only, so a whole-number float is written 2.0 and Float(2) is an error. A verb that accepts bare literals of both kinds declares two overloads. Int(3.0) is rejected although its value is whole, which is the spelling rule doing its job and still reads as a papercut the first time. A mixed call such as vec(2, 3.5) finds no overload until its author writes 2.0. And with no exponent form, very large and very small magnitudes are written out digit by digit.
A wrong-kind type argument is reported at its origin
A type parameter ranges over both kinds of type, so whether a type fits is not known where the parameter is declared. It depends on where the parameter ends up. Box<T> as a #struct holds a MainCharacter or an Int alike, while the same T in a value struct admits only values, and the deciding slot may sit several generic types and verbs below the call that supplied the type. Once the language had a mistake that only surfaces at the bottom of such a chain, it needed a place to report it.
The place a compiler naturally reaches the mistake is the bottom: the field a reference type cannot occupy, inside a declaration the caller may never have read. That is the C++ template error, a page of instantiation context ending at a line in someone else’s library. We could also have blamed the generic’s declaration, but the declaration is not wrong; it is correct for every type that fits. The person who made the mistake is the person who supplied the type, and that person can also fix it. So the error goes to the type’s origin, the first position where it is a concrete type rather than a parameter (generics.md §3.6). An explicit argument is its own origin. An inferred one originates at the value argument it was read from, so Pair(MainCharacter()) is reported at MainCharacter(). A generic verb that only forwards T is never blamed for its caller’s choice.
The cost is distance. The reported line can sit far from the field that actually rejects the type, so the line alone does not show why the type was wrong. We considered leaving the rest to the compiler as a matter of quality, and decided against it: an origin-only report would satisfy the rule while telling its reader nothing about the cause, so the diagnostic is required to name the path from the origin down to the slot that rejects the type, the way a dependency-cycle error is already required to name the cycle.
A type parameter’s introduction carries the passing mode: ^T Type and &T Type
The memory model gave a reference-type parameter three passing modes, chosen entirely by the parameter’s surface form: a bare T borrows, ^T takes the owner, and &T takes a reference (memory.md §2.9). One of the generics examples showed what that left missing. The wrong-kind chapter’s Box constructor was Box<T>(value T Type) => init{value;}, and Box(MainCharacter()) was called legal. Under the new rules that constructor borrows its argument, and a borrow can never be stored, so the example performed a store the language forbids. Only a roaming owner moves, and nothing in the signature marked value as one.
The fix had to go on the introduction, because in a verb the introduction is the only place T is written on that parameter. We could have introduced T elsewhere and marked the parameter ^T on its own, but a constructor has nowhere else: introducing T on a separate t Type parameter would make every caller pass the type explicitly, which is the cost the inline introduction exists to avoid. We could also have read the mode off the body, so that a constructor storing its argument took it and one only reading it borrowed. That would make a verb’s contract depend on its implementation, and the passing mode is the part of the contract a caller acts on, since a take spends the caller’s symbol. So the marker goes in front of the introduction, value ^T Type, exactly where it would go in front of a concrete type, and it belongs to the parameter rather than to T: a bare T elsewhere in the signature names the type without it (generics.md §3.2). Over a value type the ^ changes nothing, since a value is only ever borrowed, so Box(Int(3)) still works.
Once ^ could stand there, leaving & out would have made the reference the one mode a generic verb could not request, so &T Type came with it. A generic holder of a reference, Pin<T>(at &T Type) => init{at;}, needs it for the same reason Box needs ^. It does narrow T: & takes only a reference type, and the Type concept does not express that limit. We did not add a second concept for it. A value type that fills an &T is a wrong-kind argument like a reference type that reaches a value mould, so it is reported where the previous chapter already reports those, at the type’s origin (generics.md §3.6). The cost is that the narrowing is easy to miss: T Type reads as “any type”, and only the marker in front of it, not the concept, says that a value will be refused.
A type may not hold itself at a growing argument
An audit of the compiler turned up a declaration it could not finish compiling, and the spec did not state whether the declaration was legal:
type Grow<T Type> = variant { done Unit; more Grow<Array<T, 2>>; }
The boxing rule looks as though it covers this. more leads back to Grow, so it is boxed, and every type on the cycle has a finite size. But the cycle never comes back to the same type. Grow<Int> holds a Grow<Array<Int, 2>>, which holds a Grow<Array<Array<Int, 2>, 2>>, and each step is a type that has not been met before. Since a type is a templated function and each application is a concrete type with its own layout, the compiler has to produce every one of them before it can produce the first, and there is no last one.
Our first reaction was that this ought to work anyway. Every argument is a written-out type, and every value ends at done after a few levels, so the program never holds anything infinite. That is true of the values, and it is the same distinction adt.md §4 draws for sizes: the leaf terminates a value, not the type’s equation. A compiler that writes out a layout and the copy, move and drop code for each type, before any value exists, must prepare for every depth a value could reach, and here every depth is a new type.
The languages that accept this shape do so by not writing out types ahead of time. OCaml and Haskell, where it is called a nested datatype, give every instance one uniform representation, so one compiled function serves every T. C# and Swift build an instance’s type information while the program runs, and only for the depths a program actually reaches. Either road would have made Grow work, and either would have given up the fixed, compile-time layout that the rest of the language is built on. The languages that write out every instance, as Zane does, all reject it, and the choice left to us was when. C++ and Rust find out by instantiating until a depth limit runs out, and report the failure where the type is used, as a long chain of generated names. Go’s compiler recognizes growing instantiation as a shape and reports it as an instantiation cycle, without counting.
We took the shape check, at the declaration (generics.md §2.4). A type may lead back to itself any number of times, but each argument it passes back is one of its own parameters or names none of them. The wrong-kind chapter sent its error to the origin of a type argument, because the generic’s declaration was correct for every type that fit. Here the declaration is correct for no type at all, so the mistake lies in the declaration, and its author can fix it. Reporting at a use would also let a package publish such a type, compile cleanly, and fail only for whoever imported it. And a check that recognizes the shape needs no limit, so there is no number to choose and no program that fails only because it ran a little deeper than one.
The harder question was whether & fields count. A reference is an address, so a type’s layout and its copy, move and drop code stop at it. An & field that points at a growing type does not hang code generation the way an owning member does, and we came close to exempting it. We decided against that for three reasons. The compiler’s borrow checking follows references to the types behind them, so the exemption would have moved the endless chain from code generation into checking rather than removed it. An & is never empty (lifetimes.md §2.4), so a struct whose & field grows needs an existing value one level deeper before it can be built, and that one needs another: no value of it can ever exist, and only a growing reference inside a variant case could be built at all. And forbidding it now leaves room to allow it later, should a real use appear, without invalidating any program; allowing it now and forbidding it later would not. So the rule follows every member, & fields included, and stays one sentence with no exception in it.
The cost is a technique rather than a structure. Grow is how a perfectly balanced tree is encoded in its type, so that an unbalanced one cannot even be written. Zane writes that tree as an ordinary recursive type, which holds the same data and leaves the balancing to the code that builds it. The guarantee moves from the type into the code, and that is the whole of the cost.
List becomes a value, and ListRef takes the reference form
The container chapter made the one growable container a reference type, so that no value could hold one. That left the value world without a sequence whose length is not known when the program is written. A value struct describing a polygon, a word’s letters, or a row of a table could hold a fixed Array or nothing, and a type that needed more had to take a # it had no other use for: an identity nobody pointed at, a move where a copy was wanted, an owner where a plain value would have done. The one exception was String, which is a growable run of bytes underneath, and which had already crossed the line.
That crossing was the argument. When strings became values, in the text chapter, we had concluded that the size of a payload is not a reason for identity: a value can own out-of-line storage, and a deep copy gives the copy storage of its own. A list of values is the same case with elements in place of bytes. The deep-copy chapter had kept List out of values on the ground that a reference type exists in order not to be copied, and that ground still holds for a list of owners, whose elements have identity a copy would split. It does not hold for a list of Ints, which never had any.
We could have let the list’s side of the # axis follow its element, a value over values and a reference over owners, and we turned that down for the reason the ArrayRef chapter turned it down for Array: one name would stand for two constructs, and every reader of List<T> would have to find out which. We could also have made the list a value outright and dropped the reference form. That would have left no way to collect owners whose number changes, which is the common case for objects with identity, and an ArrayRef cannot grow. And we could have kept List as it was and given the value list a new name. The array pair had already settled the naming, though: the plain name is the value, and the Ref suffix is the same layout as a reference type. Following it moved the familiar word to the new side.
So @primitives$List<T> is now the dynamically sized value primitive, over a value T, and a copy copies every element (generics.md §8.3). The reference list it was is @primitives$ListRef<T>, unchanged in everything but its name: it takes each element through ^T, its elements are roaming, and none may be referenced (generics.md §8.5). The two share one layout and one runtime, so the compiler owns no second growth scheme. The ban on reference-type fields in a value did not move; it now names ListRef where it used to name List (memory.md §2.10). The program’s arguments, a list of strings nobody points into, became a value List<String>.
The costs are the costs String already pays, now paid by more types. Storing an existing list in another slot copies every element, and a list of strings copies every string, where a reference list would have moved one handle; a program that wants the move writes ListRef. The familiar name changed sides, so List<Engine> over a # type is now a wrong-kind error, and the program writes ListRef<Engine>. And generic code over “a growable run of T” has two containers to choose between, as it has two fixed ones.
A method’s subject may be a type parameter
Workers (the control-flow story) gave us a method no type could own. machine!work(step) should run on an interpreter’s machine, a game’s world or anything else that holds a worker’s state, and core declares none of those types. A subject could already be generic, as this List<T Type> is, but only inside a type that names it. A method on a subject of every type had no way to be written.
We weighed three ways round it before adding one. core could have shipped no wrapper at all, leaving programs to call @controlflow$work directly. That puts an intrinsic in every program and loses the subject call that makes a worker read as the subject’s own. Each type could declare its own work, which is the same four lines in every package that has a worker, all forwarding to the same intrinsic. Or core could declare a Worker<S Type> struct holding the state, with work an ordinary generic method on it. That form already existed. But the state would then live inside a Worker rather than as the programmer’s own Machine, and every read of it would go through the wrapper.
So a method may now introduce its subject’s type: this S Type makes the method apply to a subject of any type (generics.md §3.7). It is the inline introduction verbs already have, x T Type, written on the subject. It carries no passing marker, because the subject takes none. The body sees nothing about S beyond the signature, so it can only pass the subject on. That is all work needs, and Zane has no constraints that would let a body do more.
The harder question was how a call finds such a method. Method lookup searches the subject type’s home package, then the current package, so that an unqualified call resolves the same way wherever it is written. A method declared for every type is beside no subject type, so no home reaches it. We could have searched core always, but that would have made core privileged in exactly the way it was made ordinary to avoid. We could have searched every package the file imports, in whatever form, but then an import would affect method lookup in general, which is the rule we had kept imports out of. What we took is narrower: such a method is reached by its plain name, as a function is. It is the third step of lookup, searched only when the subject’s own type and the current package have no candidate, and it finds the methods for any type that the file’s imports spell bare (functions.md §6.1). import core$ brings work as it brings if. A file that imports core qualified writes machine!core$work(...). A method declared for the subject’s own type always wins.
That made one sentence of the packages chapter false. Methods were not importable members, because none was reached by a plain name. A method for every type is, so an import may now bring it by name (packages.md §3.6). Every other method still is not importable.
The cost is a lookup step whose answer depends on imports, which method lookup never had. We accepted it because the step only ever applies to methods that no type could have owned, and imports already affect the functions they resemble in the same way. The first two steps still resolve the way they always did.
A function type’s slot may introduce a type parameter
core wraps every ArrayRef constructor the compiler has except fill. The others take an array literal, and ArrayRef<T, n>.roaming(values @concepts$Array<^T Type, n @concepts$Int>) introduces T inside the literal’s type. fill takes a lambda, ArrayRef.fill(100, ^Enemy(i Int) => Enemy(i)), and the only place a wrapper could introduce T was the return of that lambda’s type, make ^T[Int]. A function type had no form for an introduction, so core could not declare the wrapper, and the example in the spec could not be written against core at all.
We weighed two ways round it. The caller could name the element type, ArrayRef.fill(Enemy, 100, ^Enemy(i Int) => Enemy(i)), as an explicit parameter is passed. That repeats a type the lambda already carries, and it makes fill the one ArrayRef constructor whose element type is not read off its argument. Or the wrapper could take a lambda over the primitives, ^T[@primitives$I64], which puts an intrinsic type in every program that fills an array.
What we took is the form verbs already use. A slot of a value parameter’s function type may introduce a type parameter, written as a value parameter’s own type writes one: T Type, ^T Type or &T Type (generics.md §3.2, syntax.md §2.13). The marker needed no new meaning. A function type’s slots already carry passing modes, so the marker on an introduction there is that slot’s mode, as the marker on a parameter’s own type is that parameter’s. A nested introduction inside a type argument stays bare, because no type argument is passed.
The parameter belongs to the verb whose signature the function type is written in. That was the line to hold, because a function value that is itself generic is still unspecified (the deferred list). ArrayRef.fill is generic, and the lambda passed to it is not: ^Enemy(i Int) => Enemy(i) has one type, and the compiler reads T off it as it reads T off any argument.
The lambda’s own parameter raised the second question. The compiler calls it with each position as an @primitives$I64, and a program’s lambda takes core’s Int. A call cannot write a conversion of a function value’s parameter, any more than of its result. A worker’s step had already met this problem from the other side: its result reaches @primitives$Bool through the implicit constructor its type declares. fill now does the same in the other direction (generics.md §8.4). The lambda takes the position as @primitives$I64 or as any type with an implicit constructor from it, and each position reaches the lambda through that constructor. core now declares that constructor for Int, so i Int is accepted as written.
The list primitives’ operations are specified, and a position outside a list stops the program
The deferred chapter left two gaps that core had filled in practice long before the spec did. The lists’ operations were open, and so was the behaviour at a position outside a container, yet core had written its List and ListRef over push, size, remove and swapRemove from the start, and the LangArena work had added the range operations its regex package needed: appendRange, appendOwn, copyRange, sameRange, hashRange, sort, sortBy and text. Each is an intrinsic because core could not write it, or could not write it fast enough, from the primitives alone. So we specified all of them, with the subscripts and the two list constructors, in one place (generics.md §8.6).
For the bounds we took the rule the compiler already followed. A position outside its container, and a range that does not lie in its list, stops the program, as a call that nests too deep does; a stop is not an abort, so no handler can catch it (control-flow.md §5.2). A range of no elements may start just past the end, at the position the next element would take.
The range operations work on raw storage: one copy, one comparison or one hash over the elements’ bytes. That limits the element types each accepts, and we had two ways to state the limit. The narrower option was a signature per type, sort over @primitives$List<@primitives$I64> and its siblings. It fails on core’s own lists: core’s Int is a struct around an @primitives$I64, so a List<Int> holds a primitive list of Int and would match none of those signatures. So each operation stays generic, and the spec lists the element types each accepts, counting a struct whose only field is one of them as that type (generics.md §8.6). The cost is that a wrong element type is refused only once the generic call is instantiated, rather than at the signature, as the deferred chapter already records for every generic.
Writing the rules down settled two details and caught two bugs. sameRange had given an @primitives$I64 of 1 or 0, as the runtime’s comparison returns it; a comparison gives a truth value, so it now gives an @primitives$Bool. And the compiler disagreed with the rule twice: the copying operations rejected enums and every element holding a Unit, none of which owns a block, and sortBy skipped its position check for a list of one element. Both now follow the rule.
Only verbs reach a veiled value
The spec had never stated the operations a generic body may apply to a value of type T. The subject chapter stated that a body could only pass its subject on, while zanec checked each instance the way a C++ template is checked, so x:level() compiled whenever every caller’s type had a level, and so did x.value whenever every caller’s type had a value field. We noticed the gap while designing a plugin library that takes its plugin’s types as package parameters and calls methods on them. Asking which of those calls were legal showed that the spec had no answer.
Methods and functions clearly had to work, since they are how a library talks to a type it has never seen. Field access was the open question, and we decided against it. A field is representation and a verb is behaviour. If a generic body could read x.value, every type that fills T would need a public field of that name and type, and the type’s package could no longer rename it, compute it, or make it private with _ (types.md §2.3) without breaking a generic it never heard of. A method leaves all of those choices with the package that owns the type. Fields also exist only on product moulds, while every mould can declare verbs, so a body written against verbs accepts a variant or an enum exactly as it accepts a struct. Constructors for every mould closed the last gap in that claim. The same reasoning excludes the other uses that depend on a type’s shape: an enum map read, naming an enum member through the parameter, a match, and calling the value as a function value. A case name needed no rule of its own: T.done(...) has the spelling of a named constructor, and a named constructor’s name differs from every case, so the call always looks for a constructor and fails at instantiation when the type has none (generics.md §3.8).
Functions turned out narrower than methods. A body can call util$clamp(x) because its file imports util, but it cannot call a function from the type argument’s own package, because the body was written before that package existed and cannot import it. We considered a qualifier for “the function f in T’s home package” and found the language already has one: x:f() searches the home package of x’s type first. So a generic expects methods, operators and constructors from its type arguments, and takes functions only from its own package and its imports.
We kept the rule apart from how a compiler checks it. It fixes the operations a body may apply to T; checking each instance stays allowed, and so do a future constraint system and dictionary passing for generic function values. Under the rule a constraint becomes a list of verb signatures, and a dictionary needs one entry per verb and never a type’s field layout. One check does move earlier: a field read on a value of type T is wrong for every type argument, so the compiler reports it where the body writes it, even when nothing instantiates the body.
The rule needed a name for the values it covers, which include a parameter x T Type, a this S Type subject, a local of type T, and a T read out of a Box<T>. The working name was “generic value”, but “generic” already describes a declaration with type parameters, not a value. We passed over “opaque value”, because the spec already uses “opaque” for the C object behind a foreign handle, a type whose layout is hidden from every program forever. A value of type T is hidden only from the body, and only until a caller supplies the type. “Guided value” pictured the type argument steering the body, but it put the guidance on the value and conveyed nothing about the restriction. “Stand-in value” and “parametric value”, the type-theory word, were also candidates. We chose veiled value. A veiled object is whole and present, but its face is hidden; the body handles the value without seeing its type, and the caller always sees it. An error such as “cannot read a field of a veiled value” then explains itself.
The cost falls on a type’s package. A generic that needs a field’s value needs the package to declare a one-line method, Float level(this Knob) => this.value;, where the generic could otherwise have read the field directly. We accepted that cost, because the method is the part of the type that its package has promised to keep.