zax.io

A guide to the Zax programming language

View project on GitHub

Zax contracts

Field Value
Status Current conceptual design
Audience Human developers writing one function that works with many types, and type authors deciding how their types take part
Applies To contract declarations; fulfill members; static and dynamic dispatch; passing a contract to a function; satisfies for generics; contracts inside contracts; not a formal grammar, ABI, or compiler mapping
Implementation State Not established by this repository
Owns The contract mental model; the difference between a contract and a type with roles; _ and roles in a contract’s own functions; contract fulfill members and their dispatch; static and dynamic dispatch and their costs; construction rules for contract members; contract references and pointers, as static and as dynamic, member selection, and restricting a parameter’s dispatch; callable values with contract parameters; optional and relaxed roles in contracts and the is fulfilled test; contract roles whose type is a contract; visibility of contract members; which members count for satisfies; contracts inside contracts; generics inside a contract; what a contract can never be
Does Not Own Roles on types, the short and long fulfill forms, and routed fulfillment (composition); constraint and ranking rules in general (generics); hook points and partials (partials); the order of declaration words (qualifiers); reference origins (lifetimes and references)
Source / Provenance Maintainer direction for contracts and explicitly chosen dispatch, reconciled with current composition, generics, partials, and invocation design

One function for many types

When you write one function that works with many types, the compiler can build it in one of two ways. It can compile a separate copy of the function for each type, which costs code size but makes every call inside the copy direct. Or it can compile the function once and look up each type’s declarations in a table, which keeps one copy of the code but makes each of those lookups an indirect call or read. With a contract, you write the function once, and each caller chooses which of the two the compiler builds:

Drawable :: contract {
  draw abstract : ()() readonly
  label abstract : String
}

Circle :: type {
  radius : Float
  drawing static fulfill : Drawable      // Circle fulfills Drawable through its member drawing

  draw final fulfill drawing : ()() readonly = {
  }

  label fulfill drawing : String
}

drawOne final : ()(shape : Drawable readonly loan &) = {
  shape.draw()
}

myCircle : Circle

drawOne(myCircle as static)      // the compiler builds a copy of drawOne for Circle; the call to draw is direct
drawOne(myCircle as dynamic)     // the single shared drawOne runs; the call to draw goes through a table for Circle
drawOne(myCircle)                // error: write `as static` or `as dynamic`

Drawable declares two roles: abstract declarations that any type using Drawable must supply, here a draw function and a label string. Circle declares the member drawing with fulfill, which makes drawing a fulfill member: Circle must then supply each role, which it does with the declarations draw and label (the fulfill forms are described in composition). drawOne accepts any value whose type has a Drawable fulfill member. Because the caller writes as static or as dynamic at every call, a reader of the call can see whether it duplicates code or goes through a table.

The static on drawing is a separate choice: it controls how Drawable’s own functions call or read Circle’s fulfillments. Drawable declares no functions of its own in this example. Static and dynamic dispatch explains that choice.

A contract is not a base class. Circle is not a Drawable: Circle contains a Drawable member, and a function written for Drawable can use Circle’s declarations only through the roles that Drawable declares.

Later examples reuse Drawable, Circle, and drawOne from this section, Labelled from the next section, the first Account and Ledger from fulfilling a contract, and Badge from passing a contract to a function, unless a block declares its own. A name starting with my, such as myCircle, is a value of the matching type, and a plural such as myCircles is an array of them.

A contract cannot exist outside a container

A contract looks like a type. It can hold stored members, functions with bodies, and roles:

Labelled :: contract {
  label : String

  rename final : ()(name : String) = {
    if _.validate(name) {      // calls a role: the container's fulfilling function runs
      _.label = name as last   // a member the contract stores
    }
  }

  validate abstract : (result : Boolean)(name : String) readonly
}

Inside a contract’s own function, _ is the contract member inside its containing value. _.label is a member that Labelled stores, and _.validate is one of Labelled’s roles: calling it runs the function that the container declared to fulfill validate.

A type can declare roles too, but a type’s own functions never call or read them. On a type, roles list what a container supplies through a fulfill member, or what partials supply through a hook point. So you can declare a variable of such a type on its own.

