| @@ -0,0 +1,81 @@ |
| 1 | +# ADR 0019: User-defined derives |
| 2 | + |
| 3 | +**Status:** Proposed — 2026-10-09 (issue #49, v1 milestone M5); needs engineering review (#44). It extends the `@derive` part of [ADR 0007](0007-type-inference-and-traits.md). |
| 4 | + |
| 5 | +## Context |
| 6 | +`@derive` covered six prelude traits (`Eq`, `Ord`, `Show`, `Debug`, `Hash`, `Default`), each generated by Rust code in Core lowering. A library could not make its own traits derivable: a `ToJson`, a `Pretty`, a size or a checksum had to be implemented by hand for every type. |
| 7 | + |
| 8 | +What the mechanism should be: |
| 9 | +- **written in tilcayo, not as compiler plugins:** there are no Rust proc macros for users; |
| 10 | +- **type-checked once**, where it is written, not after expansion at each use; |
| 11 | +- **the same in both backends**, and simple enough to review. |
| 12 | + |
| 13 | +## Decision |
| 14 | + |
| 15 | +### A derivable trait names a derive function |
| 16 | +```tilcayo |
| 17 | +@derivable(json_of_constructor) |
| 18 | +trait ToJson<a> { |
| 19 | + fn to_json(x: a) -> Json |
| 20 | +} |
| 21 | + |
| 22 | +fn json_of_constructor(c: Constructor<Json>) -> Json { |
| 23 | + match c.fields { |
| 24 | + [] -> JStr(c.name), |
| 25 | + fields -> JArr([JStr(c.name), ..list.map(fields, fn(f) { f.value })]), |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +@derive(ToJson) |
| 30 | +pub type Shape { Dot Circle(Int) Rect(Int, Int) } |
| 31 | +``` |
| 32 | + |
| 33 | +**The structural view (prelude):** |
| 34 | + |
| 35 | +```tilcayo |
| 36 | +pub type Constructor<r> { Constructor(name: String, index: Int, fields: List<Field<r>>) } |
| 37 | +pub type Field<r> { Field(label: String, value: r) } |
| 38 | +``` |
| 39 | + |
| 40 | +A derived method sees a value as **its constructor** (a sum of products, `Generic`-style, but at the value level): the constructor's name, its index in the type's declaration, and its fields in order, each with its label (`""` when positional). |
| 41 | + |
| 42 | +**What `@derive(T)` on a type `D<p1..pn>` generates:** |
| 43 | +- the impl `T<D<p1..pn>> where T<pi>`, for each parameter `pi` of kind `Type` (as before); |
| 44 | +- the method `m(x) = f(Constructor(name, index, [Field(label, m(field)), ...]))`. Each field's value is **the trait's own method applied to that field**, through the field type's impl. A recursive type therefore recurses through its own derived impl. |
| 45 | +- Each field type must implement the trait (E0410, as before). |
| 46 | + |
| 47 | +**A derivable trait must have this shape** (E0412 otherwise): |
| 48 | +- one type parameter, of kind `Type`; |
| 49 | +- exactly one method, `fn m(x: a) -> R`. It takes one argument of the trait's type and has no effects and no `where` clause. Its result `R` mentions no type variable; |
| 50 | +- the derive function `f` is in scope in the trait's module, with type `fn(Constructor<R>) -> R`, total and without constraints. It may be polymorphic (`fn(Constructor<r>) -> Int`). |
| 51 | + |
| 52 | +`@derive(module.Trait)` names a trait of an imported module. |
| 53 | + |
| 54 | +**Why this design:** |
| 55 | +- **Simple:** the derive function is ordinary code, checked once like any other function. The compiler adds one small generator (about 70 lines of Core lowering) and one validation function. There are no templates, no new syntax, and no expansion before type checking. |
| 56 | +- **Useful:** it covers the common derives: serialization (`ToJson`), printing (`Show`, `Debug`, `Pretty`), and folds over the structure (size, checksums). |
| 57 | +- **Sound by construction:** derived code type-checks if each field implements the trait and `f` has the right type. Both are checked at the `@derive` and at the trait, not in generated code. |
| 58 | +- **Both backends:** derived methods are Core, so the interpreter and the C backend need no change. |
| 59 | + |
| 60 | +### The built-in derives |
| 61 | +- **`Show` and `Debug`** are derived through this mechanism: `@derivable(show_constructor)` and `@derivable(debug_constructor)`, with derive functions written in the prelude in tilcayo. Their output is unchanged, and the Rust code that generated them is gone. |
| 62 | +- **`Eq`, `Ord`, `Hash` and `Default`** stay derived by the compiler. They are marked `@derivable` without a function; only these four may be. |
| 63 | + - **`Eq` and `Ord`** take two values, and stop at the first differing field. As a consumer of one value, the list of fields would compare every field, eagerly. |
| 64 | + - **`Default`** produces a value rather than consuming one. |
| 65 | + - **`Hash`** is a consumer, but it is on lookup paths. Through the derive function, a derived hash allocates the constructor and its field list. On a three-field record (5M hashes, `--release`), that took 0.69 s instead of 0.26 s: 2.6 times slower. `Show` was 1.65 times slower (2M shows: 0.88 s instead of 0.53 s), where building strings already dominates. |
| 66 | + |
| 67 | +## Consequences |
| 68 | +- **The prelude exports two more names, `Constructor` and `Field`.** A module's own definitions shadow prelude names, so existing code is unaffected. |
| 69 | +- **Derived `Show` and `Debug` allocate** the field list per call (see above). Specializing known evidence (M2) and inlining the derive function could remove the allocation later. |
| 70 | +- **New diagnostic:** E0412 for an invalid `@derivable`. E0408 now says the trait is not marked `@derivable`. |
| 71 | +- **Tests:** |
| 72 | + - `tests/run/user_derive.til` runs on both backends. It covers `ToJson` on records, enums and a recursive generic tree, a `Size` trait with an `Int` result, and `Show` and `Debug` next to them; |
| 73 | + - `tests/run/derive.til` checks that the built-in derives print what they printed before; |
| 74 | + - `tests/ui/derives.til` covers every shape error, missing field impls, and a polymorphic derive function. |
| 75 | + |
| 76 | +## Alternatives considered |
| 77 | +- **Type-level `Generic`** (Haskell's `Rep` type family, with a generic impl over it). Exact and fast after optimization, but it needs type families or associated types, which ADR 0018 rejected for now. |
| 78 | +- **Templates expanded per constructor** (a `derive` block with `for field in fields`). No allocation, but new syntax in the parser, which another stream is changing, and generated code type-checked at every use: errors would point into expansions. |
| 79 | +- **Two more shapes: binary consumers and producers**, to also express `Eq`, `Ord` and `Default`. A binary shape would compare all fields eagerly unless field values became closures, which allocate more. The four built-in derives are not worth that complexity; a binary shape can be added if users need one. |
| 80 | +- **Several derivable methods per trait** (`@derivable(m1: f1, m2: f2)`). Nothing needs it yet. Single-method traits keep the attribute and the generated code simple. |
| 81 | +- **Compiler plugins in Rust.** Rejected: derives must be written in tilcayo. |