Skip to content

The meta phase and deriving

Some facts about a QVR module are settled before any data arrives: whether a finite table of weights sums to one, whether a lexicon assigns a well-formed category to every word, or what a structural equality of a family must be. The meta phase states and computes such facts while the module is checked. Its code is ordinary QVR, checked by the same checker and evaluated by the reference machine, and nothing of it reaches run time. The phase separation follows multi-stage programming (Taha and Sheard, 2000): a meta computation may build declarations as data, which are then spliced into the module and checked like hand-written ones, so generated code never bypasses the type checker (Xie et al., 2022b).

Deriving is the meta phase's most common use. A deriving handler reads a description of a family, the code of the sum of products the family is, and returns the declarations of an instance, such as structural equality (Magalhães et al., 2010; Chapman et al., 2010).

Phases

A module has two phases:

Phase Holds Checked Evaluated
run time every declaration not marked meta, and the declarations the meta phase generates when the module is checked when an entry runs
meta meta declarations, meta imported modules, static assert, splices, deriving handlers when the module is checked when the module is checked

The meta phase sees its own declarations, the meta prelude, and every index sort and family of the module whose declaration mentions only such data, so meta code computes over the module's own finite families. A family that mentions a family another declaration generates, such as a deduction's item family, exists at run time only; the meta phase reads it through its description.

Run-time code never depends on meta code. A run-time declaration that calls a meta computation or names a meta family is refused with the code qiec-phase:

test.qvr:5:0: [qiec-phase] 'square' is a meta declaration (line 1) and exists only while the
module is checked; run-time code cannot depend on meta code

Meta declarations

meta before a computation, family, or index declaration places it in the meta phase:

meta define square(x : Int) : Int !{} =
    return x * x

meta family Verdict : Type
    constructor Accept : Verdict
    constructor Reject : String -> Verdict

static assert square(12) == 144

A meta computation is checked like any computation. Its evaluation is bounded by META_FUEL machine steps, so a meta computation that does not stop fails the check rather than hanging it.

Static assertions

static assert VALUE evaluates a Boolean while the module is checked. The value may call meta computations; each call is evaluated before the value that uses it. A false assertion fails the check at its own location, naming the condition and the values it was computed from:

test.qvr:5:0: [qiec-static-assert] static assertion failed: square(3) == 10 evaluated to false
(square returned 9, left side 9, right side 10)

A value is printed the way the module prints it: by its family's show instance when it has one. The show of a signature sort prints through the module's open notations, so an assertion over quoted terms reports them as they are written:

s.qvr:46:0: [qiec-static-assert] static assertion failed: same(twice(), once()) evaluated to
false (twice returned λx0. x0 x0, once returned λx0. x0, same returned false)

An assertion that is not a Bool is a type error at the assertion.

Splices and quoted declarations

$generator(arguments) calls a meta computation that returns quoted declarations and splices them into the module where the splice stands:

meta define constant(name : String, value : Int) : SynDecl !{} =
    return DeclComputation(name, SeqNil, SeqNil, TypeName("Int"), RowClosed(SeqNil), CompReturn(ValueInt(value)))

$constant("answer", 42)

define uses : Int !{} =
    let x <- answer()
    return x

The generator returns one SynDecl or a Seq[SynDecl]. Quoted syntax is ordinary meta-phase data in the closed families of the meta prelude, one family per syntactic category, so a quotation is typed by its category and a generated declaration is typed by the checker once it is spliced. A spliced declaration that does not check is reported at the splice, with the generator named:

test.qvr:4:0: [qiec-kind] computation body returns String, expected Int (in the declaration bad
generated by broken at line 1, col 0, spliced at line 4, col 0)

A code quotation writes these trees in QVR syntax: ([| x + 1 |] : SynValue) is ValueBinary("+", ValueVar("x"), ValueInt(1)), and $e splices a value of the family its position takes.

A meta computation may refuse with a message through the prelude's refusal instance (refuse[A](message)); the check then fails at the splice with that message.

A string literal explicitly written in a name position of reflected syntax (the callee of ValueCall or CompCall, the constructor of ValueConstruct, PatternConstructor, or IndexApply, the type of TypeName or TypeApply, the source constructor of a MorphClause) is resolved in the scope of the module whose meta declaration contains it, like an identifier written there (Flatt, 2016). A generator in geometry that quotes ValueCall("Line", args) and TypeName("Shape") builds geometry's Line and Shape wherever it is spliced, a qualified "base.Point" resolves through geometry's own import of base, and a name geometry does not bind is resolved at the splice site. A qualified name whose module lacks the member is refused where the literal is written (resolve_quoted_names). See Object languages for the root scope used by the typed lambda declaration splices with textual code quotations.