A contract is different: a contract’s functions can call or read the contract’s roles, as rename calls validate, and only a container can supply those roles. So you can never declare a contract value on its own:

showLabel final : ()() = {
  naming : Labelled                   // error: a local cannot have a contract type
}

As a type, a contract can appear in only three places: as the type of a fulfill member, as the type of an abstract role (see a contract role whose type is a contract), and as the target of a reference or borrowing pointer to a fulfill member. A contract name can also be a generic constraint, as described in generic code over many values.

A contract’s functions can use the containing value only through the contract’s roles. Inside rename, you cannot name any other member of the container, because Labelled works with any container type that fulfills it. For the same reason, a role in a contract cannot use outer to mean the container’s type, as a role in a type can. When a contract’s roles need to mention the container’s type, give the contract a generic type parameter instead:

Comparable$(Other : type) :: contract {
  equals abstract : (result : Boolean)(other : Other readonly loan &) readonly
}

Point :: type {
  x : Float
  y : Float
  comparing static fulfill : Comparable$(Point)

  equals final fulfill comparing : (result : Boolean)(other : Point readonly loan &) readonly = {
  }
}

Fulfilling a contract

A type fulfills a contract by declaring a fulfill member of that contract, with static or dynamic written before fulfill:

Account :: type {
  naming static fulfill : Labelled

  validate final fulfill naming : (result : Boolean)(name : String) readonly = {
  }
}

Ledger :: type {
  naming dynamic fulfill : Labelled

  validate final fulfill naming : (result : Boolean)(name : String) readonly = {
  }
}

Broken :: type {
  naming fulfill : Labelled            // error: write static or dynamic before fulfill
  other : Labelled                     // error: a contract member must be a fulfill member
}

The compiler places the contract’s stored members, such as label, in the container at the position of the fulfill member, so the container’s author decides where the contract’s data sits.

The container must fulfill every required role of the contract. Optional roles may be left unfulfilled. When the fulfilling declaration has the role’s name, write only the member name, as in validate final fulfill naming. When it has another name, write the role’s full path, as in check final fulfill naming.validate. Both forms are described in composition.

A contract’s callable roles must be fulfilled by fixed final functions. A varying fulfillment would leave a replaceable slot that might hold no function when the contract’s code calls the role, and every call would need an extra indirection to find the slot’s current function. When a container needs replaceable behavior, it fulfills the role with a private final function that calls a public varying slot and decides what to do when the slot is empty:

Account :: type {
  naming static fulfill : Labelled

  validate private final fulfill naming : (result : Boolean)(name : String) readonly = {
    if ?_.validator {
      return _.validator(name)
    }
    return true                  // no validator installed: accept every name
  }

  validator : (result : Boolean)(name : String) readonly   // a public, replaceable slot
}

Broken :: type {
  naming static fulfill : Labelled
  validate varying fulfill naming : (result : Boolean)(name : String) readonly   // error: a contract's role needs a final fulfillment
}

You must write static or dynamic even when the contract’s functions do not call any roles yet. If the contract’s author later changes a function to call a role, existing containers still compile, because each container already chose how those calls are made. Other changes to a contract can still break containers, as with any interface: adding a required role, or calling a relaxed role with qualifiers that some container did not fulfill.

In two cases, a fulfill member uses the dispatch already chosen for an outer contract’s fulfill member, so you write neither static nor dynamic on it. Both are described under contracts inside contracts:

  • a contract member declared inside another contract; and
  • a member that fulfills a contract’s role whose type is itself a contract.

own and expose work on a fulfill member as on any member. own publishes the contract’s stored members, and expose makes the contract’s functions that are eligible for exposure callable on the container. Neither adds the contract’s roles to the container: each role is a requirement on the container, and the container’s own fulfilling declaration is already one of the container’s members:

Account :: type {
  naming own expose static fulfill : Labelled

  validate final fulfill naming : (result : Boolean)(name : String) readonly = {
  }
}

myAccount.label           // published by own
myAccount.rename("x")     // exposed by expose
myAccount.validate("x")   // Account's own fulfilling function

