Skip to content
Weaverv0.5.0

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 first self parameter (self, mut self or sink self), it is a method: c.grow(2). Without one, an associated function: Circle.unit(). Inside the block, Self denotes 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, with Self standing for Circle; a method that has a default body may be omitted, or redefined. A method of an impl may 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 … }, an impl of the contract without for, 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 no self, and call one another without naming the contract.
  • Constraints. fn f<T: Shape>(s: T) or fn f<T>(s: T) where T: Shape. In the body, s.area() and T.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 ConfigError and impl From<ParseIntError> for ConfigError coexist, and each gives its methods to the type, between which a call decides by the type of its arguments. A bound I: Iterable<T> infers T from I, 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 of From<X>, the one that the type of x designates.
  • Contract sets. A & B requires both contracts: it is written wherever a contract goes, in a bound (fn index<K: Eq & Hash, V>(…), where K: Eq & Hash) as in an any (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 an impl; impl IList<Char> for Rope is rejected, and the message suggests adopting each contract. When two contracts of a set declare a method of the same name, the call x.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 & B for several) and adds its methods. It is adopted explicitly, by impl Solid for Cube, rejected if Cube does not already adopt Shape; Shape’s methods stay in impl Shape for Cube. Solid’s default bodies call Shape’s, and a bound T: Solid, or an any Solid, provides them too.
  • Static dispatch by default. fn f<T: Shape>(s: T) is monomorphized.
  • Explicit dynamic dispatch. any Shape denotes 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 an any Shape wherever 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::area names them as functions. An any is a value: its copy is independent, and an mut self method modifies only the variable through which it is called.
  • The actual type of an any. w is Button(b), or an arm Button(b) =>, tests whether the any Widget holds 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: a match keeps 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 an any if each of its methods receives self or mut self and 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 an any of the same contract, the value boxed again; Self elsewhere in the result, Self[], is rejected. The table of an any Solid also holds Shape’s methods, and that of an any (Reader & Show) those of each contract. A resource only goes into an any that names Disposable, any (Reader & Disposable<IoError>), with the error of its disposal: the any is 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, a meta fn derive(t: Type, …): Decls that returns the methods; the compiler places them in impl C for T and checks them like those of any impl. It may also return the impl of another contract for the same type, one that C requires or makes useful: #Cli writes impl FromArgs for T, which main(args: T) expects. Arguments go to the generator: #Cli(name: "wc"). A contract all of whose methods have a default body is adopted by #C without a generator. An alias is derived like a contract, and derives each of its own, in the order of the set: with contract 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> is impl<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() })}
}
}
#Default
type 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
}
  1. Closed set. Only + - * / % and their in-place versions += -= *= /= %=, unary -, == < (through Eq and Ord), && || ! and ?? can be bound, with a fixed precedence. |>, the propagation !, ?., .. and . cannot. An in-place version receives its first operand as mut and returns nothing; &&, || and ?? receive the second as lazy, which keeps short-circuiting.
  2. Checked arity. Two parameters for a binary operator, one for a unary one.
  3. Derived operators. != follows from ==; >, <= and >= follow from Ord. a += b uses the += version if it exists, otherwise a = a + b.
  4. No ambiguity. A single function per symbol and per pair of operand types.
  5. Nothing hidden. @operator is a language annotation, like @assert and @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).
  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 calls p.wire() only if it imports the module that writes impl 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) with T: 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 import reexports names, not adoptions, and a module importing one that imports wire does not see them; a build loads the modules its imports reach, but each file sees only its own imports.