A string is a quoted name because of how it is used, so a name may also reach its position through a helper. A parameter of a meta computation is a name parameter when its value reaches a quoted-name position, either directly, through a let that renames it, or as the argument of another computation's name parameter. A literal written as the argument of a name parameter, or bound by a let whose variable reaches one, is resolved where it is written, like a literal at the position itself (NameParameters). With

meta define binary(constructor : String, image : String) : MorphClause !{} =
    return MorphClause(constructor, ValueCall(image, SeqNil))

the call binary("Semantic.Fwd", "Over") written in geometry resolves both strings in geometry, wherever binary is declared. A string that reaches no name position, such as the text of ValueString, is left as written. A parameter that a binder of the same name hides before it reaches the position is not a name parameter.

Every generated declaration records its provenance: the generator, its location, the splice site, and a content digest of kind meta-provenance (a BLAKE3 digest in the content-hash domain) of the meta inputs it depends on, namely the meta-phase library, the source of every module meta declaration the generator reached, the generator's arguments (or a family's description), and the declaration itself. Positions and comments enter none of these, so moving code leaves the digest unchanged and changing any meta input changes it. expand_meta returns the generated declarations with their MetaProvenance.

Deriving

deriving (...) derives instances of classes for a family. It ends the header of a family, ends the header of a deduction after its options (for the deduction's generated item family), or stands alone and names any family, including a generated one:

family Term : Type deriving (Eq, Show)
    constructor Leaf : Int -> Term
    constructor Node : Term * Term -> Term

deriving (Ord, Hash) for Term

define same(a : Int, b : Int) : Bool !{} =
    let x = (Node(Leaf(a), Leaf(2)) : Term)
    let y = (Node(Leaf(b), Leaf(2)) : Term)
    let equal <- Term.eq(x, y)
    return equal

The instance of a class at a family is the family's member named by the class in snake case: Term.eq, Term.show, CCG.Item.quote. Its static telescope is the family's parameters followed by one copy of the family's indices per operand of the family's type, so the two operands of a binary method may sit at different indices. A parametric family's instance first takes one function per type parameter, the method at that parameter: Box.eq[A](eq_A, x, y) with eq_A : A * A -> Bool. At any other field type the instance calls that type's own instance, and the builtin types Int, Real, Bool, String, and Unit have builtin instances, declared once in a module that needs them.

Class Instance Meaning
Eq F.eq(x, y) : Bool the same constructor with equal fields
Ord F.ord(x, y) : Int -1, 0, or 1: constructors in declaration order, then fields from left to right; also F.constructor_index(x)
Hash F.hash(x) : Int the constructor's position, then each field's hash folded in as h * 31 + field modulo 2147483647
Show F.show(x) : String the constructor's declared name, followed by its fields in parentheses, a tensor field as a literal
Fold F.fold[.., R](algebra0, ..., x) : R the catamorphism: one function per constructor, from its fields with each recursive field replaced by R
Map F.map[.., A, A_to](f, x) applies f to every field of the last type parameter's type
Traverse F.traverse(f, x) !{\| rho} maps with an effectful f, running it on the fields in order
Quote[T via q] F.quote(x) : T the fold the signature morphism q induces into T
Include[T via q] F.include(x) : T the same fold, named include, for an inclusion into another family
Arbitrary F.arbitrary(size, seed) : F * Int a value at most size constructors deep, drawn from a Lehmer generator, and the generator's next state

A constructor's declared name is the one its own module gives it, without a module path, so a derived show prints Cons(1, Nil) for a list of the standard library whichever module runs it. A derived show displays a value apart from any scope, unlike the printing of a syntax sort through its notations, which must read back in the root module and so writes constructors as the root does (Printing). Real has no builtin Hash or Show: no primitive hashes or renders a real number identically on every target. An indexed family has no derived Arbitrary, since which constructors build a value depends on its indices.

A field whose type has no instance of the class fails the derivation, naming the field and the missing instance:

test.qvr:1:33: [qiec-deriving] deriving Hash for Weighted refused: field arg1 of constructor W
has type Real, which has no hash instance (no primitive hashes a Real value)

Quote

Quote[T via q] reifies a family into another along a signature morphism q, a meta computation returning a Morph: for each constructor of the family, a term of T over the constructor's field names. The derived F.quote is the unique fold the morphism induces: a recursive field stands for its own reification and every other field for itself. A morphism without a clause for some constructor, or with a clause for a constructor of another family, is refused. Reading a chart item of a deduction back into a user term type is the typical use, as in the reifying grammar of std.grammar.ccg:

deduction Grammar : Word -> Word [start=S, depth=6] deriving (Quote[C.Category via english])

When one deduction extends another, its item family includes the core's. Deriving Include[Ext.Item via inclusion] on the core gives the inclusion as a fold, and the library's quote_naturality generator states that reification commutes with it:

$quote_naturality("Core.Item", "Ext.Item", "Category")

splices the property reification of Core.Item is natural along its inclusion into Ext.Item, forall (x : Core.Item), expecting Category.eq(Core.Item.quote(x), Ext.Item.quote(Core.Item.include(x))). qvr test checks it like any property; an inclusion that sends a core constructor elsewhere than its image fails it. qvr test runs a module's meta phase before it collects the tests, so every property a splice generates is run and reported with the hand-written ones, and a meta phase that fails is reported as the module's error.

Descriptions

A deriving handler receives the family's description, a value of the prelude family Desc:

Family Constructor Fields
Desc Desc name, parameters, indices, constructors
CtorDesc CtorDesc name, its own telescope, fields, result indices, declared name
FieldDesc FieldDesc name, type, role
FieldRole RoleRecursive, RoleParameter(name), RoleOther how the field relates to its family

Binders, types, and index terms are quoted as SynBinder, SynType, and SynIndex values. A family a declaration generates is described from its checked declaration, so a deduction's item family is described like a hand-written one (Escot and Cockx, 2022).

A signature's sorts are families of the meta phase too, so meta code quotes terms of a sort, a family may take a field of a sort, and its derived instances call the sort's generated ones, Sig.S.eq, Sig.S.ord, Sig.S.hash, and Sig.S.show (which prints through the module's open notations), instead of deriving second ones. Deriving a class whose instance a family already has, written by hand or generated, is refused (qiec-deriving).

A field may be a tensor, as in Real[Fin 3] or Int[Fin 2, World]: its type is described as TypeTensor(element, axes), each positional axis as TypeFin(n) and each named axis as its type: an index sort or a nullary family by name, a record type as TypeRecord over its row. The derived instances read a tensor's entries in one order: the type's axes in their canonical order, the first varying slowest, and each axis's elements in the order its type enumerates them, so World's constructors in declaration order and Fin n from 0. The entries of an Eq or Ord field are Int, Real, or Bool, compared with the primitive == and < (false before true); those of a Hash or Show field are Int or Bool.

  • Eq: the same shape and equal entries at every element of the axes.
  • Ord: lexicographic, with each tensor read as nested lists, first axis outermost: the first entry or list length that differs decides, so a tensor that is a prefix of a longer one comes first. Two values of an indexed family can hold tensors of different extents, as Row(2) and Row(3) do for constructor Row[m : Nat] : Int[Fin m] -> Row(m); tensors that are equal as nested lists, which happens only when both are empty along some axis, are ordered by their counts, so the order is zero exactly where Eq holds.
  • Hash: the shape, each axis's count folded in as h * 31 + count, then the sum of each entry's hash times its position in the order plus one, modulo 2147483647, so equal tensors hash alike and the hash depends on where each entry is.
  • Show: a tensor literal with one pair of brackets per axis and entries printed as the builtin show prints them, so Grid([[1, 2], [3, -4]]) for a field of type Int[Fin 2, World], and [] for an axis with no elements.

Deriving Hash or Show over a Real tensor is refused for the reason a Real field is, which the refusal names.

For a closed record, Eq compares every field and Ord considers the fields in their declared order. For a closed variant, Eq compares the alternative and its payload, and Ord uses the declaration order of alternatives before comparing payloads. Hash uses label order for both types, and Show writes record and variant literals. These instances recurse into nested records and variants. Deriving these methods for an open row is refused because its remaining fields or alternatives are unknown when the method is generated.

Writing a handler

A handler is a meta computation named by its class. It takes the description and the names of the available instances, then a SynType per static argument of the class and the value of each via computation, and returns Seq[SynDecl]:

meta define Size(d : Desc, instances : Seq[String]) : Seq[SynDecl] !{} = ...

family Tree : Type deriving (Size)

The prelude supplies the pieces the built-in handlers are written with: instance_name, field_locals, constructor_pattern (from the deriving library), apply_instance, which binds a method applied at a field type and refuses with the field and the missing instance named, family_type, renaming of quoted types, and sequence operations. The built-in handlers are ordinary QVR in the same library, so they read as examples of the protocol (Christiansen and Brady, 2016).

The meta prelude

Family Quotes
SynDecl a computation (DeclComputation), a family (DeclFamily), an index (DeclIndex), a pattern synonym (DeclPattern), or a property (DeclProperty), which joins the module's tests
SynComp return, pure and monadic let, calls, requests, if, and case with or without a motive
SynValue variables, literals, operators, builtin calls, tuples, projections, constructor values, lambdas, tensor selection (ValueIndex), reductions (ValueReduce), tabulations (ValueTabulate)
SynPattern constructor, name, wildcard, and literal patterns
SynType, SynTypeRow, SynLabeled, SynStatic, SynIndex, SynSort, SynBinder, SynRow types (tensors as TypeTensor, Fin n as TypeFin, records and variants as TypeRecord and TypeVariant over a row of LabeledType entries, closed or open), static arguments, index terms, sorts, binders, effect rows
Seq[A], Outcome[A] sequences, and a value or a refusal
Morph, MorphClause signature morphisms

These names are in scope in the meta phase of every module, so a module declaration may not reuse one there (qiec-meta-name).

The prelude and the deriving handlers are checked once per process. Inside a persisting_meta_library block, the checked library is also kept in an artifact store, under the namespace meta-library and a key that digests the library's sources and the engine the block names (the engine identity), so a later process with the same store reads it instead of checking it again, and an edited library or a different engine misses. A ModuleBuild with a store persists it in that store.

Meta imports

meta import M brings the module M into the meta phase only: its declarations serve meta code, static assertions, splices, and deriving handlers, and run-time code that names one of them is refused with qiec-phase. A module's own meta declarations and its meta imports are separated from its run-time code the same way, in the manner of a separation of phases by binding scopes (Flatt, 2016).

A module of the program is meta-only when the root reaches it, and only through meta imports; an import of a hole reaches its filler. The filler of a hole that no module imports is not reached at all and stays run-time code: the link that brings it into the program is run-time code, so the filler is checked against its hole's signature like any other.

Diagnostics

Code Meaning
qiec-static-assert a static assertion is false, or its evaluation failed
qiec-splice a splice's generator does not return declarations, or refused
qiec-deriving a handler refused, the class names no meta computation, or the family is unknown
qiec-phase run-time code names a meta declaration
qiec-meta-name a declaration reuses a meta-prelude name, or two generators produced different declarations of one name
qiec-meta a splice or deriving class names something other than a meta computation

The semantics of the phase and of descriptions are stated in The meta phase and deriving.

Cited sources

Walid Taha and Tim Sheard. MetaML and Multi-Stage Programming with Explicit Annotations. Theoretical Computer Science, 248(1–2):211–242, 2000. doi:10.1016/S0304-3975(00)00053-0.

Ningning Xie, Matthew Pickering, Andres Löh, Nicolas Wu, Jeremy Yallop, and Meng Wang. Staging with Class: A Specification for Typed Template Haskell. Proceedings of the ACM on Programming Languages, 6(POPL):1–30, 2022b. doi:10.1145/3498723.

José Pedro Magalhães, Atze Dijkstra, Johan Jeuring, and Andres Löh. A Generic Deriving Mechanism for Haskell. In Proceedings of the Third ACM Haskell Symposium on Haskell, 37–48. 2010. doi:10.1145/1863523.1863529.

James Chapman, Pierre-Évariste Dagand, Conor McBride, and Peter Morris. The Gentle Art of Levitation. In Proceedings of the 15th ACM SIGPLAN International Conference on Functional Programming, 3–14. 2010. doi:10.1145/1863543.1863547.

Matthew Flatt. Binding as Sets of Scopes. In Proceedings of the 43rd Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 705–717. 2016. doi:10.1145/2837614.2837620.

Lucas Escot and Jesper Cockx. Practical Generic Programming over a Universe of Native Datatypes. Proceedings of the ACM on Programming Languages, 6(ICFP):625–649, 2022. doi:10.1145/3547644.

David Christiansen and Edwin Brady. Elaborator Reflection: Extending Idris in Idris. In Proceedings of the 21st ACM SIGPLAN International Conference on Functional Programming, 284–297. 2016. doi:10.1145/2951913.2951932.