These words follow canonical ordering: the composition words (own, preferred, expose), then private, then words such as final or varying, then static or dynamic, and fulfill after all of them.

Static and dynamic dispatch

Dispatch is how code written for a contract calls or reads a container’s fulfillments. The programmer chooses it in two separate places: on a fulfill member, for the contract’s own functions such as rename, and at a call, for a function that takes a contract parameter (see passing a contract to a function). Writing static or dynamic on a fulfill member chooses dispatch for the contract’s own functions:

  • Static dispatch. The compiler builds a separate copy of the contract’s functions for each static fulfill member’s container type and member, and each copy calls or reads that member’s fulfillments directly. The cost is one copy of the contract’s code for each static fulfill member.
  • Dynamic dispatch. The compiler builds the contract’s functions once, and every container type shares that copy. Each call or read of a role goes through a table for that container type and contract, called a dispatcher. The cost is an indirect call or read on every use of a role.

Dynamic dispatch adds no storage to the container. The compiler passes the right dispatcher wherever the shared code is called. When you call a contract function on a value whose type the compiler knows, as in myLedger.naming.rename("x"), the compiler passes Ledger’s dispatcher. When you call through a dynamic contract reference, described in passing a contract to a function, the reference holds the dispatcher next to the address.

The two choices stay separate. When code holding a dynamic reference to a static fulfill member calls one of the contract’s functions, the dispatcher leads to that container’s static copy of the function, and inside that copy the role calls are direct:

relabel final : ()(item : Labelled writable loan & dynamic) = {
  item.rename("x")      // through Account's dispatcher, to Account's static copy of rename
}

relabel(myAccount as dynamic)   // Account declares naming static fulfill : Labelled

A generic contract function is the exception. A dispatcher cannot hold a copy for every type argument that callers might use, so when code holding a dynamic reference calls a generic contract function, the compiler builds one shared instantiation for that call’s type arguments. Inside it, everything that depends on the container goes through the dispatcher, even when the fulfill member is static: every call or read of a role, and possibly also access to the contract’s stored members, depending on the dynamic reference’s layout, which is not established yet.

// suppose Labelled also declares:
//   describe$ final : (Format : type)(result : String)(format : Format readonly loan &) readonly
show final : ()(item : Labelled readonly loan & dynamic) = {
  text := item.describe(myJsonFormat)   // a shared instantiation of describe$; role uses go through the dispatcher
}

A callable value bound to a contract function of a dynamically dispatched member, such as callback := myLedger.naming.rename, holds the dispatcher as well as the receiver, so it takes more space than a callable value bound to a statically dispatched member’s function.

Construction and destruction

A contract’s stored members are members of the container, so the compiler constructs and destroys them with the container’s other members, under the ordinary construction rules. A contract may declare its own constructor (+++) and destructor (---) for those members. Neither may call or read a role: during construction the container’s fulfillment could use container members that are not constructed yet, and during destruction it could use members that are already destroyed.

Labelled :: contract {
  label : String

  +++ final : ()() = {
    _.label = "untitled"         // fine: a member Labelled stores
    if _.validate(_.label) { }   // error: a role cannot be used during construction
  }

  validate abstract : (result : Boolean)(name : String) readonly
}

When setting up a contract needs a role, write an ordinary function on the contract and call it from the container’s constructor.

Passing a contract to a function

A function parameter whose type is a contract is always a reference or a non-owning pointer. It accepts any value whose type has a fulfill member of that contract, and it borrows that member: the function never copies or owns the contract member, because the contract member cannot exist outside its container.

The caller writes how the function reaches the container’s fulfillments:

  • With as static, the compiler builds a separate copy of the called function for the argument’s type, and every call or read of a role inside that copy is direct.
  • With as dynamic, the single shared copy of the function runs. The reference passed to it holds the dispatcher as well as the address, so it takes more space than an ordinary reference, and every call or read of a role is indirect.

Inside the called function, only the contract’s members and roles are available, whichever dispatch the caller chose. For a parameter that lets the caller choose, the compiler checks the function’s body once, against the contract. (A parameter restricted to static, described in the next section, also sees only the contract’s names, but the compiler builds and checks a copy for each concrete type.)

