12. Interfaces, implementations and derive
Taught in Interfaces and Dispatch.
Interface declarations
Section titled “Interface declarations”Taught in Interfaces and Dispatch.
interface Name, its items on the lines below and end, declares a
contract. Every item is a function.
self in an item’s signature stands for the implementing type. It is a type,
valid only in an interface’s signatures: not a value, not an implicit
parameter, not a qualifier. Every self in one signature denotes the same
type for a given impl.
interface Display fn to_string(value: self) -> String end
Item kinds
Section titled “Item kinds”| Item form | Role |
|---|---|
fn signature, no body | Required function: every impl writes it. The next line is another item or the interface’s end. |
fn with a body | Final default: every implementor gets it, and an impl may not write it. |
open fn with a body | Open default: every implementor gets it, and an impl may write its own. |
host fn, no body | Host-backed default, supplied by the runtime; final. |
open host fn, no body | Host-backed default; an impl may override it. |
- Interface items carry no
pub. A function’s visibility is the interface’s. - An interface declares no fields:
field tag: Intis the parse errorinterfaces declare functions only; replace `field tag: Int` with a function requirement such as `fn tag(value: self) -> Int`(Requiring a Value). - A default is reachable interface-qualified (
Iter.known_count(xs)) and type-qualified on an implementor (List.known_count(xs)). Both name one function, selected by the type bound toself. - A default an implementor inherits is the implementor’s member exactly as a
function its impl writes is.
Square.describe(sq)needs no import of the interface, asSquare.area(sq)needs none, wherever the interface and the impl are declared. An import of the interface that only such a call would use is unused, and so an error. The interface-qualified callShape.describe(sq)names the interface and needs it in scope. - A default’s body calls the interface’s other functions bare.
- A Nomi-bodied default may give its trailing parameters default values
(
fn announce(value: self, loud: Bool = False) -> String). A required or host-backed function may not. - An operation with no
selfthat belongs with the interface goes in an inherentimpl Ifaceblock beside it and is called owner-qualified (Iter.from(0)).
interface Formatted fn format(value: self, style: String) -> String fn format_pretty(value: self) -> String format(value, "pretty") end open fn format_brief(value: self) -> String format(value, "brief") end end
Iter’s known_count is an open Nomi default returning None. List
overrides it with a host fn known_count, and Vector returns
Some(Vector.length(vector)) (§13 The Iter protocol).
where on an interface function
Section titled “where on an interface function”An interface function may carry its own where clause, constraining the
interface’s type parameter or a type parameter the function declares. A
required signature writes it after the result; a default writes it between the
result and the body. The bound is checked at each call.
interface Ranked<T> fn entries(collection: self) -> List<T> fn best(collection: self) -> Maybe<T> where T: Comparable Iter.sort(entries(collection), .Descending) |> Iter.first() end fn prefer<K>(_value: self, lhs: K, rhs: K) -> Bool where K: Comparable Comparable.compare(lhs, rhs) != .Less end end
A type name that the function neither declares nor the interface has (a bare
K in fn prefer(lhs: K)) is an error: an interface function does not invent
type parameters. where is a keyword, and every function form may have one.
where self on a default
Section titled “where self on a default”Taught in Interfaces and Dispatch.
A default runs for each implementor, so its body may use only what every
implementor has: the interface’s own functions, Debug, and ==. Any other
interface it needs of a self value (a function of another interface,
"${value}", an ordering operator, a generic call whose bound names another
interface) is an error at the use: `scale` is a `self`, and Scale does not require Display of its implementors, with a hint that shows the clause. The
default states what it needs with where self: Display:
interface Scale fn unit(scale: self) -> String fn format(scale: self) -> String where self: Display "${scale} ${unit(scale)}" end end
- In the body, a
selfvalue may enter a position typed with a bound interface, and a bound such aswhere self: Add<self, self>gives it the operator. Another value of the interface’s own type (other: Scale) does not get the bound. Aselfpassed to a generic function instantiates it at the implementor. - An implementor that implements every bound gets the default. One that lacks
a bound writes the function itself, even when the default is final. An impl
that does neither is the error
`Secret` does not implement Display, which `Scale.format`'s default requires (`where self: Display`), with the hintimplement Display for Secret, or write `fn format` in this impl. So every implementor has the function, and a call checks noselfbound. - On a required function it is the error
interface function 'unit': `where self` is only allowed on a default function, and 'unit' is a required function. Outside an interface it isfunction 'f': `where self` is only allowed on an interface's default function. - A default’s signature may name
selfanywhere: in its result (fn grown(x: self) -> self), in a composite (-> (self, self),List<self>), or with noselfparameter at all (fn zero() -> self). An interface-qualified call of a function with noselfparameter inside the interface’s own default runs the implementor’s function.
Defaults over distinct types
Section titled “Defaults over distinct types”Taught in Interfaces and Dispatch.
In a default bounded by where self: Distinct<T> (§4 Distinct Types), the
pattern self(p) takes a self value apart, binding what it wraps to p, and
self(x) builds a self from a T. The default is specialized to each
implementor, so self(p) is that implementor’s own destructuring and self(x)
its constructor.
type Celsius Decimal interface Temperature fn unit(t: self) -> String fn label(self(n) as t) -> String where self: Distinct<Decimal> "${Decimal.round(n, 1, .HalfUp)} ${Temperature.unit(t)}" end fn scale(self(n), by: Decimal) -> self where self: Distinct<Decimal> self(n * by) end end impl Temperature for Celsius fn unit(_t: Celsius) -> String "C" end end fn main() dbg Temperature.label(Celsius(21.456d)) // "21.5 C" dbg Celsius.scale(Celsius(10d), 2d) // Celsius(20d) end
- A parameter written
self(p)has typeselfand needs no annotation. self(p)is also a pattern in acasearm and a binding (self(m) = other) for anotherselfvalue.- Named as a value,
selfis the constructor (ns |> Iter.map(self)). Tmay be a type parameter of the interface:interface Wrapper<T>withfn unwrap(self(x)) -> T where self: Distinct<T>servesimpl Wrapper<Int> for UserIdandimpl Wrapper<String> for Name.- A free function bounded by
where D: Distinct<T>cannot takeDapart or build one. - An implementor that is not a distinct type over
Twrites the function. The error at its impl is`Count` does not implement Distinct<Decimal>, which `Temperature.label`'s default requires (`where self: Distinct<Decimal>`), with the hint`Count` wraps Int, so it is not a Distinct<Decimal>; write `fn label` in this impl. - An opaque type implemented outside its own file (§4 Opaque distinct types)
satisfies
Distinct<T>but does not get a default that takes it apart or builds it:`Meters` is opaque here, so it can't use `Scaled.scale`'s default, which builds and takes apart `self`; write `fn scale` in this impl. Writing the function is then allowed even when the default is final. self(...)in a default without the bound is`self(...)` needs `where self: Distinct<T>` on this function. Outside an interface default it is`self(...)` only appears in an interface's default function. Against a value of the interface’s own type it is`self(...)` takes apart a value of type `self`.
Requiring a Value
Section titled “Requiring a Value”An interface declares functions only. A value every implementor must supply is a function requirement, read with a qualified call:
interface Tagged fn tag(value: self) -> Int end struct Event tag: Int name: String end impl Tagged for Event fn tag(value: Event) -> Int value.tag end end fn tag_of(x: Tagged) -> Int Tagged.tag(x) end fn main() dbg tag_of(Event{tag: 7, name: "start"}) // 7 end
A value of interface type or of type-parameter type has no fields, so x.tag
on one is an error (§14 Member access is fail-loud).
Implementations
Section titled “Implementations”Taught in Interfaces and Dispatch.
impl Iface for Type, its functions below and end, implements one
interface for one type. Its body holds that interface’s functions as plain
fn or host fn items, with the implementing type written where the
interface writes self. An impl with nothing to write, for a marker or a
default-only interface, is one line: impl Marker for P end. impl Type
with its functions below is an inherent impl: functions owned by the type,
called Type.f(...) (§8 Calls and qualification).
interface Formatted fn format(value: self, style: String) -> String end struct User name: String end impl Formatted for User fn format(value: User, style: String) -> String "User: ${value.name} (${style})" end end fn main() user = User{name: "Alice"} dbg User.format(user, "pretty") // "User: Alice (pretty)" dbg Formatted.format(user, "brief") // "User: Alice (brief)" end
- Impls, derives and the type are sibling top-level declarations. An impl block
holds only its interface’s functions: no inherent
fn, no nestedimpl, noderive. - Implementation functions do not write
self. Inside the block, sibling functions are called bare; outside, a call is qualified. - A generic receiver names its type parameters:
impl Formatted for Box<T>, neverimpl<T> Formatted for Box<T>.impl Formatted for Boxfor a genericBoxis`Box` expects 1 type argument, got 0, whose hint is the header to write. - Constraints on the type’s declaration apply to its impls. An impl’s
whereonly adds constraints:impl Iter for Range<T> where T: Discrete. - An interface whose functions all have defaults, or that declares none, is
implemented by the one-line
impl Iface for Type end. - One impl per interface, type and type arguments, program-wide. A duplicate is
an error (Several instantiations for one type), and so is an impl beside a
deriveof the same interface (Derive). - A file holding an impl does not itself implement anything. A stateless API that must take part in an interface is a zero-sized type with an impl.
- Nomi has no extension methods. A file cannot add type-qualified members to an imported type; it writes file-level functions beside it.
- The functions of an impl have the interface’s visibility. Implementing a public interface lets every caller dispatch every function of it, defaults included, on the type. To use an interface’s defaults only inside a file, implement it on a private distinct type that wraps the public one.
derive Iface for Type asks the compiler to write the impl (Derive). It may
take options after with and constraints after where, with first:
derive Display for Box<T> where T: Display derive ToJson for User with ToJson.Options{rename_all: Json.Case.Camel}
Matching an impl to its interface
Section titled “Matching an impl to its interface”An implementation function matches the interface function’s signature after
the header’s type arguments replace the interface’s type parameters and the
receiver replaces self.
- Parameter names match, since a call may name its arguments. A name at a
position typed exactly
selfis free.fn format(report: Report, s: String)forformat(value: self, style: String)is the errorimpl function 'format': parameter name 's' does not match interface declaration 'style'. A parameter the body does not read is named in the discard form:_stylematchesstyle, and a call still names the argumentstyle. - A
selfposition takes the receiver.fn greet(p: Person)inimpl Greeter for Peonisimpl function 'greet': parameter 1 has type Person, but it stands forself, which this block implements for Peon. - Types match, a result naming
selfincluded (fn make(n: Int) -> selfimplemented forDayreturnsDay). A function the interface declares with no result returnsUnit. A mismatch names the function to write:impl function 'add': parameter 2 has type Day, but interface 'Add' declares Days, with the helpinterface 'Add<Days, Day>' requires `fn add(lhs: Day, rhs: Days) -> Day`. - Each header type argument names a type:
impl Add<Dbys, Day> for Dayisunknown type "Dbys". - The impl’s own type parameters are fixed inside it: where the interface
requires
T, the function takes or returnsT, never a concrete type or another parameter. - A function-level type parameter may be renamed, but each of the interface function’s corresponds to exactly one of the implementation’s. The implementation may not fix one to a concrete type, merge two, or replace one with an impl parameter.
- An implementation function’s
wheremay only repeat bounds a call through the interface already guarantees: the interface function’s own bounds and, for an impl parameter, the bounds on the impl block and the receiver’s declaration. A bound on an impl parameter belongs on the impl block.
Function Name Collisions
Section titled “Function Name Collisions”When a type implements two interfaces that declare the same function name, a type-qualified call is ambiguous and must be interface-qualified:
interface Speaker fn speak(value: self) -> String end interface Performer fn speak(value: self) -> String end struct Dog name: String end impl Speaker for Dog fn speak(value: Dog) -> String "${value.name}: woof" end end impl Performer for Dog fn speak(value: Dog) -> String "${value.name} takes a bow" end end fn main() rex = Dog{name: "Rex"} dbg Speaker.speak(rex) // "Rex: woof" dbg Performer.speak(rex) // "Rex takes a bow" end
Dog.speak(rex)is the errortype 'Dog' impl 'Performer' and 'Speaker', which each declare 'speak' — type-qualified 'Dog.speak(...)' is ambiguous; qualify by interface, e.g. 'Performer.speak(...)'. This holds wherever the impls are, a third file included, and for defaults the type inherits as for functions its impls write: two interfaces that each giveDoga defaultspeakmakeDog.speak(rex)ambiguous, whether or not the calling file imports either.- A type’s own function may not share a name with a function its interface
impls write, in any file or order, since Nomi does not overload. Beside
impl Multiply<Int, Box> for Box, an inherentfn multiplyis the error`Box.multiply` is already `Multiply<Int, Box>`'s `multiply` for `Box`, and Nomi does not overload, so a call `Box.multiply(...)` would name both; give this function another nameat the inherent function’s name. - The same holds for a default the type gets from an interface whose impl
does not write it. Beside
impl Ord2 for Odd, whereOrd2declaresopen fn least, an inherentfn leastis the error`Odd.least` shadows the default `least` that `Ord2` gives `Odd`, and Nomi does not overload, so a call `Odd.least(...)` would name both; to override the default, write `fn least` in `impl Ord2 for Odd` instead. For a final default the error ends`Ord2`'s `least` is final and cannot be overridden, so give this function another name, and for a derived impl it says to rename the function or replace the derive with a written impl. DisplayandDebugname their functionsto_stringandinspect, so a type implements both without a collision.
No interface inheritance
Section titled “No interface inheritance”An interface does not extend another, and requires nothing of its implementors
but its own functions. A function that needs two contracts names both in its
bound. A typealias may name the conjunction:
typealias SortableValue Sortable and Comparable fn sort<T>(list: List<T>) -> List<T> where T: SortableValue list end
The alias names the interface conjunction Sortable and Comparable, which is
a bound in a where clause and a value type anywhere else (Interface
conjunctions).
A collection of values of several types is an enum with embeds variants
when the set is closed (§4), and an interface-typed collection when callers
supply their own types (Interface values).
Bounds and dispatch in generic code
Section titled “Bounds and dispatch in generic code”Taught in Interfaces and Dispatch.
where T: Iface requires every type argument for T to implement Iface.
For Equatable and Hashable that means having equality: a declared type
with no impl of its own meets either bound when == accepts it (§5
Equality bounds). Several
bounds join with and: where T: Showable and Tagged. There is no or: a
T bounded by one interface or another could call neither’s functions, so
where T: Priced or Costed is `where` bounds combine with `and`: a type parameter bounded by one interface or another could call neither's functions; declare an interface both implement, or bound on one
at the or. A generic header introduces names only; constraints go in the where clause,
after a function’s result or after a type declaration’s parameter list. Every
type parameter is in scope in the whole header and the where clause.
fn step_by<T, S>(r: Range<T>, by: S) -> Iter<T> where T: Comparable and Steppable<S> StepByRange{range: r, by:} end opaque struct StepByRange<T, S> where T: Comparable range: Range<T> by: S end
What a body may use. A generic body runs for every type argument its
callers pass, so an interface it needs of a T value is one of T’s bounds,
from the function’s where, its impl block’s, or its type’s declaration. That
covers an interface-qualified call or pipe, "${value}", an ordering or
arithmetic operator, and a call of a generic function that bounds it.
A T value with where T: Iface also enters any position of type Iface:
a parameter, an annotated binding, a list element, a result or a struct
field. It is held there as an interface value of the type argument the
caller passed (Interface values). For a generic interface the bound’s type
arguments must be the position’s: where T: Conv<String> does not make a
T a Conv<Int>.
fn take(x: Display) -> String "${x}" end fn wrap<T>(v: T) -> String where T: Display take(v) end
Without the bound it is the position’s ordinary mismatch, with a hint
showing the signature with the bound added: take(v) in fn wrap<T>(v: T) -> String is argument 1: expected Display, got T, with the help require it in the signature: `fn wrap<T>(v: T) -> String where T: Display` .
- Without the bound the use is an error:
`x` is a `T`, and `f` does not require Display of `T`, with a hint showing the signature withwhere T: Display. A value that holdsTis reported as`xs` holds values of `T`, and `f` does not require Display of `T`. - On an interface impl the hint puts the bound on the block (
impl Display for Box<T> where T: Display). On an inherent impl it puts it on the function. Debugneeds no bound, since every type implements it, and neither does==.
At the call. A type argument that does not satisfy a bound is an error:
sort([{x: 1}]) is no impl of `Comparable` for `{x: Int}`; anonymous struct types cannot implement `Comparable` . The help offers what the program
can write:
- for a type the program declares,
derivewhen the interface is derivable, and an impl block spelled with its required functions; - where the program declares neither the type nor the interface, a note that the orphan rule forbids the impl;
- for an interface at most four types implement, their names: with
fn has<M>(text: String, m: M) -> Bool where M: Matcher,has("a1b", 1)isInt does not implement Matcher (required by `where M: Matcher`)with the helponly std can implement `Matcher` for `Int`; `Codepoint`, `Regex` and `String` implement it; - otherwise, to wrap the type:
only std can implement `Comparable` for `Ordering`; wrap it in a type of your own that implements `Comparable`.
Tuples, anonymous structs and functions. No impl can be written for a tuple, an anonymous struct or a function type, so none of them implements an interface the program declares. What each implements of std’s:
- A tuple implements
Equatable,Hashable,ComparableandDisplaywhen every element does, andDebug. - An anonymous struct implements
StructandDebug, andEquatable,HashableandDisplaywhen every field does. It implements std::parse’sParseFields, which reads named texts into its fields and writes them back, when every field implementsParseandDisplay. It implements std::json’sToJsonandFromJsonwhen every field does, as a struct that derives them with no options: an object keyed by its field names as written, keys it has no field for ignored, and a missing key read as the field type’sfrom_missing(Derive). SoResponse.json({error: "no todo 99"})sends{"error":"no todo 99"}andJson.decode_as<{title: String, order: Maybe<Int>}>(text)reads a request body. A tuple implements neither. - A function implements only
Debug.
The same rule decides a bound and an interface-typed position (Interface
values): a parameter, a field, a list element, or a map key of type
Hashable. So a where T: Hashable bound takes (1, "a") and
[(1, 2)], and refuses (1, f) for a function f:
(Int, (Int) -> Int) does not implement Hashable (required by `where T: Hashable`). One difference: an interface value holds an implementor, so a
position of type Equatable or Hashable takes a declared type P only
when P has an impl, where a bound takes any P with equality.
fn f(h: Hashable) called with (1, p) for a p: P with no impl is argument 1: expected Hashable, got (Int, P), with help that begins `(Int, P)` is Hashable when each element is, and `P` is not. A where T: Shape bound refuses (1, 2) with the help no impl can be written for a tuple, which implements only Equatable, Hashable, Comparable and Display, each when every element does; declare a struct of your own that implements `Shape` .
A tuple held as an interface value behaves as the tuple does: its
Hashable.hash is the tuple’s own hash, two equal tuples are ==, and
"${d}" renders it as the tuple renders.
Calls through a bound. In generic code, call an interface function through
the interface (Formatted.format(item, style)) or through the bounded type
parameter (T.format(item, style)). The checker resolves T to the bound that
declares the function, and the call selects the impl for the concrete type
bound to self. An unbounded T, a function no bound provides, and a function
two bounds both declare are errors; the last must be interface-qualified.
Named arguments use the interface’s parameter names.
An interface-qualified call is required in two cases: when the static type is the interface (Interface values), and when two of a parameter’s bounds declare the same function name.
Generic interfaces
Section titled “Generic interfaces”An interface may have type parameters: interface Container<T>. In it, self
is the whole implementing type with its type arguments.
- An impl writes the interface’s type arguments in its header (
impl Add<Days, Day> for Day) or leaves them to be inferred from its functions’ signatures when the type implements the interface once (impl Iter for List<T>, itsTread fromeach_while). - A type parameter of the interface names a type the implementor determines.
An interface-typed parameter (
container: Container<T>) or a bound (where I: Iter<T>) projects it:saw_any([10, 20])forfn saw_any<T, I>(it: I) where I: Iter<T>solvesI = List<Int>andT = Int. There is no separate associated-type syntax. - A type parameter that only a bound and the result name is projected the same
way:
plus(Day(10), Days(4))forfn plus<L, R, Out>(lhs: L, rhs: R) -> Out where L: Add<R, Out>is aDay.
Several instantiations for one type
Section titled “Several instantiations for one type”A type may implement one generic interface at several type arguments: impl Contains<String> for String, impl<C> Contains<Regex<C>> for String and impl Contains<Codepoint> for String are three impls (the second’s <C> declares
the parameter its argument names, since the receiver names none).
interface Holds<T> fn holds(b: self, x: T) -> Bool end struct Box n: Int s: String end impl Holds<Int> for Box fn holds(b: Box, x: Int) -> Bool b.n == x end end impl Holds<String> for Box fn holds(b: Box, x: String) -> Bool b.s == x end end fn held_by<C, T>(c: C, x: T) -> Bool where C: Holds<T> C.holds(c, x) end fn main() b = Box{n: 1, s: "a"} dbg Box.holds(b, 1) // True: Holds<Int> dbg Holds.holds(b, "b") // False: Holds<String> dbg held_by(b, "a") // True: the bound at String end
- Each impl writes its type arguments. An impl that leaves them to be
inferred beside another impl of the interface for the type is
`Box` implements `Holds` more than once, so each impl writes its type arguments in its header, whose help is the header (write `impl Holds<Int> for Box`). - No two overlap. Either every impl names distinct concrete type
arguments, or there is one impl, generic in them.
impl Holds<T> for Wrap<T>besideimpl Holds<Int> for Wrap<T>isoverlapping impls: `Holds<T>` for `Wrap` is generic in its type arguments, so it covers `Holds<Int>`, which `Wrap` also implements. Two impls at the same arguments areduplicate impl: `Holds<Int>` is implemented for `Box` by modules ... (function `holds`); a type implements an interface once at each set of type arguments, which names the modules that declare them. - The orphan rule applies to each impl (Foreign Types).
- A call takes the impl its arguments’ types choose, statically, in every
call form: type- or interface-qualified, a pipe stage, a partial capture, an
operator, and a generic call whose bound the call solves. An argument whose
type its parameter decides (
.Variant, an open&1) does not choose. - A type argument only the result names is chosen by the expected type, as a
generic call’s result-only type parameter is (§5): with
impl Make<Int> for Factoryandimpl Make<String> for Factory,n: Int = Factory.make(f)calls the first. - When nothing chooses, the call is an error naming the candidates:
`Holds.holds` for `Box` has impls at `Color` and `Shade`; the argument's type does not choose one: annotate it,`Make.make` for `Factory` has impls at `Int` and `String`; only the result's type tells them apart, and nothing here expects one: annotate the result, and`Holds.holds` for `Box` has impls at `Int` and `String`, and none takes `Float`. A bound the call leaves open is`Box` implements `Holds` at `Int` and `String`, and the call's arguments do not choose one for this bound: annotate them. - A value held as an instantiation (
h: Holds<Int>, aList<Holds<Int>>) takes any type with an impl at those arguments, and a call through it dispatches to that impl. A type that implements two instantiations is held as either:a: Holds<Int> = bands: Holds<String> = bare both accepted.
Foreign Types
Section titled “Foreign Types”Taught in Interfaces and Dispatch.
An impl may implement an imported interface for a local type, a local
interface for an imported type, or both local, as the orphan rule permits. A
std generic container is an imported type like any other: a module’s own
interface may be implemented for it generically (impl Show for List<T> where T: Show), at a partly concrete instance (impl Show for Map<String, V> where V: Show) or at a concrete one (impl Sized for List<Int>). A concrete instance
beside a generic impl of the same interface over the same container is a
duplicate.
An impl block is part of a program when its file is, and a file is when some
file in the program imports it. Then the impl applies everywhere in the
program, in files that do not import it too. A file of impls only is brought
in with an import that names nothing from it (import html_impls), which
counts as used when the program uses one of its impls (§14 Unused imports are
errors). std’s impls are always part of the program. Coherence allows at most
one impl per interface, type and type arguments program-wide, so a call never
depends on which file it is in.
Orphan rule. An impl Iface for T block must have Iface or T declared
in the current module (§14). A program outside any module is one module, rooted
at its project root (tooling reference),
so impl Debug for Bool in a lone script is an orphan impl: orphan impl: Debug(declared in module "std") forBool(declared in module "std") cannot be implemented in module "..." (functioninspect): the interface, the implementing type, or a type heading a type argument the interface's functions take must be declared in the implementing module.
A local type argument. An impl of a foreign interface for a foreign
receiver is also allowed when a type the module declares heads one of the
interface’s type arguments, and that argument is an input: the interface names
its type parameter in a parameter type of one of its functions (Rhs in
Multiply<Rhs, Out>, T in Contains<T>). One named only in results (Out)
is not.
struct Rate per_unit: Decimal end impl Multiply<Rate, Decimal> for Decimal fn multiply(lhs: Decimal, rhs: Rate) -> Decimal lhs * rhs.per_unit end end fn main() rate = Rate{per_unit: 4.25d} dbg 12.5d * rate // 53.125d dbg 2d * 3d // 6d: std's impl end
The impl must also meet three conditions (Rust’s RFC 2451, narrowed to inputs). The orphan error names the one it breaks:
- The local type heads the argument.
RateandRate<Int>count;List<Rate>does not, since std keeps the freedom to implement an interface generically over its own container there:`Rate` is declared in this module but does not head the type argument `List<Rate>`. - No bare type parameter comes first. Neither the receiver nor a type
argument before the local one is a bare type parameter:
impl<T> Multiply<Rate, T> for Tisits receiver is the bare type parameter `T`. - Not generic in that position.
impl Contains<Tagged<T>> for List<T>isthe impl is generic in `Contains`'s type parameter `T` (`Tagged<T>`).
A local type in a result-only position is an orphan impl, since it would compete
for calls that exist: `Rate` stands in `Multiply`'s type parameter `Out`, which only results name. std’s Literal admits no impl this way (a typed literal's handler is chosen by its type alone, §18). Only the module that
declares Rate can write an impl naming it, which keeps coherence.
Two libraries may each add an instantiation to one std interface and receiver
(Multiply<Rate, Decimal>, Multiply<Shares, Decimal>). Both stand beside
std’s Multiply<Decimal, Decimal>, since they name distinct type arguments,
and a call takes the impl its arguments choose. An impl generic in that type
argument overlaps them. When the generic impl is std’s, the error is at the
program’s impl: impl Contains<Rate> for List<Rate> is overlapping impls: std's `Contains<T>` for `List` is generic in its type arguments, so it covers `Contains<Rate>`, which this impl implements.
Interface values
Section titled “Interface values”Taught in Interfaces and Dispatch.
A value of interface type holds a value of any implementor. An interface
requires nothing of its implementors but its own functions, so the interfaces
a Scale value can be used at are Scale, Debug, Equatable and
Hashable.
- A value whose type does not implement the interface is the position’s
mismatch,
argument 2: expected Matcher, got Int, with the help a bound gives the same type:deriveor an impl block for a type the program declares, and for a std interface and type,only std can implement `Matcher` for `Int`; `Codepoint`, `Regex` and `String` implement it. - Any other use (
Display.to_string(other),"${other}",a < b,Iter.sort(scales), a generic call whose bound names another interface) is an error at the use:`other` is a `Scale`, and Scale does not require Display of its implementors, whose hint writes a type parameter bounded by both. ForComparableit adds that values of different types have no order:`a` is a `Scale`, and Scale does not require Comparable of its implementors: values of different types have no order. ==and!=on two interface values, and aSetelement orMapkey of interface type, compare the held values. Values held as different concrete types are unequal: aPointand aSpotwith the same fields, anIntand aString, two empty lists of different element types, a value of an enum with anembedsvariant and a value of the struct it embeds. Values of one concrete type compare as==on that type does (§5 Equality and Ordering Semantics), and hash by its hand-writtenimpl Hashablewhen it has one. The same holds for values held asDisplayorDebug, and for==and!=between an interface value and a value of a concrete type, on either side:t == (1, "a")for at: Equatablecompares as if the tuple were held as anEquatabletoo.- So an interface value satisfies an
EquatableorHashablebound with that meaning (List.contains(scales, s),Iter.to_set,derive Equatableover aScalefield). AnIter<T>value is the exception: it is a function and has no equality. - A call through the interface needs only the receiver to be the implementor.
A function whose result is
self, that takes a secondselfor a value holdingself, cannot be called on an interface value:`Sized.same` cannot be called on `e`, a `Sized`: its result is `self`, the implementor's own type, and a `Sized` value does not say which implementor it holds. A function with noselfparameter called through the interface is an error unless the expected type names the implementor (p: Pot = Sized.make(1)) or the call is in one of the interface’s defaults:`Sized.make` has no `self` parameter, so this call does not say which implementor of Sized runs. Through the implementing type or a bounded type parameter every such call is accepted. - A generic function that instantiates itself at an ever-growing type (
fn grow<T>(x: T)callinggrow(Box{inner: x})) is a compile error at that call (§4 Generics).
Interface conjunctions
Section titled “Interface conjunctions”A and B is a type: a value of any type that implements both. It is written
wherever a type is, and typealias Name A and B names it.
interface Priced fn price(item: self) -> Int end interface Costed fn cost(item: self) -> Int end struct Coffee beans: Int end impl Priced for Coffee fn price(c: Coffee) -> Int c.beans * 3 end end impl Costed for Coffee fn cost(c: Coffee) -> Int c.beans end end fn margin(item: Priced and Costed) -> Int Priced.price(item) - Costed.cost(item) end fn main() items: List<Priced and Costed> = [Coffee{beans: 2}, Coffee{beans: 5}] dbg items |> Iter.map(margin) |> Iter.to_list() // [4, 10] both: Priced and Costed = Coffee{beans: 2} one: Priced = both dbg Priced.price(one) // 6 end
- Entering. A value converts into
A and Bwhen its type implements every member. Otherwise it is the position’s mismatch, with help naming the member it lacks:type mismatch: expected Costed and Priced, got Mug, helpMug does not implement Costed; write an `impl Costed for Mug` block. - Calls. A call through any member (
Priced.price(item)) dispatches to the held value’s impl. A use that needs an interface outside the members is the error Interface values gives:`item` is a `Costed and Priced`, and Costed and Priced does not require Display of its implementors. - Widening.
A and Bconverts toA, and to any conjunction of some of its members, at the top and at any position that converts (§5 Covariant conversion).Adoes not convert toA and B:a Priced value need not implement Costed, so it does not convert to Costed and Priced. Widening moves nothing at run time. - Identity. Members are interfaces, in any order, and one written twice
counts once:
A and B,B and AandA and B and Aare one type, shown with its members sorted by name. A member that is no interface is an error:`and` joins interfaces or subtypes, and Int is neither. - Equality.
==, hashing andDebugwork on a conjunction as on any interface value, through the held value (Interface values), soEquatable and Hashablevalues go in aSet. A conjunction with anItermember has no equality.Displayrenders only when it is a member. - Bounds. In a
whereclauseT: A and BboundsTby each member (Bounds and dispatch in generic code).
TryFrom
Section titled “TryFrom”TryFrom<E>, in the prelude beside From, makes a value from an E
when the E allows it:
interface TryFrom<E> fn try_from(value: E) -> Maybe<self> end
A type with a rule in its chain, its own when or a subtype it wraps
(§4 Validated types), implements TryFrom of its base because of its
rule and its base, as every distinct type satisfies Distinct<T>:
try_from is TryFrom’s function, with a body the compiler supplies,
which checks the base’s rules, then the type’s own, and answers Some
or None. That impl cannot be written by hand:
impl TryFrom<Int> for Percent, with type Percent Int when ..., is
`TryFrom<Int>` for Percent is supplied by its rule and cannot be implemented; every `type` with a rule over Int satisfies `TryFrom<Int>` automatically — remove this `impl TryFrom<Int> for Percent`.
An impl from any other source type is the program’s to write, one per
source type as From’s are, and T.try_from(x) picks by the argument’s
type. A subtype implements no interface of its own (§4 Subtypes), so
its try_from is its own function and no TryFrom impl.
type Celsius Float when fn c -> c >= -273.15 type Kelvin Float when fn k -> k >= 0.0 impl TryFrom<Celsius> for Kelvin fn try_from(Celsius(c)) -> Maybe<Kelvin> Kelvin.try_from(c + 273.15) end end enum Weekday Monday Tuesday end impl TryFrom<Int> for Weekday fn try_from(value: Int) -> Maybe<Weekday> case value 1 -> Some(Weekday.Monday) 2 -> Some(Weekday.Tuesday) _ -> None end end end fn load<T>(n: Int) -> Maybe<T> where T: TryFrom<Int> T.try_from(n) end fn main() dbg Kelvin.try_from(Celsius(20.0)) // Some(Kelvin(293.15)) dbg Kelvin.try_from(-1.0) // None day: Maybe<Weekday> = load(2) dbg day // Some(Tuesday) end
A type with no rule anywhere, type Plain Int, has no TryFrom:
load at a Plain is
Plain does not implement TryFrom<Int> (required by `where T: TryFrom<Int>`).
Display and Debug
Section titled “Display and Debug”Taught in Interfaces and Dispatch.
Display renders a value for users and Debug for developers:
interface Display fn to_string(value: self) -> String end interface Debug fn inspect(value: self) -> String end
Interpolation ("${x}") and io.print call Display.to_string. io.inspect
and dbg call Debug.inspect.
Display is opt-in. A type has it through an impl or derive Display.
Rendering a value without it is a compile error: "${p}" is no impl of `Display` for `P` (required via call site), with the help add `derive Display` to `P` or write an `impl Display for P` block, and io.print(p) is P does not implement Display (required by `where T: Display`). A function value has no Display: no impl of `Display` for `(Int) -> Int`; a function value has no `Display` . A tuple
or anonymous struct has Display when each part has it.
Debug is universal. Every type implements it, with no derive and no
impl, so there is no where T: Debug bound to write, and type variables and
interface values inspect. Precedence, highest first: a hand-written impl Debug, then derive Debug, then the synthesized impl.
| Construct | Display | Debug without an impl |
|---|---|---|
| struct, enum, distinct type | an impl or derive Display | structural, the same as derive Debug |
opaque type | only the owning file can write or derive one | the name only, <opaque T> |
host type | an impl | the bare type name, T |
| interface value | the held value’s | the held value’s |
| function or builtin value | none | <function> |
Task, Sender, Receiver, Arm | none | <task>, <channel>, <arm> |
Context | none | <context> |
Type<T> witness | none | Type<T> with the type as its declaration names it, Type<TraceId> |
lazy Iter (an adapter or constructor result, before materializing) | none | <iter> |
- Opaque types get the name-only default, so the floor never shows hidden
internals. The owning file writes
impl Debugorderive Debugto show structure (Derive). - Host types get the bare type name:
Bool’sembeds Trueinspects asTrue, andUnitasUnit. A host type whose values are Go handles (std’sRegex, ago-bound type) renders by its ownimpl Debugwhen it declares one, at the top level and nested, and otherwise by its name.Regex’s renders the typed literal that builds it (Regex`\d+`). - A lazy
Iterinspects as<iter>, nested too ([<iter>]), and is left unconsumed. AnIter<T>position holding a source rather than a pipeline (a list, a range, a value of a type with its ownimpl Iter) inspects as that source:[1, 2]. - Dispatch is keyed by nominal identity (declaring file, name), so two types
named
Pointeach keep their own impl. - Each type’s rendering is in its std module’s reference.
A lazy Iter has no Display: "${it}" and io.print(it) are
`it` is an `Iter<Int>`, and Iter<Int> does not require Display of its implementors.
Self-calls. An impl that renders, compares or hashes its own arguments through the function it defines calls itself forever, and is a compile error at that use:
- In
impl Display for Foo,fn to_string(foo: Foo)may not contain"${foo}",io.print(foo),io.write(foo),Display.to_string(foo)orFoo.to_string(foo):"${foo}" calls Display.to_string(foo), the function being defined, so it never returns, with the helpDebug.inspect(foo) renders its fields. - In
impl Debug for Foo,fn inspect(foo: Foo)may not containio.inspect(foo),dbg foo,Debug.inspect(foo)orFoo.inspect(foo). - In
impl Equatable for P,fn equal(a: P, b: P)may not compareaandbwith==or!=or pass them toEquatable.equalorP.equal:`a == b` calls P's `equal`, the function being defined, with its own arguments, so it calls itself forever, with the helpcompare the fields instead (`a.field == b.field`), or write `derive Equatable for P`. - In
impl Comparable for P,fn compare(a: P, b: P)may not compare them with<,>,<=or>=or pass them toComparable.compareorP.compare. Inimpl Hashable for P,fn hash(p: P)may not passptoHashable.hashorP.hash. - A plain binding of the argument (
same = foo) is the same value and the same error. Rendering, comparing or hashing a field, or another value of the type, is allowed, as is the receiver through the other interface.
Derive
Section titled “Derive”Taught in Interfaces and Dispatch.
derive Iface for Type asks the compiler to synthesize Type’s impl of
Iface from its fields or variants. One declaration derives one interface. The
synthesized impl is the one a program would write by hand, and dispatches like
any other.
struct Point x: Int y: Int end derive Equatable for Point derive Hashable for Point fn main() dbg Point{x: 1, y: 2} == Point{x: 1, y: 2} // True dbg Hashable.hash(Point{x: 1, y: 2}) // 33 end
- Targets. A
struct,enum, distincttypeorhost type. - Same file. A derive sits in the file and scope of the type’s declaration,
or in that file’s partner test file (§14 Visibility). A derive in any
other file is the error
`derive ... for T` must be written in the file that declares `T`, or in that file's partner test file. - Derives in a partner test.
api_test.nomimay writederive FromJson for TodoJsonfor theTodoJsonthatapi.nomideclares,pubor private, when it imports the name fromapi. The impl is the test file’s own, as a hand-writtenimplthere is: it is in a program only when the test file is, whichnomi testmakes the entry and an ordinary program reaches only by importing it. So production code that decodes aTodoJsonfailsnomi checkandnomi run, which do not compile the test file, even though its tests pass. The derived body is the one a derive inapi.nomiwould have: a field’s type means whatapi.nomimakes it mean, and the test file need not import it. The interface name resolves in the test file. A derive of an interfaceapi.nomialready implements for the type,Debugincluded, is the errorduplicate impl: `FromJson` for `TodoJson` is derived here and implemented in `api`. - Scope. The interface name resolves through ordinary scope: it counts as a
use, and a name not in scope is an error with the import to add:
`ToJson` is not in scope — import `std::json.ToJson`. Names inwithoptions are uses too.Debugneeds no import. Names only the synthesized code uses (Ordering,True, the recursive calls,Map.getinderive FromJson) need none. - Fields. Each field’s type must implement the interface, checked at the
derive:
no impl of `Display` for `User` (required via `derive Display for Wrapper`, field `id`), with the help to derive or implement it onUser. ForEquatableandHashablea field’s type implements the interface when it meets the bound (§5 Equality bounds): a structPwith no impl of its own is accepted when it has equality. A variant’s payload is checked the same way, named by its variant. When the field’s type is a std type, which a program cannot derive or implement an interface for, the help says so:only std can implement `Equatable` for `Json.ShapeError`; wrap it in a type of your own that implements `Equatable`. Every derivable interface butDebug, which every type has, is checked. A field of a tuple or anonymous struct type is checked part by part, since it implementsEquatable,Hashable,Display(and, for a tuple,Comparable) when each part does:f: (Int, P)isno impl of `Hashable` for `P` (required via `derive Hashable for W`, field `f`). An interface-typed field is not checked there, since its concrete type is known only at run time. A function has no equality, so a field that is or holds one cannot take a derivedEquatable,HashableorComparable:no impl of `Equatable` for `(Int) -> Int` (required via `derive Equatable for W`, field `f`), with the help to write an impl that leaves the field out. - With a hand-written impl. A derive beside an impl of the same interface
for the same type is the error
`derive Equatable for P` conflicts with a hand-written `impl Equatable for P` block — a derived impl is synthesized whole, so it cannot coexist with a manual impl; drop one. - Options. Only the per-declaration
withoptions. There is no per-field exclude or rename, and no user-defined derive. - Visibility. A derived impl’s functions have the interface’s visibility, as a hand-written impl’s do.
- Nomi has no decorators: an
@nameline is the parse error`@uses` is not supported: Nomi has no decorators.
Derivable interfaces
Section titled “Derivable interfaces”| Interface | Synthesized impl |
|---|---|
Equatable | Field by field with ==, stopping at the first difference. Enum values are equal when the variants match and then the payloads. |
Hashable | Hashable.hash(f0) * 31 + Hashable.hash(f1), folded left over the fields with wrapping arithmetic. An enum mixes its variant’s declaration index ahead of the payload. |
Comparable | Lexicographic in field declaration order. An earlier-declared variant is less than a later one, and ties compare the payloads. |
Debug | The literal shape: Point{x: 3, y: 4}, Circle(5.0) (the variant, with no enum prefix). |
Display | Debug’s shape with nested strings unquoted: C{name: bob} where Debug gives C{name: "bob"}. |
ToJson | Fields as object keys, each written as its type’s ToJson.to_json_field answers: Some(json) writes the key, None leaves it out. The default is Some(to_json(v)), so a None field is null; Presence<T>’s leaves an Absent field out. A distinct type through its inner value; a bare variant as its name, a payload variant as an object keyed by its name. ToJson.Options{rename_all: ...} sets the key case. |
FromJson | The inverse of derived ToJson. A missing key reads as its field type’s FromJson.from_missing(): Some(v) is the field’s value, as Maybe<T>’s None and Presence<T>’s Absent are. The default answers None, and then a defaulted field takes its default and any other is the error title: expected String, got missing. A mismatch names the variant and field. Every shape error names the Nomi type it expected and the JSON kind it got (Json.kind): title: expected String, got null, expected Todo, got array. FromJson.Options{rename_all: ...} sets the key case. |
Variants | Only for an enum without type parameters whose variants carry no data. variants() lists every variant in declaration order: Coin.variants() == [Coin.Penny, Coin.Nickel]. |
- The
Hashablemix collides easily:Hashable.hash(Point{x: 0, y: 31}) == Hashable.hash(Point{x: 1, y: 0}) == 31. It is meant for in-process bucketing. derive Displayandderive Debuggive the same output for a type with noStringinside it. Each variant shape renders as follows (Dis the derived interface applied to the part): a struct asT{f1: D(v1), ...}(T{}when empty); a bare variant as its name; a positional variant asV(D(p0), ...), with one part per element of a payload declared as a tuple (Node(Leaf(1), Leaf(2))) and one part otherwise (Some((1, 2))); a struct-payload variant asV{f: D(v), ...}; anembedsvariant as the embedded value’s rendering; a distinct primitive asT(D(inner)); a distinct tuple asT(D(a), D(b)); a distinct map, vector or set in the call form (Kvs({"a" => 1}),Path(Vector[1, 2]),Tags(Set["a"])); a zero-sized distinct as its name.Variantson anything else is an error at the derive that names the reason:`derive Variants for Shape`: variant `Shape.Circle` carries data, and `Variants` lists only variants that carry none; remove its data, or write `impl Variants for Shape` by hand. Generic code calls it through a bound:T.variants()withwhere T: Variants.- A
FromJsontarget is named by the implementing type (User.from_json(value)), an explicit type argument (FromJson.from_json<User>(value)) or an expected type.Json.encode_asandJson.decode_asconvert and encode or decode in one call (std::json). - std implements
ToJsonandFromJsonforMap<String, V>alone, since a JSON object’s keys are strings, and a tuple implements neither (Tuples, anonymous structs and functions). A derive over a field that holds either, directly or inside aList,Vector,Set,MaybeorMapvalue, is an error at the field:no impl of `ToJson` for `Map<Int, Int>` (required via `derive ToJson for W`, field `m`).
derive Debug on a type that is neither opaque nor a host type is redundant,
since the synthesized Debug is the same. It is accepted.
Generic types
Section titled “Generic types”derive Equatable for Box<T> implies the bound T: Equatable, checked at each
use. The implied bound for Debug is always met. The type may be named bare,
derive FromJson for Box, and the derive applies it to the declaration’s own
parameters: decoding a Box<Int> needs Int: FromJson, as a hand-written
impl FromJson for Box<T> where T: FromJson does.
Distinct types
Section titled “Distinct types”A derive delegates to the inner type: with type Id Int and derive Hashable for Id, Hashable.hash(Id(n)) == Hashable.hash(n).
Opaque types
Section titled “Opaque types”A pub opaque type may be derived. Equatable, Hashable and Comparable
show no structure. derive Debug replaces the name-only default with
structural output in place of <opaque Token>.
Host types
Section titled “Host types”A derive on a host type asserts the type has one inhabitant.
Equatable.equal returns True, Comparable.compare returns Equal,
Hashable.hash returns 0, and Debug and Display render the bare type
name. There are no fields to check. A host type that carries a value (such as
Instant) writes its impls with host fn items instead.