Macros and Derive

Monad has a real macro system: defmacro, quote, and compile-time reflection. It is not a bolted-on preprocessor — #[derive] is implemented in Monad, in std/derive.mo, on top of these primitives. The compiler only supplies one reflection intrinsic, meta!.

Term macros work on both compilers, with one shape difference: the reference contract (and the bootstrap host) requires the body to be a quote, while the self-hosted compiler also accepts a bare term (defmacro double x := x + x). Both accept defmacro double x := quote { x + x }. See bootstrap-host for the divergence table.

Quoting

quote { ... } turns a term into data instead of evaluating it:

quote { 1 + 2 }

Defining a Macro

There are two forms of defmacro.

Term macros produce an expression. The portable spelling wraps the body in a quote — the compiler strips that quote and expands the result (this is what fmt! does):

defmacro double x := quote { x + x }
def y : I64 := double! 9

Bare bodies are a self-hosted extension. The self-hosted compiler also accepts defmacro double x := x + x; the bootstrap host requires the quote (otherwise it fails with "macro double did not return a Term value"). Write the quote form for code that must run on both.

Declaration macros produce a list of top-level declarations, using a decls { ... } template:

defmacro derive_lens T := decls {
    reflect_type_info! T derive_lens_meta
}

A macro is invoked with a ! suffix — double! 9, derive_lens! Point.

Both forms accept two optional attributes. #[at decl], #[at term] or #[at [decl, term]] declares where the macro may be used (absent means both); a use at a position it excludes is an error. #[returns expr] / #[returns decls] states what the body produces and is checked against the body at the definition site, so the two cannot drift apart. fmt! below is declared #[at term] #[returns expr].

Reflection as Data

The interesting half is meta!, a compiler intrinsic that hands a type's structure to an ordinary Monad function as an ordinary value. That function computes a List Decl, and the compiler splices the result back into the program. (reflect_type_info! is the name the shipped derives still use; it remains an accepted alias until a nightly carrying the rename is published — see bootstrap-host.)

The data model lives in init/meta.mo:

type FieldInfo {
    field_info (name : String) (typ : Expr) (attrs : List String)
}

type CtorInfo {
    ctor_info (name : String) (fields : List FieldInfo)
}

type TypeInfo {
    type_info (name : String) (ctors : List CtorInfo)
}

and a deliberately minimal mirror of the compiler's own term and declaration surface:

type Expr {
    e_var (name : String),
    e_str (value : String),
    e_int (value : I64),
    e_bool (value : Bool),
    e_app (func : Expr) (arg : Expr),
    e_lam (param_name : String) (param_typ : Expr) (body : Expr),
    e_if (cond : Expr) (then_ : Expr) (else_ : Expr),
    e_match (scrutinee : Expr) (arms : List MatchArm),
    e_ctor (ctor_name : String) (args : List Expr)
}

type Decl {
    d_def (name : String) (params : List Param) (ret_typ : Expr) (body : Expr),
    d_instance (class_name : String) (target_typ : Expr) (methods : List Decl),
    d_error (message : String)
}

The payoff is that a "macro" is a normal function you can read, test, and debug. A derive backend is written with List.map, match, and recursion — not with quasi-quotation gymnastics:

pub def derive_lens_meta (info : TypeInfo) : List Decl :=
    match info {
        type_info type_name ctors =>
            match ctors {
                cons c tail =>
                    match tail {
                        empty => lens_decls_for_ctor type_name c,
                        cons _ _ => List.empty
                    },
                empty => List.empty
            }
    }

d_error is the escape hatch: returning one anywhere in the list fails macro expansion with that message, which is how a derive rejects a type it cannot handle.

#[derive ...]

Works on both compilers. The self-hosted compiler bridges the attribute to the same std/derive.mo macros the host calls (derive_bridge_decls, lang/src/typecheck/macro_queue.mo), so #[derive BEq BOrd Debug Lens] generates its instances either way. What you must do on both is import the backend — #[derive BEq] resolves through the derive-target registry to a macro by name, and a macro that is not in scope is "macro derive_beq not found".

The attribute form dispatches to those macros by name. Arguments are space-separated bare names — not #[derive(BEq, BOrd)]:

use std::derive {derive_beq, derive_bord, derive_debug, derive_lens}
use init::optics {Lens, set, view}
use std::debug {Debug}

#[derive BEq BOrd Debug Lens]
struct Point {
    x : I64,
    y : I64
}