drawOne final : ()(shape : Drawable readonly loan &) = {
  shape.draw()           // fine: draw is a role of Drawable
  shape.radius           // error: Drawable has no member radius, even when the argument is a Circle
}

Writing myCircle as static, without naming a member, is a shorthand: the compiler looks for the one fulfill member of Circle for the parameter’s contract that is visible everywhere Circle is, meaning it is not private and was not added by a partial. When the type has more than one such member, the caller names the member:

Badge :: type {
  front static fulfill : Drawable
  back static fulfill : Drawable
  // ... fulfillments for front and back
}

myBadge : Badge

drawOne(myBadge as static)          // error: Badge has two Drawable fulfill members; name one
drawOne(myBadge.back as static)     // fine

Naming the member also chooses between overloads that accept different contracts:

Printable :: contract {
  print abstract : ()() readonly
}

Poster :: type {
  drawing static fulfill : Drawable
  printing static fulfill : Printable
  // ... fulfillments for drawing and printing
}

show final : ()(shape : Drawable readonly loan &) = { }
show final : ()(document : Printable readonly loan &) = { }

myPoster : Poster

show(myPoster as dynamic)            // error: ambiguous; both overloads accept a Poster
show(myPoster.drawing as dynamic)    // fine: drawing is a Drawable fulfill member

Restricting the dispatch a parameter accepts

A function’s author can restrict a contract parameter to one dispatch by writing static or dynamic right after & or *:

drawOne final : ()(shape : Drawable readonly loan &) = { }             // the caller chooses
paint final : ()(shape : Drawable readonly loan & dynamic) = { }       // dynamic only
measure final : ()(shape : Drawable readonly loan & static) = { }      // static only
trace final : ()(shape : Drawable readonly loan * dynamic) = { }       // a non-owning pointer, dynamic only

paint(myCircle as dynamic)       // fine
paint(myCircle as static)        // error: paint accepts only dynamic

The dispatch is part of the reference or pointer’s type: a dynamic one holds a dispatcher and a static one does not, so neither can be used where the other is expected. static and dynamic are the only words written after &. On a pointer, the dispatch word comes first after *.

The caller still writes as static or as dynamic when only one is allowed, so the choice stays visible at every call. Inside a function whose parameter is restricted to static, every call or read of that parameter’s roles is direct, at the cost of a separate copy of the function for each argument type.

Some functions must compile to exactly one body: a function stored as a callable value or in a replaceable varying slot, a function that fulfills a contract’s role, and an exported function. Each contract parameter of such a function must be declared & dynamic or * dynamic. The compiler never adds dynamic because of how a function is used:

onPaint : ()(shape : Drawable readonly loan & dynamic) = paint      // fine
onDraw : ()(shape : Drawable readonly loan & dynamic) = drawOne     // error: drawOne's shape parameter is not declared & dynamic

For the same reason, you cannot store a function whose parameter lets the caller choose as a value for one concrete type:

onCircle : ()(circle : Circle readonly loan &) = drawOne   // error: no dispatch was chosen for drawOne's shape parameter

Instead, write a small function that takes a Circle and calls drawOne(circle as static).

Passing a parameter on

A parameter that lets the caller choose can be passed on only with as dynamic. The compiler checks the function’s body once, so that one body must also work when the function was called with as dynamic, and in that case the concrete type is unknown. A & static parameter can be passed on either way, because the compiler builds that function separately for each concrete type:

drawTwice final : ()(shape : Drawable readonly loan &) = {
  drawOne(shape as dynamic)      // fine
  drawOne(shape as static)       // error: shape's concrete type is unknown when drawTwice is called with as dynamic
}

measureTwice final : ()(shape : Drawable readonly loan & static) = {
  drawOne(shape as static)       // fine: each copy of measureTwice knows its concrete type
  drawOne(shape as dynamic)      // fine
}

A & dynamic parameter, like one that lets the caller choose, can be passed on only with as dynamic.

Other contract references

A contract reference or pointer that is not a parameter must also state its dispatch:

