Skip to the content
Diaspar

Decision D010 · accepted in part; the rest proposed

Data and polymorphism: records, opaque types, protocols

A record of the language's design, as it stood on 2026-11-18: written for the people who build Diaspar, and kept as it was written. Its code is a sketch, not a program of the site, and an older record may show syntax that a later one changed. It names files of the language's source, which is not public yet.

Status: accepted (2026-11-15) for keyword field access without dot syntax, construction by name, reading old values through their own type description after redefinition, replacing a whole protocol implementation on redefinition in the same module, protocols as namespaces for their methods, and :derive; accepted (2026-11-18, decided by the review agent on the author's delegation) for a variant without fields as a value (§3c), to be implemented in the next migration wave; proposed for the rest

1. Records are data

A type defined with deftype is a record: a fixed set of named fields, stored at offsets for fast access, that behaves like a map from the outside.

(deftype Point [x y])

(def p (Point x: 1 y: 2))
p.x                  ; → 1 (D029)
(get p :y)           ; → 2
(assoc p :x 10)      ; → a new Point; updated in place if p is unique (D004)
p.z                  ; compiler warning and run-time error: Point has no field :z (D007, D029)
order.customer.address.city

Fields are read with the dot, p.x, and (.x p) for the result of a call (D029, which replaced the earlier "no dot syntax, (:x p)").

Superseded (2026-11-16) by D029 as the main form: a field is read with the dot, p.x, and chains order.customer.address.city. The example above shows the keyword access this section decided; the examples below use the dot.

Types with the same field names do not interfere. p.x looks at the type of p and reads :x from that type's layout. Records of different types are never equal: (= (Point x: 1 y: 2) (Vec2 x: 1 y: 2)) is false.

Records have structural equality, hashing, and printing by default.

2. Construction by name (accepted)

The names of fields are written as labels since 2026-11-17 (D030, "Fields and the options of forms are labels"): (Point x: 1 y: 2).

Values are constructed by field name, in any order. Positional construction is allowed only for types with exactly one field.

(Point x: 1 y: 2)          ; order does not matter
(Point x: 1)               ; warning, and an error at run time: :y is missing
(Point x: 1 y: 2 z: 3)     ; error: Point has no field z:

(deftype Meters [value])
(Meters 5)                 ; positional: one field only

(deftype Point3 [x y (z 0)])   ; a field with a default
(Point3 x: 1 y: 2)             ; z = 0

Patterns also use names: (match s (Shape.Rect w: w h: h) ...). Field order in deftype carries no meaning; the compiler chooses the memory layout.

Why: positional construction breaks silently when fields are reordered ((Point 1 2) swaps x and y after (deftype Point [y x])). Rust, Elixir, and Common Lisp's make-point construct by name; go vet warns about positional literals of imported types for this reason; Clojure's positional ->Point breaks when fields change. With one field there is nothing to swap, and adding a second field gives an arity error instead of a silent swap.

2a. Access: strict for records, open for maps (accepted)

Record Map
v.x, (.x v) (D029) the field must exist: a compile warning when the type is known, else an error the key must exist, else an error
(get v :x) an error if there is no such field nil if the key is absent
(get v :x default) the default the default

Keywords are not functions: Clojure's (:x v) is removed (accepted, 2026-11-16, D029), so a field read is always strict and an absent map key is read only with get.

A record's fields are declared, so a missing one is almost always a typo, and the error says so: User has no field :nmae with help: did you mean :name? User has fields :name, :email. When inference knows the type, the compiler warns before running (D007). A map is open data (JSON from a network), where absent keys are normal. Elixir draws the same line: user.name on a struct raises, map[:name] returns nil, and its compiler warns about unknown struct fields when it knows the type.

There is one access syntax, not two: records are their own kind (D013), unlike Elixir's structs, which are maps and need separate syntax to stay strict, and code such as (defn greet [x] (+ "Hello, " x.name)) works for both a record and a map.

For maps whose keys must be present (accepted; the shape of decoding is still to design):

  • Strict access: (fetch m :port) raises when the key is absent; with several keys it follows a path: (fetch user :address :city) raises "user has no key :address (at :address :city)". With the dot, user.address.city is as strict (D029); fetch remains for keys computed at run time.
  • Strict destructuring: shorthand in map patterns (D015): (let [#{port host timeout} config] …) binds the three names from the keys :port, :host, :timeout and raises when a key is missing. Nested map patterns are allowed but not the recommended style.
  • Data of a known shape becomes a record: (json.decode Config text) maps JSON names to fields explicitly (userId to user-id), reports errors with the path (at: .server.port, expected: integer, actual: "80"), and takes the policy for unknown fields as an option of the decoding call, not of the type: the same type may be decoded strictly from its own config and leniently from an external API. JSON keys are never turned into keywords silently ("@type", "user id"). The shape of decoding still needs design.

2b. Field metadata (accepted)

A field's default: and doc: and the options of forms are labels (D030); the namespaced keys derivers read stay keywords.

A field may carry metadata as keyword options, read by derivers; each deriver reads its own namespaced keys, so they do not clash. A default is written with default:; (z 0) stays as a shorthand when a default is the only option. A field's default is evaluated at each construction that omits the field (so (deftype Event [(at default: (now))]) stamps each event), by the same rule as defaults in patterns (D015). Python's dataclass and Elixir's defstruct evaluate a default once, when the type is defined, which freezes (now) or (uuid); requiring pure defaults would force a constructor function for this common case and differ from the rule for patterns.

(deftype User
  [(user-id :json.name "userId")
   (email   default: nil doc: "contact address")]
  derive: #[json.Codec Show])

3. Variants: defenum (accepted)

A type that is one of several variants is declared with defenum; deftype declares only records. match warns when a variant is not handled.

(defenum Shape
  (Circle [r])
  (Rect [w h]))
(defenum Color Red Green Blue)

(defn area [s]
  (match s
    (Shape.Circle r: r) (* 3.14 r r)
    (Shape.Rect w: w h: h) (* w h)))

Why a separate form: brackets are interchangeable (D008), so (deftype Point [x y]) and a single variant (deftype Shape (Circle [r])) have the same shape, and telling them apart by capital letters and nesting is fragile. enum is the word Rust and Swift use for the same thing.

3a. Enumerations, wrappers, constraints (accepted)

(defenum Color Red Green Blue)                    ; variants without fields
(deftype Meters [value])                          ; a wrapper: (Meters 5) and (Seconds 5) do not mix
(deftype Percent [value] where: (<= 0 value 100)) ; checked whenever a value is constructed

Variants catch misspellings and get exhaustiveness checks (D015); keywords stay for open data. A variant without fields is written by its name, Color.Red (§3c). A :where constraint is checked at construction, like Ferron's refinement types; a violation is an error.

3b. Variants are reached through their enum (accepted, 2026-11-16)

Outside the module that defines it, a variant is named through its enum, as Rust's Color::Red: (Color.Red). A bare (Red) is available only after an explicit import of the variants, (use std.term.color.Color [Red Green]), as Rust's use Color::*. So names such as Red or Error never appear in a module by themselves. (The separator is the dot, D029.)

Inside the defining module too (accepted, 2026-11-17): a variant is written through its enum everywhere, (Status.Error), (match s (Status.Ok) … (Status.Error) …), unless its variants are imported by the same explicit use with a list, which works in the defining module as elsewhere. So two enums of one module may have variants with the same name (Status.Error and FsOp.Error, KeyKind.Release next to the protocol Release), and a reader never has to know which enums a module defines to read a variant.

Superseded in part (2026-11-18) by §3c: a variant without fields is the value Color.Red, written and printed without the call; the (Color.Red), (Status.Error) and (Red) of this section are the spelling until the migration.

A variant prints as it is written, through its enum: (Shape.Circle r: 1), (Color.Red), and its type Shape.Circle (D030, "Printing follows construction"); the prelude's (Ok, Err, the runtime's errors) are written and printed bare (stated 2026-11-18). Since a variant is reached through its enum, its name does not hide the prelude's in its own module: with (defenum Unknown Ignore Error) in std.json, Error is still the protocol, and Unknown.Error the variant (stated 2026-11-18, when std.json gained that enum). Rejected: bare names inside the module when they are unambiguous (a name that reads fine today becomes an error when another enum of the module gains the same variant); choosing the enum by the inferred type, as OCaml does (too much machinery for a dynamically checked language).

3c. A variant without fields is a value (accepted, 2026-11-18)

Status: accepted (2026-11-18, decided by the review agent on the author's delegation). Not implemented: it belongs to the next migration wave, and until then the tools take the call, (Mode.Fast).

Until now a variant was a type and its value a call, also when it had no fields: Round.HalfUp named the type and (Round.HalfUp) was the value. From this decision the name of a variant without fields is the value itself, a constant like nil and true.

(defenum Mode Fast Slow (Custom [n]))

Mode.Fast                                  ; the value
(Mode.Custom n: 3)                         ; a variant with fields is constructed, as before
(Mode.Fast)                                ; error: Mode.Fast is a value, not a constructor

(decimal.round x 2 round: Round.HalfUp)    ; was round: (Round.HalfUp)
(term.pad s 10 align: Align.Right)
(= mode Mode.Fast)
(def speed #{Mode.Fast 100 Mode.Slow 10})  ; a key of a map, an element of a set

(match mode
  Mode.Fast        100                     ; matches that value
  Mode.Slow        10
  (Mode.Custom n:) n)

(defn pad [doc width align: (Align) Align.Left] …)   ; the type pattern (Align), the default Align.Left

(use app.Mode [Fast Slow])                 ; the variants imported (§3b)
(match mode
  Fast 100                                 ; the bare name is the value, in a pattern too
  Fsat 10                                  ; error: Fsat is not a variant in scope
  _    0)
(let [Total (sum xs)] …)                   ; error: a name that starts with an upper-case letter never binds

The rules

  1. The name is the value. A variant declared without fields (Fast, (Fast), (Fast doc: "…"), or with an empty field list) is a constant. Mode.Fast gives it wherever an expression stands, and so does Fast after an import of the variants (§3b). Nothing is constructed: it is the immediate constant D028 already gives such a variant, with no allocation and no counting.
  2. Calling it is an error, so there is one spelling. (Mode.Fast) and (Mode.Fast 1) are compile errors, in an expression and in a pattern; the head of the form is a name the expander resolves, so the error never waits for the program to run. Called through a variable, (f) with f holding Mode.Fast, it is the run-time error every call of a value that is not a function gives.
  3. In a pattern the name matches the value. A dotted name cannot be a new binding, so Mode.Fast in a pattern can only mean the variant. D015's principle holds: a pattern looks like construction, and the "construction" of this value is its name. A dotted name in a pattern must name a variant without fields; anything else is an error that says what to write: (Shape.Circle) for any Circle, (= math.pi) to compare with another value.
  4. Its type has no name. The type of the value still exists (dispatch, printing and reflection use it), and (type Mode.Fast) gives it. No name refers to it: protocols are implemented for the enum, and (extend-type Mode.Fast P …) and a field's of: Mode.Fast are errors that name the enum.
  5. Variants with fields and structs are unchanged. (Shape.Circle r: 1) constructs, Shape.Circle is the type, (Shape.Circle) as a pattern matches any Circle. A struct without fields stays (deftype Empty []), (Empty), and an effect without fields (perform (Tick)): a struct's name is its type, used wherever types are named.
  6. A name that starts with an upper-case letter never binds in a pattern. There a bare capitalized name must be a variant without fields that is in scope, imported or from the prelude; otherwise it is an error. It holds for every binding a pattern makes, as: and the shorthand of a field or a label included: a field named Width is given a local, (Box Width: w). To make the rule complete, a variant's name must start with an upper-case letter, where it is declared and where an import renames it with as:. So a pattern is read without looking at the imports: lower case binds, upper case is compared.

What follows from them

  • Equality, hashing, order. The value is = only to itself: Status.Error and FsOp.Error (§3b) are different values, and no variant is = to a keyword, a string or its ordinal (D013). It is truthy, and it is a key of a map or an element of a set like any value. Variants are ordered only through Ord, implemented or derived for the enum, as before.
  • Printing follows construction (D030): the value prints as Mode.Fast and Color.Red (was (Mode.Fast)), in pr-str, str, f-strings, the REPL, test reports and diagnostics; a variant with fields prints (Mode.Custom n: 3) as before. The type of the value prints as the code that gives it, (type Mode.Fast), so the two never print alike. Messages name it by its short name, as before: Fast.
  • Data (D033). data.write writes Mode.Fast. For data.read the name of such a variant is data of the same standing as a struct's (Point x: 1): what lets it read the one lets it read the other, and nothing is evaluated. Any other symbol in the text stays a ReadError.
  • Reflection (D034). (reflect.variants Shape) gives each variant as its name denotes it: #[Shape.Dot Shape.Circle Shape.Rect] holds the value Shape.Dot and the types Shape.Circle and Shape.Rect, and prints as it is written. So (reflect.variants Color) of an enum without fields is the vector of its values, Swift's allCases: (for [v (reflect.variants Color)] (v)) becomes (reflect.variants Color). Where std.reflect takes a type, a variant without fields stands for its own: (reflect.fields Shape.Dot) is #[], (reflect.variants Shape.Dot) its enum's variants, (reflect.from-map Shape.Dot #{}) is Shape.Dot, so code that walks reflect.variants and builds each one with from-map needs no special case.
  • Protocols. A call dispatches on the value as on any other, and finds the enum's implementation. (implements? P Mode.Fast) asks about the value, with the answer it had. (Named.label Mode.Fast) is an ordinary call with the value; it used to pass the type (§5a).
  • Opaque enums (§4). Outside its module the value of an opaque enum can be neither named nor matched: Lock.Open is the error (Lock.Open) was, in an expression and in a pattern. It can be passed, compared with =, and printed.
  • Redefinition (§5). A variant without fields has no fields for a redefinition to change, so it is one value in every version of its enum that declares it without fields: after (defenum Mode Fast Slow Medium) is evaluated in a running program, a Mode.Fast stored before is = to Mode.Fast and matches it. §5's "never =" is about values with fields. For the runtime: such a variant keeps its type id when its enum gets a new version (D028 §3, "A redefinition makes a new version", gave every variant a new one).
  • A variant that gains or loses fields. In the sources, every pattern Mode.Fast becomes a compile error once Fast has fields ("write (Mode.Fast) or (Mode.Fast n:)"), and every (Mode.Fast) once it has none. An expression Mode.Fast whose variant gained fields now gives the type; this is found when the value is used (a labelled slot's "takes a Mode, not the type Mode.Fast", "no clause matched"), and at compile time where a type is given to a slot whose pattern is an enum: D034's check of a constant given to such a slot now also takes a name that is a type. In a live program, a value made before the variant gained fields is an old value of it under §5: (Mode.Fast) matches it, and a field it lacks reads its default or is §5's error. After the variant lost its fields, the old records are not = to Mode.Fast, and the pattern Mode.Fast does not match them.
  • Exhaustiveness (D015). Mode.Fast and an imported Fast handle their variant, as (Mode.Fast) did; the help reads "add a clause for each, such as Mode.Slow, or _ for the rest".
  • Labelled slots and fields (D034). In align: (Align) Align.Left the first form is the type pattern of the enum and the second the default; in align: Align.Left the one form is the default. (Column align: Align.Left) builds, and as a pattern matches that field.
  • Map patterns. A value position takes the variant, #{:mode Mode.Fast}. The key position is unchanged: a symbol there is the shorthand for a keyword key (D015), so a capitalized name there is rule 6's error.
  • Macros and derivers. In syntax the value is one symbol, where it was a list of one; its scopes are those of its first segment (D029), so a template's Mode.Fast is found where the macro is defined. A deriver that writes code for each variant writes the name for a variant without fields and a call for one with fields; the description it receives says which (§7). A template that binds a capitalized name is rule 6's error at the template.
  • Top-level names. (def READ 0) at the top level is not a pattern and stays allowed. Used in a pattern, READ is an error with the help to write (= READ), where it used to bind a new local silently.

The messages

error: Round.HalfUp is a value, not a constructor
  --> invoice.dias:4:29
   |
 4 |   (decimal.round x 2 round: (Round.HalfUp))
   |                             ^^^^^^^^^^^^^^
   = note: HalfUp is a variant of Round without fields
   = help: write Round.HalfUp

error: Fsat is not a variant in scope
  --> app.dias:7:3
   = note: a name that starts with an upper-case letter never binds in a pattern
   = help: did you mean Fast? To bind the value, use a lower-case name

error: Shape.Circle has fields, so it is not a value to match
   = help: write (Shape.Circle) for any Circle, or take it apart: (Shape.Circle r:)

error: Mode.Fast is a value, not a type
   = help: implement Named for Mode, and match on the variant in its methods

error: a variant's name starts with an upper-case letter: fast
   = help: write Fast

Why

  • It is how the value is written everywhere else, and a call that passes nothing and constructs nothing says nothing: 857 pairs of parentheses in this repository.
  • It removes a silent trap. With the call, forgetting it gave the type, a value too: (= mode Mode.Fast) was false without a word, and (match Mode.Fast (Mode.Fast) …) did not match. Now the slip is the other one, (Mode.Fast), and it is a compile error.
  • The representation was already this: an immediate word per variant, compared as a word (D028).
  • Rule 6 costs nothing here and closes Rust's trap. No pattern in the repository's 64,910 lines of Diaspar binds a capitalized name, and every variant is capitalized. Without the rule, a bare Fast in a pattern would be compared when it is imported and would bind a new name when the import is missing or the name misspelt, turning a test into a clause that takes everything. That is so today: with Red imported, (match x Red …) binds. D030 removed the same kind of dependence from fields (a pattern is read without knowing the type), and D029 rule 3 from locals.
Language A variant without fields A bare name in a pattern
Rust Mode::Fast, a constant; Mode::Fast {} also reads, for macros decided by scope: a variant or constant in scope is compared, anything else binds. A missing import makes a catch-all; the lints bindings_with_variant_name (an error by default, and it needs the type of the matched value), non_snake_case and unreachable_patterns exist for it
Swift .fast, Mode.fast a binding is marked with let, so there is no question; .fast needs the type known
OCaml, Haskell, Gleam Fast by the grammar: constructors are capitalized, variables are not
Scala a case object or an enum case, Mode.Fast lower case binds; a capitalized or dotted name (a stable identifier) is compared; backquotes compare with a lower-case name
F# Fast, Mode.Fast by scope, as Rust; warning FS0049 on a capitalized name that binds ("may indicate a missing open declaration or a misspelt pattern name")
Python's match Mode.FAST a dotted name is compared, a bare name always binds
Kotlin an object of a sealed class or an enum entry: the value and its type under one name when compares; it has no binding patterns
Elixir, Clojure, Racket a keyword or an atom: an open set, with no check of the cases Elixir's variables are lower case by the grammar and compared with ^x; Racket's match always binds and compares with (== e)

Rule 3 is Python's and Scala's dotted name, rule 6 OCaml's, Haskell's, Gleam's and Scala's capital letter. Scala's backquotes are not needed: (= x) compares with any value.

Rejected

  • Keeping the call (Mode.Fast): the reasons above.
  • Both spellings, the name and the call, as Rust's Mode::Fast and Mode::Fast {}: two ways to write one value in every program for the benefit of a few macros, which know each variant's fields anyway.
  • (Mode.Fast) kept as a pattern, by D015's "(T) matches any value of the type": a second spelling of the same pattern, and one that no longer looks like the construction.
  • Rust's rule for a bare name in a pattern (compared when it is in scope, else bound) with a warning: the meaning of a pattern would depend on the imports, and the warning needs the type of the matched value, which is inferred and often unknown here (D007).
  • Python's rule (only a dotted name is compared; a bare one binds): an imported variant could not stand in a pattern, where §3b's import is most wanted.
  • Any dotted name as a value pattern (math.pi, a field p.x), as Scala and Python: (= math.pi) already says it, and with variants only, a dotted pattern is always a case of a closed set, which exhaustiveness counts. It can be widened later without breaking code.
  • A name for the type of such a variant (extend-type Mode.Fast, Kotlin's and Scala's object types): no code here implements a protocol for a variant without fields, and the enum's implementation with a match says the same in one place. It can be allowed later without breaking code.
  • reflect.variants giving types only: the common use, all values of an enum without fields, would need a second step for each, and the types print as (type Color.Red). A second function reflect.values: two functions for one question.
  • The name as the value for a struct without fields too, as Rust's struct Empty;: a struct's name is needed as its type (extend-type, (Empty) patterns, of:), and Swift, Kotlin, Scala and Python all keep Empty() beside Mode.fast.
  • A swift-like .fast resolved by the expected type: rejected in D029 and D034.
  • Capital letters enforced for every type, protocol and top-level name: only variants stand bare in patterns, so only they need it; the rest stays a convention.

Migration

For the next migration wave, in one change as D030's:

  • What is rewritten (counted by a script over the sources of main, aa39e33): 857 uses of a variant without fields in 108 files, 622 through the enum and 235 bare after an import (std 335, tests 468, the compiler 47, examples 5, the programs under docs 2). 241 of the 566 variants in the repository's 151 defenum forms have no fields.
  • The rewrite is mechanical: over the formatter's lossless reader (D031), every list of one item whose head the expander resolves to a variant without fields becomes that item, in expressions and patterns alike. It needs the resolution, not only the text: (Idle) may be a struct without fields, and (Circle) a pattern for a variant with fields. The tool is run once and not kept.
  • By hand: the 24 places that name such a variant without the call and mean its type today, all in tests of that behaviour (tests/cases/ctor-value.dias, the reflection tests); the two places that build each variant of an enum by calling it (std/term/color.dias, tests/dias/term-props.dias); the texts programs print, about 70 (E.V) in expect forms, snapshots and doc strings, recorded again; the examples in the decisions and design documents.
  • Rule 6 changes no source: no pattern binds a capitalized name and no variant is in lower case.
  • The order, since the compiler compiles itself: first the tools take the name as the value and still take the call; the sources are rewritten and the seed regenerated; then the call becomes an error. The interpreter, the compiler and the evaluator change together (D003), with the runtime's printer.
  • After it the call is an error with no mention of the old spelling beyond what the message says of any call of a value.

Open

  • Names in scripts without case cannot name a variant, as in Haskell, OCaml and Go's exports.
  • Whether a variant with fields whose own fields did not change also keeps its identity when another variant of its enum changes; D028 §3 gives it a new version today.
  • How data.read learns which types it may read; D033 does not say it for structs either.

3d. where: on variants with fields (accepted, 2026-11-18)

A variant of an enum that has fields may carry a where: constraint, with the rules of a struct's (§2b, D034): it is checked at every construction of the variant, assoc included, and a violation is a BadArgument naming the variant and the constraint.

(defenum Temperature
  (Celsius [deg] where: (>= deg -273.15))
  (Kelvin [deg] where: (>= deg 0)))

(Temperature.Kelvin deg: -1)   ; error: Temperature.Kelvin: where: (>= deg 0) failed

The FFI needs it: a C enum's (Unlisted [value]) variant may not hold a number the enum names, so that one C value is one Diaspar value (design/ffi.md §19).

4. Opaque types (proposed)

An opaque type's constructor is private to the module that defines it. Outside that module, values of the type can be neither constructed nor destructured, and access to its fields is an error everywhere. Inside the module, fields are read by destructuring.

;; src/bank.dias — the module bank
(deftype Account [balance] opaque: true)

(defn open [] (Account balance: 0))
(defn deposit [(Account balance: b) n]      ; destructuring: only inside bank
  (Account balance: (+ b n)))
(defn balance [(Account balance: b)] b)     ; a public getter, if wanted

;; src/app.dias — the module app
(use bank)
(bank.deposit (bank.open) 100)   ; works: public functions
(Account balance: 1000000)       ; error: Account's constructor is private to bank
acc.balance                      ; error: Account's fields are closed

This follows Rust: private fields mean a value can be neither built nor taken apart outside its module. No generated accessor names (such as Racket's account-balance) are needed.

Opaque types do not print their fields by default.

5. Redefining types in the REPL (accepted)

Every value points to its type's description. Compiled field access checks the description and reads at the cached offset; if the description differs, it looks the field up by name. The check is one comparison.

After a type is redefined, old values keep their old description and stay readable by field name. Reading a field an old value does not have returns the field's default if one is declared; otherwise it is an error ("this Point was created before :z was added"). The default is evaluated once per old value, on the first read, and remembered, so a default such as (now) does not change from read to read. Release builds, where types no longer change, may drop the checks.

A value made before a redefinition is never = to one made after it, even when its missing fields take their defaults: they belong to different versions of the type. A variant without fields has nothing a redefinition could change, and is one value in every version of its enum that declares it so (§3c).

Common Lisp updates old instances lazily on first access; Clojure makes old values a different type, which is a known pain. The description check follows JavaScript engines' hidden classes.

4a. Documentation on types (accepted)

deftype, defenum, and each variant take doc:, read by tools and derivers (help texts of std.cli subcommands, generated documentation).

5a. Protocol methods called on a type (accepted)

A protocol method may be called with a type value as its first argument, which dispatches to that type's implementation, as Rust's associated functions; this is how constructors and decoders that have no value yet are written:

(json.Codec.from-json Config data)    ; Config's implementation of from-json
(Config.from-json data)               ; the same, through the type (D029)

6. Protocols

Operations are declared in a protocol, separately from types, and implemented per type. A method call is an ordinary function call, dispatched on the type of the first argument.

(defprotocol Shape
  (area [s])
  (perimeter [s])
  (describe [s] (str "shape with area " (area s))))   ; a default implementation

(extend-type Circle Shape
  (area [c] (* 3.14 c.r c.r))
  (perimeter [c] (* 2 3.14 c.r)))

(extend-type Square Shape
  (area [s] (* s.side s.side))
  (perimeter [s] (* 4 s.side)))

(map Shape.area #[(Circle r: 1) (Square :side 2)])   ; each element uses its own implementation

Rules:

  • Redefinition in the same module replaces the whole block (accepted). Re-evaluating extend-type for the same type and protocol in the same module, for example in the REPL, replaces that protocol's implementation for that type entirely. Old and new methods never mix; methods missing from the new block disappear, and the partial-implementation warning lists them.
  • Partial implementation is a warning (proposed). A missing method gives a warning at extend-type and a clear error when called ("no implementation of Shape.perimeter for Circle"), unless the protocol has a default. CI may turn the warning into an error.
  • Orphan rule (proposed). A protocol may be implemented for a type only in the module that owns the protocol or the module that owns the type. Your own protocol for a foreign or built-in type is allowed; a foreign protocol for your own type is allowed; a foreign protocol for a foreign type is an error. If both owners implement the same pair, loading the second is an error. The workaround is wrapping the foreign type in your own, as with Rust's newtypes.
  • A protocol is a namespace for its methods (accepted). Every method has a path through its protocol: Shape.area, or geom.Shape.area from another module (D011). Two protocols may define methods with the same name, even in one module. A short name such as area is available only through an explicit use. Inside defprotocol P and extend-type T P, method names refer to P's methods. Methods remain ordinary functions.
;; src/geom.dias — the module geom
(defprotocol Shape (area [s]) (perimeter [s]))
(defprotocol Land  (area [l]) (owner [l]))      ; not an error: each protocol has its own area

(extend-type Circle Shape                      ; inside the block, area is Shape.area
  (area [c] (* 3.14 c.r c.r))
  (perimeter [c] (* 2 3.14 c.r)))

(Shape.area (Circle r: 1))
(Land.area my-plot)

;; src/app.dias — the module app
(use geom [Shape Land])
(use geom.Shape [perimeter])
(geom.Shape.area c)            ; the full path always works
(Shape.area c)                 ; the protocol is imported
(perimeter c)                  ; the method is imported explicitly
(area c)                       ; error: area is not imported
(map Shape.area shapes)

A short name can be imported from only one protocol: importing area from both Shape and Land is an error at the second use, resolved with as:, as in (use geom.Land [(area as: land-area)]). Elixir, also a dynamic language with protocols, makes protocols namespaces in the same way (Enumerable.count).

  • Plain functions from different modules are different functions (geom.scale, land.scale); importing both under the same short name is an error, resolved with as:.

Why protocols: implementations can be added and replaced in a running program without touching types or existing values; a protocol can be implemented for types you do not own, including built-in ones; there is no inheritance, behaviour is composed from protocols; a method is a function, so it can be passed to map; agents know Clojure protocols, and they resemble Rust's and Ferron's traits.

Single dispatch on the first argument is simple and fast (a table in the type description). Multiple dispatch, as in Julia and CLOS, is more powerful but more complex and admits ambiguities; it can come later as a library.

7. Derive (accepted)

Derivers are macros (accepted, 2026-11-17). A deriver is defined with defderiver and expanded by the same expander as macros (D015): it receives the type's description as syntax (the name, and each field and variant with its options and its place in the source), is hygienic, may take the description apart with patterns, and reports a problem with (syntax-error node "message" help: "…") at the field or option at fault, as a macro does. Rust's derives work this way: procedural macros over tokens with spans, which report errors with syn::Error::new_spanned. Rejected: an ordinary function over a map of the description, as until now (no positions, no hygiene: every name written in full).

(defderiver Codec [(TypeSyntax name: fields:)]
  (for [f fields]
    (when-not (json-name? f.name)
      (syntax-error f "a JSON field name must be text"
                    help: "write (email :json.name \"e-mail\")")))
  …)

deftype takes a derive: list. Each name refers to a deriver: an ordinary Diaspar function that receives the type's description (name, fields, variants) at macro-expansion time and returns extend-type code.

(deftype Point [x y] derive: #[Ord Json])
(deftype Account [balance] opaque: true derive: #[Eq Hash])

The standard derivers (Eq, Hash, Show, Ord, serialization) live in the standard library, written in Diaspar; users write their own the same way. Redefining a type in the REPL reruns its derivers, since they are part of the deftype expansion. The compiler needs nothing special beyond making the type description available during expansion.

Rejected alternatives

  • Classes with inheritance: closed, and they fit badly with live redefinition.
  • Short metadata keys implied by the deriver (:flag meaning :cli/flag inside derive: #[cli/Command]): a key's meaning would depend on which derivers are listed; keys stay fully namespaced.
  • Dot syntax p.x: a special case in the reader; / is the only path separator (D011). (Accepted later, D029.)
  • Maps only, as idiomatic Clojure: no type name, slower access, typos not caught.
  • Positional construction for several fields: breaks silently when fields are reordered.
  • Generated accessors such as account-balance: not in the Clojure vocabulary (D009), and unnecessary with private constructors.
  • "Last loaded wins" for protocol implementations, as in Clojure: silent conflicts between modules.
  • Multiple dispatch in the core: more complex; possible later as a library.
  • Protocol methods as flat module names, as in Clojure and Haskell: two protocols in one module could not share a method name, although extend-type already says which protocol a method belongs to.
  • Choosing among same-named methods by the argument's type, as Rust does: Rust resolves this at compile time with exact types; with inferred types and warnings (D007), the ambiguity would surface only at run time, and unrelated operations that share a word (a shape's area, a plot's area) would merge.

Open questions

  • Whether a missing field at construction is an error or a warning plus a run-time error.