Contracts
A contract is a nominal interface. Conformance to it is declared explicitly, because a contract carries semantics and not just a signature. The language’s contracts unlock syntax.
contract Shape { fn area(self): Float fn describe(self): String = "shape of area ${self.area()}" // default method}
type Circle = { r: Float }impl Shape for Circle { fn area(self) = PI * self.r * self.r }
fn total(shapes: (any Shape)[]): Float = shapes.map(Shape::area).sum()- Functions of a type.
impl Circle { … }, without a contract, declares the type’s own functions. With a firstselfparameter (self,mut selforsink self), it is a method:c.grow(2). Without one, an associated function:Circle.unit(). Inside the block,Selfdenotes the type. In a uniform call, a method of the type takes precedence over a free function of the same name. - Adoption.
impl Shape for Circle { … }defines each method of the contract, withSelfstanding forCircle; a method that has a default body may be omitted, or redefined. A method of animplmay omit its return type, which the contract gives:fn area(self) = …. A method may have type parameters of its own,fn fromJson<R: Reader>(r: mut JsonReader<R>): Self, which the adoption writes with its own, in the same order, and which a call infers:T.fromJson(&r)reaches the method of the actual type, instantiated for R. - A contract’s own functions.
impl Json { pub fn decode<T: Json>(text: String): T ! JsonError … }, animplof the contract withoutfor, declares functions that no adoption owes, called on the contract,Json.decode<Book>(text): the API a library builds on its contract, under the contract’s name. Its module declares them; they take noself, and call one another without naming the contract. - Constraints.
fn f<T: Shape>(s: T)orfn f<T>(s: T) where T: Shape. In the body,s.area()andT.default()denote the contract’s methods; a type that does not adopt the contract is rejected at the call. - Generic contracts.
contract Iterable<T> { fn next(mut self): T? }has type parameters, which adoption fixes:impl Iterable<Int> for Count. A type adopts a generic contract once per set of arguments:impl From<IoError> for ConfigErrorandimpl From<ParseIntError> for ConfigErrorcoexist, and each gives its methods to the type, between which a call decides by the type of its arguments. A boundI: Iterable<T>infersTfromI, which adopts it once (fn collect<I, T>(it: mut I): T[] where I: Iterable<T>); a type that adopts it with other arguments is rejected at the call or at the instance, and a type that adopts it several times leaves T ambiguous, to be written out:kind<Int, E>(e).E.from(x)chooses, among E’s adoptions ofFrom<X>, the one that the type of x designates. - Contract sets.
A & Brequires both contracts: it is written wherever a contract goes, in a bound (fn index<K: Eq & Hash, V>(…),where K: Eq & Hash) as in anany(any (Reader & Show), one table per contract).contract IList<T> = Eq & Index<Int, T>names it: an alias has no body and adds nothing, so any type that adopts each of its contracts satisfies it, without animpl;impl IList<Char> for Ropeis rejected, and the message suggests adopting each contract. When two contracts of a set declare a method of the same name, the callx.f()is ambiguous, and is qualified:Index::len(x). - Extended contracts.
contract Solid: Shape { fn volume(self): Float }declares a contract that presupposes others (: A & Bfor several) and adds its methods. It is adopted explicitly, byimpl Solid for Cube, rejected if Cube does not already adopt Shape; Shape’s methods stay inimpl Shape for Cube. Solid’s default bodies call Shape’s, and a boundT: Solid, or anany Solid, provides them too. - Static dispatch by default.
fn f<T: Shape>(s: T)is monomorphized. - Explicit dynamic dispatch.
any Shapedenotes an existential value, visible in the type: the value, and the method table of its actual type. A value of a type that adopts Shape becomes anany Shapewherever one is expected, without a written conversion:[Circle{…}, Square{…}]for an(any Shape)[], an argument, a field. Its methods, default ones included, go through the table;Shape::areanames them as functions. Ananyis a value: its copy is independent, and anmut selfmethod modifies only the variable through which it is called. - The actual type of an
any.w is Button(b), or an armButton(b) =>, tests whether theany Widgetholds a Button, by its table, and binds the value it holds; Button adopts the contract. In a generic function,w is T(x)tests each instance’s T:fn widgetOf<T: Widget>(ws: (any Widget)[]): T?. The set of types being open, such an arm covers nothing: amatchkeeps its_.TypeId.of<T>()names a type, compared and hashed, a key of a map holding one value per type,styles[TypeId.of<Button>()]; it shows as the type’s qualified name. - What goes into an
any. A contract can be used as ananyif each of its methods receivesselformut selfand receives no other Self:Eq(equals(self, other: Self)) would require two values of the same actual type,Default(default(): Self) a value with no actual type. A method that returns Self,fn clone(self): Self, returns ananyof the same contract, the value boxed again; Self elsewhere in the result,Self[], is rejected. The table of anany Solidalso holds Shape’s methods, and that of anany (Reader & Show)those of each contract. A resource only goes into ananythat names Disposable,any (Reader & Disposable<IoError>), with the error of its disposal: theanyis then a resource, disposed of through its table, and its linearity is checked like that of any resource. - Derivation.
#Eq #Hash #Show type User = …declares that the type adopts these contracts, with a generated implementation. A contract carries its generator, ameta fn derive(t: Type, …): Declsthat returns the methods; the compiler places them inimpl C for Tand checks them like those of anyimpl. It may also return theimplof another contract for the same type, one that C requires or makes useful:#Cliwritesimpl FromArgs for T, whichmain(args: T)expects. Arguments go to the generator:#Cli(name: "wc"). A contract all of whose methods have a default body is adopted by#Cwithout a generator. An alias is derived like a contract, and derives each of its own, in the order of the set: withcontract Key = Eq & Hash,#Key type User = …is equivalent to#Eq #Hash, which avoids a long list in front of each type. It takes no arguments, which would not know which generator to go to. On a generic type, the generated adoption holds for each instance whose arguments adopt the contract, as in Rust:#Eq enum Tree<T>isimpl<T> Eq for Tree<T> where T: Eq. Conformance can thus be read in the declaration, without running meta code.
contract Default { fn default(): Self meta fn derive(t: Type): Decls = quote { fn default(): Self = ${t.construct(f => quote { ${f.type}.default() })} }}
#Defaulttype Counts = { lines: Int, words: Int }| Contract | Syntax unlocked |
|---|---|
Iterable<T> |
for x in xs |
Traversable<T, I> |
for x in xs, through the iterator that xs.iter() returns |
Disposable |
using, checked linearity (section 7) |
Awaitable<T> |
await x, x.await |
Try<T, E> |
! operator: x! is x.toResult()! |
Eq, Ord |
==, <, sorting, xs.sorted(), deduplication, xs.distinct() |
Additive |
xs.sum(): zero() and plus |
Hash |
key of Map and Set |
Index<K, V> |
a[k], for reading and as mut; read-only through a bound C: Index<K, V> |
Show |
interpolation "${x}" |
Default |
T.default(), fields omitted at construction |
Parse<E> |
T.parse(s), T ! E: Int, Float, the types of weaver.time, a #Parse enum; an option of #Cli |
Language contracts. They are declared by the library and form the prelude together with the types:
contract Eq { @operator("==") fn equals(self, other: Self): Bool }contract Ord: Eq { @operator("<") fn less(self, other: Self): Bool }contract Hash: Eq { fn hash(self): Int }contract Show { fn show(self): String; fn literal(self): String = self.show() }contract Default { fn default(): Self }Int, String, Bool and UInt8 adopt them according to their nature, Bool ordered by false < true. Ord and Hash extend Eq: a type adopts them once it adopts Eq, since a total order and a hash presuppose equality, and a bound T: Ord or T: Hash also provides ==. Ord also provides a.max(b), a.min(b), a.clamp(lo, hi) and a.compare(b), methods rather than free functions: they come with the type, without an import. compare returns an Ordering (.less, .equal, .greater), which then(…) extends on equality, its lazy argument (6.6) being computed only if it is needed: a.len().compare(b.len()).then(a.compare(b)). #Ord generates the lexicographic order, field by field in declaration order, and for an enum the rank of the variant, then its fields. #Eq generates field-by-field equality of a record; on an enum, two values are equal if they are of the same variant, with equal fields. #Hash likewise mixes the hashes of the fields, and for an enum the rank of the variant: #Eq #Hash enum Shape = … can serve as a key. An enum without fields has its == without adopting anything, but must adopt Eq and Hash, by #Eq #Hash, to serve as a key. An optional T? adopts Eq, Hash and Show if T adopts them: Map<String?, Int>, a field nick: String? of an #Eq #Hash type. Likewise a result T ! E adopts Eq, Hash and Show, and an array Eq, Hash, Ord and Show, its order being lexicographic: [1, 2] < [1, 3], [1] < [1, 0].
Show. show writes a value for a human, literal as in source code, which tells it apart: a string a is written there as "a". Its default body returns show, which String and Char redefine. #Show writes a record Point{x: 1, y: 2} and a variant Circle(r: 3), the way an array [1, 2], a tuple (1, "a"), an optional Some(1) are written out of the box: nested values through their literal, so that "${["a"]}" is ["a"], and "${"a"}" is a.
Generic adoption. impl<W: Writer> Writer for Buffered<W> { … } makes each instance of Buffered whose argument satisfies the constraint adopt the contract, with the block’s methods instantiated for it.
Language types. Int, String, T[], Option<T> and the other prelude types adopt the contracts of core and of the standard library, and those of the package that declares them: the package of Json writes impl Json for Int and impl<T: Json> Json for T[], which no other package can do (rule 6).
Operators. An operator is syntactic sugar, separate from semantics: the @operator annotation binds a symbol to a function whose name remains free. The function can also be called by its name, and the parser never reads an operator definition. Bound in an impl<T>, or generic itself, it holds for each instance whose arguments satisfy its constraints: @operator("+") fn concat(self, other: T[]): T[] provides xs + ys on every array; a non-generic function for the same types wins. == and < are bound only through Eq and Ord, the operator’s equality and order being those of tables, sorts and searches: impl Eq for P { fn equals(self, other: P): Bool = … }.
@operator("+") fn concatenate(a: Text, b: Text): Text@operator("+") fn translate(p: Point, v: Vector): Point@operator("+=") fn append(t: mut Text, b: Text) // in-place version, optional
contract Eq { @operator("==") fn equals(self, other: Self): Bool}- Closed set. Only
+ - * / %and their in-place versions+= -= *= /= %=, unary-,== <(throughEqandOrd),&& || !and??can be bound, with a fixed precedence.|>, the propagation!,?.,..and.cannot. An in-place version receives its first operand asmutand returns nothing;&&,||and??receive the second aslazy, which keeps short-circuiting. - Checked arity. Two parameters for a binary operator, one for a unary one.
- Derived operators.
!=follows from==;>,<=and>=follow fromOrd.a += buses the+=version if it exists, otherwisea = a + b. - No ambiguity. A single function per symbol and per pair of operand types.
- Nothing hidden.
@operatoris a language annotation, like@assertand@threadPool: the checker binds the symbol to the annotated function, and the parser knows no defined operator.&&,||and??are thus functions of core (6.6). - Coherence. A library adopts a contract, by
impl C for T, and binds an operator, only if it declares the contract or one of the types: two libraries thus cannot contradict each other. The application, the root of the build, which nobody imports, writes the glue between two libraries,impl Serialize for geo.Point; if a dependency later adopts the same contract, compilation names the other adoption, and the application removes its own. An adoption works everywhere, but its methods are named only where its module is seen: a file callsp.wire()only if it imports the module that writesimpl Wire for geo.Point, or if that module declares the point’s type, whose adoptions go with it. A constraint is satisfied without the import,send(p)withT: Wire, as is a function that uses the adoption itself: what the import brings is the names, not what makes the code work. The visibility is not transitive:pub importreexports names, not adoptions, and a module importing one that importswiredoes not see them; a build loads the modules its imports reach, but each file sees only its own imports.