missing : Labelled readonly loan & = myLedger.naming as dynamic           // error: write static or dynamic after &
named : Labelled readonly loan & dynamic = myLedger.naming as dynamic     // fine

A static contract reference or pointer is allowed only as a parameter, or as a local in code that the compiler builds for one known concrete type, such as a generic or a function with a & static parameter. A member of a type can point at containers of different types over its life, so a contract pointer stored as a member must be dynamic:

Painter :: type {
  target : Drawable readonly loan * static        // error: a contract pointer member must be dynamic
  shared : Drawable readonly loan * dynamic       // fine: the pointer holds its dispatcher
}

A function may return a contract reference as a borrowed result, under the ordinary result-origin rules:

pick final : (result : Drawable readonly loan & dynamic)(
  first : Drawable readonly loan & dynamic,
  second : Drawable readonly loan & dynamic
) = {
  return first
}

Optional and relaxed roles

A contract may declare abstract optional, abstract relaxed, and abstract optional relaxed roles, with the meanings that composition gives them. A container may fulfill such a contract with either dispatch.

An optional role may have no fulfillment, so code may call or read it only inside a test that it is fulfilled. The spelling of the test is shared with hook points and is not final:

Notifying :: contract {
  message : String
  notify abstract optional : ()(text : String readonly loan &)

  send final : ()() = {
    if _.notify is fulfilled {      // illustrative spelling
      _.notify(_.message)
    }
    _.notify(_.message)             // error: notify may have no fulfillment; test it first
  }
}
  • if ... is fulfilled works in any code. When the compiler knows the container’s type, it decides the test at compile time and removes the branch that cannot run. In code shared under dynamic dispatch, the dispatcher records whether the container fulfilled the role, and the test checks that record at run time. That check is one of the costs of dynamic dispatch.
  • if compile ... is fulfilled asks for a compile-time answer, so the compiler allows that form only where the concrete type is known: on a value of a known type, in a function with a & static parameter, and in a generic. A contract’s own functions cannot use it, because a container may fulfill the contract with dynamic dispatch; they write if ... is fulfilled, which the compiler still decides at compile time in a static copy.
Inbox :: type {
  alerts static fulfill : Notifying     // fine: notify is optional, so Inbox leaves it unfulfilled
}

Outbox :: type {
  alerts dynamic fulfill : Notifying    // fine under dynamic dispatch too
}

notifyNow final : ()(target : Notifying readonly loan & static) = {
  if compile target.notify is fulfilled { }   // fine: each copy knows its concrete type
}

notifyLater final : ()(target : Notifying readonly loan & dynamic) = {
  if compile target.notify is fulfilled { }   // error: the concrete type is not known here
  if target.notify is fulfilled { }           // fine: checks the dispatcher at run time
}

A relaxed role leaves its omitted qualifiers open, so a container may supply one or more fulfillments with different qualifiers, for example one readonly version and one mutable writable version. A contract’s own functions may call a relaxed role. When a container fulfills the contract, the compiler checks that the container supplies every qualified version that the contract’s functions use, and builds dispatcher entries for exactly those.

A function outside the contract that holds a dynamic reference, or a parameter that lets the caller choose, cannot call a relaxed role: the compiler does not know the container’s type, so it cannot know which qualified versions exist. A function with a & static parameter can:

Observing :: contract {
  observe abstract relaxed : ()()

  watch final : ()() readonly = {
    _.observe()                     // watch is readonly, so this needs a readonly fulfillment
  }
}

Monitor :: type {
  watching dynamic fulfill : Observing

  observeQuietly final fulfill watching.observe : ()() readonly = {   // the readonly version watch needs
  }
}

poke final : ()(target : Observing readonly loan & dynamic) = {
  target.observe()                  // error: a relaxed role cannot be called through a dynamic reference
}

pokeEach final : ()(target : Observing readonly loan & static) = {
  target.observe()                  // fine: the compiler builds pokeEach for each concrete type
}

Visibility

The visibility of a fulfill member decides which code may pass the container as that contract:

