Stories: Effect Model
See also:
spec/effects.md— the rules these chapters explain.
Inferring effects instead of naming them
Every language that takes effects seriously has to answer one question first: who states a function’s effects — the author, or the compiler? The well-trodden road is to make the author say it, in a vocabulary built for the purpose. Haskell threads effects through the type as monads; Koka and the effect-system languages put an effect row on every arrow; even the modest version, a pure/readonly/io keyword the programmer sprinkles on declarations, is the same move — the signature carries a hand-written claim about side effects, and the compiler’s job is to check the claim rather than discover the fact. We turned that whole family down. An effect annotation is exactly the kind of declaration the foundations bet argues a good language should not need the programmer to write: it is a proof obligation bolted onto the signature, a second language to learn beside the first, and — worst for a language that prizes a rule you can read — it can lie by omission or staleness, drifting out of step with the body it describes until the annotation records one behaviour and the code performs another.
The resolution is to let the compiler infer the effect level structurally, from facts it already has, and give the user a single modifier — mut — and nothing else (effects.md §1). There are no purity keywords to write, no effect rows to thread, no capability qualifiers in signatures. A function’s classification falls out of two facts the compiler can see without help: its body’s effect on the ownership graph, and the classifications of the functions it calls (§3). This is the verifiability symmetry cashed out for effects: an effect is a local, structural property — does this body write this, does it touch a capability, does it call a function that does — and a checker confirms exactly such local structural facts cheaply and a reader confirms by looking. Nothing is gained by making the human transcribe a fact the compiler can read straight off the call graph.
The cost is the honest cost for any inference that has to stay sound across a boundary it cannot see through: it must be conservative at the edges. When the compiler cannot prove a callee’s effects — an opaque or not-yet-analyzed function — it has no annotation to fall back on, so it must apply the strongest effect level that keeps the program safe (§5.4). An annotation system can let an author promise purity across such a boundary; we cannot, because we refused the vocabulary in which that promise would be written. We judged that a good trade: the cases where a programmer would want to assert an effect the compiler can’t see are rare, and letting them assert it is exactly the channel through which annotations go stale and lie. Better a compiler that occasionally over-classifies a call it can’t see into than a signature that can quietly contradict its body.
Where mutation is allowed to reach
Inference can only read mutation off the call graph if the language has first pinned down what mutation is and where it may happen — and that rule did not begin as a rule about effects at all. It began as a plain wish: to know what a function mutates. If the compiler and the reader could both see exactly which state a call might change, most of what the effect model wants — parallelism, reorderability, a legible call site — would follow. So the first decision was that mutation should be tracked, and the second fell straight out of how defaults behave. Tracking only pays off if the common case is the annotated case, and if you make immutability the property you opt into — marking the read-only parameters — no one ever will: the annotation you must remember in order to earn a guarantee is the annotation that gets skipped, and the guarantee quietly evaporates. So mutation had to be opt-in. A function states when it may write; without that statement it may not.
Opt-in mutation, taken at face value, requires a mut marker on every parameter a function intends to change — f(mut a, b, mut c). That works, and it shows its cost immediately: signatures bloat. Every mutation point in the program sprouts a marker in a parameter list, and declarations that should read as intent start reading as bookkeeping. That irritation prompted the question that actually cracked the design open: do you ever genuinely need to mutate two parameters at once? Walking through the examples one at a time, the answer kept coming back no. Every case that looked like it needed two mutable parameters could be expressed with one — sometimes by splitting the work across two calls, sometimes by gathering the objects-to-be-changed inside a single wrapper object that then became the one mutated object. Two mutable parameters was a generality that practice never cashed in.
That observation met a second question being chewed over at the same time: whether Zane should support object-orientation at all, OOP being controversial enough to owe a why before an inclusion. So — what is OOP actually for? Stripped down, it is for mutating objects. A player that switches to a different weapon is the canonical case, and the canonical answer is a Player class with methods that change it. Mutation and OOP were not two features competing for room; they were one need wearing two hats. And that is where the threads fused into a single restriction: if you never need more than one mutable object per operation, and OOP exists to mutate an object, then let methods be the only place mutation is opted into, and let a method mutate only this — the one object it was called on. The single mutable parameter the examples always needed is the receiver, and it never has to appear in a parameter list, because the call already names it before the dot.
This is why the spec’s mut is a property of a method, granting write access to this and its owned subtree and nothing else (effects.md §2.3), and why every other parameter is read-only (§2.4). One restriction stands in for three wishes at once: mutation stays tracked (opt-in, on the method), signatures stay short (the mutable object is the receiver, never an annotated parameter), and OOP earns its keep by being defined as the mechanism for controlled mutation rather than bolted on for its own sake. Changing another object is still available — you call a mut method on it, making it the receiver of its own change (§4.2) — so nothing is lost; it is only ever phrased as one writable object per call. The lone exception proves the shape of the rule: a value-like number parameter can be declared mut, because a value is a private copy that cannot alias anything, so writing it changes nothing anyone else can observe (§2.4).
The cost is the cost the example-walk already hinted at: the rare operation that really is symmetric in two objects — swap their contents, settle a transaction between two accounts — cannot be written as a single call that mutates both. It has to be restructured into two calls, or the two objects gathered under a wrapper that becomes the single receiver. That is a genuine expressive narrowing, accepted on the evidence that the cases needing it are rare and the restructuring is mechanical. What it buys is large and out of proportion to the cost: exactly one writable object per call site, known from the syntax without reading a signature — the fact the concurrency rules lean on to run mut calls on different receivers in parallel, and the fact a reader leans on to know at a glance the most a call could disturb. A safety bonus falls out for free — with only one mutable path per call there are never two mutable handles to one object to alias, so the write–write aliasing that pushes other languages toward a borrow checker simply cannot arise — but that is a consequence of the restriction, not the reason it was chosen.
No ambient I/O: effects you can see in the structure
Receiver-scoped mut covers writes to a program’s own state, but it covers nothing of the other kind of effect — the filesystem, the socket, the clock, the logger, the world outside the program. Here the universal convenience is ambient authority: a global print, a module-level logger, an IO you can reach from anywhere. It reads beautifully at the call site, and that is precisely the problem. Ambient I/O is an effect the source does not show — a function that secretly writes a file looks, in its signature and its caller, identical to one that does not. For a language whose whole wager is that intent should be captured in the structure rather than reconstructed by a runtime, an effect you cannot see in the structure is a contradiction in terms.
So the language has no ambient global I/O at all. External state is reachable only through a capability — an ordinary object whose methods model access to some piece of the outside world — and a capability is reachable only if it was explicitly passed in or stored (effects.md §6.1). There is no back door: constructor injection records an explicit ownership path to a capability rather than conjuring ambient authority, and a “context object” that bundles several capabilities is just another ordinary object in the ownership graph — it may cut a parameter list down, but it hides nothing, because the capabilities it carries are still reachable only through visible storage and call structure. The consequence the spec is willing to state outright is that prop drilling is intentional (§6.5): threading a capability down through constructors and method calls is not a wart to be designed away with a global, it is the mechanism by which an effect stays visible in the shape of the program.
The cost is exactly the ergonomic tax that ambient authority exists to dodge, and we are choosing to pay it: more parameters, more wiring, the logger that has to be handed down four call frames to reach the place that logs. We considered the usual softeners — an implicit context, a thread-local — and rejected them on the same ground each time: every one of them buys brevity by making an effect reachable without the source showing it, which is precisely the hidden reach the model exists to prevent. The capability that has to be passed is annoying to pass and, for that very reason, impossible to overlook — and that legibility makes the inference of the previous chapters trustworthy, since a function’s reachable effects are all there in its parameters and fields, with nothing ambient leaking in from the side.
Four levels, and the line between terminating and merely pure
With mutation and capabilities pinned down, the compiler can see, for any function, its strongest effect: nothing observable, a capability read, a capability or receiver write. The question that remains is how finely to grade that — and the tempting answer is the coarse answer, a single pure/impure split, because two buckets are the least machinery that could distinguish a reorderable function from one that is not. We graded more finely than that, into four levels, because two of the payoffs we wanted draw the line in two different places (effects.md §3). One payoff is automatic parallelism — the strictness-buys-speed bargain spent on effects: code that writes no shared mutable state can be reordered and run in parallel, and that needs only the line between “writes nothing observable” and “writes something.” The other payoff is compile-time evaluation, and it needs a sharper line, because running a function at compile time is only safe if the function is guaranteed to finish.
That second requirement is what splits the top of the ladder in two. Total Pure functions depend only on parameters and immutable constants and are guaranteed to terminate for all inputs; Pure functions have no side effects either, but carry no proof of termination (§3.1, §3.2). Both are equally safe to parallelize — neither writes anything — so a pure/impure split would happily merge them. But only Total Pure is safe to evaluate at compile time, because evaluating a merely-Pure function might never return and hang the compiler. Below them sit Read-Only Impure (reads capabilities, writes nothing) and Write Impure (mutates the receiver or the outside world), which grade the impure half by whether concurrent reads can still compose with the single-writer rule. Four levels, then, not as taxonomy for its own sake but because parallelism and compile-time evaluation each need a cut, and the cuts do not coincide.
The cost is inherited from a theorem rather than chosen: termination is undecidable, so the Total Pure tier can only ever be conservatively recognized — the compiler admits a function to it via rules it can actually check, and some genuinely-terminating functions will fail those rules and be classified merely Pure, losing compile-time evaluation they could in principle have had. We took that without much agonizing, because it is the only honest option: the alternative is to either promise compile-time evaluation the compiler cannot guarantee will halt, or to make the author assert termination by hand — another annotation, which we refused for the reasons the first chapter gives. A conservative Total Pure tier is the price of getting compile-time evaluation soundly and without a vocabulary.
Memory machinery is deliberately not an effect
The last pressure runs the opposite way from the others. The memory model the effect system is built on top of is busy underneath — it allocates, it destroys deterministically when a scope drains, it mints anchors, it can abort and unwind. The danger is that all that machinery leaks upward into the effect classification and drags otherwise-pure code into an impure tier for reasons that have nothing to do with what the programmer wrote. A function that builds a small object, reads two fields, and returns a number is, to any reader, pure — and if the mere fact that it allocated a value forced it out of the pure levels, the classification would have stopped tracking intent and started tracking implementation incident.
So the model draws an explicit line around the behaviour that is not an effect. Heap allocation and deterministic destruction are runtime implementation events, not side effects for classification purposes; a function stays in the pure levels unless it also writes owned state or touches a capability (effects.md §7.2). Constructors, by the same logic, may allocate freely yet are not mut, because creating a fresh value is not mutating an existing receiver (§7.1). And abortability is held fully orthogonal: a function’s abort type and its effect level are independent axes, so an abortable function may be Total Pure or Write Impure depending only on its other behaviour (§7.3) — the error-handling model and the effect model are kept from contaminating each other on purpose.
Mutation through a borrowed receiver
mut began life bound to one kind: only a class receiver could carry it, because a class was the only type with a stable identity to write, and a struct handed to a method was a copy whose mutations the caller would never see. The where mutation is allowed to reach chapter took that as given. When the type system collapsed into a single value/reference axis (the foundations story records that arc), the restriction became the odd rule out: with struct now the value product and #struct the reference one, tying mut to “reference receiver” would have left every value type stuck with the return-a-replacement dance for even a one-field update.
The reframing that freed it is that value types are passed as borrows — the callee is handed the caller’s actual storage, not a fresh copy — of which a mut receiver is simply the writable borrow; the rest are read-only (effects.md §2.3, memory.md §2.9). Once a mutation writes the caller’s actual slot rather than a copy, the reason value types could not be mutated evaporates — the write lands where the caller can see it — so mut applies to a value or a reference receiver alike (a reference receiver reaches its object as an implicit &, not a borrow — borrowing is the value world’s device), and the effect classification is the same for both: a write to owned state is Write Impure however the receiver is spelled. The old “returns a replacement” rule (§4.2) simply went away, because it had only ever been a workaround for the copy.
The cost the borrow does not impose is worth recording. One might expect that making a value’s receiver a live reference would reopen aliasing — the very hazard the value world is closed to avoid. It does not, because the borrow is non-escaping: it may be read and written but never stored as an & or returned as one, so it cannot outlive the call that created it. The effect system therefore gains in-place value mutation without gaining a new route for state to be aliased, and the concurrency layer above it can keep treating “value type” as a synonym for “alias-free” (concurrency.md §4.2). The whole change is one idea — value types are passed as borrows, the receiver being the writable borrow — and its value is measured by how little else had to move.
This is one of the places where the honest account is that the decision cost almost nothing. There is no expressiveness given up, no pattern forbidden; the rule only declines to count machinery the memory and error models already pay for as a second time against the effect tier. If it carries a cost at all it is a conceptual one — a reader has to hold the slightly counterintuitive fact that a function which obviously does work at runtime (allocates, destroys, may unwind) can still be Total Pure — and that small surprise is a far better deal than the alternative, in which the effect levels would track the runtime’s bookkeeping instead of the program’s meaning, and almost nothing would be classifiable as pure at all.
Where the first capability comes from
No ambient I/O settled that a capability reaches code only by being passed or stored, and never stated where the first capability comes from. Two passages in the spec showed the gap. The examples printed with a bare print(...), an ambient console the model forbids. And the thread pool was configured by @threads(8), the one use of @ that was neither an intrinsic namespace nor defined anywhere in the grammar — a directive setting whole-program state with no object behind it at all.
The directive went first, and not to a manifest field, although that is where whole-program configuration usually lives. A manifest fixes a number at build time, and a program sometimes has to choose a thread count while it runs. A call was the only shape that could take a value computed at runtime. We had expected the call to need rules about when it may be made, since a pool size looks like a setting that must be settled before any work starts. It needs none: parallelism the compiler schedules is allowed to change only timing, never results (concurrency.md §2.2), and spawned work may already depend on scheduling at any pool size, so resizing the pool mid-run makes no result possible that was not possible before. For the same reason the fixed and automatic forms became two methods, setThreads and setThreadsAuto, rather than one taking a count or the string "auto". A magic string is a typo waiting for a special case, and an intrinsic with one signature is simpler to implement than one the compiler must resolve among overloads — which became the rule for every intrinsic operation. A count below one aborts the call rather than being clamped: asking for no threads is a mistake, and an abort surfaces it where it was made. That made setThreads the first intrinsic with an abort type, and an intrinsic may name no package’s Unit, so the compiler gained its own, @primitives$Unit, which core’s Unit wraps like every other primitive. Methods stay the exception, since a method’s subject is a parameter and two intrinsic types may each have a method of the same name.
Free-standing intrinsics would have left the call reachable from every package, and a library three dependencies deep could have retuned the pool for everyone. That pointed at the better shape: the runtime is an object, the thread count is a method on it, and the console is the same kind of object with print as a method. Both are capabilities in exactly the sense this file already used. We made them reference types. A program has one console and one runtime, every part of it that uses either uses that single instance, and a copy of the console would be a strange value to hold. Neither can be constructed; the compiler creates the only instances when the program starts.
That left who may reach them. The convenient answer was every package, the way C++ offers cout to anyone. It would not have made the effect model unsound — the compiler infers a function’s effects from its body and everything it calls, so it still classifies a printing function as impure. What it loses is the reader: a function that prints would look, in its signature, exactly like one that does not, which is the very opacity we refused in the earlier chapter. So the types, @runtime$Console and @runtime$Runtime, are visible to every package, and their instances, @program$console and @program$runtime, are visible only to the root package (effects.md §6.6). Every other package gets them by being passed them, so its signatures show them. The instances got a namespace of their own because they were the outliers: the types and their methods are ordinary intrinsics, found through their home like any type’s methods, and only the instances needed a narrower reach. We named it @program$ for its members — the running program’s own console and runtime. @private$ was the first name to hand, but it names who may look rather than the namespace’s contents, and the language already uses privacy for _-prefixed members.
The root package needed a term as well, because the spec had none: dependencies.md used “top-level project” once, and “home package” already means the package that declares a type. “Project package” said nothing, since every package is some project’s package, including a library consumed three levels down. “Entry package” named the package by its main, and a library project may have no main at all. “Root” is the word the dependency graph already supplies, and it is relative to the build rather than to the package (packages.md §6.1): a library built or tested on its own is the root of that build and can reach its console, and the same library consumed by an application cannot. main lives in any file of the root package and takes no parameters, since the root package already reaches what a parameter would have delivered. The console a program prints through is std’s, not core’s — core holds the language’s core types, the way C++ keeps cout in its standard library rather than in the language.
The cost falls on the root package. Code there reaches the console directly, anywhere in the package, without passing it, so inside the application’s own package the structure no longer shows where printing happens. We accepted that because the root package is the one package whose author is also the author of the program: the libraries it uses stay honest, and those are the signatures a reader cannot otherwise check. The other cost is a line in every program that prints — building a std Console from @program$console — and a convention that every printing example presupposes that line.
A mutating call is a write
The question that reopened this was small: the section on effect levels read as though the compiler had to discover whether a function writes, when mut sits right there in the signature. Pulling on that thread turned up a larger problem. The rule that mutation reaches only this had been stated as “parameters are read-only”, and read-only had quietly narrowed to a ban on assigning a parameter. Nothing stopped a function from calling a mut method on one. log(console, msg) could print through its console parameter, and the call site showed no ! at all. The concurrency rules had already tripped over the same hole from the other side and fenced it off by making such verbs unspawnable — which treated a function that writes its parameters as a legitimate kind of verb with one restriction, rather than as the leak it was.
We did not want a special case banning ! on parameters, because there was nothing special to ban. A mut method writes its subject; calling one on a place writes that place, exactly as an assignment does. Read-only was always meant as the umbrella — a read-only binding admits no write — and a ! call is simply the second way of writing, so it falls under the umbrella with no rule of its own (effects.md §4.1). The value-like number parameter, which the earlier chapter let be declared mut as the one exception, went with it: a parameter is read-only, with no marker that changes that.
Stating the umbrella exposed the second half of the problem. A guest parameter is not the object; it names the caller’s object, and a guest can be copied. Bind it to a local, or hand it to a constructor that stores it in an & field, and the local or the new object is the verb’s own — writable — while still naming the caller’s console. Banning ! on the parameter’s name would have closed the front door and left the side door open one line below it. So read-only had to follow the guest rather than the name: a guest derived from a read-only binding stays read-only wherever it goes, and a ! call whose subject reaches one is an error (§4.4). This needed no new machinery in the source. The compiler already records, for lifetimes, where each parameter comes to rest and substitutes the caller’s argument paths at every call (lifetimes.md §1.11); writability rides on the same record. That substitution is also what keeps ordinary wiring working: a Car handed its caller’s own Engine can still tune it, while one handed an engine the caller itself only borrowed cannot.
We chose the conservative form of the check: a mut method is assumed to write through every guest its subject reaches. The precise alternative — recording in each signature which guests a mut method actually writes — would reject fewer programs, but it makes signatures carry a second summary for a gain we had no example of needing, and a conservative rule can be relaxed later without making any accepted program illegal.
With the leak closed, the unspawnable rule had nothing left to catch, and the spawn check went back to inspecting only the subject (concurrency.md §4.2).
The same closure is what finished off the four-level ladder. Once a callee can write only through its own this, and a caller supplies that this only with a ! on a place it may itself write, the question the ladder was graded around — what can this call write? — is answered by the signature before the body is read. There are exactly three answers, one per kind of verb: a mut method writes this and what it reaches, and a method without mut or a function writes nothing its caller can see (effects.md §3). Looked at from there, the four levels were a taxonomy laid over the language rather than part of it. No programmer writes one, no rule was stated in terms of one except the compiler’s own optimizations, and they graded the call by facts that the kind of verb already fixed for the most part. What the ladder did carry that the kinds of verb do not — whether a call touches a capability, and whether it terminates — is real, but it is the compiler’s bookkeeping for deciding what to fold at compile time and what to run in parallel, so it stays as two derived facts with no names and no tiers (§5.2). Termination, which the ladder had described only as “conservatively recognized”, now has the concrete rule the control-flow design made available: every repetition carries a count, so a verb terminates when no call path leads back to it.
The root package spoils the neatness in one place, and we left it visible rather than hiding it. Code there reaches the program’s console and runtime directly, so a function in the root package can print, and a spawned one can write an object other spawned work may be reading. The concurrency rules name that as the one exception to “spawned work never mutates a reference type”, and route it through the serialization every capability access already gets (concurrency.md §4.2).
The cost is that writing to a capability became a mut operation all the way up. Outside the root package, a function that wants to print can no longer take the console as an argument; the console has to be this, or be reached through this of a mut method, so every layer between the root package and the print is a ! call. That is heavier prop drilling than the capability chapter signed up for, and we accepted it because it is the same bargain made one step more honest: a write is now visible at every call site it passes through, not just at the call site that happens to hold the console. The conservative check adds a smaller cost of its own — it will reject a ! call whose method never touches the read-only guest it could reach. Dropping the ladder costs a vocabulary: there is no longer a one-word name for a call the compiler may fold at compile time, so a rule that needs one has to spell out the three conditions. We judged that fair, since only the compiler ever asked the question.
Compile-time evaluation needs no termination proof and sits beside capability access
The rule for compile-time evaluation was written long before anything performed it. It was what the four-level ladder left behind once the kinds of verb replaced it: a call with known inputs was evaluated at compile time when it wrote nothing its caller could see, touched no capability-backed state, and terminated (concurrency.md §2.1). Each condition looked like a safety requirement, and none had been tested against an implementation. When we set out to build the evaluator in the compiler, they came apart one at a time, and each for a different reason.
Termination went first, because the compiler had no use for the answer. A proof that a verb terminates is a claim about every input it could ever receive, and recursion fails it outright, even when the call actually in front of the compiler finishes in a few steps. A verb that really does run forever on some inputs still holds plenty of code whose inputs are known. Neither of those is the question for evaluation, which is whether this computation finishes. So the compiler stopped asking for a proof: it evaluates from the leaves up, spends a bounded amount of work on each computation, and leaves whatever does not finish for run time. Once nothing consulted termination, it stopped being a derived fact, and capability access was left as the only derived fact.
The capability condition went next, because it was drawn too wide. It kept a whole call at run time because a statement inside it printed, and what printing actually threatens is narrower than that. A program cannot tell whether a computation ran early so long as everything it outputs still appears at the same point and in the same order, so an output can be made again where the computation was. A read cannot be made early, because only the running program has a line from the console or the time. The line that matters is between computations that depend on such a read and those that do not. A write through a mut call’s subject went the same way as an output: it is part of what the computation produces, and the replacement makes it. That split reads from writes, which the one fact “touches capability-backed state” could not express, so the compiler now derives the two separately: evaluation considers only reads, parallelism both (§5.2).
Our first draft wrote all of that into the spec, in concurrency.md where the old rule had lived: evaluation from the leaves up, the work bound, outputs made again in order. Read back, it was a specification of a compiler, and it sat in a document about concurrency, which compile-time evaluation is not. Our first instinct was to take it out of the spec altogether. Nothing about it can be observed, so a sentence permitting the compiler to change how a program runs but never what it computes would have covered it, with the design kept in the compiler’s own documents.
What stopped us was implicit parallelism, which is just as unobservable and which we would never take out. Almost no language runs a program’s independent work in parallel without being asked to, and Zane can because of its effect model: the kind of verb fixes what a verb may write, and capabilities are explicit, so the compiler proves independence rather than guesses at it. Compile-time evaluation rests on the same ground. A verb receives what it works with through its parameters and through capabilities, so the compiler can tell exactly which computations depend on neither. Behaviour that follows from the language’s rules in this way is part of the language’s definition, even when it is the compiler that carries it out.
So we drew the line between the possibilities a rule creates and a compiler’s use of them. The spec states compile-time evaluation directly after capability access, the rule it rests on: which computations may be evaluated at compile time, and that doing so changes none of the program’s side effects and nothing it computes (§5.3). The leaves, the bound, and outputs made again belong to the compiler. Implicit parallelism stays in concurrency.md, as one half of the split between parallelism and spawn that the concurrency story opens with, and lost only its link to compile-time evaluation (concurrency.md §2.1). We wrote the line into the spec guide so the next behaviour of this kind lands in the same place, with one qualification we care about as much as the rule: not every compiler behaviour belongs in the spec, only one that shows what the rule before it buys.
The cost is that the spec no longer states how much a compiler evaluates. The old rule could be checked against a signature and a call graph; now two programs that look alike may be evaluated differently, depending on how much work each takes and on a bound the spec does not fix. We accepted that because the program cannot tell, and because a promise about how much gets folded would have been a promise about one compiler. The guide’s qualification costs judgement where a rule would have been easier: whether a compiler behaviour shows what its rule buys is a call each change has to make.
The console moves into core
Where the first capability comes from put the Console a program prints through in std, on the model of C++, which keeps cout in its standard library rather than in the language. core was to hold the language’s core types and std everything built on them. That plan was made before either package was written, and it did not survive writing core.
What changed it was field privacy moving to the package. A _ field is now reachable only in the package that declares its type (types.md §2.3), and core’s String holds its text in a private _value over @primitives$String. Printing is one of the operations on that representation. The console’s own method takes the primitive, so a Console that takes a String has to reach inside it. The same is true of joining two strings, comparing them, and building one from an Int, and privacy had already put all of those in core, because only core can reach the field. A Console in std would have been the one verb on text outside the package that owns text, able to reach only what core chose to make public. The same held for anything else std was meant to hold that works on a fundamental type’s representation.
So we did not split the library at all. core declares the Console beside String (effects.md §6.6), and there is no std: its intended contents belong to core. The line between the two packages had been drawn by audience, with the language’s types on one side and the conveniences built on them on the other. Privacy draws it by representation, and on that line the console and the string fall on the same side. The C++ comparison never pointed the other way either: its std::string and its cout sit in one library.
The cost is that core is no longer small. “Core” now names the library every program starts from, not the handful of types the language leans on, and everything in it is versioned as one package, so a project that wants a newer Console takes a newer Int with it. Side-by-side versions and remapping soften that, as they do for any package, but they do not remove it. We accepted it because the alternative was a second package whose most basic operations depended on the declarations the first package made public.
arguments becomes the first read of capability-backed state
Once the compiler could run a program, we wanted to know how fast what it builds actually runs, measured against the same programs in other compiled languages. The first benchmark we sketched could not be measured. A benchmark is a computation with no input: a fixed problem size, a loop, a printed result. That is exactly what compile-time evaluation is for, so an optimized build did the work while it compiled, and the program that ran only printed the answer. The rule that marks where evaluation stops was already in place: a computation that depends on a read of capability-backed state is left for run time (effects.md §5.3). The benchmark lacked a read. The console could only be written and the runtime only configured, so no Zane program could depend on anything but its own source, and the compiler’s class of operations that stop a fold had no members at all.
We did not want to get around it. Measuring unoptimized builds would have compared Zane with its evaluation switched off against other compilers with theirs on. Hiding the size behind a construct the evaluator happens not to see through would have measured a trick, and the next compiler release could see through it. The evaluation is a real optimization, and a benchmark of a program it can finish should show that. What a benchmark also needs is a program it cannot finish, and that takes an input.
So the question was which input comes first. A line read from the console, the time, and a random number were all candidates, and programs will need all of them. We started with the command-line arguments, because they are the most basic input a program has: every system passes them, a program receives them before it does anything else, and they are how one program is run on different problems without being rebuilt. They describe how the program was started rather than what it prints to, so they are a method of the runtime, not of the console (effects.md §6.6). The method gives all of them at once, as a fresh list, rather than one at a time by index. A lookup by index would have had to abort when the index ran past the end, and every caller would have carried a handler for a case a list’s size already answers. Like every runtime method it is stated over storage primitives, so the list holds @primitives$String, and core wraps it in its own types the way it wraps the console.
Calling it is a : call, a read, so it changes nothing about what the caller may write, and any verb that reaches the runtime may make it. That is the whole of its effect on the effect model. Its effect on evaluation is the point: everything computed before the read can still be computed at compile time, and everything that depends on what it returns runs when the program does.
The cost is that a Zane program’s output can now depend on how it was started, which was not true before. Until now an optimized build could in principle compute a whole program, and that is no longer guaranteed of any program that reads its arguments. The text is also the system’s, not ours. Where the system passes arguments as bytes, the strings hold those bytes unchanged, and nothing guarantees they are valid UTF-8; where it passes UTF-16, they are converted. We took that over checking and rejecting arguments a program never asked to be checked, but as a result a string from arguments is the one string a program did not write that may not be text.
comptime marks a call, not a scope
The request for explicit compile-time evaluation arrived together with a second one, and for a while we took them for the same request. One was a marker for “evaluate this at compile time” and have the build fail if that could not be done. The other was a means of running a large number of peer workers, a hundred request handlers say, which spawn could not express. A shared shape seemed to join them. Both appeared to need a scope that does not drain. A compile-time block that computed a few values for the code after it to use at run time would have to leave its bindings behind when it ended, and a loop that spawned a worker on each pass would have to leave its workers running past each pass. So the first sketch was a leaky scope, a bracketed run of statements whose declarations outlived it, with comptime as one keyword that took one and a parallel loop as another.
Pulling the two apart is what this chapter records, because the shape was shared and the mechanism was not. Nothing from the compile-time stage is alive when the program starts, so a compile-time scope has nothing to drain. What it needs is for values to flow in one direction, from the build into the binary. A block whose every declaration leaks into the enclosing scope is also no longer a scope: it is a label saying which stage some statements run in, and a label is stated more simply on the call it labels. Leaky bindings at run time would have cut across the lifetime rules besides, which restrict a move to its declaration block and destroy each object at a known point (lifetimes.md §1.3). The workers went their own way, into the concurrency story, and what was left here was a marker.
The marker could have gone on a statement, comptime content String = …, or on a call. We put it on the call: content String = comptime readNotes(files, "notes.txt"). A statement form covers only declarations and invents questions a call form never meets, such as what comptime console!print(…) or a compile-time reassignment would mean. A call marker only ever produces a value, it works anywhere an expression does, and it sits beside a marker the language already has. spawn marks a call to change when it runs, comptime marks a call to change the stage it runs in, and neither changes the verb, so there are no compile-time functions any more than there are async ones (concurrency.md §5.3). Work that needs several statements is written as a verb or a lambda, and its call is marked. That a lambda captures nothing turned out to fit exactly: a compile-time call may depend only on what is known at compile time, and taking everything as a parameter is how that shows. We kept the word comptime from Zig, where it marks the same property: it names a stage, and the marker changes exactly the stage, and a reader who has met it there reads it right.
Writing the rule down showed us that half of what we had asked for already existed. The compiler had folded computations at compile time for a long time (the chapter on that rule), so evaluating a pure call early needed no marker. The marker adds two guarantees folding cannot give (effects.md §5.6). It turns the compiler’s “may” into “must”: a marked call is evaluated at compile time or the build fails, where folding may quietly leave anything for run time. And it lets a call read capability-backed state at compile time, which folding never does, because a fold must change nothing the program computes and a read made early reads a different world. The second is the reason the feature exists, and the next chapter describes that different world.
The cost of the call form is the cost spawn already pays: a compound computation has to be named before it can be marked.
A comptime call reads the build machine
A call that reads at compile time needs a capability to read through, and Zane has no ambient I/O. Every read goes through a capability that was passed in (effects.md §6.1), every capability comes from the root package, out of @program$ or a foreign variable, and the console and the runtime are created when the program starts. At build time none of them exists. So we had to define a capability during a compile-time call.
Our first proposal was a second set of capabilities: a @build$ namespace holding the build’s files, clock and environment, reached only by the root package and passed on like @program$. It kept the build and the running program visibly apart, at the price of a parallel vocabulary, and it could not read through a capability a library declares. The objection that replaced it was that the checker already knows the capability is there. If a capability reached the call without an error, it is in hand, and its origin needs no new rule. That was almost enough. What it leaves open is which object the compiler calls when it runs the call during the build, since the program’s object does not exist yet, and one sentence closes it: inside a comptime call, a capability stands for its counterpart on the build machine. It is the move the marker already makes for time. comptime Time.now(clock) is the build’s time, and a file read through files in a marked call is the build machine’s file. The marker at the call shows the reader which world is meant, so the capabilities need no second name.
The runtime’s arguments was the case that tested the rule. A build has no program arguments, and our first reading made a compile-time read of them an error. The counter-proposal was to have the read give an empty list and to let the build command take arguments to pass through, and together the two stop being a special case. The runtime’s counterpart at build time is the build, so arguments in a marked call gives the arguments the build was started with, and an empty list when there are none, exactly as a program started with nothing gets an empty list. Zane gets build options this way, the role -D plays for a C compiler, with no mechanism of its own, and only a marked call can see them. How a build is given those arguments is the toolchain’s business, as how a program is started is.
The results and writes of a compile-time call were quicker to settle. Its result is built into the binary, so it must be a value type, which carries no reference, capability or handle that could point into the build’s memory (memory.md §2.10). It writes nothing outside itself. Inside the call anything goes, since its locals and the values it makes live and die in the build. But a write to capability-backed state would give the build itself effects, and a write to the marked call’s subject would write run-time storage before the program exists. comptime list!sort() is therefore an error, and the sorted copy is computed and assigned instead. An abortable marked call is handled like any other, and its handler runs where the call does, at compile time, so the whole marked expression is one constant. We considered running the handler at run time against an error value built into the binary, which would allow “embed it if possible, else load it now”, but it blurred the marker’s meaning, and a call that returns a variant for the program to branch on expresses the same choice explicitly.
The cost is that a Zane build is no longer a function of its sources. A marked call that reads a file, the clock or the build’s arguments gives a different binary depending on where and when it was built, and reading the build machine is correct but still surprising when the build machine is not the target: a compile-time read of anything that describes the system describes the builder. The feature also reaches less than “any capability” suggests. The compiler evaluates C as compiled for the target, and a call into a function it has no body for, such as one in the platform’s C library, stops the evaluation (the FFI story). For a fold, that stop only delays the call to run time, but a marked call has no later, so it fails the build. A C capability whose reads end in the platform’s library therefore cannot be read at compile time, and in practice compile-time reads go through the capabilities the compiler supplies itself. The earlier chapter’s claim that a read cannot be made early still holds for folding: a marked call does not make the program’s read early, it makes a different read.
Pure dependencies join a comptime call, and reads need their own marker
Once a call could be forced into compile time, its arguments had to be available there too, and most arguments are computed. The sharpest case was a call whose input came from a read made just before it:
time Time = Time.now(clock);
content String = comptime readNotes(files, String(time));
Two rules were easy to state. One rejected any argument that is not a literal, a constant or another marked call’s result, which is safe and makes even String(time) need a marker of its own. The other pulled every dependency into compile time along with the call, which is convenient and changes the meaning of code the marker does not touch: time would hold the build’s time everywhere it is used, lines away, in code that still reads as a request for the current time.
The rule we kept splits the dependencies by whether they read. A dependency that folding could already evaluate, one that depends on no parameter and reads no capability-backed state, is pulled into compile time automatically. That is safe because folding it was already allowed and changes nothing the program computes (effects.md §5.3), so the marker only turns the compiler’s “may” into “must” for that part, and a dependency that writes, a verb that prints and returns, still contributes its value while its print stays at run time. A dependency that reads capability-backed state is never pulled in. It is an error unless it carries its own marker, so in the example time is written comptime Time.now(clock), and the build’s time is announced where it is taken. The split costs a reader nothing on the pure side, where the stage cannot be observed, and requires a marker exactly where the stage changes a value’s nature.
Two consequences followed, one for the compiler and one for the build. Folding needs no termination proof because it can give up and leave the work for run time. A marked call cannot give up, so explicit and pulled-in evaluation runs to completion, and a marked call that never finishes is a build that never finishes, as a program that never finishes is a run that never does. We kept any limit out of the language: a compiler may offer one as a diagnostic, and whatever budget it spends on folding is its own, with marked work not counted against it. The build follows from the reads. A compile-time call that reads capability-backed state reflects what those reads return in the current build, because a file may change between two builds, so such calls run again on every build and only calls that read nothing may be reused.
The cost is a build whose slowness the source shows but does not bound. An expensive marked call that reads a file runs on every build, and one that loops runs until someone stops the compiler.