// `Copy` is not derived: sharing is opt-in, and a field-wise instance is
// how a struct of Copy fields requests it. The match binds `p` once; the
// two fresh `Point`s duplicate the (Copy) fields.
instance Copy Point {
    def copy (p : Point) : Pair Point Point :=
        match p {
            { x, y } =>
                let a : Point := { x := x, y := y } in
                let b : Point := { x := x, y := y } in
                Pair.pair a b,
        }
}

#[test]
def test_equality : Bool :=
    let p1 : Point := { x := 1, y := 2 } in
    let p2 : Point := { x := 1, y := 2 } in
    let p3 : Point := { x := 1, y := 3 } in
    p1 == p2 && Bool.not (p1 == p3)

#[test]
def test_debug : Bool :=
    let p : Point := { x := 1, y := 2 } in
    Debug.debug p == "Point { x: 1, y: 2 }"

#[test]
def test_lens : Bool :=
    let p : Point := { x := 1, y := 2 } in
    view Point.x p == 1 && view Point.y (set Point.y 9 p) == 9

What can be derived

Target Generates Works on
BEq structural equality any type
BOrd ordering, following declaration order any type
Debug Rust-style debug representation any type
Lens one Lens per field single-constructor types only

Derives work on multi-constructor types too:

use std::derive {derive_beq, derive_bord, derive_debug}
use std::debug {Debug}

#[derive BEq BOrd Debug]
type Suit {
    hearts,
    spades,
    number (rank : I64)
}

#[test]
def test_suit : Bool :=
    Suit.number 7 == Suit.number 7
        && Suit.hearts < Suit.spades
        && Debug.debug (Suit.number 7) == "Suit::number { rank: 7 }"

Lens is deliberately absent there — a lens focuses on one field of one shape. For sum types, init.optics provides Prism instead.

You must import the backend

#[derive BEq] resolves to derive_beq through the registry, then calls it by name, so the module defining it has to be in scope:

use std::derive {derive_beq, derive_bord, derive_debug, derive_lens}

The compiler's unused-import analysis does not see macro-name dispatch as a reference, so it will report these as unused. Keep them — removing the import makes #[derive BEq] fail with "macro derive_beq not found".

Writing Your Own Derive

Because a derive is just a TypeInfo -> List Decl function plus a two-line defmacro, adding one is ordinary programming. Annotate the defmacro with #[derive_handler <Target> ...] and #[derive <Target>] dispatches to it — no compiler change, and it works from any mote the compiling file imports:

#[derive_handler Focus]
defmacro derive_focus T := decls {
    reflect_type_info! T derive_focus_meta
}

motes/clap/src/args.mo does exactly this for #[derive Cli], generating an argv parser from a type's constructors and fields, with #[arg]/#[opt]/ #[pos] and their named arguments (e.g. #[arg {short := "v"}]) coming through in FieldInfo.attrs as canonical strings. The richer surface is documented in the reference; cli/src/main.mo still hand-writes its parser and is deliberately not a derive consumer.

Registration rules:

Format strings (fmt!)

init::format provides a compile-time format macro with the ergonomics of Rust's format! and none of the run-time cost:

use init::format {fmt}

def greet (name : String) (n : I64) : String :=
    fmt! "hi {name}, you are {n:>4}"

A hole names a variable that is already in scope: fmt! takes exactly one argument — the template — and introduces no binders of its own. {name} interpolates it, {name:>N} right-aligns to a minimum width, {name:^N} centres, and {{/}} are literal braces. A hole with no name ({} or {:>N}), an unknown specifier, an unclosed hole, or an out-of-scope variable is a compile-time error at the call site. Widths count UTF-8 bytes, not display columns.

The template never reaches the generated code: it is parsed and lowered at expansion time into one String.concat_list with direct FmtDisplay.fmt_display calls, so there is no run-time template walking.

Compiler support. fmt! rides the term-position meta! intrinsic and cross-module term-macro lookup. The bootstrap host and a self-hosted compiler built from this change both expand it; an installed nightly older than the parity change may not, which is why this sample stays tagged monad,ignore until such a nightly is published.

Limitations

cli/src/main.mo hand-writes its own argv parser rather than using #[derive Cli], and stays free of macro syntax on purpose: the self-hosted parse/scope/typecheck suite re-parses that file through the self-hosted pipeline, and it is the one file where an attribute would be load-bearing for the bootstrap itself. motes/clap/src/tests/cli_derive_tests.mo is the derived equivalent.

Summary

Next, we'll look at linear types.