HiddenCircle :: type {
  drawing private static fulfill : Drawable

  draw private final fulfill drawing : ()() readonly = {
  }

  label fulfill drawing : String
}

myHiddenCircle : HiddenCircle

drawOne(myHiddenCircle as static)           // error, even inside HiddenCircle: the shorthand ignores private members
drawOne(myHiddenCircle.drawing as static)   // error outside HiddenCircle: drawing is private; fine inside

You choose each fulfilling declaration’s visibility separately from the fulfill member’s. If drawing were public and draw private, code could still call draw through the contract, as shape.draw() does inside drawOne, but could not call myHiddenCircle.draw() directly. A type’s author can use that to make an operation available only through a contract.

Generic code over many values

A contract parameter borrows one value. For a function over a slice of values such as Circle readonly loan[], write a generic, and constrain its type parameter to types that satisfy the contract:

drawAll$ final : (Shape : Drawable)()(shapes : Shape readonly loan[]) = {
  each shape : in shapes {
    drawOne(shape as static)       // passes each element as a static Drawable reference
  }
}

drawAll(myCircles)     // fine: Circle satisfies Drawable
drawAll(myBadges)      // error: Badge has two Drawable fulfill members, so Badge does not satisfy Drawable

drawAll$ is an ordinary generic, and Shape : Drawable is short for requires Shape satisfies Drawable, as the short form describes. The compiler builds drawAll$ separately for each type argument. In the copy for Circle, shape has type Circle and Circle’s own names. Writing shape.draw() would look up draw on Circle, which works only if Circle’s fulfilling function happens to be named draw. To use the contract’s roles whatever the fulfillments are named, pass shape as static or shape as dynamic to a function with a Drawable parameter, as drawAll$ does.

A type satisfies a contract when it has exactly one fulfill member of that contract that is visible everywhere the type is visible. That member may be one of the type’s own members, or a contract member nested inside one of the type’s contract fulfill members (see contracts inside contracts).

  • “Exactly one” guarantees that shape as static inside the generic body is never ambiguous.
  • “Visible everywhere” is needed because the compiler works out Shape satisfies Drawable once for each type and reuses that answer across the whole program, so the answer cannot depend on which code asks. A private member does not count, nor does a nested member inside a private fulfill member. A member that a partial adds does not count either, because a partial’s members are visible only in code that grants the partial.

A fulfill member inside an ordinary stored member does not count: if Car has a plain member engine : Engine, and Engine has a Drawable fulfill member, Car does not satisfy Drawable.

The shorthand myCircle as static follows the same counting rule. Code that can see a member that does not count can still pass that member by naming it, as code inside HiddenCircle can write myHiddenCircle.drawing as static.

Contracts inside contracts

A contract can declare a fulfill member of another contract. You write neither static nor dynamic on that inner member: it uses the dispatch that the container chose for the outer contract. The outer contract must deal with every required role of the inner contract in one of two ways. It can fulfill the role with its own function or member, or it can declare a role of its own with abstract fulfill, which fulfills the inner role and leaves the outer role for the container to fulfill:

Step :: type {
  description : String
}

Undoable :: contract {
  history : Step[16]

  undo final : ()() = {
    _.revert(_.history[0])
  }

  revert abstract : ()(step : Step readonly loan &)
  forget abstract : ()()
}

Document :: contract {
  undoing fulfill : Undoable                                   // uses the dispatch chosen for Document
  revert abstract fulfill undoing : ()(step : Step readonly loan &) // left for the container to fulfill
  save abstract : ()()

  clear final fulfill undoing.forget : ()() = {                // fulfilled by Document's own function
  }
}

Editor :: type {
  doc static fulfill : Document                                // so undoing is static too

  revert final fulfill doc : ()(step : Step readonly loan &) = {
  }

  save final fulfill doc : ()() = {
  }
}

Because Document must declare every role it leaves for its container, a reader of Document alone sees every role a container must fulfill, without reading Undoable.

