Skip to the content
Diaspar

Decision D015 · accepted

One pattern language for the whole language; hygienic macros as in Racket

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 one pattern language, the principle that a pattern looks like construction, functions with several clauses, field shorthand in patterns, and (TypeName) matching any value of a type; accepted (2026-11-17) for impl patterns, implemented on 2026-11-18 in the interpreter, the compiler and the evaluator; accepted (2026-11-18, decided by the review agent on the author's delegation) for a variant without fields matched by its name and for capitalized names that never bind (D010 §3c), to be implemented in the next migration wave; proposed for macros with patterns and for sequence patterns that match the end of a sequence (D040)

Decision

Patterns take a value apart by its shape. The same pattern language is used everywhere a value is taken apart:

Where Example
match (match s (Shape.Circle r:) … (Shape.Rect w: h:) …)
let (let [(Point x: y:) p] (+ x y))
Function parameters and clauses (defn area ([(Shape.Circle r:)] …) ([(Shape.Rect w: h:)] …))
Labelled parameters (D034) (defn pad [doc width align: (Align) (Align.Left)] …)
Effect handlers (D005) (handle body (BadEntry line) [resume] …)
catch (D005) (catch body (NotFound path:) …)
Actor messages (D006) (receive (Get key: reply:) …)
Tests (D016) (is (match? (Ok value: _) (attempt (parse-int "42"))))
Macros (proposed) (defmacro unless ([test & body] …))

The principle: a pattern looks like construction

A record is built with (Point x: 1 y: 2) and taken apart with (Point x: x y: y); a vector is built with #[1 2] and taken apart with #[a b]; a map is built with #{:k v} and taken apart with #{:k v}. This also resolves the clash with interchangeable brackets (D008): [a b] is just a list, so a sequence pattern is written like a sequence literal, #[a b].

The patterns

Pattern Matches
42, "hi", :k, nil that value
Mode.Fast, an imported Fast that variant without fields (below; (Mode.Fast) until the migration)
x anything, bound to x; the name starts in lower case (below)
_ anything, not bound
(Circle r: r) a record or variant, by field names (D010)
(Circle) any Circle, fields ignored
(Shape) any value of the type Shape: any of its variants, for a defenum
(Meters v) a one-field type, positionally
#[a b & rest] a sequence
#[first & _ penult _], #[& init last] a sequence, by its end too (D040)
#{:type "circle" :r r} a map that has these keys; other keys are allowed
#{port host} a map with the keys :port and :host, bound to port and host (shorthand)
#{port (timeout default: 30)} :timeout may be absent; then timeout is 30
p when: (> p 0) with a guard
(or (Circle) (Square)) one of the alternatives
(Circle r: r) as: c a match, with the whole value bound to c (D030)
(= :primary) equal to a value computed by an expression
(impl Show Hash) a value whose type implements every protocol named (below)

A variant without fields, and capitalized names (accepted, 2026-11-18)

Status: accepted (2026-11-18, decided by the review agent on the author's delegation) with D010 §3c, which has the reasons, the prior art and the migration. Not implemented yet: until the migration the tools take (Mode.Fast), and a capitalized name binds.

A variant without fields is a value written by its name, so its pattern is its name: the principle holds, a pattern looks like construction.

(match mode
  Mode.Fast        100                  ; that value
  Mode.Slow        10
  (Mode.Custom n:) n)                   ; a variant with fields, as before

(use app.Mode [Fast Slow])
(defn speed ([Fast] 100) ([Slow] 10) ([(Mode.Custom n:)] n))

(match key
  (or Key.Up Key.Down) (scroll key)
  Key.Enter as: k      (submit k)
  _                    nil)

(defn pad [doc width align: (Align) Align.Left] …)   ; a type pattern, then the default
  • A dotted name in a pattern is a variant without fields, matched by =. It cannot be a binding, since a local has no dot. Any other dotted name is an error that says what to write: Shape.Circle, which has fields, is written (Shape.Circle) for any Circle; a constant or a field such as math.pi or p.x is compared with (= math.pi).
  • (Mode.Fast) is an error, in a pattern as in an expression: "Mode.Fast is a value, not a constructor". (T) stays the pattern for any value of a struct type, of a variant with fields, of an enum or of a kind.
  • A name that starts with an upper-case letter never binds. In a pattern a bare capitalized name must be a variant without fields in scope, imported with (use app.Mode [Fast Slow]) or from the prelude; it is found by its scopes, as any reference, so hygiene holds. Otherwise it is an error, "Fsat is not a variant in scope", with the nearest variant as help. This holds wherever a pattern binds: let, parameters, clauses, def in a body, loop and for, catch, handlers, as:, and the shorthand of a field, a label or a map pattern (a field named Width is given a local, (Box Width: w)). A variant's name must start with an upper-case letter, where it is declared and where an import renames it, so a name in lower case always binds and a capitalized one never does: a pattern is read without its file's imports.
  • Exhaustiveness counts Mode.Fast and an imported Fast as handling the variant, and the help names a variant as it is written: "add a clause for each, such as Mode.Slow, or _ for the rest".
  • A top-level constant with a capitalized name, (def READ 0), is not a variant: in a pattern it is the same error, with the help to write (= READ).

Functions with several clauses (accepted)

The parameters of each clause of a multi-arity function are patterns, as in Elixir. A call first selects the clauses whose number of parameters fits the number of arguments, then tries their patterns in order. A clause with & more fits any number of arguments from its fixed count up. A parameter may be followed by as: name, as a clause's pattern may: [(or (BigInt) (Int)) as: a] tests the argument and binds the whole of it to a. An operator's method written so says which operands it takes (D022), and an operand it does not take is the operator's own error (+ does not mix strings and BigInt values).

(defn step
  ([(Idle) (Jump)]          (Jumping :t 0))
  ([(Jumping :t) (Tick)]    (if (> t 30) (Idle) (Jumping :t (inc t))))
  ([state _]                state)
  ([state]                  (step state (Tick))))

(step (Idle) (Jump) 5)   ; error: step has no clause for 3 arguments (has 1, 2)
  • No clause for the number of arguments: an error listing the counts there are; a warning at compile time when the call is visible.
  • A fitting count but no matching pattern: an error naming the arguments ("step: no clause matched (Running) (Tick)"); a warning at compile time when inference sees an unhandled variant (D007).

Exhaustiveness

When the cases form a closed set (the variants of a type), match, clauses, and catch warn about unhandled variants; adding a variant to a type shows every place that misses it.

Accepted details (2026-11-16):

  • No inference is needed when the patterns name the variants. If the clauses' patterns are variants of one enum ((Shape.Circle r:), (Shape.Rect)), the missing ones are known from the enum itself, so both the interpreter and the compiler warn at compile time, with the same text and position:

    warning: match does not handle Shape.Square
      --> shapes.dias:6:3
       = help: add a clause (Shape.Square …), or _ for the rest
  • Several enums in one match are checked each on its own: for every enum that appears in the clauses, its missing variants are reported, one warning per enum (match does not handle Mouse.Move, Mouse.Scroll); an enum that is fully handled gives nothing.

  • A clause with when: does not count as handling its variant, since its guard may fail; _, a bare variable, or the type pattern (Shape) handles everything left.

  • With inference, the same check also covers match on values whose type is inferred, catch, function clauses and handlers.

Guards are ordinary code (accepted, 2026-11-16)

An error inside a when: guard is an error, as in Rust and OCaml, not "the clause did not match" as in Elixir: swallowing errors silently would hide bugs. A guard that applies only to some values tests for them first: n :when (and (number? n) (< n 0)).

Choosing between the tools

  • A closed set of cases (states, error variants, syntax tree nodes): variants and match, with exhaustiveness checks.
  • An open set of types ("anything that can be drawn"): protocols (D010).
  • Open data (JSON, options, map keys): keywords and maps.

Field shorthand (accepted)

Fields in patterns are labels since 2026-11-17 (D030): (Rect w: h: 0) binds w and matches h against 0, and a keyword in a pattern is always a value, so the earlier rule for keywords that name fields, and (= :h), are gone.

A field in a record pattern with no pattern after it binds a variable named after the field, as Point { x, y } in Rust, { x, y } in JavaScript, or {:keys [x y]} in Clojure:

(defn area ([(Rect w: h:)] (* w h)))        ; binds w and h
(Rect w: width h: height)                   ; renames
(Rect w: h: 0)                              ; binds w; h must equal 0

A label is followed by its pattern, or by another label or the end, which binds the field's name; a keyword is always a value, so (Button style: :primary) matches style equal to :primary and (Button style: size:) binds both fields. The shorthand applies to patterns; a construction gives every label its value.

Costs: a shorthand name can shadow an outer name (a field named count hides the function count), which gets a warning; two nested records with the same field name in one pattern bind the same name twice, which is an error that asks for a rename.

Shorthand in map patterns (accepted)

In a map pattern, a bare symbol where a key would be is shorthand: #{port host} takes the keys :port and :host and binds port and host. Keys in maps are keywords or strings, so a symbol in key position is unambiguous, and a keyword after a key is always a value to match:

(let [#{port host (timeout default: 30)} config] …)   ; an optional key, written like a field with :default (D010)
(let [#{port :host h} config] …)                      ; an explicit pair renames

(defn handle-event
  ([#{:type :click x y}] (click x y))                 ; :type equals :click; x and y are shorthand
  ([#{:type :key code}]  (press code))
  ([#{:type t}]          (log f"ignored event {t}")))

(let [#{json.type http.status} m] …)                  ; keys :json.type and :http.status, names type and status
  • Shorthand covers keyword keys only. String keys ("userId", "@type") are written as explicit pairs: #{"userId" uid}; data of a known shape is better decoded into a record (D010).
  • A map whose keys are symbols (in code handled by macros) is matched with quoted keys: #{'a v}.
  • Struct patterns have label shorthand ((Rect w: h:)), since a struct's fields are declared; a map's keys are open.

A default is evaluated when the pattern matches and the key is absent, every time, left to right, and may use names bound earlier in the same pattern: #{start (end default: (+ start 10))}. This is JavaScript's, Kotlin's, and Racket's rule, not Python's, which evaluates a default once at definition (so (now) would freeze); defaults are not lazy, so an effect in a default happens at a predictable place.

Rejected for maps: keyword shorthand (#{:status :active} would silently bind active instead of matching the value), Clojure's {:keys [...]} form with its separate :or and :as, and an & marker.

A map pattern matches maps only (accepted, 2026-11-17). #{host port} does not match a struct with the fields host and port; a struct is taken apart with its own pattern, (Config host: port:). Rust, Python's match (a mapping pattern needs a Mapping, an object needs a class pattern) and Go do the same; Clojure and Elixir, where a record or a struct is a map, do not.

  • A type is its meaning, not the set of its fields: Proxy and Database may both have host and port, and a pattern that took any value with those fields would take both, as a match whose first clause is a map pattern would silently take every struct before the clause written for it.
  • Opaque types (D010 §4) would need an exception, and a second way of taking a struct apart would bring the expectation that get and assoc work on structs, turning structs into maps, which D010 keeps apart.
  • The cost is the change of a map into a struct: every map pattern on it stops matching, and this is found when the program runs. So the failure says what to write: matching a struct against a map pattern raises, or adds to "no clause matched", the note "a map pattern does not match a struct: write (Config host: port:)"; and the compiler warns when it knows the value is a struct. A program that wants a struct as a map converts it explicitly with reflect.to-map, as Rust converts with From.
  • cli.simulate's result, kept a map by the std refactor so that its tests' map patterns kept working, becomes a struct, and the tests are rewritten.

Patterns for protocols: impl (accepted, 2026-11-17)

(impl P …) matches a value whose type implements every protocol named; implements? asks the same in an expression.

(catch (run-user-code)
  (impl Error) as: f (report f))          ; any error value, not anything at all; f is the Failure (D005)

(match x
  (impl Show Hash) (cache-key x)          ; implements both
  (or (impl Encode) (impl Show)) (save x) ; either: or-patterns already exist
  _ (skip x))

(implements? Error e)                     ; in an expression
(implements? Show Point)                  ; about a type, given the type as a value
  • The form says it is a protocol. A bare (Error) would read like a type pattern, and the reader could not tell which it is without finding the definition: the ambiguity D030 removed from fields.
  • What implements: an extend-type for the value's type, a derived implementation, or a built-in one (numbers implement Add). The answer follows the program as it is loaded: an extend-type evaluated in the REPL makes the same pattern match from then on.
  • A protocol, checked where it is read: (impl Square) with a type is an error, "Square is not a protocol", with the help to write (Square); a let whose impl pattern fails says which protocol is missing: "at [0]: :k does not implement Area".
  • Exhaustiveness: an impl pattern counts as a clause with a guard. It never makes a match over an enum exhaustive, even when every variant implements the protocol, so an extend-type added in another module cannot change this module's warnings.
  • Cost: the check is the lookup dispatch already does, by type id, with its cache (D026).
  • std-test found satisfies? false for a derived implementation; implements? replaces it, with that case as a test.

Rejected: (P) like a type pattern (above); only a predicate in a guard (it cannot be nested in another pattern, #[(impl Show) _]).

Sequence patterns that match the end (accepted, 2026-11-18)

Status: accepted, not implemented; the rules, the costs, the prior art and the questions for the author are in D040.

Patterns may follow the rest and match the last elements: #[first & _ penult _], #[a b & mid z], #[& init last]. One & at most; after it a name or _, then the patterns for the end; the sequence has at least as many elements as there are patterns beside the rest, and no element is taken twice. The rest is a list, as today. A sequence is a list or a vector, never an iterator or a string, so a pattern for the end always has an end to reach. Parameter vectors keep & rest as their last positional parameter. The sign stays &.

Macros with patterns (proposed)

A macro describes what its call looks like, with clauses like a function's, and a template for the result:

(defmacro unless
  ([test & body] `(if ~test nil (do ~@body))))

A call that fits no clause gets a diagnostic at the call site ("unless expects a test and a body"), as Racket's syntax-parse and Rust's macro_rules! give.

Hygiene: sets of scopes, as in Racket (accepted)

Macros are hygienic by Racket's model, "binding as sets of scopes" (Flatt, POPL 2016). Syntax objects already carry positions and bracket shape (D008); they also carry a set of scopes, and an identifier refers to the binding whose scopes are the largest subset of its own.

  • Names a macro introduces cannot capture the user's names, and the user's names cannot capture the macro's: a tmp inside a macro and a tmp at the call site stay different.
  • Identifiers in a macro's template resolve where the macro is defined. A macro that uses a private helper of its own module works when called from any module (D011): the reference keeps the defining module's scope, and privacy is checked against that module, not the caller's. This fixes the bootstrap's current failure, where such macros break across modules.
  • Deliberate capture is explicit: a macro that wants to introduce a name visible to its caller (an anaphoric it, a defn-like form that defines the caller's name) takes that name from the call or marks it with an explicit operation, as Racket's datum->syntax.
  • gensym remains for code that builds names by hand.
  • The capture operation is capture (proposed name, as built in the bootstrap): (capture 'it) gives a name the macro call's context; (capture sym ctx) gives it the context of a symbol from the call, for definers.
  • Literal symbols in syntax patterns match by binding, as Racket's free-identifier=?: a literal 'else does not match a caller's local or another module's global named else; unbound symbols match by name.
  • Locals may shadow special forms and macros, as in Racket: inside (let [if f] …) the user's (if …) calls f, while a template's if stays the special form. A shadowing warning comes with static warnings.
  • Top-level definitions introduced by a template are hidden: visible to the template's code only; using such a name from the caller is an error that suggests capture.

Phases: two, implicit (accepted)

Racket's model, without its ceremony:

  • Exactly two phases, compile time and run time; no further levels.
  • No for-syntax. (use m) makes a module available in both phases. The compiler tells apart what a macro's body calls (needed at compile time) from what its template produces (needed at run time); hygiene's scopes make that distinction.
  • Only run-time dependencies are linked into a binary; a module used only by macros is not.
  • Compile-time state never leaks into the program. Each phase gets its own instance of a module; macros may perform no effects beyond reading their own sources (D025) and may not read mutable cells while expanding, so expansion gives the same result in the REPL and in a build.
  • Cross-compilation is correct: macro code runs on the build machine, the program on the target (WebAssembly, another architecture).
  • The REPL is one live environment: a redefined helper is used by the next expansion, as Lisp users expect; with no effects and no cell reads during expansion, the REPL and a build agree.

Why: Racket's "separate compilation guarantee" (a module compiles the same wherever and in whatever order it is built) matters for a C backend, build caches, and several targets; Clojure's single environment lets compile-time state leak into AOT builds. Racket's explicit phase levels are hard to learn, so they stay implicit here.

Expansion order and names (accepted, 2026-11-16)

Decided while designing the expander written in Diaspar (design/expander.md); the interpreter and the compiler behave the same (D003).

  • A module expands in two passes, as in Racket (accepted, 2026-11-16; replaces "one pass"). The first pass goes through the top-level forms in order: it expands macros, defines macros as it meets them, and collects every definition of the module. The second pass expands the bodies, when all of the module's names are known. So a function may be used before its definition, and a macro is visible only after its definition: using it earlier is an error that names the definition below.

  • A module's own definition wins over the prelude in the whole module (accepted), as in Rust, Racket, Python, and Go. In one file a name has one meaning: a call of read-string above (defn- read-string …) calls the module's function. Adding a name to the prelude therefore never changes existing code. To use the prelude's item of the same name, write its full path, std.core.read-string. An own definition that collides with an explicit import is an error, as in Rust.

  • A module is checked whole before it runs (accepted, 2026-11-16): both passes and analysis finish for the whole module, and every warning is reported, before its first top-level form is evaluated; then the forms run in order. A failure while loading therefore never hides the warnings of the forms after it, and the interpreter, the compiler and the evaluator report the same warnings (D003). The REPL, where forms arrive one at a time, checks and warns per form.

  • Redefinition in a live program is different: redefining a function in the REPL makes every caller use the new version (D018, D026). In the REPL, definitions arrive one at a time; when a new definition gives a module its own item named like a prelude item that the module's earlier functions already call, the REPL warns and lists them, so they can be re-evaluated (proposed).

  • An unknown name is a warning at compile time and the same error at run time, at the same point in both tools. The build does not stop, consistent with warnings-only types (D007), and a compiled program fails exactly where the interpreter fails.

    warning: undefined name: totl
      --> app.dias:4:10
       = help: did you mean total?
  • Superseded (2026-11-16) by D034: def in a body is a local name. Earlier text: def inside a function body is an error, in both tools: it would silently define a global. Local names are bound with let; a global that a function must change is an atom (D027).

    error: def inside a function body
      --> app.dias:3:3
       = help: bind a local with let, or define the name at the top level

Rejected alternatives

  • Separate destructuring mini-languages per form (Clojure's let destructuring differs from core.match).
  • Sequence patterns in plain brackets ([a b]): brackets are interchangeable lists (D008).
  • Positional record patterns for several fields: break silently when fields are reordered (D010).

Open questions