Document contains Undoable. When undoing and the outer fulfill member are both visible everywhere, a type that satisfies Document, such as Editor, also has an Undoable member that counts toward satisfies, doc.undoing, and so satisfies Undoable as well. A type with a second Undoable member that counts, directly or nested, does not satisfy Undoable, because it has two, though it can still satisfy Document. When overloaded generics are constrained on Undoable and on Document, the declaration constrained on Document is more specific, because Document contains Undoable; see which declaration wins.

A contract role whose type is a contract

Instead of storing another contract inside itself, a contract can declare a role whose type is a contract, so that the container must supply that contract member. The outer contract’s functions use the inner contract through the role, and the container’s author decides where the inner member is stored:

BankAccount :: contract {
  balance : Integer
  naming abstract : Labelled          // the container must supply a Labelled member

  close final : ()() = {
    _.naming.rename("closed")
  }
}

Bank :: type {
  account dynamic fulfill : BankAccount

  naming fulfill account : Labelled   // fulfills account.naming; uses account's dynamic dispatch
  validate final fulfill naming : (result : Boolean)(name : String) readonly = {
  }
}

You write neither static nor dynamic on naming: it uses the dispatch chosen for account. Because naming is Bank’s own member, Bank fulfills Labelled’s roles directly, through naming.validate, and BankAccount declares none of them.

  Where the inner contract member is stored Who fulfills the inner contract’s roles
A fulfill member inside the outer contract Inside the outer contract The outer contract, or the container when the outer contract leaves a role with abstract fulfill
A role of the outer contract whose type is a contract In the container, where its author declares it The container, through its own member

A routed fulfillment of such a role points at an existing contract member, which already has a dispatch. When that dispatch differs from the outer fulfill member’s, the fulfillment is an error:

Registry :: type {
  naming static fulfill : Labelled
  validate final fulfill naming : (result : Boolean)(name : String) readonly = {
  }
}

Branch :: type {
  account dynamic fulfill : BankAccount
  registry : Registry

  naming fulfill account via registry.naming    // error: registry.naming is static, but account is dynamic
}

A role in a type, rather than a contract, can also have a contract type. The fulfill member for that role has no outer dispatch to use, so you write static or dynamic on it; see roles whose type has roles.

Generics inside a contract

A contract can be generic, as Comparable$(Other) is, and a contract’s own functions can be generic too. Two restrictions on a contract’s roles keep every contract usable with dynamic dispatch:

  • A role cannot be generic. A dispatcher holds one entry per role, and a generic role would need a separate function for every type argument.
  • When a role has a contract reference or pointer parameter, declare that parameter & dynamic or * dynamic. A container may fulfill the role’s contract with dynamic dispatch, and then the container’s fulfilling function must be a single function in the dispatcher.
Scene :: contract {
  visit$ abstract : (Node : type)()(node : Node readonly loan &)          // error: a role cannot be generic
  accept abstract : ()(shape : Drawable readonly loan &)                   // error: declare the parameter & dynamic
  acceptShared abstract : ()(shape : Drawable readonly loan & dynamic)     // fine

  describe$ final : (Value : type)()(value : Value readonly loan &) = {   // fine: a generic function, not a role
  }
}

These restrictions, like the rule against outer, apply only to contracts. A type’s roles are never called through the type, so a role in a type may be generic, use outer, or have a parameter that lets the caller choose.

What a contract can never be

A contract member cannot exist outside its container, so the compiler rejects:

  • a contract as the type of a local, a by-value parameter, or a by-value result;
  • copying or moving a contract member out of its container;
  • a contract as the target of a compatibility conversion or view; and
  • unsafe cast to a contract type.
LabelRecord :: type {
  label : String
}

myLabel : LabelRecord = [{ .label = "x" }]
view : Labelled readonly loan & dynamic =
  myLabel as shape Labelled readonly loan & dynamic    // error: a contract cannot be the target of as shape

LabelRecord has the same stored members as Labelled, but nothing fulfills validate for a LabelRecord, so a LabelRecord can never be viewed as a Labelled. The other direction is allowed: you can view a contract member’s stored data as a complete type such as LabelRecord, under the compatibility posture that the container’s author wrote.

A contract reference also hides the container’s concrete type, so outer cast from a contract reference or pointer to its container is an error, including tracked outer cast, whether the dispatch is static or dynamic:

recover final : ()(shape : Drawable readonly loan & dynamic) = {
  circle : Circle readonly loan & = shape outer cast Circle.drawing    // error: no outer cast from a contract reference
}

Costs

Choice What it costs
A static fulfill member A separate copy of the contract’s functions for each container type
A dynamic fulfill member An indirect call or read on each use of a role in the contract’s functions, and a run-time check for each if ... is fulfilled test; no added storage
as static A separate copy of the called function for each concrete type
as dynamic A reference or pointer that holds a dispatcher and takes more space than an ordinary reference or pointer, an indirect call or read on each use of a role, and a run-time check for each if ... is fulfilled test
A callable value bound to a dynamic member’s function A callable value that also holds the dispatcher

Both kinds of dispatch cost something. Dynamic dispatch makes every role use indirect and contract references larger, while static dispatch duplicates code for each concrete type.

Diagnostics

Required contract diagnostics include:

  • a contract used as a local, a by-value parameter or result, a copy, or a move source;
  • a contract member that is not a fulfill member;
  • a fulfill member of a contract without static or dynamic, unless the member takes its dispatch from an outer contract, and static or dynamic on a member that does;
  • static or dynamic on a fulfill member whose type is not a contract;
  • outer in a contract’s role;
  • a generic role in a contract, or a contract role with a contract reference or pointer parameter that is not dynamic;
  • a role used in a contract’s +++ or ---;
  • a contract’s callable role fulfilled by a varying declaration;
  • a call or read of an optional role outside an is fulfilled test;
  • if compile ... is fulfilled where the concrete type is not known;
  • a relaxed role called through a dynamic reference or pointer, or through a parameter that lets the caller choose;
  • a container that does not supply a qualified version of a relaxed role that the contract’s functions use, naming the use;
  • a call that passes a contract without as static or as dynamic;
  • a shorthand that finds no fulfill member that counts toward satisfies, or more than one, naming each candidate;
  • as static on a parameter that lets the caller choose or on a dynamic reference or pointer;
  • a contract reference or pointer without a dispatch, other than a parameter that lets the caller choose;
  • a static reference or pointer where no concrete type is known;
  • a function with a contract parameter that is not dynamic, used as a callable value, stored in a varying slot, used to fulfill a contract’s role, or exported;
  • a call that writes as static for a dynamic-only parameter, or as dynamic for a static-only parameter;
  • an owning pointer to a contract;
  • a routed fulfillment of a contract role whose dispatch differs from the outer fulfill member’s;
  • a contract as a compatibility target, an unsafe cast target, or an outer cast operand; and
  • for a failed satisfies, the reason: no fulfill member, more than one, or only members that do not count because they are private or added by a partial.

Source stability

  • Changing a contract’s function to call one of the contract’s roles never forces existing containers to change their dispatch, because each container already wrote static or dynamic.
  • Adding a required role breaks existing containers until their authors fulfill it. Adding an optional role breaks none, because every use of an optional role is already inside an is fulfilled test.
  • Changing a contract’s function to use a relaxed role with qualifiers that a container did not supply breaks that container.
  • Making a fulfill member private, or adding a second fulfill member of the same contract, can make a type stop satisfying the contract and make the shorthand fail.
  • Adding & static or & dynamic to a parameter that let the caller choose breaks callers that wrote the other dispatch.
  • Adding a contract fulfill member to another contract makes the outer contract contain the inner one, which can change which generic declaration is more specific.

Boundaries and maturity

This document describes current conceptual design, not a formal grammar, specification, ABI, or compiler lowering. It does not establish:

  • owning pointers to a contract, such as a unique or strong pointer that hides its container’s type and destroys the container through the dispatcher;
  • the layout of a dispatcher or of a dynamic reference;
  • any ABI for contracts;
  • a way to recover the concrete type from a dynamic reference;
  • a way for a fulfill member added by a partial to count toward satisfies; or
  • default implementations for roles.

Until owning pointers to a contract are designed, the compiler rejects them. Future work may add any of the features listed above without making dispatch implicit, adding hidden storage to containers, or letting a contract member exist without its container.