Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Dada and this model

Dada explores ownership through operations that give values, share ownership, and borrow access. Its goal is a Java-like object model with Rust-like control of storage and lifetimes: programmers describe objects and their relationships without requiring every object to occupy its own allocation.

The book is organized into language layers:

  1. Given begins with operational semantics for unique ownership, followed by a type system that tracks initialized, empty, and unknown places with views and proves progress and preservation.
  2. Shared adds operational semantics for shared ownership. Its type-system chapter is coming.
  3. CFlow reserves the next part for control flow.

Each language has its own syntax, execution rules, examples, and invariants. A correspondence theorem shows that the translation of a Given program has exactly its original execution behavior in Shared. The checked operational models cover construction and fresh-variable bindings. Given also contains an unpacking extension used by the typing chapter. Its operations and structural preservation are checked, as are static progress and preservation for the Given type system. Assignment, drop, primitives, function calls, and borrowing remain outside these models.

Later chapters will add features to this foundation one layer at a time. The design goals explain the choices the model is intended to support.

The prose and mathematics stand on their own. A Lean selector reveals the associated formal definition, theorem, or example. Lean checks proofs; recorded reviews compare their statements with the explanation. The contributor guide describes that process.

Design goals and principles

These goals describe Dada’s intended design. They are distinct from the repository’s methods for documenting and verifying it. Their realization remains work for the specification and implementations.

Java-like mental model, Rust-like execution

A programmer should be able to think in terms of objects and references without first reconstructing stack offsets, inline storage, or reference-count headers. An abstract object need not occupy a separate allocation. A concrete implementation may place several abstract objects within one memory region.

Ownership remains meaningful in the abstract account. References differ in whether they keep an object alive and in how they permit access. Abstracting storage does not erase destruction or invalid access.

Composability and semantic equivalence

Types should compose according to the operations they permit. If two type expressions permit the same operations with the same observable semantics, our goal is for them to describe the same type rather than expose incidental representation choices.

Consider the Rust-shaped alternatives &Option<str>, &Option<String>, Option<&String>, and Option<&str>. They illustrate different placements of borrowing and different string representations. For the shared optional-string interface we want to express, Dada’s goal is to use one type:

shared Option[String]

This is an illustration of the intended Dada equivalence, not a claim that these are interchangeable Rust types or that every expression above is a valid Rust type (Option<str> in particular is excluded by Option<T>’s sized type parameter). Rust’s distinctions carry additional representation and operational consequences. The Dada model needs to make precise which observations and operations determine the proposed equivalence.

Execution independently of static checking

The machine’s operations should have meanings we can explain without consulting the type checker. Checking predicts and restricts executions, and may reject some dynamically safe executions. This is a gradual-typing-compatible goal: we want a foundation on which dynamic enforcement and static guarantees can coexist, without claiming that the current model already implements gradual typing.

Rust did not adopt this as its language design approach: Dada aims to give a useful execution account for programs before static permission checking. We must still define faults and access rules; independence does not mean every unchecked program is valid.

Tracing-friendly execution

We want efficient backends for the JVM, WASM-GC, WASM, and native x86. The semantics should accommodate tracing garbage collectors as well as implementations using explicit ownership and lifetime management. Abstract object identity should not force an allocation strategy that makes one of these backends unnecessarily costly.

Uninitialized slots are part of this design discussion. Native implementations should not be forced to perform unnecessary initialization solely to mimic a tracing backend’s representation. Conversely, a tracing backend must maintain its collector’s requirements. The model must distinguish abstract initialization state from the concrete contents a backend requires for safe tracing.

Proofs over unsafe code

Where the type system cannot establish a necessary property, our goal is to cover the gap with SMT-proven predicates. Low-level operations should have explicit obligations that library code can discharge, rather than leave those obligations as informal promises merely because an operation is unsafe.

This is a language goal, distinct from our choice to explore the semantic model and its metatheory in Lean. The interface for those predicates and their connection to the type system remain to be designed.

Lexical capability safety

We want information and value flow to be readily amenable to static analysis, with authority carried through explicit values and lexical scope. In the spirit of WASM’s explicit capability boundaries, code should not acquire authority from implicit ambient channels.

This goal excludes global variables, thread-local storage, and other dynamically scoped mechanisms for implicitly acquiring values or capabilities. Capabilities needed by an operation should arrive through its explicit inputs or lexically captured values. The semantics must eventually explain those boundaries and how backends preserve them.

Given

Given: operational semantics

This language studies transfer of ownership. Variables and object fields hold references to objects. Giving a reference moves it to its destination and leaves its source empty; constructing an object moves references into its fields.

A class declaration \(d\) names a class and its fields. Write \(C\) for a class name in \(\mathsf{ClassName}\), and \(f\) for a field name in \(\mathsf{FieldName}\). The field count \(n\) is a natural number, including zero:

\[ d ::= \mathsf{class}\ C\ \{f_1,\ldots,f_n\}. \]

Fields are distinct and listed in constructor-argument order. They have names but no declared types. An empty class still has objects, so this language needs no primitive values. Subscripts and primes distinguish names in the same category.

Unique/Syntax:ClassName
abbrev ClassName := String
Unique/Syntax:FieldName
abbrev FieldName := String
Unique/Syntax:Class
structure Class where
  fields : List FieldName
  deriving DecidableEq, Repr

Places, expressions, and statements

A place expression \(p\) follows a route from a variable through zero or more fields. Write \(x\) for a variable name in \(\mathsf{VariableId}\). A value expression \(e\) produces an owning reference. Giving a place, p→, is the only way to obtain a value from an existing place. A constructor creates an object from the values of its argument expressions:

\[ \begin{aligned} p &::= x \mid p.f \\ e &::= p\mathord{\to} \mid \mathsf{new}\ C(e_1,\ldots,e_n). \end{aligned} \]

Constructor arguments can themselves be constructors or gives of places.

A statement \(t\) determines what the machine executes next. In this language, the only statement evaluates an expression and binds its result to a fresh variable:

\[ t ::= \mathsf{let}\ x=e. \]

Expressions evaluate within a statement; they do not choose the next statement. Each let introduces a distinct runtime variable. This fragment has no shadowing, scopes, function calls, assignment, or destruction.

Unique/Syntax:VariableId
abbrev VariableId := String
Unique/Syntax:Place
inductive Place where
  | variable (name : VariableId)
  | field (base : Place) (name : FieldName)
  deriving DecidableEq, Repr
Unique/Syntax:Value
inductive Value where
  | give (source : Place)
  | new (className : ClassName) (arguments : List Value)
  deriving Repr
Unique/Syntax:Statement
structure Statement where
  letValue ::
  destination : VariableId
  value : Value
  deriving Repr

Programs

Write \(A\rightharpoonup B\) for finite partial maps from domain \(A\) to codomain \(B\), and \(\mathsf{List}(A)\) for finite ordered sequences of elements of \(A\).

Common/FiniteMap:FiniteMap
structure FiniteMap (Key Value : Type) where
  entries : List (Key × Value)
  uniqueKeys : (entries.map Prod.fst).Nodup

A program \(\Pi\) supplies class declarations and an ordered sequence of statements. Its class table \(\Delta\) maps each declared class name to its field names in declaration order. Each class name is declared once.

A statement sequence \(P\) is empty, written \([]\), or has a first statement \(t\) followed by a sequence \(P\), written \(t::P\):

\[ \begin{aligned} \Delta &\in \mathsf{ClassName}\rightharpoonup\mathsf{List}(\mathsf{FieldName}) \\ P &::= [] \mid t::P \\ \Pi &::= \langle\Delta,P\rangle. \end{aligned} \]

For a declaration \(\mathsf{class}\ C\ \{f_1,\ldots,f_n\}\), the table contains \(\Delta(C)=[f_1,\ldots,f_n]\).

Unique/Syntax:Classes
abbrev Classes := List (ClassName × Class)
Unique/Syntax:Program
structure Program where
  classes : Classes
  body : List Statement
  deriving Repr

A class table is well formed when class names are distinct and each declaration lists distinct field names.

Unique/Soundness:ClassesWellFormed
def ClassesWellFormed (classes : Classes) : Prop :=
  (classes.map Prod.fst).Nodup ∧
    ∀ name declaration, (name, declaration) ∈ classes → declaration.fields.Nodup

Objects and slots

An object identity \(\alpha\) is a tagged natural number. The tag keeps identities distinct from ordinary numbers. We also use \(\beta\) for an object identity; \(\operatorname{index}\) extracts its number:

\[ \alpha,\beta\in\mathsf{ObjectId} =\{\mathsf{obj}(n)\mid n\in\mathbb N\}, \qquad \operatorname{index}(\mathsf{obj}(n))=n. \]
Unique/Syntax:ObjectId
structure ObjectId where
  index : Nat
  deriving DecidableEq, Repr

A slot is a variable or object field. Its contents \(s\), in the category \(\mathsf{Slot}\), are empty, written \(\bot\), or hold an owning reference, represented by an object identity. An object \(o\), in the category \(\mathsf{Object}\), has a class name and an ordered list of named field slots. All references in this language are owners:

\[ \begin{aligned} s &::= \bot \mid \alpha \\ o &::= C\{f_1:s_1,\ldots,f_n:s_n\}. \end{aligned} \]
Unique/State:Slot
abbrev Slot := Option ObjectId
Unique/State:Object
structure Object where
  className : ClassName
  fields : List (FieldName × Slot)
  deriving DecidableEq, Repr

A storage state \(S\) has an object table \(O\), a variable table \(V\), and an allocation counter \(\nu\):

\[ \begin{aligned} O &\in \mathsf{ObjectId}\rightharpoonup\mathsf{Object} \\ V &\in \mathsf{VariableId}\rightharpoonup\mathsf{Slot} \\ \nu &\in \mathbb N \\ S &::= \langle O,V,\nu\rangle. \end{aligned} \]

The counter supplies \(\mathsf{obj}(\nu)\) for the next allocation, then increases by one. Finite-map notation assumes distinct keys. The tables and field lists record empty slots as well as occupied ones.

Unique/State:State
structure State where
  objects : List (ObjectId × Object)
  variables : List (VariableId × Slot)
  nextId : Nat
  deriving DecidableEq, Repr

The empty storage state has no objects or variables, and its allocation counter is zero:

\[S_{\emptyset}=\langle\varnothing,\varnothing,0\rangle.\]

Here \(\varnothing\) denotes the empty map.

Unique/State:State.empty
def State.empty : State := ⟨[], [], 0⟩

A storage place \(q\) selects one slot directly: either a variable or a field of a particular object:

\[ q ::= x \mid \alpha.f. \]

A place expression such as b.value describes a route to a slot; a storage place such as \(\mathsf{obj}(1).\mathsf{value}\) identifies the slot itself.

Unique/State:StoragePlace
inductive StoragePlace where
  | variable (name : VariableId)
  | field (object : ObjectId) (name : FieldName)
  deriving DecidableEq, Repr

For \(S=\langle O,V,\nu\rangle\), write \(S[q]=s\) for slot lookup at a storage place. It is a partial operation, defined by:

\[ \begin{aligned} S[x] &= V(x) &&\text{when }V(x)\text{ is defined}, \\ S[\alpha.f_i] &= s_i &&\text{when }O(\alpha)=C\{f_1:s_1,\ldots,f_n:s_n\},\ 1\leq i\leq n. \end{aligned} \]

Lookup has no result for an absent variable, object, or field. An existing empty slot has the defined result \(\bot\). An occupied slot contains an object identity, not that object’s data; the data is in \(O\).

Unique/State:Stored
def Stored (state : State) (place : StoragePlace) (slot : Slot) : Prop :=
  match place with
  | .variable name => (name, slot) ∈ state.variables
  | .field object name =>
      ∃ data, (object, data) ∈ state.objects ∧ (name, slot) ∈ data.fields

For a slot with defined lookup, \(S[q\leftarrow s]\) replaces its contents and leaves all other slots, object identities, class names, and the counter unchanged. This update preserves the slot even when its new contents are \(\bot\).

Unique/State:Updated
inductive Updated : State → StoragePlace → Slot → State → Prop where
  | variable (objects : List (ObjectId × Object)) (nextId : Nat)
      (leading suffix : List (VariableId × Slot)) (name : VariableId) (old new : Slot) :
      Updated ⟨objects, leading ++ (name, old) :: suffix, nextId⟩ (.variable name) new
        ⟨objects, leading ++ (name, new) :: suffix, nextId⟩
  | field (variables : List (VariableId × Slot)) (nextId : Nat)
      (before after : List (ObjectId × Object)) (parent : ObjectId) (className : ClassName)
      (leading suffix : List (FieldName × Slot)) (name : FieldName) (old new : Slot) :
      Updated ⟨before ++ (parent, ⟨className, leading ++ (name, old) :: suffix⟩) :: after,
          variables, nextId⟩ (.field parent name) new
        ⟨before ++ (parent, ⟨className, leading ++ (name, new) :: suffix⟩) :: after,
          variables, nextId⟩

The machine

A frame \(f=(V,P)\) owns its local variable store \(V\) and remaining statements \(P\). The program has one initial frame; after its exit there is no frame. Heap objects \(O\) and the allocation counter \(\nu\) live outside it:

\[ K=\langle O,\nu,F\rangle,\qquad F::=\mathsf{none}\mid\mathsf{some}(V,P). \]

For expression evaluation, combine the live frame’s locals with the heap and counter as the storage \(S=\langle O,V,\nu\rangle\). Write \(\operatorname{run}(S,P)=\langle O,\nu,\mathsf{some}(V,P)\rangle\). The pair \(\langle S,P\rangle\) used by local statement rules is an observation of that live frame, not a terminal program state.

Initially \(K=\operatorname{run}(S_{\emptyset},P)\), including when \(P=[]\). Exhausting the statements leaves a live frame whose bindings can still be inspected. A separate exit step pops it. There are no nested scopes or calls in this layer; Functions will extend this single-frame lifetime to a stack.

Unique/Frames:Frame
structure Frame (Instruction : Type) where
  variables : List (VariableId × Slot)
  code : List Instruction
  deriving Repr
Unique/Frames:Configuration
structure Configuration (Instruction : Type) where
  objects : List (ObjectId × Object)
  nextId : Nat
  frame : Option (Frame Instruction)
  deriving Repr
Unique/Frames:Configuration.running
def Configuration.running (state : State) (code : List Instruction) : Configuration Instruction :=
  ⟨state.objects, state.nextId, some ⟨state.variables, code⟩⟩
Unique/Frames:Configuration.initial
def Configuration.initial (code : List Instruction) : Configuration Instruction :=
  .running State.empty code
Unique/Frames:Configuration.state
def Configuration.state (configuration : Configuration Instruction) : State :=
  ⟨configuration.objects, configuration.frame.map Frame.variables |>.getD [], configuration.nextId⟩

Reachability starts at an initialized slot of the live frame and follows initialized object fields. Write \(\mathsf{Live}_S(\alpha)\) when this reaches object \(\alpha\). An absent frame has no roots.

Eager collection retains exactly reachable object entries. For object data \(D\) (its class tag and field slots), define:

\[ \operatorname{gc}(K)=\langle [(\alpha,D)\in O\mid\mathsf{Live}_{S_K}(\alpha)],\nu,F\rangle. \]

Here \(S_K\) uses the frame’s locals, or an empty variable store if the frame is absent. Collection preserves surviving objects and their identifiers, the allocation counter, and the frame. It invokes no user code. With no frame, it removes the entire heap.

The Lean definition is a mathematical reachability filter, not an executable traversal. Collection runs after whole statements and frame exit, never between constructor operands or while an expression result awaits binding.

Unique/State:Live
inductive Live (state : State) : ObjectId → Prop where
  | variable {name object} : (name, some object) ∈ state.variables → Live state object
  | field {parent object data name} :
      Live state parent → (parent, data) ∈ state.objects →
      (name, some object) ∈ data.fields → Live state object
Unique/Frames:State.collect
def State.collect (state : State) : State := by
  classical
  exact { state with objects := state.objects.filter (fun entry => decide (Live state entry.1)) }
Unique/Frames:Configuration.collect
def Configuration.collect (configuration : Configuration Instruction) : Configuration Instruction :=
  { configuration with objects := configuration.state.collect.objects }

A configuration is finished exactly when its initial frame has been popped:

\[ \mathsf{Finished}(\langle O,\nu,F\rangle)\iff F=\mathsf{none}. \]

An empty statement sequence still has a live frame and can take its exit step. Completion discards the frame’s locals and collects its unreachable objects.

Unique/Frames:Configuration.finished
def Configuration.finished (configuration : Configuration Instruction) : Prop :=
  configuration.frame = none

Operational semantics

Resolving a place

Place resolution, written \(S\vdash p\Downarrow q:\alpha\), follows route \(p\) to a storage place \(q\) holding reference \(\alpha\). These two rules define it:

\[ \frac{\href{#claim-given.lookup}{S[x]}=\alpha}{S\vdash x\Downarrow x:\alpha} \quad\text{Variable} \]
\[ \frac{ S\vdash p\Downarrow q:\beta \qquad \href{#claim-given.lookup}{S[\beta.f]}=\alpha }{S\vdash p.f\Downarrow\beta.f:\alpha} \quad\text{Field} \]

Each slot along the route must hold a reference. Undefined lookup and the empty contents \(\bot\) satisfy neither rule’s lookup premise. Resolution itself changes nothing.

Unique/Step:Resolve
inductive Resolve (state : State) : Place → StoragePlace → ObjectId → Prop where
  | variable {name object} :
      (name, some object) ∈ state.variables →
      Resolve state (.variable name) (.variable name) object
  | field {base source parent data name object} :
      Resolve state base source parent →
      (parent, data) ∈ state.objects →
      (name, some object) ∈ data.fields →
      Resolve state (.field base name) (.field parent name) object

Evaluating an expression

Expression evaluation, written

\[ \Delta\vdash\langle S,e\rangle\Downarrow\langle S',\alpha\rangle, \]

produces an owning reference \(\alpha\) and updated storage \(S'\). The following rules define successful evaluation, including nested expressions.

Give. Resolve the place and empty its slot. Return the reference taken:

\[ \frac{\href{#claim-given.resolution}{S\vdash p\Downarrow q:\alpha}}{ \Delta\vdash\langle S,p\mathord{\to}\rangle \Downarrow\langle \href{#claim-given.update}{S[q\leftarrow\bot]},\alpha\rangle } \quad\text{Give} \]

Construct. Evaluate the arguments from left to right, then allocate the object and put their results into its fields in declaration order.

\[ \frac{ \begin{gathered} \href{#claim-given.programs}{\Delta(C)}=[f_1,\ldots,f_n] \\ \Delta\vdash\langle S_{i-1},e_i\rangle \Downarrow\langle S_i,\alpha_i\rangle \quad\text{for each }i=1,\ldots,n \\ \beta\notin\operatorname{dom}(O_n) \end{gathered} }{ \Delta\vdash\langle S_0,\mathsf{new}\ C(e_1,\ldots,e_n)\rangle \Downarrow\langle S',\beta\rangle } \quad\text{Construct} \]

where \(S_0\) is the starting storage and \(S_i\) is the storage after the first \(i\) arguments, with

\[ \begin{aligned} S_n &= \langle O_n,V_n,\nu_n\rangle, \\ \beta &= \href{#claim-given.identities}{\mathsf{obj}(\nu_n)}, \\ O' &= O_n[\beta\mapsto C\{f_1:\alpha_1,\ldots,f_n:\alpha_n\}], \\ S' &= \langle O',V_n,\nu_n+1\rangle. \end{aligned} \]

Here \(\operatorname{dom}(O_n)\) is the set of allocated identities, and \(O_n[\beta\mapsto o]\) adds the fresh object’s entry.

With no arguments, there are no argument premises and allocation uses \(S_n=S_0\). Argument results remain owned by the ongoing evaluation until placed in the new object’s fields; they are not copied.

An empty slot, a missing field, or an unknown class has no successful evaluation. Giving the same slot twice as constructor arguments fails on the second give. An expression runs within one statement transition, but it can still fail.

Unique/Step:Eval
inductive Eval (classes : Classes) : State → Value → State → ObjectId → Prop where
  | give {state cleared : State} {path : Place} {source : StoragePlace} {object : ObjectId} :
      Resolve state path source object →
      Take state source object cleared →
      Eval classes state (.give path) cleared object
  | new {state evaluated : State} {className : ClassName} {declaration : Class}
      {arguments : List Value} {objects : List ObjectId} :
      (className, declaration) ∈ classes →
      EvalArgs classes state arguments evaluated objects →
      objects.length = declaration.fields.length →
      ObjectId.mk evaluated.nextId ∉ evaluated.objects.map Prod.fst →
      Eval classes state (.new className arguments)
        (evaluated.allocate className declaration.fields objects) ⟨evaluated.nextId⟩
Unique/Step:EvalArgs
inductive EvalArgs (classes : Classes) : State → List Value → State → List ObjectId → Prop where
  | nil (state : State) : EvalArgs classes state [] state []
  | cons {before middle after : State} {argument : Value} {arguments : List Value}
      {object : ObjectId} {objects : List ObjectId} :
      Eval classes before argument middle object →
      EvalArgs classes middle arguments after objects →
      EvalArgs classes before (argument :: arguments) after (object :: objects)
Unique/Step:State.allocate
def State.allocate (state : State) (className : ClassName) (fields : List FieldName)
    (arguments : List ObjectId) : State :=
  ⟨(⟨state.nextId⟩, ⟨className, fields.zip (arguments.map some)⟩) :: state.objects,
    state.variables, state.nextId + 1⟩

Executing a statement

To execute let x = e, evaluate the expression completely, then put its result in the new variable x. For the resulting storage \(S'=\langle O',V',\nu'\rangle\), write \(V'[x\mapsto\alpha]\) for the variable table extended with that binding, and abbreviate the updated state as:

\[ S'[x\mapsto\alpha]=\langle O',V'[x\mapsto\alpha],\nu'\rangle. \]

The domain \(\operatorname{dom}(V')\) is the set of variable names already present.

The local binding rule is:

\[ \frac{ \begin{gathered} \Delta\vdash\langle S,e\rangle\Downarrow\langle S',\alpha\rangle \\ S'=\langle O',V',\nu'\rangle \qquad x\notin\operatorname{dom}(V') \end{gathered} }{ \Delta\vdash\langle S,(\mathsf{let}\ x=e)::P\rangle \rightsquigarrow\langle S'[x\mapsto\alpha],P\rangle } \quad\text{Let} \]

The remaining statements keep their order. If evaluation fails or the variable already exists, the statement has no transition. There is no recovery transition or separately observable state partway through a failed expression.

The local rule above is auxiliary. Write \(\rightsquigarrow\) for that local operation. The program machine collects after it and has a separate exit rule:

\[ \frac{\Delta\vdash\langle S,P\rangle\rightsquigarrow\langle S',P'\rangle} {\Delta\vdash\operatorname{run}(S,P)\longrightarrow \operatorname{gc}(\operatorname{run}(S',P'))} \qquad \Delta\vdash\operatorname{run}(\langle O,V,\nu\rangle,[]) \longrightarrow\operatorname{gc}(\langle O,\nu,\mathsf{none}\rangle). \]

The exit target has no frame and an empty heap, retaining counter \(\nu\). Even an empty program takes one exit step. A finished configuration has no successor. The Lean Step in Unique/Step is the auxiliary local relation; Framed.Step is this program machine. baseOperation selects the single-variable binding relation; later patternOperation selects the unpacking relation.

Unique/Step:State.bind
def State.bind (state : State) (name : VariableId) (object : ObjectId) : State :=
  { state with variables := (name, some object) :: state.variables }
Unique/Step:Step
inductive Step (classes : Classes) : Configuration → Configuration → Prop where
  | letValue {state evaluated : State} {destination : VariableId} {value : Value}
      {object : ObjectId} {rest : List Statement} :
      destination ∉ evaluated.variables.map Prod.fst →
      Eval classes state value evaluated object →
      Step classes ⟨state, ⟨destination, value⟩ :: rest⟩
        ⟨evaluated.bind destination object, rest⟩
Unique/Frames:Step
inductive Step (operation : LocalStep Instruction) : Configuration Instruction → Configuration Instruction → Prop where
  | «local» {before after code rest} :
      operation before code after rest →
      Step operation (.running before code) (Configuration.running after rest).collect
  | exit {state} :
      Step operation (.running state []) (Configuration.mk state.objects state.nextId none).collect
Unique/Frames:baseOperation
def baseOperation (classes : Classes) : LocalStep Statement :=
  fun before code after rest => Dada.Unique.Step classes ⟨before, code⟩ ⟨after, rest⟩
Unique/Frames:patternOperation
def patternOperation (classes : Classes) : LocalStep Unpacking.Statement :=
  fun before code after rest => Unpacking.Step classes ⟨before, code⟩ ⟨after, rest⟩

Finite executions and failure

A finite execution, written \(\Delta\vdash K\longrightarrow^{*}K'\), consists of zero or more statement steps. These rules define it:

\[ \frac{}{\Delta\vdash K\longrightarrow^{*}K} \qquad \frac{ \href{#claim-given.steps}{\Delta\vdash K\longrightarrow K'} \qquad \Delta\vdash K'\longrightarrow^{*}K'' }{\Delta\vdash K\longrightarrow^{*}K''}. \]
Unique/Frames:Steps
def Steps (operation : LocalStep Instruction) (before after : Configuration Instruction) : Prop :=
  ∃ count, StepsExactly operation before count after
Unique/Frames:StepsExactly
inductive StepsExactly (operation : LocalStep Instruction) : Configuration Instruction → Nat → Configuration Instruction → Prop where
  | refl (configuration) : StepsExactly operation configuration 0 configuration
  | step {before middle after count} :
      Step operation before middle → StepsExactly operation middle count after →
      StepsExactly operation before (count + 1) after

A configuration is stuck when its frame remains but no next step is possible:

\[ \mathsf{Stuck}_{\Delta}(K)\iff \neg\href{#claim-given.finished}{\mathsf{Finished}(K)}\;\land\; \neg\exists K'.\;\href{#claim-given.steps}{\Delta\vdash K\longrightarrow K'}. \]

This is how execution goes wrong. For example, trying to give through an absent variable or an empty field yields no expression evaluation and therefore no statement step. Undefined lookup alone is a property of storage; attempting an operation that requires that lookup is what leaves the machine stuck.

Unique/Frames:Stuck
def Stuck (operation : LocalStep Instruction) (configuration : Configuration Instruction) : Prop :=
  ¬ configuration.finished ∧ ¬ ∃ after, Step operation configuration after

Worked executions

An empty class provides a value we can move:

class Token {}
let t = new Token();

Starting with empty storage, one step creates a Token object and puts its reference in t. No statements remain, but the initial frame is still live. The second step pops it and collects the object, leaving an empty heap and counter one. The check also covers the single exit step of an empty program.

Unique/FrameChecks:lifetime
example :
    Step (baseOperation classes) (.initial []) (Configuration.terminal (Instruction := Statement) 0) ∧
    Step (baseOperation classes) (.initial code) (.running observed []) ∧
    ("t", some 0) ∈ observed.variables ∧
    ¬ (Configuration.running observed ([] : List Statement)).finished ∧
    StepsExactly (baseOperation classes) (.initial code) 2 (.terminal 1) ∧
    (Configuration.terminal (Instruction := Statement) 1).finished := by
  refine ⟨exit_step State.empty, local_step allocated observed_wellFormed, by decide,
    by simp [Configuration.running, Configuration.finished], ?_, rfl⟩
  exact .step (local_step allocated observed_wellFormed) (.step (exit_step observed) (.refl _))

A field can receive a reference and later give it away:

class Token {}
class Box { value }

let t = new Token();
let b = new Box(t→);
let u = b.value→;

Starting with empty storage, the machine takes three steps:

  1. Create the token and put its reference in t.
  2. Create a box and move t into its value field, leaving t empty.
  3. Follow b to the box and move the field’s reference into u.

At this pre-exit observation, the statements are exhausted. Variable b owns the box and u owns the token; t and the box’s value field are empty. Giving the field moves its contents; the containing box remains in place.

Unique/Examples:give_execution
example : Framed.StepsExactly (Framed.baseOperation exampleClasses)
    (.initial (tokenProgram ++ boxProgram ++ moveProgram)) 3 (.running movedState []) := by
  have classesWf : ClassesWellFormed exampleClasses := by simp [ClassesWellFormed, exampleClasses, or_imp, and_imp, forall_and]
  have tokenWf : WellFormed exampleClasses tokenState := (createToken []).preserves_wellFormed classesWf (WellFormed.empty _)
  have boxWf : WellFormed exampleClasses boxState := (createBox []).preserves_wellFormed classesWf tokenWf
  have movedWf : WellFormed exampleClasses movedState := (giveField []).preserves_wellFormed classesWf boxWf
  exact .step (Framed.local_step (createToken _) tokenWf)
    (.step (Framed.local_step (createBox _) boxWf)
      (.step (Framed.local_step (giveField []) movedWf) (.refl _)))

Constructor arguments can create their own objects:

class Token {}
class Box { value }
let b = new Box(new Token());

Starting with empty storage, this is one statement step. Evaluate new Token() first, then put its reference in the newly created box’s value field. Bind the box’s reference to b. The pre-exit observation contains both objects, with no temporary source variable needed in the program.

Unique/Examples:nested_constructor
example : Framed.Step (Framed.baseOperation exampleClasses)
    (.initial [⟨"b", .new "Box" [.new "Token" []]⟩]) (.running nestedState []) :=
  Framed.local_step nested_operation (nested_operation.preserves_wellFormed
    (by simp [ClassesWellFormed, exampleClasses, or_imp, and_imp, forall_and]) (WellFormed.empty _))

Starting with the pre-exit storage of refgiven.example.field, try:

let v = b.value→;

Let \(\Delta\) be that example’s class table, and let \(K_{\mathrm{bad}}\) put that storage in a live frame with this one remaining statement. It is stuck: b still holds the box’s reference, but its value field is empty. The give cannot evaluate, so the statement cannot execute. Giving once leaves no reference behind for a second give.

Execution from this configuration cannot finish:

\[ \neg\exists K'.\; \bigl(\Delta\vdash K_{\mathrm{bad}}\longrightarrow^{*}K'\bigr) \;\land\;\mathsf{Finished}(K'). \]

Zero steps leave the statement pending, and a nonempty execution would need a first step, which does not exist.

Unique/Examples:second_give_fails
example : Framed.Stuck (Framed.baseOperation exampleClasses)
    (.running badConfiguration.state badConfiguration.code) ∧
    ¬ ∃ after, Framed.Steps (Framed.baseOperation exampleClasses)
      (.running badConfiguration.state badConfiguration.code) after ∧ after.finished := by
  refine ⟨framed_second_give_stuck, ?_⟩
  rintro ⟨after, ⟨_, execution⟩, finished⟩
  cases execution with
  | refl => exact framed_second_give_stuck.1 finished
  | step first _ => exact framed_second_give_stuck.2 ⟨_, first⟩

Liveness and well-formedness

For \(S=\langle O,V,\nu\rangle\), an object is allocated when its identity occurs in the object table:

\[ \mathsf{Allocated}_S(\alpha)\iff\alpha\in\operatorname{dom}(O). \]
Unique/State:Allocated
def Allocated (state : State) (object : ObjectId) : Prop :=
  object ∈ state.objects.map Prod.fst

An object is live when an owning path reaches it from a variable. Write \(\mathsf{Live}_S(\alpha)\) for the judgment defined by these two rules:

\[ \frac{\href{#claim-given.lookup}{S[x]}=\alpha}{\mathsf{Live}_S(\alpha)} \qquad \frac{\mathsf{Live}_S(\beta)\qquad \href{#claim-given.lookup}{S[\beta.f]}=\alpha}{\mathsf{Live}_S(\alpha)}. \]

An empty slot contributes no edge to such a path. Allocation and liveness are properties of the object graph, independent of how the state was produced.

Unique/State:Live
inductive Live (state : State) : ObjectId → Prop where
  | variable {name object} : (name, some object) ∈ state.variables → Live state object
  | field {parent object data name} :
      Live state parent → (parent, data) ∈ state.objects →
      (name, some object) ∈ data.fields → Live state object

During expression evaluation, a result may have left its source slot without yet entering a constructor or local binding. Such a result is a pending root. Let \(R\) be the list of object identities held by these pending results.

An object is live with pending roots, written \(\mathsf{Live}_{S;R}(\alpha)\), when it can be reached from a variable or an identity in \(R\), following initialized fields. This extends ordinary liveness with one additional starting rule:

\[ \frac{\alpha\in R}{\mathsf{Live}_{S;R}(\alpha)}. \]

The variable and field rules are otherwise the same. Pending results count as roots even though they are not entries in the variable table.

Unique/State:LiveWith
inductive LiveWith (state : State) (pending : List ObjectId) : ObjectId → Prop where
  | pending {object} : object ∈ pending → LiveWith state pending object
  | variable {name object} : (name, some object) ∈ state.variables → LiveWith state pending object
  | field {parent object data name} :
      LiveWith state pending parent → (parent, data) ∈ state.objects →
      (name, some object) ∈ data.fields → LiveWith state pending object

The following conditions describe storage between statements, including before the first statement. Write \(\mathsf{WF}_{\Delta}(S)\) when the state meets all these conditions:

  • Object-table keys and variable names are each distinct.
  • Every object’s class is declared. Its field names occur exactly in declaration order, without duplicates, including fields whose slots are empty.
  • Every allocated identity \(\alpha\) satisfies \(\href{#claim-given.identities}{\operatorname{index}(\alpha)}<\nu\). This bounds the identities already used, so the next allocation is fresh.
  • Every allocated object is live: a path from a variable reaches it through initialized fields.
  • The references in all variable slots and all object fields, counted by occurrence, contain each allocated object identity exactly once and contain no other identity.

The last condition excludes both duplicate ownership and references to missing objects. Two slots containing the same identity count as two references even though their contents are equal. Rootedness is a separate condition: a cycle with no variable root does not become valid merely because each object has one incoming reference. Object identities do not impose an ordering on field edges.

Within an expression, write \(\mathsf{WF}_{\Delta}(S;R)\) for the version with pending roots. Rootedness uses \(\mathsf{Live}_{S;R}\), and reference counting includes every occurrence in \(R\) as well as the variable slots and object fields. The other conditions are unchanged. Thus moving an owner out of a field can leave that slot empty while the returned object remains rooted in the ongoing evaluation.

Unique/State:References
def References (state : State) : List ObjectId :=
  state.variables.filterMap (fun binding => binding.2) ++
    state.objects.flatMap (fun entry => entry.2.fields.filterMap (fun field => field.2))
Unique/Soundness:WellFormed
structure WellFormed (classes : Classes) (state : State) : Prop where
  objectKeys : (state.objects.map Prod.fst).Nodup
  variableKeys : (state.variables.map Prod.fst).Nodup
  shapes : ∀ id data, (id, data) ∈ state.objects →
    ∃ declaration, (data.className, declaration) ∈ classes ∧
      data.fields.map Prod.fst = declaration.fields ∧ declaration.fields.Nodup
  bounds : ∀ id data, (id, data) ∈ state.objects → id.index < state.nextId
  rooted : ∀ object, Allocated state object → Live state object
  referencesUnique : (References state).Nodup
  referencesComplete : ∀ id, id ∈ References state ↔ Allocated state id
Unique/Soundness:WellFormedWith
structure WellFormedWith (classes : Classes) (state : State) (pending : List ObjectId) : Prop where
  objectKeys : (state.objects.map Prod.fst).Nodup
  variableKeys : (state.variables.map Prod.fst).Nodup
  shapes : ∀ id data, (id, data) ∈ state.objects →
    ∃ declaration, (data.className, declaration) ∈ classes ∧
      data.fields.map Prod.fst = declaration.fields ∧ declaration.fields.Nodup
  bounds : ∀ id data, (id, data) ∈ state.objects → id.index < state.nextId
  rooted : ∀ object, Allocated state object → LiveWith state pending object
  referencesUnique : (pending ++ References state).Nodup
  referencesComplete : ∀ id, id ∈ pending ++ References state ↔ Allocated state id

The well-formedness invariant accepts this storage, with allocation counter 3:

variables: b → Box#1
objects:   Box#1.value → Token#2
           Token#2 has no fields

Each object has exactly one incoming reference and is reached from b. The field points from identity 1 to identity 2; the target’s index is larger. This is an example of admissible storage, not a claim that the constructor-only Given language produces it from an empty state.

Taking b.value empties that field and returns identity 2. The checked preservation result establishes well-formedness with identity 2 as a pending root; identity 1 remains rooted at b. No allocation-order comparison is needed to preserve this state.

Unique/RootedChecks:younger_child
example : WellFormed classes youngerChild ∧
    ¬ ((2 : ObjectId).index < (1 : ObjectId).index) ∧
    WellFormedWith classes takenChild [2] := by
  exact ⟨youngerChild_wellFormed, by decide, take_younger.preserves_pending youngerChild_wellFormed.with_empty⟩

A single allocated Box#1 with value pointing back to itself and no variables fails well-formedness, even with allocation counter 2. Its one field supplies exactly one incoming reference to the allocated object, but no path starts at a variable. It is not live.

This separates ownership counting from rootedness: the former does not imply the latter, even when all references are unique.

Unique/RootedChecks:unreachable_cycle
example : ¬ WellFormed classes unreachableCycle := by
  intro wf
  have noLive : ∀ id, ¬ Live unreachableCycle id := by
    intro id live
    induction live with
    | «variable» member => exact List.not_mem_nil member
    | field _ _ _ ih => exact ih
  exact noLive 1 (wf.rooted 1 (by simp [Allocated, unreachableCycle]))

In every well-formed state, an object is live exactly when it is allocated:

\[ \href{#claim-given.well_formed}{\mathsf{WF}_{\Delta}(S)} \quad\Longrightarrow\quad \bigl(\href{#claim-given.live}{\mathsf{Live}_S(\alpha)}\iff\href{#claim-given.allocated}{\mathsf{Allocated}_S(\alpha)}\bigr). \]

Thus every allocated object has an owning path from a variable, and following owning paths cannot reach a missing object.

Unique/Liveness:WellFormed.live_iff_allocated
theorem WellFormed.live_iff_allocated (wf : WellFormed classes state) :
    Live state object ↔ Allocated state object :=
  ⟨wf.live_allocated, wf.allocated_live⟩

In every well-formed state, each allocated object has exactly one owning reference across all variable slots and object fields. This counts the slot that immediately holds its reference: a path through several enclosing objects does not add extra owners of its final target.

Unique/Liveness:WellFormed.owner_count
theorem WellFormed.owner_count (wf : WellFormed classes state)
    (allocated : Allocated state object) : (References state).count object = 1 := by
  exact wf.referencesUnique.count_of_mem ((wf.referencesComplete object).mpr allocated)

Collection leaves structurally well-formed evaluation storage unchanged: every allocated object is already reachable. Ordinary statements preserve this property, so their following collection is inert. Popping the frame removes its roots; collection at that boundary empties the heap instead.

Unique/Frames:State.collect_eq_self
theorem State.collect_eq_self (wf : WellFormed classes state) : state.collect = state := by
  classical
  have keep : state.objects.filter (fun entry => decide (Live state entry.1)) = state.objects :=
    List.filter_eq_self.mpr (by
      intro entry member
      simpa using wf.allocated_live (List.mem_map.mpr ⟨entry, member, rfl⟩))
  simp [State.collect, keep]

For any program with a well-formed class table, every configuration reached by a finite execution from its empty initial state has a well-formed state. This includes zero steps, intermediate configurations, and completed executions.

Consequently, every allocated object remains live and has exactly one owning reference. The theorem covers successful execution; it does not promise that a program can always take another step.

Unique/Frames:base_soundness
theorem base_soundness (classesWf : ClassesWellFormed classes)
    (trace : StepsExactly (baseOperation classes) (.initial code) count after) :
    WellFormed classes after.state :=
  trace.preserves (fun _ _ _ _ wf operation => operation.preserves_wellFormed classesWf wf)
    (WellFormed.empty _)

Unpacking

An unpacking pattern consumes an object and transfers its field slots into new variables. This extends the statement syntax with a binding pattern \(b\):

\[ \begin{aligned} b &::= x \mid C\mathord{\to}\{f_1:x_1,\ldots,f_n:x_n\} \\ t &::= \mathsf{let}\ b=e. \end{aligned} \]

In a pattern, f: x names the field f and its new variable x; f alone is shorthand for f: f. The pattern must name every declared field exactly once, and its variable names must be distinct. Fields may be listed in any order. This first version has flat patterns, with no _ or .. entries.

The expression p→ transfers the reference out of p. The pattern C → { ... } then removes the enclosing object and transfers its components. An ordinary field give leaves the enclosing object in place. An empty class can be consumed with C → {}.

This extension adds patterns while keeping expression evaluation unchanged. The preceding results concern single-variable bindings.

Unique/Unpacking:Pattern
inductive Pattern where
  | variable (name : VariableId)
  | unpack (className : ClassName) (fields : List (FieldName × VariableId))
  deriving DecidableEq, Repr
Unique/Unpacking:Statement
structure Statement where
  pattern : Pattern
  value : Value
  deriving Repr
Unique/Unpacking:Configuration
structure Configuration where
  state : State
  code : List Statement
  deriving Repr

To execute let C → { ... } = e, evaluate e, check that its result names a C object, and transfer that object’s slots into fresh variables. An initialized field becomes an initialized variable; an empty field becomes an empty variable. The consumed object’s entry is removed from the object table.

Write \(\Delta\vdash K\rightsquigarrow_u K'\) for the extended transition relation. It has the earlier Let rule, read over the extended statement syntax, and the following Unpack rule. We display the pattern fields in declaration order:

\[ \frac{ \begin{gathered} \Delta\vdash\langle S,e\rangle\Downarrow\langle S',\alpha\rangle \\ \Delta(C)=[f_1,\ldots,f_n] \qquad S'=\langle O',V',\nu'\rangle \\ O'(\alpha)=C\{f_1:s_1,\ldots,f_n:s_n\} \\ x_1,\ldots,x_n\text{ are distinct} \qquad x_i\notin\operatorname{dom}(V')\quad(1\leq i\leq n) \end{gathered} }{ \Delta\vdash \langle S,(\mathsf{let}\ C\mathord{\to}\{f_1:x_1,\ldots,f_n:x_n\}=e)::P\rangle \rightsquigarrow_u\langle S'',P\rangle } \quad\text{Unpack} \]

where

\[ S''=\left\langle O'\setminus\{\alpha\},\; V'[x_1\mapsto s_1,\ldots,x_n\mapsto s_n],\; \nu' \right\rangle. \]

Here \(O'\setminus\{\alpha\}\) removes the object-table entry for \(\alpha\). The variable-map extension adds exactly the displayed slots, including those containing \(\bot\). All other objects and variables, and the allocation counter, retain their values from \(S'\).

The slots move together within one statement step. No object stored in a field is removed by unpacking its container. A class mismatch or an already allocated destination variable gives this rule no transition, even when that variable’s slot is empty.

These are local-frame operations. The program machine uses patternOperation in the same collection and exit rules as single-variable bindings.

Unique/Unpacking:Transfer
inductive Transfer : List (FieldName × VariableId) → List (FieldName × Slot) → List (VariableId × Slot) → Prop where
  | nil : Transfer [] [] []
  | cons {field name slot pattern before after bindings} :
      Transfer pattern (before ++ after) bindings →
      Transfer ((field, name) :: pattern) (before ++ (field, slot) :: after)
        ((name, slot) :: bindings)
Unique/Unpacking:Bind
inductive Bind (classes : Classes) : State → ObjectId → Pattern → State → Prop where
  | variable {state object name} :
      name ∉ state.variables.map Prod.fst →
      Bind classes state object (.variable name) (state.bind name object)
  | unpack {before after variables nextId object className fields pattern bindings declaration} :
      (className, declaration) ∈ classes →
      fields.map Prod.fst = declaration.fields →
      (pattern.map Prod.fst).Nodup →
      (pattern.map Prod.snd).Nodup →
      (∀ name ∈ pattern.map Prod.snd, name ∉ variables.map Prod.fst) →
      Transfer pattern fields bindings →
      Bind classes ⟨before ++ (object, ⟨className, fields⟩) :: after, variables, nextId⟩
        object (.unpack className pattern)
        ⟨before ++ after, bindings ++ variables, nextId⟩
Unique/Unpacking:Step
inductive Step (classes : Classes) : Configuration → Configuration → Prop where
  | letValue {before evaluated after pattern value object rest} :
      Eval classes before value evaluated object →
      Bind classes evaluated object pattern after →
      Step classes ⟨before, ⟨pattern, value⟩ :: rest⟩ ⟨after, rest⟩

For a well-formed class table, every extended step from well-formed storage preserves well-formedness. Unpacking transfers every field slot and removes only the consumed container, so its children retain their owners.

Unique/Frames:pattern_preservation
theorem pattern_preservation (classesWf : ClassesWellFormed classes)
    (wf : WellFormed classes before.state) (step : Step (patternOperation classes) before after) :
    WellFormed classes after.state :=
  step.preserves (fun _ _ _ _ wf operation => operation.preserves_wellFormed classesWf wf) wf

Unpacking also works after a field has been moved:

class Token {}
class Pair { left, right }

let p = new Pair(new Token(), new Token());
let taken = p.left→;
let Pair → { left, right } = p→;

After the three-step execution, taken owns the first token and right owns the second. Variables p and left have empty slots. The pair object has been removed; both token objects remain. The configuration is finished.

The empty field does not produce a value: its new binding left is empty too. Trying to evaluate left→ afterward would have no result.

Unique/UnpackingChecks:unpack_after_move
example : Steps exampleClasses ⟨State.empty, unpackingProgram⟩ ⟨unpacked, []⟩ ∧
    (Configuration.mk unpacked []).finished ∧
    ¬ ∃ after object, Eval exampleClasses unpacked (.give (.variable "left")) after object := by
  exact ⟨unpacking_execution, rfl, moved_field_has_no_value⟩

Given: typing and soundness

The type system checks that each give finds a value and that each binding can receive its result. A move changes the source’s type description as well as its contents.

This chapter uses the unpacking extension refgiven.unpacking; expression evaluation is unchanged.

A typed class table \(\Sigma\) gives each field a declared class:

\[ \begin{aligned} d &::= \mathsf{class}\ C\ \{f_1:C_1,\ldots,f_n:C_n\},\\ \Sigma &\in \mathsf{ClassName}\rightharpoonup \mathsf{List}(\mathsf{FieldName}\times\mathsf{ClassName}). \end{aligned} \]

Fields retain their constructor-argument order.

Field declarations constrain the class of an object stored there. They do not require its slot to remain initialized after a move. All value types in this chapter are nominal types; ownership is unique.

Unique/Views:TypedClass
structure TypedClass where
  fields : List (FieldName × ClassName)
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr
Unique/Views:ClassTable
abbrev ClassTable := List (ClassName × TypedClass)

A typed class table is well formed when each class name has one declaration, field names within each declaration are distinct, and every field’s declared class occurs in \(\Sigma\).

Unique/Views:ClassTable.WellFormed
def ClassTable.WellFormed (classes : ClassTable) : Prop :=
  (classes.map Prod.fst).Nodup ∧
    ∀ entry ∈ classes, (entry.2.fields.map Prod.fst).Nodup ∧
      ∀ field ∈ entry.2.fields, field.2 ∈ classes.map Prod.fst

Class-table erasure removes field types to recover the operational class table: if \(\href{#claim-given.typing.declarations}{\Sigma(C)}=[f_1:C_1,\ldots,f_n:C_n]\), then \(\lfloor\Sigma\rfloor(C)=[f_1,\ldots,f_n]\).

Unique/Views:ClassTable.erase
def ClassTable.erase (classes : ClassTable) : Classes :=
  classes.map fun (name, declaration) => (name, ⟨declaration.fields.map Prod.fst⟩)

Types describe accessible places

A relative place \(\rho\) is a finite sequence of field names. The empty sequence \(\epsilon\) denotes the value itself; concatenation is written \(\rho\cdot\sigma\); \(\rho f\) appends the single field \(f\).

\[\rho ::= \epsilon \mid f\cdot\rho.\]
Unique/Views:Path
abbrev Path := List FieldName

A relative path is valid from \(C\) when its fields can be followed through the declarations in \(\Sigma\). Write \(\operatorname{class}_{\Sigma}(C,\rho)\) for its final declared class; in particular, \(\operatorname{class}_{\Sigma}(C,\epsilon)=C\).

Unique/Views:classAt
def classAt (classes : ClassTable) (base : ClassName) : Path → Option ClassName
  | [] => some base
  | field :: rest => do
      let declaration ← classes.lookup base
      let target ← declaration.fields.lookup field
      classAt classes target rest

A view entry \(a\), in the category \(\mathsf{ViewEntry}\), is a positive relative place or a negative nonempty relative place. A view \(A\) is a finite set of entries. A type \(T\) always pairs a nominal class with a view:

\[ \begin{aligned} a &::= \rho \mid -\rho \qquad(\text{negative entries require }\rho\ne\epsilon),\\ A &\subseteq_{\mathrm{fin}}\mathsf{ViewEntry},\\ T &::= C.A. \end{aligned} \]

The surface notation uses braces: Point.{x, -y}. A positive entry exposes an initialized value of the path’s declared class, including its fully initialized fields. A negative entry exposes an existing empty slot. Every proper prefix of either kind of entry must hold an object. A branch not covered by an entry is unknown and cannot be accessed through this type.

We write bare \(C\) as shorthand for \(C.\{\epsilon\}\): the whole value, including all fields reachable from it, is initialized. It is not a separate form of type. By contrast, \(C.\{\}\) exposes the object itself but none of its fields. The empty path \(\epsilon\) and the empty set \(\{\}\) have different meanings.

Unique/Views:Entry
inductive Entry where
  | positive (path : Path)
  | negative (path : Path)
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr
Unique/Views:ViewType
structure ViewType where
  className : ClassName
  entries : List Entry
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr
Unique/Views:ViewType.whole
def ViewType.whole (name : ClassName) : ViewType :=
  ⟨name, [.positive []]⟩

The base class is \(\operatorname{base}(C.A)=C\).

Unique/Views:ViewType
structure ViewType where
  className : ClassName
  entries : List Entry
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr

A type is well formed when its base class is declared and its view satisfies the following condition.

Entries do not overlap. Their paths must be valid from \(C\), distinct, and pairwise prefix-incomparable: no entry’s path is a prefix of another’s. Thus C.{f, -f.g} is not a valid view. Exposing all of f would claim initialization that -f.g denies. To describe such a hole, first expand f into its fields.

Unique/Views:Entry.valid
def Entry.valid (classes : ClassTable) (base : ClassName) (entry : Entry) : Bool :=
  (classAt classes base entry.path).isSome &&
    match entry with
    | .positive _ => true
    | .negative path => !path.isEmpty
Unique/Views:entriesDisjoint
def entriesDisjoint : List Entry → Bool
  | [] => true
  | entry :: rest =>
    rest.all (fun other =>
      !entry.path.isPrefixOf other.path && !other.path.isPrefixOf entry.path) &&
    entriesDisjoint rest
Unique/Views:ViewType.WellFormed
def ViewType.WellFormed (ty : ViewType) (classes : ClassTable) : Prop :=
  (classes.lookup ty.className).isSome = true ∧
    ty.entries.all (Entry.valid classes ty.className) = true ∧
    entriesDisjoint ty.entries = true

A full view accounts for every field recursively, including fields known to be empty. A partial view leaves some statuses unknown. The formal fullness predicate comes after this example; only this distinction is needed to read the table.

Consider these declarations:

class Token {}
class Pair { left: Token, right: Token }
class Box { item: Pair }
TypeInformation available
PairBoth fields contain tokens.
Pair.{left}left contains a token; right is unknown.
Pair.{-left, right}left is empty and right contains a token: a full view.
Box.{-item.left}item contains a pair whose left is empty; its right is unknown.
Box.{-item.left, item.right}item contains a pair whose left is empty and right contains a token: a full view.

In the last two types, item itself remains initialized. Its negative child does not make the containing field empty.

Unique/ViewChecks:view_information
example :
    (Pos viewClasses ⟨"Pair", [.positive ["left"]]⟩ ["left"] ∧
    ¬ Pos viewClasses ⟨"Pair", [.positive ["left"]]⟩ ["right"] ∧
    ¬ Neg ⟨"Pair", [.positive ["left"]]⟩ ["right"] ∧
    Pos viewClasses ⟨"Box", [.negative ["item", "left"]]⟩ ["item"] ∧
    Neg ⟨"Box", [.negative ["item", "left"]]⟩ ["item", "left"] ∧
    ¬ Pos viewClasses ⟨"Box", [.negative ["item", "left"]]⟩ ["item", "right"]) ∧
    (Full viewClasses (.whole "Pair") ∧
    ¬ Full viewClasses ⟨"Pair", [.positive ["left"]]⟩ ∧
    Full viewClasses ⟨"Pair", [.negative ["left"], .positive ["right"]]⟩ ∧
    ¬ Full viewClasses ⟨"Box", [.negative ["item", "left"]]⟩ ∧
    Full viewClasses ⟨"Box", [.negative ["item", "left"], .positive ["item", "right"]]⟩) := by
  exact ⟨by decide, view_fullness⟩

Each type determines a set of known-initialized paths \(\operatorname{pos}_{\Sigma}(T)\) and known-empty paths \(\operatorname{neg}_{\Sigma}(T)\). These sets give precise meanings to the view notation.

For \(T=C.A\):

  • \(\epsilon\) is positive: the described value is an object.
  • Every proper prefix of an entry’s path is positive.
  • A positive entry’s path and all its valid descendants are positive.
  • Exactly the paths of negative entries are negative.

No other path is known. In particular, a negative path does not say that its descendants are empty: there is no object in that slot whose fields could be examined. The shorthand \(C=C.\{\epsilon\}\) makes every valid path positive.

Unique/Views:positive
def positive (classes : ClassTable) (ty : ViewType) (path : Path) : Bool :=
  (classAt classes ty.className path).isSome &&
    (path.isEmpty || ty.entries.any (fun entry =>
      (path.length < entry.path.length && path.isPrefixOf entry.path) ||
      match entry with
      | .positive initialPath => initialPath.isPrefixOf path
      | .negative _ => false))
Unique/Views:negative
def negative (ty : ViewType) (path : Path) : Bool :=
  ty.entries.contains (.negative path)
Unique/Views:Pos
def Pos (classes : ClassTable) (ty : ViewType) (path : Path) : Prop :=
  positive classes ty path = true
Unique/Views:Neg
def Neg (ty : ViewType) (path : Path) : Prop :=
  negative ty path = true

A view is full when every direct field of every known-initialized object has a known status:

\[ \mathsf{Full}_{\Sigma}(T)\iff \begin{gathered} \forall\rho\in\href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(T).\\ \forall(f:D)\in\Sigma(\href{#claim-given.typing.class_at}{\operatorname{class}}_{\Sigma}(\href{#claim-given.typing.base}{\operatorname{base}}(T),\rho)).\\ \rho f\in\href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(T)\cup\href{#claim-given.typing.observations}{\operatorname{neg}}_{\Sigma}(T). \end{gathered} \]

A full view may contain empty slots; being full does not mean being fully initialized.

Unique/Views:Full
def Full (classes : ClassTable) (ty : ViewType) : Prop :=
  ∀ path, Pos classes ty path →
    ∀ name declaration, classAt classes ty.className path = some name →
      classes.lookup name = some declaration →
      ∀ field ∈ declaration.fields,
        Pos classes ty (path ++ [field.1]) ∨ Neg ty (path ++ [field.1])

Normalizing a view

Several spellings can describe the same accessible fields:

class Foo { bar: Bar }
class Bar { baz: Baz }
class Baz {}

In Foo.{bar.baz}, bar must contain an object, and its only field, baz, is fully initialized. We can therefore write bar instead. The same reasoning then applies to the whole Foo:

\[ \mathsf{Foo}.\{\mathsf{bar.baz}\} \;\leadsto\;\mathsf{Foo}.\{\mathsf{bar}\} \;\leadsto\;\mathsf{Foo}.\{\epsilon\} \;=\;\mathsf{Foo}. \]

All these spellings are well formed. The normalization procedure defined next chooses the last one; this example illustrates only the collapses it performs. If Bar also declared another field, an unknown or empty sibling would prevent the first collapse. A deeper path remains when it describes only part of an intermediate object.

Unique/ViewChecks:normalize_nested_whole
example :
    normalize viewClasses ⟨"Foo", [.positive ["bar", "baz"]]⟩ = .whole "Foo" ∧
    normalize viewClasses ⟨"Foo", [.positive ["bar"]]⟩ = .whole "Foo" := by
  decide

Normalization \(\mathsf{N}_{\Sigma}(T)\) replaces a completely exposed subtree with its shortest positive entry. Work from the deepest entries toward the root. If the class at \(\rho\) declares exactly the nonempty list of fields \(f_1,\ldots,f_n\), replace all their positive entries together:

\[ A\cup\{\rho f_1,\ldots,\rho f_n\} \;\leadsto\; A\cup\{\rho\} \qquad(n>0). \]

Here none of the replaced entries occurs in \(A\). Repeat until no such replacement is possible. A negative or unknown child prevents a collapse. The procedure shortens the finite paths in the view; it does not unfold recursive class declarations.

Keep a positive entry for an empty-class object: it records that the object exists. Do not create an entry for an unknown field merely because its declared class is empty. The root is already known to exist, so for an empty class \(C\), normalize \(C.\{\}\) to \(C.\{\epsilon\}\).

Print \(C.\{\epsilon\}\) as \(C\). Expanded spellings remain valid input. The typing rules use normalized types throughout, including when comparing constructor arguments with their declared types.

Unique/Views:Entry.dropPrefix
def Entry.dropPrefix (initialPath : Path) (entry : Entry) : Option Entry :=
  if initialPath.isPrefixOf entry.path then
    some (match entry with
      | .positive path => .positive (path.drop initialPath.length)
      | .negative path => .negative (path.drop initialPath.length))
  else none
Unique/Views:Entry.prepend
def Entry.prepend (initialPath : Path) : Entry → Entry
  | .positive path => .positive (initialPath ++ path)
  | .negative path => .negative (initialPath ++ path)
Unique/Views:normalizeEntries
def normalizeEntries (classes : ClassTable) : Nat → ClassName → List Entry → List Entry
  | fuel, name, entries =>
    if entries.contains (.positive []) then [.positive []]
    else match classes.lookup name with
    | none => entries
    | some declaration =>
      if declaration.fields.isEmpty && entries.isEmpty then [.positive []]
      else match fuel with
      | 0 => entries
      | fuel + 1 =>
        let children := declaration.fields.flatMap fun (field, target) =>
          let selected := entries.filterMap (Entry.dropPrefix [field])
          if selected.isEmpty then []
          else if selected.contains (.negative []) then [.negative [field]]
          else (normalizeEntries classes fuel target selected).map (Entry.prepend [field])
        if !declaration.fields.isEmpty && declaration.fields.all
            (fun field => children.contains (.positive [field.1])) then
          [.positive []]
        else children
Unique/Views:normalize
def normalize (classes : ClassTable) (ty : ViewType) : ViewType :=
  let depth := ty.entries.foldl (fun depth entry => max depth entry.path.length) 0
  { ty with entries := normalizeEntries classes (depth + 1) ty.className ty.entries }
Unique/Views:Normalized
def Normalized (classes : ClassTable) (ty : ViewType) : Prop :=
  normalize classes ty = ty

For a well-formed class table \(\Sigma\) and well-formed type \(T\), normalization preserves the base class, well-formedness, and every initialization fact:

\[ \begin{aligned} \href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(\href{#claim-given.typing.normalization}{\mathsf N}_{\Sigma}(T)) &= \href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(T),\\ \href{#claim-given.typing.observations}{\operatorname{neg}}_{\Sigma}(\href{#claim-given.typing.normalization}{\mathsf N}_{\Sigma}(T)) &= \href{#claim-given.typing.observations}{\operatorname{neg}}_{\Sigma}(T),\\ \href{#claim-given.typing.normalization}{\mathsf N}_{\Sigma}(\href{#claim-given.typing.normalization}{\mathsf N}_{\Sigma}(T)) &= \href{#claim-given.typing.normalization}{\mathsf N}_{\Sigma}(T). \end{aligned} \]

Reordering a view’s entries gives the same normalized type. Once normalized, a second pass makes no further change.

Unique/Normalization:normalization_correct
theorem normalization_correct {classes : ClassTable} (classesWf : classes.WellFormed)
    {ty : ViewType} (wf : ty.WellFormed classes) :
    (normalize classes ty).WellFormed classes ∧
    (normalize classes ty).className = ty.className ∧
    (∀ path, Pos classes (normalize classes ty) path ↔ Pos classes ty path) ∧
    (∀ path, Neg (normalize classes ty) path ↔ Neg ty path) ∧
    normalize classes (normalize classes ty) = normalize classes ty ∧
    (∀ entries, ty.entries.Perm entries →
      normalize classes ⟨ty.className, entries⟩ = normalize classes ty) := by
  refine ⟨normalize_wellFormed classesWf wf, rfl,
    normalize_pos_iff classesWf wf, normalize_neg_iff classesWf wf,
    normalize_idempotent classesWf wf, ?_⟩
  intro entries permutation
  exact (normalize_permutation classesWf wf.1 permutation).symm

Reading and updating a view

Focusing a type at an initialized relative place returns the current type of the value stored there, including any holes. Write \(T\downarrow\rho\); it is defined only when \(\rho\in\href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(T)\).

Start from \(\href{#claim-given.typing.normalization}{\mathsf{N}}_{\Sigma}(T)\). Focusing at \(\epsilon\) returns that type. For a nonempty path, let \(D=\href{#claim-given.typing.class_at}{\operatorname{class}}_{\Sigma}(\href{#claim-given.typing.base}{\operatorname{base}}(T),\rho)\).

  • If a positive entry’s path is a prefix of \(\rho\), including an entry at \(\epsilon\), the result is \(D\), the whole-type shorthand.
  • Otherwise, retain the entries below \(\rho\), remove their common prefix \(\rho\), and attach the resulting view to \(D\). Normalize the result.

For example, under the example declarations:

\[ \mathsf{Box}.\{-\mathsf{item.left},\mathsf{item.right}\} \downarrow\mathsf{item} = \mathsf{Pair}.\{-\mathsf{left},\mathsf{right}\}. \]

This operation does not restore fields that have been moved or hidden.

Unique/Views:focus
def focus (classes : ClassTable) (ty : ViewType) (path : Path) : Option ViewType := do
  if !decide (ty.WellFormed classes) then none else do
    let source := normalize classes ty
    if !positive classes source path then none else do
      let target ← classAt classes source.className path
      if path.isEmpty then some source
      else if source.entries.any (fun entry => match entry with
          | .positive initialPath => initialPath.isPrefixOf path
          | .negative _ => false) then
        some (.whole target)
      else some (normalize classes ⟨target, source.entries.filterMap (Entry.dropPrefix path)⟩)

Emptying an initialized nonempty path updates its enclosing type. Write \(T[-\rho]\), where \(\rho\in\href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(T)\). The result records that this slot is now empty and preserves the information about every other branch.

Compute the update as follows:

  1. Normalize the input type.
  2. Expand any positive entry that is a strict prefix of \(\rho\) into its declared fields, including an entry at \(\epsilon\). Continue only along the finite path to \(\rho\).
  3. Remove all entries at or below \(\rho\), then insert \(-\rho\). Normalize the result.

An expansion cannot pass through an empty class, because no longer valid path exists there. This procedure also handles a target that is already the common prefix of several view entries.

For the example’s Box, moving item.left yields:

\[ \mathsf{Box}[-\mathsf{item.left}] = \mathsf{Box}.\{-\mathsf{item.left},\mathsf{item.right}\}. \]

The preserved sibling is essential. Replacing the result with Box.{-item.left} would also forget access to item.right. An empty or unknown target has no emptying operation.

Unique/Views:remainingAfterMove
def remainingAfterMove (classes : ClassTable) (name : ClassName) : Path → List Entry
  | [] => []
  | field :: rest =>
    match classes.lookup name with
    | none => []
    | some declaration => declaration.fields.flatMap fun (other, target) =>
        if other == field then
          (remainingAfterMove classes target rest).map (Entry.prepend [other])
        else [.positive [other]]
Unique/Views:emptyPath
def emptyPath (classes : ClassTable) (ty : ViewType) (path : Path) : Option ViewType :=
  if !decide (ty.WellFormed classes) || path.isEmpty then none
  else
    let source := normalize classes ty
    if !positive classes source path then none
    else
      let retained := source.entries.flatMap fun entry =>
        if path.isPrefixOf entry.path then []
        else match entry with
        | .negative _ => [entry]
        | .positive initialPath =>
          if initialPath.isPrefixOf path then
            match classAt classes source.className initialPath with
            | none => []
            | some target =>
              (remainingAfterMove classes target (path.drop initialPath.length)).map
                (Entry.prepend initialPath)
          else [entry]
      some (normalize classes ⟨source.className, retained ++ [.negative path]⟩)

A value can be used through a view that provides less information. To compare types, first normalize them. For the normalized types \(T\) and \(U\), write \(T\preceq_{\Sigma}U\) when they have the same base class and:

\[ \href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(U)\subseteq\href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(T), \qquad \href{#claim-given.typing.observations}{\operatorname{neg}}_{\Sigma}(U)\subseteq\href{#claim-given.typing.observations}{\operatorname{neg}}_{\Sigma}(T). \]

This view weakening can forget initialization facts and access. It cannot invent them. For the example declarations, Pair can be weakened to Pair.{left}, but neither Pair.{left} nor Pair.{} can be strengthened to Pair. Unknown does not imply empty. Compare the known paths, not just the written entries: the single root entry in Pair includes both of its fields.

Weakening does not change storage, copy a reference, or abandon an object’s ownership. Hidden fields remain part of the owned object graph.

Unique/Views:Subtype
def Subtype (classes : ClassTable) (source target : ViewType) : Prop :=
  source.className = target.className ∧
    (∀ path, Pos classes (normalize classes target) path →
      Pos classes (normalize classes source) path) ∧
    (∀ path, Neg (normalize classes target) path → Neg (normalize classes source) path)

Typing expressions

A slot description \(B\) says that a slot is empty or contains a value of a particular type. A typing environment \(\Gamma\) describes every allocated variable slot:

\[ B ::= 0 \mid T, \qquad \Gamma\in\mathsf{VariableId}\rightharpoonup B. \]

Here \(B\) also denotes the set of slot descriptions generated by its grammar. The marker \(0\) describes an empty slot; it is not a value type. All types in an environment must be well formed and normalized under \(\Sigma\). An empty variable remains in \(\operatorname{dom}(\Gamma)\); its name cannot be reused by a fresh binding. An absent variable has no description.

Unique/Typing:SlotDescription
abbrev SlotDescription := Option ViewType
Unique/Typing:Environment
abbrev Environment := List (VariableId × SlotDescription)
Unique/Typing:Admissible
def Admissible (classes : ClassTable) (ty : ViewType) : Prop :=
  ty.WellFormed classes ∧ Normalized classes ty
Unique/Typing:Environment.WellFormed
def Environment.WellFormed (environment : Environment) (classes : ClassTable) : Prop :=
  (environment.map Prod.fst).Nodup ∧
    environment.all (fun entry => match entry.2 with
      | none => true
      | some ty => decide (Admissible classes ty)) = true
Unique/Typing:Environment.lookup
def Environment.lookup (environment : Environment) (name : VariableId) :
    Option SlotDescription :=
  (environment.find? fun entry => entry.1 == name).map Prod.snd
Unique/Typing:Environment.replace
def Environment.replace (environment : Environment) (name : VariableId)
    (description : SlotDescription) : Environment :=
  environment.map fun entry => if entry.1 = name then (name, description) else entry

To check a give, find the variable where the path starts, then follow its fields inside that variable’s type. For b.item.left, the variable is b and the relative place is item.left. Giving b itself has no field suffix.

Thus every place expression has a unique decomposition \(p=x.\rho\), with \(x.\epsilon=x\). Taking a place returns its current type and updates that variable’s environment description. Define \(\mathsf{take}_{\Sigma}(\Gamma,p)=(T,\Gamma')\) when \(\Gamma(x)=U\), \(\rho\in\href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(U)\), and:

\[ T=U\href{#claim-given.typing.focus}{\downarrow}\rho, \qquad \Gamma'= \begin{cases} \Gamma[x\mapsto 0] & \rho=\epsilon,\\ \Gamma[x\mapsto \href{#claim-given.typing.emptying}{U[-\rho]}] & \rho\ne\epsilon. \end{cases} \]

All other variables keep their descriptions. Taking an absent variable, an empty slot, or an unknown field is undefined.

Unique/Typing:splitPlace
def splitPlace : Place → VariableId × Path
  | .variable name => (name, [])
  | .field base name =>
      let (root, path) := splitPlace base
      (root, path ++ [name])
Unique/Typing:take
def take (classes : ClassTable) (environment : Environment) (place : Place) :
    Option (ViewType × Environment) := do
  let (root, path) := splitPlace place
  let source ← environment.lookup root
  let source ← source
  let result ← focus classes source path
  if path = [] then
    return (result, environment.replace root none)
  else
    let remaining ← emptyPath classes source path
    return (result, environment.replace root (some remaining))

Suppose \(\Gamma(b)=\mathsf{Box}\), using the Box, Pair, and Token declarations above. The following are two separate takes from that starting environment:

GiveRoot and relative placeResult typeUpdated description of b
b→\(b,\epsilon\)Box0
b.item.left→\(b,\mathsf{item.left}\)TokenBox.{-item.left, item.right}

The first takes the whole box. The second takes one token, leaving the box, the pair, and its other token accessible through b. Both leave every other variable’s description unchanged.

Unique/TypingChecks:take_root_and_field
example :
    splitPlace (.variable "b") = ("b", []) ∧
    splitPlace leftPlace = ("b", ["item", "left"]) ∧
    take classes afterConstruct (.variable "b") = some (box, [("b", none)]) ∧
    take classes afterConstruct leftPlace = some (token, [("b", some partialBox)]) := by
  decide

Expression typing records both the value produced and the environment after its moves:

\[ \Sigma;\Gamma\vdash e:T\;\triangleright\;\Gamma'. \]

The Give rule uses the current view of the source:

\[ \frac{\href{#claim-given.typing.take}{\mathsf{take}}_{\Sigma}(\Gamma,p)=(T,\Gamma')} {\Sigma;\Gamma\vdash p\mathord{\to}:T\;\triangleright\;\Gamma'} \quad\text{Give} \]

Construct checks arguments from left to right, passing each updated environment to the next argument:

\[ \frac{ \begin{gathered} \href{#claim-given.typing.declarations}{\Sigma(C)}=[f_1:C_1,\ldots,f_n:C_n]\\ \Sigma;\Gamma_{i-1}\vdash e_i:C_i\;\triangleright\;\Gamma_i \quad(1\leq i\leq n) \end{gathered} }{ \Sigma;\Gamma_0\vdash\mathsf{new}\ C(e_1,\ldots,e_n):C \;\triangleright\;\Gamma_n } \quad\text{Construct} \]

For no arguments, the environment is unchanged. The argument count must match the declaration. Each argument supplies an owning value, so the new object has fully initialized fields.

A result may expose less information:

\[ \frac{ \Sigma;\Gamma\vdash e:T\;\triangleright\;\Gamma' \qquad T\href{#claim-given.typing.forgetting}{\preceq}_{\Sigma}U }{ \Sigma;\Gamma\vdash e:U\;\triangleright\;\Gamma' } \quad\text{Weaken} \]

First-pass restriction. Constructor arguments must have their whole declared class types. A partially moved object can be transferred to another variable or unpacked, but cannot be passed to a constructor requiring its whole class. This rejects some dynamically safe programs. The Future extensions chapter records the proposed generic-view constructor signatures.

Unique/Typing:ExprTyped
inductive ExprTyped (classes : ClassTable) : Environment → Value → ViewType → Environment → Prop where
  | give {before after : Environment} {place : Place} {ty : ViewType} :
      before.WellFormed classes →
      take classes before place = some (ty, after) →
      Admissible classes ty → after.WellFormed classes →
      ExprTyped classes before (.give place) ty after
  | new {before after : Environment} {name : ClassName} {declaration : TypedClass}
      {arguments : List Value} :
      (name, declaration) ∈ classes →
      ArgsTyped classes before arguments (declaration.fields.map Prod.snd) after →
      Admissible classes (ViewType.whole name) →
      ExprTyped classes before (.new name arguments) (ViewType.whole name) after
  | weaken {before after : Environment} {value : Value} {ty other : ViewType} :
      ExprTyped classes before value ty after →
      Admissible classes other → Subtype classes ty other →
      ExprTyped classes before value other after
Unique/Typing:ArgsTyped
inductive ArgsTyped (classes : ClassTable) : Environment → List Value → List ClassName → Environment → Prop where
  | nil {environment : Environment} :
      environment.WellFormed classes → ArgsTyped classes environment [] [] environment
  | cons {before middle after : Environment} {value : Value} {values : List Value}
      {name : ClassName} {names : List ClassName} :
      ExprTyped classes before value (ViewType.whole name) middle →
      ArgsTyped classes middle values names after →
      ArgsTyped classes before (value :: values) (name :: names) after

Typing bindings and statements

The direct-field description records whether a field has the empty-slot description or gives its current type:

\[ \mathsf{field}_{\Sigma}(T,f)= \begin{cases} 0 & f\in\href{#claim-given.typing.observations}{\operatorname{neg}}_{\Sigma}(T),\\ T\href{#claim-given.typing.focus}{\downarrow} f & f\in\href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(T). \end{cases} \]

It is undefined if that field is unknown.

Unique/Typing:fieldDescription
def fieldDescription (classes : ClassTable) (ty : ViewType) (name : FieldName) :
    Option SlotDescription :=
  if negative ty [name] then some none
  else (focus classes ty [name]).map some

Binding typing, written \(\Sigma;\Gamma\vdash b:T\Rightarrow\Gamma'\), describes where an expression’s result goes. A variable pattern transfers its current type unchanged:

\[ \frac{x\notin\operatorname{dom}(\Gamma)} {\Sigma;\Gamma\vdash x:T\Rightarrow\Gamma[x\mapsto T]} \quad\text{Bind} \]

An unpacking pattern must name every declared field, and each field’s description must be defined:

\[ \frac{ \begin{gathered} \href{#claim-given.typing.base}{\operatorname{base}}(T)=C \qquad\href{#claim-given.typing.declarations}{\Sigma(C)}=[f_1:C_1,\ldots,f_n:C_n]\\ \href{#claim-given.typing.field}{\mathsf{field}}_{\Sigma}(T,f_i)=B_i\quad(1\leq i\leq n)\\ x_1,\ldots,x_n\text{ are distinct} \qquad x_i\notin\operatorname{dom}(\Gamma)\quad(1\leq i\leq n) \end{gathered} }{ \Sigma;\Gamma\vdash C\mathord{\to}\{f_1:x_1,\ldots,f_n:x_n\}:T \Rightarrow\Gamma[x_1\mapsto B_1,\ldots,x_n\mapsto B_n] } \quad\text{Unpack} \]

The rule displays fields in declaration order; named patterns can be reordered to that order. A known-empty field produces an empty binding. An initialized field transfers its current type, which may itself be a partial view.

Knowing every direct field’s status is sufficient: unpacking does not inspect the interiors of the objects transferred. An unknown direct field prevents this rule from applying. It cannot be silently dropped or assigned an invented initialization status.

Unique/Typing:FieldBindings
inductive FieldBindings (classes : ClassTable) (ty : ViewType) : List (FieldName × VariableId) → Environment → Prop where
  | nil : FieldBindings classes ty [] []
  | cons {field : FieldName} {destination : VariableId} {description : SlotDescription}
      {fields : List (FieldName × VariableId)} {bindings : Environment} :
      fieldDescription classes ty field = some description →
      FieldBindings classes ty fields bindings →
      FieldBindings classes ty ((field, destination) :: fields)
        ((destination, description) :: bindings)
Unique/Typing:BindingTyped
inductive BindingTyped (classes : ClassTable) : Environment → Unpacking.Pattern → ViewType → Environment → Prop where
  | variable {environment : Environment} {name : VariableId} {ty : ViewType} :
      environment.WellFormed classes → Admissible classes ty →
      name ∉ environment.map Prod.fst →
      BindingTyped classes environment (.variable name) ty ((name, some ty) :: environment)
  | unpack {before : Environment} {ty : ViewType} {name : ClassName}
      {declaration : TypedClass} {fields : List (FieldName × VariableId)}
      {bindings : Environment} :
      before.WellFormed classes → Admissible classes ty →
      ty.className = name → (name, declaration) ∈ classes →
      (fields.map Prod.fst).Perm (declaration.fields.map Prod.fst) →
      (fields.map Prod.snd).Nodup →
      (∀ destination ∈ fields.map Prod.snd, destination ∉ before.map Prod.fst) →
      FieldBindings classes ty fields bindings →
      (bindings ++ before).WellFormed classes →
      BindingTyped classes before (.unpack name fields) ty (bindings ++ before)

Statement typing, written \(\Sigma;\Gamma\vdash t\Rightarrow\Gamma'\), first types the expression and then its binding pattern:

\[ \frac{ \Sigma;\Gamma\vdash e:T\;\href{#claim-given.typing.expressions}{\triangleright}\;\Gamma_1 \qquad \href{#claim-given.typing.bindings}{\Sigma;\Gamma_1\vdash b:T\Rightarrow\Gamma_2} }{ \Sigma;\Gamma\vdash\mathsf{let}\ b=e\Rightarrow\Gamma_2 } \quad\text{Let} \]
Unique/Typing:StatementTyped
inductive StatementTyped (classes : ClassTable) : Environment → Unpacking.Statement → Environment → Prop where
  | letValue {before middle after : Environment} {pattern : Unpacking.Pattern}
      {value : Value} {ty : ViewType} :
      ExprTyped classes before value ty middle →
      BindingTyped classes middle pattern ty after →
      StatementTyped classes before ⟨pattern, value⟩ after

A statement-sequence typing \(\Sigma;\Gamma\vdash P\Rightarrow\Gamma_f\) threads statement typings through the remaining code:

\[ \frac{}{\Sigma;\Gamma\vdash []\Rightarrow\Gamma} \qquad \frac{ \href{#claim-given.typing.statements}{\Sigma;\Gamma\vdash t\Rightarrow\Gamma_1} \qquad\Sigma;\Gamma_1\vdash P\Rightarrow\Gamma_f }{ \Sigma;\Gamma\vdash t::P\Rightarrow\Gamma_f }. \]
Unique/Typing:SequenceTyped
inductive SequenceTyped (classes : ClassTable) : Environment → List Unpacking.Statement → Environment → Prop where
  | nil {environment : Environment} :
      environment.WellFormed classes → SequenceTyped classes environment [] environment
  | cons {before middle after : Environment} {statement : Unpacking.Statement}
      {rest : List Unpacking.Statement} :
      StatementTyped classes before statement middle →
      SequenceTyped classes middle rest after →
      SequenceTyped classes before (statement :: rest) after

A program is well typed when \(\Sigma\) is well formed and \(\href{#claim-given.typing.sequences}{\Sigma;\varnothing\vdash P\Rightarrow\Gamma_f}\) for some final environment \(\Gamma_f\). The final environment describes locals before initial-frame exit and need not be empty. Frame exit discards those locals and collects the heap; user-defined destruction is not part of this language.

Unique/Typing:ProgramTyped
def ProgramTyped (classes : ClassTable) (code : List Unpacking.Statement) : Prop :=
  classes.WellFormed ∧ ∃ finalEnvironment, SequenceTyped classes [] code finalEnvironment

A nested move followed by unpacking

With the Token, Pair, and Box declarations above:

let b = new Box(new Pair(new Token(), new Token()));
let taken = b.item.left→;
let p = b.item→;
let Pair → { left, right } = p→;

The statement rules change the following entries; all others keep their descriptions. The marker 0 means that a variable exists with an empty slot.

StatementUpdated bindingNew bindings
Construct—b: Box
Give leftb: Box.{-item.left, item.right}taken: Token
Give itemb: Box.{-item}p: Pair.{-left, right}
Unpackp: 0left: 0, right: Token

Unpacking consumes the pair object; the box and both tokens remain. A subsequent left→ has no typing derivation, because left is empty. Nor can p→ be repeated.

Unique/TypingExecutionChecks:moves_and_unpacking
example :
    StatementTyped classes [] (program[0]'(by decide)) afterConstruct ∧
    StatementTyped classes afterConstruct (program[1]'(by decide)) afterLeft ∧
    StatementTyped classes afterLeft (program[2]'(by decide)) afterItem ∧
    StatementTyped classes afterItem (program[3]'(by decide)) afterUnpack ∧
    SequenceTyped classes [] program afterUnpack ∧
    Unpacking.Steps classes.erase ⟨State.empty, program⟩ ⟨runtimeFinal, []⟩ ∧
    (Unpacking.Configuration.mk runtimeFinal []).finished ∧
    (∀ ty after, ¬ ExprTyped classes afterUnpack (.give (.variable "left")) ty after) ∧
    (∀ ty after, ¬ ExprTyped classes afterUnpack (.give (.variable "p")) ty after) := by
  exact ⟨construct_typed, left_typed, item_typed, unpack_typed, program_typed,
    program_executes, rfl, fun _ _ => failed_take_not_typed (by decide),
    fun _ _ => failed_take_not_typed (by decide)⟩

The expression and binding rules distinguish failure from lack of knowledge:

  • From p: Pair.{-left, right}, p.left→ is rejected because the field is known empty.
  • From p: Pair.{right}, the same expression is rejected because left is unknown. It might exist and be initialized at runtime.
  • From p: Pair.{-left, right}, giving p→ succeeds statically with that same viewed type. It does not produce a whole Pair.
  • Passing that result to new Box(p→) is rejected by this first constructor rule, even though the untyped machine could put the partial pair in the box.
  • Unpacking Pair.{right} is rejected because it would need a description for the hidden left field.

Constructor argument order also matters:

class Two { a: Token, b: Token }
let t = new Token();
let bad = new Two(t→, t→);

The first argument leaves t: 0. The second argument therefore has no typing derivation. Constructor arguments are checked in the same order as evaluation.

Unique/TypingRejectionChecks:rejected_moves
example :
    (∀ ty after, ¬ ExprTyped classes partialEnvironment (.give left) ty after) ∧
    (∀ ty after, ¬ ExprTyped classes hiddenEnvironment (.give left) ty after) ∧
    Satisfies classes runtimeFull 2 hiddenPair ∧
    Eval classes.erase runtimeFull (.give left) runtimeGivenLeft 0 ∧
    ExprTyped classes partialEnvironment (.give root) partialPair [("p", none)] ∧
    (∀ after, ¬ ExprTyped classes partialEnvironment (.give root) pair after) ∧
    (∀ ty after, ¬ ExprTyped classes partialEnvironment (.new "Box" [.give root]) ty after) ∧
    Eval classes.erase runtimePartial (.new "Box" [.give root])
      (runtimeAfterTake.allocate "Box" ["item"] [2]) 3 ∧
    (∀ before pattern after, ¬ BindingTyped classes before
      (.unpack "Pair" pattern) hiddenPair after) ∧
    ExprTyped twoClasses tokenEnvironment tokenGive token [("t", none)] ∧
    (∀ ty after, ¬ ExprTyped twoClasses [("t", none)] tokenGive ty after) ∧
    (∀ ty after, ¬ ExprTyped twoClasses tokenEnvironment
      (.new "Two" [tokenGive, tokenGive]) ty after) := by
  exact ⟨fun _ _ => failed_take_not_typed (by decide),
    fun _ _ => failed_take_not_typed (by decide), initialized_hidden_field.1,
    initialized_hidden_field.2, partial_give, fun _ => partial_not_whole,
    fun _ _ => partial_constructor_rejected, partial_constructor_executes,
    fun _ _ _ => hidden_unpack_rejected, first_argument_moves,
    fun _ _ => failed_take_not_typed (by decide), fun _ _ => repeated_argument_rejected⟩

Relating types to storage

Reading a relative path, written \(\mathsf{read}_S(\alpha,\rho)\), starts at object \(\alpha\) and follows the fields of the relative path \(\rho\). At \(\epsilon\), it returns \(\alpha\) if the object exists. At a nonempty path, every intermediate slot must contain an existing object; the final slot may contain an object identity or \(\bot\). A missing object or field encountered while following the path, or an empty intermediate slot, makes the read undefined. The final identity is not dereferenced.

Unique/TypingRealization:readPath
def readPath (state : State) (object : ObjectId) : Path → Option Slot
  | [] => do
      let _ ← state.objects.lookup object
      return some object
  | field :: rest => do
      let data ← state.objects.lookup object
      let slot ← data.fields.lookup field
      match rest with
      | [] => return slot
      | _ :: _ => do
          let target ← slot
          readPath state target rest

An object satisfies a type, written \(\Sigma;S\models\alpha:T\), when:

  • \(O(\alpha)\) exists and has class \(\href{#claim-given.typing.base}{\operatorname{base}}(T)\).
  • For every \(\rho\in\href{#claim-given.typing.observations}{\operatorname{pos}}_{\Sigma}(T)\), \(\href{#claim-given.typing.read}{\mathsf{read}}_S(\alpha,\rho)=\beta\) for an allocated object \(\beta\) of class \(\href{#claim-given.typing.class_at}{\operatorname{class}}_{\Sigma}(\href{#claim-given.typing.base}{\operatorname{base}}(T),\rho)\).
  • For every \(\rho\in\href{#claim-given.typing.observations}{\operatorname{neg}}_{\Sigma}(T)\), \(\href{#claim-given.typing.read}{\mathsf{read}}_S(\alpha,\rho)=\bot\).

Omitted branches impose no local initialization requirement. The definition ranges over finite paths; recursive class declarations need no infinite syntactic unfolding.

Unique/TypingRealization:Satisfies
structure Satisfies (classes : ClassTable) (state : State) (object : ObjectId) (ty : ViewType) : Prop where
  root : ∃ data, (object, data) ∈ state.objects ∧ data.className = ty.className
  positive : ∀ path, Pos classes ty path →
    ∃ target data, readPath state object path = some (some target) ∧
      (target, data) ∈ state.objects ∧
      classAt classes ty.className path = some data.className
  negative : ∀ path, Neg ty path → readPath state object path = some none

Expression results can temporarily own objects before binding or construction. Let \(R\) be a finite ordered list of pairs \((\alpha:T)\) for these pending values. Write \(\Sigma;\Gamma\models(S;R)\) when all of the following hold:

  1. Storage satisfies refgiven.well_formed, with the references in \(R\) counted alongside stored references in the ownership condition. Thus every allocated object has exactly one owner, including hidden fields and pending values.
  2. Every occupied object field targets an object of its declared nominal class in \(\Sigma\). This condition applies even to fields hidden by views.
  3. \(\operatorname{dom}(\Gamma)=\operatorname{dom}(V)\). If \(\Gamma(x)=0\), then \(V(x)=\bot\). If \(\Gamma(x)=T\), then \(V(x)=\alpha\) and \(\href{#claim-given.typing.satisfaction}{\Sigma;S\models\alpha:T}\).
  4. Each \((\alpha:T)\) in \(R\) satisfies \(\href{#claim-given.typing.satisfaction}{\Sigma;S\models\alpha:T}\).

Here \(\Sigma\) is a well-formed typed class table, \(S=\langle O,V,\nu\rangle\), and the operational class table is \(\href{#claim-given.typing.erasure}{\lfloor\Sigma\rfloor}\). Types must be well formed and normalized throughout. Empty pending lists are written \([]\).

This relation does not require every allocated object to satisfy its whole class type. That would rule out the very field moves the views describe.

Unique/TypingRealization:FieldsMatchClasses
def FieldsMatchClasses (classes : ClassTable) (state : State) : Prop :=
  ∀ parent data field target, (parent, data) ∈ state.objects →
    (field, some target) ∈ data.fields →
    ∃ declaration targetClass targetData,
      (data.className, declaration) ∈ classes ∧
      (field, targetClass) ∈ declaration.fields ∧
      (target, targetData) ∈ state.objects ∧ targetData.className = targetClass
Unique/TypingRealization:PendingValues
abbrev PendingValues := List (ObjectId × ViewType)
Unique/TypingRealization:Realizes
structure Realizes (classes : ClassTable) (environment : Environment) (state : State) (pending : PendingValues) : Prop where
  classesWellFormed : classes.WellFormed
  environmentWellFormed : environment.WellFormed classes
  pendingTypes : ∀ object ty, (object, ty) ∈ pending → Admissible classes ty
  ownership : WellFormedWith classes.erase state (pending.map Prod.fst)
  fields : FieldsMatchClasses classes state
  variableDomain : ∀ name,
    name ∈ environment.map Prod.fst ↔ name ∈ state.variables.map Prod.fst
  emptyVariables : ∀ name, (name, none) ∈ environment → (name, none) ∈ state.variables
  initializedVariables : ∀ name ty, (name, some ty) ∈ environment →
    ∃ object, (name, some object) ∈ state.variables ∧ Satisfies classes state object ty
  pendingValues : ∀ object ty, (object, ty) ∈ pending → Satisfies classes state object ty

Write \(\longrightarrow_u^{*}\) for zero or more extended steps, using the reflexive and transitive rules of refgiven.executions with \(\longrightarrow_u\) in place of \(\longrightarrow\). Write \(K\longrightarrow_u^k K'\) for exactly \(k\) program steps, including collection and initial-frame exit. The local operation is the unpacking-capable relation.

Unique/Frames:Steps
def Steps (operation : LocalStep Instruction) (before after : Configuration Instruction) : Prop :=
  ∃ count, StepsExactly operation before count after
Unique/Frames:StepsExactly
inductive StepsExactly (operation : LocalStep Instruction) : Configuration Instruction → Nat → Configuration Instruction → Prop where
  | refl (configuration) : StepsExactly operation configuration 0 configuration
  | step {before middle after count} :
      Step operation before middle → StepsExactly operation middle count after →
      StepsExactly operation before (count + 1) after

A configuration is stuck in the extended language when it is not finished and has no \(\href{given.html#claim-given.unpacking}{\longrightarrow_u}\) successor. Finishing means that the initial frame has been popped.

Unique/Frames:Stuck
def Stuck (operation : LocalStep Instruction) (configuration : Configuration Instruction) : Prop :=
  ¬ configuration.finished ∧ ¬ ∃ after, Step operation configuration after

A live frame is well typed with final environment \(\Gamma_f\) when its storage realizes an environment under which its remaining statements typecheck:

\[ \Sigma\vdash\operatorname{run}(S,P):\Gamma_f \iff \exists\Gamma.\;\Sigma;\Gamma\models(S;[]) \land \Sigma;\Gamma\vdash P\Rightarrow\Gamma_f. \]

A configuration with no frame is well typed when its heap is empty. Its counter may be nonzero. The final environment describes the locals before exit; it does not assert that terminal storage still contains those bindings. For a live frame, realization requires a well-formed class table.

Write \(K\longrightarrow_u^k K'\) for exactly \(k\) program steps using unpacking-capable local operations. Finite executions existentially quantify \(k\); stuckness means an unfinished configuration with no successor. The frame-pop step is included in this count.

Unique/FrameSafety:ConfigurationTyped
def ConfigurationTyped (classes : ClassTable) (configuration : Configuration Unpacking.Statement)
    (finalEnvironment : Environment) : Prop :=
  match configuration.frame with
  | none => configuration.objects = []
  | some frame => Typing.ConfigurationTyped classes ⟨configuration.state, frame.code⟩ finalEnvironment
Unique/Frames:StepsExactly
inductive StepsExactly (operation : LocalStep Instruction) : Configuration Instruction → Nat → Configuration Instruction → Prop where
  | refl (configuration) : StepsExactly operation configuration 0 configuration
  | step {before middle after count} :
      Step operation before middle → StepsExactly operation middle count after →
      StepsExactly operation before (count + 1) after
Unique/Frames:Stuck
def Stuck (operation : LocalStep Instruction) (configuration : Configuration Instruction) : Prop :=
  ¬ configuration.finished ∧ ¬ ∃ after, Step operation configuration after
Unique/TypedConfigurations:ConfigurationTyped
def ConfigurationTyped (classes : ClassTable) (configuration : Unpacking.Configuration)
    (finalEnvironment : Environment) : Prop :=
  ∃ current, Realizes classes current configuration.state [] ∧
    SequenceTyped classes current configuration.code finalEnvironment

Progress and preservation

Expression typing guarantees both successful evaluation and the description of its result. For every well-formed \(\Sigma\), environment \(\Gamma\), storage \(S\), and pending-value list \(R\), assume:

\[ \Sigma;\Gamma\vdash e:T\;\href{#claim-given.typing.expressions}{\triangleright}\;\Gamma', \qquad \href{#claim-given.typing.realization}{\Sigma;\Gamma\models(S;R)}. \]

Then an evaluation exists:

\[ \exists S',\alpha.\; \href{#claim-given.typing.erasure}{\lfloor\Sigma\rfloor}\vdash\langle S,e\rangle \href{given.html#claim-given.evaluation}{\Downarrow}\langle S',\alpha\rangle. \]

Moreover, every such evaluation satisfies:

\[ \href{#claim-given.typing.realization}{\Sigma;\Gamma'\models(S';R\mathbin{+\!\!+}[(\alpha:T)])}. \]

Here \(+\!\!+\) appends lists. Earlier constructor arguments are included in \(R\) while later arguments run. The lemma preserves their types as well as the variables’ types. Evaluation leaves the variable domain unchanged, so the typing rules’ freshness checks also hold at the point of runtime binding.

Unique/TypingSafety:expression_soundness
theorem expression_soundness
    (typed : ExprTyped classes before value ty after)
    (realized : Realizes classes before state pending) :
    (∃ result object, Eval classes.erase state value result object) ∧
    (∀ result object, Eval classes.erase state value result object →
      Realizes classes after result (pending ++ [(object, ty)])) := by
  have sound := typed.sound state pending realized
  refine ⟨sound.1, fun result object evaluated => ?_⟩
  exact (sound.2 result object evaluated).perm (by simpa using (List.perm_middle (a := (object, ty)) (l₁ := pending) (l₂ := [])).symm)

For every well-typed configuration, either execution has finished or a next step is possible:

\[ \Sigma\vdash K:\Gamma_f \quad\Longrightarrow\quad \mathsf{Finished}(K) \;\lor\; \exists K'.\;\lfloor\Sigma\rfloor\vdash K\longrightarrow_u K'. \]

This is a claim about the operational rules: typing does not add a transition for an otherwise failing operation.

Unique/FrameSafety:ConfigurationTyped.progress
theorem ConfigurationTyped.progress
    (typed : ConfigurationTyped classes configuration finalEnvironment) :
    configuration.finished ∨ ∃ after, Step (patternOperation classes.erase) configuration after := by
  rcases configuration with ⟨objects, nextId, frame⟩
  cases frame with
  | none => exact .inl rfl
  | some frame =>
    rcases frame with ⟨variables, code⟩
    have localTyped : Typing.ConfigurationTyped classes ⟨⟨objects, variables, nextId⟩, code⟩ finalEnvironment := typed
    rcases localTyped.progress with finished | ⟨after, step⟩
    · change code = [] at finished
      subst code
      exact .inr ⟨_, exit_step ⟨objects, variables, nextId⟩⟩
    · exact .inr ⟨_, local_step (operation := patternOperation classes.erase)
        (before := ⟨objects, variables, nextId⟩) (code := code) (after := after.state)
        (rest := after.code) step (local_wellFormed (localTyped.preservation step))⟩

Every step from a well-typed configuration preserves its typing:

\[ \frac{ \Sigma\vdash K:\Gamma_f \qquad \lfloor\Sigma\rfloor\vdash K\longrightarrow_u K' }{ \Sigma\vdash K':\Gamma_f }. \]

The existential current environment changes to reflect moved slots and new bindings. The final environment stays the same. This theorem quantifies over every operational successor, including unpacking an object with empty fields.

Unique/FrameSafety:ConfigurationTyped.preservation
theorem ConfigurationTyped.preservation
    (typed : ConfigurationTyped classes before finalEnvironment)
    (step : Step (patternOperation classes.erase) before after) :
    ConfigurationTyped classes after finalEnvironment := by
  cases step with
  | «local» operation =>
    have next := Typing.ConfigurationTyped.preservation typed operation
    rw [collect_running (local_wellFormed next)]
    exact next
  | exit =>
    rw [collect_popped]
    rfl

For a well-formed class table, a program whose statements check from the empty environment cannot reach a stuck configuration. Every execution prefix remains well typed and can be completed.

If the original program has \(n\) statements, every such prefix extends to completion after exactly \(n+1\) steps in total: one per statement, followed by one frame-pop step. A live frame’s remaining work is its statement count plus one; a finished configuration has zero remaining work. Terminal storage has no locals and an empty heap; its allocation counter records the identifiers spent.

Unique/FrameSafety:program_safety
theorem program_safety (classesWf : classes.WellFormed)
    (typed : SequenceTyped classes [] code finalEnvironment)
    (execution : StepsExactly (patternOperation classes.erase) (.initial code) count configuration) :
    ¬ Stuck (patternOperation classes.erase) configuration ∧
    ConfigurationTyped classes configuration finalEnvironment ∧
    count + configuration.remaining = code.length + 1 ∧
    ∃ nextId,
      StepsExactly (patternOperation classes.erase) configuration configuration.remaining (.terminal nextId) ∧
      StepsExactly (patternOperation classes.erase) (.initial code) (code.length + 1) (.terminal nextId) := by
  have current := (ConfigurationTyped.initial classesWf typed).trace execution
  have length : count + configuration.remaining = code.length + 1 := by
    exact (execution.remaining (fun _ _ _ _ step => step.code_length)).symm
  obtain ⟨nextId, rest⟩ := current.finishes
  refine ⟨?_, current, length, nextId, rest, length ▸ execution.trans rest⟩
  intro stuck
  rcases current.progress with finished | next
  · exact stuck.1 finished
  · exact stuck.2 next

From a well-typed live frame with \(n\) statements, there is an observation state \(S_f\) after exactly \(n\) program steps. Its frame has no statements left, and its locals still realize the final environment. One further step pops that frame, leaving no roots and an empty heap with counter \(S_f.\nu\). This separates inspection of the computed bindings from program completion.

Unique/FrameSafety:completion
theorem completion (typed : Typing.ConfigurationTyped classes before finalEnvironment) :
    ∃ observed,
      StepsExactly (patternOperation classes.erase) (.running before.state before.code)
        before.code.length (.running observed []) ∧
      Realizes classes finalEnvironment observed [] ∧
      StepsExactly (patternOperation classes.erase) (.running before.state before.code)
        (before.code.length + 1) (.terminal observed.nextId) := by
  obtain ⟨last, trace, finished, realized⟩ := typed.finishes
  have lifted := lift_local_trace typed trace
  change last.code = [] at finished
  rw [finished] at lifted
  exact ⟨last.state, lifted, realized, lifted.trans (.step (exit_step _) (.refl _))⟩

Shared

Shared: operational semantics

Shared ownership lets several references own the same object. A reference \(r\) pairs a mode \(\kappa\) with an object identity \(\alpha\). The object itself has no ownership mode. Variables and object fields are slots; their contents \(s\) are empty or hold one reference:

\[ \begin{aligned} \kappa &::= \mathsf{unique}\mid\mathsf{shared} \\ r &::= (\kappa,\alpha) \\ s &::= \bot\mid r. \end{aligned} \]

Object identities are tagged natural numbers, written \(\mathsf{obj}(n)\), with \(\operatorname{index}(\mathsf{obj}(n))=n\).

Shared/Syntax:ObjectId
structure ObjectId where
  index : Nat
  deriving DecidableEq, Repr
Shared/State:Mode
inductive Mode where
  | unique
  | shared
  deriving DecidableEq, Repr
Shared/State:Reference
structure Reference where
  reference ::
  mode : Mode
  object : ObjectId
  deriving DecidableEq, Repr
Shared/State:Reference.owned
def Reference.owned (object : ObjectId) : Reference := ⟨.unique, object⟩
Shared/State:Reference.shared
def Reference.shared (object : ObjectId) : Reference := ⟨.shared, object⟩
Shared/State:Slot
abbrev Slot := Option Reference

A place expression \(p\) follows fields from a variable to select a slot. Giving it, p→, requires every slot and intermediate object on the route to exist, and every slot to hold a reference. It moves the reference when every reference along that route is unique. If any is shared, it returns a shared copy and keeps the source initialized:

Path accessStored modeResult modeSource slot afterwards
UniqueUniqueUniqueEmpty
SharedSharedSharedUnchanged
SharedUniqueSharedStored reference becomes shared

In every case, the result refers to the source reference’s object. When copying a unique reference through shared access, the stored reference becomes shared too. Only the reference in that final slot changes; every other reference and object identity stay unchanged.

Sharing a container leaves its field references’ modes alone. Those fields are already reached through a shared path, even if their own references are unique. Copying one of those references later makes the final stored reference shared as well.

Shared/Syntax:Place
inductive Place where
  | variable (name : VariableId)
  | field (base : Place) (name : FieldName)
  deriving DecidableEq, Repr
Shared/Step:Resolve
inductive Resolve (state : State) : Place → StoragePlace → ObjectId → Mode → Prop where
  | variable {name reference} :
      (name, some reference) ∈ state.variables →
      Resolve state (.variable name) (.variable name) reference.object reference.mode
  | field {base source parent permission data name reference} :
      Resolve state base source parent permission →
      (parent, data) ∈ state.objects →
      (name, some reference) ∈ data.fields →
      Resolve state (.field base name) (.field parent name) reference.object
        (permission.join reference.mode)
Shared/Step:Take
inductive Take : State → StoragePlace → ObjectId → State → Prop where
  | variable (objects : List (ObjectId × Object)) (nextId : Nat)
      (leading suffix : List (VariableId × Slot)) (name : VariableId) (object : ObjectId) :
      Take ⟨objects, leading ++ (name, some (.owned object)) :: suffix, nextId⟩
        (.variable name) object
        ⟨objects, leading ++ (name, none) :: suffix, nextId⟩
  | field (variables : List (VariableId × Slot)) (nextId : Nat)
      (before after : List (ObjectId × Object)) (parent : ObjectId) (className : ClassName)
      (leading suffix : List (FieldName × Slot)) (name : FieldName) (object : ObjectId) :
      Take ⟨before ++ (parent, ⟨className, leading ++ (name, some (.owned object)) :: suffix⟩) :: after,
          variables, nextId⟩
        (.field parent name) object
        ⟨before ++ (parent, ⟨className, leading ++ (name, none) :: suffix⟩) :: after,
          variables, nextId⟩
Shared/Step:Promote
inductive Promote : State → StoragePlace → ObjectId → State → Prop where
  | variable (objects : List (ObjectId × Object)) (nextId : Nat)
      (leading suffix : List (VariableId × Slot)) (name : VariableId) (object : ObjectId) :
      Promote ⟨objects, leading ++ (name, some (.owned object)) :: suffix, nextId⟩
        (.variable name) object
        ⟨objects, leading ++ (name, some (.shared object)) :: suffix, nextId⟩
  | field (variables : List (VariableId × Slot)) (nextId : Nat)
      (before after : List (ObjectId × Object)) (parent : ObjectId) (className : ClassName)
      (leading suffix : List (FieldName × Slot)) (name : FieldName) (object : ObjectId) :
      Promote ⟨before ++ (parent, ⟨className, leading ++ (name, some (.owned object)) :: suffix⟩) :: after,
          variables, nextId⟩
        (.field parent name) object
        ⟨before ++ (parent, ⟨className, leading ++ (name, some (.shared object)) :: suffix⟩) :: after,
          variables, nextId⟩
Shared/Step:Give
inductive Give : State → Place → Reference → State → Prop where
  | move {state cleared : State} {path : Place} {source : StoragePlace} {object : ObjectId} :
      Resolve state path source object .unique →
      Take state source object cleared →
      Give state path (.owned object) cleared
  | copy {state : State} {path : Place} {source : StoragePlace} {object : ObjectId} :
      Resolve state path source object .shared →
      Stored state source (some (.shared object)) →
      Give state path (.shared object) state
  | promote {state promoted : State} {path : Place} {source : StoragePlace} {object : ObjectId} :
      Resolve state path source object .shared →
      Promote state source object promoted →
      Give state path (.shared object) promoted

A nominal type has a name and an ordered list of fields. Its declaration chooses whether its values can be shared and whether construction makes them shared immediately:

DeclarationMay be sharedConstructor result
class C { ... }NoGiven C
struct C { ... }YesGiven C
shared struct C { ... }Yesshared C

These three forms describe nominal types; they do not introduce three different kinds of runtime object representation. Modes still belong to references.

Shared/Syntax:Kind
inductive Kind where
  | classType
  | structType
  | sharedStruct
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr
Shared/Syntax:Class
structure Class where
  fields : List FieldName
  kind : Kind := .structType
  deriving DecidableEq, Repr
Shared/State:Kind.mode
def Kind.mode : Kind → Mode
  | .sharedStruct => .shared
  | _ => .unique

The predicate struct(T) means that the nominal type underlying T is declared as either struct or shared struct. It does not depend on the reference’s current permission or on which fields its view exposes. It is false for a class.

Every field of a struct, including a shared struct, must itself have a struct type. This restriction applies to all declared fields, including ones hidden by a view or currently empty. Classes may contain either classes or structs. Thus sharing a container cannot expose a class through shared field access. A shared C type is permitted only when struct(C) holds.

This layer checks struct(T) directly from nominal declarations. Generic type parameters, user-written predicates, and predicate where-clauses are not part of this language. Destructors and assignment belong to later layers.

Shared/Syntax:Kind.isStruct
def Kind.isStruct : Kind → Bool
  | .classType => false
  | _ => true
Shared/TypingViews:StructType
def StructType (classes : ClassTable) (ty : ValueType) : Prop :=
  (classes.lookup ty.base).any (fun declaration => declaration.kind.isStruct) = true
Shared/TypingViews:ClassTable.WellFormed
def ClassTable.WellFormed (classes : ClassTable) : Prop :=
  (classes.map Prod.fst).Nodup ∧
    ∀ entry ∈ classes, (entry.2.fields.map Prod.fst).Nodup ∧
      ∀ field ∈ entry.2.fields, field.2.className ∈ classes.map Prod.fst ∧
        KindValid classes field.2.toType ∧
        (entry.2.kind.isStruct = true → StructType classes field.2.toType)
Shared/TypingViews:KindValid
def KindValid (classes : ClassTable) (ty : ValueType) : Prop :=
  (classes.lookup ty.base).any (fun declaration => kindAllows declaration.kind ty.permission) = true

These declarations distinguish the three forms without requiring primitive types:

struct Token {}
struct Box { value: Token }
shared struct SharedBox { value: Token }
class Resource { token: Token }
class Owner { resource: Resource, box: Box }

Box and SharedBox satisfy the struct-only field restriction. Owner may contain a Resource because Owner is a class. In contrast, both of the following declarations are rejected:

struct BadBox { resource: Resource }
shared struct BadSharedBox { resource: Resource }

An empty view of Resource would not make either declaration valid: hiding its fields does not make the nominal type a struct.

Shared/KindChecks:declarations
example : classes.WellFormed ∧
    StructType classes (.whole "Token") ∧ StructType classes (.whole "Box") ∧
    StructType classes (.whole "SharedBox" .shared) ∧
    ¬ StructType classes (.whole "Resource") ∧
    ¬ StructType classes ⟨.given, ⟨"Resource", []⟩⟩ ∧
    ¬ ClassTable.WellFormed (("BadBox", badBox) :: classes) ∧
    ¬ ClassTable.WellFormed (("BadSharedBox", badSharedBox) :: classes) := by
  decide

Places, values, and programs

A nominal declaration named \(C\), in \(\mathsf{ClassName}\), declares an ordered list of \(n\) fields, where \(n\) is a natural number including zero. A field name \(f\) belongs to \(\mathsf{FieldName}\). Constructor arguments supply the fields in order. Source fields have types checked by the type system. The operational declaration retains its kind and ordered field names; all values are objects.

Shared/Syntax:ClassName
abbrev ClassName := String
Shared/Syntax:FieldName
abbrev FieldName := String
Shared/Syntax:Class
structure Class where
  fields : List FieldName
  kind : Kind := .structType
  deriving DecidableEq, Repr

A variable name \(x\) belongs to \(\mathsf{VariableId}\). A place expression \(p\) starts at a variable and follows fields. A value expression \(e\) gives from a place, gives and shares the result, or constructs an object. A statement \(t\) binds an expression’s result:

\[ \begin{aligned} p &::= x\mid p.f \\ e &::= p\mathord{\to} \\ &\phantom{{}::={}}\mid p\mathord{\to}\mathsf{share} \\ &\phantom{{}::={}}\mid\mathsf{new}\ C(e_1,\ldots,e_n) \\ t &::= \mathsf{let}\ x=e \end{aligned} \]

The expression p→share performs the give, requires a struct result, then makes that result a shared owner. A class result cannot be shared. Giving along a unique route empties the source. To share a newly constructed object, first construct it in a variable, then give-share that variable.

Each let names a fresh runtime variable. Constructor arguments are value expressions, evaluated from left to right; they may themselves construct objects. There is no shadowing, scope, call, assignment, destruction, or borrowing in this fragment.

Shared/Syntax:VariableId
abbrev VariableId := String
Shared/Syntax:Place
inductive Place where
  | variable (name : VariableId)
  | field (base : Place) (name : FieldName)
  deriving DecidableEq, Repr
Shared/Syntax:Value
inductive Value where
  | give (source : Place)
  | giveShare (source : Place)
  | new (className : ClassName) (arguments : List Value)
  deriving Repr
Shared/Syntax:Statement
structure Statement where
  letValue ::
  destination : VariableId
  value : Value
  deriving Repr

A program \(\Pi=\langle\Delta,P\rangle\) has a class table \(\Delta\) and a finite ordered sequence \(P\) of statements:

\[ \begin{aligned} \Delta &\in \mathsf{ClassName}\rightharpoonup(\mathsf{Kind}\times\mathsf{List}(\mathsf{FieldName})),\\ P &::= []\mid t::P. \end{aligned} \]

The finite-map and list notation is unchanged. For a nominal declaration of kind \(k\) listing \(f_1,\ldots,f_n\), \(\Delta(C)=(k,[f_1,\ldots,f_n])\).

Shared/Syntax:Classes
abbrev Classes := List (ClassName × Class)
Shared/Syntax:Program
structure Program where
  classes : Classes
  body : List Statement
  deriving Repr

A class table is well formed when class names are distinct and each declaration lists distinct field names.

Shared/Soundness:ClassesWellFormed
def ClassesWellFormed (classes : Classes) : Prop :=
  (classes.map Prod.fst).Nodup ∧
    ∀ name declaration, (name, declaration) ∈ classes → declaration.fields.Nodup

Copying a field

Start with no objects or variables and execute:

struct Token {}
struct Box { value: Token }

let t = new Token();
let b = new Box(t→);
let s = b→share;
let u = s.value→;
let v = s.value→;

The first two statements construct a token and put its reference in a box, leaving t empty. The third moves the box’s reference out of b and makes it shared in s. The box’s field still holds a unique reference to the token.

The fourth statement reaches the token through shared variable s. It changes the reference in the box’s value field to shared and gives u a shared copy. The fifth copies the already-shared reference into v.

After these statements, before frame exit, there are still two objects. Variable s is a shared owner of the box. The box’s field, u, and v are three shared owners of the token. Variables t and b are empty. Both field gives succeed because neither empties the field.

Shared/Examples:sharing_execution
example : Steps exampleClasses ⟨State.empty, sharingCode⟩ ⟨twiceCopiedState, []⟩ := by
  exact .step (example_create_token _)
    (.step (example_create_box _) (.step (example_share_box _)
      (.step (example_copy_field _) (.step (example_copy_again _) (.refl _)))))

Objects and slots

An object \(o\) has a class name and named field slots, whose contents can be empty:

\[ o::=C\{f_1:s_1,\ldots,f_n:s_n\}. \]
Shared/State:Object
structure Object where
  className : ClassName
  fields : List (FieldName × Slot)
  deriving DecidableEq, Repr

A storage state \(S=\langle O,V,\nu\rangle\) consists of the object table, variable table, and allocation counter \(\nu\). Object identities are tagged numbers. Creation uses \(\mathsf{obj}(\nu)\), then increments the counter.

We use finite-map notation for tables with distinct keys:

\[ O\in\mathsf{ObjectId}\rightharpoonup\mathsf{Object},\qquad V\in\mathsf{VariableId}\rightharpoonup\mathsf{Slot},\qquad \nu\in\mathbb N. \]
Shared/State:State
structure State where
  objects : List (ObjectId × Object)
  variables : List (VariableId × Slot)
  nextId : Nat
  deriving DecidableEq, Repr

The empty storage state has no objects or variables, and counter zero:

\[S_{\emptyset}=\langle\varnothing,\varnothing,0\rangle.\]

Here \(\varnothing\) denotes the empty map.

Shared/State:State.empty
def State.empty : State := ⟨[], [], 0⟩

A storage place \(q\) selects one slot directly: a variable or a field of a particular object:

\[ q::=x\mid\alpha.f. \]

A place expression follows a route to a slot; a storage place identifies the slot itself.

Shared/State:StoragePlace
inductive StoragePlace where
  | variable (name : VariableId)
  | field (object : ObjectId) (name : FieldName)
  deriving DecidableEq, Repr

Slot lookup \(S[q]=s\) reads the contents at a storage place. For storage \(S=\langle O,V,\nu\rangle\):

\[ \begin{aligned} S[x]&=V(x)&&\text{when }V(x)\text{ is defined},\\ S[\alpha.f_i]&=s_i&&\text{when }O(\alpha)=C\{f_1:s_1,\ldots,f_n:s_n\},\ 1\le i\le n. \end{aligned} \]

An empty slot still exists; lookup at an absent variable, object, or field is undefined. A reference identifies an object in \(O\); the slot does not contain that object’s data.

Shared/State:Stored
def Stored (state : State) (place : StoragePlace) (slot : Slot) : Prop :=
  match place with
  | .variable name => (name, slot) ∈ state.variables
  | .field object name =>
      ∃ data, (object, data) ∈ state.objects ∧ (name, slot) ∈ data.fields

Reading a route

Mode combination \(\kappa_0\sqcup\kappa_1\) combines the access to a containing object with the mode of a field’s reference. The result is unique only when both are unique:

\[ \kappa_0\sqcup\kappa_1 = \begin{cases} \mathsf{unique} & \kappa_0=\mathsf{unique}\ \land\ \kappa_1=\mathsf{unique},\\ \mathsf{shared} & \text{otherwise}. \end{cases} \]
Shared/State:Mode.join
def Mode.join : Mode → Mode → Mode
  | .unique, .unique => .unique
  | _, _ => .shared

Resolving a place reads its route without changing the state. Write \(S\vdash p\Downarrow q:\alpha@\kappa\) when the route selects a storage place \(q\) and object \(\alpha\), with effective access mode \(\kappa\). The effective mode describes the entire route, not just the last stored reference.

A variable starts with its stored reference’s mode. A field combines the mode of its prefix with its own using mode combination:

\[ \frac{\href{#claim-shared.lookup}{S[x]}=(\kappa,\alpha)} {S\vdash x\Downarrow x:\alpha@\kappa} \qquad \frac{S\vdash p\Downarrow q:\beta@\kappa_0\quad \href{#claim-shared.lookup}{S[\beta.f]}=(\kappa_1,\alpha)} {S\vdash p.f\Downarrow\beta.f:\alpha@\href{#claim-shared.mode_join}{(\kappa_0\sqcup\kappa_1)}}. \]

Thus once a shared reference occurs along a path, the rest of that path has shared access. An absent variable, a missing field or intermediate object, or an empty slot prevents resolution.

Shared/Step:Resolve
inductive Resolve (state : State) : Place → StoragePlace → ObjectId → Mode → Prop where
  | variable {name reference} :
      (name, some reference) ∈ state.variables →
      Resolve state (.variable name) (.variable name) reference.object reference.mode
  | field {base source parent permission data name reference} :
      Resolve state base source parent permission →
      (parent, data) ∈ state.objects →
      (name, some reference) ∈ data.fields →
      Resolve state (.field base name) (.field parent name) reference.object
        (permission.join reference.mode)

Executing statements

A frame \(f=(V,P)\) owns its local variable store \(V\) and remaining statements \(P\). The program has one initial frame; after its exit there is no frame. Heap objects \(O\) and the allocation counter \(\nu\) live outside it:

\[ K=\langle O,\nu,F\rangle,\qquad F::=\mathsf{none}\mid\mathsf{some}(V,P). \]

For expression evaluation, combine the live frame’s locals with the heap and counter as the storage \(S=\langle O,V,\nu\rangle\). Write \(\operatorname{run}(S,P)=\langle O,\nu,\mathsf{some}(V,P)\rangle\). The pair \(\langle S,P\rangle\) used by local statement rules is an observation of that live frame, not a terminal program state.

Initially \(K=\operatorname{run}(S_{\emptyset},P)\), including when \(P=[]\). Exhausting the statements leaves a live frame whose bindings can still be inspected. A separate exit step pops it. There are no nested scopes or calls in this layer; Functions will extend this single-frame lifetime to a stack.

Shared/Frames:Frame
structure Frame (Instruction : Type) where
  variables : List (VariableId × Slot)
  code : List Instruction
  deriving Repr
Shared/Frames:Configuration
structure Configuration (Instruction : Type) where
  objects : List (ObjectId × Object)
  nextId : Nat
  frame : Option (Frame Instruction)
  deriving Repr
Shared/Frames:Configuration.running
def Configuration.running (state : State) (code : List Instruction) : Configuration Instruction :=
  ⟨state.objects, state.nextId, some ⟨state.variables, code⟩⟩
Shared/Frames:Configuration.initial
def Configuration.initial (code : List Instruction) : Configuration Instruction :=
  .running State.empty code
Shared/Frames:Configuration.state
def Configuration.state (configuration : Configuration Instruction) : State :=
  ⟨configuration.objects, configuration.frame.map Frame.variables |>.getD [], configuration.nextId⟩

Reachability starts at an initialized slot of the live frame and follows initialized object fields. Write \(\mathsf{Live}_S(\alpha)\) when this reaches object \(\alpha\). An absent frame has no roots.

Eager collection retains exactly reachable object entries. For object data \(D\) (its class tag and field slots), define:

\[ \operatorname{gc}(K)=\langle [(\alpha,D)\in O\mid\mathsf{Live}_{S_K}(\alpha)],\nu,F\rangle. \]

Here \(S_K\) uses the frame’s locals, or an empty variable store if the frame is absent. Collection preserves surviving objects and their identifiers, the allocation counter, and the frame. It invokes no user code. With no frame, it removes the entire heap.

The Lean definition is a mathematical reachability filter, not an executable traversal. Collection runs after whole statements and frame exit, never between constructor operands or while an expression result awaits binding.

Shared/State:Live
inductive Live (state : State) : ObjectId → Prop where
  | variable {name reference} :
      (name, some reference) ∈ state.variables → Live state reference.object
  | field {parent reference data name} :
      Live state parent → (parent, data) ∈ state.objects →
      (name, some reference) ∈ data.fields → Live state reference.object
Shared/Frames:State.collect
def State.collect (state : State) : State := by
  classical
  exact { state with objects := state.objects.filter (fun entry => decide (Live state entry.1)) }
Shared/Frames:Configuration.collect
def Configuration.collect (configuration : Configuration Instruction) : Configuration Instruction :=
  { configuration with objects := configuration.state.collect.objects }

A configuration is finished exactly when its initial frame has been popped:

\[ \mathsf{Finished}(\langle O,\nu,F\rangle)\iff F=\mathsf{none}. \]

An empty statement sequence still has a live frame and can take its exit step. Completion discards the frame’s locals and collects its unreachable objects.

Shared/Frames:Configuration.finished
def Configuration.finished (configuration : Configuration Instruction) : Prop :=
  configuration.frame = none

Expression evaluation, written

\[ \Delta\vdash\langle S,e\rangle\Downarrow\langle S',r\rangle, \]

produces a reference and updated storage. These clauses define successful evaluation:

  • Give. Evaluate p→ by giving from its route. The result is unique when it moves and shared when it copies.
  • Give-share. Evaluate p→share by the same give, require that its result targets a struct, then replace the result’s mode with shared, preserving its object identity. This last conversion changes no stored slot.
  • Construct. Evaluate arguments from left to right, then create an object containing their results in declaration order:
\[ \frac{ \begin{gathered} \href{#claim-shared.programs}{\Delta(C)}=(k,[f_1,\ldots,f_n])\\ \Delta\vdash\langle S_{i-1},e_i\rangle\Downarrow\langle S_i,r_i\rangle \quad(1\le i\le n)\\ \beta\notin\operatorname{dom}(O_n)\\ \mathsf{isStruct}(k)\Rightarrow\forall i.\;\mathsf{StructReference}_{\Delta,S_n}(r_i) \end{gathered} }{ \Delta\vdash\langle S_0,\mathsf{new}\ C(e_1,\ldots,e_n)\rangle \Downarrow\langle S',(\mathsf{mode}(k),\beta)\rangle } \quad\text{Construct} \]

where

\[ \begin{aligned} S_n&=\langle O_n,V_n,\nu_n\rangle,\\ \beta&=\href{#claim-shared.references}{\mathsf{obj}(\nu_n)},\\ O'&=O_n[\beta\mapsto C\{f_1:r_1,\ldots,f_n:r_n\}],\\ S'&=\langle O',V_n,\nu_n+1\rangle. \end{aligned} \]

Here mode(k) is shared for a shared struct and unique otherwise, as specified by the declaration kinds. StructReference means that the reference targets an allocated object whose declaration is a struct. The argument guard applies to both struct kinds and prevents constructing a struct containing a class even in an untyped program.

Here \(S_i\) is the storage after the first \(i\) arguments; \(\operatorname{dom}(O_n)\) is its set of allocated identities and the map update adds the fresh object’s entry. An empty class takes no arguments and uses \(S_n=S_0\). Argument results remain owned by the evaluation until placed in the new object’s fields. An unknown class, wrong argument count, or failed argument evaluation gives no successful construction.

Shared/Step:Eval
inductive Eval (classes : Classes) : State → Value → State → Reference → Prop where
  | give {state evaluated : State} {path : Place} {reference : Reference} :
      Give state path reference evaluated →
      Eval classes state (.give path) evaluated reference
  | giveShare {state evaluated : State} {path : Place} {reference : Reference} :
      Give state path reference evaluated →
      StructReference classes evaluated reference →
      Eval classes state (.giveShare path) evaluated (.shared reference.object)
  | new {state evaluated : State} {className : ClassName} {declaration : Class}
      {arguments : List Value} {references : List Reference} :
      (className, declaration) ∈ classes →
      EvalArgs classes state arguments evaluated references →
      references.length = declaration.fields.length →
      ObjectId.mk evaluated.nextId ∉ evaluated.objects.map Prod.fst →
      StructArguments classes evaluated declaration.kind references →
      Eval classes state (.new className arguments)
        (evaluated.allocate className declaration.fields references) (⟨declaration.kind.mode, ⟨evaluated.nextId⟩⟩)
Shared/Step:EvalArgs
inductive EvalArgs (classes : Classes) : State → List Value → State → List Reference → Prop where
  | nil (state : State) : EvalArgs classes state [] state []
  | cons {before middle after : State} {argument : Value} {arguments : List Value}
      {reference : Reference} {references : List Reference} :
      Eval classes before argument middle reference →
      EvalArgs classes middle arguments after references →
      EvalArgs classes before (argument :: arguments) after (reference :: references)
Shared/Step:State.allocate
def State.allocate (state : State) (className : ClassName) (fields : List FieldName)
    (references : List Reference) : State :=
  ⟨(⟨state.nextId⟩, ⟨className, fields.zip (references.map some)⟩) :: state.objects,
    state.variables, state.nextId + 1⟩
Shared/Step:StructReference
def StructReference (classes : Classes) (state : State) (reference : Reference) : Prop :=
  ∃ data declaration, (reference.object, data) ∈ state.objects ∧
    (data.className, declaration) ∈ classes ∧ declaration.kind.isStruct = true
Shared/Step:StructArguments
def StructArguments (classes : Classes) (state : State) (kind : Kind)
    (references : List Reference) : Prop :=
  kind.isStruct = true → ∀ reference ∈ references, StructReference classes state reference
Shared/State:Kind.mode
def Kind.mode : Kind → Mode
  | .sharedStruct => .shared
  | _ => .unique

An auxiliary local statement operation \(\Delta\vdash K\rightsquigarrow K'\) executes the first statement in a local observation of the frame. It completes expression evaluation, stores the result in a fresh variable, and removes the statement:

\[ \frac{ \href{#claim-shared.evaluation}{\Delta\vdash\langle S,e\rangle\Downarrow\langle S',r\rangle} \quad x\notin\operatorname{dom}(V') }{ \Delta\vdash\langle S,(\mathsf{let}\ x=e)::P\rangle \rightsquigarrow\langle\langle O',V'[x\mapsto r],\nu'\rangle,P\rangle } \quad\text{Let} \]

where \(S'=\langle O',V',\nu'\rangle\), and \(V'[x\mapsto r]\) adds variable \(x\) holding \(r\). The remaining statements keep their order. If evaluation fails or the variable already exists, there is no transition. All argument evaluations belong to this one step; there is no separately observable state partway through a failed expression. Write \(\rightsquigarrow\) for that local operation. The program machine collects after it and has a separate exit rule:

\[ \frac{\Delta\vdash\langle S,P\rangle\rightsquigarrow\langle S',P'\rangle} {\Delta\vdash\operatorname{run}(S,P)\longrightarrow \operatorname{gc}(\operatorname{run}(S',P'))} \qquad \Delta\vdash\operatorname{run}(\langle O,V,\nu\rangle,[]) \longrightarrow\operatorname{gc}(\langle O,\nu,\mathsf{none}\rangle). \]

The exit target has no frame and an empty heap, retaining counter \(\nu\). Even an empty program takes one exit step. A finished configuration has no successor. The Lean Step in Shared/Step is the auxiliary local relation; Framed.Step is this program machine. baseOperation selects the single-variable binding relation; later patternOperation selects the unpacking relation.

Shared/Step:State.bind
def State.bind (state : State) (name : VariableId) (reference : Reference) : State :=
  { state with variables := (name, some reference) :: state.variables }
Shared/Step:Step
inductive Step (classes : Classes) : Configuration → Configuration → Prop where
  | letValue {state evaluated : State} {destination : VariableId} {value : Value}
      {reference : Reference} {rest : List Statement} :
      destination ∉ evaluated.variables.map Prod.fst →
      Eval classes state value evaluated reference →
      Step classes ⟨state, ⟨destination, value⟩ :: rest⟩
        ⟨evaluated.bind destination reference, rest⟩
Shared/Frames:Step
inductive Step (operation : LocalStep Instruction) : Configuration Instruction → Configuration Instruction → Prop where
  | «local» {before after code rest} :
      operation before code after rest →
      Step operation (.running before code) (Configuration.running after rest).collect
  | exit {state} :
      Step operation (.running state []) (Configuration.mk state.objects state.nextId none).collect
Shared/Frames:baseOperation
def baseOperation (classes : Classes) : LocalStep Statement :=
  fun before code after rest => Dada.Shared.Step classes ⟨before, code⟩ ⟨after, rest⟩
Shared/Frames:patternOperation
def patternOperation (classes : Classes) : LocalStep Unpacking.Statement :=
  fun before code after rest => Unpacking.Step classes ⟨before, code⟩ ⟨after, rest⟩
class Token {}
let t = new Token();

The first step binds the token in the initial frame. That frame is still live even though its statements are exhausted. The second step pops it and collects the token, leaving an empty heap and allocation counter one. An empty program has no statements but still takes its initial-frame exit step.

Shared/FrameChecks:lifetime
example :
    Step (baseOperation classes) (.initial []) (Configuration.terminal (Instruction := Statement) 0) ∧
    Step (baseOperation classes) (.initial code) (.running observed []) ∧
    ("t", some (.owned 0)) ∈ observed.variables ∧
    ¬ (Configuration.running observed ([] : List Statement)).finished ∧
    StepsExactly (baseOperation classes) (.initial code) 2 (.terminal 1) ∧
    (Configuration.terminal (Instruction := Statement) 1).finished := by
  refine ⟨exit_step State.empty, local_step allocated observed_wellFormed, by decide,
    by simp [Configuration.running, Configuration.finished], ?_, rfl⟩
  exact .step (local_step allocated observed_wellFormed) (.step (exit_step observed) (.refl _))

Using the declarations above:

let b = new SharedBox(new Token());
let c = b→;
let t = b.value→;

Construction gives b a shared reference immediately. Giving b copies that reference into c, leaving b initialized. The token field initially holds a unique reference; giving it through shared b promotes that stored reference and produces a shared token in t. Immediate sharing of the container does not require its fields to have been stored with shared modes.

Shared/KindChecks:immediately_shared
example : SequenceTyped classes [] program finalEnvironment ∧
    Unpacking.Steps classes.erase ⟨State.empty, program⟩ ⟨finalState, []⟩ ∧
    RawType.normalize classes (.nominal (.whole "SharedBox")) = sharedBox ∧
    ¬ Admissible classes (.whole "SharedBox") ∧
    ¬ Admissible classes (.whole "Resource" .shared) ∧
    ("b", some (.shared 1)) ∈ finalState.variables ∧
    ("c", some (.shared 1)) ∈ finalState.variables ∧
    ("t", some (.shared 0)) ∈ finalState.variables := by
  exact ⟨program_typed, execution, by decide, by decide, by decide,
    by decide, by decide, by decide⟩

new Resource(new Token()) produces a unique class reference. Binding it to r and then evaluating r→share is rejected. Plain r→ remains a move; a class may contain structs without becoming shareable itself.

Shared/KindChecks:class_boundary
example : ExprTyped classes [] (.new "Resource" [.new "Token" []]) (.whole "Resource") [] ∧
    (∀ ty after, ¬ ExprTyped classes [("r", some (.whole "Resource"))]
      (.giveShare (.variable "r")) ty after) ∧
    (∀ after, ¬ Unpacking.Bind classes.erase constructed (.shared 1)
      (.unpack "SharedBox" [("value", "v")]) after) ∧
    give classes [("r", some (.whole "Resource"))] (.variable "r") =
      some (.whole "Resource", [("r", none)]) := by
  exact ⟨class_construction, fun _ _ => class_sharing_rejected,
    (fun _ => Unpacking.shared_cannot_unpack), by decide⟩

A finite execution \(\Delta\vdash K\longrightarrow^{*}K'\) consists of zero or more statement steps:

\[ \frac{}{\Delta\vdash K\longrightarrow^{*}K} \qquad \frac{\href{#claim-shared.steps}{\Delta\vdash K\longrightarrow K'} \quad\Delta\vdash K'\longrightarrow^{*}K''} {\Delta\vdash K\longrightarrow^{*}K''}. \]
Shared/Frames:Steps
def Steps (operation : LocalStep Instruction) (before after : Configuration Instruction) : Prop :=
  ∃ count, StepsExactly operation before count after
Shared/Frames:StepsExactly
inductive StepsExactly (operation : LocalStep Instruction) : Configuration Instruction → Nat → Configuration Instruction → Prop where
  | refl (configuration) : StepsExactly operation configuration 0 configuration
  | step {before middle after count} :
      Step operation before middle → StepsExactly operation middle count after →
      StepsExactly operation before (count + 1) after

A configuration is stuck when its frame remains but no step is available:

\[ \mathsf{Stuck}_{\Delta}(K)\iff \neg\href{#claim-shared.finished}{\mathsf{Finished}(K)}\ \land\ \neg\exists K'.\;\href{#claim-shared.steps}{\Delta\vdash K\longrightarrow K'}. \]

For example, giving through an entirely unique path empties its slot, so giving it again cannot evaluate and leaves the machine stuck. Repeated gives through shared access leave the source initialized.

Shared/Frames:Stuck
def Stuck (operation : LocalStep Instruction) (configuration : Configuration Instruction) : Prop :=
  ¬ configuration.finished ∧ ¬ ∃ after, Step operation configuration after

Use struct Token {} and struct Box { value: Token }. Let object \(\mathsf{obj}(0)\) be a token and object \(\mathsf{obj}(1)\) a box, with these slots and allocation counter \(2\):

SlotContents
bUnique owner of box \(\mathsf{obj}(1)\)
tEmpty
Box \(\mathsf{obj}(1)\), field valueUnique owner of token \(\mathsf{obj}(0)\)

Execute:

let s = b→share;

Variable s receives a shared owner of box \(\mathsf{obj}(1)\), and b becomes empty. The field remains a unique owner of token \(\mathsf{obj}(0)\). The objects, empty t, and allocation counter are unchanged.

Shared/Examples:share_value
example : Step exampleClasses
    ⟨boxState, [⟨"s", .giveShare (.variable "b")⟩]⟩ ⟨sharedBoxState, []⟩ := by
  exact example_share_box []

Start again from the pre-exit storage of refshared.example.share_value, before copying its field. Execute:

class Outer { value: shared Box }
let outer = new Outer(s→);
let u = outer.value.value→;

The constructor copies shared variable s into the new outer object \(\mathsf{obj}(2)\); s remains initialized. Variable outer uniquely owns the outer object \(\mathsf{obj}(2)\). The give then traverses three references: unique outer, shared outer.value to box \(\mathsf{obj}(1)\), and the unique value field of box \(\mathsf{obj}(1)\) to token \(\mathsf{obj}(0)\).

The shared middle link makes this a shared access even though the first and last stored references are unique. The give changes only the reference in box \(\mathsf{obj}(1)\)’s value field to shared, and u receives a shared owner of token \(\mathsf{obj}(0)\). outer stays unique; its field stays shared; s still refers to box \(\mathsf{obj}(1)\). All three objects remain allocated and the allocation counter is \(3\).

Shared/Examples:nested_shared_path
example : Steps nestedClasses
    ⟨sharedBoxState, [⟨"outer", .new "Outer" [.give (.variable "s")]⟩,
      ⟨"u", .give (.field (.field (.variable "outer") "value") "value")⟩]⟩
    ⟨nestedCopiedState, []⟩ := by
  apply Steps.step (middle := ⟨nestedSharedState,
    [⟨"u", .give (.field (.field (.variable "outer") "value") "value")⟩]⟩)
  · apply Step.letValue (reference := .owned 2)
      (evaluated := sharedBoxState.allocate "Outer" ["value"] [.shared 1])
    · simp [State.allocate, sharedBoxState]
    · apply Eval.new (declaration := ⟨["value"], .classType⟩) (references := [.shared 1])
      · simp [nestedClasses]
      · apply EvalArgs.cons (reference := .shared 1)
        · apply Eval.give
          apply Give.copy (source := .variable "s")
          · exact Resolve.variable (reference := .shared 1) (by simp [sharedBoxState])
          · simp [Stored, sharedBoxState]
        · exact EvalArgs.nil _
      · rfl
      · decide
      · simp [StructArguments, Kind.isStruct]
  apply Steps.step (middle := ⟨nestedCopiedState, []⟩)
  · apply Step.letValue (reference := .shared 0)
      (evaluated := ⟨nestedCopiedState.objects, nestedSharedState.variables, 3⟩)
    · simp [nestedSharedState, sharedBoxState]
    · apply Eval.give
      apply Give.promote (source := .field 1 "value")
      · apply Resolve.field (permission := .shared) (reference := .owned 0)
          (data := ⟨"Box", [("value", some (.owned 0))]⟩)
        · apply Resolve.field (permission := .unique) (reference := .shared 1)
            (data := ⟨"Outer", [("value", some (.shared 1))]⟩)
          · exact Resolve.variable (reference := .owned 2) (by simp [nestedSharedState])
          · simp [nestedSharedState, Reference.owned]
          · simp
        · simp [nestedSharedState, boxState]
        · simp
      · exact Promote.field nestedSharedState.variables 3
          [(2, ⟨"Outer", [("value", some (.shared 1))]⟩)] [(0, ⟨"Token", []⟩)]
          1 "Box" [] [] "value" 0
  exact Steps.refl _

Liveness and well-formedness

An object is allocated when its identity appears in the object table:

\[ \mathsf{Allocated}_S(\alpha)\iff\alpha\in\operatorname{dom}(O). \]
Shared/State:Allocated
def Allocated (state : State) (object : ObjectId) : Prop :=
  object ∈ state.objects.map Prod.fst

An object is live when an owning path reaches it from a variable, following occupied slots. Both unique and shared references contribute owning edges:

\[ \frac{\href{#claim-shared.lookup}{S[x]}=(\kappa,\alpha)}{\mathsf{Live}_S(\alpha)} \qquad \frac{\mathsf{Live}_S(\beta)\quad\href{#claim-shared.lookup}{S[\beta.f]}=(\kappa,\alpha)} {\mathsf{Live}_S(\alpha)}. \]

Empty slots contribute no edge.

Shared/State:Live
inductive Live (state : State) : ObjectId → Prop where
  | variable {name reference} :
      (name, some reference) ∈ state.variables → Live state reference.object
  | field {parent reference data name} :
      Live state parent → (parent, data) ∈ state.objects →
      (name, some reference) ∈ data.fields → Live state reference.object

During expression evaluation, an object can be live with pending values even when no variable points to it. A list of pending references supplies additional roots alongside the variable roots of ordinary liveness. An object is live with pending values when a finite sequence of occupied field slots reaches it from either kind of root. Both unique and shared references contribute edges, and a pending reference reaches its own target directly.

Shared/Reachability:LiveWith
inductive LiveWith (state : State) (pending : List Reference) : ObjectId → Prop where
  | pending {reference} : reference ∈ pending → LiveWith state pending reference.object
  | variable {name reference} : (name, some reference) ∈ state.variables →
      LiveWith state pending reference.object
  | field {parent data name reference} : LiveWith state pending parent →
      (parent, data) ∈ state.objects → (name, some reference) ∈ data.fields →
      LiveWith state pending reference.object

Allocated objects and live objects are distinguished by presence in storage and reachability from roots.

A state is well formed, written \(\mathsf{WF}_{\Delta}(S)\), when:

  • Object identities and variable names are each distinct.
  • Every object’s class is declared, and its distinct field names match the declaration’s order, including fields whose slots are empty.
  • Every allocated identity has an index below the allocation counter.
  • Every allocated object is live: some finite owning path reaches it from a variable root. Field edges need not follow allocation order.
  • Every stored reference targets an allocated object, and every allocated object has at least one stored owning reference.
  • Any two distinct owning occurrences targeting the same object are both shared.
  • Every occupied field of a struct targets another struct object.
  • Every shared reference targets a struct, and every reference to an instance of a shared struct is shared.

The first six clauses are structural well-formedness. The final two are the declaration-kind invariants. Structural well-formedness also has a form that counts pending expression results as additional owning occurrences and uses liveness with pending values for its rootedness condition. This lets expression soundness describe values not yet placed in a slot.

Owning occurrences are counted across all variable slots and all object fields. The ownership-compatibility condition permits several shared references to an object, but a stored unique reference must be its only incoming owning reference. That local condition does not by itself give a path unique access: every preceding reference must also be unique. Rootedness excludes an unreachable component even when its objects reference one another. It permits cycles reachable through shared access; the allocation counter is a freshness bound, not a ranking of heap edges.

Shared/State:Allocated
def Allocated (state : State) (object : ObjectId) : Prop :=
  object ∈ state.objects.map Prod.fst
Shared/State:Live
inductive Live (state : State) : ObjectId → Prop where
  | variable {name reference} :
      (name, some reference) ∈ state.variables → Live state reference.object
  | field {parent reference data name} :
      Live state parent → (parent, data) ∈ state.objects →
      (name, some reference) ∈ data.fields → Live state reference.object
Shared/State:References
def References (state : State) : List ObjectId :=
  state.variables.filterMap (fun binding => binding.2.map Reference.object) ++
    state.objects.flatMap (fun entry => entry.2.fields.filterMap
      (fun field => field.2.map Reference.object))
Shared/Soundness:Owners
def Owners (state : State) : List Reference :=
  state.variables.filterMap (fun binding => binding.2) ++
    state.objects.flatMap (fun entry => entry.2.fields.filterMap (fun field => field.2))
Shared/Soundness:Compatible
def Compatible (first second : Reference) : Prop :=
  first.object ≠ second.object ∨ first.mode = .shared ∧ second.mode = .shared
Shared/Soundness:WellFormed
structure WellFormed (classes : Classes) (state : State) : Prop where
  objectKeys : (state.objects.map Prod.fst).Nodup
  variableKeys : (state.variables.map Prod.fst).Nodup
  shapes : ∀ id data, (id, data) ∈ state.objects →
    ∃ declaration, (data.className, declaration) ∈ classes ∧
      data.fields.map Prod.fst = declaration.fields ∧ declaration.fields.Nodup
  bounds : ∀ id data, (id, data) ∈ state.objects → id.index < state.nextId
  rooted : ∀ object, Allocated state object → Live state object
  ownersCompatible : (Owners state).Pairwise Compatible
  referencesComplete : ∀ id, id ∈ References state ↔ Allocated state id
Shared/Soundness:WellFormedWith
structure WellFormedWith (classes : Classes) (state : State) (pending : List Reference) : Prop where
  objectKeys : (state.objects.map Prod.fst).Nodup
  variableKeys : (state.variables.map Prod.fst).Nodup
  shapes : ∀ id data, (id, data) ∈ state.objects →
    ∃ declaration, (data.className, declaration) ∈ classes ∧
      data.fields.map Prod.fst = declaration.fields ∧ declaration.fields.Nodup
  bounds : ∀ id data, (id, data) ∈ state.objects → id.index < state.nextId
  rooted : ∀ object, Allocated state object → LiveWith state pending object
  ownersCompatible : (pending ++ Owners state).Pairwise Compatible
  referencesComplete : ∀ id, id ∈ (pending.map Reference.object ++ References state) ↔ Allocated state id
Shared/KindSafety:HasKind
def HasKind (classes : Classes) (state : State) (object : ObjectId) (kind : Kind) : Prop :=
  ∃ name declaration, (object, name) ∈ objectNames state ∧
    (name, declaration) ∈ classes ∧ declaration.kind = kind
Shared/KindSafety:ReferenceAllowed
def ReferenceAllowed (classes : Classes) (state : State) (reference : Reference) : Prop :=
  ∃ kind, HasKind classes state reference.object kind ∧
    (reference.mode = .shared → kind.isStruct = true) ∧
    (kind = .sharedStruct → reference.mode = .shared)
Shared/KindSafety:KindCorrect
structure KindCorrect (classes : Classes) (state : State) (pending : List Reference) : Prop where
  references : ∀ reference ∈ pending ++ Owners state, ReferenceAllowed classes state reference
  fields : ∀ object data declaration, (object, data) ∈ state.objects →
    (data.className, declaration) ∈ classes → declaration.kind.isStruct = true →
    ∀ name reference, (name, some reference) ∈ data.fields →
      StructReference classes state reference
Shared/KindSafety:WellFormedState
def WellFormedState (classes : Classes) (state : State) : Prop :=
  WellFormed classes state ∧ KindCorrect classes state []

Structural well-formedness accepts a parent whose child was allocated later. The checked heap contains class Parent object 0, class Leaf object 1, and allocation counter 2. Variable p uniquely owns object 0; its child field uniquely owns object 1. Both objects are reachable, and each has exactly one owning occurrence. The field edge from 0 to 1 is permitted independently of their allocation indices.

Shared/RootedChecks:newer_child
example : WellFormed classes newerChild := by
  refine ⟨by decide, by decide, ?_, ?_, ?_, ?_, ?_⟩
  · intro id data member
    simp only [newerChild, List.mem_cons, List.not_mem_nil, or_false] at member
    rcases member with h | h <;> cases h
    · exact ⟨⟨["child"], .classType⟩, by decide, rfl, by decide⟩
    · exact ⟨⟨[], .classType⟩, by decide, rfl, by decide⟩
  · intro id data member
    simp only [newerChild, List.mem_cons, List.not_mem_nil, or_false] at member
    rcases member with h | h <;> cases h <;> decide
  · intro object allocated
    have cases : object = ⟨0⟩ ∨ object = ⟨1⟩ := by simpa [Allocated, newerChild] using allocated
    rcases cases with rfl | rfl
    · exact .variable (name := "p") (reference := .owned ⟨0⟩) (by decide)
    · exact .field (parent := ⟨0⟩) (name := "child") (reference := .owned ⟨1⟩)
        (.variable (name := "p") (reference := .owned ⟨0⟩) (by decide))
        (data := ⟨"Parent", [("child", some (.owned ⟨1⟩))]⟩) (by decide) (by decide)
  · simp [Owners, newerChild, Compatible, Reference.owned]
  · intro object
    simp [References, Allocated, newerChild, Reference.owned]

Consider two struct Node objects, 0 and 1, each with a next field. Variable root holds a shared reference to object 0; object 0’s next holds a shared reference to object 1, and object 1’s next holds a shared reference back to 0. With allocation counter 2, this heap satisfies structural well-formedness. Both objects have finite paths from root, despite the cycle. This is a check of an arbitrary heap, not a claim that this layer’s constructor-only operations can create the cycle.

Shared/RootedChecks:shared_cycle
example : WellFormed classes sharedCycle := by
  refine ⟨by decide, by decide, ?_, ?_, ?_, ?_, ?_⟩
  · intro id data member
    simp only [sharedCycle, List.mem_cons, List.not_mem_nil, or_false] at member
    rcases member with h | h <;> cases h
    all_goals exact ⟨⟨["next"], .structType⟩, by decide, rfl, by decide⟩
  · intro id data member
    simp only [sharedCycle, List.mem_cons, List.not_mem_nil, or_false] at member
    rcases member with h | h <;> cases h <;> decide
  · intro object allocated
    have cases : object = ⟨0⟩ ∨ object = ⟨1⟩ := by simpa [Allocated, sharedCycle] using allocated
    rcases cases with rfl | rfl
    · exact .variable (name := "root") (reference := .shared ⟨0⟩) (by decide)
    · exact .field (parent := ⟨0⟩) (name := "next") (reference := .shared ⟨1⟩)
        (.variable (name := "root") (reference := .shared ⟨0⟩) (by decide))
        (data := ⟨"Node", [("next", some (.shared ⟨1⟩))]⟩) (by decide) (by decide)
  · simp [Owners, sharedCycle, Compatible, Reference.shared]
  · intro object
    simp [References, Allocated, sharedCycle, Reference.shared, or_comm]

In the preceding cycle, change only object 0’s next reference to unique. The heap still satisfies structural well-formedness: that field is the sole owning occurrence of object 1. Access from variable root still traverses a shared reference first. Thus a unique stored edge may occur inside a cycle whose access from roots is shared; stored uniqueness alone is not unique access.

Shared/RootedChecks:mixed_cycle
example : WellFormed classes mixedCycle := by
  refine ⟨by decide, by decide, ?_, ?_, ?_, ?_, ?_⟩
  · intro id data member
    simp only [mixedCycle, List.mem_cons, List.not_mem_nil, or_false] at member
    rcases member with h | h <;> cases h
    all_goals exact ⟨⟨["next"], .structType⟩, by decide, rfl, by decide⟩
  · intro id data member
    simp only [mixedCycle, List.mem_cons, List.not_mem_nil, or_false] at member
    rcases member with h | h <;> cases h <;> decide
  · intro object allocated
    have cases : object = ⟨0⟩ ∨ object = ⟨1⟩ := by simpa [Allocated, mixedCycle] using allocated
    rcases cases with rfl | rfl
    · exact .variable (name := "root") (reference := .shared ⟨0⟩) (by decide)
    · exact .field (parent := ⟨0⟩) (name := "next") (reference := .owned ⟨1⟩)
        (.variable (name := "root") (reference := .shared ⟨0⟩) (by decide))
        (data := ⟨"Node", [("next", some (.owned ⟨1⟩))]⟩) (by decide) (by decide)
  · simp [Owners, mixedCycle, Compatible, Reference.shared, Reference.owned]
  · intro object
    simp [References, Allocated, mixedCycle, Reference.shared, Reference.owned, or_comm]

The distinction between stored uniqueness and unique access matters when moving an object. Use the mixed cycle shape with these concrete names: variable a shares object 0 of struct A; its field f uniquely owns object 1 of struct B; field g of object 1 shares object 0.

Starting at object 1, the path g.f leads back to object 1 with shared access. The low-level slot-removal operation used by give can clear object 0’s f slot. Afterwards, following g.f from object 1 reaches an empty slot. Thus removing an incoming reference does not, by itself, preserve all observations inside its target.

This is an abstract-heap check of the storage helper, not an execution of a.f→. A valid move also requires unique access along the entire source path.

Shared/RootedPathChecks:raw_take_changes_interior
example :
    Take cyclic (.field ⟨0⟩ "f") ⟨1⟩ removed ∧
    readPath cyclic (.owned ⟨1⟩) ["g", "f"] = some (some (.shared ⟨1⟩)) ∧
    readPath removed (.owned ⟨1⟩) ["g", "f"] = some none := by
  exact ⟨.field _ _ [] [(⟨1⟩, ⟨"B", [("g", some (.shared ⟨0⟩))]⟩)]
    ⟨0⟩ "A" [] [] "f" ⟨1⟩, by decide, by decide⟩

In the preceding heap, a.f→ has shared access. The checked transition uses give’s promotion case: it changes object 0’s f reference to shared and returns a shared reference to object 1. There is no unique resolution of a.f, so this access cannot select the move case.

Every finite field-path observation starting from the returned shared reference to object 1 is unchanged by the promotion. This includes the shared g.f backedge, empty slots, and failed lookups. The cycle remains present; no allocation ordering or global acyclicity is required for this result. As above, the example starts from an abstract heap rather than constructing the cycle with this layer’s source operations.

Shared/RootedPathChecks:give_preserves_shared_cycle
example :
    Give cyclic fieldPlace (.shared ⟨1⟩) promoted ∧
    (¬ ∃ source, Resolve cyclic fieldPlace source ⟨1⟩ .unique) ∧
    (∀ path, readPath promoted (.shared ⟨1⟩) path = readPath cyclic (.shared ⟨1⟩) path) := by
  have given : Give cyclic fieldPlace (.shared ⟨1⟩) promoted := .promote resolves_shared promotes
  have afterWf := given.preserves_pending cyclic_wellFormed.with_pending
  refine ⟨given, ?_, ?_⟩
  · rintro ⟨source, unique⟩
    have impossible := (resolve_deterministic cyclic_wellFormed.with_pending resolves_shared unique).2.2
    cases impossible
  · intro path
    exact promote_readPath_eq cyclic_wellFormed.with_pending afterWf promotes
      (route_of_resolve resolves_shared) (route_of_resolve resolves_shared) path

Remove variable root from the two-shared-edge cycle. Each object still has an incoming shared reference, but neither has a path from a variable. The resulting heap fails structural well-formedness. Incoming-reference coverage does not replace rootedness.

Shared/RootedChecks:unrooted_cycle
example : ¬ WellFormed classes { sharedCycle with variables := [] } := by
  intro wf
  have noLive : ∀ object, ¬ Live { sharedCycle with variables := [] } object := by
    intro object live
    induction live with
    | «variable» member => simp at member
    | field _ _ _ ih => exact ih
  exact noLive ⟨0⟩ (wf.rooted ⟨0⟩ (by simp [Allocated, sharedCycle]))

In a well-formed state, no object can be reached both by an entirely unique path and by a path containing a shared reference:

\[ \begin{aligned} &\mathsf{WF}_{\Delta}(S)\;\land\; (\href{#claim-shared.resolution}{S\vdash p\Downarrow q:\alpha@\mathsf{unique}})\\ &\quad\Longrightarrow\quad \neg\exists p',q'.\ \href{#claim-shared.resolution}{S\vdash p'\Downarrow q':\alpha@\mathsf{shared}}. \end{aligned} \]

The paths start at variables. A unique reference stored inside a shared container does not contradict this property: the path through that container already contains a shared reference.

Shared/KindSafety:WellFormedState.path_mode_exclusive
theorem WellFormedState.path_mode_exclusive (wf : WellFormedState classes state)
    (unique : Resolve state uniquePath uniquePlace object .unique)
    (shared : Resolve state sharedPath sharedPlace object .shared) : False :=
  wf.1.path_mode_exclusive unique shared

In a well-formed state, an object is live exactly when it is allocated:

\[ \mathsf{WF}_{\Delta}(S) \quad\Longrightarrow\quad \bigl(\href{#claim-shared.live}{\mathsf{Live}_S(\alpha)}\iff\href{#claim-shared.allocated}{\mathsf{Allocated}_S(\alpha)}\bigr). \]

Every allocated object therefore has an owning path from a variable. Sharing allows several such paths without making missing objects reachable.

Shared/KindSafety:WellFormedState.live_iff_allocated
theorem WellFormedState.live_iff_allocated (wf : WellFormedState classes state) :
    Live state object ↔ Allocated state object := wf.1.live_iff_allocated

Collection leaves structurally well-formed evaluation storage unchanged: every allocated object is already reachable. Ordinary statements preserve this property, so their following collection is inert. Popping the frame removes its roots; collection at that boundary empties the heap instead.

Shared/Frames:State.collect_eq_self
theorem State.collect_eq_self (wf : WellFormed classes state) : state.collect = state := by
  classical
  have keep : state.objects.filter (fun entry => decide (Live state entry.1)) = state.objects :=
    List.filter_eq_self.mpr (by
      intro entry member
      simpa using wf.allocated_live (List.mem_map.mpr ⟨entry, member, rfl⟩))
  simp [State.collect, keep]

For any program with a well-formed class table, every configuration reached by a finite execution from the empty initial state has a well-formed state. This includes intermediate configurations and the state after the final statement.

Consequently, every allocated object remains live. In each such state, a unique stored reference is the only incoming owner of its object; when an object has several incoming owners, all those references are shared. No object has both a unique path and a shared path from variables. This covers both explicit give-share and copying through a shared path, including the change to the path’s final stored reference.

Shared/FrameInvariants:base_soundness
theorem base_soundness (classesWf : ClassesWellFormed classes)
    (trace : StepsExactly (baseOperation classes) (.initial code) count after) :
    WellFormedState classes after.state := by
  have preserve : ∀ start n finish, WellFormedState classes start.state →
      StepsExactly (baseOperation classes) start n finish → WellFormedState classes finish.state := by
    intro start n finish wf execution
    induction execution with
    | refl => exact wf
    | step next _ rest => exact rest (base_kind_preservation classesWf wf next)
  exact preserve _ _ _ ⟨WellFormed.empty _, KindCorrect.empty _⟩ trace

The Given fragment inside Shared

The Shared language contains a translation of the Given fragment with single-variable bindings. This section restricts the correspondence to that fragment. Write \(E\) for this translation, applied to programs, configurations, and their components.

For a state, \(E\) replaces every reference \(\alpha\) with the unique reference \((\mathsf{unique},\alpha)\). Empty slots remain empty. Class names, field names, variable names, object identities, table order, and the next-identity counter are preserved.

For a program, \(E\) preserves its class declarations, places, constructors, gives, and statement order. Every Given declaration becomes a class, never a struct or shared struct. It introduces no give-share expression. For a configuration, it translates the heap and any live frame, preserving the counter and the distinction between a live frame and no frame. Thus a related pair describes the same point in the same computation, with explicit unique mode tags in the Shared state.

Correspondence/UniqueSharedFrames:embed
def embed (instruction : I → J) (configuration : Unique.Framed.Configuration I) : Shared.Framed.Configuration J :=
  ⟨(embedState configuration.state).objects, configuration.nextId,
    configuration.frame.map fun frame => ⟨embedSlots frame.variables, frame.code.map instruction⟩⟩
Correspondence/UniqueShared:embedId
def embedId (object : Unique.ObjectId) : Shared.ObjectId := ⟨object.index⟩
Correspondence/UniqueShared:embedReference
def embedReference (object : Unique.ObjectId) : Shared.Reference := .owned (embedId object)
Correspondence/UniqueShared:embedSlots
def embedSlots {Key : Type} (slots : List (Key × Unique.Slot)) : List (Key × Shared.Slot) :=
  slots.map (fun entry => (entry.1, entry.2.map embedReference))
Correspondence/UniqueShared:embedObject
def embedObject (object : Unique.Object) : Shared.Object :=
  ⟨object.className, embedSlots object.fields⟩
Correspondence/UniqueShared:embedState
def embedState (state : Unique.State) : Shared.State :=
  ⟨state.objects.map (fun entry => (embedId entry.1, embedObject entry.2)),
    embedSlots state.variables, state.nextId⟩
Correspondence/UniqueShared:embedPlace
def embedPlace : Unique.Place → Shared.Place
  | .variable name => .variable name
  | .field base name => .field (embedPlace base) name
Correspondence/UniqueShared:embedValue
def embedValue : Unique.Value → Shared.Value
  | .give source => .give (embedPlace source)
  | .new name arguments => .new name (arguments.map embedValue)
Correspondence/UniqueShared:embedStatement
def embedStatement (statement : Unique.Statement) : Shared.Statement :=
  ⟨statement.destination, embedValue statement.value⟩
Correspondence/UniqueShared:embedClasses
def embedClasses (classes : Unique.Classes) : Shared.Classes :=
  classes.map (fun entry => (entry.1, ⟨entry.2.fields, .classType⟩))
Correspondence/UniqueShared:embedProgram
def embedProgram (program : Unique.Program) : Shared.Program :=
  ⟨embedClasses program.classes, program.body.map embedStatement⟩
Correspondence/UniqueShared:embedConfiguration
def embedConfiguration (configuration : Unique.Configuration) : Shared.Configuration :=
  ⟨embedState configuration.state, configuration.code.map embedStatement⟩

For every class table \(\Delta\) and configuration \(c\) of this Given fragment, the embedding matches steps in both directions:

  • If \(\href{given.html#claim-given.steps}{\Delta\vdash c\longrightarrow c'}\), then \(\href{#claim-shared.steps}{E(\Delta)\vdash E(c)\longrightarrow E(c')}\).
  • If \(\href{#claim-shared.steps}{E(\Delta)\vdash E(c)\longrightarrow d}\), then there is a Given successor \(c'\) with \(\href{given.html#claim-given.steps}{\Delta\vdash c\longrightarrow c'}\) and \(d=E(c')\).

The second statement covers every Shared successor \(d\); it does not assume in advance that \(d\) is a translated state. These statements give a one-step bisimulation between Given and its embedded fragment: Shared adds no behavior to translated Given computations, and loses none of their steps.

Correspondence/UniqueSharedFrames:base_step_correspondence
theorem base_step_correspondence :
    Shared.Framed.Step (Shared.Framed.baseOperation (embedClasses classes))
      (embed embedStatement before) after ↔
    ∃ successor, Unique.Framed.Step (Unique.Framed.baseOperation classes) before successor ∧
      after = embed embedStatement successor := by
  constructor
  · apply step_backward embedStatement
    intro state code next rest step
    obtain ⟨successor, original, same⟩ := Dada.Correspondence.step_backward (before := ⟨state, code⟩) (after := ⟨next, rest⟩) step
    have states := congrArg Shared.Configuration.state same
    exact ⟨successor.state, successor.code, original, states, by simpa [Dada.Correspondence.embedConfiguration] using congrArg (fun c => c.code) same⟩
  · rintro ⟨successor, step, rfl⟩
    exact step_forward embedStatement (fun state code after rest step => Dada.Correspondence.step_forward
      (before := ⟨state, code⟩) (after := ⟨after, rest⟩) step) step

For every program in the Given fragment with single-variable bindings, translating its initial configuration gives exactly the initial configuration of its translated Shared program.

For every configuration in this fragment, the translated configuration is finished exactly when the original is finished. Using the program’s class table, the translated configuration is stuck exactly when the original is stuck. The correspondence therefore agrees on how execution starts, on successful completion, and on the absence of an available step before completion.

Correspondence/UniqueSharedFrames:base_boundary_correspondence
theorem base_boundary_correspondence (classes : Unique.Classes)
    (code : List Unique.Statement) (configuration : Unique.Framed.Configuration Unique.Statement) :
    embed embedStatement (.initial code) = .initial (code.map embedStatement) ∧
    ((embed embedStatement configuration).finished ↔ configuration.finished) ∧
    (Shared.Framed.Stuck (Shared.Framed.baseOperation (embedClasses classes)) (embed embedStatement configuration) ↔
      Unique.Framed.Stuck (Unique.Framed.baseOperation classes) configuration) :=
  ⟨initial_correspondence _ _, finished_correspondence _ _, base_stuck_correspondence⟩

Shared: typing and soundness

When a give copies

The type of a place tells us whether giving it moves or copies. Consider a box whose field has type Token:

struct Token {}
struct Box { item: Token }

let b = new Box(new Token());
let s = b→share;
let u = s.item→;
let v = s.item→;
StatementResult typeEffect on the source
Construct bBox—
Give-share bshared Boxb becomes empty.
Give s.item into ushared TokenThe field stays initialized.
Give s.item into vshared TokenThe field stays initialized.

The field is declared Token, but access through s makes its effective type shared Token. The first field give changes its stored reference to shared and returns a shared copy; the second copies it again. Neither changes s’s type.

This chapter adds two permissions, given and shared, to Given’s types and views. Token is shorthand for given Token. It also carries Given’s unpacking patterns into Shared, with unpacking restricted to unique results.

Shared/TypingExecutionChecks:copying_through_shared
example : SequenceTyped classes [] copyProgram copyFinal ∧
    Unpacking.StepsExactly classes.erase ⟨State.empty, copyProgram⟩ 4 ⟨boxCopiedTwice, []⟩ ∧
    Eval classes.erase boxShared (.give (field "s" "item"))
      ⟨boxCopied.objects, boxShared.variables, 2⟩ (.shared 0) ∧
    Eval classes.erase boxCopied (.give (field "s" "item")) boxCopied (.shared 0) ∧
    copyFinal.lookup "b" = some none ∧
    copyFinal.lookup "s" = some (some box.shared) ∧
    copyFinal.lookup "u" = some (some token.shared) ∧
    copyFinal.lookup "v" = some (some token.shared) ∧
    (1, ⟨"Box", [("item", some (.owned 0))]⟩) ∈ boxShared.objects ∧
    (1, ⟨"Box", [("item", some (.shared 0))]⟩) ∈ boxCopied.objects ∧
    ("s", some (.shared 1)) ∈ boxCopiedTwice.variables ∧
    ("u", some (.shared 0)) ∈ boxCopiedTwice.variables ∧
    ("v", some (.shared 0)) ∈ boxCopiedTwice.variables := by
  exact ⟨copy_typed, copy_execution, first_copy, second_copy, by decide, by decide, by decide, by decide,
    by decide, by decide, by decide, by decide, by decide⟩

Permissions and field declarations

A permission \(\pi\) describes unique or shared access. A nominal type \(N\) pairs a class name \(C\) with a signed view \(A\). A type \(T\) may apply a permission to another type:

\[ \begin{aligned} \pi &::= \mathsf{given}\mid\mathsf{shared},\\ N &::= C.A,\\ T &::= N\mid\pi\,T. \end{aligned} \]

Bare \(C\) still abbreviates \(C.\{\epsilon\}\). Positive view entries expose initialized subtrees; negative entries describe empty slots; omitted branches are unknown and inaccessible. Views do not assign ownership modes to objects.

Shared/TypingViews:Perm
inductive Perm where
  | given
  | shared
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr
Shared/TypingViews:Nominal
abbrev Nominal := Unique.Typing.ViewType
Shared/TypingViews:RawType
inductive RawType where
  | nominal (view : Nominal)
  | apply (permission : Perm) (inner : RawType)
  deriving DecidableEq, Repr
Shared/TypingViews:ValueType.whole
def ValueType.whole (name : ClassName) (permission : Perm := .given) : ValueType :=
  ⟨permission, .whole name⟩

Permission composition \(\pi\pi'\) combines an outer permission with an inner one. The result is given only when both are given:

Outer permissionInner givenInner shared
givengivenshared
sharedsharedshared
Shared/TypingViews:Perm.comp
def Perm.comp : Perm → Perm → Perm
  | .given, .given => .given
  | _, _ => .shared

Type normalization combines nested permissions and normalizes the nominal view. Its normalized form has exactly one outer permission:

\[ \pi\,C.A. \]

Combine permissions using composition and these equations:

\[ \mathsf{given}\ T=T, \qquad \pi(\pi'T)=(\href{#claim-shared.typing.composition}{\pi\pi'})T. \]

Normalize the nominal view using Given’s view normalization. For a class or ordinary struct, a bare nominal type supplies the outer permission given; we omit that permission when printing. For a shared struct, the nominal declaration supplies shared instead; applying given does not remove that intrinsic sharing. Thus shared shared Token normalizes to shared Token.

Shared/TypingViews:ValueType
structure ValueType where
  permission : Perm
  nominal : Nominal
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr
Shared/TypingViews:RawType.normalize
def RawType.normalize (classes : ClassTable) : RawType → ValueType
  | .nominal view =>
      ⟨initialPermission ((classes.lookup view.className).map TypedClass.kind |>.getD .classType),
        Unique.Typing.normalize classes.nominal view⟩
  | .apply permission inner =>
      let result := inner.normalize classes
      { result with permission := permission.comp result.permission }
Shared/TypingViews:normalize
def normalize (classes : ClassTable) (ty : ValueType) : ValueType :=
  { ty with nominal := Unique.Typing.normalize classes.nominal ty.nominal }
Shared/TypingViews:Normalized
def Normalized (classes : ClassTable) (ty : ValueType) : Prop :=
  Unique.Typing.Normalized classes.nominal ty.nominal
Shared/TypingViews:initialPermission
def initialPermission : Kind → Perm
  | .sharedStruct => .shared
  | _ => .given

The permission of a type \(\operatorname{perm}(T)\) is its outer permission in normalized form:

\[ \operatorname{perm}(\pi\,C.A)=\pi. \]

A bare class or ordinary struct type has permission given. A bare shared struct type has permission shared, as specified by normalization.

Shared/TypingViews:ValueType.perm
def ValueType.perm (ty : ValueType) : Perm := ty.permission

The base class \(\operatorname{base}(T)\) is the class named by a type, independent of its permission and view. For a normalized type:

\[ \operatorname{base}(\pi\,C.A)=C. \]
Shared/TypingViews:ValueType.base
def ValueType.base (ty : ValueType) : ClassName := ty.nominal.className

A typed nominal table \(\Sigma\) records each declaration kind and gives each field a permission and a nominal type. Constructor arguments must supply whole values of the declared types:

\[ \begin{aligned} F &::= \pi\,C,\\ k &::= \mathsf{class}\mid\mathsf{struct}\mid\mathsf{shared\ struct},\\ d &::= k\ C\ \{f_1:F_1,\ldots,f_n:F_n\},\\ \Sigma &\in \mathsf{ClassName}\rightharpoonup\mathsf{Kind}\times \mathsf{List}(\mathsf{FieldName}\times F). \end{aligned} \]

Here \(F\) also denotes the set of field types generated by its grammar. The declaration kind belongs to the set Kind generated by the grammar for k. Below, Σ(C) = [f₁:F₁, …, fₙ:Fₙ] abbreviates lookup of just the ordered fields; kindΣ(C) selects the declaration kind. Field permissions are normalized, including the intrinsic sharing of shared struct types. The table records normalized field types, so path permission composition uses those permissions.

Shared/TypingViews:FieldType
structure FieldType where
  permission : Perm
  className : ClassName
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr
Shared/TypingViews:FieldType.toType
def FieldType.toType (field : FieldType) : ValueType :=
  .whole field.className field.permission
Shared/TypingViews:TypedClass
structure TypedClass where
  fields : List (FieldName × FieldType)
  kind : Kind := .structType
  deriving DecidableEq, BEq, ReflBEq, LawfulBEq, Repr
Shared/TypingViews:ClassTable
abbrev ClassTable := List (ClassName × TypedClass)

A typed class table \(\Sigma\) is well formed when class names are distinct, field names within each class are distinct, and every class named by a field type is declared in \(\Sigma\).

For every struct or shared struct declaration, each field type F must satisfy struct(F). A class declaration has no such restriction. A field with shared permission must have a struct type even when its container is a class. These checks inspect nominal declarations, not field accessibility in a view.

Shared/TypingViews:ClassTable.WellFormed
def ClassTable.WellFormed (classes : ClassTable) : Prop :=
  (classes.map Prod.fst).Nodup ∧
    ∀ entry ∈ classes, (entry.2.fields.map Prod.fst).Nodup ∧
      ∀ field ∈ entry.2.fields, field.2.className ∈ classes.map Prod.fst ∧
        KindValid classes field.2.toType ∧
        (entry.2.kind.isStruct = true → StructType classes field.2.toType)

Class-table erasure \(\lfloor\Sigma\rfloor\) supplies the operational class table by removing field types. It retains every nominal name, declaration kind, and field order:

\[ \lfloor\Sigma\rfloor(C)=(\operatorname{kind}_{\Sigma}(C),[f_1,\ldots,f_n]) \quad\text{where }\href{#claim-shared.typing.declarations}{\Sigma(C)}=[f_1:F_1,\ldots,f_n:F_n]. \]
Shared/TypingViews:ClassTable.erase
def ClassTable.erase (classes : ClassTable) : Classes :=
  classes.map fun (name, declaration) => (name, ⟨declaration.fields.map Prod.fst, declaration.kind⟩)

The nominal class table \(\Sigma_{\mathrm{nom}}\) supplies Given’s typed class table by removing declaration kinds and each field’s permission, retaining the nominal names and field order:

\[ \Sigma_{\mathrm{nom}}(C)=[f_1:C_1,\ldots,f_n:C_n] \quad\text{where }\href{#claim-shared.typing.declarations}{\Sigma(C)}=[f_1:\pi_1 C_1,\ldots,f_n:\pi_n C_n]. \]

Use this table for Given’s relative paths and views, view normalization, nominal focusing, and emptying.

Shared/TypingViews:ClassTable.nominal
def ClassTable.nominal (classes : ClassTable) : Unique.Typing.ClassTable :=
  classes.map fun (name, declaration) =>
    (name, ⟨declaration.fields.map fun (field, ty) => (field, ty.className)⟩)

A type is well formed when its base class is declared and its view satisfies Given’s view conditions under the nominal class table: paths are valid, distinct, and pairwise prefix-incomparable. In addition, a shared permission requires struct(T). A shared struct has shared permission after normalization; there is no normalized given type for its instances.

Shared/TypingViews:ValueType.WellFormed
def ValueType.WellFormed (ty : ValueType) (classes : ClassTable) : Prop :=
  ty.nominal.WellFormed classes.nominal ∧ KindValid classes ty
Shared/TypingViews:KindValid
def KindValid (classes : ClassTable) (ty : ValueType) : Prop :=
  (classes.lookup ty.base).any (fun declaration => kindAllows declaration.kind ty.permission) = true
Shared/TypingViews:kindAllows
def kindAllows (kind : Kind) (permission : Perm) : Bool :=
  match kind with
  | .classType => permission == .given
  | .structType => true
  | .sharedStruct => permission == .shared

The known-initialized paths \(\operatorname{pos}_{\Sigma}(T)\) and known-empty paths \(\operatorname{neg}_{\Sigma}(T)\) depend on a type’s nominal view, not its permission. For normalized \(T=\pi N\), use Given’s observations under the nominal class table:

\[ \operatorname{pos}_{\Sigma}(\pi N)=\href{given-typing.html#claim-given.typing.observations}{\operatorname{pos}}_{\href{#claim-shared.typing.nominal_table}{\Sigma_{\mathrm{nom}}}}(N), \qquad \operatorname{neg}_{\Sigma}(\pi N)=\href{given-typing.html#claim-given.typing.observations}{\operatorname{neg}}_{\href{#claim-shared.typing.nominal_table}{\Sigma_{\mathrm{nom}}}}(N). \]

A positive entry exposes a whole declared subtree, including shared fields. A negative entry describes an empty slot; an omitted branch remains unknown and inaccessible.

Shared/TypingViews:Pos
def Pos (classes : ClassTable) (ty : ValueType) (path : Path) : Prop :=
  Unique.Typing.Pos classes.nominal ty.nominal path
Shared/TypingViews:Neg
def Neg (ty : ValueType) (path : Path) : Prop :=
  Unique.Typing.Neg ty.nominal path

Following a path

A shared link may occur anywhere along a path:

struct Token {}
struct Box { item: Token }
class Outer { box: shared Box }
struct Holder { item: shared Token }

Consider initialized variables b: Box, s: shared Box, o: Outer, and h: Holder:

PlaceEffective typeGiving it
b.itemTokenMoves the token.
s.itemshared TokenCopies a shared reference.
o.box.itemshared TokenCopies a shared reference.
h.itemshared TokenCopies a shared reference.

In the third row, o is unique but its box field is shared. In the fourth, the final field itself is declared shared. A unique container can therefore contain a field that is copied when given.

Shared/TypingChecks:permission_paths
example :
    focus classes box ["item"] = some token ∧
    focus classes box.shared ["item"] = some token.shared ∧
    focus classes (.whole "Outer") ["box", "item"] = some token.shared ∧
    focus classes holder ["item"] = some token.shared ∧
    give classes [("b", some box)] (field "b" "item") =
      some (token, [("b", some ⟨.given, ⟨"Box", [.negative ["item"]]⟩⟩)]) ∧
    give classes [("s", some box.shared)] (field "s" "item") =
      some (token.shared, [("s", some box.shared)]) ∧
    give classes [("o", some (.whole "Outer"))] (place :=
      .field (field "o" "box") "item") =
      some (token.shared, [("o", some (.whole "Outer"))]) ∧
    give classes [("h", some holder)] (field "h" "item") =
      some (token.shared, [("h", some holder)]) := by
  exact ⟨by decide, by decide, by decide, by decide,
    by decide, by decide, by decide, by decide⟩

The declared permission \(\operatorname{decl}_{\Sigma}(C,\rho)\) combines the field permissions along a relative path \(\rho\) from class \(C\), using permission composition:

\[ \begin{aligned} \operatorname{decl}_{\Sigma}(C,\epsilon)&=\mathsf{given},\\ \operatorname{decl}_{\Sigma}(C,f\rho)&= \pi_f\operatorname{decl}_{\Sigma}(D,\rho) &&\text{where }(f:\pi_f D)\in\href{#claim-shared.typing.declarations}{\Sigma(C)}. \end{aligned} \]

It is defined exactly on paths valid from \(C\) under the nominal class table.

Shared/TypingViews:declaredPermission
def declaredPermission (classes : ClassTable) (name : ClassName) : Path → Option Perm
  | [] => some .given
  | field :: rest => do
      let declaration ← classes.lookup name
      let target ← declaration.fields.lookup field
      let permission ← declaredPermission classes target.className rest
      return target.permission.comp permission

Focusing \(T\downarrow\rho\) finds the type reached by a path, carrying the enclosing permission into each field. Access to a field declared \(F\) through a whole value of type \(\pi\,C\) has type \(\pi F\).

Using permission composition, extend Given’s focusing operation (\(\href{given-typing.html#claim-given.typing.focus}{N\downarrow\rho}\)) to a type \(T=\pi N\), where the nominal type is \(N=C.A\):

\[ T\downarrow\rho =\bigl(\pi\href{#claim-shared.typing.declared_permission}{\operatorname{decl}_{\Sigma}(C,\rho)}\bigr) (\href{given-typing.html#claim-given.typing.focus}{N\downarrow\rho}), \qquad \rho\in\href{#claim-shared.typing.observations}{\operatorname{pos}_{\Sigma}(T)}. \]

The nominal focus uses the nominal class table and preserves the field’s current view, including holes. The new operation \(T\downarrow\rho\) adds the effective permission and normalizes the result. It does not restore moved or hidden fields.

Shared/TypingViews:focus
def focus (classes : ClassTable) (ty : ValueType) (path : Path) : Option ValueType := do
  let nominal ← Unique.Typing.focus classes.nominal ty.nominal path
  let permission ← declaredPermission classes ty.base path
  return ⟨ty.permission.comp permission, nominal⟩

Emptying \(T[-\rho]\) marks a field path as empty while retaining the outer permission and every other branch’s information. For normalized \(T=\pi N\):

\[ (\pi N)[-\rho]=\pi\,(\href{given-typing.html#claim-given.typing.emptying}{N[-\rho]}), \qquad \rho\ne\epsilon,\quad \rho\in\href{#claim-shared.typing.observations}{\operatorname{pos}_{\Sigma}(T)}. \]

The right-hand side uses Given’s emptying operation under the nominal class table. Normalize the result.

Shared/TypingViews:emptyPath
def emptyPath (classes : ClassTable) (ty : ValueType) (path : Path) : Option ValueType :=
  (Unique.Typing.emptyPath classes.nominal ty.nominal path).map fun remaining =>
    ⟨ty.permission, remaining⟩

The static give operation

A slot description \(B\) is either \(0\), for an empty variable, or a type. A typing environment \(\Gamma\) describes every variable slot:

\[ B::=0\mid T, \qquad \Gamma\in\mathsf{VariableId}\rightharpoonup B. \]

Types must be well formed and normalized. Empty variables remain in the domain and cannot be reused as fresh names.

Shared/Typing:SlotDescription
abbrev SlotDescription := Option ValueType
Shared/Typing:Environment
abbrev Environment := List (VariableId × SlotDescription)
Shared/Typing:Environment.WellFormed
def Environment.WellFormed (environment : Environment) (classes : ClassTable) : Prop :=
  (environment.map Prod.fst).Nodup ∧
    environment.all (fun entry => match entry.2 with
      | none => true
      | some ty => decide (Admissible classes ty)) = true
Shared/Typing:Environment.lookup
def Environment.lookup (environment : Environment) (name : VariableId) :
    Option SlotDescription :=
  (environment.find? fun entry => entry.1 == name).map Prod.snd
Shared/Typing:Environment.replace
def Environment.replace (environment : Environment) (name : VariableId)
    (description : SlotDescription) : Environment :=
  environment.map fun entry => if entry.1 = name then (name, description) else entry

The static give operation computes the type produced by giving a place and the environment afterwards. Write \(\mathsf{give}_{\Sigma}(\Gamma,p)=(T,\Gamma')\): the result has type \(T\), and the variable slots have descriptions \(\Gamma'\).

Write a place as \(p=x.\rho\): for o.box.item, the root variable is o and the relative path is box.item; for o, the relative path is \(\epsilon\). The operation is defined exactly when \(\Gamma(x)=U\) and \(\rho\in\href{#claim-shared.typing.observations}{\operatorname{pos}_{\Sigma}(U)}\). Its outputs are:

\[ T=\href{#claim-shared.typing.focus}{U\downarrow\rho}, \qquad \Gamma'=\begin{cases} \Gamma & \href{#claim-shared.typing.perm}{\operatorname{perm}(T)}=\mathsf{shared},\\ \Gamma[x\mapsto0] & \href{#claim-shared.typing.perm}{\operatorname{perm}(T)}=\mathsf{given},\ \rho=\epsilon,\\ \Gamma[x\mapsto \href{#claim-shared.typing.emptying}{U[-\rho]}] & \href{#claim-shared.typing.perm}{\operatorname{perm}(T)}=\mathsf{given},\ \rho\ne\epsilon. \end{cases} \]

The last case empties the field path. A given result requires every permission along its route to be given. A shared result leaves the entire environment unchanged. An absent variable, an empty source, or an inaccessible field makes this static give operation undefined. A field hidden by a view may still hold a value at runtime.

Shared/Typing:splitPlace
def splitPlace : Place → VariableId × Path
  | .variable name => (name, [])
  | .field base name =>
      let (root, path) := splitPlace base
      (root, path ++ [name])
Shared/Typing:give
def give (classes : ClassTable) (environment : Environment) (place : Place) :
    Option (ValueType × Environment) := do
  let (root, path) := splitPlace place
  let source ← environment.lookup root
  let source ← source
  let result ← focus classes source path
  if result.permission = .shared then
    return (result, environment)
  else if path = [] then
    return (result, environment.replace root none)
  else
    let remaining ← emptyPath classes source path
    return (result, environment.replace root (some remaining))

Weakening a view

As in Given, view weakening can hide initialization facts while preserving the permission. For normalized types \(T=\pi C.A\) and \(U=\pi'C'.A'\), define:

\[ T\preceq_{\Sigma}U \iff \begin{gathered} \pi=\pi'\ \land\ C=C'\\ {}\land\ \href{#claim-shared.typing.observations}{\operatorname{pos}_{\Sigma}(U)}\subseteq\href{#claim-shared.typing.observations}{\operatorname{pos}_{\Sigma}(T)}\\ {}\land\ \href{#claim-shared.typing.observations}{\operatorname{neg}_{\Sigma}(U)}\subseteq\href{#claim-shared.typing.observations}{\operatorname{neg}_{\Sigma}(T)}. \end{gathered} \]

For example, shared Box can be weakened to shared Box.{}. There is no weakening from Box to shared Box: creating a shared reference requires the runtime give-share operation. Different aliases may expose different views of the same object.

Shared/TypingViews:Subtype
def Subtype (classes : ClassTable) (source target : ValueType) : Prop :=
  source.permission = target.permission ∧
    Unique.Typing.Subtype classes.nominal source.nominal target.nominal

Typing expressions

Expression typing \(\Sigma;\Gamma\vdash e:T\;\triangleright\;\Gamma'\) records the result’s type and the variable descriptions after evaluation. All type expressions in the rules use type normalization. Both Give and Give-share use the static give operation \(\href{#claim-shared.typing.giving}{\mathsf{give}_{\Sigma}(\Gamma,p)=(T,\Gamma')}\) defined above. Give returns its result type. Give-share additionally requires struct(T) and applies shared to that type:

\[ \frac{\href{#claim-shared.typing.giving}{\mathsf{give}_{\Sigma}(\Gamma,p)=(T,\Gamma')}} {\Sigma;\Gamma\vdash p\mathord{\to}:T\;\triangleright\;\Gamma'} \quad\text{Give} \]
\[ \frac{\href{#claim-shared.typing.giving}{\mathsf{give}_{\Sigma}(\Gamma,p)=(T,\Gamma')}\qquad\href{shared.html#claim-shared.struct}{\mathsf{struct}}(T)} {\Sigma;\Gamma\vdash p\mathord{\to}\mathsf{share}:\mathsf{shared}\ T \;\triangleright\;\Gamma'} \quad\text{Give-share} \]

Both rules make the same change to the source. Give-share preserves the result’s view: it changes permission, not initialization.

Construct checks arguments from left to right against the declared field types. Define initΣ(C) to be shared for a shared struct declaration and given for a class or ordinary struct. This permission describes the constructor result; the arguments retain their own permissions:

\[ \frac{ \begin{gathered} \href{#claim-shared.typing.declarations}{\Sigma(C)}=[f_1:F_1,\ldots,f_n:F_n]\\ \Sigma;\Gamma_{i-1}\vdash e_i:F_i\;\triangleright\;\Gamma_i \quad(1\le i\le n) \end{gathered} }{ \Sigma;\Gamma_0\vdash\mathsf{new}\ C(e_1,\ldots,e_n):\operatorname{init}_{\Sigma}(C)\,C \;\triangleright\;\Gamma_n } \quad\text{Construct} \]

The argument count must match the declaration. With no arguments, the environment is unchanged. Arguments still require their whole declared types. A result may expose a weaker view:

\[ \frac{\Sigma;\Gamma\vdash e:T\;\triangleright\;\Gamma' \qquad\href{#claim-shared.typing.weakening}{T\preceq_{\Sigma}U}} {\Sigma;\Gamma\vdash e:U\;\triangleright\;\Gamma'} \quad\text{Weaken} \]
Shared/Typing:ExprTyped
inductive ExprTyped (classes : ClassTable) : Environment → Value → ValueType → Environment → Prop where
  | give {before after : Environment} {place : Place} {ty : ValueType} :
      before.WellFormed classes →
      Typing.give classes before place = some (ty, after) →
      Admissible classes ty → after.WellFormed classes →
      ExprTyped classes before (.give place) ty after
  | giveShare {before after : Environment} {place : Place} {ty : ValueType} :
      before.WellFormed classes →
      Typing.give classes before place = some (ty, after) →
      Admissible classes ty → after.WellFormed classes →
      StructType classes ty →
      ExprTyped classes before (.giveShare place) ty.shared after
  | new {before after : Environment} {name : ClassName} {declaration : TypedClass}
      {arguments : List Value} :
      (name, declaration) ∈ classes →
      ArgsTyped classes before arguments (declaration.fields.map Prod.snd) after →
      Admissible classes (ValueType.whole name (initialPermission declaration.kind)) →
      (declaration.kind.isStruct = true →
        ∀ field ∈ declaration.fields, StructType classes field.2.toType) →
      ExprTyped classes before (.new name arguments)
        (ValueType.whole name (initialPermission declaration.kind)) after
  | weaken {before after : Environment} {value : Value} {ty other : ValueType} :
      ExprTyped classes before value ty after →
      Admissible classes other → Subtype classes ty other →
      ExprTyped classes before value other after
Shared/Typing:ArgsTyped
inductive ArgsTyped (classes : ClassTable) : Environment → List Value → List FieldType → Environment → Prop where
  | nil {environment : Environment} :
      environment.WellFormed classes → ArgsTyped classes environment [] [] environment
  | cons {before middle after : Environment} {value : Value} {values : List Value}
      {field : FieldType} {fields : List FieldType} :
      ExprTyped classes before value field.toType middle →
      ArgsTyped classes middle values fields after →
      ArgsTyped classes before (value :: values) (field :: fields) after
Shared/TypingViews:StructType
def StructType (classes : ClassTable) (ty : ValueType) : Prop :=
  (classes.lookup ty.base).any (fun declaration => declaration.kind.isStruct) = true
Shared/TypingViews:initialPermission
def initialPermission : Kind → Perm
  | .sharedStruct => .shared
  | _ => .given

With Token, Box, and Holder declared above:

let t = new Token();
let h = new Holder(t→share);
let a = h.item→;
let b = h.item→;

The constructor rule requires a shared Token, so its argument explicitly shares the token. Afterwards t is empty, h: Holder, and both a and b have type shared Token. Giving h.item does not empty it.

Replacing the constructor argument with t→ is rejected: its type is Token, not the declared shared Token. Conversely, new Box(a→) is rejected because the shared result cannot supply the given Token required by Box.

Shared/TypingExecutionChecks:constructor_permissions
example : SequenceTyped classes [] argumentProgram argumentFinal ∧
    Unpacking.Steps classes.erase ⟨State.empty, argumentProgram⟩ ⟨Unpacking.argumentsFinished, []⟩ ∧
    argumentFinal.lookup "t" = some none ∧
    argumentFinal.lookup "h" = some (some holder) ∧
    argumentFinal.lookup "a" = some (some token.shared) ∧
    argumentFinal.lookup "b" = some (some token.shared) ∧
    (∀ ty after, ¬ ExprTyped classes [("t", some token)]
      (.new "Holder" [.give (.variable "t")]) ty after) ∧
    (∀ ty after, ¬ ExprTyped classes argumentFinal
      (.new "Box" [.give (.variable "a")]) ty after) := by
  exact ⟨arguments_typed, Unpacking.arguments_execution, by decide, by decide, by decide, by decide,
    fun _ _ => holder_requires_sharing, fun _ _ => box_rejects_shared⟩

Sharing also preserves a partially moved value:

struct Token {}
struct Pair { left: Token, right: Token }

let p = new Pair(new Token(), new Token());
let t = p.left→;
let s = p→share;
let a = s.right→;
let b = s.right→;

Moving left leaves p: Pair.{-left, right}. Give-share then empties p and produces s: shared Pair.{-left, right}. The last two statements produce shared tokens and preserve that view of s.

Giving s.left→ is rejected because left is empty. Weakening s’s view could hide that fact, but could not make the field accessible again.

Shared/TypingExecutionChecks:sharing_partial_views
example : SequenceTyped classes [] partialProgram partialFinal ∧
    Unpacking.StepsExactly classes.erase ⟨State.empty, partialProgram⟩ 5 ⟨pairCopiedTwice, []⟩ ∧
    partialFinal.lookup "s" = some (some partialPair.shared) ∧
    partialFinal.lookup "a" = some (some token.shared) ∧
    partialFinal.lookup "b" = some (some token.shared) ∧
    (2, ⟨"Pair", [("left", none), ("right", some (.shared 1))]⟩) ∈ pairCopiedTwice.objects ∧
    ("p", none) ∈ pairCopiedTwice.variables ∧
    ("a", some (.shared 1)) ∈ pairCopiedTwice.variables ∧
    ("b", some (.shared 1)) ∈ pairCopiedTwice.variables ∧
    (∀ ty after, ¬ ExprTyped classes partialFinal (.give (field "s" "left")) ty after) := by
  exact ⟨partial_typed, partial_execution, by decide, by decide, by decide,
    by decide, by decide, by decide, by decide,
    fun _ _ => failed_give_not_typed (by decide)⟩

Binding results

An unpacking pattern consumes a uniquely owned container and transfers its field slots to fresh variables. This extends Shared’s statements with Given’s flat binding patterns \(b\):

\[ \begin{aligned} b&::=x\mid C\mathord{\to}\{f_1:x_1,\ldots,f_n:x_n\},\\ t&::=\mathsf{let}\ b=e. \end{aligned} \]

Each declared field must appear exactly once; destination variables are distinct and fresh in the variable table after expression evaluation. Field order in the pattern is immaterial. f abbreviates f: f; there are no _ or .. patterns here.

Shared/Unpacking:Pattern
inductive Pattern where
  | variable (name : VariableId)
  | unpack (className : ClassName) (fields : List (FieldName × VariableId))
  deriving DecidableEq, Repr
Shared/Unpacking:Statement
structure Statement where
  pattern : Pattern
  value : Value
  deriving Repr

The program configuration keeps its heap and optional initial frame. Its frame now contains pattern-binding statements. A local-frame observation \(\langle S,P\rangle\) pairs the frame’s storage with its remaining statements for local evaluation. It is not a complete program lifetime.

Shared/Frames:Frame
structure Frame (Instruction : Type) where
  variables : List (VariableId × Slot)
  code : List Instruction
  deriving Repr
Shared/Frames:Configuration
structure Configuration (Instruction : Type) where
  objects : List (ObjectId × Object)
  nextId : Nat
  frame : Option (Frame Instruction)
  deriving Repr
Shared/Unpacking:Configuration
structure Configuration where
  state : State
  code : List Statement
  deriving Repr

A local-frame observation pairs storage with the remaining statement sequence. An extended local operation runs one let statement with a binding pattern.

Write \(\href{shared.html#claim-shared.evaluation}{\Delta\vdash\langle S,e\rangle\Downarrow\langle S',r\rangle}\) for Shared’s expression evaluation. It is unchanged. The extended step first evaluates the expression, then binds its result:

  • A variable pattern stores the reference, of either mode, in its fresh slot.
  • A C → { ... } pattern requires \(r=(\mathsf{unique},\alpha)\) and an allocated C object at \(\alpha\). Transfer every field slot to its named destination and remove \(\alpha\) from the object table.

Field references retain their modes and targets; empty fields become empty variables. All other storage and the allocation counter remain as in \(S'\). The statement is removed from the remaining sequence. A shared result has no unpacking transition: consuming its container would invalidate other owners. The program machine applies patternOperation and collects after this local operation; its frame-exit rule is unchanged.

Shared/Unpacking:Configuration
structure Configuration where
  state : State
  code : List Statement
  deriving Repr
Shared/Unpacking:Transfer
inductive Transfer : List (FieldName × VariableId) → List (FieldName × Slot) → List (VariableId × Slot) → Prop where
  | nil : Transfer [] [] []
  | cons {field name slot pattern before after bindings} :
      Transfer pattern (before ++ after) bindings →
      Transfer ((field, name) :: pattern) (before ++ (field, slot) :: after)
        ((name, slot) :: bindings)
Shared/Unpacking:Bind
inductive Bind (classes : Classes) : State → Reference → Pattern → State → Prop where
  | variable {state object name} :
      name ∉ state.variables.map Prod.fst →
      Bind classes state object (.variable name) (state.bind name object)
  | unpack {before after variables nextId object className fields pattern bindings declaration} :
      (className, declaration) ∈ classes →
      fields.map Prod.fst = declaration.fields →
      (pattern.map Prod.fst).Nodup →
      (pattern.map Prod.snd).Nodup →
      (∀ name ∈ pattern.map Prod.snd, name ∉ variables.map Prod.fst) →
      Transfer pattern fields bindings →
      Bind classes ⟨before ++ (object, ⟨className, fields⟩) :: after, variables, nextId⟩
        (.owned object) (.unpack className pattern)
        ⟨before ++ after, bindings ++ variables, nextId⟩
Shared/Unpacking:Step
inductive Step (classes : Classes) : Configuration → Configuration → Prop where
  | letValue {before evaluated after pattern value object rest} :
      Eval classes before value evaluated object →
      Bind classes evaluated object pattern after →
      Step classes ⟨before, ⟨pattern, value⟩ :: rest⟩ ⟨after, rest⟩

A finite execution \(\Delta\vdash K\longrightarrow_u^{*}K'\) consists of zero or more program steps, including collection and frame exit, all using the same class table \(\Delta\).

Shared/Frames:Steps
def Steps (operation : LocalStep Instruction) (before after : Configuration Instruction) : Prop :=
  ∃ count, StepsExactly operation before count after
Shared/Frames:StepsExactly
inductive StepsExactly (operation : LocalStep Instruction) : Configuration Instruction → Nat → Configuration Instruction → Prop where
  | refl (configuration) : StepsExactly operation configuration 0 configuration
  | step {before middle after count} :
      Step operation before middle → StepsExactly operation middle count after →
      StepsExactly operation before (count + 1) after

A configuration is finished exactly when its initial frame has been popped, as in Shared completion. Exhausted statements alone do not finish the program.

Shared/Frames:Configuration.finished
def Configuration.finished (configuration : Configuration Instruction) : Prop :=
  configuration.frame = none

A configuration is stuck if it is not finished and has no successor. An exhausted live frame can still take its exit step, so it is neither finished nor stuck.

Shared/Frames:Stuck
def Stuck (operation : LocalStep Instruction) (configuration : Configuration Instruction) : Prop :=
  ¬ configuration.finished ∧ ¬ ∃ after, Step operation configuration after

The field description \(\mathsf{field}_{\Sigma}(T,f)\) tells an unpacking pattern whether a direct field is empty or which type it transfers:

\[ \mathsf{field}_{\Sigma}(T,f)=\begin{cases} 0&f\in\href{#claim-shared.typing.observations}{\operatorname{neg}_{\Sigma}(T)},\\ \href{#claim-shared.typing.focus}{T\downarrow f}&f\in\href{#claim-shared.typing.observations}{\operatorname{pos}_{\Sigma}(T)}. \end{cases} \]

An unknown field has no description.

Shared/Typing:fieldDescription
def fieldDescription (classes : ClassTable) (ty : ValueType) (name : FieldName) :
    Option SlotDescription :=
  if Unique.Typing.negative ty.nominal [name] then some none
  else (focus classes ty [name]).map some

Binding typing \(\Sigma;\Gamma\vdash b:T\Rightarrow\Gamma'\) describes where a result goes in the environment. A fresh variable receives its type unchanged:

\[ \frac{x\notin\operatorname{dom}(\Gamma)} {\Sigma;\Gamma\vdash x:T\Rightarrow\Gamma[x\mapsto T]} \quad\text{Bind} \]

For unpacking, the container must be given and every direct field’s status must be known. Unpacking transfers its field descriptions:

\[ \frac{ \begin{gathered} \href{#claim-shared.typing.perm}{\operatorname{perm}(T)}=\mathsf{given} \qquad\href{#claim-shared.typing.base}{\operatorname{base}(T)}=C \qquad\href{#claim-shared.typing.declarations}{\Sigma(C)}=[f_1:F_1,\ldots,f_n:F_n]\\ \href{#claim-shared.typing.field}{\mathsf{field}_{\Sigma}(T,f_i)}=B_i\quad(1\le i\le n)\\ x_1,\ldots,x_n\text{ distinct and absent from }\operatorname{dom}(\Gamma) \end{gathered} }{ \Sigma;\Gamma\vdash C\mathord{\to}\{f_1:x_1,\ldots,f_n:x_n\}:T \Rightarrow\Gamma[x_1\mapsto B_1,\ldots,x_n\mapsto B_n] } \quad\text{Unpack} \]

The displayed fields are ordered as declared. A transferred field can be shared even though the container must be given. As in Given’s binding rules, a field’s interior may have a partial view; only its direct slot status must be known.

Shared/Typing:FieldBindings
inductive FieldBindings (classes : ClassTable) (ty : ValueType) : List (FieldName × VariableId) → Environment → Prop where
  | nil : FieldBindings classes ty [] []
  | cons {field : FieldName} {destination : VariableId} {description : SlotDescription}
      {fields : List (FieldName × VariableId)} {bindings : Environment} :
      fieldDescription classes ty field = some description →
      FieldBindings classes ty fields bindings →
      FieldBindings classes ty ((field, destination) :: fields)
        ((destination, description) :: bindings)
Shared/Typing:BindingTyped
inductive BindingTyped (classes : ClassTable) : Environment → Unpacking.Pattern → ValueType → Environment → Prop where
  | variable {environment : Environment} {name : VariableId} {ty : ValueType} :
      environment.WellFormed classes → Admissible classes ty →
      name ∉ environment.map Prod.fst →
      BindingTyped classes environment (.variable name) ty ((name, some ty) :: environment)
  | unpack {before : Environment} {ty : ValueType} {name : ClassName}
      {declaration : TypedClass} {fields : List (FieldName × VariableId)}
      {bindings : Environment} :
      before.WellFormed classes → Admissible classes ty →
      ty.permission = .given → ty.nominal.className = name → (name, declaration) ∈ classes →
      (fields.map Prod.fst).Perm (declaration.fields.map Prod.fst) →
      (fields.map Prod.snd).Nodup →
      (∀ destination ∈ fields.map Prod.snd, destination ∉ before.map Prod.fst) →
      FieldBindings classes ty fields bindings →
      (bindings ++ before).WellFormed classes →
      BindingTyped classes before (.unpack name fields) ty (bindings ++ before)

Continuing the Holder example:

let Holder → { item } = h→;
let c = item→;

The unpacking rule empties h, consumes the holder, and binds item: shared Token. The aliases a and b still own the token. The second copies it again, leaving item initialized.

If s: shared Holder, the pattern let Holder → { item } = s→ is rejected. The result is shared even if this happens to be the only reference to that holder. A type grants the access its permission describes; it does not count aliases to recover unique ownership.

Shared/TypingExecutionChecks:unpacking_shared_fields
example : SequenceTyped classes argumentFinal
    [⟨.unpack "Holder" [("item", "item")], .give (.variable "h")⟩,
     ⟨.variable "c", .give (.variable "item")⟩] unpackFinal ∧
    Unpacking.StepsExactly classes.erase
      ⟨State.empty, Unpacking.unpackingProgram⟩ 6 ⟨Unpacking.unpackingFinished, []⟩ ∧
    unpackFinal.lookup "h" = some none ∧
    unpackFinal.lookup "item" = some (some token.shared) ∧
    unpackFinal.lookup "a" = some (some token.shared) ∧
    unpackFinal.lookup "b" = some (some token.shared) ∧
    unpackFinal.lookup "c" = some (some token.shared) ∧
    ¬ Allocated Unpacking.unpackingFinished 1 ∧
    (∀ after, ¬ BindingTyped classes [("s", some holder.shared)]
      (.unpack "Holder" [("item", "item")]) holder.shared after) := by
  refine ⟨unpack_typed, Unpacking.unpacking_execution, by decide, by decide,
    by decide, by decide, by decide, ?_, ?_⟩
  · change (1 : ObjectId) ∉ [0]; decide
  · intro after typed
    cases typed with
    | unpack _ _ given => cases given

Statement typing \(\Sigma;\Gamma\vdash t\Rightarrow\Gamma'\) threads the environment through expression typing and binding typing:

\[ \frac{\href{#claim-shared.typing.expressions}{\Sigma;\Gamma\vdash e:T\;\triangleright\;\Gamma_1} \qquad\href{#claim-shared.typing.bindings}{\Sigma;\Gamma_1\vdash b:T\Rightarrow\Gamma_2}} {\Sigma;\Gamma\vdash\mathsf{let}\ b=e\Rightarrow\Gamma_2} \quad\text{Let} \]
Shared/Typing:StatementTyped
inductive StatementTyped (classes : ClassTable) : Environment → Unpacking.Statement → Environment → Prop where
  | letValue {before middle after : Environment} {pattern : Unpacking.Pattern}
      {value : Value} {ty : ValueType} :
      ExprTyped classes before value ty middle →
      BindingTyped classes middle pattern ty after →
      StatementTyped classes before ⟨pattern, value⟩ after

Statement-sequence typing \(\Sigma;\Gamma\vdash P\Rightarrow\Gamma_f\) passes each statement’s resulting environment to the next. Here \(P\) is an ordered sequence of statements:

\[ \frac{}{\Sigma;\Gamma\vdash[]\Rightarrow\Gamma} \qquad \frac{\href{#claim-shared.typing.statements}{\Sigma;\Gamma\vdash t\Rightarrow\Gamma_1} \qquad\Sigma;\Gamma_1\vdash P\Rightarrow\Gamma_f} {\Sigma;\Gamma\vdash t::P\Rightarrow\Gamma_f}. \]
Shared/Typing:SequenceTyped
inductive SequenceTyped (classes : ClassTable) : Environment → List Unpacking.Statement → Environment → Prop where
  | nil {environment : Environment} :
      environment.WellFormed classes → SequenceTyped classes environment [] environment
  | cons {before middle after : Environment} {statement : Unpacking.Statement}
      {rest : List Unpacking.Statement} :
      StatementTyped classes before statement middle →
      SequenceTyped classes middle rest after →
      SequenceTyped classes before (statement :: rest) after

A well-typed program has a well-formed typed class table \(\Sigma\) and a statement sequence \(P\) that typechecks from the empty environment:

\[ \exists\Gamma_f.\;\href{#claim-shared.typing.sequences}{\Sigma;\varnothing\vdash P\Rightarrow\Gamma_f}. \]

The final environment describes locals before frame exit and need not be empty. Completion pops the initial frame and collects the heap.

Shared/Typing:ProgramTyped
def ProgramTyped (classes : ClassTable) (code : List Unpacking.Statement) : Prop :=
  classes.WellFormed ∧ ∃ finalEnvironment, SequenceTyped classes [] code finalEnvironment

Relating types to storage

The runtime mode \(\operatorname{mode}(\pi)\) maps a type permission to the corresponding reference mode:

\[ \begin{aligned} \operatorname{mode}(\mathsf{given})&=\mathsf{unique},\\ \operatorname{mode}(\mathsf{shared})&=\mathsf{shared}. \end{aligned} \]
Shared/TypingViews:Perm.toMode
def Perm.toMode : Perm → Mode
  | .given => .unique
  | .shared => .shared

For \(r=(\kappa,\alpha)\), the reference-path read \(\mathsf{read}_S(r,\rho)\) follows a relative path \(\rho\) from \(\alpha\), accumulating reference modes starting with \(\kappa\), as in refshared.resolution. The empty path returns \(r\) if its object exists. A missing object or field encountered while following the path, or an empty intermediate slot, makes traversal undefined. The final slot may be empty; if occupied, its reference is returned without dereferencing the target.

Shared/TypingPaths:enter
def enter (permission : Mode) (reference : Reference) : Reference :=
  ⟨permission.join reference.mode, reference.object⟩
Shared/TypingPaths:readPath
def readPath (state : State) (reference : Reference) : List FieldName → Option Slot
  | [] => do
      let _ ← state.objects.lookup reference.object
      return some reference
  | field :: rest => do
      let data ← state.objects.lookup reference.object
      let slot ← data.fields.lookup field
      match rest with
      | [] => return slot.map (enter reference.mode)
      | _ :: _ => do
          let target ← slot
          readPath state (enter reference.mode target) rest

Reference realization \(\Sigma;S\models r:T\) says that a reference’s type describes access from that reference. It does not prescribe one view for the object independent of its aliases.

Using the reference-path read, the relation holds for a normalized type \(T=\pi C.A\), when:

  1. The root reference has mode \(\href{#claim-shared.typing.mode}{\operatorname{mode}(\pi)}\) and targets an allocated object of class \(C\).
  2. Every \(\rho\in\href{#claim-shared.typing.observations}{\operatorname{pos}_{\Sigma}(T)}\) reaches an allocated object of its declared class. Every \(\rho\in\href{#claim-shared.typing.observations}{\operatorname{neg}_{\Sigma}(T)}\) reaches an existing empty slot.
  3. Every valid finite path read from \(C\) that reaches an occupied slot from this root, including paths hidden by the view, has effective mode \(\href{#claim-shared.typing.mode}{\operatorname{mode}}(\pi\href{#claim-shared.typing.declared_permission}{\operatorname{decl}_{\Sigma}(C,\rho)})\).

The third condition composes permissions along the whole route. A field declared given inside a shared container may store a unique reference before copying and a shared one afterwards. Both routes have effective shared mode.

Shared/TypingRealization:Satisfies
structure Satisfies (classes : ClassTable) (state : State) (reference : Reference) (ty : ValueType) : Prop where
  mode : reference.mode = ty.permission.toMode
  root : ∃ data, (reference.object, data) ∈ state.objects ∧ data.className = ty.nominal.className
  positive : ∀ path, Pos classes ty path →
    ∃ target data, readPath state reference path = some (some target) ∧
      (target.object, data) ∈ state.objects ∧
      Unique.Typing.classAt classes.nominal ty.nominal.className path = some data.className
  negative : ∀ path, Neg ty path → readPath state reference path = some none
  modes : ∀ path target permission,
    declaredPermission classes ty.nominal.className path = some permission →
    readPath state reference path = some (some target) →
    target.mode = (ty.permission.comp permission).toMode

Storage realization \(\Sigma;\Gamma\models(S;R)\) relates all variables and pending results to their type descriptions.

Here \(S=\langle O,V,\nu\rangle\) is the storage, and \(R\) is an ordered list of pending values \((r:T)\): expression results not yet stored by a binding or constructor. The relation holds when:

  • The structural clauses of refshared.well_formed hold, counting pending references alongside all stored owning occurrences. The additional declaration-kind invariants are not premises of this relation; the operational preservation result establishes them for executions from the empty initial state.
  • Every occupied field targets an object of its declared class, including fields hidden by views.
  • \(\operatorname{dom}(\Gamma)=\operatorname{dom}(V)\). A description \(\Gamma(x)=0\) means \(V(x)=\bot\); a description \(\Gamma(x)=T\) means \(V(x)=r\) with reference realization \(\href{#claim-shared.typing.reference_realization}{\Sigma;S\models r:T}\).
  • Every pending pair \((r:T)\) satisfies \(\href{#claim-shared.typing.reference_realization}{\Sigma;S\models r:T}\).

The table \(\Sigma\) and all types must be well formed. Shared aliases may carry different views; each must describe the actual storage. Hidden references still contribute to ownership and liveness.

Shared/TypingRealization:FieldsMatchClasses
def FieldsMatchClasses (classes : ClassTable) (state : State) : Prop :=
  ∀ parent data field target, (parent, data) ∈ state.objects →
    (field, some target) ∈ data.fields →
    ∃ declaration fieldType targetData,
      (data.className, declaration) ∈ classes ∧
      (field, fieldType) ∈ declaration.fields ∧
      (target.object, targetData) ∈ state.objects ∧ targetData.className = fieldType.className
Shared/TypingRealization:PendingValues
abbrev PendingValues := List (Reference × ValueType)
Shared/TypingRealization:Realizes
structure Realizes (classes : ClassTable) (environment : Environment) (state : State) (pending : PendingValues) : Prop where
  classesWellFormed : classes.WellFormed
  environmentWellFormed : environment.WellFormed classes
  pendingTypes : ∀ reference ty, (reference, ty) ∈ pending → Admissible classes ty
  ownership : WellFormedWith classes.erase state (pending.map Prod.fst)
  fields : FieldsMatchClasses classes state
  variableDomain : ∀ name,
    name ∈ environment.map Prod.fst ↔ name ∈ state.variables.map Prod.fst
  emptyVariables : ∀ name, (name, none) ∈ environment → (name, none) ∈ state.variables
  initializedVariables : ∀ name ty, (name, some ty) ∈ environment →
    ∃ reference, (name, some reference) ∈ state.variables ∧ Satisfies classes state reference ty
  pendingValues : ∀ reference ty, (reference, ty) ∈ pending →
    Satisfies classes state reference ty

For any well-formed \(\Sigma\), if expression typing and storage realization give

\[ \href{#claim-shared.typing.expressions}{\Sigma;\Gamma\vdash e:T\;\triangleright\;\Gamma'}, \qquad\href{#claim-shared.typing.realization}{\Sigma;\Gamma\models(S;R)}, \]

then an evaluation exists:

\[ \exists S',r.\; \href{#claim-shared.typing.erasure}{\lfloor\Sigma\rfloor}\vdash\langle S,e\rangle\href{shared.html#claim-shared.evaluation}{\Downarrow}\langle S',r\rangle. \]

Every such evaluation satisfies \(\href{#claim-shared.typing.realization}{\Sigma;\Gamma'\models(S';R\mathbin{+\!\!+}[(r:T)])}\), where \(+\!\!+\) appends lists. This includes arbitrary pending results of earlier constructor arguments. A copy preserves existing aliases’ views; a move preserves the types of the other owning roots.

Shared/TypingSafety:expression_soundness
theorem expression_soundness
    (typed : ExprTyped classes before value ty after)
    (realized : Realizes classes before state pending) :
    (∃ result object, Eval classes.erase state value result object) ∧
    (∀ result object, Eval classes.erase state value result object →
      Realizes classes after result (pending ++ [(object, ty)])) := by
  have sound := typed.sound state pending realized
  refine ⟨sound.1, fun result object evaluated => ?_⟩
  exact (sound.2 result object evaluated).perm (by simpa using (List.perm_middle (a := (object, ty)) (l₁ := pending) (l₂ := [])).symm)

A live frame is well typed with final environment \(\Gamma_f\) when its storage realizes an environment under which its remaining statements typecheck:

\[ \Sigma\vdash\operatorname{run}(S,P):\Gamma_f \iff \exists\Gamma.\;\Sigma;\Gamma\models(S;[]) \land \Sigma;\Gamma\vdash P\Rightarrow\Gamma_f. \]

A configuration with no frame is well typed when its heap is empty. Its counter may be nonzero. The final environment describes the locals before exit; it does not assert that terminal storage still contains those bindings. For a live frame, realization requires a well-formed class table.

Write \(K\longrightarrow_u^k K'\) for exactly \(k\) program steps using unpacking-capable local operations. Finite executions existentially quantify \(k\); stuckness means an unfinished configuration with no successor. The frame-pop step is included in this count.

Shared/FrameSafety:ConfigurationTyped
def ConfigurationTyped (classes : ClassTable) (configuration : Configuration Unpacking.Statement)
    (finalEnvironment : Environment) : Prop :=
  match configuration.frame with
  | none => configuration.objects = []
  | some frame => Typing.ConfigurationTyped classes ⟨configuration.state, frame.code⟩ finalEnvironment
Shared/Frames:StepsExactly
inductive StepsExactly (operation : LocalStep Instruction) : Configuration Instruction → Nat → Configuration Instruction → Prop where
  | refl (configuration) : StepsExactly operation configuration 0 configuration
  | step {before middle after count} :
      Step operation before middle → StepsExactly operation middle count after →
      StepsExactly operation before (count + 1) after
Shared/Frames:Stuck
def Stuck (operation : LocalStep Instruction) (configuration : Configuration Instruction) : Prop :=
  ¬ configuration.finished ∧ ¬ ∃ after, Step operation configuration after
Shared/TypedConfigurations:ConfigurationTyped
def ConfigurationTyped (classes : ClassTable) (configuration : Unpacking.Configuration)
    (finalEnvironment : Environment) : Prop :=
  ∃ current, Realizes classes current configuration.state [] ∧
    SequenceTyped classes current configuration.code finalEnvironment

Progress and preservation

A well-typed configuration has finished or can take a step:

\[ \href{#claim-shared.typing.configurations}{\Sigma\vdash K:\Gamma_f} \quad\Longrightarrow\quad \href{#claim-shared.typing.finished}{\mathsf{Finished}(K)}\ \lor\ \exists K'.\;\href{#claim-shared.typing.erasure}{\lfloor\Sigma\rfloor}\vdash K\href{#claim-shared.typing.steps}{\longrightarrow_u} K'. \]
Shared/FrameSafety:ConfigurationTyped.progress
theorem ConfigurationTyped.progress
    (typed : ConfigurationTyped classes configuration finalEnvironment) :
    configuration.finished ∨ ∃ after, Step (patternOperation classes.erase) configuration after := by
  rcases configuration with ⟨objects, nextId, frame⟩
  cases frame with
  | none => exact .inl rfl
  | some frame =>
    rcases frame with ⟨variables, code⟩
    have localTyped : Typing.ConfigurationTyped classes ⟨⟨objects, variables, nextId⟩, code⟩ finalEnvironment := typed
    rcases localTyped.progress with finished | ⟨after, step⟩
    · change code = [] at finished
      subst code
      exact .inr ⟨_, exit_step ⟨objects, variables, nextId⟩⟩
    · exact .inr ⟨_, local_step (operation := patternOperation classes.erase)
        (before := ⟨objects, variables, nextId⟩) (code := code) (after := after.state)
        (rest := after.code) step (local_wellFormed (localTyped.preservation step))⟩

Every step from a well-typed configuration preserves its final typing:

\[ \frac{\href{#claim-shared.typing.configurations}{\Sigma\vdash K:\Gamma_f} \qquad\href{#claim-shared.typing.erasure}{\lfloor\Sigma\rfloor}\vdash K\href{#claim-shared.typing.steps}{\longrightarrow_u} K'} {\href{#claim-shared.typing.configurations}{\Sigma\vdash K':\Gamma_f}}. \]

The current environment changes when a source is moved or a result is bound. A shared give itself preserves the environment even when the final stored reference changes mode; binding its result then adds a fresh variable.

Shared/FrameSafety:ConfigurationTyped.preservation
theorem ConfigurationTyped.preservation
    (typed : ConfigurationTyped classes before finalEnvironment)
    (step : Step (patternOperation classes.erase) before after) :
    ConfigurationTyped classes after finalEnvironment := by
  cases step with
  | «local» operation =>
    have next := Typing.ConfigurationTyped.preservation typed operation
    rw [collect_running (local_wellFormed next)]
    exact next
  | exit =>
    rw [collect_popped]
    rfl

For a well-typed program, no finite execution reaches a stuck configuration. Every execution prefix remains well typed and can be completed.

If the original program has \(n\) statements, every such prefix extends to completion after exactly \(n+1\) steps in total: one per statement, followed by one frame-pop step. A live frame’s remaining work is its statement count plus one; a finished configuration has zero remaining work. Terminal storage has no locals and an empty heap; its allocation counter records the identifiers spent.

Shared/FrameSafety:program_safety
theorem program_safety (classesWf : classes.WellFormed)
    (typed : SequenceTyped classes [] code finalEnvironment)
    (execution : StepsExactly (patternOperation classes.erase) (.initial code) count configuration) :
    ¬ Stuck (patternOperation classes.erase) configuration ∧
    ConfigurationTyped classes configuration finalEnvironment ∧
    count + configuration.remaining = code.length + 1 ∧
    ∃ nextId,
      StepsExactly (patternOperation classes.erase) configuration configuration.remaining (.terminal nextId) ∧
      StepsExactly (patternOperation classes.erase) (.initial code) (code.length + 1) (.terminal nextId) := by
  have current := (ConfigurationTyped.initial classesWf typed).trace execution
  have length : count + configuration.remaining = code.length + 1 := by
    exact (execution.remaining (fun _ _ _ _ step => step.code_length)).symm
  obtain ⟨nextId, rest⟩ := current.finishes
  refine ⟨?_, current, length, nextId, rest, length ▸ execution.trans rest⟩
  intro stuck
  rcases current.progress with finished | next
  · exact stuck.1 finished
  · exact stuck.2 next

Embed every Given declaration as a class, restrict field declarations and types to given, and omit give-share expressions. The typing rules then agree with Given’s rules, including its unpacking extension. Embedding every runtime reference with mode unique preserves and reflects statement transitions and exhaustion of the local statement sequence in this fragment. These selected results concern local-frame observations; program-level steps use the framed correspondence below.

This extends the earlier correspondence, which covers only single-variable bindings, to local operations with unpacking.

Correspondence/UniqueSharedTyping:given_fragment
theorem given_fragment (classes : Unique.Typing.ClassTable) :
    (∀ before value ty after,
      Unique.Typing.ExprTyped classes before value ty after ↔
        Shared.Typing.ExprTyped (embedClasses classes) (embedEnvironment before)
          (embedValue value) (embedType ty) (embedEnvironment after)) ∧
    (∀ before pattern ty after,
      Unique.Typing.BindingTyped classes before pattern ty after ↔
        Shared.Typing.BindingTyped (embedClasses classes) (embedEnvironment before)
          (Unpacking.embedPattern pattern) (embedType ty) (embedEnvironment after)) ∧
    (∀ before statement after,
      Unique.Typing.StatementTyped classes before statement after ↔
        Shared.Typing.StatementTyped (embedClasses classes) (embedEnvironment before)
          (Unpacking.embedStatement statement) (embedEnvironment after)) ∧
    (∀ before statements after,
      Unique.Typing.SequenceTyped classes before statements after ↔
        Shared.Typing.SequenceTyped (embedClasses classes) (embedEnvironment before)
          (statements.map Unpacking.embedStatement) (embedEnvironment after)) ∧
    (∀ statements, Unique.Typing.ProgramTyped classes statements ↔
      Shared.Typing.ProgramTyped (embedClasses classes) (statements.map Unpacking.embedStatement)) ∧
    (∀ before after,
      Shared.Unpacking.Step (embedClasses classes).erase (Unpacking.embedConfiguration before) after ↔
        ∃ successor, Unique.Unpacking.Step classes.erase before successor ∧
          after = Unpacking.embedConfiguration successor) ∧
    (∀ before after,
      Shared.Unpacking.Steps (embedClasses classes).erase (Unpacking.embedConfiguration before) after ↔
        ∃ successor, Unique.Unpacking.Steps classes.erase before successor ∧
          after = Unpacking.embedConfiguration successor) ∧
    (∀ configuration, (Unpacking.embedConfiguration configuration).finished ↔ configuration.finished) ∧
    (∀ configuration,
      (∃ final, Shared.Unpacking.Steps (embedClasses classes).erase
        (Unpacking.embedConfiguration configuration) final ∧ final.finished) ↔
      (∃ final, Unique.Unpacking.Steps classes.erase configuration final ∧ final.finished)) := by
  refine ⟨fun _ _ _ _ => expression_correspondence,
    fun _ _ _ _ => binding_correspondence, fun _ _ _ => statement_correspondence,
    fun _ _ _ => sequence_correspondence, program_correspondence classes, ?_, ?_,
    Unpacking.finished_correspondence, ?_⟩
  · intro before after
    simpa using (Unpacking.step_correspondence (classes := classes.erase)
      (before := before) (after := after))
  · intro before after
    simpa using (Unpacking.steps_correspondence (classes := classes.erase)
      (before := before) (after := after))
  · intro configuration
    simpa using (Unpacking.completion_correspondence (classes := classes.erase) configuration)

From a well-typed live frame with \(n\) statements, there is an observation state \(S_f\) after exactly \(n\) program steps. Its frame has no statements left, and its locals still realize the final environment. One further step pops that frame, leaving no roots and an empty heap with counter \(S_f.\nu\). This separates inspection of the computed bindings from program completion.

Shared/FrameSafety:completion
theorem completion (typed : Typing.ConfigurationTyped classes before finalEnvironment) :
    ∃ observed,
      StepsExactly (patternOperation classes.erase) (.running before.state before.code)
        before.code.length (.running observed []) ∧
      Realizes classes finalEnvironment observed [] ∧
      StepsExactly (patternOperation classes.erase) (.running before.state before.code)
        (before.code.length + 1) (.terminal observed.nextId) := by
  obtain ⟨last, trace, finished, realized⟩ := typed.finishes
  have lifted := lift_local_trace typed trace
  change last.code = [] at finished
  rw [finished] at lifted
  exact ⟨last.state, lifted, realized, lifted.trans (.step (exit_step _) (.refl _))⟩

The program machines with unpacking also preserve and reflect every step of the all-given fragment. From an embedded Given configuration, every Shared successor is the embedding of a Given successor, and every Given successor has that Shared step. This includes eager collection and initial-frame exit, not just local statement operations.

Correspondence/UniqueSharedFrames:pattern_step_correspondence
theorem pattern_step_correspondence :
    Shared.Framed.Step (Shared.Framed.patternOperation (embedClasses classes))
      (embed Unpacking.embedStatement before) after ↔
    ∃ successor, Unique.Framed.Step (Unique.Framed.patternOperation classes) before successor ∧
      after = embed Unpacking.embedStatement successor := by
  constructor
  · apply step_backward Unpacking.embedStatement
    intro state code next rest step
    obtain ⟨successor, original, same⟩ := Unpacking.step_backward (before := ⟨state, code⟩) (after := ⟨next, rest⟩) step
    exact ⟨successor.state, successor.code, original, congrArg Shared.Unpacking.Configuration.state same,
      by simpa [Unpacking.embedConfiguration] using congrArg Shared.Unpacking.Configuration.code same⟩
  · rintro ⟨successor, step, rfl⟩
    exact step_forward Unpacking.embedStatement (fun state code after rest step => Unpacking.step_forward
      (before := ⟨state, code⟩) (after := ⟨after, rest⟩) step) step

Functions and methods

Moving a value into a call and back

A function gives a sequence of statements its own parameters and locals. A call transfers argument values into those parameters; a return transfers a result back to the caller.

class Token {}

fn identity(token: → Token) → Token {
    return token→;
}

let original = new Token();
let result = identity(original→);

Here → Token in a signature means uniquely owned Token, called given Token in the model. The argument expression original→ empties original. The function receives that reference in token, then moves it into its return value. The caller binds the same reference to result. No object is copied or reconstructed.

The arrow after the parameter list introduces a uniquely owned result type: fn identity(...) → Token. A shared result instead uses fn copy(...) shared Point. This chapter uses the same permission-prefixed type syntax as parameters, without an additional return-type separator.

This layer adds functions and methods to Shared. The examples check typing and execution in Lean. The new rules come first; the explicit forward reference to the inherited machinery in the appendix keeps the call rules together without repeating Shared’s expression calculus here.

Functions/Checks:identity
example : ProgramTyped identityProgram ∧
    Steps classes.erase declarations (.initial identityProgram) identityReturned ∧
    Step classes.erase declarations identityReturned ⟨[], 1, []⟩ ∧
    ("original", none) ∈ identityReturned.rootState.variables ∧
    ("result", some (.owned 0)) ∈ identityReturned.rootState.variables :=
  ⟨⟨by decide, declarations_typed, _, identity_main⟩, identity_execution,
    by exact collected_step .exit (by simp), by decide, by decide⟩

A shared parameter receives an owned shared reference. It does not borrow from the caller, and returning it does not create a dependency on the callee’s locals.

struct Point {}

fn copy(point: shared Point) shared Point {
    return point→;
}

let p = new Point();
let s = p→share;
let t = copy(s→);

Sharing empties the uniquely owned p and produces the shared reference s. Giving s copies it, and giving the shared parameter point copies it again. Both s and t remain initialized and refer to the same object.

shared Point means shared[] Point: shared ownership with no lease dependency. The empty brackets may be omitted. Classes cannot be shared, so a parameter of type shared Token for the class in the preceding example is invalid.

Functions/Checks:shared
example : ProgramTyped sharedProgram ∧
    Steps classes.erase declarations (.initial sharedProgram) sharedReturned ∧
    Step classes.erase declarations sharedReturned ⟨[], 1, []⟩ ∧
    ("p", none) ∈ sharedReturned.rootState.variables ∧
    ("s", some (.shared 0)) ∈ sharedReturned.rootState.variables ∧
    ("t", some (.shared 0)) ∈ sharedReturned.rootState.variables ∧
    ¬ Admissible classes (ValueType.whole "Token" .shared) :=
  ⟨⟨by decide, declarations_typed, _, shared_main⟩, shared_execution,
    by exact collected_step .exit (by simp), by decide, by decide, by decide, by decide⟩

Locals live in frames

A suspended caller keeps its locals alive while another function runs:

class Token {}
class Box { child: Token }
fn work() {
    let temporary = new Token();
}
let box = new Box(new Token());
work();

The focused runtime check starts inside work, with the caller’s box and its child already allocated. It checks these transitions:

BoundaryFramesHeap
After allocating temporarywork, initial callerbox, child, temporary
After returning from workinitial callerbox, child
After popping the initial framenoneempty

The box is rooted only by the suspended caller during work; its child is reachable through a field. Both survive collection. The temporary is reclaimed as soon as work returns. All three object identifiers remain spent: the final allocation counter is three. The check also covers the single exit step of an empty program.

These examples observe returned values before the final frame exits. The frame rules and collector definition below make this lifetime explicit. The later Destructors layer will require consuming class values before a frame can exit; this layer permits them to become unreachable.

Functions/Checks:gc
example : Step classes.erase declarations gcBefore gcDuring ∧
    gcDuring.objects.length = 3 ∧
    Step classes.erase declarations gcDuring gcAfter ∧
    gcAfter.objects = callerHeap ∧
    Step classes.erase declarations gcAfter ⟨[], 3, []⟩ ∧
    (Configuration.mk [] 3 []).finished ∧
    Step classes.erase declarations (.initial ⟨classes, declarations, []⟩) ⟨[], 0, []⟩ :=
  ⟨gc_local, rfl, gc_return, rfl, collected_step .exit (by simp), rfl,
    collected_step .exit (by simp)⟩

Methods choose a receiver permission

A method belongs to a nominal declaration. Its first parameter names the permission it requires for self; the enclosing declaration fixes the nominal type of the receiver.

struct Point {
    fn take(→self) → Point {
        return self→;
    }
    fn copy(shared self) shared Point {
        return self→;
    }
}

let p = new Point();
let q = Point.take(p→);
let s = q→share;
let t = Point.copy(s→);

The take call gives p to an owned receiver. The copy call gives s, which produces a shared copy, to a shared receiver. p becomes empty; s remains initialized. Both receiver permissions use prefix syntax in declarations. There is no general self: Type receiver form.

Each call names the enclosing type and method explicitly, with the receiver as the first argument. The give operation moves or copies according to the receiver’s permission. Method-call sugar is deferred to a later layer.

Functions/Checks:methods
example : ProgramTyped methodProgram ∧
    Steps classes.erase declarations (.initial methodProgram) methodReturned ∧
    Step classes.erase declarations methodReturned ⟨[], 1, []⟩ ∧
    ("p", none) ∈ methodReturned.rootState.variables ∧
    ("s", some (.shared 0)) ∈ methodReturned.rootState.variables ∧
    ("t", some (.shared 0)) ∈ methodReturned.rootState.variables :=
  ⟨⟨by decide, declarations_typed, _, method_main⟩, method_execution,
    by exact collected_step .exit (by simp), by decide, by decide, by decide⟩

Syntax

A callable name \(a\) identifies either a global function \(f\) or a method named \(m\) of nominal type \(C\). Parameter names \(x\) are local variables. A signature type \(T\) is a whole nominal type with an explicit permission \(Q\); it carries no partial view.

\[ \begin{aligned} a &::= f \mid C.m, & Q &::= {\to} \mid \mathsf{shared}, \\ T &::= Q\ C, & P &::= x:T, \\ R &::= \mathsf{none} \mid T, & \sigma &::= ({\overline P})\;R. \end{aligned} \]

Here \(P\) is a parameter, \(R\) an optional result type, and \(\sigma\) a signature.

shared[] abbreviates the same permission as shared. The model calls → permission given. A result annotation follows the parameter list directly; its absence denotes no result. There is no implicit parameter permission.

A method’s first parameter is written →self or shared self. These elaborate to the parameter named self with type → C or shared C, respectively, where C is the enclosing nominal type. No self: Type surface form is provided. Ordinary function parameters cannot be named self.

A well-formed signature has distinct parameter names and admissible parameter and result types. A method must have its correctly named and typed receiver first. In particular, classes admit only given access, shared structs admit only shared access, and ordinary structs admit either.

Functions/Syntax:Name
inductive Name where
  | function (name : String)
  | method (owner : ClassName) (name : String)
  deriving DecidableEq, Repr
Functions/Syntax:Parameter
structure Parameter where
  name : VariableId
  type : FieldType
  deriving DecidableEq, Repr
Functions/Syntax:Signature
structure Signature where
  parameters : List Parameter
  result : Option FieldType
  deriving DecidableEq, Repr
Functions/Syntax:receiver
def receiver (owner : ClassName) (permission : Perm) : Parameter :=
  ⟨"self", ⟨permission, owner⟩⟩
Functions/Syntax:Signature.WellFormed
def Signature.WellFormed (classes : ClassTable) (name : Name)
    (signature : Signature) : Prop :=
  (signature.parameters.map Parameter.name).Nodup ∧
  (∀ p ∈ signature.parameters, Admissible classes p.type.toType) ∧
  (∀ ty ∈ signature.result, Admissible classes ty.toType) ∧
  match name with
  | .function _ => "self" ∉ signature.parameters.map Parameter.name
  | .method owner _ => match signature.parameters with
    | [] => False
    | first :: rest => first.name = "self" ∧ first.type.className = owner ∧
        "self" ∉ rest.map Parameter.name

A value expression \(e\) and binding pattern \(b\) are inherited from Shared (see the appendix). An optional call destination \(d\) is either a fresh local name or absent. The core syntax is:

\[ \begin{aligned} d &::= \mathsf{none}\mid x, \\ t &::= \mathsf{let}\ b=e \mid d\mathrel{:=}\mathsf{call}\ a({\overline e}), \\ r &::= \mathsf{none}\mid e, \\ B &::= ({\overline t};\ \mathsf{return}\ r), \\ D &::= (\sigma,B). \end{aligned} \]

Here \(t\) is a statement, \(r\) an optional return expression, \(B\) a body, and \(D\) a declaration pairing a signature with its body. The call notation above is metasyntax: let x = f(args); supplies destination x, while f(args); supplies none. A method call is C.method(receiver, args), with its receiver as argument zero. There is no receiver-based call sugar.

A body stores its final return separately from its statement list. return; and falling off the end both mean no return expression. There are no early returns. Receivers, arguments, and returned values use call-free expressions; write nested calls as successive statements.

A program contains a nominal class table \(\Delta\), a declaration table \(F\) listing callable-name/declaration pairs, and a top-level statement list. Method lookup uses the qualified name, not runtime dispatch. There is no overloading. These are abstract syntax definitions, not a source parser.

Functions/Syntax:Statement
inductive Statement where
  | local (statement : Unpacking.Statement)
  | call (destination : Option VariableId) (name : Name) (arguments : List Value)
  deriving Repr
Functions/Syntax:Body
structure Body where
  statements : List Statement
  result : Option Value
  deriving Repr
Functions/Syntax:Declaration
structure Declaration where
  signature : Signature
  body : Body
  deriving Repr
Functions/Syntax:Program
structure Program where
  classes : ClassTable
  declarations : Declarations
  main : List Statement
  deriving Repr

Typing calls and bodies

An environment \(\Gamma\) maps local names to types or empty slots. Write \(\operatorname{WF}_{\Delta}(\Gamma)\) for the inherited check of distinct names and normalized, admissible types. Write \(\operatorname{env}(\sigma)\) for a signature’s parameter environment: each parameter is initially present at its declared whole type. Write \(\operatorname{params}(\sigma)\) for its ordered parameter types and \(\operatorname{result}(\sigma)\) for its optional result type.

Functions/Syntax:Signature.environment
def Signature.environment (signature : Signature) : Environment :=
  signature.parameters.map fun p => (p.name, some p.type.toType)

The judgment \(\Delta\vdash\Gamma;d:R\Rightarrow\Gamma'\) installs a call’s result in a well-formed environment. An absent destination requires an absent result; a present one uses Shared’s fresh-variable binding judgment, written \(\Delta\vdash\Gamma;x:T\Rightarrow_{\mathrm{bind}}\Gamma'\).

\[ \frac{\operatorname{WF}_{\Delta}(\Gamma)} {\Delta\vdash\Gamma;\mathsf{none}:\mathsf{none}\Rightarrow\Gamma} \qquad \frac{\Delta\vdash\Gamma;x:T\Rightarrow_{\mathrm{bind}}\Gamma'} {\Delta\vdash\Gamma;x:T\Rightarrow\Gamma'} \]

A value-returning call cannot silently discard its result. The binding premise also checks admissibility and freshness.

Functions/Typing:DestinationTyped
inductive DestinationTyped (classes : ClassTable) : Environment → Option VariableId → Option FieldType → Environment → Prop where
  | none {environment} :
      environment.WellFormed classes → DestinationTyped classes environment none none environment
  | some {before after name type} :
      BindingTyped classes before (.variable name) type.toType after →
      DestinationTyped classes before (some name) (some type) after

Write \(\Delta;F\vdash\Gamma\mathrel{\xrightarrow{t}}\Gamma'\) for statement typing. Shared’s argument judgment \(\Delta\vdash\Gamma;{\overline e}:{\overline T}\Rightarrow\Gamma_e\) checks arguments left to right and threads their effects through the environment. The receiver, when present, is the first argument.

The destination judgment installs the result after argument evaluation.

\[ \frac{ \begin{gathered} (a,(\sigma,B))\in F \quad d\notin\operatorname{dom}(\Gamma) \\ \Delta\vdash\Gamma;{\overline e}:\operatorname{params}(\sigma)\Rightarrow\Gamma_e \quad \Delta\vdash\Gamma_e;d:\operatorname{result}(\sigma)\Rightarrow\Gamma' \end{gathered} }{\Delta;F\vdash\Gamma\mathrel{\xrightarrow{d:=\mathsf{call}\ a({\overline e})}}\Gamma'} \]

The freshness premise is vacuous when \(d=\mathsf{none}\). Arguments must match the declared whole types; there is no automatic sharing at the boundary. The rule consults a signature, not a body expansion.

Shared bindings and unpacking retain their typing rule. Sequence typing chains statement environments; an empty sequence requires a well-formed environment:

\[ \frac{\Delta\vdash\Gamma\mathrel{\xrightarrow{t}_{\mathrm{Shared}}}\Gamma'} {\Delta;F\vdash\Gamma\mathrel{\xrightarrow{t}}\Gamma'} \qquad \frac{\operatorname{WF}_{\Delta}(\Gamma)} {\Delta;F\vdash\Gamma\mathrel{\xrightarrow{[]}}\Gamma} \qquad \frac{\Delta;F\vdash\Gamma\mathrel{\xrightarrow{t}}\Gamma_1\quad \Delta;F\vdash\Gamma_1\mathrel{\xrightarrow{{\overline t}}}\Gamma'} {\Delta;F\vdash\Gamma\mathrel{\xrightarrow{t::{\overline t}}}\Gamma'} \]
Functions/Typing:StatementTyped
inductive StatementTyped (classes : ClassTable) (declarations : Declarations) : Environment → Statement → Environment → Prop where
  | local {before after statement} :
      Shared.Typing.StatementTyped classes before statement after →
      StatementTyped classes declarations before (.local statement) after
  | call {before middle after destination name arguments declaration} :
      (name, declaration) ∈ declarations →
      (∀ x ∈ destination, x ∉ before.map Prod.fst) →
      ArgsTyped classes before arguments (declaration.signature.parameters.map Parameter.type) middle →
      DestinationTyped classes middle destination declaration.signature.result after →
      StatementTyped classes declarations before (.call destination name arguments) after
Functions/Typing:SequenceTyped
inductive SequenceTyped (classes : ClassTable) (declarations : Declarations) : Environment → List Statement → Environment → Prop where
  | nil {environment} :
      environment.WellFormed classes → SequenceTyped classes declarations environment [] environment
  | cons {before middle after statement rest} :
      StatementTyped classes declarations before statement middle →
      SequenceTyped classes declarations middle rest after →
      SequenceTyped classes declarations before (statement :: rest) after

The judgment \(\Delta\vdash\Gamma;r:R\Rightarrow_{\mathrm{return}}\Gamma'\) checks the final return. The environment condition is inherited. It has two cases:

\[ \frac{\operatorname{WF}_{\Delta}(\Gamma)} {\Delta\vdash\Gamma;\mathsf{none}:\mathsf{none}\Rightarrow_{\mathrm{return}}\Gamma} \qquad \frac{\Delta\vdash\Gamma;e:T\Rightarrow\Gamma'} {\Delta\vdash\Gamma;e:T\Rightarrow_{\mathrm{return}}\Gamma'} \]

The expression judgment in the second rule is Shared’s.

Functions/Typing:ResultTyped
inductive ResultTyped (classes : ClassTable) : Environment → Option Value → Option FieldType → Environment → Prop where
  | none {environment} :
      environment.WellFormed classes → ResultTyped classes environment none none environment
  | some {before after value type} :
      ExprTyped classes before value type.toType after →
      ResultTyped classes before (some value) (some type) after

A body checks against its signature by typing its statements from the parameter environment, then checking its return expression:

\[ \frac{ \Delta;F\vdash\operatorname{env}(\sigma)\mathrel{\xrightarrow{{\overline t}}}\Gamma_m \quad \Delta\vdash\Gamma_m;r:\operatorname{result}(\sigma)\Rightarrow_{\mathrm{return}}\Gamma_f }{\Delta;F\vdash({\overline t};\mathsf{return}\ r):\sigma} \]

There is no consumption condition on \(\Gamma_f\) in this layer.

Functions/Typing:BodyTyped
def BodyTyped (classes : ClassTable) (declarations : Declarations) (signature : Signature)
    (body : Body) : Prop :=
  ∃ middle after,
    SequenceTyped classes declarations signature.environment body.statements middle ∧
    ResultTyped classes middle body.result signature.result after

A declaration table checks when callable names are distinct and every signature is well formed and every body checks against its signature, using the complete table. This permits mutual recursion.

Functions/Typing:DeclarationsTyped
def DeclarationsTyped (classes : ClassTable) (declarations : Declarations) : Prop :=
  (declarations.map Prod.fst).Nodup ∧
    ∀ entry ∈ declarations,
      entry.2.signature.WellFormed classes entry.1 ∧
      BodyTyped classes declarations entry.2.signature entry.2.body

A program checks when its nominal table and declaration table check, and its top-level statements check from the empty environment to some final environment.

Functions/Typing:ProgramTyped
def ProgramTyped (program : Program) : Prop :=
  program.classes.WellFormed ∧ DeclarationsTyped program.classes program.declarations ∧
    ∃ finalEnvironment,
      SequenceTyped program.classes program.declarations [] program.main finalEnvironment

Every typed call names a declaration in its table, supplies exactly as many arguments as that declaration has parameters, and supplies a destination exactly when the declaration has a result.

Functions/Typing:call_arity
theorem call_arity
    (typed : StatementTyped classes declarations before (.call destination name arguments) after) :
    ∃ declaration, (name, declaration) ∈ declarations ∧
      arguments.length = declaration.signature.parameters.length ∧
      DestinationMatches destination declaration.signature.result := by
  cases typed with
  | call declared _ args dest =>
    exact ⟨_, declared, by simpa using args.length, dest.shape⟩

The formal checks reject each of these boundaries:

AttemptReason
fn bad(x: shared Token) with class TokenClasses cannot be shared.
A Point method with a receiver of nominal type Token in the core signatureA method’s receiver must have its enclosing nominal type.
let x = identity();The owned parameter is missing.
identity(new Token());The call omits the destination for its result.
Functions/Checks:rejection
example :
    ¬ Signature.WellFormed classes (.function "bad") ⟨[⟨"x", ⟨.shared, "Token"⟩⟩], none⟩ ∧
    ¬ Signature.WellFormed classes (.method "Point" "bad")
      ⟨[⟨"self", ownedToken⟩], none⟩ ∧
    (∀ after, ¬ StatementTyped classes [(.function "identity", identity)] []
      (.call (some "x") (.function "identity") []) after) ∧
    (∀ after, ¬ StatementTyped classes [(.function "identity", identity)] []
      (.call none (.function "identity") [.new "Token" []]) after) := by
  refine ⟨by decide, by decide, ?_, ?_⟩
  · intro after typed
    obtain ⟨declaration, member, arity, _⟩ := call_arity typed
    simp only [List.mem_singleton, Prod.mk.injEq] at member
    rcases member with ⟨_, rfl⟩
    cases arity
  · intro after typed
    obtain ⟨declaration, member, _, shape⟩ := call_arity typed
    simp only [List.mem_singleton, Prod.mk.injEq] at member
    rcases member with ⟨_, rfl⟩
    cases shape

Stores, frames, and calls

Each call has a frame \(\phi\) containing its local store \(V\), remaining body \(B\), and destination \(d\) for its result in the caller. A store maps local names to references or empty slots. The frame stack \(K\) lists the active frame first, followed by suspended callers. The heap \(H\) and next object identifier \(n\) belong to the whole machine:

\[ \phi=(V,B,d),\qquad K=[\phi_0,\ldots,\phi_j],\qquad M=\langle H,n,K\rangle. \]

Only the active frame’s locals are accessible to expressions. For evaluation, combine them with the heap and counter to form Shared’s state \(S=(H,V,n)\). The Lean helper Configuration.running constructs a configuration from such a state, an active body, a caller stack, and a result destination.

The initial configuration has an empty heap, counter zero, and one frame: empty locals, the program’s statements, no return expression, and no destination.

Functions/Step:Store
abbrev Store := List (VariableId × Slot)
Functions/Step:Frame
structure Frame where
  variables : Store
  body : Body
  destination : Option VariableId
  deriving Repr
Functions/Step:Configuration
structure Configuration where
  objects : List (ObjectId × Object)
  nextId : Nat
  frames : List Frame
  deriving Repr
Functions/Step:Configuration.running
def Configuration.running (state : State) (body : Body)
    (frames : List Frame := []) (destination : Option VariableId := none) : Configuration :=
  ⟨state.objects, state.nextId, ⟨state.variables, body, destination⟩ :: frames⟩
Functions/Step:Configuration.initial
def Configuration.initial (program : Program) : Configuration :=
  .running State.empty ⟨program.main, none⟩

A configuration is finished exactly when its frame stack is empty. Exhausting the initial body’s statements still leaves its frame to be popped.

Functions/Step:Configuration.finished
def Configuration.finished (configuration : Configuration) : Prop :=
  configuration.frames = []

Roots are initialized local slots in all live frames, including suspended callers. rootState concatenates their stores solely to reuse Shared’s reachability relation; identical local names in different frames remain distinct slots. There are no retained stores from completed calls.

Functions/Step:Configuration.rootState
def Configuration.rootState (configuration : Configuration) : State :=
  ⟨configuration.objects, configuration.frames.flatMap Frame.variables, configuration.nextId⟩
Functions/Step:Configuration.roots
def Configuration.roots (configuration : Configuration) : List Reference :=
  configuration.rootState.variables.filterMap Prod.snd

As in Shared, eager garbage collection, written \(\operatorname{gc}(M)\), retains exactly the heap entries reachable from the live frames’ roots. Here \(o\) is an object identifier and \(h\) its class tag and field store. Reachability follows zero or more initialized object fields, regardless of reference permission. Write \(\operatorname{live}_M(o)\) for Shared’s Live relation with all frame stores as its variable store. Then:

\[ \operatorname{gc}(\langle H,n,K\rangle) =\langle [(o,h)\in H\mid\operatorname{live}_M(o)],n,K\rangle. \]

Collection preserves surviving objects, their identifiers and fields, the allocation counter, and every frame. It invokes no destructor. With no frames, there are no roots and collection removes the entire heap.

This is a mathematical definition of the resulting heap. Its Lean definition reuses Shared’s noncomputable reachability filter; it does not prescribe an executable graph-traversal algorithm.

Functions/Step:Configuration.collect
def Configuration.collect (configuration : Configuration) : Configuration := by
  exact { configuration with objects := configuration.rootState.collect.objects }
Shared/Frames:State.collect
def State.collect (state : State) : State := by
  classical
  exact { state with objects := state.objects.filter (fun entry => decide (Live state entry.1)) }

For equally long parameter and reference lists, \(\operatorname{bind}(\sigma, {\overline v})\) pairs each parameter name with its argument reference, in order. Here \(v\) denotes a runtime reference. The call rule checks lengths before using this operation.

\[ \operatorname{bind}((x_1:T_1,\ldots,x_j:T_j)\,R,[v_1,\ldots,v_j]) =[x_1\mapsto v_1,\ldots,x_j\mapsto v_j]. \]

Write \(d\sim R\) when destination and result are either both present or both absent. This is an operational shape check, not runtime type checking.

Functions/Step:parameterStore
def parameterStore (parameters : List Parameter) (references : List Reference) : Store :=
  (parameters.map Parameter.name).zip (references.map some)
Functions/Step:DestinationMatches
def DestinationMatches (destination : Option VariableId)
    (result : Option Shared.Typing.FieldType) : Prop :=
  destination.isSome = result.isSome

Let \(u\) be an optional reference. Write \(S\vdash r\Downarrow S_e;u\) for optional-result evaluation. An absent expression produces no reference and leaves the state unchanged; a present one uses Shared’s value evaluation.

Delivery, written \(V;d;u\Rightarrow V'\), has just two cases:

\[ V;\mathsf{none};\mathsf{none}\Rightarrow V \qquad \frac{x\notin\operatorname{dom}(V)}{V;x;v\Rightarrow(x\mapsto v)::V}. \]
Functions/Step:ResultEval
inductive ResultEval (classes : Classes) : State → Option Value → State → Option Reference → Prop where
  | none (state : State) : ResultEval classes state none state none
  | some {before after value reference} :
      Eval classes before value after reference →
      ResultEval classes before (some value) after (some reference)
Functions/Step:Deliver
inductive Deliver : Store → Option VariableId → Option Reference → Store → Prop where
  | none (variables : Store) : Deliver variables none none variables
  | some {variables name reference} :
      name ∉ variables.map Prod.fst →
      Deliver variables (some name) (some reference) ((name, some reference) :: variables)

Every transition first performs a raw step \(M\rightsquigarrow M_r\), then collects. Raw steps are auxiliary rules, not observable machine steps:

\[ \frac{M\rightsquigarrow M_r}{M\longrightarrow\operatorname{gc}(M_r)}. \]

In the rules below, \(S=(H,V,n)\) is the active frame’s evaluation state, and \(S_e=(H_e,V_e,n_e)\) is its result. Write \(S\vdash{\overline e}\Downarrow S_e;{\overline v}\) for Shared’s left-to-right argument evaluation, and \(S\vdash t\Downarrow S_e\) for one Shared binding or unpacking statement. Write \(B_r=({\overline t};\mathsf{return}\ r)\) for the remaining body and \(d_0\) for the current frame’s own return destination.

The parameter operations define \(d\sim R\) and \(\operatorname{bind}\). The return premises use optional-result evaluation and delivery.

Local statement

\[ \frac{S\vdash t\Downarrow S_e} {\langle H,n,(V,(t::{\overline t};\mathsf{return}\ r),d_0)::K\rangle \rightsquigarrow\langle H_e,n_e,(V_e,B_r,d_0)::K\rangle} \]

Call

\[ \frac{ \begin{gathered} (a,(\sigma,B_c))\in F\quad d\sim\operatorname{result}(\sigma)\quad d\notin\operatorname{dom}(V) \\ S\vdash{\overline e}\Downarrow S_e;{\overline v}\quad |{\overline v}|=|\operatorname{params}(\sigma)| \end{gathered} }{ \begin{gathered} \langle H,n,(V,(d:=\mathsf{call}\ a({\overline e})::{\overline t};\mathsf{return}\ r),d_0)::K\rangle \\ \rightsquigarrow \langle H_e,n_e,(\operatorname{bind}(\sigma,{\overline v}),B_c,d)::(V_e,B_r,d_0)::K\rangle \end{gathered} } \]

Freshness is vacuous for an absent destination. The caller retains its updated locals and continuation; the callee receives a new frame. Arguments are transferred to parameters before collection. Qualified methods use this same rule.

Return

\[ \frac{S\vdash r\Downarrow S_e;u\quad V_c;d;u\Rightarrow V'} {\langle H,n,(V,([];\mathsf{return}\ r),d)::(V_c,B_c,d_c)::K\rangle \rightsquigarrow\langle H_e,n_e,(V',B_c,d_c)::K\rangle}. \]

Evaluate the result, deliver it to the caller, and pop the callee. Collection then uses the resumed caller and remaining frames as roots. A returned object survives even when its last callee reference has just disappeared. Other objects reachable only from the departed frame are reclaimed.

Initial frame exit

\[ \langle H,n,[(V,([];\mathsf{return}\ \mathsf{none}),\mathsf{none})]\rangle \rightsquigarrow\langle H,n,[]\rangle. \]

Collection makes this step’s target \(\langle\varnothing,n,[]\rangle\). Even an empty program takes this exit step. No rule steps from an empty stack.

No collection occurs midway through expression evaluation: constructor arguments, call arguments, and returned values remain available until the raw transition finishes transferring them. Collection runs after local statements, calls, returns, and initial-frame exit.

Functions/Step:RawStep
inductive RawStep (classes : Classes) (declarations : Declarations) : Configuration → Configuration → Prop where
  | local {before after statement rest result frames destination} :
      Unpacking.Step classes ⟨before, [statement]⟩ ⟨after, []⟩ →
      RawStep classes declarations
        (.running before ⟨.local statement :: rest, result⟩ frames destination)
        (.running after ⟨rest, result⟩ frames destination)
  | call {before evaluated destination name arguments rest result frames returnTo
      declaration references} :
      (name, declaration) ∈ declarations →
      DestinationMatches destination declaration.signature.result →
      (∀ x ∈ destination, x ∉ before.variables.map Prod.fst) →
      EvalArgs classes before arguments evaluated references →
      references.length = declaration.signature.parameters.length →
      RawStep classes declarations
        (.running before ⟨.call destination name arguments :: rest, result⟩ frames returnTo)
        (.running { evaluated with variables := parameterStore declaration.signature.parameters references }
          declaration.body (⟨evaluated.variables, ⟨rest, result⟩, returnTo⟩ :: frames) destination)
  | «return» {before evaluated result reference caller frames destination variables} :
      ResultEval classes before result evaluated reference →
      Deliver caller.variables destination reference variables →
      RawStep classes declarations
        (.running before ⟨[], result⟩ (caller :: frames) destination)
        (.running { evaluated with variables := variables } caller.body frames caller.destination)
  | exit {objects nextId variables} :
      RawStep classes declarations
        (.running ⟨objects, variables, nextId⟩ ⟨[], none⟩) ⟨objects, nextId, []⟩
Functions/Step:Step
inductive Step (classes : Classes) (declarations : Declarations) : Configuration → Configuration → Prop where
  | collect {before raw} : RawStep classes declarations before raw →
      Step classes declarations before raw.collect

A nested call suspends the current function just as the outer call suspended the program. Reusing a local name in different frames does not identify their storage slots:

class Token {}
fn identity(token: → Token) → Token {
    return token→;
}
fn relay(token: → Token) → Token {
    let answer = identity(token→);
    return answer→;
}

let token = new Token();
let result = relay(token→);

All three frames have a local named token. After both returns, the program’s token is empty and result owns the original object. Only the initial frame remains. The example checks typing, these observations after the calls, and the final exit step that pops this frame and empties the heap.

Functions/Checks:nested
example : ProgramTyped nestedProgram ∧
    Steps classes.erase nestedTable (.initial nestedProgram) nestedReturned ∧
    Step classes.erase nestedTable nestedReturned ⟨[], 1, []⟩ ∧
    nestedReturned.rootState.variables = [("result", some (.owned 0)), ("token", none)] ∧
    nestedReturned.frames.length = 1 :=
  ⟨nested_typed, nested_execution, by exact collected_step .exit (by simp), rfl, rfl⟩

Completion and recursion

This layer accepts a function that leaves its owned parameter initialized:

class Token {}
fn leave(token: → Token) { }

let t = new Token();
leave(t→);

Returning from leave pops its frame. The caller’s t is empty, so eager GC immediately reclaims the token, before the initial frame exits. Nothing invokes a destructor. Explicit unpacking is also accepted:

fn consume(token: → Token) {
    let Token → {} = token→;
}

The checks cover the first program’s typing and full execution, and the second function’s body typing. Mandatory consumption is added in the next layer; it is not a premise of these Functions rules.

Functions/Checks:completion
example : ProgramTyped leaveProgram ∧
    Steps classes.erase declarations (.initial leaveProgram) leaveReturned ∧
    Step classes.erase declarations leaveReturned ⟨[], 1, []⟩ ∧ leaveReturned.objects = [] ∧
    BodyTyped classes declarations consume.signature consume.body :=
  ⟨⟨by decide, declarations_typed, _, leave_main⟩, leave_execution,
    by exact collected_step .exit (by simp), rfl, consume_body⟩

The relation \(M\longrightarrow^{*}M'\) is the reflexive, transitive closure of steps, represented by zero steps or one step followed by a trace.

Functions/Step:Steps
inductive Steps (classes : Classes) (declarations : Declarations) : Configuration → Configuration → Prop where
  | refl (configuration : Configuration) : Steps classes declarations configuration configuration
  | step {before middle after} :
      Step classes declarations before middle → Steps classes declarations middle after →
      Steps classes declarations before after

A configuration is stuck when it is not finished and has no successor.

Functions/Step:Stuck
def Stuck (classes : Classes) (declarations : Declarations) (configuration : Configuration) : Prop :=
  ¬ configuration.finished ∧ ¬ ∃ after, Step classes declarations configuration after
fn recur() {
    recur();
}
recur();

This program checks. After any number of calls it can call again, adding one suspended caller. The formal example supplies an infinite sequence of adjacent steps, all reachable from the initial configuration and none finished. The Shared completion bound therefore does not extend to Functions.

Functions/Checks:recursion
example : ProgramTyped recursionProgram ∧
    (∀ depth, Steps classes.erase recursionTable (.initial recursionProgram) (recursionState depth)) ∧
    (∀ depth, Step classes.erase recursionTable (recursionState depth) (recursionState (depth + 1))) ∧
    (∀ depth, ¬ (recursionState depth).finished) := by
  refine ⟨⟨by decide, ?_, [], .cons recursive_statement (.nil (by decide))⟩,
    recursion_reachable, recursive_step, ?_⟩
  · refine ⟨by decide, ?_⟩
    intro entry member
    have : entry = (.function "recur", recur) := by simpa [recursionProgram, recursionTable] using member
    subst entry
    exact ⟨by decide, [], [], .cons recursive_statement (.nil (by decide)), .none (by decide)⟩
  · intro depth
    simp [recursionState, Configuration.finished, Configuration.running]

A finished configuration has no successor, for any declaration table.

Functions/Step:finished_no_step
theorem finished_no_step (finished : configuration.finished) :
    ¬ Step classes declarations configuration after := by
  intro step
  cases step with
  | collect raw => cases raw <;> simp_all [Configuration.finished, Configuration.running]

If a machine step reaches a finished configuration, its heap is empty. The allocation counter need not be zero. This theorem concerns the targets of steps; an arbitrary hand-written configuration with no frames need not already have been collected.

Functions/Step:terminal_heap_empty
theorem terminal_heap_empty (step : Step classes declarations before after)
    (finished : after.finished) : after.objects = [] := by
  cases step with
  | collect raw =>
    cases raw <;> simp_all [Configuration.finished, Configuration.running,
      Configuration.collect_frames, Configuration.collect_empty_frames]

Embed a Shared program configuration with the same heap and allocation counter. Its live frame becomes a one-element Functions stack with no result or return destination; its absent frame becomes an empty stack. Wrap each statement as a local statement.

Under any callable table, every Shared step has its corresponding Functions step. Conversely, every Functions successor of an embedded configuration is exactly the embedding of a Shared successor. This includes collection and the initial-frame exit, and quantifies over arbitrary successors and starting states. There is no extra Functions-only completion step: both layers pop their initial frame and collect at the same boundary.

Correspondence/SharedFunctionsFrames:framed_step_correspondence
theorem framed_step_correspondence :
    Functions.Step classes declarations (embedFramed before) after ↔
      ∃ successor, Framed.Step (Framed.patternOperation classes) before successor ∧ after = embedFramed successor := by
  constructor
  · exact framed_step_backward
  · rintro ⟨successor, step, rfl⟩
    exact framed_step_forward step

Every finite Functions trace from an embedded Shared program configuration has a Shared trace to a configuration whose embedding is exactly the Functions endpoint. This includes finished configurations with no frames or heap objects; no well-formedness restriction is needed for this correspondence.

Correspondence/SharedFunctionsFrames:framed_steps_backward
theorem framed_steps_backward (steps : Functions.Steps classes declarations start after) :
    ∀ before, start = embedFramed before →
      ∃ successor, Framed.Steps (Framed.patternOperation classes) before successor ∧ after = embedFramed successor := by
  induction steps with
  | refl => intro before equality; exact ⟨before, ⟨0, .refl _⟩, equality⟩
  | step first _ ih =>
    intro before equality
    subst equality
    obtain ⟨middle, original, rfl⟩ := framed_step_backward first
    obtain ⟨last, ⟨count, rest⟩, equality⟩ := ih middle rfl
    exact ⟨last, ⟨count + 1, .step original rest⟩, equality⟩

For any initial and final environments, nominal table, and callable table, a sequence containing only embedded Shared statements checks in Functions if and only if the original sequence checks in Shared.

Correspondence/SharedFunctions:typing_correspondence
theorem typing_correspondence :
    Functions.SequenceTyped classes declarations before (code.map Functions.Statement.local) after ↔
      Typing.SequenceTyped classes before code after :=
  ⟨fun typed => typing_backward typed code rfl, typing_forward⟩

A Shared program configuration is finished exactly when its Functions embedding is finished. Both conditions mean the initial frame has been popped.

Correspondence/SharedFunctionsFrames:framed_finished_correspondence
theorem framed_finished_correspondence :
    (embedFramed configuration).finished ↔ configuration.finished := by
  rcases configuration with ⟨objects, nextId, frame⟩
  cases frame <;> simp [embedFramed, Functions.Configuration.finished, Framed.Configuration.finished]

A Shared program configuration is stuck exactly when its Functions embedding is stuck, for any nominal and callable tables. An exhausted live frame can take its exit step in both layers; an absent frame is finished in both.

Correspondence/SharedFunctionsFrames:framed_stuck_correspondence
theorem framed_stuck_correspondence :
    Functions.Stuck classes declarations (embedFramed configuration) ↔
      Framed.Stuck (Framed.patternOperation classes) configuration := by
  simp only [Functions.Stuck, Framed.Stuck, framed_finished_correspondence]
  constructor
  · rintro ⟨unfinished, noStep⟩
    exact ⟨unfinished, fun ⟨after, step⟩ => noStep ⟨_, framed_step_forward step⟩⟩
  · rintro ⟨unfinished, noStep⟩
    refine ⟨unfinished, ?_⟩
    rintro ⟨after, step⟩
    obtain ⟨successor, original, _⟩ := framed_step_backward step
    exact noStep ⟨successor, original⟩

Safety across calls

The nested relay/identity example uses token in three different frames. The safety check now covers every finite execution prefix of that program: the whole stack remains well typed, and execution cannot get stuck. It also checks the returned initial frame and the empty terminal state after its exit. The following stack-typing definition explains what being well typed means for a suspended caller whose result has not arrived yet.

Functions/SafetyChecks:nested_safety
example :
    (∀ configuration, Steps classes.erase nestedTable (.initial nestedProgram) configuration →
      ConfigurationTyped classes nestedTable configuration ∧ ¬ Stuck classes.erase nestedTable configuration) ∧
    ConfigurationTyped classes nestedTable nestedReturned ∧
    ConfigurationTyped classes nestedTable ⟨[],1,[]⟩ := by
  refine ⟨fun configuration trace => ?_, ?_, ?_⟩
  · have safe := program_safety nested_typed trace
    exact ⟨safe.1,safe.2.2⟩
  · exact (program_safety nested_typed nested_execution).1
  · have exit : RawStep classes.erase nestedTable nestedReturned ⟨nestedReturned.objects,1,[]⟩ := .exit
    have collected := Step.collect exit
    simp only [Configuration.collect_empty_frames] at collected
    exact (program_safety nested_typed nested_execution).1.preservation collected

A typed store pairs a frame’s environment with its runtime locals, in order. Their names agree, empty descriptions have empty slots, and each initialized slot pairs a reference with its type. Write \(\mathcal R\) for the resulting list of reference/type pairs. These are the frame’s typed roots.

The list retains occurrences: two shared aliases contribute two roots even when their references are equal. This relation only pairs names, slots, and types; it does not itself require distinct names or check the heap.

Functions/Realization:Slots
inductive Slots : Environment → Store → PendingValues → Prop where
  | nil : Slots [] [] []
  | empty {environment variables roots} (name) : Slots environment variables roots →
      Slots ((name, none) :: environment) ((name, none) :: variables) roots
  | value {environment variables roots} (name reference ty) : Slots environment variables roots →
      Slots ((name, some ty) :: environment) ((name, some reference) :: variables) ((reference, ty) :: roots)

Write \(\Delta;F\vdash M\ \mathsf{ok}\) when the machine is well typed. Its nominal and callable tables must check. The remaining requirements are:

ComponentRequirement
Active frameIts locals form a typed store; its remaining statements and return expression check from that environment to its promised optional result type.
Suspended callerIts stored locals form a typed store before delivery. The delivery typing judgment checks the destination against the callee’s promised result type. Its remaining body checks from the environment after delivery.
Outer callersThe same condition repeats down the stack, using each caller’s own result destination and promised result type.
Initial frameIts result and destination are absent; there is no caller below it.
Common heapShared realization holds with an empty variable environment and all frames’ typed roots as pending values.

Thus the heap counts every owner, including those in suspended callers, while expression evaluation sees only the active frame’s locals. Realization checks reference modes and views, nominal field types, object layouts, allocation bounds, and compatibility of owning occurrences. A finished stack has no roots.

The Lean BodyFrom judgment checks a remaining body from a given environment. ContinuationTyped checks the suspended callers, StackShape adds the active frame (or an empty stack), and ConfigurationTyped joins those checks to heap realization. None assumes a future execution or successful runtime operation.

Functions/StackTyping:BodyFrom
def BodyFrom (classes : ClassTable) (declarations : Declarations) (environment : Environment)
    (body : Body) (result : Option FieldType) : Prop :=
  ∃ middle final, SequenceTyped classes declarations environment body.statements middle ∧
    ResultTyped classes middle body.result result final
Functions/StackTyping:ContinuationTyped
inductive ContinuationTyped (classes : ClassTable) (declarations : Declarations) : Option VariableId → Option FieldType → List Frame → PendingValues → Prop where
  | done : ContinuationTyped classes declarations none none [] []
  | caller {destination result caller rest environment resumed roots laterRoots callerResult} :
      Slots environment caller.variables roots → environment.WellFormed classes →
      DestinationTyped classes environment destination result resumed →
      BodyFrom classes declarations resumed caller.body callerResult →
      ContinuationTyped classes declarations caller.destination callerResult rest laterRoots →
      ContinuationTyped classes declarations destination result (caller :: rest) (roots ++ laterRoots)
Functions/StackTyping:StackShape
inductive StackShape (classes : ClassTable) (declarations : Declarations) : List Frame → PendingValues → Prop where
  | done : StackShape classes declarations [] []
  | active {frame rest environment roots laterRoots result} :
      Slots environment frame.variables roots → environment.WellFormed classes →
      BodyFrom classes declarations environment frame.body result →
      ContinuationTyped classes declarations frame.destination result rest laterRoots →
      StackShape classes declarations (frame :: rest) (roots ++ laterRoots)
Functions/StackTyping:ConfigurationTyped
def ConfigurationTyped (classes : ClassTable) (declarations : Declarations) (configuration : Configuration) : Prop :=
  classes.WellFormed ∧ DeclarationsTyped classes declarations ∧
  ∃ roots, StackShape classes declarations configuration.frames roots ∧
    Realizes classes [] (heapState configuration.rootState) roots
Functions/Realization:heapState
def heapState (state : State) : State := ⟨state.objects,[],state.nextId⟩

A well-typed machine is finished or has a successor:

\[ \Delta;F\vdash M\ \mathsf{ok} \quad\Longrightarrow\quad \mathsf{Finished}(M)\ \lor\ \exists M'.\ M\longrightarrow M'. \]

This includes calls, returns, and the initial-frame exit. The transition uses the erased nominal table and the same callable table as the typing judgment.

Functions/Safety:ConfigurationTyped.progress
theorem ConfigurationTyped.progress {configuration : Configuration}
    (typed : ConfigurationTyped classes declarations configuration) :
    configuration.finished ∨ ∃ after, Step classes.erase declarations configuration after := by
  rcases configuration with ⟨objects,nextId,frames⟩
  obtain ⟨classesWf,declarationsWf,roots,shape,heap⟩ := typed
  cases shape with
  | done => exact .inl rfl
  | @active frame rest environment localRoots laterRoots result slots envWf body continuation =>
    have realized := from_heap heap slots envWf
    rcases frame with ⟨variables,frameBody,destination⟩
    rcases frameBody with ⟨code,returnValue⟩
    obtain ⟨middle,final,sequence,returned⟩ := body
    right
    cases code with
    | cons first restCode =>
      cases sequence with
      | cons firstTyped tail =>
        cases firstTyped with
        | «local» localTyped =>
          cases localTyped with
          | letValue expression binding =>
            obtain ⟨evaluated,reference,evaluation⟩ := (expression.sound _ _ realized).1
            have evaluatedRealized := (expression.sound _ _ realized).2 _ _ evaluation
            obtain ⟨after,operation⟩ := binding.exists_bind_pending evaluatedRealized
            exact ⟨_,.collect (.local (.letValue evaluation operation))⟩
        | call declared fresh args dest =>
          obtain ⟨evaluated,references,evaluation⟩ := (args.sound _ _ realized).1
          exact ⟨_,.collect (.call declared dest.shape
            (fun x member occupied => fresh x member ((realized.variableDomain x).mpr occupied))
            evaluation (by simpa using evaluation.length.trans args.length))⟩
    | nil =>
      cases sequence with
      | nil _ =>
        obtain ⟨evaluated,reference,evaluation,resultShape⟩ := returned.exists_eval realized
        cases continuation with
        | done =>
          cases returned with
          | none _ => exact ⟨_,.collect .exit⟩
        | caller callerSlots _ delivery _ _ =>
          obtain ⟨variables,delivered⟩ := delivery.exists_deliver callerSlots resultShape
          exact ⟨_,.collect (.return evaluation delivered)⟩

Every machine step preserves machine typing:

\[ \frac{\Delta;F\vdash M\ \mathsf{ok}\qquad M\longrightarrow M'} {\Delta;F\vdash M'\ \mathsf{ok}}. \]

This quantifies over every operational successor. Calls transfer argument roots to a new frame; returns deliver the result and remove the callee. Eager collection is part of the step. Objects reachable only from discarded locals can disappear, while the returned value and surviving callers retain their views and ownership guarantees.

Functions/Safety:ConfigurationTyped.preservation
theorem ConfigurationTyped.preservation {before after : Configuration}
    (typed : ConfigurationTyped classes declarations before)
    (step : Step classes.erase declarations before after) :
    ConfigurationTyped classes declarations after := by
  cases step with
  | collect raw => exact raw.preserves typed

In a well-typed machine, the references in all live frame slots and object fields are pairwise compatible. Distinct owning occurrences can target the same object only when both are shared. Every referenced object is allocated, and every allocated object has an incoming reference from a frame or field. These statements count all frames without requiring their local names to be globally distinct.

Functions/Safety:ConfigurationTyped.ownership
theorem ConfigurationTyped.ownership {configuration : Configuration}
    (typed : ConfigurationTyped classes declarations configuration) :
    (Owners configuration.rootState).Pairwise Compatible ∧
    (∀ id, id ∈ References configuration.rootState ↔ Allocated configuration.rootState id) := by
  obtain ⟨_,_,roots,shape,heap⟩ := typed
  have refs := shape.references
  constructor
  · simpa only [Owners,heapState,List.filterMap_nil,List.nil_append,refs,
      Configuration.rootState] using heap.ownership.ownersCompatible
  · intro id
    have complete := heap.ownership.referencesComplete id
    simpa only [heapState,References,List.filterMap_nil,List.nil_append,refs,
      Configuration.rootState,Allocated,List.map_append,List.map_filterMap,Function.comp_def] using complete

A well-typed finished configuration has an empty heap. Its initial frame has been popped, so no locals remain. The allocation counter is retained. This strengthens the earlier step-target result to every configuration satisfying the stack typing judgment.

Functions/Safety:ConfigurationTyped.finished_heap_empty
theorem ConfigurationTyped.finished_heap_empty {configuration : Configuration}
    (typed : ConfigurationTyped classes declarations configuration)
    (finished : configuration.finished) : configuration.objects = [] := by
  rcases configuration with ⟨objects,nextId,frames⟩
  change frames = [] at finished
  subst frames
  obtain ⟨_,_,roots,shape,heap⟩ := typed
  cases shape
  have same := State.collect_eq_self heap.ownership.no_pending
  rw [heapState,State.collect_no_variables] at same
  exact (congrArg State.objects same).symm

For a well-typed program, every configuration reached by a finite execution from its initial configuration remains well typed and is finished or can step. Consequently no such execution reaches a stuck configuration.

The theorem permits recursion and does not assert termination or a step bound. It starts from ordinary program typing; there is no operational-success premise added to function or method declarations.

Functions/Safety:program_safety
theorem program_safety (typed : ProgramTyped program)
    (trace : Steps program.classes.erase program.declarations (.initial program) configuration) :
    ConfigurationTyped program.classes program.declarations configuration ∧
    (configuration.finished ∨ ∃ after, Step program.classes.erase program.declarations configuration after) ∧
    ¬ Stuck program.classes.erase program.declarations configuration := by
  have preserved := (ConfigurationTyped.initial typed).trace trace
  have progress := preserved.progress
  refine ⟨preserved,progress,?_⟩
  intro stuck
  rcases progress with finished | successor
  · exact stuck.1 finished
  · exact stuck.2 successor

For the earlier recur() program, the machine remains well typed and is not stuck at every recursion depth. Each such state takes the next recursive-call step. Safety therefore holds along the infinite execution already exhibited by the example, despite the growing stack.

Functions/SafetyChecks:recursion_safety
example : ∀ depth,
    ConfigurationTyped classes recursionTable (recursionState depth) ∧
    ¬ Stuck classes.erase recursionTable (recursionState depth) ∧
    Step classes.erase recursionTable (recursionState depth) (recursionState (depth+1)) := by
  intro depth
  have safe := program_safety recursion_typed (recursion_reachable depth)
  exact ⟨safe.1,safe.2.2,recursive_step depth⟩

Later permissions and defaults

The intended permission design extends the current owned permissions with two independent distinctions:

UniqueShared
Ownedgiven, spelled → in signaturesshared[], abbreviated shared
Leasedmut[places...]shared[places...]

The eventual mutable access expression is p!, including p!method(...). A bare place expression p will abbreviate p.share, producing shared[p]; p.method(...) will use that borrowed receiver. Applying share to a value, as in p→share, instead produces owned shared[] access.

Receiver declarations keep permissions in prefix position:

fn method(→self, arg: → Foo)
fn method(!self, arg: !Foo)
fn method(shared self, arg: shared Foo)
fn method(self, arg: Foo)
fn method[perm P](P self, arg: P Foo)

Bare argument types and bare self are intended to introduce generic permissions constrained to support reading, rather than assume unique ownership. The constraint’s name and exact meaning remain to be designed; readable(P) is a candidate, not an established predicate. These defaults, leases, permission parameters, where-clauses, and permission-based method overloading are outside the initial Functions layer.

Appendix: inherited Shared machinery

The call machine and its typing judgments live in Functions/. They explicitly use Shared’s call-free expressions, storage, and binding judgments. There is no change to those definitions in this layer:

MachineryInherited behavior
Nominal kindsClasses cannot be shared; struct fields have struct types.
StorageReferences carry modes; slots hold a reference or are empty; allocation is monotonic.
ViewsPositive entries expose whole subtrees, negative entries record empty slots, and omissions are unknown.
GivingUnique access moves; shared access copies, promoting a unique final stored reference when necessary.
ExpressionsConstructor arguments are evaluated left to right and require whole declared types. Shared structs construct shared references immediately.
UnpackingUnpacking requires unique access and known status for every direct field, removes the container, and transfers its field slots to fresh bindings.

The call syntax, frame stores, and call/return judgments are defined separately in Functions. Assignments, destructors, branches, loops, and borrowing remain outside this layer.

Shared/Syntax:Value
inductive Value where
  | give (source : Place)
  | giveShare (source : Place)
  | new (className : ClassName) (arguments : List Value)
  deriving Repr
Shared/State:State
structure State where
  objects : List (ObjectId × Object)
  variables : List (VariableId × Slot)
  nextId : Nat
  deriving DecidableEq, Repr
Shared/Step:Give
inductive Give : State → Place → Reference → State → Prop where
  | move {state cleared : State} {path : Place} {source : StoragePlace} {object : ObjectId} :
      Resolve state path source object .unique →
      Take state source object cleared →
      Give state path (.owned object) cleared
  | copy {state : State} {path : Place} {source : StoragePlace} {object : ObjectId} :
      Resolve state path source object .shared →
      Stored state source (some (.shared object)) →
      Give state path (.shared object) state
  | promote {state promoted : State} {path : Place} {source : StoragePlace} {object : ObjectId} :
      Resolve state path source object .shared →
      Promote state source object promoted →
      Give state path (.shared object) promoted
Shared/Step:Eval
inductive Eval (classes : Classes) : State → Value → State → Reference → Prop where
  | give {state evaluated : State} {path : Place} {reference : Reference} :
      Give state path reference evaluated →
      Eval classes state (.give path) evaluated reference
  | giveShare {state evaluated : State} {path : Place} {reference : Reference} :
      Give state path reference evaluated →
      StructReference classes evaluated reference →
      Eval classes state (.giveShare path) evaluated (.shared reference.object)
  | new {state evaluated : State} {className : ClassName} {declaration : Class}
      {arguments : List Value} {references : List Reference} :
      (className, declaration) ∈ classes →
      EvalArgs classes state arguments evaluated references →
      references.length = declaration.fields.length →
      ObjectId.mk evaluated.nextId ∉ evaluated.objects.map Prod.fst →
      StructArguments classes evaluated declaration.kind references →
      Eval classes state (.new className arguments)
        (evaluated.allocate className declaration.fields references) (⟨declaration.kind.mode, ⟨evaluated.nextId⟩⟩)
Shared/Step:EvalArgs
inductive EvalArgs (classes : Classes) : State → List Value → State → List Reference → Prop where
  | nil (state : State) : EvalArgs classes state [] state []
  | cons {before middle after : State} {argument : Value} {arguments : List Value}
      {reference : Reference} {references : List Reference} :
      Eval classes before argument middle reference →
      EvalArgs classes middle arguments after references →
      EvalArgs classes before (argument :: arguments) after (reference :: references)
Shared/Unpacking:Pattern
inductive Pattern where
  | variable (name : VariableId)
  | unpack (className : ClassName) (fields : List (FieldName × VariableId))
  deriving DecidableEq, Repr
Shared/Unpacking:Bind
inductive Bind (classes : Classes) : State → Reference → Pattern → State → Prop where
  | variable {state object name} :
      name ∉ state.variables.map Prod.fst →
      Bind classes state object (.variable name) (state.bind name object)
  | unpack {before after variables nextId object className fields pattern bindings declaration} :
      (className, declaration) ∈ classes →
      fields.map Prod.fst = declaration.fields →
      (pattern.map Prod.fst).Nodup →
      (pattern.map Prod.snd).Nodup →
      (∀ name ∈ pattern.map Prod.snd, name ∉ variables.map Prod.fst) →
      Transfer pattern fields bindings →
      Bind classes ⟨before ++ (object, ⟨className, fields⟩) :: after, variables, nextId⟩
        (.owned object) (.unpack className pattern)
        ⟨before ++ after, bindings ++ variables, nextId⟩
Shared/Typing:ExprTyped
inductive ExprTyped (classes : ClassTable) : Environment → Value → ValueType → Environment → Prop where
  | give {before after : Environment} {place : Place} {ty : ValueType} :
      before.WellFormed classes →
      Typing.give classes before place = some (ty, after) →
      Admissible classes ty → after.WellFormed classes →
      ExprTyped classes before (.give place) ty after
  | giveShare {before after : Environment} {place : Place} {ty : ValueType} :
      before.WellFormed classes →
      Typing.give classes before place = some (ty, after) →
      Admissible classes ty → after.WellFormed classes →
      StructType classes ty →
      ExprTyped classes before (.giveShare place) ty.shared after
  | new {before after : Environment} {name : ClassName} {declaration : TypedClass}
      {arguments : List Value} :
      (name, declaration) ∈ classes →
      ArgsTyped classes before arguments (declaration.fields.map Prod.snd) after →
      Admissible classes (ValueType.whole name (initialPermission declaration.kind)) →
      (declaration.kind.isStruct = true →
        ∀ field ∈ declaration.fields, StructType classes field.2.toType) →
      ExprTyped classes before (.new name arguments)
        (ValueType.whole name (initialPermission declaration.kind)) after
  | weaken {before after : Environment} {value : Value} {ty other : ValueType} :
      ExprTyped classes before value ty after →
      Admissible classes other → Subtype classes ty other →
      ExprTyped classes before value other after
Shared/Typing:ArgsTyped
inductive ArgsTyped (classes : ClassTable) : Environment → List Value → List FieldType → Environment → Prop where
  | nil {environment : Environment} :
      environment.WellFormed classes → ArgsTyped classes environment [] [] environment
  | cons {before middle after : Environment} {value : Value} {values : List Value}
      {field : FieldType} {fields : List FieldType} :
      ExprTyped classes before value field.toType middle →
      ArgsTyped classes middle values fields after →
      ArgsTyped classes before (value :: values) (field :: fields) after

Destructors

Every owned class value needs an ending

Before a body finishes, it must account for every class value it owns. Unpacking consumes a container and transfers responsibility for its fields to local bindings. Dropping delegates that work to the class’s destructor. Moving a value to another local merely transfers the responsibility.

Start with classes that have no destructors:

class Token {}
class Pair { left: Token, right: Token }

let pair = new Pair(new Token(), new Token());
let Pair → { left, right } = pair→;
let Token → {} = left→;
let Token → {} = right→;

This program checks: unpacking consumes the pair, then each token. If either of the last two statements is omitted, the body cannot finish. The corresponding token is still owned by a local binding. Unpacking the outer container alone does not consume the contents. Since these classes have no destructors, replacing an unpack with drop is not permitted.

Likewise, ending the body with let other = right→; instead of unpacking right would leave other responsible for that token. The obligation follows the value. Struct values are exempt from this requirement; their storage is treated as garbage collected.

Destructors/ChapterChecks:consumption
example : ProgramTyped pairProgram ∧
    ¬ Finished classes [("right",some (.whole "Token")),("left",none),("pair",none)] ∧
    ¬ Finished classes [("other",some (.whole "Token")),("right",none),("left",none),("pair",none)] ∧
    ¬ Droppable classes declarations (.whole "Token") := by
  refine ⟨pair_typed, ?_, ?_, by decide⟩
  · intro h; exact (by decide : ¬ StructType classes (.whole "Token")) (h "right" _ (by simp))
  · intro h; exact (by decide : ¬ StructType classes (.whole "Token")) (h "other" _ (by simp))

Delegating consumption to a destructor

A destructor lets a class say how to finish using an instance. This layer makes that work explicit: a class value must be moved, unpacked, or dropped before its frame finishes. Declaring a destructor does not arrange an automatic call.

class Resource {
    drop {
        let Resource → {} = self→;
    }
}
class Wrapper {
    resource: Resource
    drop {
        let Wrapper → { resource } = self→;
        drop resource;
    }
}

let w = new Wrapper(new Resource());
drop w;

The execution moves w into the wrapper destructor’s self binding. Unpacking consumes the wrapper container and transfers its field to resource. Dropping that field invokes the resource destructor, whose unpack consumes the resource container. Both destructor calls then finish, and w has been emptied by the drop before the initial program frame exits. Nothing implicitly destroys the receiver or its fields.

This chapter introduces the new behavior first. The explicit forward references to the inherited machinery in the appendix keep Shared’s unchanged rules from obscuring that behavior. The appendix states which rules carry over and supplies their definitions in Shared.

Destructors/ExecutionChecks:wrapper_consumed
example : ProgramTyped wrapperProgram ∧
    Steps classes.erase declarations (.initial wrapperProgram) ⟨[],2,[]⟩ :=
  ⟨wrapper_typed, wrapper_execution⟩

Parameters and locals in a function

Using the preceding Functions chapter, these examples add the consumption requirement to ordinary function bodies. They use the Wrapper and Resource declarations above. Both an owned parameter and a locally created class value must be accounted for before the function returns.

One version explicitly unpacks everything:

fn finish(w: → Wrapper) {
    let extra = new Resource();
    let Wrapper → { resource } = w→;
    let Resource → {} = resource→;
    let Resource → {} = extra→;
}

Another delegates the work to destructors:

fn finish(w: → Wrapper) {
    let extra = new Resource();
    drop w;
    drop extra;
}

Either version can be called with an owned wrapper:

let w = new Wrapper(new Resource());
finish(w→);

These are alternative bodies. In either version, omitting the consumption of extra would leave an owned class value at return. Merely having a destructor would not make that omission legal in this explicit core. Likewise, unpacking w and leaving resource unconsumed would fail to account for its contents.

The requirement applies to program, function, method, and destructor bodies. A function can also transfer ownership to its caller by returning a value; check its remaining locals after evaluating that return expression.

Destructors/OpeningChecks:function_call
example : BodyTyped classes declarations finish.signature finish.body ∧
    BodyTyped classes declarations unpackFinish.signature unpackFinish.body ∧
    ProgramTyped finishProgram := by
  refine ⟨finish_body,unpackFinish_body,by decide,declarations_typed,[("w",none)],?_,by simp [Finished]⟩
  apply SequenceTyped.cons (middle := [("w",some (.whole "Wrapper"))])
  · apply StatementTyped.local
    apply Shared.Typing.StatementTyped.letValue (middle := []) (ty := .whole "Wrapper")
    · apply ExprTyped.new (declaration := ⟨[("resource",⟨.given,"Resource"⟩)],.classType⟩) (by decide)
      · exact .cons (.new (declaration := ⟨[],.classType⟩) (by decide) (.nil (by decide)) (by decide) (by decide)) (.nil (by decide))
      · decide
      · decide
    · exact .variable (by decide) (by decide) (by decide)
  · apply SequenceTyped.cons
    · exact .call (declaration := finish) (middle := [("w",none)])
        (by simp [finishProgram,declarations]) (by simp)
        (.cons (.give (by decide) (by decide) (by decide) (by decide)) (.nil (by decide))) (.none (by decide))
    · exact .nil (by decide)

Returning transfers the obligation to the caller

A function can return an owned value instead of destroying it. Using the Resource destructor above:

fn identity(token: → Resource) → Resource {
    return token→;
}

let original = new Resource();
let returned = identity(original→);
drop returned;

The call empties original. Returning empties the callee’s token binding, so the function can finish even though the resource is still alive. The caller now owns it through returned; the final drop consumes it. Omitting that drop would leave the caller with an outstanding class value. Returning transfers responsibility; it does not invoke the destructor.

Destructors/OpeningChecks:ownership_return
example : ProgramTyped returningProgram ∧
    ¬ Finished classes [("returned",some (.whole "Resource")),("original",none)] := by
  constructor
  · refine ⟨by decide, ?_, [("returned",none),("original",none)], ?_, by simp [Finished]⟩
    · constructor
      · decide
      · intro entry member
        simp only [returningProgram,returningTable,List.mem_cons,List.not_mem_nil,or_false] at member
        rcases member with rfl | rfl
        · refine ⟨⟨by decide,by decide,by decide,by decide⟩, ?_⟩
          exact ⟨_,[("token",none)],.nil (by decide),
            .some (.give (by decide) (by decide) (by decide) (by decide)),by simp [Finished]⟩
        · refine ⟨⟨by decide,by decide,by decide,rfl,⟨⟨[],.classType⟩,by decide,rfl⟩⟩,?_,?_,?_,?_,?_⟩
          · exact [("self",none)]
          · exact [("self",none)]
          · apply SequenceTyped.cons
            · apply StatementTyped.local
              apply Shared.Typing.StatementTyped.letValue (middle := [("self",none)]) (ty := .whole "Resource")
              · exact .give (by decide) (by decide) (by decide) (by decide)
              · exact .unpack (declaration := ⟨[],.classType⟩) (bindings := [])
                  (by decide) (by decide) rfl rfl (by decide) (by decide) (by decide) (by decide) .nil (by decide)
            · exact .nil (by decide)
          · exact .none (by decide)
          · simp [Finished]
    · apply SequenceTyped.cons (middle := [("original",some (.whole "Resource"))])
      · apply StatementTyped.local
        apply Shared.Typing.StatementTyped.letValue (middle := []) (ty := .whole "Resource")
        · exact .new (declaration := ⟨[],.classType⟩) (by decide) (.nil (by decide)) (by decide) (by decide)
        · exact .variable (by decide) (by decide) (by decide)
      · apply SequenceTyped.cons (middle := [("returned",some (.whole "Resource")),("original",none)])
        · exact .call (declaration := returningResource) (middle := [("original",none)])
            (by simp [returningProgram,returningTable]) (by decide)
            (.cons (.give (by decide) (by decide) (by decide) (by decide)) (.nil (by decide)))
            (.some (.variable (by decide) (by decide) (by decide)))
        · apply SequenceTyped.cons
          · exact .call (declaration := resource) (middle := [("returned",none),("original",none)])
              (by simp [returningProgram,returningTable]) (by simp)
              (.cons (.give (by decide) (by decide) (by decide) (by decide)) (.nil (by decide)))
              (.none (by decide))
          · exact .nil (by decide)
  · intro h
    exact (by decide : ¬ StructType classes (.whole "Resource")) (h "returned" _ (by simp))

Dropping unique and shared structs

Structs do not run destructor code in this layer. An explicit drop uses ordinary give and discards the resulting reference:

struct Point {}
shared struct SharedPoint {}

let p = new Point();
let s = new SharedPoint();
drop p;
drop s;

p starts uniquely owned. Dropping it empties its binding, so a subsequent p→ would be rejected. s starts shared; dropping it copies and discards a reference, leaving s initialized. A subsequent s→ is still allowed. Neither drop removes the local binding or calls user code.

The program may finish with s still initialized. Struct locals need no explicit consumption, and GC handles their storage.

Destructors/OpeningChecks:struct_program
example : SequenceTyped classes [] [] structProgram.main structFinal ∧
    Finished classes structFinal ∧
    (∀ ty after, ¬ ExprTyped classes structFinal (.give (.variable "p")) ty after) ∧
    ExprTyped classes structFinal (.give (.variable "s")) (.whole "SharedPoint" .shared) structFinal := by
  refine ⟨?_,?_,?_,.give (by decide) (by decide) (by decide) (by decide)⟩
  · apply SequenceTyped.cons (middle := [("p",some (.whole "Point"))])
    · apply StatementTyped.local
      apply Shared.Typing.StatementTyped.letValue (middle := []) (ty := .whole "Point")
      · exact .new (declaration := ⟨[],.structType⟩) (by decide) (.nil (by decide)) (by decide) (by decide)
      · exact .variable (by decide) (by decide) (by decide)
    · apply SequenceTyped.cons (middle := [("s",some (.whole "SharedPoint" .shared)),("p",some (.whole "Point"))])
      · apply StatementTyped.local
        apply Shared.Typing.StatementTyped.letValue (middle := [("p",some (.whole "Point"))]) (ty := .whole "SharedPoint" .shared)
        · exact .new (declaration := ⟨[],.sharedStruct⟩) (by decide) (.nil (by decide)) (by decide) (by decide)
        · exact .variable (by decide) (by decide) (by decide)
      · exact .cons (middle := structFinal) (.dropStruct (ty := .whole "Point") (.give (by decide) (by decide) (by decide) (by decide)) (by decide))
          (.cons (.dropStruct (ty := .whole "SharedPoint" .shared) (.give (by decide) (by decide) (by decide) (by decide)) (by decide)) (.nil (by decide)))
  · intro name ty member
    have eq : name = "s" ∧ ty = .whole "SharedPoint" .shared := by simpa [structFinal] using member
    rcases eq with ⟨rfl,rfl⟩
    decide
  · intro ty after
    exact failed_give_not_typed (by decide)

A class destructor can leave struct locals

The distinction between classes and structs also matters inside a destructor. Using the SharedPoint declaration above:

class Parcel {
    point: shared SharedPoint

    drop {
        let Parcel → { point } = self→;
    }
}

Unpacking consumes the class container and transfers its field into the local point. The destructor may then finish with point still initialized because it is a struct value. It needs no drop point. This is different from the Wrapper destructor, whose unpacked resource is a class and must be consumed.

Destructors/OpeningChecks:struct_field
example : parcelClasses.WellFormed ∧
    Signature.WellFormed parcelClasses (.destructor "Parcel") parcel.signature ∧
    BodyTyped parcelClasses [(.destructor "Parcel",parcel)] parcel.signature parcel.body := by
  refine ⟨by decide,⟨by decide,by decide,by decide,rfl,⟨⟨[("point",⟨.shared,"SharedPoint"⟩)],.classType⟩,by decide,rfl⟩⟩,?_,?_,?_,?_,?_⟩
  · exact [("point",some (.whole "SharedPoint" .shared)),("self",none)]
  · exact [("point",some (.whole "SharedPoint" .shared)),("self",none)]
  · apply SequenceTyped.cons
    · apply StatementTyped.local
      apply Shared.Typing.StatementTyped.letValue (middle := [("self",none)]) (ty := .whole "Parcel")
      · exact .give (by decide) (by decide) (by decide) (by decide)
      · exact .unpack (declaration := ⟨[("point",⟨.shared,"SharedPoint"⟩)],.classType⟩)
          (bindings := [("point",some (.whole "SharedPoint" .shared))])
          (by decide) (by decide) rfl rfl (by decide) (by decide) (by decide) (by decide)
          (.cons (by decide) .nil) (by decide)
    · exact .nil (by decide)
  · exact .none (by decide)
  · intro name ty member
    have eq : name = "point" ∧ ty = .whole "SharedPoint" .shared := by simpa using member
    rcases eq with ⟨rfl,rfl⟩
    decide

Unpacking after moving a field

A destructor receives a whole instance. Moving out a field of the Wrapper above leaves a partial value, so its destructor can no longer be called. Explicit unpacking can still consume the container:

fn consume(w: → Wrapper) {
    let taken = w.resource→;
    // drop w;  // rejected: resource has been moved out
    let Wrapper → { resource } = w→;
    drop taken;
}

The move transfers the resource to taken and records an empty field in w. The unpacking rule transfers that empty field into an empty resource binding; it does not recreate a value. Dropping taken consumes the resource itself. All three locals are empty when the function finishes.

Destructors/OpeningChecks:partial_cleanup
example : BodyTyped classes declarations consumePartial.signature consumePartial.body ∧
    Shared.Typing.give classes [("w",some (.whole "Wrapper"))] (.field (.variable "w") "resource") =
      some (.whole "Resource",[("w",some partialWrapper)]) ∧
    ¬ Droppable classes declarations partialWrapper := by
  refine ⟨?_,by decide,by decide⟩
  refine ⟨[("resource",none),("taken",none),("w",none)],
    [("resource",none),("taken",none),("w",none)],?_,.none (by decide),by simp [Finished]⟩
  apply SequenceTyped.cons (middle := [("taken",some (.whole "Resource")),("w",some partialWrapper)])
  · apply StatementTyped.local
    apply Shared.Typing.StatementTyped.letValue (middle := [("w",some partialWrapper)]) (ty := .whole "Resource")
    · exact .give (by decide) (by decide) (by decide) (by decide)
    · exact .variable (by decide) (by decide) (by decide)
  · apply SequenceTyped.cons (middle := [("resource",none),("taken",some (.whole "Resource")),("w",none)])
    · apply StatementTyped.local
      apply Shared.Typing.StatementTyped.letValue (middle := [("taken",some (.whole "Resource")),("w",none)]) (ty := partialWrapper)
      · exact .give (by decide) (by decide) (by decide) (by decide)
      · exact .unpack (declaration := ⟨[("resource",⟨.given,"Resource"⟩)],.classType⟩)
          (bindings := [("resource",none)])
          (by decide) (by decide) rfl rfl (by decide) (by decide) (by decide) (by decide)
          (.cons (by decide) .nil) (by decide)
    · apply SequenceTyped.cons
      · exact .call (declaration := resource) (middle := [("resource",none),("taken",none),("w",none)])
          (by simp [declarations]) (by simp)
          (.cons (.give (by decide) (by decide) (by decide) (by decide)) (.nil (by decide))) (.none (by decide))
      · exact .nil (by decide)

Empty and recursive destructor bodies

A destructor must itself account for its receiver. Compare these two bodies:

class Resource {
    drop { }
}

This alternative destructor fails: the body leaves self initialized. Even a fieldless class must unpack its receiver or transfer it to another consuming operation.

class Again {
    drop { drop self; }
}

This declaration checks, but dropping an Again instance recurses forever. Each call moves its receiver into the next frame; none returns.

As with the Token example, a class without a destructor cannot be explicitly dropped, but it can be unpacked.

Destructors/ChapterChecks:boundaries
example :
    ¬ BodyTyped classes declarations resource.signature ⟨[],none⟩ ∧
    ProgramTyped recursionProgram ∧
    (∀ depth, Steps classes.erase declarations (.initial recursionProgram) (recursionState depth)) ∧
    (∀ depth, Step classes.erase declarations (recursionState depth) (recursionState (depth + 1))) ∧
    (∀ depth, ¬ (recursionState depth).finished) ∧
    ¬ Droppable classes declarations (.whole "Token") ∧
    ¬ Droppable classes declarations partialWrapper := by
  refine ⟨?_,recursion_typed,recursion_reachable,recursive_step,?_,by decide,by decide⟩
  · rintro ⟨middle,final,sequence,result,finished⟩
    cases sequence
    cases result
    have impossible := finished "self" (.whole "Resource")
      (by simp [resource,Functions.Signature.environment,receiver,FieldType.toType])
    exact (by decide : ¬ StructType classes (.whole "Resource")) impossible
  · intro depth; simp [recursionState,Configuration.finished,Configuration.running]

Declarations and dropping

A declaration retains Shared’s name, kind, and ordered fields. A class declaration may additionally contain one destructor, written drop { body }, where body is a sequence of statements. The destructor has no parameters or result; its initial local binding is self, a uniquely owned whole instance of the declaring class. A struct or shared struct has no destructor body in this layer.

The core distinguishes ordinary function names, qualified method names, and drop(C) destructor names. A destructor is stored as a declaration with exactly one parameter →self of its owning class and no result. Names must be unique; ordinary methods cannot collide with destructor names.

Classes without destructors remain legal. Their instances must be consumed through explicit unpacking, possibly after being moved to another owner. Struct fields still have only struct types, and classes still cannot be shared. The inherited declaration restrictions are collected in the appendix.

Destructors/Syntax:Name
inductive Name where
  | function (name : String)
  | method (owner : ClassName) (name : String)
  | destructor (owner : ClassName)
  deriving DecidableEq, Repr
Destructors/Syntax:Signature.WellFormed
def Signature.WellFormed (classes : ClassTable) (name : Name)
    (signature : Signature) : Prop :=
  (signature.parameters.map Functions.Parameter.name).Nodup ∧
  (∀ p ∈ signature.parameters, Admissible classes p.type.toType) ∧
  (∀ ty ∈ signature.result, Admissible classes ty.toType) ∧
  match name with
  | .function _ => "self" ∉ signature.parameters.map Functions.Parameter.name
  | .destructor owner => signature = ⟨[receiver owner .given], none⟩ ∧
      ∃ declaration, (owner, declaration) ∈ classes ∧ declaration.kind = .classType
  | .method owner _ => match signature.parameters with
    | [] => False
    | first :: rest => first.name = "self" ∧ first.type.className = owner ∧
        "self" ∉ rest.map Functions.Parameter.name
Destructors/Syntax:Declaration
structure Declaration where
  signature : Signature
  body : Body
  deriving Repr
Destructors/Syntax:Statement
inductive Statement where
  | local (statement : Unpacking.Statement)
  | call (destination : Option VariableId) (name : Name) (arguments : List Value)
  | dropStruct (place : Place)
  deriving Repr
Destructors/Syntax:Statement.dropClass
def Statement.dropClass (owner : ClassName) (place : Place) : Statement :=
  .call none (.destructor owner) [.give place]
Destructors/Syntax:Body
structure Body where
  statements : List Statement
  result : Option Value
  deriving Repr
Destructors/Syntax:Program
structure Program where
  classes : ClassTable
  declarations : Declarations
  main : List Statement
  deriving Repr

The droppability judgment Droppable(T) says that an explicit drop can consume a value of type T, using a well-formed declaration table. Types retain Shared’s permissions and signed views, summarized in the appendix.

Type of valueCondition for Droppable(T)
Struct, including shared structAny well-formed permission and view allowed for that nominal type.
ClassGiven permission, a whole declared view, and a declared destructor.

“Whole” means that view normalization exposes the entire declared value, not merely every currently visible field. A partially moved class cannot invoke its destructor. An omitted field is unknown, not evidence that the field is empty.

Destructors/Typing:Droppable
def Droppable (classes : ClassTable) (declarations : Declarations) (ty : ValueType) : Prop :=
  Admissible classes ty ∧ (StructType classes ty ∨
    (ty = .whole ty.base .given ∧ .destructor ty.base ∈ declarations.map Prod.fst))

The new statement is drop p, where p is a place (a local followed by zero or more field names). An environment Γ maps local names to types or empty slots. Write Give(Γ, p) = (T, Γ′) for Shared’s static ordinary-give operation, recalled in the appendix.

The surface statement elaborates to a struct-discard operation or to drop(C)(p→), a core call to the destructor name with no destination. The class name comes from the given value’s type. This elaboration inserts no implicit drops and adds no receiver-call sugar.

The rule is:

  • Compute Give(Γ, p) = (T, Γ′).
  • Require Droppable(T).
  • Check the following statements under Γ′.

For a class this moves the value out of its source and calls its destructor. For a struct, dropping the resulting value invokes no code and destroys no object. Struct storage is treated as if garbage collected.

For structs, use exactly the ordinary-give effect. A given struct moves out, leaving an empty slot; a shared struct reference is copied, leaving its source initialized. The empty local binding is retained, as for ordinary give. No binding is removed.

Destructors/Typing:DropTyped
inductive DropTyped (classes : ClassTable) (declarations : Declarations) : Environment → Place → Statement → Environment → Prop where
  | struct {before after place ty} :
      ExprTyped classes before (.give place) ty after → StructType classes ty →
      DropTyped classes declarations before place (.dropStruct place) after
  | class {before after place owner declaration} :
      ExprTyped classes before (.give place) (.whole owner .given) after →
      (Name.destructor owner, declaration) ∈ declarations →
      declaration.signature = ⟨[receiver owner .given], none⟩ →
      DropTyped classes declarations before place (.dropClass owner place) after
Destructors/Typing:StatementTyped
inductive StatementTyped (classes : ClassTable) (declarations : Declarations) : Environment → Statement → Environment → Prop where
  | local {before after statement} :
      Shared.Typing.StatementTyped classes before statement after →
      StatementTyped classes declarations before (.local statement) after
  | call {before middle after destination name arguments declaration} :
      (name, declaration) ∈ declarations →
      (∀ x ∈ destination, x ∉ before.map Prod.fst) →
      ArgsTyped classes before arguments (declaration.signature.parameters.map Functions.Parameter.type) middle →
      DestinationTyped classes middle destination declaration.signature.result after →
      StatementTyped classes declarations before (.call destination name arguments) after

  | dropStruct {before after place ty} :
      ExprTyped classes before (.give place) ty after → StructType classes ty →
      StatementTyped classes declarations before (.dropStruct place) after

Finishing a frame

An environment is finished when each binding is either empty or has a struct type. A class binding is an outstanding obligation even if its class has a destructor, its view is partial, or all of its fields are empty. A frame may finish only when its statement sequence is exhausted and its environment is finished.

A frame owns a local environment and a sequence of statements still to run. There is one program frame and one fresh frame per active function, method, or destructor call. Names are local to their frame; a destructor cannot access its caller’s locals.

Moving a class to another local transfers the obligation. Storing it inside a class transfers the obligation to that owner; unpacking transfers obligations to the resulting field bindings. No class can be hidden inside a struct, because struct fields must themselves have struct types.

Frame completion discards remaining struct bindings without running code. It inserts no drops and performs no implicit unpacking.

Destructors/Typing:Finished
def Finished (classes : ClassTable) (environment : Environment) : Prop :=
  ∀ name ty, (name, some ty) ∈ environment → StructType classes ty
Destructors/Step:StoreFinished
def StoreFinished (classes : Classes) (state : State) : Prop :=
  ∀ name reference, (name, some reference) ∈ state.variables →
    StructReference classes state reference

Check every declared destructor body starting with exactly self: given C, where C is its declaring class with its whole view. Its statements must type check and leave a finished environment. Check ordinary functions and methods using their declared parameters and result types from the Functions signatures, requiring a finished environment after evaluation of any return expression. Check the top-level program from the empty environment with the same final condition.

All declared destructor signatures are available while checking each body. A call checks droppability, not an inline expansion of the called body. The whole declaration table is accepted only when every declared body checks. This permits recursive destructor calls, including drop self.

The inherited rules for declarations, expressions, fresh bindings, and unpacking otherwise apply; the appendix identifies those rules. Assignment is not part of this layer.

Destructors/Typing:BodyTyped
def BodyTyped (classes : ClassTable) (declarations : Declarations) (signature : Signature)
    (body : Body) : Prop :=
  ∃ middle after,
    SequenceTyped classes declarations signature.environment body.statements middle ∧
    ResultTyped classes middle body.result signature.result after ∧ Finished classes after
Destructors/Typing:DeclarationsTyped
def DeclarationsTyped (classes : ClassTable) (declarations : Declarations) : Prop :=
  (declarations.map Prod.fst).Nodup ∧
    ∀ entry ∈ declarations,
      Signature.WellFormed classes entry.1 entry.2.signature ∧
      BodyTyped classes declarations entry.2.signature entry.2.body
Destructors/Typing:ProgramTyped
def ProgramTyped (program : Program) : Prop :=
  program.classes.WellFormed ∧ DeclarationsTyped program.classes program.declarations ∧
    ∃ finalEnvironment,
      SequenceTyped program.classes program.declarations [] program.main finalEnvironment ∧
      Finished program.classes finalEnvironment

Calling and returning

A configuration contains a common heap, the allocation counter, an active frame, and a stack of suspended caller frames, including result destinations for ordinary calls as in Functions. This layer strengthens Functions’ frame-exit rule: a returning body must discharge its class obligations, and remaining struct bindings may be discarded. Eager GC still runs after each transition, including popping the initial frame. A runtime frame contains its local store and remaining statements. A local store maps names to empty slots or references. Heap objects, references, and allocation follow the Shared representation; object modes still belong to references.

The caller stack is empty initially. The initial active frame contains the program and an empty local store. Caller frames retain their locals while a destructor runs, but those locals are inaccessible to the callee. Roots used by the heap invariant include references in every frame, not just the active one, together with temporary values during expression evaluation.

Destructors/Step:Frame
structure Frame where
  variables : Store
  body : Body
  destination : Option VariableId
  deriving Repr
Destructors/Step:Configuration
structure Configuration where
  objects : List (ObjectId × Object)
  nextId : Nat
  frames : List Frame
  deriving Repr
Destructors/Step:Configuration.initial
def Configuration.initial (program : Program) : Configuration :=
  .running State.empty ⟨program.main, none⟩
Destructors/Step:Configuration.rootState
def Configuration.rootState (configuration : Configuration) : State :=
  ⟨configuration.objects, configuration.frames.flatMap Frame.variables, configuration.nextId⟩
Destructors/Step:Configuration.collect
def Configuration.collect (configuration : Configuration) : Configuration := by
  exact { configuration with objects := configuration.rootState.collect.objects }
Destructors/Step:Configuration.finished
def Configuration.finished (configuration : Configuration) : Prop :=
  configuration.frames = []

The transition rules extend Functions’ ordinary call and return machinery with destructor calls and stricter completion:

TransitionAction
Inherited statementExecute a Shared binding or unpacking statement in the active frame and common heap, then advance that frame.
Drop structPerform ordinary give from the source place, discard the resulting struct reference, and advance the active frame. No destructor runs; eager GC reclaims the object if it is no longer reachable.
Call class destructorPerform ordinary give as the sole argument to the declared destructor, suspend the updated caller with its following statements, and start the destructor body in a fresh frame containing only self bound to that reference.
ReturnEvaluate any ordinary function or method result as in Functions, require no initialized class locals remain, discard the remaining struct locals, and resume the caller with its result if any. A destructor returns no value.
Finish programWhen the program frame has no statements and no initialized class locals, discard its remaining locals and enter a terminal configuration.

The call transfers the reference directly to self; it does not destroy the object. Return does not delete a receiver object. Explicit unpacking is what removes a class container. A destructor’s statements may allocate, unpack, or call another destructor using the same rules as the program.

The destructor signature requires a uniquely owned whole instance: all declared fields and their declared subtrees are present, with the permissions required by their types. This is checked statically, using the same argument typing as ordinary calls; the machine does not repeat the view check at runtime. An exhausted frame with an initialized class local cannot return or finish; typing must exclude such configurations.

Destructors/Step:RawStep
inductive RawStep (classes : Classes) (declarations : Declarations) : Configuration → Configuration → Prop where
  | local {before after statement rest result frames destination} :
      Unpacking.Step classes ⟨before, [statement]⟩ ⟨after, []⟩ →
      RawStep classes declarations
        (.running before ⟨.local statement :: rest, result⟩ frames destination)
        (.running after ⟨rest, result⟩ frames destination)
  | call {before evaluated destination name arguments rest result frames returnTo
      declaration references} :
      (name, declaration) ∈ declarations →
      DestinationMatches destination declaration.signature.result →
      (∀ x ∈ destination, x ∉ before.variables.map Prod.fst) →
      EvalArgs classes before arguments evaluated references →
      references.length = declaration.signature.parameters.length →
      RawStep classes declarations
        (.running before ⟨.call destination name arguments :: rest, result⟩ frames returnTo)
        (.running { evaluated with variables := parameterStore declaration.signature.parameters references }
          declaration.body (⟨evaluated.variables, ⟨rest, result⟩, returnTo⟩ :: frames) destination)
  | dropStruct {before evaluated place reference rest result frames destination} :
      Eval classes before (.give place) evaluated reference →
      StructReference classes evaluated reference →
      RawStep classes declarations
        (.running before ⟨.dropStruct place :: rest, result⟩ frames destination)
        (.running evaluated ⟨rest, result⟩ frames destination)
  | «return» {before evaluated result reference caller frames destination variables} :
      ResultEval classes before result evaluated reference →
      Deliver caller.variables destination reference variables →
      StoreFinished classes evaluated →
      RawStep classes declarations
        (.running before ⟨[], result⟩ (caller :: frames) destination)
        (.running { evaluated with variables := variables } caller.body frames caller.destination)
  | exit {objects nextId variables} :
      StoreFinished classes ⟨objects, variables, nextId⟩ →
      RawStep classes declarations
        (.running ⟨objects, variables, nextId⟩ ⟨[], none⟩) ⟨objects, nextId, []⟩
Destructors/Step:Step
inductive Step (classes : Classes) (declarations : Declarations) : Configuration → Configuration → Prop where
  | collect {before raw} : RawStep classes declarations before raw →
      Step classes declarations before raw.collect

Safety and relation to Shared

A typed configuration has a well-formed declaration table, a compatible typing of all live frames, and a common heap realizing all of their roots. Its frame typing checks each active body from its current local environment. For a suspended caller it checks the remainder from the environment after result delivery. Every body ends in a finished environment.

The heap realization is Shared’s realization with an empty variable environment and the frame roots as pending values. Roots retain their multiplicity and their types; frame-local names need not be globally unique. Nominal field correctness covers fields hidden by views.

Write RetainsClasses(H, H′) when every non-struct object present in heap H is still present, unchanged, in heap H′. This is the collection obligation: GC may reclaim structs, but a class must be consumed explicitly.

The ownership condition still excludes simultaneous unique and shared paths to an object. Class references remain unique, and struct objects cannot contain class references. After the initial frame is popped, collection leaves the terminal heap empty. An explicit unpack removes its class container; a destructor call alone does not discharge that object’s obligation.

Hiding a field in a view does not erase a runtime class obligation.

Destructors/StackTyping:BodyFrom
def BodyFrom (classes : ClassTable) (declarations : Declarations) (environment : Environment)
    (body : Body) (result : Option FieldType) : Prop :=
  ∃ middle final, SequenceTyped classes declarations environment body.statements middle ∧
    ResultTyped classes middle body.result result final ∧ Finished classes final
Destructors/StackTyping:ContinuationTyped
inductive ContinuationTyped (classes : ClassTable) (declarations : Declarations) : Option VariableId → Option FieldType → List Frame → PendingValues → Prop where
  | done : ContinuationTyped classes declarations none none [] []
  | caller {destination result caller rest environment resumed roots laterRoots callerResult} :
      Slots environment caller.variables roots → environment.WellFormed classes →
      DestinationTyped classes environment destination result resumed →
      BodyFrom classes declarations resumed caller.body callerResult →
      ContinuationTyped classes declarations caller.destination callerResult rest laterRoots →
      ContinuationTyped classes declarations destination result (caller :: rest) (roots ++ laterRoots)
Destructors/StackTyping:StackShape
inductive StackShape (classes : ClassTable) (declarations : Declarations) : List Frame → PendingValues → Prop where
  | done : StackShape classes declarations [] []
  | active {frame rest environment roots laterRoots result} :
      Slots environment frame.variables roots → environment.WellFormed classes →
      BodyFrom classes declarations environment frame.body result →
      ContinuationTyped classes declarations frame.destination result rest laterRoots →
      StackShape classes declarations (frame :: rest) (roots ++ laterRoots)
Destructors/StackTyping:ConfigurationTyped
def ConfigurationTyped (classes : ClassTable) (declarations : Declarations) (configuration : Configuration) : Prop :=
  classes.WellFormed ∧ DeclarationsTyped classes declarations ∧
  ∃ roots, StackShape classes declarations configuration.frames roots ∧
    Realizes classes [] (heapState configuration.rootState) roots
Destructors/Safety:RetainsClasses
def RetainsClasses (classes : ClassTable) (before after : Configuration) : Prop :=
  ∀ id data, (id, data) ∈ before.objects →
    ¬ StructType classes (.whole data.className) → (id, data) ∈ after.objects

For every raw transition from a typed configuration, collection produces another typed configuration and retains every class object still present after the raw transition. Explicit unpacking may remove a class container during the raw transition; collection cannot remove it on the program’s behalf.

The proof discards only struct roots. Since struct fields have struct types, those roots cannot be the sole routes to class objects, even when their views omit fields.

Destructors/Safety:RawStep.sound
theorem RawStep.sound {before after : Configuration}
    (typed : ConfigurationTyped classes declarations before)
    (step : RawStep classes.erase declarations before after) :
    ConfigurationTyped classes declarations after.collect ∧ RetainsClasses classes after after.collect := by
  obtain ⟨classesWf,declarationsWf,roots,shape,heap⟩ := typed
  cases step with
  | @«local» beforeState afterState statement rest result frames destination operation =>
    cases shape with
    | active slots envWf body continuation =>
      obtain ⟨middle,final,sequence,returned,finished⟩ := body
      cases sequence with
      | cons first tail =>
        cases first with
        | «local» localTyped =>
          cases localTyped with
          | letValue expression binding =>
            cases operation with
            | letValue evaluation bound =>
              have realized := from_heap heap slots envWf
              have evaluated := (expression.sound _ _ realized).2 _ _ evaluation
              have afterRealized := binding.preserves_realization_pending evaluated bound
              have keys := binding_keys binding bound
                (expression.keys.trans (slots.keys.trans evaluation.variable_keys.symm))
              obtain ⟨afterRoots,afterSlots⟩ := realized_slots afterRealized keys
              have afterHeap := to_heap afterRealized afterSlots
              apply collect_safely (garbage := []) (by simp) classesWf declarationsWf
                (.active (frame := ⟨afterState.variables,⟨rest,result⟩,destination⟩) afterSlots afterRealized.environmentWellFormed ⟨middle,final,tail,returned,finished⟩ continuation)
              simpa only [List.append_nil,heapState,Configuration.rootState,Configuration.running] using afterHeap
  | @call beforeState evaluated destination name arguments rest result frames returnTo declaration references
      declared resultShape fresh evaluation lengths =>
    cases shape with
    | active slots envWf body continuation =>
      obtain ⟨middle,final,sequence,returned,finished⟩ := body
      cases sequence with
      | cons first tail =>
        cases first with
        | call expectedMember _ args delivery =>
          have same := member_value_unique declarationsWf.1 expectedMember declared
          cases same
          have realized := from_heap heap slots envWf
          have evaluatedRealized := (args.sound _ _ realized).2 _ _ evaluation
          have keys := args.keys.trans (slots.keys.trans (evalArgs_keys evaluation).symm)
          obtain ⟨callerRoots,callerSlots⟩ := realized_slots evaluatedRealized keys
          have callerHeap := to_heap evaluatedRealized callerSlots
          obtain ⟨signatureWf,calleeBody⟩ := declarationsWf.2 _ declared
          have calleeSlots := parameter_slots (result := declaration.signature.result) declaration.signature.parameters references lengths
          have calleeWf := (BodyFrom.of_declaration calleeBody).sequence_wf
          apply collect_safely (garbage := []) (by simp) classesWf declarationsWf
            (.active (frame := ⟨parameterStore declaration.signature.parameters references,declaration.body,destination⟩) calleeSlots calleeWf calleeBody
              (.caller (caller := ⟨evaluated.variables,⟨rest,result⟩,returnTo⟩) callerSlots evaluatedRealized.environmentWellFormed delivery
                ⟨middle,final,tail,returned,finished⟩ continuation))
          apply callerHeap.perm
          simp only [List.map_map, Function.comp_def, List.append_nil]
          apply List.Perm.trans (List.Perm.of_eq (List.append_assoc _ _ _).symm)
          apply List.Perm.trans (List.perm_append_comm.append_right _)
          exact List.Perm.of_eq (List.append_assoc _ _ _)
  | @dropStruct beforeState evaluated place reference rest result frames destination evaluation _ =>
    cases shape with
    | active slots envWf body continuation =>
      obtain ⟨middle,final,sequence,returned,finished⟩ := body
      cases sequence with
      | cons first tail =>
        cases first with
        | dropStruct expression structTy =>
          have realized := from_heap heap slots envWf
          have evaluatedRealized := (expression.sound _ _ realized).2 _ _ evaluation
          have keys := expression.keys.trans (slots.keys.trans evaluation.variable_keys.symm)
          obtain ⟨afterRoots,afterSlots⟩ := realized_slots evaluatedRealized keys
          have afterHeap := to_heap evaluatedRealized afterSlots
          apply collect_safely (garbage := [(reference, _)]) (by
            intro ref ty member; cases List.mem_singleton.mp member; exact structTy) classesWf declarationsWf
            (.active (frame := ⟨evaluated.variables,⟨rest,result⟩,destination⟩) afterSlots
              evaluatedRealized.environmentWellFormed ⟨middle,final,tail,returned,finished⟩ continuation)
          apply afterHeap.perm
          simpa only [List.append_assoc, List.cons_append, List.nil_append] using
            (List.perm_append_comm (l₁ := [(reference, _)])).append_left afterRoots
  | @«return» beforeState evaluated result reference caller frames destination variables evaluation delivered _ =>
    cases shape with
    | active slots envWf body continuation =>
      obtain ⟨middle,final,sequence,returned,finished⟩ := body
      cases sequence with
      | nil _ =>
        cases continuation with
        | @caller _ _ _ _ callerEnvironment resumed callerRoots laterRoots callerResult callerSlots callerWf delivery callerBody rest =>
          have realized := from_heap heap slots envWf
          obtain ⟨evaluatedRealized,staticKeys,runtimeKeys⟩ := returned.preserves realized evaluation
          obtain ⟨discarded,discardedSlots⟩ := realized_slots evaluatedRealized
            (staticKeys.trans (slots.keys.trans runtimeKeys.symm))
          have calleeHeap := to_heap evaluatedRealized discardedSlots
          have callerHeap := calleeHeap.perm (show
              (discarded ++ (resultRoots reference _ ++ (callerRoots ++ laterRoots))).Perm
              (callerRoots ++ (resultRoots reference _ ++ (laterRoots ++ discarded))) from by
            exact List.perm_append_comm.trans (by
              simpa only [List.append_assoc] using
                (List.perm_append_comm (l₁ := resultRoots reference _) (l₂ := callerRoots)).append_right (laterRoots ++ discarded)))
          have callerRealized := from_heap callerHeap callerSlots callerWf
          obtain ⟨resumedRealized,resumedKeys⟩ := delivery.preserves callerRealized callerSlots.keys delivered
          obtain ⟨resumedRoots,resumedSlots⟩ := realized_slots resumedRealized resumedKeys
          have resumedHeap := to_heap resumedRealized resumedSlots
          apply collect_safely (fun ref ty member => by
            obtain ⟨name, envMember, _⟩ := discardedSlots.root member
            exact finished name ty envMember) classesWf declarationsWf (.active (frame := ⟨variables,caller.body,caller.destination⟩) resumedSlots resumedRealized.environmentWellFormed callerBody rest)
          simpa only [List.append_assoc,heapState,Configuration.rootState,Configuration.running] using resumedHeap
  | exit _ =>
    cases shape with
    | active slots envWf body continuation =>
      cases continuation with
      | done =>
        obtain ⟨middle,final,sequence,returned,finished⟩ := body
        cases sequence with
        | nil _ =>
          cases returned with
          | none _ =>
            apply collect_safely (roots := []) (fun ref ty member => by
              obtain ⟨name, envMember, _⟩ := slots.root (by simpa only [List.append_nil] using member)
              exact finished name ty envMember) classesWf declarationsWf .done
            simpa only [List.append_nil, List.nil_append, heapState, Configuration.rootState, Configuration.running] using heap

A typed configuration with no frames has an empty heap. There are no remaining class or struct objects.

Destructors/Safety:ConfigurationTyped.finished_heap_empty
theorem ConfigurationTyped.finished_heap_empty {configuration : Configuration}
    (typed : ConfigurationTyped classes declarations configuration)
    (finished : configuration.finished) : configuration.objects = [] := by
  rcases configuration with ⟨objects,nextId,frames⟩
  change frames = [] at finished
  subst frames
  obtain ⟨_,_,roots,shape,heap⟩ := typed
  cases shape
  have same := State.collect_eq_self heap.ownership.no_pending
  rw [heapState,State.collect_no_variables] at same
  exact (congrArg State.objects same).symm

Starting from a well-typed program, every finite execution prefix ends in a typed configuration. That configuration is terminal or can take a step, and is not stuck. Recursive functions and destructors are allowed; this theorem does not assert termination.

Destructors/Safety:program_safety
theorem program_safety (typed : ProgramTyped program)
    (trace : Steps program.classes.erase program.declarations (.initial program) configuration) :
    ConfigurationTyped program.classes program.declarations configuration ∧
    (configuration.finished ∨ ∃ after, Step program.classes.erase program.declarations configuration after) ∧
    ¬ Stuck program.classes.erase program.declarations configuration := by
  have preserved := (ConfigurationTyped.initial typed).trace trace
  have progress := preserved.progress
  refine ⟨preserved,progress,?_⟩
  intro stuck
  rcases progress with finished | successor
  · exact stuck.1 finished
  · exact stuck.2 successor

Embed a Functions program by preserving its classes, ordinary names, signatures, local statements, and calls. Map each body and frame componentwise. The embedded fragment has no destructor declarations or drop statements.

Require an exit condition: if the current body has no statements, every possible result evaluation must leave a store whose initialized locals are structs, as required by frame completion. This condition is vacuous while a local statement or call remains.

Under this condition, a step from an embedded Functions configuration exists exactly when it is the embedding of a Functions step, including its collection. The backward implication quantifies over arbitrary destructor-machine successors. Thus local operations and ordinary calls retain their behavior. Frame exit adds the explicit consumption requirement.

The typing boundary is intentionally stronger. A Functions or Shared program may discard an initialized class local at exit; this layer rejects it. Preservation of all earlier program typings and completions is therefore not claimed.

Correspondence/FunctionsDestructors:step_correspondence
theorem step_correspondence (allowed : ExitAllowed classes before) :
    Destructors.Step classes (declarations ds) (configuration before) after ↔
      ∃ successor, Functions.Step classes ds before successor ∧ after = configuration successor := by
  constructor
  · exact step_backward
  · rintro ⟨successor, step, rfl⟩
    exact step_forward step allowed

Deferred conveniences

Assignment comes after this layer. Inserting explicit drops at scope exits and around control flow is a later desugaring step, rather than behavior supplied implicitly by these rules.

The spelling self → { resource } could eventually abbreviate let Wrapper → { resource } = self→;, with the nominal type inferred. This layer uses the explicit pattern.

After borrows are introduced, reconsider whether structs should support a user-defined drop body receiving a shared borrow of self. This is a tentative idea, not part of the destructor layer.

Appendix: inherited Shared machinery

The preceding rules use the following Shared machinery unchanged, except for imposing the completion condition defined above; frames already exist in Shared. These links identify the full inherited definitions; this summary fixes their role in this layer.

MachineryInherited meaning
Declarations and kindsNominal names and ordered named fields; classes, structs, and shared structs. Only structs satisfy struct(T); struct fields have struct types.
SyntaxPlaces start at locals and follow named fields. Expressions give a place, give-share a place, or construct an object from ordered argument expressions. Bindings use fresh local names.
StorageReferences carry modes and object identifiers. Object fields contain references or empty slots. Allocation uses fresh, monotonically allocated identifiers.
Types and viewsGiven and shared permissions, whole declared types, and signed views. Positive entries expose whole subtrees, negative entries record empty slots, and omissions are unknown.
Ordinary giveMove through a unique path, emptying its final slot; copy through shared access, promoting a unique final reference if necessary. Static give computes the result type and source environment.
ConstructionEvaluate arguments left to right; require whole declared argument types. Shared structs construct shared references immediately.
UnpackingA unique result can be unpacked with C → { fields }, removing the container and transferring its field slots to bindings. Every direct field’s status must be known; transferred objects may themselves be partial. Shared references cannot be unpacked.

Shared’s completion bound of one step per statement plus initial-frame exit does not carry over. Rootedness now counts all live frames; eager GC removes unreachable struct storage at each transition boundary. Class obligations survive until explicit consumption.

Destructors/Syntax:Parameter
abbrev Parameter := Functions.Parameter
Destructors/Syntax:Signature
abbrev Signature := Functions.Signature
Destructors/Typing:ResultTyped
inductive ResultTyped (classes : ClassTable) : Environment → Option Value → Option FieldType → Environment → Prop where
  | none {environment} :
      environment.WellFormed classes → ResultTyped classes environment none none environment
  | some {before after value type} :
      ExprTyped classes before value type.toType after →
      ResultTyped classes before (some value) (some type) after
Destructors/Typing:DestinationTyped
inductive DestinationTyped (classes : ClassTable) : Environment → Option VariableId → Option FieldType → Environment → Prop where
  | none {environment} :
      environment.WellFormed classes → DestinationTyped classes environment none none environment
  | some {before after name type} :
      BindingTyped classes before (.variable name) type.toType after →
      DestinationTyped classes before (some name) (some type) after
Destructors/Typing:SequenceTyped
inductive SequenceTyped (classes : ClassTable) (declarations : Declarations) : Environment → List Statement → Environment → Prop where
  | nil {environment} :
      environment.WellFormed classes → SequenceTyped classes declarations environment [] environment
  | cons {before middle after statement rest} :
      StatementTyped classes declarations before statement middle →
      SequenceTyped classes declarations middle rest after →
      SequenceTyped classes declarations before (statement :: rest) after

Assignment

Refill a field

An empty field can receive a new value. Suppose w has type given Wrapper.{-resource}, with these declarations:

class Resource {}
class Wrapper { resource: Resource }

w.resource = new Resource();

The statement checks, and w has the whole type given Wrapper afterwards. The assignment p = e installs the value of e into the slot p. It does not call a destructor for the previous contents. The negative view entry records that resource exists and is empty.

Assignment/Checks:refill
example :
    store classes partialContext (.field (.variable "w") "resource") (.whole "Resource") = some wrapper ∧
    StatementTyped classes [] partialContext
      (.store (.field (.variable "w") "resource") (.new "Resource" [])) wrapper := by
  constructor
  · decide
  · apply StatementTyped.store (middle := partialContext) (ty := .whole "Resource")
    · exact .lift (by decide)
        (.new (declaration := ⟨[], .classType⟩) (by decide) (.nil (by decide)) (by decide) (by decide))
        (by decide)
    · decide

A complete replacement lifetime

The same frame can retain a partial wrapper across a destructor call, refill its field, and then consume both the wrapper and the replacement:

class Resource {
    drop { let Resource → {} = self→; }
}
class Wrapper { resource: Resource }

let w = new Wrapper(new Resource());
drop w.resource;
w.resource = new Resource();
let Wrapper → { resource: r } = w→;
drop r;

This checks as a complete program, including the destructor body and the initial frame’s consumption obligation. Wrapper needs no destructor because the program explicitly unpacks it. Every finite execution, defined below, is safe: each reached state either has no frames or can take another step. If all frames have exited, the heap is empty.

Assignment/SafetyChecks:refill_safety
example : ProgramTyped refillProgram ∧
    ∀ configuration,
      Steps classes.erase declarations (.initial refillProgram) configuration →
      ConfigurationTyped classes declarations configuration ∧
      ¬ Stuck classes.erase declarations configuration ∧
      (configuration.finished → configuration.objects = []) := by
  refine ⟨refill_typed, ?_⟩
  intro configuration trace
  have safe := program_safety refill_typed trace
  exact ⟨safe.1, safe.2.2, safe.1.finished_heap_empty⟩

Replace a class explicitly

Use explicit destruction before storing over an owned class. With an initialized r: given Resource and replacement: given Resource, this sequence checks:

class Resource {
    drop { let Resource → {} = self→; }
}

drop r;
r = replacement→;

The destructor consumes the old resource. The store then moves the replacement into the empty r slot, leaving replacement empty. During the destructor call, the replacement remains rooted in the suspended caller frame. The example checks the destructor declaration and the two-statement sequence; it assumes the two initial bindings.

Assignment/Checks:explicit_replacement
example :
    DeclarationsTyped classes declarations ∧
    SequenceTyped classes declarations replacementBefore
      [.dropClass "Resource" (.variable "r"), .store (.variable "r") (.give (.variable "replacement"))]
      replacementAfter := by
  constructor
  · refine ⟨by decide, ?_⟩
    intro entry member
    have eq : entry = (.destructor "Resource", resourceDestructor) := by simpa [declarations] using member
    cases eq
    exact ⟨⟨by decide, by decide, by decide, rfl, ⟨⟨[], .classType⟩, by decide, rfl⟩⟩, resource_body⟩
  · apply SequenceTyped.cons (middle := replacementMiddle)
    · apply StatementTyped.call (declaration := resourceDestructor) (middle := replacementMiddle)
      · simp [declarations]
      · simp
      · exact .lift (by decide)
          (.cons (.give (by decide) (by decide) (by decide) (by decide)) (.nil (by decide))) (by decide)
      · exact .none (by decide)
    · apply SequenceTyped.cons (middle := replacementAfter)
      · apply StatementTyped.store
          (middle := replacementBefore.withCurrent [("r", none), ("replacement", none)])
          (ty := .whole "Resource")
        · exact .lift (by decide) (.give (by decide) (by decide) (by decide) (by decide)) (by decide)
        · decide
      · exact .nil (by decide)

An occupied class field cannot be overwritten, even when its class declares a destructor. Given whole w: given Wrapper, this store is rejected:

w.resource = new Resource();

An empty local retains its declared storage type. An empty r that previously held a Resource accepts another Resource, but rejects a Token:

class Token {}
r = new Resource(); // accepted from the empty-r state
r = new Token();    // rejected even from the empty-r state

These are separate checks from the same initial state.

Assignment/Checks:class_replacement
example :
    store classes wrapper (.field (.variable "w") "resource") (.whole "Resource") = none ∧
    store classes emptyResource (.variable "r") (.whole "Resource") =
      some (emptyResource.withCurrent [("r", some (.whole "Resource"))]) ∧
    store classes emptyResource (.variable "r") (.whole "Token") = none := by decide

Structs and shared references

Struct replacement needs no destructor call. Consider these declarations:

struct Point {}
shared struct SharedPoint {}
struct Box { point: Point }

The following cases check independently:

Destination’s current typeAssignmentResult
p: given Pointp = new Point()accepted
s: shared SharedPoints = new SharedPoint()accepted
b: given Boxb.point = new Point()accepted
b: shared Boxstore a shared Point into b.pointrejected

A local slot holding a shared reference is writable. A field reached through shared access is not. Overwriting a struct reference does not run user code; collection reclaims its object only if no frame can still reach it.

This layer fixes a local’s permission as well as its nominal type: a local inferred as given Point does not accept a shared Point. This is a typing restriction, not a layout requirement. Both permissions have the same nominal layout key.

Assignment/Checks:structs
example :
    store classes point (.variable "p") (.whole "Point") = some point ∧
    store classes sharedPoint (.variable "s") (.whole "SharedPoint" .shared) = some sharedPoint ∧
    store classes (box .given) (.field (.variable "b") "point") (.whole "Point") = some (box .given) ∧
    store classes (box .shared) (.field (.variable "b") "point") (.whole "Point" .shared) = none ∧
    store classes point (.variable "p") (.whole "Point" .shared) = none ∧
    layoutKey ⟨.given, "Point"⟩ = layoutKey ⟨.shared, "Point"⟩ := by decide

A shared-struct local can instead be overwritten and left for collection:

shared struct SharedPoint {}
let s = new SharedPoint();
s = new SharedPoint();

This also checks as a complete program. For every finite execution, defined below, each reached state either has no frames or can take another step; no frames means an empty heap. The completion obligation permits s to remain initialized, so it needs no explicit drop.

Assignment/SafetyChecks:overwrite_safety
example : ProgramTyped overwriteProgram ∧
    ∀ configuration,
      Steps classes.erase [] (.initial overwriteProgram) configuration →
      ConfigurationTyped classes [] configuration ∧
      ¬ Stuck classes.erase [] configuration ∧
      (configuration.finished → configuration.objects = []) := by
  refine ⟨overwrite_typed, ?_⟩
  intro configuration trace
  have safe := program_safety overwrite_typed trace
  exact ⟨safe.1, safe.2.2, safe.1.finished_heap_empty⟩

Partial values keep their views

Storing a partial value does not repair its missing fields. An empty local w with fixed storage type given Wrapper can receive a given Wrapper.{-resource} value; afterwards its current type is still given Wrapper.{-resource}. It cannot be left behind when the frame finishes: the class-consumption obligation also applies to partial classes.

Unpacking remains an alternative to repairing the container. The pattern Wrapper → { resource: r } gives the empty r binding a fixed storage type given Resource, obtained from the field declaration. Its current slot is empty, but it has not become untyped.

Assignment/Checks:partial_value
example :
    store classes (wrapper.withCurrent [("w", none)]) (.variable "w") partialWrapper = some partialContext ∧
    ¬ Finished classes partialContext ∧
    bindingTypes classes (.unpack "Wrapper" [("resource", "r")]) partialWrapper =
      some [("r", ⟨.given, "Resource"⟩)] := by
  refine ⟨by decide, ?_, by decide⟩
  intro finished
  exact (by decide : ¬ StructType classes partialWrapper)
    (finished "w" partialWrapper (by simp [partialContext, wrapper, Context.withCurrent]))

The right-hand side runs before the destination is checked. For whole w: given Wrapper, giving moves w out, then the store refills the same local:

w = w→;

It checks and leaves w whole. Conversely, an empty w does not provide a writable w.resource slot: a field store needs an initialized parent after right-hand-side evaluation. Nominal knowledge of the field name is insufficient.

Assignment/Checks:rhs_first
example :
    StatementTyped classes [] wrapper (.store (.variable "w") (.give (.variable "w"))) wrapper ∧
    store classes (wrapper.withCurrent [("w", none)])
      (.field (.variable "w") "resource") (.whole "Resource") = none := by
  constructor
  · apply StatementTyped.store (middle := wrapper.withCurrent [("w", none)]) (ty := .whole "Wrapper")
    · exact .lift (by decide) (.give (by decide) (by decide) (by decide) (by decide)) (by decide)
    · decide
  · decide

Syntax and fixed binding types

Assignment adds the statement p = e; to the Destructor statements. Here p is a place and e is a Shared value expression. Calls remain statements with fresh result bindings; a call is not an assignment expression. Bodies, declarations, and programs have the same components as in Destructors, with statement lists drawn from this extended syntax.

Assignment/Syntax:Statement
inductive Statement where
  | local (statement : Unpacking.Statement)
  | call (destination : Option VariableId) (name : Name) (arguments : List Value)
  | store (place : Place) (value : Value)
  | dropStruct (place : Place)
  deriving Repr
Assignment/Syntax:Body
structure Body where
  statements : List Statement
  result : Option Value
  deriving Repr
Assignment/Syntax:Declaration
structure Declaration where
  signature : Signature
  body : Body
  deriving Repr
Assignment/Syntax:Program
structure Program where
  classes : ClassTable
  declarations : Declarations
  main : List Statement
  deriving Repr

A storage type is a nominal type name paired with a permission. Taking the storage type of a current value type forgets its view. Its layout key forgets the permission too; given Foo and shared Foo have the same key.

A typing context contains two ordered maps with the same local names:

  • Fixed binding types retain each local’s nominal type and permission.
  • Current descriptions record either an empty slot or its present value type, including the view.

The current environment must be well formed. Each fixed type must be well formed and normalized as a whole type. Every initialized current description must agree with its binding’s fixed nominal type and permission. Empty descriptions carry no value view, but their fixed binding types remain.

Parameters begin with their declared fixed types and whole current types. A fresh variable binding infers its fixed type from its initializer’s type. Unpacking obtains fixed types from the nominal field declarations in pattern order, including for fields that are currently empty.

Assignment/StorageTypes:StorageType
abbrev StorageType := FieldType
Assignment/StorageTypes:storageType
def storageType (ty : ValueType) : StorageType := ⟨ty.permission, ty.base⟩
Assignment/StorageTypes:layoutKey
def layoutKey (ty : StorageType) : ClassName := ty.className
Assignment/StorageTypes:Context
structure Context where
  bindings : List (VariableId × StorageType)
  current : Environment
  deriving DecidableEq, Repr
Assignment/StorageTypes:Context.WellFormed
def Context.WellFormed (context : Context) (classes : ClassTable) : Prop :=
  context.current.WellFormed classes ∧
  context.bindings.map Prod.fst = context.current.map Prod.fst ∧
  (∀ entry ∈ context.bindings, Admissible classes entry.2.toType) ∧
  (∀ entry ∈ context.current, ∀ ty ∈ entry.2,
    context.bindings.lookup entry.1 = some (storageType ty))
Assignment/Typing:initialContext
def initialContext (signature : Signature) : Context :=
  ⟨signature.parameters.map (fun p => (p.name, p.type)), signature.environment⟩
Assignment/Typing:bindingTypes
def bindingTypes (classes : ClassTable) (pattern : Unpacking.Pattern)
    (ty : ValueType) : Option (List (VariableId × StorageType)) := do
  match pattern with
  | .variable name => some [(name, storageType ty)]
  | .unpack name fields =>
    let declaration ← classes.lookup name
    fields.mapM fun (field, destination) => do
      let fixed ← declaration.fields.lookup field
      some (destination, fixed)

Static store operation

Replacing the view at a field path keeps all entries outside that subtree. A positive ancestor is expanded along the destination path so its unaffected siblings remain exposed. Entries beneath the overwritten path are removed; the incoming value’s entries are prefixed by that path and inserted. Finally, the result is normalized. The root nominal type and permission do not change. Incoming negative entries stay negative; an omitted interior does not become whole.

Assignment/StorageTypes:replaceView
def replaceView (classes : ClassTable) (source incoming : ValueType) (path : Path) : ValueType :=
  let retained := source.nominal.entries.flatMap fun entry =>
    if path.isPrefixOf entry.path then []
    else match entry with
    | .negative _ => [entry]
    | .positive initialPath =>
      if initialPath.isPrefixOf path then
        match Unique.Typing.classAt classes.nominal source.base initialPath with
        | none => []
        | some target =>
          (Unique.Typing.remainingAfterMove classes.nominal target (path.drop initialPath.length)).map
            (Unique.Typing.Entry.prepend initialPath)
      else [entry]
  normalize classes ⟨source.permission, ⟨source.base,
    retained ++ incoming.nominal.entries.map (Unique.Typing.Entry.prepend path)⟩⟩

The static store operation takes a context after expression evaluation, a destination place, and an incoming value type. It returns an updated context, or fails. The input context must be well formed. The incoming type must be well formed and normalized.

For a local destination, its fixed type must match the incoming nominal type and permission. Its current slot must be empty or have a struct type.

For a field destination, the root must be initialized and the parent path must focus to a type with given permission. The declared field type must match the incoming nominal type and permission. The current field description must be known and either empty or a struct. An omitted, inaccessible field cannot be written merely because its declaration is known. The root’s view is updated using view replacement.

The operation preserves the fixed binding map and requires the resulting context to be well formed. It accepts partial incoming views. It never implicitly consumes an occupied class, including a partial class.

Assignment/StorageTypes:replaceable
def replaceable (classes : ClassTable) : SlotDescription → Bool
  | none => true
  | some ty => decide (StructType classes ty)
Assignment/StorageTypes:storeCurrent
def storeCurrent (classes : ClassTable) (context : Context) (place : Place) (incoming : ValueType) : Option Environment := do
  if !decide (context.WellFormed classes) || !decide (Admissible classes incoming) then none else do
    let (root,path) := splitPlace place
    let fixed ← context.bindings.lookup root
    let slot ← context.current.lookup root
    let result ← if path.isEmpty then do
      if storageType incoming != fixed || !replaceable classes slot then none
      else some (context.current.replace root (some incoming))
    else do
      let source ← slot
      let parentPath := path.take (path.length - 1)
      let field ← path.getLast?
      let parent ← focus classes source parentPath
      if parent.permission != .given then none else do
        let declaration ← classes.lookup parent.base
        let fieldType ← declaration.fields.lookup field
        let previous ← fieldDescription classes parent field
        if storageType incoming != fieldType || !replaceable classes previous then none
        else some (context.current.replace root (some (replaceView classes source incoming path)))
    some result
Assignment/StorageTypes:store
def store (classes : ClassTable) (context : Context) (place : Place)
    (incoming : ValueType) : Option Context := do
  let current ← storeCurrent classes context place incoming
  let after := context.withCurrent current
  if decide (after.WellFormed classes) then some after else none

Expression and argument typing use the existing Shared judgments on the current environment, retaining fixed bindings and requiring the resulting context to be well formed. Binding typing uses Shared’s binding judgment and extends the fixed map with the binding types. A local statement evaluates its initializer, then binds it.

A store statement first types its expression, producing an incoming type and an intermediate context. It then applies the static store operation to that intermediate context. The operation’s output is the statement’s output context. Thus an expression may empty the destination before the store, but cannot leave a missing ancestor along a field destination.

Calls and struct drops retain their Destructor rules, using these extended contexts. A call still requires a declared callee, correctly typed arguments, and a fresh destination matching its result signature.

Assignment/Typing:ExprTyped
inductive ExprTyped (classes : ClassTable) : Context → Value → ValueType → Context → Prop where
  | lift {before after value ty} :
      before.WellFormed classes →
      Shared.Typing.ExprTyped classes before.current value ty after →
      (before.withCurrent after).WellFormed classes →
      ExprTyped classes before value ty (before.withCurrent after)
Assignment/Typing:ArgsTyped
inductive ArgsTyped (classes : ClassTable) : Context → List Value → List FieldType → Context → Prop where
  | lift {before after values types} :
      before.WellFormed classes →
      Shared.Typing.ArgsTyped classes before.current values types after →
      (before.withCurrent after).WellFormed classes →
      ArgsTyped classes before values types (before.withCurrent after)
Assignment/Typing:BindingTyped
inductive BindingTyped (classes : ClassTable) : Context → Unpacking.Pattern → ValueType → Context → Prop where
  | lift {before after pattern ty fixed} :
      before.WellFormed classes →
      Shared.Typing.BindingTyped classes before.current pattern ty after →
      bindingTypes classes pattern ty = some fixed →
      (Context.mk (fixed ++ before.bindings) after).WellFormed classes →
      BindingTyped classes before pattern ty ⟨fixed ++ before.bindings, after⟩
Assignment/Typing:LocalTyped
inductive LocalTyped (classes : ClassTable) : Context → Unpacking.Statement → Context → Prop where
  | letValue {before middle after pattern value ty} :
      ExprTyped classes before value ty middle →
      BindingTyped classes middle pattern ty after →
      LocalTyped classes before ⟨pattern, value⟩ after
Assignment/Typing:StatementTyped
inductive StatementTyped (classes : ClassTable) (declarations : Declarations) : Context → Statement → Context → Prop where
  | local {before after statement} :
      LocalTyped classes before statement after →
      StatementTyped classes declarations before (.local statement) after
  | call {before middle after destination name arguments declaration} :
      (name, declaration) ∈ declarations →
      (∀ x ∈ destination, x ∉ before.current.map Prod.fst) →
      ArgsTyped classes before arguments (declaration.signature.parameters.map Functions.Parameter.type) middle →
      DestinationTyped classes middle destination declaration.signature.result after →
      StatementTyped classes declarations before (.call destination name arguments) after

  | store {before middle after place value ty} :
      ExprTyped classes before value ty middle →
      store classes middle place ty = some after →
      StatementTyped classes declarations before (.store place value) after
  | dropStruct {before after place ty} :
      ExprTyped classes before (.give place) ty after → StructType classes ty →
      StatementTyped classes declarations before (.dropStruct place) after

Every successful static store preserves the entire fixed binding map.

Assignment/StorageTypes:store_preserves_bindings
theorem store_preserves_bindings (stored : store classes before place ty = some after) :
    after.bindings = before.bindings := by
  unfold store at stored
  cases h : storeCurrent classes before place ty <;> simp [h] at stored
  rw [← stored.2]
  rfl

Execution

A writable slot is either a local entry (initialized or empty), or a field of an object reached through a uniquely accessible parent place. Resolving a field destination resolves the parent, not the field’s previous contents.

Runtime contents are replaceable if the slot is empty or holds a reference to a struct. Writing installs the incoming reference into the selected slot; it preserves object identities, field names, other slots, and the allocation counter. In particular, it does not reallocate the parent object.

Assignment/Write:Writable
inductive Writable (state : State) : Place → StoragePlace → Slot → Prop where
  | variable {name slot} :
      (name, slot) ∈ state.variables →
      Writable state (.variable name) (.variable name) slot
  | field {base source parent data name slot} :
      Resolve state base source parent .unique →
      (parent, data) ∈ state.objects →
      (name, slot) ∈ data.fields →
      Writable state (.field base name) (.field parent name) slot
Assignment/Write:Replaceable
def Replaceable (classes : Classes) (state : State) : Slot → Prop
  | none => True
  | some reference => StructReference classes state reference
Assignment/Write:Write
inductive Write : State → StoragePlace → Reference → State → Prop where
  | variable (objects : List (ObjectId × Object)) (nextId : Nat)
      (leading suffix : List (VariableId × Slot)) (name : VariableId)
      (previous : Slot) (reference : Reference) :
      Write ⟨objects, leading ++ (name, previous) :: suffix, nextId⟩
        (.variable name) reference
        ⟨objects, leading ++ (name, some reference) :: suffix, nextId⟩
  | field (variables : List (VariableId × Slot)) (nextId : Nat)
      (before after : List (ObjectId × Object)) (parent : ObjectId) (className : ClassName)
      (leading suffix : List (FieldName × Slot)) (name : FieldName)
      (previous : Slot) (reference : Reference) :
      Write ⟨before ++ (parent, ⟨className, leading ++ (name, previous) :: suffix⟩) :: after,
          variables, nextId⟩
        (.field parent name) reference
        ⟨before ++ (parent, ⟨className, leading ++ (name, some reference) :: suffix⟩) :: after,
          variables, nextId⟩

The machine retains the explicit stack and eager collector. Each frame owns its locals, remaining body, and result destination. Expressions run against the top frame; collection uses the roots of all frames.

For a raw store transition:

  1. Evaluate the right-hand-side expression to a reference and intermediate state.
  2. Resolve a writable destination slot in that intermediate state.
  3. Check that its previous contents are replaceable.
  4. Write the incoming reference into that slot and advance the statement list.

The resulting configuration is then collected. There is no collection between evaluation and installation of the incoming reference. Explicit drops remain separate statements, with their own calls and collection steps. Return and initial-frame exit retain the requirement that no class root remains in the completed frame.

Assignment/Step:Frame
structure Frame where
  variables : Store
  body : Body
  destination : Option VariableId
  deriving Repr
Assignment/Step:Configuration
structure Configuration where
  objects : List (ObjectId × Object)
  nextId : Nat
  frames : List Frame
  deriving Repr
Assignment/Step:RawStep
inductive RawStep (classes : Classes) (declarations : Declarations) : Configuration → Configuration → Prop where
  | local {before after statement rest result frames destination} :
      Unpacking.Step classes ⟨before, [statement]⟩ ⟨after, []⟩ →
      RawStep classes declarations
        (.running before ⟨.local statement :: rest, result⟩ frames destination)
        (.running after ⟨rest, result⟩ frames destination)
  | call {before evaluated destination name arguments rest result frames returnTo
      declaration references} :
      (name, declaration) ∈ declarations →
      DestinationMatches destination declaration.signature.result →
      (∀ x ∈ destination, x ∉ before.variables.map Prod.fst) →
      EvalArgs classes before arguments evaluated references →
      references.length = declaration.signature.parameters.length →
      RawStep classes declarations
        (.running before ⟨.call destination name arguments :: rest, result⟩ frames returnTo)
        (.running { evaluated with variables := parameterStore declaration.signature.parameters references }
          declaration.body (⟨evaluated.variables, ⟨rest, result⟩, returnTo⟩ :: frames) destination)
  | dropStruct {before evaluated place reference rest result frames destination} :
      Eval classes before (.give place) evaluated reference →
      StructReference classes evaluated reference →
      RawStep classes declarations
        (.running before ⟨.dropStruct place :: rest, result⟩ frames destination)
        (.running evaluated ⟨rest, result⟩ frames destination)
  | store {before evaluated after place value reference target previous rest result frames destination} :
      Eval classes before value evaluated reference →
      Writable evaluated place target previous →
      Replaceable classes evaluated previous →
      Write evaluated target reference after →
      RawStep classes declarations
        (.running before ⟨.store place value :: rest, result⟩ frames destination)
        (.running after ⟨rest, result⟩ frames destination)
  | «return» {before evaluated result reference caller frames destination variables} :
      ResultEval classes before result evaluated reference →
      Deliver caller.variables destination reference variables →
      StoreFinished classes evaluated →
      RawStep classes declarations
        (.running before ⟨[], result⟩ (caller :: frames) destination)
        (.running { evaluated with variables := variables } caller.body frames caller.destination)
  | exit {objects nextId variables} :
      StoreFinished classes ⟨objects, variables, nextId⟩ →
      RawStep classes declarations
        (.running ⟨objects, variables, nextId⟩ ⟨[], none⟩) ⟨objects, nextId, []⟩
Assignment/Step:Step
inductive Step (classes : Classes) (declarations : Declarations) : Configuration → Configuration → Prop where
  | collect {before raw} : RawStep classes declarations before raw →
      Step classes declarations before raw.collect
Assignment/Step:Configuration.collect
def Configuration.collect (configuration : Configuration) : Configuration := by
  exact { configuration with objects := configuration.rootState.collect.objects }

A finite execution is zero or more machine steps. A program starts with an empty heap and one initial frame containing its main statements and no locals or result destination.

Assignment/Step:Configuration.initial
def Configuration.initial (program : Program) : Configuration :=
  .running State.empty ⟨program.main, none⟩
Assignment/Step:Steps
inductive Steps (classes : Classes) (declarations : Declarations) : Configuration → Configuration → Prop where
  | refl (configuration : Configuration) : Steps classes declarations configuration configuration
  | step {before middle after} :
      Step classes declarations before middle → Steps classes declarations middle after →
      Steps classes declarations before after

A configuration is finished when its frame stack is empty.

Assignment/Step:Configuration.finished
def Configuration.finished (configuration : Configuration) : Prop :=
  configuration.frames = []

A configuration is stuck when it is not finished and has no possible next machine step. A finished configuration is therefore not stuck.

Assignment/Step:Stuck
def Stuck (classes : Classes) (declarations : Declarations) (configuration : Configuration) : Prop :=
  ¬ configuration.finished ∧ ¬ ∃ after, Step classes declarations configuration after

Replacing a local shared-struct reference can make the old object unreachable. The checked transition begins with s referencing SharedPoint object 0, constructs object 1, and stores its reference in s. In the resulting raw configuration, object 0 is unreachable and object 1 is reachable. The eager collector therefore discards object 0 and retains object 1.

Assignment/ExecutionChecks:struct_collection
example :
    RawStep classes.erase []
      (.running beforeStructStore ⟨[.store (.variable "s") (.new "SharedPoint" [])], none⟩)
      (.running afterStructStore ⟨[], none⟩) ∧
    ¬ Live (Configuration.running afterStructStore ⟨[], none⟩).rootState ⟨0⟩ ∧
    Live (Configuration.running afterStructStore ⟨[], none⟩).rootState ⟨1⟩ := by
  refine ⟨?_, ?_, .variable (name := "s") (reference := .shared ⟨1⟩) (by decide)⟩
  · apply RawStep.store (evaluated := beforeStructStore.allocate "SharedPoint" [] [])
      (reference := .shared ⟨1⟩) (target := .variable "s") (previous := some (.shared ⟨0⟩))
    · exact .new (declaration := ⟨[], .sharedStruct⟩) (by decide) (.nil _) rfl (by decide)
        (by simp [StructArguments])
    · exact .variable (by decide)
    · exact ⟨⟨"SharedPoint", []⟩, ⟨[], .sharedStruct⟩, by decide, by decide, rfl⟩
    · exact .variable _ _ [] [] "s" _ _
  · have onlyOne : ∀ id, Live (Configuration.running afterStructStore ⟨[], none⟩).rootState id → id = ⟨1⟩ := by
      intro id live
      induction live with
      | «variable» member =>
        simp only [Configuration.rootState, Configuration.running, afterStructStore,
          List.flatMap_cons, List.flatMap_nil, List.append_nil, List.mem_cons,
          List.not_mem_nil, or_false, Prod.mk.injEq, Option.some.injEq] at member
        rw [member.2]
        rfl
      | field _ obj field _ =>
        simp only [Configuration.rootState, Configuration.running, afterStructStore,
          List.mem_cons, List.not_mem_nil, or_false] at obj
        rcases obj with h | h <;> cases h <;> contradiction
    intro live
    have impossible := onlyOne _ live
    cases impossible

Refilling a field can reverse allocation-age order. In the checked step, w owns wrapper object 1 with an empty resource field. The store constructs resource object 2 and installs it in object 1. Both objects survive collection, and their identities remain 1 and 2.

This resulting heap satisfies the structural heap invariant: its objects are rooted and its owning references are compatible. It does not satisfy the stronger requirement that every field target have a smaller allocation index than its parent. The foundation deliberately does not require that ordering.

Assignment/ExecutionChecks:younger_child
example :
    Step classes.erase []
      (.running beforeRefill ⟨[.store (.field (.variable "w") "resource") (.new "Resource" [])], none⟩)
      (.running afterRefill ⟨[], none⟩) ∧
    Shared.WellFormed classes.erase afterRefill ∧
    ¬ (∀ id data name reference, (id, data) ∈ afterRefill.objects →
      (name, some reference) ∈ data.fields → reference.object.index < id.index) := by
  refine ⟨?_, ?_, ?_⟩
  · have collected : (Configuration.running afterRefill ⟨[], none⟩).collect =
        Configuration.running afterRefill ⟨[], none⟩ := by
      apply Configuration.collect_eq_self
      intro id data member
      simp only [Configuration.running, afterRefill, List.mem_cons, List.not_mem_nil, or_false] at member
      rcases member with h | h
      · cases h
        exact .field (parent := ⟨1⟩) (reference := .owned ⟨2⟩) (name := "resource") (data := ⟨"Wrapper", [("resource", some (.owned ⟨2⟩))]⟩) (.variable (name := "w") (reference := .owned ⟨1⟩) (by decide)) (by decide) (by decide)
      · cases h
        exact .variable (name := "w") (reference := .owned ⟨1⟩) (by decide)
    rw [← collected]
    exact .collect refill_raw
  · refine ⟨by decide, by decide, ?_, ?_, ?_, ?_, ?_⟩
    · intro id data member
      simp only [afterRefill, List.mem_cons, List.not_mem_nil, or_false] at member
      rcases member with h | h <;> cases h
      · exact ⟨⟨[], .classType⟩, by decide, rfl, by decide⟩
      · exact ⟨⟨["resource"], .classType⟩, by decide, rfl, by decide⟩
    · intro id data member
      simp only [afterRefill, List.mem_cons, List.not_mem_nil, or_false] at member
      rcases member with h | h <;> cases h <;> decide
    · intro object allocated
      have cases : object = ⟨2⟩ ∨ object = ⟨1⟩ := by simpa [Allocated, afterRefill] using allocated
      rcases cases with rfl | rfl
      · exact .field (parent := ⟨1⟩) (reference := .owned ⟨2⟩) (name := "resource")
          (data := ⟨"Wrapper", [("resource", some (.owned ⟨2⟩))]⟩)
          (.variable (name := "w") (reference := .owned ⟨1⟩) (by decide)) (by decide) (by decide)
      · exact .variable (name := "w") (reference := .owned ⟨1⟩) (by decide)
    · simp [Owners, afterRefill, Compatible, Reference.owned]
    · intro object
      simp [References, Allocated, afterRefill, Reference.owned, or_comm]
  · intro older
    have impossible := older ⟨1⟩ ⟨"Wrapper", [("resource", some (.owned ⟨2⟩))]⟩ "resource" (.owned ⟨2⟩) (by decide) (by decide)
    contradiction

Correspondence

Embedding Destructors into Assignment maps statements, bodies, and declarations, and frames componentwise. It adds no store statements. Heap objects, allocation counters, local slots, call names, and value expressions remain unchanged.

Correspondence/DestructorsAssignment:statement
def statement : Destructors.Statement → Assignment.Statement
  | .local s => .local s
  | .call destination name arguments => .call destination name arguments
  | .dropStruct place => .dropStruct place
Correspondence/DestructorsAssignment:body
def body (source : Destructors.Body) : Assignment.Body :=
  ⟨source.statements.map statement, source.result⟩
Correspondence/DestructorsAssignment:declaration
def declaration (source : Destructors.Declaration) : Assignment.Declaration :=
  ⟨source.signature, body source.body⟩
Correspondence/DestructorsAssignment:declarations
def declarations (source : Destructors.Declarations) : Assignment.Declarations :=
  source.map fun (name, decl) => (name, declaration decl)
Correspondence/DestructorsAssignment:frame
def frame (source : Destructors.Frame) : Assignment.Frame :=
  ⟨source.variables, body source.body, source.destination⟩
Correspondence/DestructorsAssignment:configuration
def configuration (source : Destructors.Configuration) : Assignment.Configuration :=
  ⟨source.objects, source.nextId, source.frames.map frame⟩

Every Destructor execution step is preserved by this embedding, including collection and frame transitions, with the declaration table embedded as well. This is an operational correspondence result; it does not assert preservation of typing with the new fixed binding metadata.

Correspondence/DestructorsAssignment:step_forward
theorem step_forward (h : Destructors.Step classes decls before after) :
    Assignment.Step classes (declarations decls) (configuration before) (configuration after) := by
  cases h with
  | collect raw => rw [collect]; exact .collect (raw_forward raw)

Reverse execution correspondence and preservation of Destructor typing with the new fixed binding metadata remain separate proof obligations. The forward execution theorem does not establish either.

Automatic destructor insertion remains deferred. Mutable leases and their different representation also remain outside this layer.

Appendix: inherited calls and completion

Result typing evaluates an optional result against the signature. Destination typing either accepts no result and no destination, or introduces a fresh local with the result’s declared fixed type. Sequence typing composes statement contexts in order.

Assignment/Typing:ResultTyped
inductive ResultTyped (classes : ClassTable) : Context → Option Value → Option FieldType → Context → Prop where
  | none {environment} :
      environment.WellFormed classes → ResultTyped classes environment none none environment
  | some {before after value type} :
      ExprTyped classes before value type.toType after →
      ResultTyped classes before (some value) (some type) after
Assignment/Typing:DestinationTyped
inductive DestinationTyped (classes : ClassTable) : Context → Option VariableId → Option FieldType → Context → Prop where
  | none {environment} :
      environment.WellFormed classes → DestinationTyped classes environment none none environment
  | some {before after name type} :
      BindingTyped classes before (.variable name) type.toType after →
      DestinationTyped classes before (some name) (some type) after
Assignment/Typing:SequenceTyped
inductive SequenceTyped (classes : ClassTable) (declarations : Declarations) : Context → List Statement → Context → Prop where
  | nil {environment} :
      environment.WellFormed classes → SequenceTyped classes declarations environment [] environment
  | cons {before middle after statement rest} :
      StatementTyped classes declarations before statement middle →
      SequenceTyped classes declarations middle rest after →
      SequenceTyped classes declarations before (statement :: rest) after

A well-typed body starts in its parameter context, checks its statements and result using sequence and result typing, and must satisfy the completion obligation: only empty or struct locals remain. This condition uses current descriptions, so an empty class slot is permitted while an initialized partial class is not.

Class drops use whole given receivers and the dedicated destructor name; struct drops give and discard without invoking user code.

Assignment/Typing:Finished
def Finished (classes : ClassTable) (context : Context) : Prop :=
  Destructors.Finished classes context.current
Assignment/Typing:DropTyped
inductive DropTyped (classes : ClassTable) (declarations : Declarations) : Context → Place → Statement → Context → Prop where
  | struct {before after place ty} :
      ExprTyped classes before (.give place) ty after → StructType classes ty →
      DropTyped classes declarations before place (.dropStruct place) after
  | class {before after place owner declaration} :
      ExprTyped classes before (.give place) (.whole owner .given) after →
      (Destructors.Name.destructor owner, declaration) ∈ declarations →
      declaration.signature = ⟨[receiver owner .given], none⟩ →
      DropTyped classes declarations before place (.dropClass owner place) after
Assignment/Typing:BodyTyped
def BodyTyped (classes : ClassTable) (declarations : Declarations) (signature : Signature)
    (body : Body) : Prop :=
  ∃ middle after,
    SequenceTyped classes declarations (initialContext signature) body.statements middle ∧
    ResultTyped classes middle body.result signature.result after ∧ Finished classes after

A well-typed declaration table has distinct callable names. Each declaration has a signature obeying the ordinary call restrictions and destructor restrictions, and a well-typed body checked against the entire table. Signatures are therefore available recursively; there is no termination requirement.

Assignment/Typing:DeclarationsTyped
def DeclarationsTyped (classes : ClassTable) (declarations : Declarations) : Prop :=
  (declarations.map Prod.fst).Nodup ∧
    ∀ entry ∈ declarations,
      Destructors.Signature.WellFormed classes entry.1 entry.2.signature ∧
      BodyTyped classes declarations entry.2.signature entry.2.body

A well-typed program has a well-formed class table and a well-typed declaration table. Its main sequence checks from the empty context and satisfies the same completion obligation as a function body.

Assignment/Typing:ProgramTyped
def ProgramTyped (program : Program) : Prop :=
  program.classes.WellFormed ∧ DeclarationsTyped program.classes program.declarations ∧
    ∃ finalEnvironment,
      SequenceTyped program.classes program.declarations Context.empty program.main finalEnvironment ∧
      Finished program.classes finalEnvironment

Appendix: store and stack safety

Suppose the input state is structurally well formed, counting the incoming reference and any other pending references as roots. A write to a writable slot preserves that invariant when the incoming reference leaves the pending roots and the displaced reference, if any, joins them instead.

This is an ownership exchange before collection. The displaced reference remains a temporary root even when no local or field reaches it after the write. The theorem assumes neither allocation-age order nor global acyclicity.

Assignment/WriteOwnership:Write.preserves_pending
theorem Write.preserves_pending {previous : Slot} (wf : WellFormedWith classes before (incoming :: pending))
    (writable : Writable before place source previous)
    (written : Write before source incoming after) :
    WellFormedWith classes after (previous.toList ++ pending) := by
  have owners := written.owners_pending wf writable pending
  constructor
  · simpa only [written.objectKeys] using wf.objectKeys
  · simpa only [written.variableKeys] using wf.variableKeys
  · intro id data stored
    obtain ⟨oldData, oldStored, sameClass, sameFields⟩ := written.new_object_data stored
    obtain ⟨declaration, declared, shape, unique⟩ := wf.shapes id oldData oldStored
    exact ⟨declaration, sameClass ▸ declared, sameFields ▸ shape, unique⟩
  · intro id data stored
    obtain ⟨oldData, oldStored, _, _⟩ := written.new_object_data stored
    simpa only [written.nextId] using wf.bounds id oldData oldStored
  · intro id allocated
    have oldAllocated : Allocated before id := by
      simpa only [Allocated, written.objectKeys] using allocated
    exact written.liveWith wf writable (wf.rooted id oldAllocated)
  · exact owners.pairwise wf.ownersCompatible compatible_symm
  · intro id
    have targets := (owners.map Reference.object).mem_iff (a := id)
    simp only [List.map_append, owners_targets] at targets
    have allocation : Allocated before id ↔ Allocated after id := by
      simp only [Allocated, written.objectKeys]
    simpa only [List.map_append] using
      targets.symm.trans ((wf.referencesComplete id).trans allocation)

Suppose the static store operation succeeds and the input state realizes its current environment, with the incoming value and any other pending values as roots. A writable, replaceable runtime destination and write then exist.

For every such runtime write, the resulting state realizes the output current environment and all the original pending values except the installed incoming value. Any additional pending values needed to retain displaced storage have struct types, so they can be discarded by the statement’s collector. For a field destination, the output type uses view replacement; incoming negative entries still describe empty fields.

Assignment/StoreSoundness:store_sound
theorem store_sound
    {classes : ClassTable} {before after : Context} {place : Place}
    {ty : ValueType} {state : State} {reference : Reference} {pending : PendingValues}
    (stored : store classes before place ty = some after)
    (realized : Realizes classes before.current state ((reference, ty) :: pending)) :
    (∃ target previous result, Writable state place target previous ∧
      Replaceable classes.erase state previous ∧ Write state target reference result) ∧
    (∀ target previous result, Writable state place target previous →
      Replaceable classes.erase state previous → Write state target reference result →
      ∃ garbage, (∀ ref ty, (ref, ty) ∈ garbage → StructType classes ty) ∧
        Realizes classes after.current result (pending ++ garbage)) := by
  refine ⟨store_exists stored realized, ?_⟩
  intro target previous result writable replaceable written
  exact store_preserves stored realized writable replaceable written

A typed configuration has well-formed nominal declarations, typed callable declarations, and a compatible stack. Each frame’s locals form a typed store for the current descriptions in its context.

The active body’s remainder checks from that context. A suspended caller’s remainder checks from the context after result delivery. Every body satisfies the completion obligation. The empty stack has no result destination and no roots.

The common heap has Shared realization with an empty local environment and all frame references as pending values. Their multiplicities and types are retained, so equal shared references in two slots still contribute two roots. Frame-local names need not be globally unique.

Assignment/StackTyping:BodyFrom
def BodyFrom (classes : ClassTable) (declarations : Declarations) (environment : Context)
    (body : Body) (result : Option FieldType) : Prop :=
  ∃ middle final, SequenceTyped classes declarations environment body.statements middle ∧
    ResultTyped classes middle body.result result final ∧ Finished classes final
Assignment/StackTyping:ContinuationTyped
inductive ContinuationTyped (classes : ClassTable) (declarations : Declarations) : Option VariableId → Option FieldType → List Frame → PendingValues → Prop where
  | done : ContinuationTyped classes declarations none none [] []
  | caller {destination result caller rest environment resumed roots laterRoots callerResult} :
      Slots environment.current caller.variables roots → environment.WellFormed classes →
      DestinationTyped classes environment destination result resumed →
      BodyFrom classes declarations resumed caller.body callerResult →
      ContinuationTyped classes declarations caller.destination callerResult rest laterRoots →
      ContinuationTyped classes declarations destination result (caller :: rest) (roots ++ laterRoots)
Assignment/StackTyping:StackShape
inductive StackShape (classes : ClassTable) (declarations : Declarations) : List Frame → PendingValues → Prop where
  | done : StackShape classes declarations [] []
  | active {frame rest environment roots laterRoots result} :
      Slots environment.current frame.variables roots → environment.WellFormed classes →
      BodyFrom classes declarations environment frame.body result →
      ContinuationTyped classes declarations frame.destination result rest laterRoots →
      StackShape classes declarations (frame :: rest) (roots ++ laterRoots)
Assignment/StackTyping:ConfigurationTyped
def ConfigurationTyped (classes : ClassTable) (declarations : Declarations) (configuration : Configuration) : Prop :=
  classes.WellFormed ∧ DeclarationsTyped classes declarations ∧
  ∃ roots, StackShape classes declarations configuration.frames roots ∧
    Realizes classes [] (heapState configuration.rootState) roots

Every typed configuration has no remaining frames—that is, it is finished—or can take a machine step. This covers stores, calls, returns, explicit drops, and the initial-frame exit.

Assignment/Safety:ConfigurationTyped.progress
theorem ConfigurationTyped.progress {configuration : Configuration}
    (typed : ConfigurationTyped classes declarations configuration) :
    configuration.finished ∨ ∃ after, Step classes.erase declarations configuration after :=
  ConfigurationTyped.progress_of_store store_sound typed

Every machine step from a typed configuration produces another typed configuration. The result quantifies over every operational successor and includes eager collection after the raw transition.

Assignment/Safety:ConfigurationTyped.preservation
theorem ConfigurationTyped.preservation {before after : Configuration}
    (typed : ConfigurationTyped classes declarations before)
    (step : Step classes.erase declarations before after) :
    ConfigurationTyped classes declarations after :=
  ConfigurationTyped.preservation_of_store store_sound typed step

A collection retains classes when every object whose nominal type is not a struct remains present with the same identity and contents. The comparison uses the heap immediately before collection and the heap after it.

Assignment/Safety:RetainsClasses
def RetainsClasses (classes : ClassTable) (before after : Configuration) : Prop :=
  ∀ id data, (id, data) ∈ before.objects →
    ¬ StructType classes (.whole data.className) → (id, data) ∈ after.objects

For every raw transition from a typed configuration, collection produces a typed configuration and retains every class object still present after that transition. An explicit unpack can remove a class container during the raw transition; collection cannot consume it on the program’s behalf.

Overwriting a struct reference can discard its entire unreachable subgraph. Since struct fields have struct types, this cannot hide an unconsumed class, including behind a view omission.

Assignment/Safety:RawStep.sound
theorem RawStep.sound {before after : Configuration}
    (typed : ConfigurationTyped classes declarations before)
    (step : RawStep classes.erase declarations before after) :
    ConfigurationTyped classes declarations after.collect ∧ RetainsClasses classes after after.collect :=
  RawStep.sound_of_store store_sound typed step

In a typed configuration, references in all frame slots and object fields are pairwise compatible. Distinct owning occurrences can target the same object only when both are shared. Every referenced object is allocated, and every allocated object has an incoming reference from a frame or field.

Assignment/Safety:ConfigurationTyped.ownership
theorem ConfigurationTyped.ownership {configuration : Configuration}
    (typed : ConfigurationTyped classes declarations configuration) :
    (Owners configuration.rootState).Pairwise Compatible ∧
    (∀ id, id ∈ References configuration.rootState ↔ Allocated configuration.rootState id) := by
  obtain ⟨_,_,roots,shape,heap⟩ := typed
  have refs := shape.references
  constructor
  · simpa only [Owners,heapState,List.filterMap_nil,List.nil_append,refs,
      Configuration.rootState] using heap.ownership.ownersCompatible
  · intro id
    have complete := heap.ownership.referencesComplete id
    simpa only [heapState,References,List.filterMap_nil,List.nil_append,refs,
      Configuration.rootState,Allocated,List.map_append,List.map_filterMap,Function.comp_def] using complete

A typed configuration with no frames has an empty heap. No class or struct objects remain after completion.

Assignment/Safety:ConfigurationTyped.finished_heap_empty
theorem ConfigurationTyped.finished_heap_empty {configuration : Configuration}
    (typed : ConfigurationTyped classes declarations configuration)
    (finished : configuration.finished) : configuration.objects = [] := by
  rcases configuration with ⟨objects,nextId,frames⟩
  change frames = [] at finished
  subst frames
  obtain ⟨_,_,roots,shape,heap⟩ := typed
  cases shape
  have same := State.collect_eq_self heap.ownership.no_pending
  rw [heapState,State.collect_no_variables] at same
  exact (congrArg State.objects same).symm

Starting from a well-typed program, every finite execution ends in a typed configuration. It is finished or can take another machine step, and is not stuck. This includes stores within recursive functions and destructors; the theorem makes no termination claim.

Assignment/Safety:program_safety
theorem program_safety (typed : ProgramTyped program)
    (trace : Steps program.classes.erase program.declarations (.initial program) configuration) :
    ConfigurationTyped program.classes program.declarations configuration ∧
    (configuration.finished ∨ ∃ after, Step program.classes.erase program.declarations configuration after) ∧
    ¬ Stuck program.classes.erase program.declarations configuration :=
  program_safety_of_store store_sound typed trace

CFlow

This part is reserved for control flow. Its chapters are coming.

Future extensions

Generic views

A constructor could store a value without requiring all of its fields to be initialized. Its result type would preserve the argument’s view. Consider:

class Token {}
class C { left: Token, right: Token }
class D { c: C }

Suppose a user-defined constructor fn takes a C and stores it in field c of a new D. A proposed generic view parameter would let its signature say:

\[ \forall V:\mathsf{View}[C].\quad \mathsf{fn}(C.V)\to D.\{c.V\}. \]

Here \(V\) ranges over views of \(C\). The proposed notation \(c.V\) carries that view into the result’s field \(c\). For example, an argument of type C.{-left, right} would produce D.{-c.left, c.right}: the moved-out field stays empty, and the other field stays accessible.

This is a future extension. The current Construct rule requires whole declared argument types; it has neither user-defined constructors nor view parameters.

The notation must also preserve the presence of the stored object. If \(V=\{\}\), the argument is an existing C whose fields are hidden. Simply prefixing every entry of this empty view would produce no entries and forget that c is initialized. A generic-view design must express that distinction. The operators and their typing rules remain to be defined.

Permissions that name places

A later permission given[p₁, …, pₙ] would describe access derived from named places. These are paths rooted at bindings, such as x.item, whereas a view’s paths are relative to the described object. Plain given abbreviates given[], the owning permission.

The permission of a named place matters. For example, these proposed function signatures should be equivalent:

fn foo(x: shared Point) -> given[x] Point
fn foo(x: shared Point) -> shared Point

Because x provides shared ownership, deriving access from it produces shared ownership. Simplification therefore consults the typing environment, including the effective permission of a field path. It cannot inspect the permission expression alone.

Permission application should retain the identity and shared-absorption laws. For a permission \(P\) and a type \(T\), the intended equations include:

\[ \begin{aligned} \mathsf{given}\;P&\equiv P, &\mathsf{given}\;T&\equiv T,\\ P\;\mathsf{shared}&\equiv\mathsf{shared}, &P\;(\mathsf{shared}\;T)&\equiv\mathsf{shared}\;T. \end{aligned} \]

The meaning of multiple named places, their composition with other permissions, and their interaction with borrowing remain to be specified. The initial Shared type system uses only given and shared; it has no permissions that name places.

Permission and type unions

A result may have different ownership permissions on different branches. Consider this intended use of a path-dependent permission, given[x, y]:

fn foo(x: shared Point, y: Point) -> given[x, y] Point {
    if something { x→ } else { y→ }
}

let r = foo(a, b);
let q = r→;

The function and branch syntax illustrate a future language. They are not part of the current straight-line fragments.

If foo returns from x, r contains a shared reference and r→ copies it. If it returns from y, r contains a given reference and r→ moves it. The machine can inspect the runtime reference; the type checker must account for both possibilities. Simplifying this result to an always-shared type would lose the second case.

Develop these permissions together with permission unions P | Q and type unions T | U, revisiting the union forms in the v1 model. The design needs to settle how alternative sources relate to combined dependencies, how unions compose with permissions and views, and how these rules extend to leased and shared borrowing types. The notation alone does not settle those choices.

Initialization tracking also needs a distinction between an empty slot and one that can no longer be used. After the final give above, using r again is unsafe in the given case, but claiming that its slot is empty is false in the shared case. Given’s current variable marker 0 means known empty. This extension must describe the uncertainty without changing that fact silently.

Contributing to the specification

This repository develops Dada’s semantics as a book of definitions, execution rules, examples, and theorems linked to Lean. Changes should keep the intended behavior clear in the prose and precise in the formalization.

Agents help draft and review these accounts. Their correspondence reviews record which inputs they examined, their conclusion, and the reason for it. Changed inputs make those reviews stale. A review is evidence of a comparison, not a substitute for proof checking.

Contributor guides

The specification system reference defines the renderer and evidence requirements. The implementation contracts link tooling requirements to code, tests, and review evidence. To read the language rather than work on its specification, begin with Dada and this model.

How it works

The book develops the model through named definitions, rules, theorems, and examples. Each unit carries its explanation in Markdown and mathematics and links to the corresponding named part of Lean. The mathematical account stands on its own; a Rendered/Lean selector lets the reader inspect its formalization. The reading order introduces concepts before the rules that use them.

Developing a unit

Begin with a behavior or distinction worth explaining. State it in a unit and work through examples that make its meaning concrete. Put the unit ID on the opening line and source citations in :lean:. Record contextual definitions in :uses: and link new terminology to where it is introduced. Explanatory content belongs inside the reviewed boundary rather than in untracked semantic prose. The authoring guide gives the supported forms.

A theorem may need several assumptions to capture the intended guarantee. Review compares those assumptions and the conclusion with the prose and mathematics. Lean checks the proof. An example has its own comparison: the cited Lean case must describe the setup and result actually claimed in the book. Unfinished formalizations retain their intended unit kind and use :status: draft. They cannot receive affirmative correspondence decisions or pass evidence validation.

Neither representation automatically wins when they differ. A discrepancy may reveal ambiguous prose, an inadequate proposition, or a design choice that needs discussion. Record the discrepancy and resolve it before claiming correspondence.

Keeping the comparison inspectable

dada-spec prepare snapshots a unit and its required inputs. A human or agent reviewer compares them and records a conclusion, rationale, examined inputs, and limitations. dada-spec record checks that the inputs still match current source before retaining the decision. Exact snapshots remain available so another reviewer can vet the comparison. Changing an input makes affected evidence stale.

The evidence checker validates structure, required input coverage, and freshness. It does not itself judge mathematical correspondence or prove a theorem. Its ordinary Cargo integration test makes missing or stale evidence visible during cargo test --workspace. The review procedure explains how to interpret and repair failures.

Proof checking, test execution, and correspondence review remain separate. Passing Lean establishes the proposition checked under its assumptions; a current review records a judgment that this proposition captures the intended claim. A passing test establishes its tested cases. None of these results should be silently substituted for another.

Working in this repository

Edit chapters under v2/md/ and register them in v2/md/SUMMARY.md. From the repository root, just book-v2 builds the draft and just test-lean checks the Lean project. Run mdbook serve inside v2/ to preview the book.

From v2/, run:

cargo run -p mdbook-dada --bin dada-spec -- status --explain
cargo run -p mdbook-dada --bin dada-spec -- check
cargo fmt --all
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace

Every new-style unit participates in evidence validation. v2/spec.json names strict chapters that additionally require all semantic prose to lie within units. The Given and Shared chapters use the complete review loop, alongside the implementation contracts. Legacy requirements in the system reference still await migration to review units.

The system design defines the evidence contract. The layer extension protocol describes the model organization: unique ownership with p→, then shared ownership with p→share, with a formal correspondence between the two layers.

Repository goals and principles

These principles guide how we develop and explain the specification. Dada’s language design goals are described separately in its design goals.

Describe results before algorithms

For an operation, first explain the resulting value, changed state, and possible faults. Then show an algorithm computing that result. Diagrams should let a reader understand the relationship without mentally running the algorithm.

Explain execution before static checking

Develop the machine’s behavior independently of the type checker. Then explain how static checking predicts execution and rules out particular failures. This organization makes conservative rejection and dynamic failure distinguishable.

Develop several views of the design

English, propositions, examples, code, and proofs illuminate different aspects of intent. None automatically wins when they disagree. A discrepancy may reveal ambiguous prose, an inadequate proposition, an implementation defect, or a design that needs revision. Review makes that discussion explicit.

Keep evidence inspectable

A reader should be able to follow a claim to the definitions, examples, and reasoning supporting it. State assumptions and coverage gaps explicitly. Preserve human and agent review reasoning, and distinguish those judgments from mechanical proof checking and test results.

Let the narrative organize the material

The book’s structure should serve understanding rather than mirror implementation modules. Include definitions and local documentation from code where they help the reader; use authored prose to connect concepts across those definitions.

These are working principles, not claims that the current tooling already implements all of them.

Writing style tenets

Write for a reader who knows language semantics but is new to Dada. The chapter should explain the model on its own, without requiring the reader to open Lean or reconstruct earlier design discussions.

Start with intent

Say what a concept lets us describe or what an operation accomplishes. Then introduce its representation and rules. For an operation, explain the result and the change to the state before detailing how to compute them.

Give the reader something concrete

Use a small example to motivate an unfamiliar distinction. Show the relevant declarations, action, and result; reuse them as the definitions become more precise. A table can make related cases easy to compare. Add another example when it reveals a boundary, such as the difference between an empty field and one whose status is unknown.

Examples belong in named units and need corresponding Lean cases when formalized. During Markdown-first review, keep them marked Draft. An example should help explain a rule, not force the reader to infer the rule.

Introduce only what the next step needs

Order concepts by their dependencies. Define the machine before discussing its execution, and define a judgment before stating results about it. Defer a later layer’s machinery until that layer needs it. A short link can record where an extension belongs without interrupting the current explanation.

Give every symbol a home

Introduce the term and its metavariable together: “a statement \(t\).” Give each symbol a grammar or domain before using it; spell out map domains and codomains. Distinguish formal syntax from convenient shorthand. When a rule needs local names, put their definitions beside the rule in a short “where” clause.

Give named operations and normalization rules their own definition units, so links land directly on the defining text or equation. Link uses of named operations and judgments to those definitions, including uses inside mathematical rules. Leave the defining occurrence unlinked.

Let prose and mathematics share the work

Use prose to explain purpose and consequences, and mathematics to state the precise relationship. Avoid narrating every symbol in an equation. Include the assumptions that determine behavior, and explain a side condition when its role is easy to miss. Break a long definition where the reader encounters a new idea, rather than following the boundaries of implementation modules.

Keep claims inspectable without interrupting the explanation

Put semantic explanations in named units with explicit source references and dependencies, as described in Authoring units. Use definitions for concepts and judgments, and theorems or lemmas for results. State the result and its assumptions in the book; leave proof checking to Lean. Correspondence review checks whether the formal statement captures the intended claim. Evidence belongs with that review, so the narrative can concentrate on the model.

Edit for a first reading

Prefer short sentences, concrete verbs, and familiar words. Remove repeated qualifications, announcements of what the next paragraph will say, and praise for the design. Read the chapter in order and check that each paragraph answers a question the reader can already understand. Use these tenets to improve that flow, not as a template that every unit must repeat.

Authoring units

A specification unit is one explanation that can be compared with a named formalization. Keep its definition, qualifications, notation, and explanatory text inside the same fence. The reader should understand the mathematical account without opening Lean; the Lean view makes the associated formalization inspectable.

Use the Writing style tenets to organize the explanation: start with intent, use examples to make distinctions concrete, and introduce notation before relying on it.

Identity, formalization, and context

The opening argument is the unit ID. Source citations and dependencies are options, followed by a blank line and the body:

```{definition} unique.syntax.place
:lean: Unique/Syntax:Place
:uses: unique.syntax.variable unique.syntax.field

A *place expression* \\(p\\) identifies a variable or a field reached through another place.

\\[
p ::= x \mid p.f
\\]
```

This is an authoring illustration; it does not assert that these example modules already exist. unique.syntax.place is the public unit identity. Unique/Syntax:Place is a source selector relative to the configured Lean root. They serve different purposes and need not have matching names.

A citation can select an inductive member of a top-level mutual group. The group delimiters and member headers must start at column zero; each header ends with where on its first line, and its body is indented. The Lean view shows the selected declaration; the evidence packet retains its enclosing source. Nested groups and mutual definitions of other kinds are unsupported.

Use :uses: for definitions and notation needed to interpret a unit. Link new terminology to the unit that introduces it with {anchor-ref}. A visible link supports the reader; an explicit dependency also records context that is used without being quoted. The inventory includes unit references in the review dependency set. Keep dependencies specific enough that a reviewer can explain why each is needed.

Unit IDs share the book’s global namespace. They use ASCII letters, digits, dots, underscores, and hyphens and begin with a letter or digit. Keep an ID stable when moving a unit between chapters. A second identifying {anchor} inside a structured unit is unnecessary.

Choosing a kind

KindBodyFormalization
definitionMarkdown introducing a concept, including delimited mathOne or more Lean definitions or a Rust implementation citation for a meta requirement
grammarRaw display LaTeXOne or more Lean type declarations
judgmentRaw display LaTeXOne inductive declaration
ruleRaw display LaTeXOne inductive constructor
theoremMarkdown stating a result and its assumptionsOne named Lean theorem
lemmaMarkdown stating a supporting result and its assumptionsOne named Lean theorem
exampleMarkdown explaining a concrete caseOne anchored anonymous Lean example
future-noteMarkdown exploring a possible future design, outside the current specificationForbidden

Theorem and lemma reviews compare the intended proposition with Lean’s statement, including hidden parameters and assumptions. Leave the proof to Lean. A prose proof outline is not required. Definitions introduce concepts and judgments; they do not require proofs.

Kind and readiness are separate. During a Markdown-first review, add :status: draft to retain the intended kind with a separate Draft indicator:

```{definition} unique.evaluation
:status: draft
:uses: unique.syntax.place

The following rules define expression evaluation.
```

A draft may omit source citations. Any supplied citations must still select the right declaration kind. A draft theorem states a proposed result, not an established one; a draft example describes a scenario awaiting its formal case. Evidence validation fails while a unit is draft, and no affirmative correspondence decision can be recorded for it. Add the matching formalization and remove :status: draft before preparing a correspondence review.

Future notes

Use a Future note for exploratory ideas that are not part of the current specification. Unlike a draft specification, a future note is publishable without formalization:

```{future-note} future.generic_views
:uses: given.typing.views

A future design could preserve partial views through constructors.
```

Future notes reject :lean:, :rust:, :tests:, and :status: draft. Place future notes at chapter top level, outside lists and blockquotes. They have stable IDs, Markdown bodies, and optional :uses: context; links and dependencies must resolve as usual. Nested specification units and legacy citation blocks are forbidden. The header says Future note, with no source selector. Evidence status is future note / not applicable; preparation and recording of correspondence reviews are rejected. Once an idea has an associated formalization, change it to the appropriate specification kind and review it. These checks reject declared source associations; they do not discover uncited implementations elsewhere in the repository.

Checking the formalization

Check Lean with just test-lean; its lake build --wfail rejects warnings, including those emitted by sorry. Do not use sorry to complete a formalization or suppress warn.sorry. Any future allowance for admissions must require an explicit opt-in.

Examples carry explanatory content too: describe the setup, the action, and the result that the cited Lean case actually states. A test of one small helper does not support an example claiming an entire execution. Use multiple units when different cases need independent explanation and review.

Mathematics and examples

Within Markdown bodies, use doubled-backslash delimiters: \\( and \\) for inline mathematics, \\[ and \\] for displays. Grammar, judgment, and rule bodies are already LaTeX displays and do not need those delimiters. Put distinct premises on separate lines. Group overbar expressions as {\overline f}; punctuation belongs outside the group.

Write source-language give expressions with the Unicode arrow, p→, and shared conversion as p→share. Introduce a concept with its italicized name and inline metavariable: “a statement \(t\)” or “a value expression \(e\).” Give each metavariable a grammar or domain before using it; state map domains and codomains explicitly. Define a judgment’s notation and inference rules before stating results about it. Use :uses: to identify earlier units that supply these definitions. This is a correspondence-review requirement, not an automatic notation check.

Abbreviating Lean syntax is useful when the omitted detail is explained; omitting a condition such as freshness or distinctness changes the claim.

An example citation uses the name between standalone Lean anchor comments:

```{example} unique.example.move
:lean: Unique/Examples:move
:uses: unique.operation.give

The example starts with one owner in `x`. Evaluating `x→` transfers that
reference and leaves `x` uninitialized.
```

The corresponding Lean region has exactly one anonymous example:

-- ANCHOR: move
example : True := by
  trivial
-- ANCHOR_END: move

This deliberately trivial snippet illustrates anchor syntax only. It does not check the move described above and would not pass a correspondence review of that example. Actual cases must state the relevant setup and result.

Use a longer outer fence for bodies containing fenced diagrams or code. Named units are top-level review boundaries; do not nest them. A diagram inside an example belongs to that example’s reviewed body. Legacy citation directives also cannot appear inside a structured unit: make them separate units with :lean: citations and connect them with :uses:.

Write reviewed text directly in its unit. mdBook include, playground, and rustdoc-include expansion is rejected in structured units, including inside literal code samples: mdBook can expand those samples too. This keeps the published claim equal to the text retained for review. To discuss an expansion command literally, split its opening braces so it is not a live mdBook directive.

book.toml supplies the book source directory and preprocessor.dada.lean-source for both rendering and evidence. It participates in review freshness. Source roots must stay inside the project; changing a configured root requires a new comparison with the declarations under that root.

Requirements on the tooling

Meta requirements use the same unit identity and body structure. Cite Rust implementation symbols and tests instead of a Lean formalization:

```{definition} meta.example.required_inputs
:rust: mdbook-dada/src/evidence.rs:validate
:tests: mdbook-dada/tests/evidence.rs:rejects_missing_input

Validation reports an error when a review omits a required source input.
```

These paths and names illustrate the option layout; select actual symbols when authoring a requirement. Its selector is Rendered/Rust; the Lean-backed forms use Rendered/Lean. Do not mix :lean: and :rust: on one unit. Split a requirement with independently reviewed implementations into separate units and connect their context with :uses:. A test citation identifies coverage to inspect; it does not assert that the test was executed or prove all cases.

Scope and migration

Every new-style unit under md/ participates in required evidence. spec.json additionally lists chapters subject to strict whole-chapter coverage. In those chapters, put semantic prose inside units and use headings for navigation. The authoring illustrations and workflow explanations in this repository section remain outside the initial strict pilot scope.

Existing chapters can retain the older opening-line citation syntax until they are migrated. Their inline anchors and working Rendered/Lean selectors are preserved, but do not by themselves provide complete review units. Migration means choosing boundaries, moving explanations inside them, adding IDs and dependencies, and preparing reviews. It is not a mass relabeling exercise.

After editing a covered unit, follow Correspondence review to prepare a fresh packet and retain the comparison evidence.

Link each referenced concept or equation where it is used, including MathJax rule premises. Ordinary Markdown links, anchor-reference roles, and MathJax \href{#claim-UNIT}{symbol} are inventoried automatically. Cross-chapter MathJax links use .html paths. Leave defining occurrences unlinked.

Run dada-spec links to inspect destinations and reading order. The link-review procedure explains coverage, target clarity, and forward-reference evidence. A link that resolves is only the start: it should land directly on the definition the reader needs.

Correspondence review

A correspondence review asks whether a unit’s prose and mathematics express the intended meaning of its cited formalization. Lean checks the proof of a theorem; the review checks that its statement is the theorem we intended to prove. Evidence retains both the inputs and the reasoning behind that judgment.

Scope and configuration

spec.json makes the validation scope explicit. Its JSON uses schema: 1, a chapters array of paths relative to v2/, a policies array of review-policy files, and a context array for additional required input files. The book and Lean roots come from book.toml; this repository uses md/ and lean/. Every new-style unit under md/ participates in the inventory. Specification units require evidence; future notes are explicitly nonnormative and have no correspondence claim. Adding a strict chapter additionally rejects prose outside unit boundaries in that chapter; removing it is a coverage change, not a remedy for missing evidence.

Policy and extra context files become inputs to the comparison. Changes to those files, the configuration, or validator implementation can invalidate existing reviews. Evidence files themselves are outputs and do not recursively participate in their own input digests.

Prepare the comparison

Run these commands from v2/. Inspect the current inventory and failures with:

cargo run -p mdbook-dada --bin dada-spec -- status --explain
cargo run -p mdbook-dada --bin dada-spec -- check

Prepare one unit’s packet:

cargo run -p mdbook-dada --bin dada-spec -- prepare UNIT_ID

Preparation writes a JSON bundle under evidence/bundles/ and prints its path. It snapshots the complete authored unit, the required source selections and context, dependent units, and review policy. It records content hashes so that recording and validation can reject a comparison made against changed inputs. Preparation does not supply a verdict.

A unit marked :status: draft retains its semantic kind but is unfinished. Drafts may omit citations; supplied citations are still checked by kind. Evidence validation rejects drafts, and recording an affirmative correspondence decision for one is forbidden. Complete the formalization and remove draft status before attempting that review. A definition needs a matching Lean definition, not a proof; only a claimed result needs a proof.

A {future-note} ID records exploratory design outside the current specification. It must not have formalization citations (:lean:, :rust:, or :tests:) or :status: draft. Its structure, ID, and contextual references remain checked, but it needs no correspondence evidence and cannot be prepared or recorded for correspondence review. Status reports future note / not applicable, never approval. Context links do not formalize the note. Change its kind before adding a formalization; draft specification units retain their existing blocking behavior.

The input set is constructed from the current specification. At minimum it includes the exact unit being reviewed and every cited Lean declaration. All local Lean source files are retained conservatively for a Lean-backed unit, rather than claiming that a textual scan discovered elaborated semantic dependencies. The Lean toolchain and Lake metadata, configured policy and context, and validator source/tests, book.toml, and Cargo metadata are also inputs. Rust-backed units retain their selected implementation/test sources and complete containing files. Structured units reject mdBook expansion directives and nested legacy source citations, so neither can introduce uncaptured content into a reviewed body. This may invalidate evidence after an edit elsewhere in the formalization or a proof-only change. That conservative scope is explicit and reproducible.

Review the packet

Prefer a reviewer with fresh context. Give the reviewer the immutable packet, this procedure, and the task of finding discrepancies; an earlier author’s assurance is not evidence. Read the authored units, exact source selections, policy, and explicitly added context that the packet marks as required review inputs, and record their keys in the review. Inspect additional source context needed for the comparison and record those inputs too. The bundle also retains conservative full-source and tool snapshots for freshness; listing those snapshots does not require claiming that every line of every existing proof was examined. For each unit:

  1. Identify its intended objects, operations, quantifiers, and assumptions.
  2. Compare the complete prose and math with the selected source, including hidden parameters, side conditions, and omitted representation details.
  3. Check that concepts are introduced with an italicized name and inline metavariable, and that every metavariable has a grammar or domain before use. Check that judgments have defining rules before results rely on them. Inspect the introducing units, including those cited through :uses:.
  4. Look for a case admitted by one account and excluded by the other. For an example, check its setup and stated result rather than merely finding a similarly named test.
  5. Record what matches, any discrepancy, the scope of the comparison, and its limitations with references to the examined inputs.

In the rationale, identify the units that introduce the notation and judgments needed for the comparison. Report undefined symbols and forward references as discrepancies; if their meaning cannot be established, mark the review inconclusive. These are review criteria. The validator does not discover notation introductions from prose. The separate link audits extract authored references, check their order, and require current coverage, target, and forward-reference reviews. These audits use the same prepare/record workflow with generated subject IDs and an additional typed audit assessment.

Do not re-prove a theorem or audit its tactic choices as part of this review. Do inspect assumptions that affect its statement. A successfully checked proof of a narrower proposition does not cover a broader prose claim. Draft status must remain explicit and does not permit approval.

For a meta requirement, compare its body with the cited implementation and tests. Explain which paths or rejection cases the tests cover and which parts of the behavior are supported only by inspection. Do not infer universal correctness from a passing test.

If the comparison needs another unit, add it to the authored dependencies and prepare a new packet. Additional consulted files can be included with repeatable --input arguments, for example:

cargo run -p mdbook-dada --bin dada-spec -- prepare UNIT_ID --input md/repo/authoring.md

These extra file inputs must also appear in examined. Configured context files are conservative freshness inputs; they are not automatically an attestation that the reviewer read the whole file. Do not silently consult material that another reviewer cannot recover from the evidence. If the intended design is ambiguous, record an inconclusive result or mismatch and describe the choice that needs resolution. Do not change the design just to obtain approval.

Record the decision

The review file identifies the prepared bundle, the reviewer and provenance, examined input keys, a conclusion, comparison rationale, and limitations. The three conclusions are corresponds, mismatch, and inconclusive. The rationale must explain the comparison rather than report that filenames exist or tests passed. The review JSON has this shape; use the actual digest and required review input keys from the bundle, plus any further inputs actually examined:

{
  "schema": 1,
  "bundle": "DIGEST_FROM_PREPARED_BUNDLE",
  "reviewer": "Reviewer identity",
  "provenance": "How this review was performed; agent/model identity when applicable",
  "examined": ["EVERY_REQUIRED_REVIEW_INPUT_KEY"],
  "conclusion": "corresponds",
  "rationale": "Specific comparison of the authored claim and formal statement, with input references",
  "limitations": [],
  "supersedes": []
}

This is a schema illustration, not a review to copy and approve. Retain an explicit empty limitations list when none were identified. examined is an attestation that the reviewer read the listed inputs; the validator can check its coverage of the required review inputs, but cannot establish that the reading actually happened. Do not claim to have examined a whole conservative source snapshot just because the packet contains it. supersedes records the digests of earlier decisions for the same unit that the new decision intentionally replaces; it does not conceal them. A replacement may use a different bundle, for example after adding context needed to resolve a disagreement. Recording still validates the new bundle against current inputs. Every unsuperseded decision for a unit must apply to current inputs and conclude corresponds for the evidence check to pass. When reviewing changed inputs, explicitly supersede the earlier active decisions; creating an unrelated positive record does not silently discard a negative or stale one. If a replacement later becomes stale, the check fails rather than falling back to an older positive review.

Record a completed review with:

cargo run -p mdbook-dada --bin dada-spec -- record BUNDLE_PATH REVIEW_JSON_PATH

Recording validates the review and recomputes required inputs from current source. If the unit, formalization, dependencies, or policy changed after preparation, it refuses the obsolete comparison. Prepare again and review the changed packet. Accepted records are retained under evidence/records/ alongside their retrievable bundles. Never manufacture a favorable review or rewrite old input hashes to satisfy the workspace test.

Interpret the result

dada-spec check and the Cargo integration test perform syntactic validation. They check that required evidence exists, includes the independently derived minimum inputs, has valid contents and hashes, and applies to current sources. They also distinguish a positive review from an unresolved mismatch or inconclusive comparison. Draft units fail validation and cannot receive affirmative correspondence decisions. The checks do not judge whether the recorded reasoning is correct, launch a reviewer, compile Lean, or run the cited tests.

Run the mechanical checks separately:

cargo test --workspace
cargo clippy --workspace --all-targets -- -D warnings

From the repository root, just test-lean checks the formalization with lake build --wfail, rejecting warnings such as those emitted by sorry. just book-v2 checks the rendered book and citations. Report those results separately from the correspondence conclusion. A current review can coexist with a failing proof check, and a passing proof check can coexist with a missing or negative review.

The validator’s annotate-snippets diagnostics point to the affected unit or citation and give the preparation command. Read the reported cause before preparing again: an invalid source target needs a source or citation fix, while a stale packet needs renewed comparison. The test is a guard against missing or stale work, not a semantic oracle.

For each unit, examine prose and both inline and display mathematics for uses of concepts defined elsewhere. Check that each has a definition link, including operations in inference-rule premises. Locally bound metavariables need an introduction and scope; defining occurrences need no self-link. Explain every extracted link’s conceptual or navigation role. A navigation label cannot exempt information the reader needs to understand the unit.

For each destination, identify the subject and its defining source span. The landing must clearly introduce that subject on its own. Selecting a precise span inside a multi-part block does not make a buried destination acceptable: split the explanation or change the link. Inspect surrounding text in the retained chapter when judging the landing.

For a forward reference, consider moving the definition earlier, moving the use later, and splitting the explanation. Retain it only if those rearrangements would prevent a coherent introduction. Record why; select the explicit forward signpost; identify the minimum facts needed and where the passage states them. A motivating example or dependency cycle is not an automatic exception. Local references must be ordered by the actual defining passage, not by the unit’s header. Inspect the reading order and relevant chapter context retained in the packet. Unknown order cannot establish a backward reference.

Use mismatch or inconclusive when these requirements are not met. Syntactic validation checks the inventory and evidence, not the truth of these judgments. Follow Link and reading-order review for the generated subject IDs and assessment fields. Future notes also receive these editorial audits; they still have no formal correspondence obligation.

Record mechanical checks

spec-checks.json names executable checks separately from review units. From v2/, build the CLI and run a selected check:

cargo build -p mdbook-dada --bin dada-spec
./target/debug/dada-spec run-check lean
./target/debug/dada-spec run-check lean-assumptions
./target/debug/dada-spec run-check rust
./target/debug/dada-spec run-check book
./target/debug/dada-spec mechanical-status

Each profile supplies an argument vector, working directory, tool-version command, and source inputs. The runner stores an immutable receipt under evidence/executions/, including both command outputs, exit statuses, and snapshots before and after execution. It retains failures too. A recorded pass requires exit zero, successful matching version probes, and unchanged source snapshots. The assumptions check rebuilds Lean imports before printing the axiom dependencies of the theorems named in lean/CheckAxioms.lean; its output covers those declarations, not every theorem in the project.

Source directories include their file membership and contents. The fixed exclusions are .git, .lake, target, book, and evidence directories; selecting one as an input is rejected. Profiles and runner sources are always included. These are declared source snapshots, not a hermetic capture: generated artifacts, review records, installed dependencies, environment variables, and network responses are not recorded as execution inputs. Endpoint comparison also cannot detect an edit that is restored before the second snapshot.

mechanical-status compares the latest receipt for each named check with its current profile and source inputs. A later failure or stale receipt cannot be replaced silently by an older success. A timestamp tie is treated conservatively: any stale or failing receipt at that time prevents a reported pass. Timestamps are local provenance, not an authenticated ordering service.

dada-spec check and the ordinary Cargo evidence test validate retained receipt integrity without executing commands. They do not require a fresh mechanical pass: requiring the Cargo test to have a successful receipt for its own run would be circular. Use mechanical-status to require current recorded passes. Records are grouped by named check, not attributed automatically to every specification unit. Neither hashes nor a saved exit code authenticate who ran the command or establish correspondence with the prose.

Reviewing links and reading order

A definition link should save the reader a search. The plugin extracts links from existing units; reviewers check whether any are missing and whether their destinations explain the right subject. No extra Markdown annotations are needed.

Inspect the inventory

From v2/, run:

cargo run -p mdbook-dada --bin dada-spec -- links
cargo run -p mdbook-dada --bin dada-spec -- links --json

The output lists occurrences, destinations, reading order, candidate cycles, and required audit subjects. The JSON is useful for preparing review work; it is a derived inventory, not another source file to maintain.

The link inventory records each authored link in a structured unit: its source range, destination, label, syntax, and position in the book. It recognizes Markdown links, including reference-style links, anchor-reference roles, and MathJax \href commands. Literal code and comments do not introduce links. Authored HTML links and unsupported local URL forms are rejected rather than silently omitted. A published chapter cannot link to a chapter absent from SUMMARY.md.

An internal destination must resolve to the specified chapter and anchor; finding the same ID in another chapter is insufficient. Reading order follows SUMMARY.md, then source position within each chapter. A link into its own containing definition is classified as local, pending review of the actual defining passage. Chapters absent from the table of contents have unknown relative order; repair the table of contents before treating such a dependency as backward. Candidate cycles are reported without treating them as justified forward references.

Future notes receive the same link audits: proposals need readable explanations too. These editorial reviews do not claim that a proposal has a formalization.

mdbook-dada/src/links.rs:LinkInventory::build
#![allow(unused)]
fn main() {
pub fn build(inventory: &Inventory) -> Result<Self> {
        let markdown_root = inventory::relative_path(
            &inventory.root,
            &inventory
                .source_configuration
                .markdown_root(&inventory.root)?,
        )?;
        let summary_path = format!("{markdown_root}/SUMMARY.md");
        let summary = inventory
            .sources
            .get(&summary_path)
            .context("link order requires the configured book's SUMMARY.md")?;
        let mut chapters = Vec::new();
        let mut chapter_orders = BTreeMap::new();
        for (event, range) in Parser::new(summary).into_offset_iter() {
            if let Event::Start(Tag::Link { dest_url, .. }) = event {
                ensure!(
                    !external(&dest_url)?,
                    "{summary_path}:{}: external SUMMARY entries have no source order",
                    location(&summary_path, summary, range.clone()).line
                );
                ensure!(
                    !dest_url.contains(['#', '?']),
                    "{summary_path}: SUMMARY chapters cannot contain fragments or queries"
                );
                let path = chapter_path(&summary_path, &dest_url, &markdown_root)?;
                ensure!(
                    inventory.sources.contains_key(&path),
                    "{summary_path}: SUMMARY references missing chapter `{path}`"
                );
                ensure!(
                    !chapter_orders.contains_key(&path),
                    "{summary_path}: duplicate chapter `{path}` makes reading order ambiguous"
                );
                let order = chapters.len();
                chapter_orders.insert(path.clone(), order);
                chapters.push(Chapter {
                    path,
                    order,
                    summary_location: location(&summary_path, summary, range),
                });
            }
        }
        let mut targets = BTreeMap::new();
        let mut global_anchors = BTreeMap::new();
        let mut documents = BTreeMap::new();
        for (path, source) in &inventory.sources {
            let doc = document(source, path)?;
            let chapter_order = chapter_orders.get(path).copied();
            insert_target(
                &mut targets,
                Target {
                    key: path.clone(),
                    location: location(path, source, 0..source.len()),
                    anchor_location: location(path, source, 0..0),
                    kind: TargetKind::Chapter,
                    unit_id: None,
                    chapter_order,
                },
            )?;
            for unit in inventory
                .units
                .values()
                .filter(|unit| &unit.source_path == path)
            {
                let key = format!("{path}#claim-{}", unit.id);
                ensure!(
                    global_anchors
                        .insert(unit.id.clone(), key.clone())
                        .is_none(),
                    "{path}:{}: duplicate anchor `{}`",
                    location(path, source, unit.range.clone()).line,
                    unit.id
                );
                // The generated anchor is on the unit header, not at the actual
                // defining sentence. Target review must inspect the complete unit.
                insert_target(
                    &mut targets,
                    Target {
                        key,
                        location: location(path, source, unit.range.clone()),
                        anchor_location: location(
                            path,
                            source,
                            unit.range.start
                                ..unit.range.start
                                    + unit.raw.find('\n').map_or(unit.raw.len(), |end| end + 1),
                        ),
                        kind: TargetKind::Unit,
                        unit_id: Some(unit.id.clone()),
                        chapter_order,
                    },
                )?;
            }
            for role in crate::roles(&doc.markdown)? {
                if role.definition {
                    let key = format!("{path}#claim-{}", role.id);
                    ensure!(
                        global_anchors
                            .insert(role.id.clone(), key.clone())
                            .is_none(),
                        "{path}:{}: duplicate anchor `{}`",
                        location(path, source, role.range.clone()).line,
                        role.id
                    );
                    let unit_id = inventory
                        .units
                        .values()
                        .find(|unit| {
                            unit.source_path == *path && unit.range.contains(&role.range.start)
                        })
                        .map(|unit| unit.id.clone());
                    insert_target(
                        &mut targets,
                        Target {
                            key,
                            location: location(path, source, role.range.clone()),
                            anchor_location: location(path, source, role.range),
                            kind: TargetKind::LegacyAnchor,
                            unit_id,
                            chapter_order,
                        },
                    )?;
                }
            }
            let mut heading = None;
            let mut used = BTreeSet::new();
            let mut headings = Vec::new();
            for (event, range) in Parser::new_ext(&doc.markdown, Options::ENABLE_HEADING_ATTRIBUTES)
                .into_offset_iter()
            {
                match event {
                    Event::Start(Tag::Heading { id, level, .. }) => {
                        heading = Some((range, level, id.map(|id| id.into_string()), String::new()))
                    }
                    Event::Text(text) | Event::Code(text) if heading.is_some() => {
                        heading.as_mut().unwrap().3.push_str(&text)
                    }
                    Event::End(TagEnd::Heading(_)) => {
                        if let Some((range, level, explicit, text)) = heading.take() {
                            let base = explicit.unwrap_or_else(|| slug(&text));
                            let mut id = base.clone();
                            let mut suffix = 0;
                            while !used.insert(id.clone()) {
                                suffix += 1;
                                id = format!("{base}-{suffix}");
                            }
                            headings.push((range, level, id));
                        }
                    }
                    _ => {}
                }
            }
            for (index, (range, level, id)) in headings.iter().enumerate() {
                let unit = inventory
                    .units
                    .values()
                    .find(|unit| unit.source_path == *path && unit.range.contains(&range.start));
                let end = headings[index + 1..]
                    .iter()
                    .find(|(_, next_level, _)| next_level <= level)
                    .map_or(source.len(), |(next, _, _)| next.start)
                    .min(unit.map_or(source.len(), |unit| unit.range.end));
                insert_target(
                    &mut targets,
                    Target {
                        key: format!("{path}#{id}"),
                        location: location(path, source, range.start..end),
                        anchor_location: location(path, source, range.clone()),
                        kind: TargetKind::Heading,
                        unit_id: unit.map(|unit| unit.id.clone()),
                        chapter_order,
                    },
                )?;
            }
            let boundaries: Vec<_> = targets
                .values()
                .filter(|target| {
                    target.location.path == *path && target.kind != TargetKind::Chapter
                })
                .map(|target| target.anchor_location.range.start)
                .collect();
            for target in targets.values_mut().filter(|target| {
                target.location.path == *path && target.kind == TargetKind::LegacyAnchor
            }) {
                let end = if let Some(unit) = target
                    .unit_id
                    .as_ref()
                    .and_then(|id| inventory.units.get(id))
                {
                    unit.range.end
                } else {
                    boundaries
                        .iter()
                        .copied()
                        .filter(|start| *start > target.location.range.start)
                        .min()
                        .unwrap_or(source.len())
                };
                target.location.range.end = end;
            }
            documents.insert(path.clone(), doc);
        }
        let mut sources = BTreeMap::new();
        for unit in inventory.units.values() {
            let source = &inventory.sources[&unit.source_path];
            let mut occurrences = Vec::new();
            for raw in documents[&unit.source_path]
                .links
                .iter()
                .filter(|link| unit.range.contains(&link.range.start))
            {
                let source_location = location(&unit.source_path, source, raw.range.clone());
                let target = resolve(
                    raw,
                    &unit.source_path,
                    &markdown_root,
                    inventory,
                    &targets,
                    &global_anchors,
                )
                .with_context(|| {
                    format!(
                        "{}:{}: link `{}`",
                        source_location.path, source_location.line, raw.destination
                    )
                })?;
                if let LinkTarget::Internal { target } = &target {
                    ensure!(
                        !chapter_orders.contains_key(&unit.source_path) || target.chapter_order.is_some(),
                        "{}:{}: published chapter links to unpublished target `{}`; add the target chapter to SUMMARY.md so its .html page exists",
                        source_location.path, source_location.line, target.key
                    );
                }
                let direction = match &target {
                    LinkTarget::Internal { target }
                        if target.unit_id.as_deref() == Some(&unit.id)
                            || (target.location.path == unit.source_path
                                && target.location.range.contains(&raw.range.start)) =>
                    {
                        Direction::Local
                    }
                    LinkTarget::Internal { target } if target.location.path == unit.source_path => {
                        if target.location.range.start < raw.range.start {
                            Direction::Backward
                        } else {
                            Direction::Forward
                        }
                    }
                    LinkTarget::Internal { target } => {
                        match (chapter_orders.get(&unit.source_path), target.chapter_order) {
                            (Some(from), Some(to)) if *from < to => Direction::Forward,
                            (Some(_), Some(_)) => Direction::Backward,
                            _ => Direction::Unordered,
                        }
                    }
                    _ => Direction::External,
                };
                occurrences.push(LinkOccurrence {
                    id: format!("{}:{}", unit.id, occurrences.len() + 1),
                    source: source_location,
                    destination: raw.destination.clone(),
                    label: raw.label.clone(),
                    syntax: raw.syntax,
                    target,
                    direction,
                });
            }
            sources.insert(
                unit.id.clone(),
                SourceLinks {
                    unit_id: unit.id.clone(),
                    unit_kind: unit.kind,
                    audit_required: true,
                    location: location(&unit.source_path, source, unit.range.clone()),
                    occurrences,
                },
            );
        }
        let cycles = cycles(&sources);
        Ok(Self {
            sources,
            chapters,
            targets,
            cycles,
            summary_path,
        })
    }
}
mdbook-dada/tests/links.rs:inventory_reads_markdown_reference_roles_and_math_with_exact_ranges
#![allow(unused)]
fn main() {
#[test]
fn inventory_reads_markdown_reference_roles_and_math_with_exact_ranges() {
    let body = r"A [direct link](second.html#claim-second), [reference][ref], and {anchor-ref}`second`.

\\[ \href{second.html#claim-second}{\operatorname{target}_{x}} \\]

[ref]: second.md#claim-second

`[literal](missing.md)` and `\href{missing.md}{literal}`.

```text
[literal](missing.md)
\\[ \href{missing.md}{literal} \\]
```

<!-- [comment](missing.md) \\(\href{missing.md}{comment}\\) -->";
    let first = unit("first", body);
    let fixture = Fixture::new(
        "[First](first.md)\n- [Second](second.md)\n",
        &[
            ("first.md", first.clone()),
            ("second.md", unit("second", "Definition.")),
        ],
    );
    let inventory = fixture.inventory();
    let links = Links::build(&inventory).unwrap();
    let occurrences = &links.sources["first"].occurrences;
    assert_eq!(occurrences.len(), 4);
    assert_eq!(
        occurrences
            .iter()
            .map(|link| link.syntax)
            .collect::<Vec<_>>(),
        [
            LinkSyntax::Markdown,
            LinkSyntax::Markdown,
            LinkSyntax::AnchorRef,
            LinkSyntax::MathJax
        ]
    );
    for link in occurrences {
        assert_eq!(link.direction, Direction::Forward);
        assert!(first[link.source.range.clone()].contains(
            if link.syntax == LinkSyntax::Markdown {
                "["
            } else if link.syntax == LinkSyntax::MathJax {
                "\\href"
            } else {
                "{anchor-ref}"
            }
        ));
        assert!(
            matches!(&link.target, LinkTarget::Internal { target } if target.key == "md/second.md#claim-second")
        );
        assert!(links.occurrence(&link.id).is_some());
    }
    assert_eq!(links.inputs(&inventory).len(), inventory.sources.len());
}
}
mdbook-dada/tests/links.rs:reference_definitions_outside_unit_and_bare_math_directives_are_inventoried
#![allow(unused)]
fn main() {
#[test]
fn reference_definitions_outside_unit_and_bare_math_directives_are_inventoried() {
    let first = format!(
        "{}\n[outside]: second.md#claim-second\n",
        unit("first", "See [the definition][outside].")
    );
    let math = "```{grammar} grammar\n:status: draft\n\np ::= \\href{second.html#claim-second}{x}\\mid p.f\n```\n".to_owned();
    let fixture = Fixture::new(
        "- [First](first.md)\n- [Math](math.md)\n- [Second](second.md)",
        &[
            ("first.md", first),
            ("math.md", math),
            ("second.md", unit("second", "Definition.")),
        ],
    );
    let links = fixture.build().unwrap();
    assert_eq!(links.sources["first"].occurrences.len(), 1);
    assert_eq!(links.sources["grammar"].occurrences.len(), 1);
    assert_eq!(
        links.sources["grammar"].occurrences[0].syntax,
        LinkSyntax::MathJax
    );
}
}
mdbook-dada/tests/links.rs:relative_paths_preserve_target_chapter_and_wrong_path_does_not_match_global_id
#![allow(unused)]
fn main() {
#[test]
fn relative_paths_preserve_target_chapter_and_wrong_path_does_not_match_global_id() {
    let fixture = Fixture::new(
        "- [A](nested/a.md)\n- [B](b.md)",
        &[
            ("nested/a.md", unit("a", "[B](.././b.html#claim-b)")),
            ("b.md", unit("b", "B.")),
        ],
    );
    assert!(
        matches!(&fixture.build().unwrap().sources["a"].occurrences[0].target, LinkTarget::Internal { target } if target.key == "md/b.md#claim-b")
    );
    fs::write(
        fixture.0.join("md/nested/a.md"),
        unit("a", "[B](a.md#claim-b)"),
    )
    .unwrap();
    let error = format!("{:#}", fixture.build().unwrap_err());
    assert!(error.contains("md/nested/a.md:4"), "{error}");
    assert!(error.contains("path and anchor"), "{error}");
}
}
mdbook-dada/tests/links.rs:order_comes_from_summary_and_byte_position_not_filename_or_unit_id
#![allow(unused)]
fn main() {
#[test]
fn order_comes_from_summary_and_byte_position_not_filename_or_unit_id() {
    let fixture = Fixture::new("[Last filename first](z.md)\n- [Group](group.md)\n  - [Then A](a.md)\n\n[Appendix](appendix.md)", &[
        ("z.md", unit("z", "[forward](a.md#claim-a)")),
        ("group.md", "# Group".into()),
        ("a.md", format!("{}{}", unit("a", "[back](z.md#claim-z), [later](#claim-local), [self](#claim-a)"), unit("local", "[earlier](#claim-a)"))),
        ("appendix.md", unit("appendix", "[earlier](a.md#claim-a)")),
        ("hidden.md", unit("hidden", "[unordered](a.md#claim-a)")),
    ]);
    let links = fixture.build().unwrap();
    assert_eq!(
        links
            .chapters
            .iter()
            .map(|c| c.path.as_str())
            .collect::<Vec<_>>(),
        ["md/z.md", "md/group.md", "md/a.md", "md/appendix.md"]
    );
    assert_eq!(
        links.sources["z"].occurrences[0].direction,
        Direction::Forward
    );
    assert_eq!(
        links.sources["a"]
            .occurrences
            .iter()
            .map(|l| l.direction)
            .collect::<Vec<_>>(),
        [Direction::Backward, Direction::Forward, Direction::Local]
    );
    assert_eq!(
        links.sources["hidden"].occurrences[0].direction,
        Direction::Unordered
    );
    assert!(links
        .cycles
        .iter()
        .any(|cycle| cycle == &["a", "local", "z"]));
}
}
mdbook-dada/tests/evidence_validation.rs:configured_renderer_rejects_a_correct_claim_in_the_wrong_chapter
#![allow(unused)]
fn main() {
#[test]
fn configured_renderer_rejects_a_correct_claim_in_the_wrong_chapter() {
    let fixture = Fixture::new();
    fixture.write("md/other.md", "# Other chapter\n");
    let source = MODEL.replace(
        "The empty list has no variables:",
        "[Variables](other.md#claim-model.variable) are the list elements:",
    );
    fixture.write("md/model.md", &source);
    let mut book = chapter(&source);
    let error = mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book)
        .unwrap_err();
    let diagnostic = format!("{error:#}");
    assert!(diagnostic.contains("md/model.md:"), "{diagnostic}");
    assert!(
        diagnostic.contains("other.md#claim-model.variable"),
        "{diagnostic}"
    );
}
}

Review three questions

A link-coverage review examines one complete unit, including prose, inline math, and display math. Every referenced concept, operation, judgment, and equation must have a definition link. The defining occurrence needs no self-link, and locally bound variables need an introduction and scope rather than links.

The review explains coverage separately for prose and mathematics and classifies every occurrence in the link inventory as conceptual or navigation, with a reason. A navigation link offers optional further reading; it cannot stand in for a definition the passage needs. Reviewers must also look for unlinked uses: the extractor cannot discover a missing link by examining existing links alone.

The validator requires exactly the extracted occurrence set, including repeated links. Missing, extra, or duplicate assessments fail. It checks the existence and freshness of the review, not whether its coverage judgment is correct.

mdbook-dada/src/link_audit.rs:AuditInventory::build
#![allow(unused)]
fn main() {
pub fn build(inventory: &Inventory) -> Result<Self> {
        let links = LinkInventory::build(inventory)?;
        let mut manifests = BTreeMap::new();
        for source in links
            .sources
            .values()
            .filter(|source| source.audit_required)
        {
            let coverage = Manifest::Coverage {
                source: source.clone(),
            };
            manifests.insert(coverage.subject(), coverage);
            for occurrence in &source.occurrences {
                if let LinkTarget::Internal { target } = &occurrence.target {
                    let target = Manifest::Target {
                        target: target.clone(),
                    };
                    manifests.insert(target.subject(), target);
                    if matches!(
                        occurrence.direction,
                        Direction::Forward | Direction::Local | Direction::Unordered
                    ) {
                        let forward = Manifest::Forward {
                            source_unit: source.unit_id.clone(),
                            source: source.location.clone(),
                            occurrence: occurrence.clone(),
                        };
                        manifests.insert(forward.subject(), forward);
                    }
                }
            }
        }
        Ok(Self { links, manifests })
    }
}
mdbook-dada/src/link_audit.rs:validate_review
#![allow(unused)]
fn main() {
/// Validate against the bundle's immutable manifest as well as the general
/// review schema. Current-source comparison remains the evidence engine's job.
pub fn validate_review(bundle: &ReviewBundle, review: &ReviewRecord) -> Vec<String> {
    if !is_subject(&bundle.unit) {
        return if review.audit.is_some() {
            vec!["correspondence review cannot carry a link audit assessment".into()]
        } else {
            Vec::new()
        };
    }
    let manifest = match manifest(bundle) {
        Ok(manifest) => manifest,
        Err(error) => return vec![format!("{error:#}")],
    };
    let Some(assessment) = &review.audit else {
        return vec!["link audit review requires a purpose-specific audit assessment".into()];
    };
    let mut errors = Vec::new();
    match (&manifest, assessment) {
        (
            Manifest::Coverage { source },
            Assessment::Coverage {
                prose,
                mathematics,
                links,
            },
        ) => {
            nonempty(&mut errors, "prose coverage rationale", prose);
            nonempty(&mut errors, "mathematics coverage rationale", mathematics);
            let expected: BTreeSet<_> = source
                .occurrences
                .iter()
                .map(|link| link.id.as_str())
                .collect();
            let actual: BTreeSet<_> = links.iter().map(|link| link.occurrence.as_str()).collect();
            if actual.len() != links.len() {
                errors.push("duplicate link occurrence assessment".into());
            }
            if actual != expected {
                errors
                    .push("coverage must classify exactly every generated link occurrence".into());
            }
            for link in links {
                nonempty(
                    &mut errors,
                    "link classification rationale",
                    &link.rationale,
                );
                if review.conclusion == Conclusion::Corresponds
                    && link.role == LinkRole::Conceptual
                    && source.occurrences.iter().any(|occurrence| {
                        occurrence.id == link.occurrence
                            && !matches!(occurrence.target, LinkTarget::Internal { .. })
                    })
                {
                    errors.push("conceptual links need a local, snapshotted defining target; external and asset links may only be navigation/source citations".into());
                }
            }
        }
        (
            Manifest::Target { target },
            Assessment::Target {
                subject,
                definition,
                clarity,
                independence,
            },
        ) => {
            nonempty(&mut errors, "target subject", subject);
            nonempty(&mut errors, "target clarity rationale", clarity);
            nonempty(&mut errors, "target independence rationale", independence);
            errors.extend(span_errors(bundle, definition, &target.location));
        }
        (Manifest::Forward { .. }, Assessment::Forward { assessment }) => match assessment {
            OrderAssessment::Forward {
                necessity,
                signposting,
                signpost,
                minimal_use,
            } => {
                for (name, value) in [
                    (
                        "necessity (including rearrangement alternatives)",
                        necessity,
                    ),
                    ("explicit forward signposting", signposting),
                    ("minimal reliance", minimal_use),
                ] {
                    nonempty(&mut errors, name, value);
                }
                // The source-unit range is independently derived and hashed in
                // the manifest, rather than trusting mutable retrieval line numbers.
                if let Manifest::Forward { source, .. } = &manifest {
                    errors.extend(span_errors(bundle, signpost, source));
                }
            }
            OrderAssessment::Backward { rationale } | OrderAssessment::Navigation { rationale } => {
                nonempty(&mut errors, "order disposition rationale", rationale)
            }
        },
        _ => {
            errors.push("audit assessment has the wrong purpose for this generated subject".into())
        }
    }
    errors
}
}
mdbook-dada/tests/link_audit.rs:coverage_requires_each_occurrence_once_and_both_prose_and_math_rationales
#![allow(unused)]
fn main() {
#[test]
fn coverage_requires_each_occurrence_once_and_both_prose_and_math_rationales() {
    let fixture = Fixture::new();
    let bundle = fixture.prepare("links.coverage/alpha");
    for mutation in 0..4 {
        let mut review = synthetic_review(&bundle);
        if let Some(Assessment::Coverage {
            prose,
            mathematics,
            links,
        }) = &mut review.audit
        {
            match mutation {
                0 => links.clear(),
                1 => links.push(links[0].clone()),
                2 => prose.clear(),
                _ => mathematics.clear(),
            }
        }
        assert!(!evidence::validate_review(&bundle, &review).is_empty());
    }
    let mut review = synthetic_review(&bundle);
    review.audit = None;
    assert!(!evidence::validate_review(&bundle, &review).is_empty());
}
}
mdbook-dada/tests/link_audit.rs:complete_link_audits_pass_but_preparation_alone_does_not
#![allow(unused)]
fn main() {
#[test]
fn complete_link_audits_pass_but_preparation_alone_does_not() {
    let fixture = Fixture::new();
    for id in fixture.ids() {
        evidence::save_bundle(&fixture.inventory(), &fixture.prepare(&id)).unwrap();
    }
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(!report.is_ok());
    assert!(report
        .issues
        .iter()
        .any(|issue| issue.unit.as_deref() == Some("links.coverage/alpha")));
    fixture.complete();
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(report.is_ok(), "{}", report.render(&fixture.inventory()));
}
}
mdbook-dada/tests/link_audit.rs:conceptual_external_links_require_an_inspectable_local_definition
#![allow(unused)]
fn main() {
#[test]
fn conceptual_external_links_require_an_inspectable_local_definition() {
    let fixture = Fixture::new();
    fixture.write(
        "md/model.md",
        &SOURCE.replace(
            "[Beta](#claim-beta)",
            "[Beta](https://example.invalid/beta)",
        ),
    );
    let bundle = fixture.prepare("links.coverage/alpha");
    let mut review = synthetic_review(&bundle);
    assert!(evidence::validate_review(&bundle, &review)
        .iter()
        .any(|error| error.contains("local, snapshotted")));
    review.conclusion = Conclusion::Mismatch;
    assert!(evidence::validate_review(&bundle, &review).is_empty());
}
}

A target-clarity review names a subject in the link inventory and selects its defining passage in the retained source. It explains why the landing immediately identifies that subject and why the definition is independently understandable. A precise source span does not excuse a buried destination: split the block or retarget the link when a reader would still have to search.

The validator checks that the selected span is nonempty UTF-8 text within the resolved destination. Review supplies the judgment that it is the relevant definition. A chapter or section link used only for navigation is reviewed as such; it must not be presented as a precise concept definition.

mdbook-dada/src/link_audit.rs:validate_review
#![allow(unused)]
fn main() {
/// Validate against the bundle's immutable manifest as well as the general
/// review schema. Current-source comparison remains the evidence engine's job.
pub fn validate_review(bundle: &ReviewBundle, review: &ReviewRecord) -> Vec<String> {
    if !is_subject(&bundle.unit) {
        return if review.audit.is_some() {
            vec!["correspondence review cannot carry a link audit assessment".into()]
        } else {
            Vec::new()
        };
    }
    let manifest = match manifest(bundle) {
        Ok(manifest) => manifest,
        Err(error) => return vec![format!("{error:#}")],
    };
    let Some(assessment) = &review.audit else {
        return vec!["link audit review requires a purpose-specific audit assessment".into()];
    };
    let mut errors = Vec::new();
    match (&manifest, assessment) {
        (
            Manifest::Coverage { source },
            Assessment::Coverage {
                prose,
                mathematics,
                links,
            },
        ) => {
            nonempty(&mut errors, "prose coverage rationale", prose);
            nonempty(&mut errors, "mathematics coverage rationale", mathematics);
            let expected: BTreeSet<_> = source
                .occurrences
                .iter()
                .map(|link| link.id.as_str())
                .collect();
            let actual: BTreeSet<_> = links.iter().map(|link| link.occurrence.as_str()).collect();
            if actual.len() != links.len() {
                errors.push("duplicate link occurrence assessment".into());
            }
            if actual != expected {
                errors
                    .push("coverage must classify exactly every generated link occurrence".into());
            }
            for link in links {
                nonempty(
                    &mut errors,
                    "link classification rationale",
                    &link.rationale,
                );
                if review.conclusion == Conclusion::Corresponds
                    && link.role == LinkRole::Conceptual
                    && source.occurrences.iter().any(|occurrence| {
                        occurrence.id == link.occurrence
                            && !matches!(occurrence.target, LinkTarget::Internal { .. })
                    })
                {
                    errors.push("conceptual links need a local, snapshotted defining target; external and asset links may only be navigation/source citations".into());
                }
            }
        }
        (
            Manifest::Target { target },
            Assessment::Target {
                subject,
                definition,
                clarity,
                independence,
            },
        ) => {
            nonempty(&mut errors, "target subject", subject);
            nonempty(&mut errors, "target clarity rationale", clarity);
            nonempty(&mut errors, "target independence rationale", independence);
            errors.extend(span_errors(bundle, definition, &target.location));
        }
        (Manifest::Forward { .. }, Assessment::Forward { assessment }) => match assessment {
            OrderAssessment::Forward {
                necessity,
                signposting,
                signpost,
                minimal_use,
            } => {
                for (name, value) in [
                    (
                        "necessity (including rearrangement alternatives)",
                        necessity,
                    ),
                    ("explicit forward signposting", signposting),
                    ("minimal reliance", minimal_use),
                ] {
                    nonempty(&mut errors, name, value);
                }
                // The source-unit range is independently derived and hashed in
                // the manifest, rather than trusting mutable retrieval line numbers.
                if let Manifest::Forward { source, .. } = &manifest {
                    errors.extend(span_errors(bundle, signpost, source));
                }
            }
            OrderAssessment::Backward { rationale } | OrderAssessment::Navigation { rationale } => {
                nonempty(&mut errors, "order disposition rationale", rationale)
            }
        },
        _ => {
            errors.push("audit assessment has the wrong purpose for this generated subject".into())
        }
    }
    errors
}
}
mdbook-dada/tests/link_audit.rs:target_spans_cannot_escape_or_select_empty_text
#![allow(unused)]
fn main() {
#[test]
fn target_spans_cannot_escape_or_select_empty_text() {
    let fixture = Fixture::new();
    let bundle = fixture.prepare(&link_audit::target_subject("md/model.md#claim-beta"));
    for mutation in 0..4 {
        let mut review = synthetic_review(&bundle);
        if let Some(Assessment::Target {
            definition,
            clarity,
            ..
        }) = &mut review.audit
        {
            match mutation {
                0 => definition.path = "md/other.md".into(),
                1 => definition.start = 0,
                2 => definition.end = definition.start,
                _ => clarity.clear(),
            }
        }
        assert!(!evidence::validate_review(&bundle, &review).is_empty());
    }
    fixture.write(
        "md/model.md",
        &SOURCE.replace("Beta denotes", "Beta α denotes"),
    );
    let bundle = fixture.prepare(&link_audit::target_subject("md/model.md#claim-beta"));
    let mut review = synthetic_review(&fixture.prepare("links.coverage/alpha"));
    let chapter = &bundle
        .inputs
        .iter()
        .find(|input| input.key == "context:link-chapter:md/model.md")
        .unwrap()
        .content;
    let offset = chapter.find('α').unwrap();
    review.bundle = bundle.digest.clone();
    review.examined = bundle
        .inputs
        .iter()
        .filter(|input| input.requires_examination())
        .map(|input| input.key.clone())
        .collect();
    review.audit = Some(Assessment::Target {
        subject: "Beta".into(),
        definition: DefinitionSpan {
            path: "md/model.md".into(),
            start: offset + 1,
            end: offset + 2,
        },
        clarity: "Synthetic clarity.".into(),
        independence: "Synthetic independence.".into(),
    });
    assert!(evidence::validate_review(&bundle, &review)
        .iter()
        .any(|error| error.contains("UTF-8")));
}
}
mdbook-dada/tests/link_audit.rs:independent_positive_reviews_cannot_disagree_on_backward_links_or_target_spans
#![allow(unused)]
fn main() {
#[test]
fn independent_positive_reviews_cannot_disagree_on_backward_links_or_target_spans() {
    let fixture = Fixture::new();
    fixture.complete();
    let bundle = fixture.prepare("links.coverage/beta");
    let mut conflict = synthetic_review(&bundle);
    if let Some(Assessment::Coverage { links, .. }) = &mut conflict.audit {
        links[0].role = LinkRole::Navigation;
    }
    evidence::record(&fixture.inventory(), &bundle, &conflict).unwrap();
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(report
        .issues
        .iter()
        .any(|issue| issue.message.contains("coverage reviews disagree")));
    let bundle = fixture.prepare(&link_audit::target_subject("md/model.md#claim-alpha"));
    let mut conflict = synthetic_review(&bundle);
    if let Some(Assessment::Target { definition, .. }) = &mut conflict.audit {
        definition.end -= 1;
    }
    evidence::record(&fixture.inventory(), &bundle, &conflict).unwrap();
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(report
        .issues
        .iter()
        .any(|issue| issue.message.contains("target reviews disagree")));
}
}

A reference-order review resolves each forward, local, or unordered internal occurrence in the link inventory. It agrees with the coverage classification and uses the reviewed defining passage, not merely the block’s header, to establish whether a concept has already been introduced.

Prefer moving the definition earlier, moving its use later, or splitting a multi-part explanation. Retaining a forward conceptual reference requires all three explanations:

  • Necessity: which rearrangements were considered and why they would prevent a coherent introduction.
  • Signposting: the exact source passage that explicitly tells the reader the definition comes later, and where to find it.
  • Minimal use: the facts needed at this point, where the text states them, and which details it defers.

A motivating example may justify a forward reference; being an example is not an automatic exemption. A dependency cycle is not an exemption either. Navigation-only links need an explicit classification, and a local backward reference must point to a defining passage before its use. Conflicting active reviews block validation.

mdbook-dada/src/link_audit.rs:AuditInventory::build
#![allow(unused)]
fn main() {
pub fn build(inventory: &Inventory) -> Result<Self> {
        let links = LinkInventory::build(inventory)?;
        let mut manifests = BTreeMap::new();
        for source in links
            .sources
            .values()
            .filter(|source| source.audit_required)
        {
            let coverage = Manifest::Coverage {
                source: source.clone(),
            };
            manifests.insert(coverage.subject(), coverage);
            for occurrence in &source.occurrences {
                if let LinkTarget::Internal { target } = &occurrence.target {
                    let target = Manifest::Target {
                        target: target.clone(),
                    };
                    manifests.insert(target.subject(), target);
                    if matches!(
                        occurrence.direction,
                        Direction::Forward | Direction::Local | Direction::Unordered
                    ) {
                        let forward = Manifest::Forward {
                            source_unit: source.unit_id.clone(),
                            source: source.location.clone(),
                            occurrence: occurrence.clone(),
                        };
                        manifests.insert(forward.subject(), forward);
                    }
                }
            }
        }
        Ok(Self { links, manifests })
    }
}
mdbook-dada/src/link_audit.rs:validate_review
#![allow(unused)]
fn main() {
/// Validate against the bundle's immutable manifest as well as the general
/// review schema. Current-source comparison remains the evidence engine's job.
pub fn validate_review(bundle: &ReviewBundle, review: &ReviewRecord) -> Vec<String> {
    if !is_subject(&bundle.unit) {
        return if review.audit.is_some() {
            vec!["correspondence review cannot carry a link audit assessment".into()]
        } else {
            Vec::new()
        };
    }
    let manifest = match manifest(bundle) {
        Ok(manifest) => manifest,
        Err(error) => return vec![format!("{error:#}")],
    };
    let Some(assessment) = &review.audit else {
        return vec!["link audit review requires a purpose-specific audit assessment".into()];
    };
    let mut errors = Vec::new();
    match (&manifest, assessment) {
        (
            Manifest::Coverage { source },
            Assessment::Coverage {
                prose,
                mathematics,
                links,
            },
        ) => {
            nonempty(&mut errors, "prose coverage rationale", prose);
            nonempty(&mut errors, "mathematics coverage rationale", mathematics);
            let expected: BTreeSet<_> = source
                .occurrences
                .iter()
                .map(|link| link.id.as_str())
                .collect();
            let actual: BTreeSet<_> = links.iter().map(|link| link.occurrence.as_str()).collect();
            if actual.len() != links.len() {
                errors.push("duplicate link occurrence assessment".into());
            }
            if actual != expected {
                errors
                    .push("coverage must classify exactly every generated link occurrence".into());
            }
            for link in links {
                nonempty(
                    &mut errors,
                    "link classification rationale",
                    &link.rationale,
                );
                if review.conclusion == Conclusion::Corresponds
                    && link.role == LinkRole::Conceptual
                    && source.occurrences.iter().any(|occurrence| {
                        occurrence.id == link.occurrence
                            && !matches!(occurrence.target, LinkTarget::Internal { .. })
                    })
                {
                    errors.push("conceptual links need a local, snapshotted defining target; external and asset links may only be navigation/source citations".into());
                }
            }
        }
        (
            Manifest::Target { target },
            Assessment::Target {
                subject,
                definition,
                clarity,
                independence,
            },
        ) => {
            nonempty(&mut errors, "target subject", subject);
            nonempty(&mut errors, "target clarity rationale", clarity);
            nonempty(&mut errors, "target independence rationale", independence);
            errors.extend(span_errors(bundle, definition, &target.location));
        }
        (Manifest::Forward { .. }, Assessment::Forward { assessment }) => match assessment {
            OrderAssessment::Forward {
                necessity,
                signposting,
                signpost,
                minimal_use,
            } => {
                for (name, value) in [
                    (
                        "necessity (including rearrangement alternatives)",
                        necessity,
                    ),
                    ("explicit forward signposting", signposting),
                    ("minimal reliance", minimal_use),
                ] {
                    nonempty(&mut errors, name, value);
                }
                // The source-unit range is independently derived and hashed in
                // the manifest, rather than trusting mutable retrieval line numbers.
                if let Manifest::Forward { source, .. } = &manifest {
                    errors.extend(span_errors(bundle, signpost, source));
                }
            }
            OrderAssessment::Backward { rationale } | OrderAssessment::Navigation { rationale } => {
                nonempty(&mut errors, "order disposition rationale", rationale)
            }
        },
        _ => {
            errors.push("audit assessment has the wrong purpose for this generated subject".into())
        }
    }
    errors
}
}
mdbook-dada/src/link_audit.rs:cross_validate
#![allow(unused)]
fn main() {
/// Cross-review consistency is checked from current, active positive records.
/// No review output is smuggled into another review's source hash. A later
/// classification or defining-span change therefore causes a new check.
pub fn cross_validate(
    audits: &AuditInventory,
    active: &BTreeMap<String, Vec<ReviewRecord>>,
) -> Vec<(String, String)> {
    let mut errors = Vec::new();
    let positives = |id: &str| -> Vec<&ReviewRecord> {
        active
            .get(id)
            .into_iter()
            .flatten()
            .filter(|review| review.conclusion == Conclusion::Corresponds)
            .collect()
    };
    // Independent positive reviews cannot disagree silently, even when the
    // link is unambiguously backward and needs no forward-reference subject.
    for (id, records) in active {
        match audits.manifests.get(id) {
            Some(Manifest::Coverage { source }) => {
                for occurrence in &source.occurrences {
                    let roles: BTreeSet<_> = records
                        .iter()
                        .filter_map(|review| match &review.audit {
                            Some(Assessment::Coverage { links, .. }) => links
                                .iter()
                                .find(|link| link.occurrence == occurrence.id)
                                .map(|link| match link.role {
                                    LinkRole::Conceptual => 0,
                                    LinkRole::Navigation => 1,
                                }),
                            _ => None,
                        })
                        .collect();
                    if roles.len() > 1 {
                        errors.push((
                            id.clone(),
                            format!("active coverage reviews disagree about {}", occurrence.id),
                        ));
                    }
                }
            }
            Some(Manifest::Target { .. }) => {
                let definitions: Vec<_> = records
                    .iter()
                    .filter_map(|review| match &review.audit {
                        Some(Assessment::Target { definition, .. }) => Some(definition),
                        _ => None,
                    })
                    .collect();
                if definitions.windows(2).any(|pair| pair[0] != pair[1]) {
                    errors.push((
                        id.clone(),
                        "active target reviews disagree about the defining occurrence".into(),
                    ));
                }
            }
            _ => {}
        }
    }
    for (id, records) in active {
        let Some(Manifest::Forward {
            source_unit,
            occurrence,
            ..
        }) = audits.manifests.get(id)
        else {
            continue;
        };
        let LinkTarget::Internal { target } = &occurrence.target else {
            continue;
        };
        let coverage = positives(&coverage_subject(source_unit));
        let targets = positives(&target_subject(&target.key));
        let roles: BTreeSet<_> = coverage
            .iter()
            .filter_map(|review| match &review.audit {
                Some(Assessment::Coverage { links, .. }) => links
                    .iter()
                    .find(|link| link.occurrence == occurrence.id)
                    .map(|link| match link.role {
                        LinkRole::Conceptual => 0,
                        LinkRole::Navigation => 1,
                    }),
                _ => None,
            })
            .collect();
        if coverage.is_empty() || targets.is_empty() {
            continue;
        } // Their missing evidence is separately blocking.
        if roles.len() != 1 {
            errors.push((
                id.clone(),
                "active coverage reviews disagree about this link's conceptual role".into(),
            ));
            continue;
        }
        let role = *roles.first().unwrap();
        let definitions: Vec<_> = targets
            .iter()
            .filter_map(|review| match &review.audit {
                Some(Assessment::Target { definition, .. }) => Some(definition),
                _ => None,
            })
            .collect();
        for review in records
            .iter()
            .filter(|review| review.conclusion == Conclusion::Corresponds)
        {
            let Some(Assessment::Forward { assessment }) = &review.audit else {
                continue;
            };
            let valid = match assessment {
                OrderAssessment::Navigation { .. } => role == 1,
                OrderAssessment::Forward { .. } => {
                    role == 0
                        && !definitions.is_empty()
                        && definitions.iter().all(|definition| {
                            matches!(
                                definition_direction(&audits.links, occurrence, target, definition),
                                Direction::Forward | Direction::Unordered
                            )
                        })
                }
                OrderAssessment::Backward { .. } => {
                    role == 0
                        && !definitions.is_empty()
                        && definitions.iter().all(|definition| {
                            definition_direction(&audits.links, occurrence, target, definition)
                                == Direction::Backward
                        })
                }
            };
            if !valid {
                errors.push((id.clone(), "order disposition disagrees with current coverage or the actual defining occurrence".into()));
            }
        }
    }
    errors
}
}
mdbook-dada/tests/link_audit.rs:forward_exceptions_require_all_three_reasons_and_a_real_source_span
#![allow(unused)]
fn main() {
#[test]
fn forward_exceptions_require_all_three_reasons_and_a_real_source_span() {
    let fixture = Fixture::new();
    let bundle = fixture.prepare(&fixture.candidate("alpha"));
    for mutation in 0..4 {
        let mut review = synthetic_review(&bundle);
        if let Some(Assessment::Forward {
            assessment:
                OrderAssessment::Forward {
                    necessity,
                    signposting,
                    signpost,
                    minimal_use,
                },
        }) = &mut review.audit
        {
            match mutation {
                0 => necessity.clear(),
                1 => signposting.clear(),
                2 => minimal_use.clear(),
                _ => signpost.start = 0,
            }
        }
        assert!(!evidence::validate_review(&bundle, &review).is_empty());
    }
}
}
mdbook-dada/tests/link_audit.rs:a_local_link_before_its_actual_definition_cannot_be_called_backward
#![allow(unused)]
fn main() {
#[test]
fn a_local_link_before_its_actual_definition_cannot_be_called_backward() {
    let fixture = Fixture::new();
    fixture.complete();
    let id = fixture.candidate("local");
    let bundle = fixture.prepare(&id);
    let mut review = synthetic_review(&bundle);
    review.audit = Some(Assessment::Forward {
        assessment: OrderAssessment::Backward {
            rationale: "The block anchor is earlier; this is insufficient.".into(),
        },
    });
    fixture.save_replacement(&id, review);
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(report
        .issues
        .iter()
        .any(|issue| issue.message.contains("actual defining occurrence")));
}
}
mdbook-dada/tests/link_audit.rs:navigation_exemption_must_agree_with_current_coverage
#![allow(unused)]
fn main() {
#[test]
fn navigation_exemption_must_agree_with_current_coverage() {
    let fixture = Fixture::new();
    fixture.complete();
    let id = fixture.candidate("alpha");
    let bundle = fixture.prepare(&id);
    let mut review = synthetic_review(&bundle);
    review.audit = Some(Assessment::Forward {
        assessment: OrderAssessment::Navigation {
            rationale: "Synthetic navigation classification.".into(),
        },
    });
    fixture.save_replacement(&id, review);
    assert!(!evidence::check(&fixture.inventory()).unwrap().is_ok());
    let coverage_id = "links.coverage/alpha";
    let mut coverage = synthetic_review(&fixture.prepare(coverage_id));
    if let Some(Assessment::Coverage { links, .. }) = &mut coverage.audit {
        links[0].role = LinkRole::Navigation;
    }
    fixture.save_replacement(coverage_id, coverage);
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(report.is_ok(), "{}", report.render(&fixture.inventory()));
}
}
mdbook-dada/tests/link_audit.rs:source_movement_summary_order_and_reference_definitions_invalidate_inputs
#![allow(unused)]
fn main() {
#[test]
fn source_movement_summary_order_and_reference_definitions_invalidate_inputs() {
    let fixture = Fixture::new();
    let bundle = fixture.prepare("links.coverage/alpha");
    fixture.write("md/model.md", &format!("\n{SOURCE}"));
    assert!(!evidence::validate_bundle(&fixture.inventory(), &bundle)
        .unwrap()
        .is_empty());
    fixture.write("md/model.md", SOURCE);
    fixture.write("md/other.md", "# Other\n");
    fixture.write(
        "md/SUMMARY.md",
        "# Summary\n\n- [Other](other.md)\n- [Fixture](model.md)\n",
    );
    assert!(!evidence::validate_bundle(&fixture.inventory(), &bundle)
        .unwrap()
        .is_empty());
    fixture.write(
        "md/model.md",
        &SOURCE
            .replace("[Beta](#claim-beta)", "[Beta][beta-ref]")
            .replace(
                "Beta denotes the second thing.",
                "Beta denotes the second thing.\n\n[beta-ref]: #claim-beta\n",
            ),
    );
    let bundle = fixture.prepare("links.coverage/alpha");
    let changed = fs::read_to_string(fixture.0.join("md/model.md"))
        .unwrap()
        .replace("[beta-ref]: #claim-beta", "[beta-ref]: #claim-alpha");
    fixture.write("md/model.md", &changed);
    assert!(!evidence::validate_bundle(&fixture.inventory(), &bundle)
        .unwrap()
        .is_empty());
}
}

Prepare and record evidence

Use the subject IDs printed by dada-spec links with the existing preparation and recording workflow:

dada-spec prepare links.coverage/UNIT_ID
dada-spec prepare links.target/TARGET_HASH
dada-spec prepare links.forward/OCCURRENCE_HASH
dada-spec record BUNDLE_PATH REVIEW_JSON_PATH

Each decision retains the ordinary reviewer, provenance, examined inputs, conclusion, rationale, limitations, and superseded decisions. Its audit field adds the question-specific assessment. See the Rust Assessment schema in mdbook-dada/src/link_audit.rs for the exact JSON fields. Preparation never creates an affirmative decision.

Coverage packets retain the complete source unit, its explicit context, and linked destinations. Target packets retain the destination. Order packets retain both ends. All three also retain relevant complete chapters, a serialized position/order inventory, SUMMARY.md, policy, and tool/rendering inputs. Reviewers examine the required audit: inputs and consult the retained chapter context to assess landing clarity and possible rearrangements. Byte positions participate in freshness, so moving unchanged text can invalidate an audit. Whole-chapter snapshots conservatively invalidate affected audits after other edits in those chapters too. Evidence outputs are not inputs to other evidence; current active decisions are cross-checked for consistency instead.

dada-spec check and cargo test --workspace require these reviews alongside formal correspondence evidence. Draft units still receive editorial audits; their unfinished formalization separately blocks correspondence. The checker never invokes an agent, fetches a website, or decides whether a rationale is persuasive. An independent reader can inspect the retained inputs and reasoning.

Extending the model in layers

Each semantic layer should be understandable on its own. Keep its syntax, states, execution rules, examples, and invariants in distinct Lean modules within the same Lake project. Shared proof infrastructure can be factored out without making the earlier language depend on concepts introduced by a later one. The book follows that same conceptual progression.

The opening chapters separate execution from static typing:

ChapterScope
Given: operational semanticsClasses, including empty classes; place and value expressions; p→ transfers a unique owner.
Given: typing and soundnessSigned views track initialization and moves; progress, preservation, and completion are proved.
Shared: operational semanticsExtend execution with sharing of values, written p→share; traversal through shared ownership yields a shared copy.
Shared: typing and soundnessPermissions determine whether giving moves or copies; views track accessible fields. Progress, preservation, and completion are proved.

| Functions and methods | Explicit call frames, return destinations, and eager collection across all live roots; progress and preservation allow recursive execution. |

The first two operational models live in lean/Unique/ and lean/Shared/; lean/Correspondence/UniqueShared.lean proves the embedding preserves and reflects steps, finite executions, and execution boundaries. Shared graph reasoning lives in lean/Common/. Unique/Frames and Shared/Frames are the program machines, wrapping the existing local statement relations with eager collection and initial-frame exit. Their frame safety results and Correspondence/UniqueSharedFrames cover these public boundaries.

Both layers support explicit Class → { x, y } unpacking patterns. Shared requires a unique reference to the container; its fields may be shared. The typing chapters define nominal types and signed views, expression and statement typing, and the relation between typing environments and storage. Given needs no permission types; Shared adds given and shared.

Progress says that a well-typed configuration is finished or can take a step. Preservation says that every step retains configuration typing. Each local statement takes one step; the initial frame then takes one exit step. Well-typed programs finish after exactly the statement count plus one, with an empty heap. A separate pre-exit observation retains the final bindings. These type soundness results are separate from the structural heap invariants proved by the operational chapters.

Functions reuses Shared storage and typing machinery. Its stack realization accounts for suspended callers as well as the active frame; Functions/Safety proves progress and preservation for arbitrary successors and safety of every finite execution prefix. Recursion removes the termination guarantee. Correspondence/SharedFunctionsFrames preserves and reflects the call-free fragment, including initial-frame exit and terminal states.

Later extensions will cover control flow, primitives, destruction, and borrowing. Introduce each feature when its behavior can be explained from the preceding chapters.

Build one layer

Start with the behavior the layer adds and a small program that exhibits it. Then introduce its objects and language, separating places from values, and explain how evaluation changes a complete configuration. Define liveness and well-formedness in terms of that layer’s objects before stating preservation theorems. Each definition and example belongs to a named unit with Lean citations. Explanatory examples are part of the specification and must state cases that can be checked in Lean.

For a theorem, first make the intended assumptions and conclusion clear in the book and the Lean statement. Review that correspondence. Prove the statement in Lean and check it mechanically. A difficult proof can reveal a mistaken rule or an inadequate invariant, but difficulty alone is not a reason to weaken the claim without discussion.

Relate execution models

When a layer extends the operational semantics, it should faithfully contain the earlier language. Define an embedding of programs and configurations and a relation describing when a configuration in each model represents the same execution state. The relation must include enough information to discuss future steps, not just matching object maps.

For a one-step correspondence, establish both directions:

  • Every earlier-model step has a matching later-model step from the related configuration, and their results are related.
  • Every later-model step from a related configuration has a matching earlier-model step, and their results are related.

The second direction rules out new behavior for translated earlier programs. An equation mentioning only transitions whose endpoints are already embeddings is insufficient: it can overlook a transition that leaves the embedded fragment. State the theorem so that arbitrary successors in the later model are covered.

Also specify how initial configurations, final values, stuckness or faults, and observable results correspond. If one model needs extra administrative steps, choose and justify a relation allowing those steps instead of calling an unproved one-step equivalence a bisimulation. Fresh identities may require a renaming relation rather than literal state equality.

Keep this correspondence in a separate Lean module importing both layers. Its proofs establish the relationship between the formal models. Review units explain why that relationship captures the intended extension and cite the translation and correspondence statements. Reviews do not replace the proofs.

Record the extension’s evidence

Review the new chapter’s units with the same evidence procedure. For typing, include the relevant typing judgments, operational rules, and soundness statements. For an operational extension, also review the correspondence units: include the relevant units from both layers, their translation, and the formal correspondence statement as inputs. Changing a source layer or the translation must invalidate affected reviews, even if the prose of the correspondence theorem is unchanged.

Agent review has three distinct jobs: identify whether the units capture the intended model, compare their prose and mathematics with Lean, and assess whether the correspondence statement rules out unintended new behavior. Lean checks the resulting proofs. The saved rationale makes each of those review judgments open to a second review.

Specification system design

The specification consists of named units of Markdown and mathematics, each linked to its formalization or implementation. The Rust library in v2/mdbook-dada supplies both the mdBook renderer and the dada-spec evidence commands. A unit has one stable identity, a complete authored body, and explicit source and context dependencies. The renderer and evidence checker use the same unit boundaries.

Every structured unit under md/ participates in the inventory. Future notes record nonnormative ideas with no formalization or correspondence claim; all other structured units require evidence. v2/spec.json additionally lists strict chapters, where semantic prose must be inside units using the syntax described in Authoring units. The renderer also retains the earlier citation syntax for compatibility. Successful validation does not imply that every paragraph of this book has been reviewed.

A source citation, correspondence review, passing test, and checked Lean proof answer different questions. A shield identifies a unit; it does not certify it. The review procedure explains how to prepare and record evidence, and extending the model describes how independently understandable semantic layers are related.

anchormeta.anchors.identity Each named claim has a unique identity and one defining source location. References and generated views resolve to that definition. Missing or ambiguous identities are reported as errors rather than silently omitted.

anchormeta.anchors.content A structured unit’s opening and closing fences delimit its complete content, including its options, prose, mathematics, qualifications, and examples. The opening-line argument is its stable ID. Rendering and review use that complete unit, before Markdown escaping or HTML generation. A legacy inline anchor names a location but does not establish an evidence boundary.

In strict chapters, semantic explanations belong inside units. New terminology links to the unit that introduces it; explanatory examples cite Lean cases that state the behavior described. Headings organize the reading order without adding untracked semantic claims.

anchormeta.correspondence.coverage A claim can be associated with multiple definitions, operations, examples, tests, and propositions. The associations identify their exact targets. The system records explicit gaps and the scope covered by each association; the existence of a link alone does not establish adequate coverage.

anchormeta.reviews.correspondence Human or agent review assesses whether the associated views collectively express a coherent, intended design. It examines quantifiers, assumptions, exceptions, and relevant definitions, and considers cases that satisfy the propositions but violate the prose. Reviews retain claim-specific reasoning and unresolved issues.

Neither English, propositions, nor code automatically prevails in a discrepancy. The discrepancy must be discussed; resolving it can change any of those views or the intended design. Proof difficulty alone does not establish that a design is flawed or a proposition false.

anchormeta.reviews.freshness A saved correspondence review applies only to its recorded claim, propositions, assumptions, and relevant definitions and evidence, under its recorded review policy. Changes affecting those inputs require renewed review. A stored line number is only a diagnostic location and does not participate in the bundle digest. Moving text within a conservatively fingerprinted source file still changes that file’s contents and therefore invalidates the current implementation’s evidence. Link and reading-order audits additionally hash source positions as inventory content, so moving an unchanged use or definition changes those audit inputs.

Changing the definition of live, for example, can invalidate review even when a theorem’s displayed statement is unchanged. A change confined to proof technique need not change the mathematical intent. The current implementation conservatively fingerprints all local Lean sources for units with Lean citations, so it also invalidates reviews after proof-only edits or changes elsewhere in the local formalization. This can require extra review; it must not silently omit a dependency. Finer tracking of elaborated statement dependencies is a future refinement.

anchormeta.reviews.recording Preparing review inputs does not approve them. Recording a decision checks that its inputs still match the current sources and retains the reviewer identity and reasoning. Automated checking reports stale or missing decisions; it does not manufacture approvals to make a check pass.

anchormeta.evidence.status The system distinguishes claims awaiting formalization, proposed formalizations awaiting review, reviewed formalizations with incomplete proofs or coverage gaps, and mechanically checked proofs under recorded assumptions. It separately identifies executed examples and tests. Partial coverage of a claim is not presented as establishment of the whole claim.

Build success, a source association, a review judgment, a passing test, and a checked proof remain distinct evidence. Unfinished formalization stays marked draft and prevents the evidence check from passing.

Structured units separate kind from readiness: :status: draft keeps the Definition, Example, Theorem, or other kind label and adds a Draft indicator. A draft may omit citations; supplied citations retain their kind checks. Drafts fail evidence validation and cannot receive an affirmative correspondence record. Definitions introduce concepts and judgments without asserting a result to prove. Theorems and lemmas state results; draft status marks proposed results whose formalization is unfinished.

anchormeta.proofs.assumptions Evidence presented as a checked proof identifies its proposition, checked source version, and assumptions, including admitted results or additional axioms. Standard verification uses just test-lean, whose lake build --wfail rejects warnings, including those emitted by sorry; do not suppress warn.sorry. Any future allowance for admissions must require an explicit opt-in; an admitted statement must not be reported as proved.

anchormeta.rendering.faithfulness Mathematical views render the notation authored in the Markdown, and Lean views extract their cited source. Graph renderings derive from explicit state facts; layout hints do not silently add semantic relationships. Readers can inspect the formalization associated with a mathematical view and the facts underlying a diagram. Extraction preserves the cited source; correspondence between authored mathematics and that source requires a separate review.

The Markdown supplies a self-contained mathematical account. Its definitions and explanations can be read without opening the Lean files, whose citations identify associated formalizations for comparison.

anchormeta.system.self_specification The tooling’s review and rendering contracts are structured units in Implementation contracts and Renderer contracts. They cite Rust symbols and tests and require the same recorded comparison as language units.

The tooling review inventory includes the renderer contracts linked here, with their exact implementation and test selections. Every structured specification unit under the book source root, including dot-prefixed files and directories, requires current positive correspondence evidence, even when its chapter is not strict about surrounding prose. Explicit dependencies must name existing units and become review inputs. Future notes remain in the inventory and undergo structural and reference checks, but assert no correspondence and require no correspondence review. Their explicit boundary is described under Future notes. Specification units and future notes both require link audits, including review of future notes used as link targets.

Mechanical execution records remain separate from correspondence judgments. A review cannot stand in for a command result, and a command result cannot approve a review. The inventory checks these declared boundaries; it does not discover unwritten requirements or prove that tests exercise all possible behavior.

mdbook-dada/src/inventory.rs:Inventory::load
#![allow(unused)]
fn main() {
pub fn load(root: &Path) -> Result<Self> {
        let root = root
            .canonicalize()
            .context("resolving specification root")?;
        let config: Config = serde_json::from_str(
            &fs::read_to_string(root.join("spec.json")).context("reading spec.json")?,
        )
        .context("parsing spec.json")?;
        ensure!(
            config.schema == SCHEMA,
            "unsupported specification schema {}",
            config.schema
        );
        ensure!(
            !config.chapters.is_empty(),
            "spec.json must name at least one strict chapter"
        );
        ensure!(
            !config.policies.is_empty(),
            "spec.json must name a review policy"
        );
        let source_configuration = SourceConfiguration::load(&root)?;
        source_configuration.lean_root(&root)?;
        let mut units = BTreeMap::new();
        let mut sources = BTreeMap::new();
        for path in files(&root, &source_configuration.markdown_root(&root)?, "md")? {
            let name = relative_path(&root, &path)?;
            let source = fs::read_to_string(&path)?;
            for unit in units::parse(&source, &name)? {
                ensure!(
                    !units.contains_key(&unit.id),
                    "duplicate unit ID {}",
                    unit.id
                );
                units.insert(unit.id.clone(), unit);
            }
            sources.insert(name, source);
        }
        let mut required = BTreeSet::new();
        let mut chapters = BTreeSet::new();
        for chapter in &config.chapters {
            input_path(&root, chapter)?;
            ensure!(
                chapters.insert(chapter),
                "duplicate strict chapter {chapter}"
            );
            let source = sources
                .get(chapter)
                .with_context(|| format!("strict chapter is not Markdown under md/: {chapter}"))?;
            units::validate_coverage(source, chapter)?;
            let ids: Vec<_> = units
                .values()
                .filter(|unit| &unit.source_path == chapter)
                .map(|unit| unit.id.clone())
                .collect();
            ensure!(!ids.is_empty(), "strict chapter has no units: {chapter}");
            required.extend(ids);
        }
        // A new-style unit always participates, even before its chapter becomes
        // strict about free-floating prose. Legacy directives are not units.
        required.extend(units.keys().cloned());
        for unit in units.values() {
            for dependency in &unit.uses {
                ensure!(
                    units.contains_key(dependency),
                    "{}: {} uses missing unit {dependency}",
                    unit.source_path,
                    unit.id
                );
            }
        }
        for path in config.policies.iter().chain(&config.context) {
            input_path(&root, path)?;
        }
        let inventory = Self {
            root,
            config,
            source_configuration,
            units,
            required,
            sources,
        };
        // Resolve authored URLs against actual chapter locations. Checking only
        // global IDs misses wrong-chapter links and excludes legacy anchors.
        crate::links::Links::build(&inventory)?;
        Ok(inventory)
    }
}
mdbook-dada/src/inventory.rs:Inventory::inputs
#![allow(unused)]
fn main() {
/// Derive required snapshots from current sources, never from a review record.
    pub fn inputs(&self, id: &str) -> Result<Vec<Input>> {
        if crate::link_audit::is_subject(id) {
            return crate::link_audit::inputs(self, id);
        }
        let mut inputs = BTreeMap::new();
        self.add_unit(id, &mut inputs, &mut BTreeSet::new())?;
        for input in self.common_inputs()? {
            inputs.insert(input.key.clone(), input);
        }
        if inputs.keys().any(|key| key.starts_with("lean:")) {
            let lean_root = self.source_configuration.lean_root(&self.root)?;
            for path in files(&self.root, &lean_root, "lean")? {
                let name = relative_path(&self.root, &path)?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
            for path in ["lean-toolchain", "lakefile.toml", "lake-manifest.json"] {
                let name = relative_path(&self.root, &lean_root.join(path))?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
        }
        Ok(inputs.into_values().collect())
    }
}
mdbook-dada/src/evidence.rs:check
#![allow(unused)]
fn main() {
/// Check all required units, including record presence, minimum inputs and freshness.
/// Neither the review's conclusion nor a passing result establishes a Lean proof.
pub fn check(inventory: &Inventory) -> Result<Report> {
    let mut report = Report::default();
    if let Err(error) = crate::mechanical::records(&inventory.root) {
        report.issues.push(Issue {
            unit: None,
            message: "malformed mechanical execution evidence".into(),
            details: vec![format!("{error:#}")],
        });
    }
    let mut bundles = BTreeMap::new();
    for path in json_files(&inventory.root, &inventory.root.join("evidence/bundles"))? {
        match read_json::<ReviewBundle>(&path) {
            Ok(bundle) => {
                let errors = bundle.integrity_errors();
                let name = path
                    .file_stem()
                    .and_then(|name| name.to_str())
                    .unwrap_or("");
                if !errors.is_empty() || name != bundle.digest {
                    report.issues.push(Issue {
                        unit: inventory
                            .units
                            .contains_key(&bundle.unit)
                            .then_some(bundle.unit.clone()),
                        message: format!("invalid evidence bundle {}", path.display()),
                        details: errors,
                    });
                } else {
                    bundles.insert(bundle.digest.clone(), bundle);
                }
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed evidence bundle".into(),
                details: vec![format!("{error:#}")],
            }),
        }
    }
    let audits = AuditInventory::build(inventory)?;
    // Parse every saved decision, including retired subjects. Removing a link or
    // unit retires its obligation, not the integrity checks on its history.
    let mut all_records: BTreeMap<String, BTreeMap<String, ReviewRecord>> = BTreeMap::new();
    let records_root = inventory.root.join("evidence/records");
    for path in json_tree(&inventory.root, &records_root)? {
        let parsed = (|| -> Result<(String, String, ReviewRecord)> {
            let review: ReviewRecord = read_json(&path)?;
            let digest = review.digest()?;
            ensure!(
                path.file_stem().and_then(|name| name.to_str()) == Some(&digest),
                "record filename does not match contents"
            );
            let bundle = bundles
                .get(&review.bundle)
                .context("record's bundle is missing or malformed")?;
            ensure!(
                path == records_root
                    .join(&bundle.unit)
                    .join(format!("{digest}.json")),
                "record filed under wrong subject"
            );
            let errors = validate_review(bundle, &review);
            ensure!(errors.is_empty(), "invalid review: {}", errors.join("; "));
            Ok((bundle.unit.clone(), digest, review))
        })();
        match parsed {
            Ok((subject, digest, review)) => {
                all_records
                    .entry(subject)
                    .or_default()
                    .insert(digest, review);
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed stored review".into(),
                details: vec![format!("{}: {error:#}", path.display())],
            }),
        }
    }
    for (id, records) in &all_records {
        for review in records.values() {
            for previous in &review.supersedes {
                if !records.contains_key(previous) {
                    report.issues.push(Issue {
                        unit: Some(id.clone()),
                        message: "review supersedes absent or unrelated evidence".into(),
                        details: vec![previous.clone()],
                    });
                }
            }
        }
    }
    let required_subjects: BTreeSet<_> = inventory
        .required
        .iter()
        .chain(audits.manifests.keys())
        .cloned()
        .collect();
    let mut current_active = BTreeMap::new();
    for id in &required_subjects {
        // Derive inputs even for drafts: malformed
        // citations never disappear because a formalization is unfinished.
        let required = match if link_audit::is_subject(id) {
            audits.inputs(inventory, id)
        } else {
            inventory.inputs(id)
        } {
            Ok(inputs) => inputs,
            Err(error) => {
                report.issues.push(Issue {
                    unit: Some(id.clone()),
                    message: "cannot resolve required evidence inputs".into(),
                    details: vec![format!("{error:#}")],
                });
                report.statuses.push(UnitStatus {
                    unit: id.clone(),
                    evidence: "invalid sources",
                    correspondence: "not checked",
                });
                continue;
            }
        };
        if inventory
            .units
            .get(id)
            .is_some_and(|unit| unit.kind == UnitKind::FutureNote)
        {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "future note",
                correspondence: "not applicable",
            });
            continue;
        }
        if inventory.units.get(id).is_some_and(|unit| unit.draft) {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "draft",
                correspondence: "not asserted",
            });
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("draft unit {id} requires formalization"),
                details: vec![
                    "draft status preserves the unit's semantic kind but cannot count as completed correspondence evidence".into(),
                ],
            });
            continue;
        }
        let mut current = BTreeSet::new();
        let mut stale = Vec::new();
        for bundle in bundles.values().filter(|bundle| &bundle.unit == id) {
            // Historical bundles compare with one independently derived current
            // manifest. Re-reading all sources for each past review made the
            // ordinary evidence test grow with the entire review history.
            let errors = validate_bundle_against(inventory, bundle, required.clone())?;
            if errors.is_empty() {
                current.insert(bundle.digest.clone());
            } else {
                stale.extend(errors);
            }
        }
        let empty_records = BTreeMap::new();
        let records = all_records.get(id).unwrap_or(&empty_records);
        let superseded: BTreeSet<_> = records
            .values()
            .flat_map(|review| review.supersedes.iter().cloned())
            .collect();
        let stale_active = records.iter().any(|(digest, review)| {
            !superseded.contains(digest) && !current.contains(&review.bundle)
        });
        let active: Vec<_> = records
            .iter()
            .filter(|(digest, review)| {
                current.contains(&review.bundle) && !superseded.contains(*digest)
            })
            .map(|(_, review)| review)
            .collect();
        // Cross-review order decisions may rely only on an entirely current,
        // positive subject; a conflicting or stale active record blocks it.
        if !stale_active
            && !active.is_empty()
            && active
                .iter()
                .all(|review| review.conclusion == Conclusion::Corresponds)
        {
            current_active.insert(
                id.clone(),
                active.iter().map(|review| (*review).clone()).collect(),
            );
        }
        let evidence = if stale_active {
            "stale"
        } else if !current.is_empty() {
            "current"
        } else if !stale.is_empty() {
            "stale"
        } else {
            "missing"
        };
        let correspondence = if stale_active {
            "stale decision"
        } else if active.is_empty() {
            "missing"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Mismatch)
        {
            "mismatch"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Inconclusive)
        {
            "inconclusive"
        } else {
            "corresponds"
        };
        report.statuses.push(UnitStatus {
            unit: id.clone(),
            evidence,
            correspondence,
        });
        if correspondence != "corresponds" {
            let mut details = if evidence == "stale" {
                stale
            } else {
                Vec::new()
            };
            details.sort();
            details.dedup();
            if evidence == "current" && active.is_empty() {
                details.push("preparing a bundle does not record a completed review".into());
            }
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("{evidence} evidence for {id}: correspondence {correspondence}"),
                details,
            });
        }
    }
    for (unit, message) in link_audit::cross_validate(&audits, &current_active) {
        report.issues.push(Issue {
            unit: Some(unit),
            message,
            details: Vec::new(),
        });
    }
    Ok(report)
}
}
mdbook-dada/tests/evidence_validation.rs:complete_current_reviews_pass_and_remain_distinct_from_mechanical_checks
#![allow(unused)]
fn main() {
#[test]
fn complete_current_reviews_pass_and_remain_distinct_from_mechanical_checks() {
    let fixture = Fixture::new();
    fixture.complete_reviews();
    let inventory = fixture.inventory();
    let report = evidence::check(&inventory).unwrap();
    assert!(report.is_ok(), "{}", report.render(&inventory));
    assert_eq!(report.statuses.len(), 4);
    for status in &report.statuses {
        assert_eq!(status.evidence, "current");
        assert_eq!(status.correspondence, "corresponds");
        assert!(mdbook_dada::mechanical::status(&inventory.root)
            .unwrap()
            .is_empty());
    }
}
}
mdbook-dada/tests/evidence_validation.rs:prepared_bundles_are_not_completed_reviews
#![allow(unused)]
fn main() {
#[test]
fn prepared_bundles_are_not_completed_reviews() {
    let fixture = Fixture::new();
    let inventory = fixture.inventory();
    let bundle = fixture.bundle();
    evidence::save_bundle(&inventory, &bundle).unwrap();
    let report = evidence::check(&inventory).unwrap();
    assert!(!report.is_ok());
    let status = report
        .statuses
        .iter()
        .find(|status| status.unit == "model.empty")
        .unwrap();
    assert_eq!(status.evidence, "current");
    assert_eq!(status.correspondence, "missing");
    assert!(report
        .render(&inventory)
        .contains("preparing a bundle does not record a completed review"));
}
}
mdbook-dada/tests/evidence_validation.rs:explicit_dependencies_and_unit_links_must_resolve
#![allow(unused)]
fn main() {
#[test]
fn explicit_dependencies_and_unit_links_must_resolve() {
    let fixture = Fixture::new();
    for source in [
        MODEL.replace(":uses: model.variable", ":uses: model.missing"),
        MODEL.replace(
            "The empty list",
            "See {anchor-ref}`model.missing`. The empty list",
        ),
        MODEL.replace(
            "The empty list",
            "See [the missing unit](#claim-model.missing). The empty list",
        ),
    ] {
        fixture.write("md/model.md", &source);
        let error = Inventory::load(&fixture.0)
            .err()
            .expect("unresolved unit reference must fail");
        assert!(format!("{error:#}").contains("model.missing"));
    }

    // Referencing a real unit supplies its exact inputs even without :uses:.
    fixture.write(
        "md/model.md",
        &MODEL.replace(":uses: model.variable\n", "").replace(
            "The empty list",
            "See {anchor-ref}`model.variable`. The empty list",
        ),
    );
    let bundle = fixture.bundle();
    assert!(bundle
        .inputs
        .iter()
        .any(|input| input.key == "unit:model.variable"));
    assert!(bundle
        .inputs
        .iter()
        .any(|input| input.key == "lean:Fixture:Variable"));
}
}
mdbook-dada/tests/evidence_validation.rs:hidden_markdown_chapters_cannot_escape_required_evidence
#![allow(unused)]
fn main() {
#[test]
fn hidden_markdown_chapters_cannot_escape_required_evidence() {
    let fixture = Fixture::new();
    for (path, id) in [
        ("md/.hidden.md", "hidden.direct"),
        ("md/.drafts/chapter.md", "hidden.nested"),
    ] {
        fixture.write(path, &format!("# Hidden chapter\n\n```{{definition}} {id}\n:lean: Fixture:Variable\n\nA natural-number variable.\n```\n"));
    }
    fixture.write("md/SUMMARY.md", "# Summary\n\n- [Visible](model.md)\n- [Direct](.hidden.md)\n- [Nested](.drafts/chapter.md)\n");
    let inventory = fixture.inventory();
    for id in ["hidden.direct", "hidden.nested"] {
        assert!(inventory.required.contains(id));
        let report = evidence::check(&inventory).unwrap();
        assert!(report
            .statuses
            .iter()
            .any(|status| status.unit == id && status.evidence == "missing"));
    }
    fixture.complete_reviews();
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(report.is_ok(), "{}", report.render(&fixture.inventory()));
}
}

Evidence and validation

anchormeta.evidence.inputs The checker derives a required input set from the current unit inventory. It does not accept a review’s own list as the definition of what must have been reviewed. That set includes the complete authored unit, every exact cited Lean declaration, its required source context, referenced units, and the review policy. Meta units also identify implementation and test targets. Their source files and declared dependencies are review inputs. Tool and schema versions, including book.toml, participate in freshness. Rendering and inventory use the same configured book and Lean source roots. Structured units reject mdBook expansion directives and nested legacy citation blocks; separate units and explicit dependencies keep those sources reviewable.

A bundle retains the exact input contents and content hashes in JSON, together with source identities and locations. A reviewer can retrieve what was considered, and another reviewer can inspect the same evidence later. A repository revision is useful provenance but does not replace these snapshots. Changing an unrelated file need not invalidate a review; changing an input does.

anchormeta.evidence.minimum_inputs Syntactic validation requires the authored unit and every cited formalization to be present under the correct input identities and to match current source. Substituting a different declaration, dropping a citation or dependency, or changing snapshot contents without updating their hashes is an error. Matching hashes establish input identity, not mathematical correspondence.

anchormeta.evidence.decisions A completed review records its bundle digest, reviewer identity, examined inputs, conclusion, rationale, and limitations. Conclusions distinguish correspondence, mismatch, and an inconclusive comparison. A prepared packet is not a completed review, and a mismatch is not positive evidence. Required positive review cannot be satisfied by merely creating a packet or filling in a conclusion field. Decisions may explicitly supersede earlier decisions for the same unit, including ones made against different input bundles. Every unsuperseded decision must be current and positive; a stale replacement cannot silently restore an older approval. The retained records preserve the decision history. Draft units fail evidence validation and cannot receive affirmative decisions. A cited theorem statement alone does not establish that its proof was checked.

The examined-input list must cover the authored units, exact Lean/Rust/test selections, policy, and extra files supplied with prepare --input. Conservative full-source and tool snapshots remain available for freshness and deeper inspection; a reviewer records them as examined only when actually used. The list is a syntactic attestation, not mechanical proof that reading occurred.

anchormeta.evidence.workspace_test An ordinary Cargo integration test validates the configured evidence through the same library used by dada-spec check. Running cargo test --workspace from v2/ therefore checks evidence presence, required inputs, schema, and freshness. This validation is deterministic and syntactic: it invokes no agent, network service, or Lean compiler. It cannot decide whether a recorded rationale is persuasive or a theorem captures the intended behavior.

Diagnostics use annotate-snippets to identify the relevant unit or citation and explain the repair. Missing or stale evidence directs the author to prepare a new bundle, perform its review, and record the result. A check must not refresh hashes or generate favorable reviews on the author’s behalf.

anchormeta.evidence.self_validation Meta requirements can cite Rust implementation symbols and named tests using :rust: and :tests:. Their correspondence reviews use the same snapshots and freshness rules as language units. Tests exercise specified cases and rejection paths; they do not prove all possible behavior. The validator’s own adversarial tests remain necessary even when a review of the validator is current. Its version is an input to evidence validation, and generated evidence is not an input to its own hash.

The command and review formats are described in Correspondence review. Mechanical Lean checking remains a separate just test-lean invocation. Mechanical records retain actual command outcomes separately; a recorded review is not an assertion that Lean or Cargo was executed.

Rendering and source selection

The renderer contracts specify identities, supported blocks, mathematics, source extraction, and diagrams. Each contract cites its implementation and tests. The authoring guide gives the syntax for writing units. The contracts describe textual processing; correspondence review and Lean compilation remain separate checks.

Mathematical presentation and review

anchormeta.math.source A grammar, judgment, or rule block contains authored mathematical notation and citations into Lean. A definition block contains an authored Markdown explanation with citations to its Lean formalization. A theorem or lemma block contains an authored Markdown statement, with a citation to its Lean theorem and proof. These accounts are part of the Markdown specification and stand on their own, with symbols and assumptions explained in the book. The preprocessor renders the authored account and extracts the cited source; it does not derive mathematics from Lean.

anchormeta.lean.definitions.source Lean files contain the formal declarations cited by the book. The mathematical account and its Lean formalization are maintained independently and compared through explicit correspondence review. Neither version automatically prevails in a discrepancy; resolving it can change either view or the intended design, as in refmeta.reviews.correspondence.

anchormeta.lean.definitions.presentation The mathematical presentation may use conventional symbols and omit Lean’s implementation details under explicit notation conventions. The Lean view retains the original declaration, including fields, proof arguments, and derived instances. The renderer does not infer a mathematical grammar from these details.

anchormeta.math.identifiers The book defines a shared vocabulary of mathematical categories and metavariables for use across chapters. Short conventional letters denote variables; upright text denotes multi-character constructor or helper names. A notation key relates these symbols to their meanings and cited Lean declarations. Changing notation requires updating uses and the relevant correspondence explanations together.

anchormeta.math.fields An authored grammar may use positional constructor arguments when the surrounding notation key and prose make their meaning unambiguous. The book explains how these arguments correspond to Lean’s named fields. Any omission or abstraction of a field must be stated; a shorter presentation must not silently discard a semantic distinction.

anchormeta.math.containers An overbar denotes a finite ordered sequence, and K ⇀ V denotes a finite map from keys in K to values in V. The notation abstracts from Lean’s List, Array, and FiniteMap representations. The representation and its associated proofs remain available in the cited source. See refmeta.syntax.lean.mathematical_containers.

anchormeta.math.abbreviations Authored notation may abbreviate terms and suppress proof terms under stated conventions. Implicit parameters must be explained where introduced. Conditions represented by proof arguments remain explicit: hiding the proof of freshness or distinctness does not remove that condition. Equations introducing intermediate names must preserve their dependencies and scopes.

anchormeta.math.heap_representation Each language chapter explains its own representation conventions. For example, Given writes an empty slot as \(\bot\) and an occupied slot as an object identity; Lean represents these as none and some object. Such abbreviations must preserve distinctions used by the rules. A list may be presented as a map only under the stated uniqueness conditions, and any order relevant to the semantics must remain visible. Omitting a proof term does not omit its condition.

anchormeta.math.rule.layout Each premise occupies its own line above the inference bar. Intermediate values can have short names with defining equations. Rules use the shared vocabulary consistently in premises and conclusions, including the judgment’s introduced notation. Grammar alternatives align with their definition symbol, as described in refmeta.syntax.lean.alignment.

anchormeta.math.correspondence A mathematical block must express the intended content of its cited Lean source under the book’s notation conventions. Review checks represented categories, variables, quantification, constructor fields, premises, conclusions, scopes, and hidden parameters or proof arguments. A source citation alone is not evidence that this correspondence holds. A discrepancy can require changes to either view or to the intended design, as in refmeta.reviews.correspondence.

For example, a rule may give a short name to the state obtained by clearing a slot. The Markdown defines that name and the affected location; the renderer does not reconstruct the update from Lean.

anchormeta.math.correspondence.evidence Review evidence identifies the authored mathematics, cited Lean source, and notation conventions it covers. Saved bundles and review records make the comparison inspectable and allow syntactic checks to identify missing or stale evidence when its inputs change. A successful citation lookup or MathJax render must not be reported as that review evidence.

Informational Selectors support inspection; the evidence checker validates record structure, coverage of required inputs, and freshness. Human or agent review still judges correspondence. Passing the checker does not establish mathematical equivalence between the authored account and Lean.

anchormeta.examples.coverage Every completed semantic example links to a Lean test of its intended behavior. A proposed scenario whose semantics or test is unfinished uses :status: draft; it is not presented as a checked example. Authoring-syntax illustrations are ordinary prose and literal code; they do not create additional semantic claims or evidence records.

anchormeta.examples.evidence The source association, Lean proof check, and correspondence review are separate checks. The preprocessor checks the association. Compiling the containing Lean file checks the example under its imports, declarations, and assumptions; that compilation is separate from rendering the book. Review checks that the example’s proposition and setup cover the behavior described by the Markdown, including any stated preconditions and results. Neither a valid citation nor a successful proof by itself establishes that correspondence or broader claim coverage.

anchormeta.syntax.lean.mathematical_containers The shared mathematical notation writes an overbar over an element or category for a finite ordered sequence, whether its Lean representation uses List or Array. A finite map is written K ⇀ V, with no finiteness subscript. Map domains, comprehensions, lookup, and update are defined where used. The notation does not assert that Lean’s list and array types are identical or erase any required bounds or uniqueness conditions. Supporting representation details, such as the proof field in FiniteMap, may remain only in Lean when their mathematical meaning has been stated in the book.

anchormeta.syntax.lean.alignment Authors align grammar definition symbols and alternative separators in one column. Long constructor arguments can continue on separate lines aligned with the first argument; rules place distinct premises on separate lines. These are conventions for the authored LaTeX, not layouts inferred from Lean syntax.

Implementation contracts and evidence

Implementation contracts

A structured unit contains its reviewed text directly. It rejects mdBook include, playground, and rustdoc-include directives, including those in literal samples. It also rejects nested legacy source-citation blocks. Related source selections belong in separate units connected by explicit dependencies.

For each chapter received by the Dada preprocessor, the ordered unit IDs and raw structured-unit text must match that chapter’s original source. Earlier content preprocessing may not add, remove, or change units within that chapter. This rejects an include even if mdBook has already expanded it before this boundary.

The comparison covers received chapters at this preprocessing stage. It does not check whether a whole chapter was omitted or whether later output processing changes the generated page.

mdbook-dada/src/units.rs:parse_block
#![allow(unused)]
fn main() {
fn parse_block(
    source: &str,
    path: &str,
    range: Range<usize>,
    info: &str,
) -> Result<Option<SpecUnit>> {
    let (directive, argument) = info.split_once(char::is_whitespace).unwrap_or((info, ""));
    let Some(kind) = UnitKind::parse(directive) else {
        return Ok(None);
    };
    // Legacy directives carry path:declaration on their opening line. Keep their
    // interpretation, but never mistake them for reviewed structured units.
    if argument.contains(':') {
        ensure!(
            kind != UnitKind::FutureNote,
            "future notes cannot have formalization citations; use a stable unit ID"
        );
        return Ok(None);
    }
    let id = argument.trim();
    if kind.is_math() && id.is_empty() {
        bail!(
            "{directive} requires a stable unit ID, a :lean: citation, and an authored LaTeX body"
        );
    }
    ensure!(
        valid_id(id),
        "expected one stable unit ID after {directive}"
    );
    let raw = &source[range.clone()];
    let opening_end = raw
        .find('\n')
        .context("unit has no body or closing fence")?
        + 1;
    let closing_start = raw
        .trim_end_matches(['\n', '\r'])
        .rfind('\n')
        .context("unit has no closing fence")?
        + 1;
    let opening = raw[..opening_end].trim_start();
    let marker = opening
        .chars()
        .next()
        .context("unit has no opening fence")?;
    let width = opening.chars().take_while(|c| *c == marker).count();
    let closing = raw[closing_start..].trim();
    ensure!(
        matches!(marker, '`' | '~')
            && closing.chars().all(|c| c == marker)
            && closing.len() >= width,
        "structured unit must have an explicit matching closing fence"
    );
    let contents = &raw[opening_end..closing_start];
    let mut unit = SpecUnit {
        id: id.to_owned(),
        kind,
        draft: false,
        source_path: path.to_owned(),
        range,
        body: String::new(),
        raw: raw.to_owned(),
        lean: vec![],
        rust: vec![],
        tests: vec![],
        uses: vec![],
    };
    let mut seen = BTreeSet::new();
    let mut body_start = 0;
    for line in contents.split_inclusive('\n') {
        let line_text = line.trim_end_matches(['\n', '\r']);
        if !line_text.starts_with(':') {
            break;
        }
        let (option, value) = line_text[1..]
            .split_once(':')
            .context("unit option must have the form :name: value")?;
        ensure!(seen.insert(option), "duplicate :{option}: option");
        let values: Vec<_> = value.split_whitespace().map(str::to_owned).collect();
        ensure!(!values.is_empty(), ":{option}: must not be empty");
        if option == "status" {
            ensure!(
                values == ["draft"],
                ":status: only accepts `draft`; omit it for units ready for correspondence review"
            );
            unit.draft = true;
            body_start += line.len();
            continue;
        }
        let target = match option {
            "lean" => &mut unit.lean,
            "rust" => &mut unit.rust,
            "tests" => &mut unit.tests,
            "uses" => &mut unit.uses,
            _ => bail!("unknown unit option :{option}:"),
        };
        let unique: BTreeSet<_> = values.iter().collect();
        ensure!(
            unique.len() == values.len(),
            "duplicate value in :{option}:"
        );
        *target = values;
        body_start += line.len();
    }
    unit.body = contents[body_start..].trim_matches(['\n', '\r']).to_owned();
    // mdBook expands these even inside fenced code. The packet must contain
    // exactly the authored content, not untracked external substitutions.
    let includes = regex::Regex::new(r"\{\{\s*#(?:include|rustdoc_include|playground)\b")?;
    ensure!(
        !includes.is_match(&unit.raw),
        "mdBook include, rustdoc_include, and playground directives are unsupported inside structured units; write the content directly or cite another unit"
    );
    for event in Parser::new(&unit.body) {
        if let Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(info))) = event {
            let (directive, argument) = info.split_once(char::is_whitespace).unwrap_or((&info, ""));
            ensure!(
                UnitKind::parse(directive).is_none() || !argument.contains(':'),
                "legacy citation directives cannot nest inside structured units; create a separate unit with :lean: and refer to it with :uses:"
            );
        }
    }
    ensure!(
        !unit.body.trim().is_empty(),
        "unit requires an authored body"
    );
    ensure!(
        !unit.body.starts_with(':'),
        "unit options must immediately follow the opening fence, before the blank line and body"
    );
    if kind == UnitKind::FutureNote {
        ensure!(
            unit.lean.is_empty() && unit.rust.is_empty() && unit.tests.is_empty(),
            "future notes cannot have formalization citations (:lean:, :rust:, or :tests:); use a specification unit for formalized content"
        );
        ensure!(!unit.draft, "future notes cannot have :status: draft; they are exploratory notes, not unfinished specification units");
    }
    ensure!(
        kind == UnitKind::FutureNote || unit.draft || !unit.lean.is_empty() || !unit.rust.is_empty(),
        "unit requires :lean: or :rust: citations; use :status: draft while its formalization is pending"
    );
    ensure!(
        unit.tests.is_empty() || !unit.rust.is_empty(),
        ":tests: requires a :rust: implementation citation"
    );
    ensure!(
        unit.lean.is_empty() || unit.rust.is_empty(),
        "a unit cannot mix :lean: and :rust: citations"
    );
    ensure!(
        !matches!(kind, UnitKind::Theorem | UnitKind::Lemma)
            || !unit.lean.is_empty()
            || (unit.draft && unit.rust.is_empty()),
        "theorem and lemma units require a Lean theorem; Rust tests are not proofs"
    );
    ensure!(
        !matches!(
            kind,
            UnitKind::Judgment
                | UnitKind::Rule
                | UnitKind::Theorem
                | UnitKind::Lemma
                | UnitKind::Example
        ) || unit.lean.is_empty()
            || unit.lean.len() == 1,
        "{} requires exactly one Lean citation",
        kind.label()
    );
    for dependency in &unit.uses {
        ensure!(valid_id(dependency), "invalid dependency ID `{dependency}`");
        ensure!(dependency != id, "unit cannot depend on itself");
    }
    ensure!(
        parse(&unit.body, path)?.is_empty(),
        "named units cannot nest; cite the other unit with :uses: or a link"
    );
    Ok(Some(unit))
}
}
mdbook-dada/src/configuration.rs:SourceConfiguration::validate_chapters
#![allow(unused)]
fn main() {
/// Check original chapters even if mdBook's links preprocessor has already
    /// expanded an include. Also prevent preprocessing from adding, deleting,
    /// or changing a reviewed unit behind the inventory's back.
    pub fn validate_chapters(&self, root: &Path, book: &Value) -> Result<()> {
        let source_root = self.markdown_root(root)?;
        let key = if book.get("items").is_some_and(Value::is_array) {
            "items"
        } else {
            "sections"
        };
        crate::walk(&book[key], &mut |chapter| {
            let path = chapter["source_path"]
                .as_str()
                .or_else(|| chapter["path"].as_str())
                .context("chapter has no source path")?;
            let source_path = source_root.join(path);
            let name = inventory::relative_path(root, &source_path)?;
            let source_path = inventory::input_path(root, &name)?;
            let original = fs::read_to_string(source_path)?;
            let authored = units::parse(&original, &name)?;
            let processed = units::parse(
                chapter["content"]
                    .as_str()
                    .context("chapter has no content")?,
                &name,
            )?;
            ensure!(authored.iter().map(|unit| (&unit.id, &unit.raw)).eq(
                processed.iter().map(|unit| (&unit.id, &unit.raw))),
                "{name}: preprocessing changed structured units; includes and other external substitutions cannot supply or alter reviewed content");
            Ok(())
        })
    }
}
mdbook-dada/tests/units.rs:structured_units_reject_includes_and_nested_legacy_citations
#![allow(unused)]
fn main() {
#[test]
fn structured_units_reject_includes_and_nested_legacy_citations() {
    let files = Sources::new();
    for body in [
        "{{#include details.txt}}",
        "{{ #rustdoc_include example.rs }}",
        "```rust\n{{#playground example.rs}}\n```",
        "```{grammar} Model:Thing\nt ::= empty\n```",
        "```{judgment} Model:Step\nt \\to t\n```",
        "```{rule} Model:Step.same\nt \\to t\n```",
    ] {
        for citation in [":lean: Model:initial", ":rust: tool.rs:check"] {
            let source = format!("````{{definition}} model.unit\n{citation}\n\n{body}\n````");
            assert!(units::parse(&source, "md/model.md").is_err(), "{source}");
            assert!(render(&source, &files.lean()).is_err(), "{source}");
        }
    }
    // Existing citation-first authoring outside reviewed units remains supported.
    render(
        "````{definition} Model:initial\nText.\n\n```{grammar} Model:Thing\nt ::= empty\n```\n````",
        &files.lean(),
    )
    .unwrap();
}
}
mdbook-dada/tests/evidence_validation.rs:authored_includes_and_nested_citations_cannot_acquire_evidence
#![allow(unused)]
fn main() {
#[test]
fn authored_includes_and_nested_citations_cannot_acquire_evidence() {
    let fixture = Fixture::new();
    for body in [
        "{{#include details.txt}}",
        "{{#rustdoc_include example.rs}}",
        "{{#playground example.rs}}",
        "```{grammar} Fixture:Variable\nx ::= Nat\n```",
    ] {
        fixture.write("md/model.md", &format!("````{{definition}} model.value\n:rust: mdbook-dada/src/lib.rs:validate\n\n{body}\n````\n"));
        assert!(Inventory::load(&fixture.0).is_err(), "{body}");
    }
}
}
mdbook-dada/tests/evidence_validation.rs:preexpanded_includes_cannot_bypass_original_source_validation
#![allow(unused)]
fn main() {
#[test]
fn preexpanded_includes_cannot_bypass_original_source_validation() {
    let fixture = Fixture::new();
    let raw =
        "```{definition} model.variable\n:lean: Fixture:Variable\n\n{{#include details.txt}}\n```";
    fixture.write("md/model.md", raw);
    let expanded = raw.replace("{{#include details.txt}}", "The value is two.");
    let mut book = chapter(&expanded);
    let error = mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book)
        .unwrap_err();
    assert!(format!("{error:#}").contains("directives are unsupported"));
    // An include outside a unit cannot introduce a new unit unknown to the inventory.
    fixture.write("md/model.md", "{{#include units.txt}}\n");
    let mut book = chapter(MODEL);
    let error = mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book)
        .unwrap_err();
    assert!(format!("{error:#}").contains("preprocessing changed structured units"));
    // Other preprocessors also cannot rewrite claims while leaving evidence current.
    fixture.write("md/model.md", MODEL);
    let mut book = chapter(&MODEL.replace("natural number", "Boolean"));
    assert!(
        mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book).is_err()
    );
}
}
mdbook-dada/tests/evidence_validation.rs:actual_mdbook_pipeline_rejects_includes_in_reviewed_content
#![allow(unused)]
fn main() {
#[test]
#[ignore = "requires the mdbook executable; run with --ignored after installing book tools"]
fn actual_mdbook_pipeline_rejects_includes_in_reviewed_content() {
    let fixture = Fixture::new();
    fixture.write("md/SUMMARY.md", "# Summary\n\n- [Model](model.md)\n");
    fixture.write("md/details.txt", "The value is one.\n");
    fixture.write("md/model.md", "```{definition} model.variable\n:lean: Fixture:Variable\n\n{{#include details.txt}}\n```\n");
    let command =
        serde_json::to_string(&format!("\"{}\"", env!("CARGO_BIN_EXE_mdbook-dada"))).unwrap();
    fixture.write("book.toml", &format!("[book]\nsrc = \"md\"\n[preprocessor.dada]\ncommand = {command}\nafter = [\"links\"]\nlean-source = \"lean\"\n"));
    for contents in ["The value is one.", "The value is two."] {
        fixture.write("md/details.txt", contents);
        let output = std::process::Command::new("mdbook")
            .arg("build")
            .arg(&fixture.0)
            .output()
            .expect("install mdbook before running this test");
        assert!(!output.status.success());
        let error = String::from_utf8_lossy(&output.stderr);
        assert!(
            error.contains("directives are unsupported inside structured units"),
            "{error}"
        );
    }
}
}

Rendering and evidence read the same book and Lean source roots from book.toml. Runtime overrides that disagree with those roots are rejected. Roots remain inside the project. Rust citations use the project root, even when the Lean root is nested several directories below it.

The configuration is a review input. Changing it makes existing evidence stale; a new packet selects declarations and context from the newly configured root.

mdbook-dada/src/configuration.rs:SourceConfiguration::load
#![allow(unused)]
fn main() {
pub fn load(root: &Path) -> Result<Self> {
        let configuration = toml::from_str(
            &fs::read_to_string(root.join("book.toml")).context("reading book.toml")?,
        )
        .context("parsing book.toml source configuration")?;
        Ok(configuration)
    }
}
mdbook-dada/src/configuration.rs:SourceConfiguration::lean_root
#![allow(unused)]
fn main() {
pub fn lean_root(&self, root: &Path) -> Result<PathBuf> {
        inventory::input_path(root, &self.preprocessor.dada.lean_source)
    }
}
mdbook-dada/src/configuration.rs:SourceConfiguration::markdown_root
#![allow(unused)]
fn main() {
pub fn markdown_root(&self, root: &Path) -> Result<PathBuf> {
        inventory::input_path(root, &self.book.src)
    }
}
mdbook-dada/src/configuration.rs:SourceConfiguration::check_context
#![allow(unused)]
fn main() {
/// Runtime overrides may not make the renderer select different source
    /// trees from the book.toml snapshot used by the evidence inventory.
    pub fn check_context(&self, context: &Value) -> Result<()> {
        let effective: Self = serde_json::from_value(context["config"].clone())
            .context("reading mdBook source configuration")?;
        ensure!(self == &effective,
            "mdBook source configuration differs from book.toml; update book.toml rather than overriding book.src or preprocessor.dada.lean-source");
        Ok(())
    }
}
mdbook-dada/src/lib.rs:process_configured
#![allow(unused)]
fn main() {
/// Production mdBook boundary. Raw source checks precede rendering so already
/// expanded includes cannot bypass structured-unit restrictions.
pub fn process_configured(context: &Value, book: &mut Value) -> Result<()> {
    let root = Path::new(
        context["root"]
            .as_str()
            .context("mdBook context has no root")?,
    )
    .canonicalize()
    .context("resolving mdBook root")?;
    let configuration = configuration::SourceConfiguration::load(&root)?;
    configuration.check_context(context)?;
    configuration.validate_chapters(&root, book)?;
    if root.join("spec.json").exists() {
        inventory::Inventory::load(&root)?;
    }
    let lean_root = configuration.lean_root(&root)?;
    process_with_roots(book, Some(&lean_root), Some(&root))
}
}
mdbook-dada/src/inventory.rs:Inventory::inputs
#![allow(unused)]
fn main() {
/// Derive required snapshots from current sources, never from a review record.
    pub fn inputs(&self, id: &str) -> Result<Vec<Input>> {
        if crate::link_audit::is_subject(id) {
            return crate::link_audit::inputs(self, id);
        }
        let mut inputs = BTreeMap::new();
        self.add_unit(id, &mut inputs, &mut BTreeSet::new())?;
        for input in self.common_inputs()? {
            inputs.insert(input.key.clone(), input);
        }
        if inputs.keys().any(|key| key.starts_with("lean:")) {
            let lean_root = self.source_configuration.lean_root(&self.root)?;
            for path in files(&self.root, &lean_root, "lean")? {
                let name = relative_path(&self.root, &path)?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
            for path in ["lean-toolchain", "lakefile.toml", "lake-manifest.json"] {
                let name = relative_path(&self.root, &lean_root.join(path))?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
        }
        Ok(inputs.into_values().collect())
    }
}
mdbook-dada/tests/evidence_validation.rs:configured_lean_root_is_shared_by_rendering_and_evidence
#![allow(unused)]
fn main() {
#[test]
fn configured_lean_root_is_shared_by_rendering_and_evidence() {
    let fixture = Fixture::new();
    fixture.complete_reviews();
    let original = fixture.bundle();
    assert!(original
        .inputs
        .iter()
        .any(|input| input.key == "tool:book.toml"));
    for file in [
        "Fixture.lean",
        "lean-toolchain",
        "lakefile.toml",
        "lake-manifest.json",
    ] {
        fixture.write(
            &format!("formal/model/{file}"),
            &fs::read_to_string(fixture.0.join("lean").join(file)).unwrap(),
        );
    }
    fixture.write(
        "formal/model/Fixture.lean",
        "abbrev Variable := Nat\ndef empty : List Variable := [2]\n",
    );
    fixture.write(
        "book.toml",
        "[book]\nsrc = \"md\"\n[preprocessor.dada]\nlean-source = \"formal/model\"\n",
    );
    let inventory = fixture.inventory();
    assert!(!evidence::check(&inventory).unwrap().is_ok());
    let bundle = fixture.bundle();
    let selected = bundle
        .inputs
        .iter()
        .find(|input| input.key == "lean:Fixture:empty")
        .unwrap();
    assert_eq!(selected.path, "formal/model/Fixture.lean");
    assert!(selected.content.contains(":= [2]"));
    assert!(bundle
        .inputs
        .iter()
        .any(|input| input.key == "context:formal/model/Fixture.lean"));
    assert!(!bundle
        .inputs
        .iter()
        .any(|input| input.path.starts_with("lean/")));
    let mut book = chapter(MODEL);
    mdbook_dada::process_configured(&configured_context(&fixture, "formal/model"), &mut book)
        .unwrap();
    assert!(book.to_string().contains(":= [2]"));
    let mut book = chapter(MODEL);
    assert!(
        mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book).is_err()
    );
    // Rust selections use the project root, not the parent of the Lean directory.
    let rust =
        "```{definition} meta.check\n:rust: mdbook-dada/src/lib.rs:validate\n\nValidation.\n```";
    fixture.write("md/model.md", rust);
    let mut book = chapter(rust);
    mdbook_dada::process_configured(&configured_context(&fixture, "formal/model"), &mut book)
        .unwrap();
    assert!(book.to_string().contains("pub fn validate"));
}
}

An exact source selection contains the complete declaration or constructor named by a citation, excluding neighboring declarations.

A rule citation selects one constructor of its named inductive declaration. Unsupported indented sibling commands are rejected rather than treated as part of that declaration. A constructor from a sibling type cannot satisfy the citation.

Top-level mutual groups of named inductives are supported in the documented column-zero form. A citation selects the complete named member; the full enclosing source remains an evidence input. Nested, malformed, or other kinds of mutual groups are rejected.

Selection preserves literal tokens, including a final string or character index and quoted identifiers. It may omit a following standalone comment; it may not truncate the constructor’s type. These are textual source-selection checks, not Lean elaboration or a proof that the authored mathematical rule has the same meaning.

mdbook-dada/src/lean.rs:select
#![allow(unused)]
fn main() {
/// Resolve a citation with the same declaration-kind checks as the renderer.
pub fn select(root: &Path, target: &str, kind: crate::units::UnitKind) -> Result<LeanSelection> {
    use crate::units::UnitKind;
    ensure!(
        kind != UnitKind::FutureNote,
        "future notes cannot have formalization citations"
    );
    let (source, name) = read_source(root, target)?;
    let selected = match kind {
        UnitKind::FutureNote => unreachable!("rejected above"),
        UnitKind::Definition => extract_definition(&source, &name),
        UnitKind::Theorem | UnitKind::Lemma => extract_theorem(&source, &name),
        UnitKind::Example => extract_example(&source, &name),
        UnitKind::Grammar => extract(&source, &name),
        UnitKind::Judgment => extract(&source, &name).and_then(|declaration| {
            ensure!(
                declaration.starts_with("inductive "),
                "judgment citation must select an inductive declaration"
            );
            Ok(declaration)
        }),
        UnitKind::Rule => {
            let (name, case) = name
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            extract(&source, name).and_then(|declaration| extract_case(&declaration, case))
        }
    }
    .with_context(|| target.to_owned())?;
    let (file, _) = target
        .rsplit_once(':')
        .context("expected path:Declaration")?;
    let mut relative = std::path::PathBuf::from(file);
    if relative.extension().is_none() {
        relative.set_extension("lean");
    }
    // read_source already checks canonical containment, including symlinks.
    let path = root.join(relative).canonicalize()?;
    Ok(LeanSelection {
        path,
        source,
        selected,
    })
}
}
mdbook-dada/src/lean.rs:extract_declaration
#![allow(unused)]
fn main() {
fn extract_declaration(source: &str, name: &str, selection: Selection) -> Result<String> {
    let simple_name = |component: &str| {
        !component.is_empty() && component.chars().all(|c| c.is_alphanumeric() || c == '_')
    };
    if selection != Selection::Type {
        ensure!(
            name.split('.').all(simple_name),
            "use a declaration name with nonempty identifier components separated by single dots"
        );
    } else {
        ensure!(
            simple_name(name),
            "use a simple unqualified declaration name"
        );
    }
    let masked = mask(source)?;
    validate_mutual_groups(&masked)?;
    let mut found = Vec::new();
    let mut offset = 0;
    let lines: Vec<_> = masked
        .split_inclusive('\n')
        .map(|line| {
            let start = offset;
            offset += line.len();
            (start, line)
        })
        .collect();
    let structure_field = regex::Regex::new(r"^[ \t]+[A-Za-z_][A-Za-z0-9_']*[ \t]*:(?:[^:=]|$)")?;
    for (i, &(start, line)) in lines.iter().enumerate() {
        let words: Vec<_> = line.split_whitespace().collect();
        if selection == Selection::Definition {
            let declaration: Vec<_> = words
                .iter()
                .copied()
                .skip_while(|word| {
                    matches!(
                        *word,
                        "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
                    )
                })
                .collect();
            // Literal names are intentionally not resolved through namespaces.
            // A same-named declaration of the wrong kind must not disappear
            // from an otherwise ambiguous citation.
            if declaration.get(1) == Some(&name)
                && matches!(
                    declaration.first(),
                    Some(
                        &"def"
                            | &"abbrev"
                            | &"structure"
                            | &"inductive"
                            | &"theorem"
                            | &"lemma"
                            | &"axiom"
                            | &"opaque"
                            | &"constant"
                            | &"class"
                    )
                )
            {
                ensure!(
                    declaration.len() == words.len(),
                    "declaration modifiers are unsupported"
                );
                ensure!(
                    matches!(declaration.first(), Some(&"def" | &"abbrev" | &"structure" | &"inductive")),
                    "definition citations must select def, abbrev, structure, or inductive declarations"
                );
            }
        }
        if words.get(1) != Some(&name) {
            continue;
        }
        let supported = match selection {
            Selection::Theorem => words.first() == Some(&"theorem"),
            Selection::Type => {
                matches!(words.first(), Some(&"inductive" | &"structure" | &"abbrev"))
            }
            Selection::Definition => matches!(
                words.first(),
                Some(&"def" | &"inductive" | &"structure" | &"abbrev")
            ),
        };
        if !supported {
            continue;
        }
        ensure!(
            !line.starts_with(char::is_whitespace),
            "selected Lean declarations must begin at column zero"
        );
        if let Some((_, previous)) = lines[..i].iter().rev().find(|(_, l)| !l.trim().is_empty()) {
            ensure!(
                !previous.trim_start().starts_with("@["),
                "declaration attributes are unsupported"
            );
        }
        if let Some((_, boundary)) = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
        {
            let mut words = boundary.split_whitespace();
            let first = words.next().unwrap_or("");
            let mut word = first;
            while matches!(
                word,
                "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
            ) {
                word = words.next().unwrap_or("");
            }
            ensure!(
                (word == first
                    || matches!(
                        word,
                        "inductive" | "structure" | "abbrev" | "def" | "theorem" | "instance"
                    ))
                    && matches!(
                        word,
                        "inductive"
                            | "structure"
                            | "abbrev"
                            | "def"
                            | "theorem"
                            | "lemma"
                            | "example"
                            | "instance"
                            | "end"
                            | "namespace"
                            | "section"
                            | "mutual"
                            | "variable"
                            | "open"
                            | "#check"
                    ),
                "unsupported declaration boundary `{}`; continuation lines must be indented",
                boundary.trim()
            );
        }
        let end = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
            .map(|(n, _)| *n)
            .unwrap_or(source.len());
        let body = &source[start..end];
        let text = &body[..scan(body)?.content_end];
        {
            let code = &masked[start..end];
            // A structure field such as `variables : Store` is not a command.
            // Only exempt a bare, indented field name followed by a type colon;
            // `variable (x : Nat)` and `def sibling := ...` remain commands.
            let commands = command_pattern()?
                .find_iter(code)
                .filter(|command| {
                    words[0] != "structure"
                        || !structure_field
                            .is_match(code[command.start()..].lines().next().unwrap_or(""))
                })
                .count();
            ensure!(
                commands == 1,
                "selected declaration must contain no other commands, even when indented"
            );
        }
        if selection == Selection::Theorem {
            ensure!(
                has_definition_body(&masked[start..end]),
                "theorem must include its proof body (`:=`)"
            );
        } else if selection == Selection::Definition && words[0] == "def" {
            ensure!(
                has_named_definition_body(&masked[start..end])?,
                "definition must include a body (`:=`, `where`, or indented equations with `=>`)"
            );
        } else if words[0] != "abbrev" {
            ensure!(
                line.contains("where"),
                "declaration header must contain `where` on its first line"
            );
        } else {
            if selection == Selection::Definition {
                ensure!(
                    has_definition_body(&masked[start..end]),
                    "abbreviation must include a body (`:=`)"
                );
            } else {
                ensure!(line.contains(":="), "abbreviation header must contain `:=`");
            }
        }
        found.push(text.to_owned());
    }
    ensure!(
        found.len() == 1,
        "expected one supported declaration `{name}`, found {}",
        found.len()
    );
    Ok(found.remove(0))
}
}
mdbook-dada/src/lean.rs:validate_mutual_groups
#![allow(unused)]
fn main() {
fn validate_mutual_groups(masked: &str) -> Result<()> {
    let commands = command_pattern()?;
    let mut open = None;
    let mut members = HashSet::new();
    let mut previous = "";
    for (index, line) in masked.lines().enumerate() {
        let number = index + 1;
        let text = line.trim();
        if text.is_empty() {
            continue;
        }
        let words: Vec<_> = text.split_whitespace().collect();
        let command = words.iter().copied().find(|word| {
            !matches!(
                *word,
                "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
            )
        });
        if command == Some("mutual") {
            ensure!(
                open.is_none(),
                "nested mutual groups are unsupported at line {number}"
            );
            ensure!(
                text == "mutual" && !line.starts_with(char::is_whitespace),
                "mutual must stand alone at column zero at line {number}"
            );
            ensure!(
                !previous.starts_with("@["),
                "attributes on mutual groups are unsupported at line {number}"
            );
            open = Some(number);
            members.clear();
        } else if open.is_some() {
            if words.first() == Some(&"end") {
                ensure!(
                    text == "end" && !line.starts_with(char::is_whitespace),
                    "mutual groups must close with a standalone column-zero `end` at line {number}"
                );
                ensure!(
                    !members.is_empty(),
                    "empty mutual group ending at line {number}"
                );
                open = None;
            } else if line.starts_with(char::is_whitespace) {
                ensure!(
                    !members.is_empty() && !commands.is_match(line),
                    "mutual inductive bodies cannot contain indented commands at line {number}"
                );
            } else {
                ensure!(
                    words.first() == Some(&"inductive"),
                    "mutual groups support only column-zero named inductive declarations; unsupported member at line {number}"
                );
                let name = words
                    .get(1)
                    .context("mutual inductive declaration needs a name")?;
                ensure!(
                    *name != "where"
                        && name.split('.').all(|part| !part.is_empty()
                            && part.chars().all(|c| c.is_alphanumeric() || c == '_')),
                    "unsupported mutual inductive name at line {number}"
                );
                ensure!(
                    words.last() == Some(&"where"),
                    "mutual inductive headers must end with `where` on their first line at line {number}"
                );
                ensure!(
                    members.insert(*name),
                    "duplicate mutual inductive `{name}` at line {number}"
                );
            }
        }
        previous = text;
    }
    ensure!(
        open.is_none(),
        "unterminated mutual group beginning at line {}",
        open.unwrap_or(0)
    );
    Ok(())
}
}
mdbook-dada/src/lean.rs:extract_case
#![allow(unused)]
fn main() {
fn extract_case(declaration: &str, case: &str) -> Result<String> {
    ensure!(
        !case.is_empty() && case.chars().all(|c| c.is_alphanumeric() || c == '_'),
        "use a simple constructor name"
    );
    let masked = mask(declaration)?;
    let header = declaration
        .lines()
        .next()
        .context("missing declaration header")?;
    ensure!(
        header.starts_with("inductive "),
        "rule citation must select an inductive constructor"
    );
    let mut offset = 0;
    let mut candidates = Vec::new();
    for line in masked.split_inclusive('\n') {
        let trimmed = line.trim_start();
        let indent = line.len() - trimmed.len();
        if let Some(row) = trimmed.strip_prefix('|') {
            let name = row
                .trim_start()
                .split(|c: char| c.is_whitespace() || matches!(c, ':' | '(' | '{' | '['))
                .next()
                .unwrap_or("");
            candidates.push((offset, indent, name));
        }
        offset += line.len();
    }
    let indent = candidates
        .iter()
        .map(|(_, indent, _)| *indent)
        .min()
        .context("inductive has no constructors")?;
    let cases: Vec<_> = candidates
        .into_iter()
        .filter(|(_, i, _)| *i == indent)
        .collect();
    let found: Vec<_> = cases
        .iter()
        .enumerate()
        .filter(|(_, (_, _, n))| *n == case)
        .collect();
    ensure!(
        found.len() == 1,
        "expected one constructor `{case}`, found {}",
        found.len()
    );
    let (index, (start, _, _)) = found[0];
    let end = cases
        .get(index + 1)
        .map(|(start, _, _)| *start)
        .unwrap_or(declaration.len());
    // A comment introducing the next declaration is not part of this case.
    let selected = &declaration[*start..end];
    let selected = &selected[..scan(selected)?.content_end];
    Ok(format!("{header}\n{selected}"))
}
}
mdbook-dada/src/lean.rs:scan
#![allow(unused)]
fn main() {
fn scan(source: &str) -> Result<Scanned> {
    let bytes = source.as_bytes();
    let mut output = bytes.to_vec();
    let mut comments = Vec::new();
    let mut content_end = 0;
    let mut i = 0;
    while i < bytes.len() {
        let start = i;
        let mut comment = false;
        if bytes.get(i..i + 2) == Some(b"/-") {
            comment = true;
            i += 2;
            let mut depth = 1;
            while i < bytes.len() && depth > 0 {
                match bytes.get(i..i + 2) {
                    Some(b"/-") => {
                        depth += 1;
                        i += 2;
                    }
                    Some(b"-/") => {
                        depth -= 1;
                        i += 2;
                    }
                    _ => i += 1,
                }
            }
            ensure!(depth == 0, "unterminated Lean comment");
        } else if bytes.get(i..i + 2) == Some(b"--") {
            comment = true;
            comments.push(i);
            i = source[i..].find('\n').map_or(bytes.len(), |n| i + n);
        } else if let Some((quote, hashes)) = raw_string_start(source, i) {
            let closing = format!("\"{}", "#".repeat(hashes));
            let tail = quote + 1;
            i = tail
                + source[tail..]
                    .find(&closing)
                    .context("unterminated Lean raw string")?
                + closing.len();
        } else if let Some(end) = character_end(source, i) {
            i = end;
        } else if source[i..].starts_with('«') {
            i += source[i..]
                .find('»')
                .context("unterminated Lean quoted identifier")?
                + '»'.len_utf8();
        } else if bytes[i] == b'"' {
            i += 1;
            loop {
                ensure!(i < bytes.len(), "unterminated Lean string");
                match bytes[i] {
                    b'"' => {
                        i += 1;
                        break;
                    }
                    b'\\' => i += 2,
                    _ => i += 1,
                }
            }
        } else {
            // Keep UTF-8 boundaries for the character-literal lookahead below.
            let c = source[i..].chars().next().unwrap();
            i += c.len_utf8();
            if !c.is_whitespace() {
                content_end = i;
            }
            continue;
        }
        if !comment || !source[content_end..start].contains('\n') {
            // Keep comments beginning on the final code line, including a
            // block comment continuing onto later lines. Standalone comments
            // after the body belong to neither the selected declaration nor
            // its source extent. Comments before later code remain intact.
            content_end = i;
        }
        for byte in &mut output[start..i] {
            if *byte != b'\n' {
                *byte = b' ';
            }
        }
    }
    Ok(Scanned {
        code: String::from_utf8(output)?,
        line_comments: comments,
        content_end,
    })
}
}
mdbook-dada/tests/units.rs:rule_citations_cannot_select_an_indented_siblings_constructor
#![allow(unused)]
fn main() {
#[test]
fn rule_citations_cannot_select_an_indented_siblings_constructor() {
    let files = Sources::new();
    std::fs::write(files.lean().join("Sibling.lean"), "inductive First where\n  | first\n  inductive Second where\n  | second\n#check Second.second\n").unwrap();
    for kind in [UnitKind::Grammar, UnitKind::Judgment, UnitKind::Definition] {
        let error = lean::select(&files.lean(), "Sibling:First", kind).unwrap_err();
        assert!(format!("{error:#}").contains("no other commands"));
    }
    let error = lean::select(&files.lean(), "Sibling:First.second", UnitKind::Rule).unwrap_err();
    assert!(format!("{error:#}").contains("no other commands"));
    assert!(render(
        "```{rule} model.invalid\n:lean: Sibling:First.second\n\nP\n```",
        &files.lean()
    )
    .is_err());
    assert!(render("```{rule} Sibling:First.second\nP\n```", &files.lean()).is_err());
}
}
mdbook-dada/tests/units.rs:rule_selections_preserve_final_literal_tokens
#![allow(unused)]
fn main() {
#[test]
fn rule_selections_preserve_final_literal_tokens() {
    let files = Sources::new();
    for (ty, term) in [
        ("String", r#""zero""#),
        ("String", "r#\"raw -- /- «text»\"#"),
        ("Char", "'α'"),
        ("Char", "'\\n'"),
        ("Nat", "«some index»"),
    ] {
        let header = format!("inductive Indexed : {ty} → Type where");
        let case = format!("  | zero : Indexed {term}");
        for ending in [
            "\n",
            " -- attached\n",
            "\n  -- next constructor\n  | next : Indexed default\n",
        ] {
            std::fs::write(
                files.lean().join("Indexed.lean"),
                format!("{header}\n{case}{ending}"),
            )
            .unwrap();
            let selected =
                lean::select(&files.lean(), "Indexed:Indexed.zero", UnitKind::Rule).unwrap();
            assert!(
                selected.selected.starts_with(&format!("{header}\n{case}")),
                "{}",
                selected.selected
            );
            assert_eq!(
                selected.selected.contains("-- attached"),
                ending.contains("-- attached")
            );
            assert!(!selected.selected.contains("next constructor"));
            assert!(!selected.selected.contains("| next"));
            let output = render(
                "```{rule} model.literal\n:lean: Indexed:Indexed.zero\n\nP\n```",
                &files.lean(),
            )
            .unwrap();
            assert!(output.contains(&mdbook_dada::escape(term)), "{output}");
        }
    }
}
}
mdbook-dada/src/lean.rs:tests::selects_mutual_inductive_members_and_surrounding_declarations
#![allow(unused)]
fn main() {
#[test]
    fn selects_mutual_inductive_members_and_surrounding_declarations() {
        let source = include_str!("../tests/fixtures/lean/Mutual.lean");
        let eval = "inductive Eval : Nat → Prop where\n  | arguments {n : Nat} : Args n → Eval n";
        let args = "inductive Args : Nat → Prop where\n  | nil : Args 0\n  | cons {n : Nat} : Eval n → Args n";
        for (name, expected) in [("Eval", eval), ("Args", args)] {
            assert_eq!(extract(source, name).unwrap(), expected);
            assert_eq!(extract_definition(source, name).unwrap(), expected);
            assert!(extract_theorem(source, name).is_err());
        }
        assert_eq!(
            extract(source, "Token").unwrap(),
            "inductive Token where\n  | token"
        );
        assert_eq!(
            extract(source, "Step").unwrap(),
            "inductive Step : Prop where\n  | evaluated : Eval 0 → Step"
        );
        assert_eq!(
            extract_theorem(source, "finished").unwrap(),
            "theorem finished : True := by\n  trivial"
        );

        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lean");
        for kind in [
            crate::units::UnitKind::Definition,
            crate::units::UnitKind::Grammar,
            crate::units::UnitKind::Judgment,
        ] {
            let selection = select(&root, "Mutual:Eval", kind).unwrap();
            assert_eq!(selection.selected, eval);
            assert_eq!(selection.source, source);
        }
        let rule = select(&root, "Mutual:Args.cons", crate::units::UnitKind::Rule).unwrap();
        assert_eq!(
            rule.selected,
            "inductive Args : Nat → Prop where\n  | cons {n : Nat} : Eval n → Args n"
        );
        assert_eq!(rule.source, source);
        assert!(select(&root, "Mutual:Eval", crate::units::UnitKind::Theorem).is_err());
        assert!(select(&root, "Mutual:finished", crate::units::UnitKind::Definition).is_err());
    }
}
mdbook-dada/src/lean.rs:tests::mutual_validation_ignores_comment_and_literal_decoys
#![allow(unused)]
fn main() {
#[test]
    fn mutual_validation_ignores_comment_and_literal_decoys() {
        let source = format!(
            r###"/- mutual
/- mutual -/
def fake := 0
end
-/
def text := r##"
mutual
def fake := "end"
"##
def «mutual» := 0
-- mutual
{}
"###,
            include_str!("../tests/fixtures/lean/Mutual.lean")
        );
        assert!(extract(&source, "Eval")
            .unwrap()
            .contains("Args n → Eval n"));
        let comments = "mutual -- start\n/- group comment -/\ninductive First where -- header\n  | first -- end\n-- mutual\ninductive Second where\n  | second\nend -- close\n";
        assert_eq!(
            extract(comments, "Second").unwrap(),
            "inductive Second where\n  | second"
        );
        assert!(extract(comments, "First")
            .unwrap()
            .ends_with("  | first -- end"));
    }
}
mdbook-dada/src/lean.rs:tests::rejects_unsupported_or_incomplete_mutual_groups_before_any_selection
#![allow(unused)]
fn main() {
#[test]
    fn rejects_unsupported_or_incomplete_mutual_groups_before_any_selection() {
        for (group, message) in [
            (
                "mutual\ndef member := 0\nend",
                "only column-zero named inductive",
            ),
            (
                "mutual\ntheorem member : True := by trivial\nend",
                "only column-zero named inductive",
            ),
            (
                "mutual\nstructure Member where\n  field : Nat\nend",
                "only column-zero named inductive",
            ),
            (
                "mutual\ninductive Member where\n  | member\nmutual\nend\nend",
                "nested mutual",
            ),
            (
                "mutual\n  inductive Member where\n    | member\nend",
                "indented commands",
            ),
            (
                "mutual\ninductive Member where\n  | member\n  def hidden := 0\nend",
                "indented commands",
            ),
            (
                "mutual\ninductive Member where\n  | member\n  #check Nat\nend",
                "indented commands",
            ),
            (
                "mutual\ninductive Member where\n  | member\nend Member",
                "standalone column-zero `end`",
            ),
            (
                "mutual\ninductive Member where\n  | member\n  end",
                "standalone column-zero `end`",
            ),
            (
                "mutual\ninductive Member where\n  | member",
                "unterminated mutual",
            ),
            ("mutual\nend", "empty mutual"),
            (
                "mutual extra\ninductive Member where\n  | member\nend",
                "mutual must stand alone",
            ),
            (
                "private mutual\ninductive Member where\n  | member\nend",
                "mutual must stand alone",
            ),
            (
                "  mutual\ninductive Member where\n  | member\nend",
                "mutual must stand alone",
            ),
            (
                "@[expose]\nmutual\ninductive Member where\n  | member\nend",
                "attributes on mutual",
            ),
            (
                "mutual\ninductive Member\n  where\n  | member\nend",
                "headers must end with `where`",
            ),
            (
                "mutual\ninductive «Member» where\n  | member\nend",
                "unsupported mutual inductive name",
            ),
            (
                "mutual\ninductive Member where\n  | one\ninductive Member where\n  | two\nend",
                "duplicate mutual inductive",
            ),
        ] {
            let source = format!("inductive Selected where\n  | selected\n{group}\n");
            let error = extract(&source, "Selected").expect_err(group).to_string();
            assert!(error.contains(message), "{group}: {error}");
        }
        let duplicate = format!(
            "{}\ninductive Eval where\n  | another\n",
            include_str!("../tests/fixtures/lean/Mutual.lean")
        );
        assert!(extract(&duplicate, "Eval")
            .unwrap_err()
            .to_string()
            .contains("found 2"));
    }
}

Recording a review rechecks its inputs against current sources. A later decision may explicitly supersede an earlier decision for the same unit; the earlier record remains available. Every active decision must concern current inputs and conclude correspondence for that specification unit’s check to pass. Future notes assert no correspondence and cannot be prepared or recorded for correspondence review.

An independent positive decision cannot conceal an active mismatch, inconclusive review, or stale decision. If a replacement becomes stale, checking fails rather than falling back to the old positive review. Draft units fail validation and cannot receive affirmative correspondence decisions.

mdbook-dada/src/evidence.rs:record
#![allow(unused)]
fn main() {
/// Record a review only after checking the same current input set used by check.
/// Recording a mismatch is permitted and will cause required review checks to fail.
pub fn record(
    inventory: &Inventory,
    bundle: &ReviewBundle,
    review: &ReviewRecord,
) -> Result<PathBuf> {
    let current = Inventory::load(&inventory.root)?;
    let inventory = &current;
    if !link_audit::is_subject(&bundle.unit) {
        ensure!(
            inventory.unit(&bundle.unit)?.kind != UnitKind::FutureNote,
            "cannot record correspondence for a future note: it has no formalization"
        );
    }
    let mut errors = validate_bundle(inventory, bundle)?;
    errors.extend(validate_review(bundle, review));
    ensure!(
        errors.is_empty(),
        "cannot record review: {}",
        errors.join("; ")
    );
    ensure!(
        link_audit::is_subject(&bundle.unit) || !inventory.unit(&bundle.unit)?.draft,
        "cannot record review for draft unit {}: complete its formalization and matching citations, remove :status: draft, then prepare and review a new bundle",
        bundle.unit
    );
    for previous in &review.supersedes {
        ensure!(valid_digest(previous), "invalid superseded review digest");
        let old: ReviewRecord = read_json(
            &inventory
                .root
                .join("evidence/records")
                .join(&bundle.unit)
                .join(format!("{previous}.json")),
        )?;
        ensure!(
            old.digest()? == *previous,
            "superseded review contents differ"
        );
        let prior: ReviewBundle = read_json(
            &inventory
                .root
                .join("evidence/bundles")
                .join(format!("{}.json", old.bundle)),
        )?;
        ensure!(
            prior.unit == bundle.unit,
            "superseded review must concern the same unit"
        );
    }
    save_bundle(inventory, bundle)?;
    write_immutable(
        &inventory.root,
        &PathBuf::from("evidence/records")
            .join(&bundle.unit)
            .join(format!("{}.json", review.digest()?)),
        review,
    )
}
}
mdbook-dada/src/evidence.rs:check
#![allow(unused)]
fn main() {
/// Check all required units, including record presence, minimum inputs and freshness.
/// Neither the review's conclusion nor a passing result establishes a Lean proof.
pub fn check(inventory: &Inventory) -> Result<Report> {
    let mut report = Report::default();
    if let Err(error) = crate::mechanical::records(&inventory.root) {
        report.issues.push(Issue {
            unit: None,
            message: "malformed mechanical execution evidence".into(),
            details: vec![format!("{error:#}")],
        });
    }
    let mut bundles = BTreeMap::new();
    for path in json_files(&inventory.root, &inventory.root.join("evidence/bundles"))? {
        match read_json::<ReviewBundle>(&path) {
            Ok(bundle) => {
                let errors = bundle.integrity_errors();
                let name = path
                    .file_stem()
                    .and_then(|name| name.to_str())
                    .unwrap_or("");
                if !errors.is_empty() || name != bundle.digest {
                    report.issues.push(Issue {
                        unit: inventory
                            .units
                            .contains_key(&bundle.unit)
                            .then_some(bundle.unit.clone()),
                        message: format!("invalid evidence bundle {}", path.display()),
                        details: errors,
                    });
                } else {
                    bundles.insert(bundle.digest.clone(), bundle);
                }
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed evidence bundle".into(),
                details: vec![format!("{error:#}")],
            }),
        }
    }
    let audits = AuditInventory::build(inventory)?;
    // Parse every saved decision, including retired subjects. Removing a link or
    // unit retires its obligation, not the integrity checks on its history.
    let mut all_records: BTreeMap<String, BTreeMap<String, ReviewRecord>> = BTreeMap::new();
    let records_root = inventory.root.join("evidence/records");
    for path in json_tree(&inventory.root, &records_root)? {
        let parsed = (|| -> Result<(String, String, ReviewRecord)> {
            let review: ReviewRecord = read_json(&path)?;
            let digest = review.digest()?;
            ensure!(
                path.file_stem().and_then(|name| name.to_str()) == Some(&digest),
                "record filename does not match contents"
            );
            let bundle = bundles
                .get(&review.bundle)
                .context("record's bundle is missing or malformed")?;
            ensure!(
                path == records_root
                    .join(&bundle.unit)
                    .join(format!("{digest}.json")),
                "record filed under wrong subject"
            );
            let errors = validate_review(bundle, &review);
            ensure!(errors.is_empty(), "invalid review: {}", errors.join("; "));
            Ok((bundle.unit.clone(), digest, review))
        })();
        match parsed {
            Ok((subject, digest, review)) => {
                all_records
                    .entry(subject)
                    .or_default()
                    .insert(digest, review);
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed stored review".into(),
                details: vec![format!("{}: {error:#}", path.display())],
            }),
        }
    }
    for (id, records) in &all_records {
        for review in records.values() {
            for previous in &review.supersedes {
                if !records.contains_key(previous) {
                    report.issues.push(Issue {
                        unit: Some(id.clone()),
                        message: "review supersedes absent or unrelated evidence".into(),
                        details: vec![previous.clone()],
                    });
                }
            }
        }
    }
    let required_subjects: BTreeSet<_> = inventory
        .required
        .iter()
        .chain(audits.manifests.keys())
        .cloned()
        .collect();
    let mut current_active = BTreeMap::new();
    for id in &required_subjects {
        // Derive inputs even for drafts: malformed
        // citations never disappear because a formalization is unfinished.
        let required = match if link_audit::is_subject(id) {
            audits.inputs(inventory, id)
        } else {
            inventory.inputs(id)
        } {
            Ok(inputs) => inputs,
            Err(error) => {
                report.issues.push(Issue {
                    unit: Some(id.clone()),
                    message: "cannot resolve required evidence inputs".into(),
                    details: vec![format!("{error:#}")],
                });
                report.statuses.push(UnitStatus {
                    unit: id.clone(),
                    evidence: "invalid sources",
                    correspondence: "not checked",
                });
                continue;
            }
        };
        if inventory
            .units
            .get(id)
            .is_some_and(|unit| unit.kind == UnitKind::FutureNote)
        {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "future note",
                correspondence: "not applicable",
            });
            continue;
        }
        if inventory.units.get(id).is_some_and(|unit| unit.draft) {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "draft",
                correspondence: "not asserted",
            });
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("draft unit {id} requires formalization"),
                details: vec![
                    "draft status preserves the unit's semantic kind but cannot count as completed correspondence evidence".into(),
                ],
            });
            continue;
        }
        let mut current = BTreeSet::new();
        let mut stale = Vec::new();
        for bundle in bundles.values().filter(|bundle| &bundle.unit == id) {
            // Historical bundles compare with one independently derived current
            // manifest. Re-reading all sources for each past review made the
            // ordinary evidence test grow with the entire review history.
            let errors = validate_bundle_against(inventory, bundle, required.clone())?;
            if errors.is_empty() {
                current.insert(bundle.digest.clone());
            } else {
                stale.extend(errors);
            }
        }
        let empty_records = BTreeMap::new();
        let records = all_records.get(id).unwrap_or(&empty_records);
        let superseded: BTreeSet<_> = records
            .values()
            .flat_map(|review| review.supersedes.iter().cloned())
            .collect();
        let stale_active = records.iter().any(|(digest, review)| {
            !superseded.contains(digest) && !current.contains(&review.bundle)
        });
        let active: Vec<_> = records
            .iter()
            .filter(|(digest, review)| {
                current.contains(&review.bundle) && !superseded.contains(*digest)
            })
            .map(|(_, review)| review)
            .collect();
        // Cross-review order decisions may rely only on an entirely current,
        // positive subject; a conflicting or stale active record blocks it.
        if !stale_active
            && !active.is_empty()
            && active
                .iter()
                .all(|review| review.conclusion == Conclusion::Corresponds)
        {
            current_active.insert(
                id.clone(),
                active.iter().map(|review| (*review).clone()).collect(),
            );
        }
        let evidence = if stale_active {
            "stale"
        } else if !current.is_empty() {
            "current"
        } else if !stale.is_empty() {
            "stale"
        } else {
            "missing"
        };
        let correspondence = if stale_active {
            "stale decision"
        } else if active.is_empty() {
            "missing"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Mismatch)
        {
            "mismatch"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Inconclusive)
        {
            "inconclusive"
        } else {
            "corresponds"
        };
        report.statuses.push(UnitStatus {
            unit: id.clone(),
            evidence,
            correspondence,
        });
        if correspondence != "corresponds" {
            let mut details = if evidence == "stale" {
                stale
            } else {
                Vec::new()
            };
            details.sort();
            details.dedup();
            if evidence == "current" && active.is_empty() {
                details.push("preparing a bundle does not record a completed review".into());
            }
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("{evidence} evidence for {id}: correspondence {correspondence}"),
                details,
            });
        }
    }
    for (unit, message) in link_audit::cross_validate(&audits, &current_active) {
        report.issues.push(Issue {
            unit: Some(unit),
            message,
            details: Vec::new(),
        });
    }
    Ok(report)
}
}
mdbook-dada/tests/evidence_validation.rs:recording_rechecks_sources_even_with_an_existing_inventory
#![allow(unused)]
fn main() {
#[test]
fn recording_rechecks_sources_even_with_an_existing_inventory() {
    let fixture = Fixture::new();
    let inventory = fixture.inventory();
    let bundle = ReviewBundle::prepare(&inventory, "model.empty", &[]).unwrap();
    fixture.write(
        "md/model.md",
        &MODEL.replace("has no variables", "has one variable"),
    );
    assert!(
        evidence::record(&inventory, &bundle, &review(&bundle)).is_err(),
        "record accepted a changed authored source through a cached inventory"
    );
}
}
mdbook-dada/tests/evidence_validation.rs:mismatch_and_inconclusive_reviews_never_count_as_correspondence
#![allow(unused)]
fn main() {
#[test]
fn mismatch_and_inconclusive_reviews_never_count_as_correspondence() {
    for conclusion in [Conclusion::Mismatch, Conclusion::Inconclusive] {
        let fixture = Fixture::new();
        fixture.complete_reviews();
        let inventory = fixture.inventory();
        let bundle = fixture.bundle();
        let mut negative = review(&bundle);
        negative.conclusion = conclusion;
        evidence::record(&inventory, &bundle, &negative).unwrap();
        let report = evidence::check(&inventory).unwrap();
        assert!(
            !report.is_ok(),
            "negative review was hidden by a positive one"
        );
        let status = report
            .statuses
            .iter()
            .find(|status| status.unit == "model.empty")
            .unwrap();
        assert_ne!(status.correspondence, "corresponds");
    }
}
}
mdbook-dada/tests/evidence_validation.rs:revised_review_can_supersede_same_unit_after_consulting_more_context
#![allow(unused)]
fn main() {
#[test]
fn revised_review_can_supersede_same_unit_after_consulting_more_context() {
    let fixture = Fixture::new();
    fixture.complete_reviews();
    let inventory = fixture.inventory();
    let initial = fixture.bundle();
    let mut unresolved = review(&initial);
    unresolved.conclusion = Conclusion::Inconclusive;
    unresolved.rationale = "Fixture review requests additional context before deciding.".into();
    let old_path = evidence::record(&inventory, &initial, &unresolved).unwrap();
    let old_bytes = fs::read(&old_path).unwrap();
    assert!(!evidence::check(&inventory).unwrap().is_ok());

    fixture.write(
        "additional-context.txt",
        "Additional context resolves the fixture question.\n",
    );
    let revised = ReviewBundle::prepare(
        &inventory,
        "model.empty",
        &["additional-context.txt".into()],
    )
    .unwrap();
    assert_ne!(initial.digest, revised.digest);
    let mut resolved = review(&revised);
    resolved.rationale = "Fixture review now accounts for the additional context.".into();
    resolved.supersedes = vec![unresolved.digest().unwrap()];
    evidence::record(&inventory, &revised, &resolved).unwrap();
    let report = evidence::check(&inventory).unwrap();
    assert!(report.is_ok(), "{}", report.render(&inventory));
    assert_eq!(
        fs::read(&old_path).unwrap(),
        old_bytes,
        "supersession must retain the original evidence"
    );

    let other = ReviewBundle::prepare(&inventory, "model.variable", &[]).unwrap();
    let other_review = review(&other);
    let mut wrong_unit = resolved;
    wrong_unit.supersedes = vec![other_review.digest().unwrap()];
    assert!(
        evidence::record(&inventory, &revised, &wrong_unit).is_err(),
        "a review cannot supersede another unit's evidence"
    );
}
}
mdbook-dada/tests/evidence_validation.rs:stale_supersession_cannot_fall_back_to_an_independent_positive_review
#![allow(unused)]
fn main() {
#[test]
fn stale_supersession_cannot_fall_back_to_an_independent_positive_review() {
    let fixture = Fixture::new();
    // This positive review will remain current throughout the scenario.
    fixture.complete_reviews();
    let inventory = fixture.inventory();
    let initial = fixture.bundle();
    let mut mismatch = review(&initial);
    mismatch.conclusion = Conclusion::Mismatch;
    mismatch.rationale = "The fixture reviewer reports a mismatch.".into();
    evidence::record(&inventory, &initial, &mismatch).unwrap();

    fixture.write(
        "resolution.txt",
        "Extra context justifies the revised fixture conclusion.\n",
    );
    let revised =
        ReviewBundle::prepare(&inventory, "model.empty", &["resolution.txt".into()]).unwrap();
    let mut resolved = review(&revised);
    resolved.supersedes = vec![mismatch.digest().unwrap()];
    evidence::record(&inventory, &revised, &resolved).unwrap();
    assert!(evidence::check(&inventory).unwrap().is_ok());

    fixture.write(
        "resolution.txt",
        "The justification changed and needs a new review.\n",
    );
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(!report.is_ok(), "a stale superseding review hid the mismatch while the checker fell back to another positive review");
    let diagnostic = report.render(&fixture.inventory());
    assert!(diagnostic.contains("stale"), "{diagnostic}");
    assert!(diagnostic.contains("resolution.txt"), "{diagnostic}");
}
}

Required inputs

For a review bundle, validation derives its required inputs from the current specification inventory. The bundle must contain the complete authored unit and every exact cited Lean declaration, together with required context, policy, and tooling snapshots. Tooling snapshots include the renderer’s Lean test fixtures and the theme’s JavaScript and CSS, so edits to those files invalidate existing reviews. A complete Lean source file does not substitute for a missing exact declaration selection.

Validation reports missing required inputs, changed or substituted input contents or paths, and inconsistent snapshot hashes. Additional consulted files are included as explicit extra inputs and checked against their current contents. This is a check of input identity and completeness; it does not decide whether the mathematical explanation corresponds to Lean.

mdbook-dada/src/evidence.rs:validate_bundle
#![allow(unused)]
fn main() {
/// Compare against the independently derived inventory, not a self-declared
/// checklist. Extra inputs are allowed only as current project file snapshots.
pub fn validate_bundle(inventory: &Inventory, bundle: &ReviewBundle) -> Result<Vec<String>> {
    validate_bundle_against(inventory, bundle, inventory.inputs(&bundle.unit)?)
}
}
mdbook-dada/src/inventory.rs:Inventory::inputs
#![allow(unused)]
fn main() {
/// Derive required snapshots from current sources, never from a review record.
    pub fn inputs(&self, id: &str) -> Result<Vec<Input>> {
        if crate::link_audit::is_subject(id) {
            return crate::link_audit::inputs(self, id);
        }
        let mut inputs = BTreeMap::new();
        self.add_unit(id, &mut inputs, &mut BTreeSet::new())?;
        for input in self.common_inputs()? {
            inputs.insert(input.key.clone(), input);
        }
        if inputs.keys().any(|key| key.starts_with("lean:")) {
            let lean_root = self.source_configuration.lean_root(&self.root)?;
            for path in files(&self.root, &lean_root, "lean")? {
                let name = relative_path(&self.root, &path)?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
            for path in ["lean-toolchain", "lakefile.toml", "lake-manifest.json"] {
                let name = relative_path(&self.root, &lean_root.join(path))?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
        }
        Ok(inputs.into_values().collect())
    }
}
mdbook-dada/tests/evidence_validation.rs:rejects_missing_or_substituted_required_inputs
#![allow(unused)]
fn main() {
#[test]
fn rejects_missing_or_substituted_required_inputs() {
    let fixture = Fixture::new();
    let inventory = fixture.inventory();
    let original = fixture.bundle();
    assert!(original
        .inputs
        .iter()
        .any(|input| input.key == "context:lean/Fixture.lean"));
    for key in [
        "unit:model.empty",
        "lean:Fixture:empty",
        "unit:model.variable",
        "lean:Fixture:Variable",
        "policy:policy.md",
        "context:context.txt",
        "tool:Cargo.lock",
        "context:lean/lean-toolchain",
    ] {
        let mut reduced = original.clone();
        reduced.inputs.retain(|input| input.key != key);
        repack(&mut reduced);
        let errors = evidence::validate_bundle(&inventory, &reduced).unwrap();
        assert!(
            errors
                .iter()
                .any(|error| error == &format!("missing required input {key}")),
            "missing {key} escaped validation: {errors:?}"
        );
        assert!(
            !errors.iter().any(|error| error.contains("digest")),
            "attack manifest should remain internally consistent"
        );
    }

    let mut substituted = original;
    let input = substituted
        .inputs
        .iter_mut()
        .find(|input| input.key == "lean:Fixture:empty")
        .unwrap();
    input.content = "def other : List Variable := [1]".into();
    input.sha256 = hash(input.content.as_bytes());
    repack(&mut substituted);
    let errors = evidence::validate_bundle(&inventory, &substituted).unwrap();
    assert!(
        errors
            .iter()
            .any(|error| error == "stale or substituted input lean:Fixture:empty"),
        "{errors:?}"
    );
}
}
mdbook-dada/tests/evidence_validation.rs:renderer_lean_fixtures_are_required_freshness_inputs
#![allow(unused)]
fn main() {
#[test]
fn renderer_lean_fixtures_are_required_freshness_inputs() {
    let fixture = Fixture::new();
    let path = "mdbook-dada/tests/fixtures/lean/Renderer.lean";
    let key = format!("tool:{path}");
    fixture.write(path, "abbrev Sample := Nat\n");
    fixture.complete_reviews();
    let bundle = fixture.bundle();
    let input = bundle.inputs.iter().find(|input| input.key == key).unwrap();
    assert_eq!(input.content, "abbrev Sample := Nat\n");

    let mut reduced = bundle.clone();
    reduced.inputs.retain(|input| input.key != key);
    repack(&mut reduced);
    let errors = evidence::validate_bundle(&fixture.inventory(), &reduced).unwrap();
    assert!(errors.contains(&format!("missing required input {key}")));

    fixture.write(path, "abbrev Sample := String\n");
    let inventory = fixture.inventory();
    assert!(evidence::record(&inventory, &bundle, &review(&bundle)).is_err());
    let report = evidence::check(&inventory).unwrap();
    assert!(!report.is_ok());
    assert!(report.render(&inventory).contains(&key));
}
}
mdbook-dada/tests/evidence_validation.rs:theme_assets_are_required_freshness_inputs
#![allow(unused)]
fn main() {
#[test]
fn theme_assets_are_required_freshness_inputs() {
    let fixture = Fixture::new();
    fixture.write("theme/mathjax.js", "const version = 'first';\n");
    fixture.write("theme/dada.css", "figure { display: block; }\n");
    let bundle = fixture.bundle();
    for path in ["theme/mathjax.js", "theme/dada.css"] {
        let key = format!("tool:{path}");
        assert!(bundle.inputs.iter().any(|input| input.key == key));
        let mut reduced = bundle.clone();
        reduced.inputs.retain(|input| input.key != key);
        repack(&mut reduced);
        let errors = evidence::validate_bundle(&fixture.inventory(), &reduced).unwrap();
        assert!(errors.contains(&format!("missing required input {key}")));
    }
    fixture.write("theme/mathjax.js", "const version = 'second';\n");
    let errors = evidence::validate_bundle(&fixture.inventory(), &bundle).unwrap();
    assert!(errors
        .iter()
        .any(|error| error.contains("stale or substituted input tool:theme/mathjax.js")));
    fixture.write("theme/extra.css", "figure { color: red; }\n");
    let errors = evidence::validate_bundle(&fixture.inventory(), &bundle).unwrap();
    assert!(errors.contains(&"missing required input tool:theme/extra.css".to_owned()));
}
}

Finite maps

A finite map associates a key with at most one value. Write \(M : K \rightharpoonup T\) for a finite map from keys in \(K\) to values in \(T\). Its finite list of entries contains pairs \((k,v)\), and no key occurs twice. The list records an order; the unique-key condition does not impose an order on the keys themselves.

definitionevidence.map.empty_definition The empty map \(\varnothing\) has no entries.

Common/FiniteMap:FiniteMap
structure FiniteMap (Key Value : Type) where
  entries : List (Key × Value)
  uniqueKeys : (entries.map Prod.fst).Nodup
Common/FiniteMap:FiniteMap.empty
def FiniteMap.empty : FiniteMap Key Value where
  entries := []
  uniqueKeys := List.nodup_nil

For any refevidence.map \(M\), key \(k\), and values \(v,w\), if both \((k,v)\) and \((k,w)\) are entries of \(M\), then \(v=w\). This holds for any key and value types; no ordering or decidable equality on keys is assumed.

Common/FiniteMap:FiniteMap.value_unique
theorem FiniteMap.value_unique (map : FiniteMap Key Value)
    {key : Key} {value value' : Value}
    (member : (key, value) ∈ map.entries)
    (member' : (key, value') ∈ map.entries) : value = value' := by
  obtain ⟨i, hi, entry⟩ := List.getElem_of_mem member
  obtain ⟨j, hj, entry'⟩ := List.getElem_of_mem member'
  have same_index : i = j := map.uniqueKeys.eq_of_getElem_eq
    (by simpa using hi) (by simpa using hj) (by simp [entry, entry'])
  subst j
  have same_entry : (key, value) = (key, value') := entry.symm.trans entry'
  exact (Prod.mk.inj same_entry).2

Choose natural numbers as both keys and values. The empty map has the empty entry list \([]\). There is no key-value pair stored in this example.

Common/FiniteMapExamples:empty_map
example : (FiniteMap.empty : FiniteMap Nat Nat).entries = [] := by
  rfl

Mechanical execution records

A mechanical execution receipt records a named check from spec-checks.json. Only an explicit run-check command executes it. The receipt retains the exact profile, working directory, command and tool-version outputs as bytes, exit statuses, local timing, and declared source snapshots before and after execution. The profile and runner sources are mandatory inputs; directory snapshots record membership, including empty directories. Source symlinks and generated input roots are rejected. The fixed generated-directory exclusions are .git, .lake, target, book, and evidence.

A recorded pass requires a successful command, successful identical version probes, and identical before/after snapshots. Failed commands, failed launches, and failed recapture remain recorded failures. Saved input hashes, membership, profile identity, receipt contents, and filenames are checked independently of correspondence decisions. Missing declared roots, runner/configuration roots, or members listed in directory snapshots are invalid, even when the remaining hashes have been recomputed.

Status uses the latest local finish time for each check. Any failure or stale receipt tied at that time prevents a reported pass; an older success cannot conceal it. Source or profile changes make receipts stale. Syntactic evidence validation reads these records without running checks or requiring recorded success. This keeps a Cargo test from depending on a receipt of its own run.

The receipt covers its declared sources and observed outputs. It is not a hermetic execution trace or authentication of the runner. Generated artifacts, review records, ambient environment, and installed dependencies are outside the source snapshot; edits restored between snapshots can escape detection. A separate Lean assumptions command reports dependencies for its explicitly named theorems after rebuilding imports. These observations do not establish the meaning of a theorem or constitute a correspondence judgment.

mdbook-dada/src/mechanical.rs:run
#![allow(unused)]
fn main() {
/// Execute only an explicitly selected configured check. Preserve failures as well
/// as successes; endpoint snapshots do not provide filesystem isolation.
pub fn run(root: &Path, name: &str) -> Result<PathBuf> {
    let root = root.canonicalize()?;
    let config = Configuration::load(&root)?;
    let check = config
        .checks
        .get(name)
        .with_context(|| format!("unknown mechanical check {name}"))?
        .clone();
    let cwd = working_directory(&root, &check.cwd)?;
    let before = snapshot(&root, &check)?;
    let started_unix_ms = now()?;
    let timer = Instant::now();
    let version_before = execute(&check.version, &cwd);
    let command = version_before
        .succeeded()
        .then(|| execute(&check.command, &cwd));
    let version_after = execute(&check.version, &cwd);
    let (after, after_error) = match snapshot(&root, &check) {
        Ok(inputs) => (Some(inputs), None),
        Err(error) => (None, Some(format!("{error:#}"))),
    };
    let mut receipt = Execution {
        schema: SCHEMA,
        name: name.into(),
        check,
        host_os: std::env::consts::OS.into(),
        host_arch: std::env::consts::ARCH.into(),
        started_unix_ms,
        finished_unix_ms: now()?,
        elapsed_ms: timer.elapsed().as_millis(),
        before,
        after,
        after_error,
        version_before,
        command,
        version_after,
        digest: String::new(),
    };
    receipt.digest = receipt.content_digest()?;
    receipt.validate()?;
    write_immutable(
        &root,
        &PathBuf::from(RECORDS).join(format!("{}.json", receipt.digest)),
        &receipt,
    )
}
}
mdbook-dada/src/mechanical.rs:snapshot
#![allow(unused)]
fn main() {
/// Capture directory membership and complete UTF-8 source contents, in path order.
/// Versioned profiles and runner sources are always included independently of inputs.
pub fn snapshot(root: &Path, check: &Check) -> Result<Vec<Input>> {
    let mut inputs = BTreeMap::new();
    for relative in check
        .inputs
        .iter()
        .map(String::as_str)
        .chain([CONFIG, "mdbook-dada/src"])
    {
        let path = input_path(root, relative)?;
        ensure!(
            !generated(path.strip_prefix(root)?),
            "generated output cannot be a mechanical input"
        );
        // Inspect the lexical path as well, so a selected symlink is not followed.
        let mut lexical = root.to_owned();
        for component in Path::new(relative).components() {
            lexical.push(component);
            ensure!(
                !fs::symlink_metadata(&lexical)?.file_type().is_symlink(),
                "mechanical input uses a symbolic link"
            );
        }
        collect(root, &path, &mut inputs)?;
    }
    Ok(inputs.into_values().collect())
}
}
mdbook-dada/src/mechanical.rs:Execution::validate
#![allow(unused)]
fn main() {
pub fn validate(&self) -> Result<()> {
        ensure!(
            self.schema == SCHEMA && self.content_digest()? == self.digest,
            "execution digest or schema is invalid"
        );
        validate_check(&self.check)?;
        ensure!(!self.before.is_empty(), "execution has no input snapshots");
        ensure!(
            self.after.is_some() != self.after_error.is_some(),
            "execution needs an after snapshot or an error"
        );
        ensure!(
            self.command.is_some() == self.version_before.succeeded(),
            "execution command/version results are inconsistent"
        );
        for inputs in std::iter::once(&self.before).chain(self.after.iter()) {
            validate_snapshot(inputs, &self.check)?;
        }
        let config_input = self
            .before
            .iter()
            .find(|input| input.path == CONFIG)
            .context("missing check configuration")?;
        let config: Configuration = serde_json::from_str(&config_input.content)?;
        ensure!(
            config.schema == SCHEMA && config.checks.get(&self.name) == Some(&self.check),
            "recorded check differs from its configuration snapshot"
        );
        for outcome in [&self.version_before, &self.version_after]
            .into_iter()
            .chain(self.command.iter())
        {
            if let Some(error) = &outcome.launch_error {
                ensure!(
                    !error.is_empty()
                        && outcome.exit_code.is_none()
                        && outcome.stdout.is_empty()
                        && outcome.stderr.is_empty(),
                    "launch error has process output or exit code"
                );
            }
        }
        Ok(())
    }
}
mdbook-dada/src/mechanical.rs:status
#![allow(unused)]
fn main() {
/// Report the latest receipt per configured check. A later failure or stale run
/// cannot be hidden by an older success. Local receipt timestamps are provenance,
/// not an authenticated clock.
pub fn status(root: &Path) -> Result<Vec<Status>> {
    let records = records(root)?;
    if !root.join(CONFIG).exists() {
        if records.is_empty() {
            return Ok(Vec::new());
        }
        bail!("execution receipts exist without {CONFIG}");
    }
    let config = Configuration::load(root)?;
    config
        .checks
        .into_iter()
        .map(|(name, check)| {
            let latest_time = records
                .iter()
                .filter(|r| r.name == name)
                .map(|r| r.finished_unix_ms)
                .max();
            let latest: Vec<_> = records
                .iter()
                .filter(|r| r.name == name && Some(r.finished_unix_ms) == latest_time)
                .collect();
            let current = snapshot(root, &check)?;
            let state = if latest.is_empty() {
                "not recorded"
            } else if latest
                .iter()
                .any(|r| r.check != check || r.before != current)
            {
                "stale"
            } else if latest.iter().any(|r| !r.succeeded()) {
                "recorded failure"
            } else {
                "recorded pass"
            };
            let responsible = latest
                .iter()
                .filter(|r| match state {
                    "stale" => r.check != check || r.before != current,
                    "recorded failure" => !r.succeeded(),
                    _ => true,
                })
                .min_by_key(|r| &r.digest);
            Ok(Status {
                name,
                state,
                receipt: responsible.map(|r| r.digest.clone()),
            })
        })
        .collect()
}
}
mdbook-dada/src/mechanical.rs:records
#![allow(unused)]
fn main() {
/// Validate retained receipts without executing any commands, including historical
/// failures and receipts for checks no longer configured.
pub fn records(root: &Path) -> Result<Vec<Execution>> {
    let directory = root.join(RECORDS);
    if !directory.exists() {
        return Ok(Vec::new());
    }
    ensure!(
        directory.canonicalize()?.starts_with(root),
        "execution directory escapes project"
    );
    let mut records = Vec::new();
    for entry in fs::read_dir(directory)? {
        let path = entry?.path();
        ensure!(
            !fs::symlink_metadata(&path)?.file_type().is_symlink(),
            "execution receipt is a symbolic link"
        );
        if path.extension().is_some_and(|s| s == "json") {
            records.push(load(&path)?);
        }
    }
    Ok(records)
}
}
mdbook-dada/src/evidence.rs:check
#![allow(unused)]
fn main() {
/// Check all required units, including record presence, minimum inputs and freshness.
/// Neither the review's conclusion nor a passing result establishes a Lean proof.
pub fn check(inventory: &Inventory) -> Result<Report> {
    let mut report = Report::default();
    if let Err(error) = crate::mechanical::records(&inventory.root) {
        report.issues.push(Issue {
            unit: None,
            message: "malformed mechanical execution evidence".into(),
            details: vec![format!("{error:#}")],
        });
    }
    let mut bundles = BTreeMap::new();
    for path in json_files(&inventory.root, &inventory.root.join("evidence/bundles"))? {
        match read_json::<ReviewBundle>(&path) {
            Ok(bundle) => {
                let errors = bundle.integrity_errors();
                let name = path
                    .file_stem()
                    .and_then(|name| name.to_str())
                    .unwrap_or("");
                if !errors.is_empty() || name != bundle.digest {
                    report.issues.push(Issue {
                        unit: inventory
                            .units
                            .contains_key(&bundle.unit)
                            .then_some(bundle.unit.clone()),
                        message: format!("invalid evidence bundle {}", path.display()),
                        details: errors,
                    });
                } else {
                    bundles.insert(bundle.digest.clone(), bundle);
                }
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed evidence bundle".into(),
                details: vec![format!("{error:#}")],
            }),
        }
    }
    let audits = AuditInventory::build(inventory)?;
    // Parse every saved decision, including retired subjects. Removing a link or
    // unit retires its obligation, not the integrity checks on its history.
    let mut all_records: BTreeMap<String, BTreeMap<String, ReviewRecord>> = BTreeMap::new();
    let records_root = inventory.root.join("evidence/records");
    for path in json_tree(&inventory.root, &records_root)? {
        let parsed = (|| -> Result<(String, String, ReviewRecord)> {
            let review: ReviewRecord = read_json(&path)?;
            let digest = review.digest()?;
            ensure!(
                path.file_stem().and_then(|name| name.to_str()) == Some(&digest),
                "record filename does not match contents"
            );
            let bundle = bundles
                .get(&review.bundle)
                .context("record's bundle is missing or malformed")?;
            ensure!(
                path == records_root
                    .join(&bundle.unit)
                    .join(format!("{digest}.json")),
                "record filed under wrong subject"
            );
            let errors = validate_review(bundle, &review);
            ensure!(errors.is_empty(), "invalid review: {}", errors.join("; "));
            Ok((bundle.unit.clone(), digest, review))
        })();
        match parsed {
            Ok((subject, digest, review)) => {
                all_records
                    .entry(subject)
                    .or_default()
                    .insert(digest, review);
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed stored review".into(),
                details: vec![format!("{}: {error:#}", path.display())],
            }),
        }
    }
    for (id, records) in &all_records {
        for review in records.values() {
            for previous in &review.supersedes {
                if !records.contains_key(previous) {
                    report.issues.push(Issue {
                        unit: Some(id.clone()),
                        message: "review supersedes absent or unrelated evidence".into(),
                        details: vec![previous.clone()],
                    });
                }
            }
        }
    }
    let required_subjects: BTreeSet<_> = inventory
        .required
        .iter()
        .chain(audits.manifests.keys())
        .cloned()
        .collect();
    let mut current_active = BTreeMap::new();
    for id in &required_subjects {
        // Derive inputs even for drafts: malformed
        // citations never disappear because a formalization is unfinished.
        let required = match if link_audit::is_subject(id) {
            audits.inputs(inventory, id)
        } else {
            inventory.inputs(id)
        } {
            Ok(inputs) => inputs,
            Err(error) => {
                report.issues.push(Issue {
                    unit: Some(id.clone()),
                    message: "cannot resolve required evidence inputs".into(),
                    details: vec![format!("{error:#}")],
                });
                report.statuses.push(UnitStatus {
                    unit: id.clone(),
                    evidence: "invalid sources",
                    correspondence: "not checked",
                });
                continue;
            }
        };
        if inventory
            .units
            .get(id)
            .is_some_and(|unit| unit.kind == UnitKind::FutureNote)
        {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "future note",
                correspondence: "not applicable",
            });
            continue;
        }
        if inventory.units.get(id).is_some_and(|unit| unit.draft) {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "draft",
                correspondence: "not asserted",
            });
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("draft unit {id} requires formalization"),
                details: vec![
                    "draft status preserves the unit's semantic kind but cannot count as completed correspondence evidence".into(),
                ],
            });
            continue;
        }
        let mut current = BTreeSet::new();
        let mut stale = Vec::new();
        for bundle in bundles.values().filter(|bundle| &bundle.unit == id) {
            // Historical bundles compare with one independently derived current
            // manifest. Re-reading all sources for each past review made the
            // ordinary evidence test grow with the entire review history.
            let errors = validate_bundle_against(inventory, bundle, required.clone())?;
            if errors.is_empty() {
                current.insert(bundle.digest.clone());
            } else {
                stale.extend(errors);
            }
        }
        let empty_records = BTreeMap::new();
        let records = all_records.get(id).unwrap_or(&empty_records);
        let superseded: BTreeSet<_> = records
            .values()
            .flat_map(|review| review.supersedes.iter().cloned())
            .collect();
        let stale_active = records.iter().any(|(digest, review)| {
            !superseded.contains(digest) && !current.contains(&review.bundle)
        });
        let active: Vec<_> = records
            .iter()
            .filter(|(digest, review)| {
                current.contains(&review.bundle) && !superseded.contains(*digest)
            })
            .map(|(_, review)| review)
            .collect();
        // Cross-review order decisions may rely only on an entirely current,
        // positive subject; a conflicting or stale active record blocks it.
        if !stale_active
            && !active.is_empty()
            && active
                .iter()
                .all(|review| review.conclusion == Conclusion::Corresponds)
        {
            current_active.insert(
                id.clone(),
                active.iter().map(|review| (*review).clone()).collect(),
            );
        }
        let evidence = if stale_active {
            "stale"
        } else if !current.is_empty() {
            "current"
        } else if !stale.is_empty() {
            "stale"
        } else {
            "missing"
        };
        let correspondence = if stale_active {
            "stale decision"
        } else if active.is_empty() {
            "missing"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Mismatch)
        {
            "mismatch"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Inconclusive)
        {
            "inconclusive"
        } else {
            "corresponds"
        };
        report.statuses.push(UnitStatus {
            unit: id.clone(),
            evidence,
            correspondence,
        });
        if correspondence != "corresponds" {
            let mut details = if evidence == "stale" {
                stale
            } else {
                Vec::new()
            };
            details.sort();
            details.dedup();
            if evidence == "current" && active.is_empty() {
                details.push("preparing a bundle does not record a completed review".into());
            }
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("{evidence} evidence for {id}: correspondence {correspondence}"),
                details,
            });
        }
    }
    for (unit, message) in link_audit::cross_validate(&audits, &current_active) {
        report.issues.push(Issue {
            unit: Some(unit),
            message,
            details: Vec::new(),
        });
    }
    Ok(report)
}
}
mdbook-dada/tests/mechanical.rs:execution_preserves_success_failure_and_non_utf8_output
#![allow(unused)]
fn main() {
#[test]
fn execution_preserves_success_failure_and_non_utf8_output() {
    let successful = Fixture::new("printf done; printf diagnostic >&2");
    let (_, receipt) = successful.run();
    assert!(receipt.succeeded());
    let output = receipt.command.unwrap();
    assert_eq!(output.stdout, b"done");
    assert_eq!(output.stderr, b"diagnostic");
    assert_eq!(output.exit_code, Some(0));
    assert_eq!(successful.state(), "recorded pass");

    let failing = Fixture::new("printf '\\377\\000ok'; printf '\\376err' >&2; exit 7");
    let (path, receipt) = failing.run();
    assert!(path.is_file(), "failure must leave an inspectable receipt");
    assert!(!receipt.succeeded());
    let output = receipt.command.unwrap();
    assert_eq!(output.stdout, [255, 0, b'o', b'k']);
    assert_eq!(output.stderr, [254, b'e', b'r', b'r']);
    assert_eq!(output.exit_code, Some(7));
    assert_eq!(failing.state(), "recorded failure");
}
}
mdbook-dada/tests/mechanical.rs:execution_retains_source_mutations_additions_and_deletions
#![allow(unused)]
fn main() {
#[test]
fn execution_retains_source_mutations_additions_and_deletions() {
    for script in [
        "printf changed > sources/model.txt",
        "printf added > sources/added.txt",
        "rm sources/model.txt",
    ] {
        let fixture = Fixture::new(script);
        let (_, receipt) = fixture.run();
        assert_eq!(receipt.command.as_ref().unwrap().exit_code, Some(0));
        assert!(!receipt.succeeded(), "input changes escaped: {script}");
        assert_ne!(receipt.after.as_ref(), Some(&receipt.before));
        assert_eq!(fixture.state(), "stale");
    }
}
}
mdbook-dada/tests/mechanical.rs:failed_after_snapshot_and_launch_failures_are_retained
#![allow(unused)]
fn main() {
#[test]
fn failed_after_snapshot_and_launch_failures_are_retained() {
    let deleted = Fixture::new("rm sources/model.txt");
    let mut check = deleted.check();
    check.inputs = vec!["sources/model.txt".into()];
    deleted.configure(check);
    let (_, receipt) = deleted.run();
    assert!(receipt.after.is_none());
    assert!(receipt.after_error.is_some());
    assert!(!receipt.succeeded());
    assert_eq!(mechanical::records(&deleted.0).unwrap().len(), 1);

    let missing_command = Fixture::new("exit 0");
    let mut check = missing_command.check();
    check.command = vec![missing_command
        .0
        .join("absent-program")
        .display()
        .to_string()];
    missing_command.configure(check);
    let (_, receipt) = missing_command.run();
    assert!(receipt.command.unwrap().launch_error.is_some());
    assert_eq!(missing_command.state(), "recorded failure");

    let failed_version = Fixture::new("touch should-not-run");
    let mut check = failed_version.check();
    check.version = vec!["sh".into(), "-c".into(), "exit 3".into()];
    failed_version.configure(check);
    let (_, receipt) = failed_version.run();
    assert!(receipt.command.is_none());
    assert_eq!(receipt.version_before.exit_code, Some(3));
    assert!(!failed_version.0.join("should-not-run").exists());
}
}
mdbook-dada/tests/mechanical.rs:status_and_record_validation_never_execute_profile_commands
#![allow(unused)]
fn main() {
#[test]
fn status_and_record_validation_never_execute_profile_commands() {
    let fixture = Fixture::new("printf called >> invocations");
    assert_eq!(fixture.state(), "not recorded");
    assert!(!fixture.0.join("invocations").exists());
    fixture.run();
    for _ in 0..3 {
        assert_eq!(fixture.state(), "recorded pass");
        assert_eq!(mechanical::records(&fixture.0).unwrap().len(), 1);
    }
    assert_eq!(fs::read(fixture.0.join("invocations")).unwrap(), b"called");
}
}
mdbook-dada/tests/mechanical.rs:source_or_profile_changes_stale_receipts_without_corrupting_history
#![allow(unused)]
fn main() {
#[test]
fn source_or_profile_changes_stale_receipts_without_corrupting_history() {
    let fixture = Fixture::new("exit 0");
    let (path, _) = fixture.run();
    fixture.write("sources/model.txt", "changed\n");
    assert_eq!(fixture.state(), "stale");
    assert!(mechanical::load(&path).unwrap().succeeded());
    fixture.write("sources/model.txt", "original source\n");
    let mut check = fixture.check();
    check.description.push_str(" with revised scope");
    fixture.configure(check);
    assert_eq!(fixture.state(), "stale");
    assert_eq!(mechanical::records(&fixture.0).unwrap().len(), 1);
}
}
mdbook-dada/tests/mechanical.rs:later_failures_and_tied_failures_cannot_be_hidden_by_success
#![allow(unused)]
fn main() {
#[test]
fn later_failures_and_tied_failures_cannot_be_hidden_by_success() {
    let fixture = Fixture::new("if test -f fail-now; then exit 8; fi");
    let (pass_path, mut passed) = fixture.run();
    fixture.write("fail-now", "");
    let (fail_path, mut failed) = fixture.run();
    fs::remove_file(pass_path).unwrap();
    fs::remove_file(fail_path).unwrap();

    // Give the failed fixture receipt a strictly later timestamp first.
    failed.finished_unix_ms = passed.finished_unix_ms + 1;
    failed.started_unix_ms = passed.started_unix_ms;
    let fail_path = save_repacked(&fixture.0, failed.clone());
    let pass_path = save_repacked(&fixture.0, passed.clone());
    assert_eq!(fixture.state(), "recorded failure");
    fs::remove_file(pass_path).unwrap();
    fs::remove_file(fail_path).unwrap();

    // Timestamps are not unique. Choose a success digest that sorts after the
    // failure, so digest tie-breaking cannot accidentally hide that failure.
    passed.finished_unix_ms = failed.finished_unix_ms;
    repack(&mut failed);
    for nonce in 0..10_000 {
        passed.host_os = format!("synthetic-test-host-{nonce}");
        repack(&mut passed);
        if passed.digest > failed.digest {
            break;
        }
    }
    assert!(passed.digest > failed.digest);
    let failed_digest = failed.digest.clone();
    save_repacked(&fixture.0, passed);
    save_repacked(&fixture.0, failed);
    assert_eq!(fixture.state(), "recorded failure");
    assert_eq!(
        mechanical::status(&fixture.0).unwrap()[0].receipt,
        Some(failed_digest),
        "a failure status must identify the failing receipt"
    );
}
}
mdbook-dada/tests/mechanical.rs:receipt_validation_rejects_tampering_and_profile_substitution
#![allow(unused)]
fn main() {
#[test]
fn receipt_validation_rejects_tampering_and_profile_substitution() {
    let fixture = Fixture::new("exit 0");
    let (path, receipt) = fixture.run();
    let mut tampered = receipt.clone();
    tampered.command.as_mut().unwrap().stdout.push(42);
    fs::write(&path, serde_json::to_vec(&tampered).unwrap()).unwrap();
    assert!(mechanical::load(&path).is_err());
    fs::remove_file(path).unwrap();

    let mut substituted = receipt;
    substituted.check.command = vec!["made-up-check".into()];
    let path = save_repacked(&fixture.0, substituted);
    assert!(
        mechanical::load(&path).is_err(),
        "embedded check must agree with snapshotted configuration"
    );
}
}
mdbook-dada/tests/mechanical.rs:receipt_validation_requires_selected_sources_and_runner_snapshots
#![allow(unused)]
fn main() {
#[test]
fn receipt_validation_requires_selected_sources_and_runner_snapshots() {
    let fixture = Fixture::new("exit 0");
    let (original_path, receipt) = fixture.run();
    fs::remove_file(original_path).unwrap();
    for missing in [
        "sources/model.txt",
        "mdbook-dada/src/lib.rs",
        "spec-checks.json",
    ] {
        let mut reduced = receipt.clone();
        reduced.before.retain(|input| input.path != missing);
        reduced
            .after
            .as_mut()
            .unwrap()
            .retain(|input| input.path != missing);
        let path = save_repacked(&fixture.0, reduced);
        assert!(
            mechanical::load(&path).is_err(),
            "a self-consistently rehashed missing input escaped: {missing}"
        );
        fs::remove_file(path).unwrap();
    }
}
}
mdbook-dada/tests/mechanical.rs:snapshots_record_empty_directories_and_ignore_generated_outputs
#![allow(unused)]
fn main() {
#[test]
fn snapshots_record_empty_directories_and_ignore_generated_outputs() {
    let fixture = Fixture::new("exit 0");
    fs::create_dir(fixture.0.join("sources/empty")).unwrap();
    let original = mechanical::snapshot(&fixture.0, &fixture.check()).unwrap();
    assert!(original
        .iter()
        .any(|input| input.key == "directory:sources/empty"));
    for output in [
        "sources/.lake/cache",
        "sources/target/debug/output",
        "sources/book/page.html",
        "sources/evidence/record.json",
    ] {
        fixture.write(output, "generated");
    }
    assert_eq!(
        original,
        mechanical::snapshot(&fixture.0, &fixture.check()).unwrap()
    );
    let mut check = fixture.check();
    check.inputs = vec!["sources/target".into()];
    assert!(mechanical::snapshot(&fixture.0, &check).is_err());
}
}
mdbook-dada/tests/mechanical.rs:snapshots_and_records_reject_symbolic_links
#![allow(unused)]
fn main() {
#[test]
fn snapshots_and_records_reject_symbolic_links() {
    use std::os::unix::fs::symlink;

    let fixture = Fixture::new("exit 0");
    symlink("model.txt", fixture.0.join("sources/alias.txt")).unwrap();
    assert!(mechanical::snapshot(&fixture.0, &fixture.check()).is_err());
    let mut selected_link = fixture.check();
    selected_link.inputs = vec!["sources/alias.txt".into()];
    assert!(mechanical::snapshot(&fixture.0, &selected_link).is_err());
    fs::remove_file(fixture.0.join("sources/alias.txt")).unwrap();
    let (path, _) = fixture.run();
    symlink(path, fixture.0.join("evidence/executions/alias.json")).unwrap();
    assert!(mechanical::records(&fixture.0).is_err());
}
}
mdbook-dada/tests/evidence_validation.rs:workspace_validation_rejects_malformed_execution_receipts
#![allow(unused)]
fn main() {
#[test]
fn workspace_validation_rejects_malformed_execution_receipts() {
    let fixture = Fixture::new();
    fixture.complete_reviews();
    fixture.write("evidence/executions/invalid.json", "{}");
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(!report.is_ok());
    assert!(report
        .issues
        .iter()
        .any(|issue| issue.message == "malformed mechanical execution evidence"));
}
}

Renderer contracts

Identities and blocks

An identity names one location in the book. IDs begin with an ASCII letter or digit and otherwise contain ASCII letters, digits, dots, underscores, or hyphens. Structured unit IDs and legacy defining roles share one global namespace. Malformed IDs, duplicate definitions, and unresolved references fail rendering. Forward references and references between nested chapter directories work.

definitionmeta.syntax.anchors.roles Legacy {anchor} and {definition} roles define locations; {anchor-ref} links to them. A neutral anchor inherits the surrounding definition, theorem, or lemma label. A role’s label does not establish correspondence or a proof.

definitionmeta.syntax.anchors.inline A defining role stays in its paragraph. Put it immediately before the text to show the shield inline with that text.

definitionmeta.syntax.anchors.rendering Definitions become local HTML shields. References become ref shields linking to the defining chapter and fragment. Shields require no external badge service.

definitionmeta.syntax.anchors.literal Roles inside fenced or indented code, links, or HTML blocks remain literal. Escaped role prefixes and double-backtick demonstrations also remain literal. These are the supported custom roles, not a general MyST parser.

mdbook-dada/src/lib.rs:roles
#![allow(unused)]
fn main() {
fn roles(source: &str) -> Result<Vec<Role>> {
    let id_pattern = Regex::new(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")?;
    let mut found = vec![];
    let mut text_end = None;
    let mut excluded = 0;
    for (event, range) in Parser::new(source).into_offset_iter() {
        match event {
            Event::Start(
                Tag::CodeBlock(_) | Tag::Link { .. } | Tag::Image { .. } | Tag::HtmlBlock,
            ) => {
                excluded += 1;
                text_end = None;
            }
            Event::End(TagEnd::CodeBlock | TagEnd::Link | TagEnd::Image | TagEnd::HtmlBlock) => {
                excluded -= 1;
                text_end = None;
            }
            Event::Text(_) if excluded == 0 => text_end = Some(range),
            Event::Code(id) if excluded == 0 => {
                if let Some(previous) = text_end.take() {
                    let removed = "{obligation}";
                    if previous.end == range.start
                        && source[previous.clone()].ends_with(removed)
                        && !source[..range.start - removed.len()].ends_with('\\')
                        && source[range.clone()] == format!("`{id}`")
                    {
                        bail!("{{obligation}} has been removed; use a named definition, theorem, lemma, or example with :status: draft when formalization is pending");
                    }
                    for (prefix, definition, label, lean) in [
                        ("{anchor}", true, None, false),
                        ("{definition}", true, Some("definition"), false),
                        ("{anchor-ref}", false, None, false),
                        ("{lean.type}", false, None, true),
                    ] {
                        if previous.end != range.start
                            || !source[previous.clone()].ends_with(prefix)
                        {
                            continue;
                        }
                        let start = range.start - prefix.len();
                        if source[..start].ends_with('\\') {
                            continue;
                        }
                        // Double-backtick spans are literal demonstrations, not roles.
                        if source[range.clone()] != format!("`{id}`") {
                            continue;
                        }
                        ensure!(lean || id_pattern.is_match(&id), "invalid anchor ID `{id}`");
                        found.push(Role {
                            range: start..range.end,
                            id: id.into_string(),
                            definition,
                            label,
                            lean,
                        });
                        break;
                    }
                }
            }
            _ => text_end = None,
        }
    }
    Ok(found)
}
}
mdbook-dada/src/lib.rs:chapter_roles
#![allow(unused)]
fn main() {
fn chapter_roles(source: &str) -> Result<Vec<Role>> {
    let protected = protect_math(source);
    let mut found = roles(&protected)?;
    for unit in units::parse(source, "chapter")? {
        found.push(Role {
            range: unit.range,
            id: unit.id,
            definition: true,
            label: None,
            lean: false,
        });
    }
    for block in directive_blocks(&protected) {
        if block
            .info
            .split_whitespace()
            .next()
            .is_some_and(|name| MarkdownDirective::parse(name).is_some() || name == "{future-note}")
        {
            // These bodies are Markdown; grammar, judgment, and rule bodies are TeX.
            ensure!(
                !directive_blocks(&block.body).iter().any(|nested| {
                    ["{definition}", "{example}", "{theorem}", "{lemma}", "{future-note}"]
                        .iter()
                        .any(|name| nested.info.starts_with(name))
                }),
                "definition, example, theorem, and lemma directives cannot be nested within one another"
            );
            found.extend(roles(&protect_math(&block.body))?);
        }
    }
    Ok(found)
}
}
mdbook-dada/src/lib.rs:process_with_roots
#![allow(unused)]
fn main() {
fn process_with_roots(
    book: &mut Value,
    lean_root: Option<&Path>,
    project_root: Option<&Path>,
) -> Result<()> {
    let key = if book.get("items").is_some_and(Value::is_array) {
        "items"
    } else if book.get("sections").is_some_and(Value::is_array) {
        "sections"
    } else {
        bail!("unsupported mdBook input: expected an items or sections array");
    };
    let mut anchors = BTreeMap::new();
    walk(&book[key], &mut |chapter| {
        let source = chapter["content"]
            .as_str()
            .context("chapter has no content")?;
        let path = chapter["path"].as_str().context("chapter has no path")?;
        lint::check_latex(source, path)?;
        for role in chapter_roles(source).with_context(|| path.to_owned())? {
            if role.definition {
                if let Some(previous) = anchors.insert(role.id.clone(), path.to_owned()) {
                    bail!("duplicate anchor `{}` in {previous} and {path}", role.id);
                }
            }
        }
        Ok(())
    })?;
    fn update(
        items: &mut Value,
        anchors: &BTreeMap<String, String>,
        lean_root: Option<&Path>,
        project_root: Option<&Path>,
    ) -> Result<()> {
        if let Some(items) = items.as_array_mut() {
            for item in items {
                if let Some(chapter) = item.get_mut("Chapter") {
                    let path = chapter["path"].as_str().context("chapter has no path")?;
                    let source = chapter["content"]
                        .as_str()
                        .context("chapter has no content")?;
                    let content = render(
                        source,
                        path,
                        anchors,
                        lean_root,
                        project_root,
                        path,
                        "anchor",
                    )
                    .with_context(|| format!("chapter {path}"))?;
                    chapter["content"] = Value::String(content);
                    update(&mut chapter["sub_items"], anchors, lean_root, project_root)?;
                }
            }
        }
        Ok(())
    }
    update(&mut book[key], &anchors, lean_root, project_root)
}
}
mdbook-dada/src/lib.rs:relative_html
#![allow(unused)]
fn main() {
fn relative_html(from: &str, to: &str) -> Result<String> {
    // mdBook chapter paths are relative to the source directory.
    let parts = |s: &str| -> Result<Vec<String>> {
        Path::new(s)
            .components()
            .map(|c| match c {
                std::path::Component::Normal(p) => Ok(p.to_string_lossy().into_owned()),
                _ => bail!("chapter path must be relative and normalized: {s}"),
            })
            .collect()
    };
    let mut from = parts(from)?;
    from.pop();
    let mut to = parts(to)?;
    let file = to.last_mut().context("empty chapter path")?;
    *file = Path::new(file)
        .with_extension("html")
        .to_string_lossy()
        .into_owned();
    let common = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
    let path = std::iter::repeat_n("..".to_owned(), from.len() - common)
        .chain(to[common..].iter().cloned())
        .collect::<Vec<_>>()
        .join("/");
    Ok(path
        .replace('%', "%25")
        .replace(' ', "%20")
        .replace('#', "%23")
        .replace('?', "%3F"))
}
}
mdbook-dada/src/lib.rs:render_role
#![allow(unused)]
fn main() {
fn render_role(
    role: &Role,
    path: &str,
    anchors: &BTreeMap<String, String>,
    definition_label: &str,
) -> Result<String> {
    ensure!(
        !role.lean,
        "lean.type has been replaced: use ```{{grammar}} path:Name with authored LaTeX in the body"
    );
    let target = anchors
        .get(&role.id)
        .with_context(|| format!("unknown anchor `{}`", role.id))?;
    let fragment = format!("claim-{}", role.id);
    let href = if target == path {
        format!("#{fragment}")
    } else {
        format!("{}#{fragment}", relative_html(path, target)?)
    };
    let id_attr = if role.definition {
        format!(" id=\"{fragment}\"")
    } else {
        String::new()
    };
    let label = if role.definition {
        role.label.unwrap_or(definition_label)
    } else {
        "ref"
    };
    Ok(format!(
        "<a{id_attr} class=\"spec-shield\" href=\"{}\" aria-label=\"{label}: {}\"><span class=\"spec-shield-label\">{label}</span><span class=\"spec-shield-name\">{}</span></a>",
        escape(&href), escape(&role.id), escape(&role.id)
    ))
}
}
mdbook-dada/tests/book.rs:indexes_forward_references_and_nested_chapters
#![allow(unused)]
fn main() {
#[test]
fn indexes_forward_references_and_nested_chapters() {
    let mut book = json!({"sections":[chapter("intro.md","See {anchor-ref}`model.live`."),
        {"Chapter":{"path":"model/index.md","content":"{anchor}`model.live`\nLive objects.","sub_items":[chapter("model/details.md","See {anchor-ref}`model.live`.")]}}]});
    process(&mut book).unwrap();
    assert!(book["sections"][0]["Chapter"]["content"]
        .as_str()
        .unwrap()
        .contains("model/index.html#claim-model.live"));
    assert!(
        book["sections"][1]["Chapter"]["sub_items"][0]["Chapter"]["content"]
            .as_str()
            .unwrap()
            .contains("index.html#claim-model.live")
    );
}
}
mdbook-dada/tests/book.rs:cross_references_traverse_to_parent_and_bad_references_fail
#![allow(unused)]
fn main() {
#[test]
fn cross_references_traverse_to_parent_and_bad_references_fail() {
    let mut book = json!({"sections":[chapter("index.md","{anchor}`top`"),chapter("a/b.md","{anchor-ref}`top`")]});
    process(&mut book).unwrap();
    assert!(book.to_string().contains("../index.html#claim-top"));
    for entries in [
        vec![chapter("a.md", "{anchor-ref}`missing`")],
        vec![
            chapter("a.md", "{anchor}`x`"),
            chapter("b.md", "{anchor}`x`"),
        ],
        vec![chapter("a.md", "{anchor}`bad id`")],
    ] {
        assert!(process(&mut json!({"sections":entries})).is_err());
    }
}
}
mdbook-dada/tests/book.rs:literal_examples_are_not_anchors
#![allow(unused)]
fn main() {
#[test]
fn literal_examples_are_not_anchors() {
    let source="```text\n{anchor}`literal`\n```\n\n    {anchor}`indented`\n\n`{anchor}`literal\n\n\\{anchor}`escaped`\n\n<!-- {anchor}`comment` -->\n\n[{anchor}`linked`](https://example.com)\n";
    let mut book = json!({"sections":[chapter("a.md",source)]});
    process(&mut book).unwrap();
    assert_eq!(book["sections"][0]["Chapter"]["content"], source);
}
}
mdbook-dada/tests/book.rs:typed_anchor_roles_share_ids_and_references_without_implying_proofs
#![allow(unused)]
fn main() {
#[test]
fn typed_anchor_roles_share_ids_and_references_without_implying_proofs() {
    let mut book = json!({"items": [
        chapter("index.md", "{anchor}`navigation` See {anchor-ref}`state` and {anchor-ref}`slots`."),
        chapter("model/state.md", "{definition}`state` State components.\n\n{definition}`slots` Slots hold references."),
    ]});
    process(&mut book).unwrap();
    let intro = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(intro.contains("aria-label=\"anchor: navigation\""));
    assert!(intro.contains("model/state.html#claim-state"));
    assert!(intro.contains("model/state.html#claim-slots"));
    let body = book["items"][1]["Chapter"]["content"].as_str().unwrap();
    assert!(body.contains("aria-label=\"definition: state\""));
    assert!(body.contains("aria-label=\"definition: slots\""));
    assert!(!body.contains("lean-selector"));
    assert!(!body.contains("Theorem"));
    for first in ["anchor", "definition"] {
        for second in ["anchor", "definition"] {
            let mut duplicate = json!({"items": [
                chapter("a.md", &format!("{{{first}}}`same`")),
                chapter("b.md", &format!("{{{second}}}`same`")),
            ]});
            assert!(
                format!("{:#}", process(&mut duplicate).unwrap_err()).contains("duplicate anchor")
            );
        }
    }
    let literal = "```text\n{definition}`duplicate`\n{obligation}`duplicate`\n```\n\n{definition}``double``\n\n\\{obligation}`escaped`";
    let mut book = json!({"items": [chapter("literal.md", literal)]});
    process(&mut book).unwrap();
    assert_eq!(book["items"][0]["Chapter"]["content"], literal);
}
}

Inline roles label or refer to locations. Fenced directives create blocks: {definition}, {grammar}, {judgment}, {rule}, {theorem}, {lemma}, {example}, and {heap}. Ordinary language fences such as lean, heap, grammar, and text remain literal code.

A structured block starts with its kind and stable ID, followed by options and an authored body.

definitionmeta.syntax.draft :status: draft marks unfinished formalization without changing the kind. It permits omitted citations; supplied citations keep their kind checks. A draft without citations has no source selector.

The former {lean.type}, {lean.judgment}, {lean.rule}, and {obligation} forms are rejected with migration diagnostics. An {example} paragraph prefix is also rejected: examples use fenced blocks.

definitionmeta.syntax.informational A paragraph starting with {informational} and a space receives an inline Informational label. Its remaining text keeps normal Markdown formatting. The marker creates no identity and remains literal in code samples.

mdbook-dada/src/units.rs:parse_block
#![allow(unused)]
fn main() {
fn parse_block(
    source: &str,
    path: &str,
    range: Range<usize>,
    info: &str,
) -> Result<Option<SpecUnit>> {
    let (directive, argument) = info.split_once(char::is_whitespace).unwrap_or((info, ""));
    let Some(kind) = UnitKind::parse(directive) else {
        return Ok(None);
    };
    // Legacy directives carry path:declaration on their opening line. Keep their
    // interpretation, but never mistake them for reviewed structured units.
    if argument.contains(':') {
        ensure!(
            kind != UnitKind::FutureNote,
            "future notes cannot have formalization citations; use a stable unit ID"
        );
        return Ok(None);
    }
    let id = argument.trim();
    if kind.is_math() && id.is_empty() {
        bail!(
            "{directive} requires a stable unit ID, a :lean: citation, and an authored LaTeX body"
        );
    }
    ensure!(
        valid_id(id),
        "expected one stable unit ID after {directive}"
    );
    let raw = &source[range.clone()];
    let opening_end = raw
        .find('\n')
        .context("unit has no body or closing fence")?
        + 1;
    let closing_start = raw
        .trim_end_matches(['\n', '\r'])
        .rfind('\n')
        .context("unit has no closing fence")?
        + 1;
    let opening = raw[..opening_end].trim_start();
    let marker = opening
        .chars()
        .next()
        .context("unit has no opening fence")?;
    let width = opening.chars().take_while(|c| *c == marker).count();
    let closing = raw[closing_start..].trim();
    ensure!(
        matches!(marker, '`' | '~')
            && closing.chars().all(|c| c == marker)
            && closing.len() >= width,
        "structured unit must have an explicit matching closing fence"
    );
    let contents = &raw[opening_end..closing_start];
    let mut unit = SpecUnit {
        id: id.to_owned(),
        kind,
        draft: false,
        source_path: path.to_owned(),
        range,
        body: String::new(),
        raw: raw.to_owned(),
        lean: vec![],
        rust: vec![],
        tests: vec![],
        uses: vec![],
    };
    let mut seen = BTreeSet::new();
    let mut body_start = 0;
    for line in contents.split_inclusive('\n') {
        let line_text = line.trim_end_matches(['\n', '\r']);
        if !line_text.starts_with(':') {
            break;
        }
        let (option, value) = line_text[1..]
            .split_once(':')
            .context("unit option must have the form :name: value")?;
        ensure!(seen.insert(option), "duplicate :{option}: option");
        let values: Vec<_> = value.split_whitespace().map(str::to_owned).collect();
        ensure!(!values.is_empty(), ":{option}: must not be empty");
        if option == "status" {
            ensure!(
                values == ["draft"],
                ":status: only accepts `draft`; omit it for units ready for correspondence review"
            );
            unit.draft = true;
            body_start += line.len();
            continue;
        }
        let target = match option {
            "lean" => &mut unit.lean,
            "rust" => &mut unit.rust,
            "tests" => &mut unit.tests,
            "uses" => &mut unit.uses,
            _ => bail!("unknown unit option :{option}:"),
        };
        let unique: BTreeSet<_> = values.iter().collect();
        ensure!(
            unique.len() == values.len(),
            "duplicate value in :{option}:"
        );
        *target = values;
        body_start += line.len();
    }
    unit.body = contents[body_start..].trim_matches(['\n', '\r']).to_owned();
    // mdBook expands these even inside fenced code. The packet must contain
    // exactly the authored content, not untracked external substitutions.
    let includes = regex::Regex::new(r"\{\{\s*#(?:include|rustdoc_include|playground)\b")?;
    ensure!(
        !includes.is_match(&unit.raw),
        "mdBook include, rustdoc_include, and playground directives are unsupported inside structured units; write the content directly or cite another unit"
    );
    for event in Parser::new(&unit.body) {
        if let Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(info))) = event {
            let (directive, argument) = info.split_once(char::is_whitespace).unwrap_or((&info, ""));
            ensure!(
                UnitKind::parse(directive).is_none() || !argument.contains(':'),
                "legacy citation directives cannot nest inside structured units; create a separate unit with :lean: and refer to it with :uses:"
            );
        }
    }
    ensure!(
        !unit.body.trim().is_empty(),
        "unit requires an authored body"
    );
    ensure!(
        !unit.body.starts_with(':'),
        "unit options must immediately follow the opening fence, before the blank line and body"
    );
    if kind == UnitKind::FutureNote {
        ensure!(
            unit.lean.is_empty() && unit.rust.is_empty() && unit.tests.is_empty(),
            "future notes cannot have formalization citations (:lean:, :rust:, or :tests:); use a specification unit for formalized content"
        );
        ensure!(!unit.draft, "future notes cannot have :status: draft; they are exploratory notes, not unfinished specification units");
    }
    ensure!(
        kind == UnitKind::FutureNote || unit.draft || !unit.lean.is_empty() || !unit.rust.is_empty(),
        "unit requires :lean: or :rust: citations; use :status: draft while its formalization is pending"
    );
    ensure!(
        unit.tests.is_empty() || !unit.rust.is_empty(),
        ":tests: requires a :rust: implementation citation"
    );
    ensure!(
        unit.lean.is_empty() || unit.rust.is_empty(),
        "a unit cannot mix :lean: and :rust: citations"
    );
    ensure!(
        !matches!(kind, UnitKind::Theorem | UnitKind::Lemma)
            || !unit.lean.is_empty()
            || (unit.draft && unit.rust.is_empty()),
        "theorem and lemma units require a Lean theorem; Rust tests are not proofs"
    );
    ensure!(
        !matches!(
            kind,
            UnitKind::Judgment
                | UnitKind::Rule
                | UnitKind::Theorem
                | UnitKind::Lemma
                | UnitKind::Example
        ) || unit.lean.is_empty()
            || unit.lean.len() == 1,
        "{} requires exactly one Lean citation",
        kind.label()
    );
    for dependency in &unit.uses {
        ensure!(valid_id(dependency), "invalid dependency ID `{dependency}`");
        ensure!(dependency != id, "unit cannot depend on itself");
    }
    ensure!(
        parse(&unit.body, path)?.is_empty(),
        "named units cannot nest; cite the other unit with :uses: or a link"
    );
    Ok(Some(unit))
}
}
mdbook-dada/src/lib.rs:directive_blocks
#![allow(unused)]
fn main() {
fn directive_blocks(source: &str) -> Vec<DirectiveBlock> {
    let mut found = vec![];
    let mut block = None;
    for (event, range) in Parser::new(source).into_offset_iter() {
        match event {
            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(info)))
                if [
                    "{heap}",
                    "{grammar}",
                    "{judgment}",
                    "{rule}",
                    "{definition}",
                    "{theorem}",
                    "{lemma}",
                    "{example}",
                    "{future-note}",
                    // Recognized only so the shared validator can reject it.
                    "{obligation}",
                    "{lean.type}",
                    "{lean.judgment}",
                    "{lean.rule}",
                ]
                .iter()
                .any(|name| info.starts_with(name)) =>
            {
                block = Some(DirectiveBlock {
                    range,
                    info: info.into_string(),
                    body: String::new(),
                });
            }
            Event::Text(text) => {
                if let Some(block) = &mut block {
                    block.body.push_str(&text);
                }
            }
            Event::End(TagEnd::CodeBlock) => {
                if let Some(mut block) = block.take() {
                    block.range.end = range.end;
                    found.push(block);
                }
            }
            _ => {}
        }
    }
    found
}
}
mdbook-dada/src/lib.rs:render
#![allow(unused)]
fn main() {
fn render(
    source: &str,
    path: &str,
    anchors: &BTreeMap<String, String>,
    lean_root: Option<&Path>,
    project_root: Option<&Path>,
    scope: &str,
    definition_label: &str,
) -> Result<String> {
    let protected = protect_math(source);
    let source = protected.as_str();
    let structured_units = units::parse(source, path)?;
    let mut edits = vec![];
    for role in roles(source)? {
        let rendered = render_role(&role, path, anchors, definition_label)?;
        edits.push((role.range, rendered));
    }
    for (event, range) in Parser::new(source).into_offset_iter() {
        if matches!(event, Event::Start(Tag::Paragraph)) {
            ensure!(
                !source[range.clone()].starts_with("{example} "),
                "the paragraph {{example}} marker has been replaced: use a fenced ```{{example}} path:anchor with a Markdown body and a Lean test, or label an unfinished scenario as informational"
            );
            if source[range.clone()].starts_with("{informational} ") {
                edits.push((
                    range.start..range.start + "{informational}".len(),
                    "<span class=\"informational-label\">Informational</span>".to_owned(),
                ));
            }
        }
    }

    for block in directive_blocks(source) {
        if let Some(unit) = structured_units
            .iter()
            .find(|unit| unit.range.start == block.range.start)
        {
            for dependency in &unit.uses {
                ensure!(
                    anchors.contains_key(dependency),
                    "unknown unit dependency `{dependency}`"
                );
            }
            edits.push((
                block.range,
                render_unit(unit, path, anchors, lean_root, project_root)?,
            ));
            continue;
        }
        let start = block.range.start;
        let kind = block.info;
        let facts = block.body;
        let (directive, argument) = kind.split_once(char::is_whitespace).unwrap_or((&kind, ""));
        ensure!(
            ![
                "{heap}",
                "{grammar}",
                "{rule}",
                "{judgment}",
                "{definition}",
                "{theorem}",
                "{lemma}",
                "{example}",
                "{future-note}"
            ]
            .iter()
            .any(|name| directive.starts_with(name) && directive != *name),
            "separate the directive name and citation with whitespace"
        );
        ensure!(!matches!(directive, "{lean.type}" | "{lean.judgment}" | "{lean.rule}"),
                        "{directive} has been replaced: use ```{{grammar}} path:Name, ```{{judgment}} path:Name, or ```{{rule}} path:Name.case with authored LaTeX in the body");
        let id = format!("{scope}-{start}");
        if let Some(markdown) = MarkdownDirective::parse(directive) {
            let name = markdown.name();
            let label = markdown.label();
            let citations = argument.split_whitespace().count();
            if matches!(markdown, MarkdownDirective::Definition) {
                ensure!(
                    citations > 0,
                    "definition requires at least one opening-line citation"
                );
            } else {
                ensure!(
                    citations == 1,
                    "{name} requires exactly one opening-line citation"
                );
            }
            ensure!(!facts.trim().is_empty(), "{name} requires a Markdown body");
            let root =
                lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
            let lean_source = match markdown {
                MarkdownDirective::Definition => lean::definition_source(root, argument)?,
                MarkdownDirective::Example => lean::example_source(root, argument.trim())?,
                MarkdownDirective::Theorem | MarkdownDirective::Lemma => {
                    lean::theorem_source(root, argument.trim())?
                }
            };
            let heading_label = if matches!(markdown, MarkdownDirective::Example) {
                "example"
            } else {
                markdown.definition_label()
            };
            let (heading, body) = markdown_heading(&facts, path, anchors, heading_label)?;
            ensure!(
                !body.trim().is_empty(),
                "{name} requires a Markdown body after its heading anchors"
            );
            let body = render(
                body,
                path,
                anchors,
                lean_root,
                project_root,
                &id,
                markdown.definition_label(),
            )?;
            let selector = selector_header(
                label,
                (!heading.is_empty()).then_some(heading.as_str()),
                &format!("{name}-{id}"),
                "rendered",
                "Lean",
            );
            // Blank lines terminate raw HTML blocks so mdBook renders the body
            // as Markdown, including its explicit math delimiters and proof prose.
            edits.push((block.range, format!(
                "\n<figure class=\"lean-declaration lean-group lean-markdown lean-{name}\">{selector}<div class=\"lean-markdown-body\">\n\n{}\n\n</div><div class=\"lean-source\">{lean_source}</div></figure>\n\n",
                body.trim_matches('\n')
            )));
            continue;
        }
        let view = match directive {
            "{grammar}" => Some(lean::View::Grammar),
            "{judgment}" => Some(lean::View::Judgment),
            "{rule}" => Some(lean::View::Rule),
            _ => None,
        };
        if let Some(view) = view {
            let root =
                lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
            edits.push((
                block.range,
                format!(
                    "\n{}\n",
                    lean::render_authored(root, argument.trim(), &facts, view, &id)?
                ),
            ));
            continue;
        }
        ensure!(
            argument.trim().is_empty(),
            "{directive} does not accept opening-line arguments"
        );
        let graph = graph::render(&facts)?;
        let selector = selector_header("Diagram", None, &format!("heap-{id}"), "rendered", "Facts");
        let source = escape(&facts).replace('\n', "&#10;");
        edits.push((block.range, format!("\n<figure class=\"heap-figure\">{selector}{graph}<pre class=\"heap-facts\"><code>{source}</code></pre></figure>\n")));
    }
    edits.sort_by_key(|(range, _)| range.start);
    let mut result = String::new();
    let mut end = 0;
    for (range, replacement) in edits {
        ensure!(range.start >= end, "overlapping markup");
        result.push_str(&source[end..range.start]);
        result.push_str(&replacement);
        end = range.end;
    }
    result.push_str(&source[end..]);
    Ok(result)
}
}
mdbook-dada/tests/book.rs:block_directives_are_distinct_from_literal_code_and_inline_roles
#![allow(unused)]
fn main() {
#[test]
fn block_directives_are_distinct_from_literal_code_and_inline_roles() {
    let literal =
        "```heap\nnot facts\n```\n\n```grammar\nnot grammar\n```\n\n```lean\nnot lean\n```\n\n```text\n{lean.type}`Missing:Place`\n```";
    let mut book = json!({"items": [chapter("a.md", literal)]});
    process(&mut book).unwrap();
    assert_eq!(book["items"][0]["Chapter"]["content"], literal);
    let mut old = json!({"items": [chapter("a.md", "{lean.type}`Renderer:Place`")]});
    let error = process(&mut old).unwrap_err();
    assert!(format!("{error:#}").contains("lean.type"));
}
}
mdbook-dada/tests/book.rs:informational_paragraphs_preserve_markdown_and_literal_examples
#![allow(unused)]
fn main() {
#[test]
fn informational_paragraphs_preserve_markdown_and_literal_examples() {
    let source = "{informational} Rationale with [a link](state.md) and *emphasis*.\n\n```text\n{informational} Literal.\n```";
    let mut book = json!({"items": [chapter("a.md", source)]});
    process(&mut book).unwrap();
    let output = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(output.contains("<span class=\"informational-label\">Informational</span> Rationale"));
    assert!(output.contains("[a link](state.md) and *emphasis*"));
    assert!(output.contains("{informational} Literal."));
}
}
mdbook-dada/tests/book.rs:generated_grammar_directives_require_migration
#![allow(unused)]
fn main() {
#[test]
fn generated_grammar_directives_require_migration() {
    let root = lean_fixtures();
    for source in [
        "```{lean.type}\nRenderer:Place\n```",
        "```{grammar}\nSlot = Empty | Ref(target: Id);\n```",
    ] {
        let mut book = json!({"items": [chapter("state.md", source)]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).expect_err(source);
        let message = format!("{error:#}");
        assert!(message.contains("state.md"));
        assert!(message.contains("grammar"), "{source}: {message}");
        assert!(message.contains("authored LaTeX"), "{source}: {message}");
    }
}
}
mdbook-dada/tests/book.rs:inferred_judgment_and_rule_directives_require_migration
#![allow(unused)]
fn main() {
#[test]
fn inferred_judgment_and_rule_directives_require_migration() {
    let root = lean_fixtures();
    for (kind, target) in [
        ("judgment", "Renderer:Step"),
        ("rule", "Renderer:Step.allocVariable"),
    ] {
        let source = format!("```{{lean.{kind}}}\n{target}\n```");
        let mut book = json!({"items": [chapter("ops.md", &source)]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains(&format!("lean.{kind}")));
        assert!(message.contains(&format!("{{{kind}}}")));
        assert!(message.contains("ops.md"));
    }
}
}
mdbook-dada/tests/units.rs:drafts_keep_their_semantic_kind_without_claiming_a_formalization
#![allow(unused)]
fn main() {
#[test]
fn drafts_keep_their_semantic_kind_without_claiming_a_formalization() {
    let files = Sources::new();
    for kind in [
        "definition",
        "grammar",
        "judgment",
        "rule",
        "theorem",
        "lemma",
        "example",
    ] {
        let source = format!("```{{{kind}}} model.draft\n:status: draft\n\nProposed content.\n```");
        let parsed = units::parse(&source, "model.md").unwrap();
        assert!(parsed[0].draft);
        assert_eq!(
            parsed[0].kind,
            UnitKind::parse(&format!("{{{kind}}}")).unwrap()
        );
        let output = render(&source, &files.lean()).unwrap();
        assert!(output.contains(&format!("{kind}: model.draft")));
        assert!(output.contains("class=\"block-label unit-status\""));
        assert!(output.contains(">Draft</span>"));
        assert!(!output.contains("proof obligation"));
        assert!(!output.contains("type=\"radio\""));
        assert!(!output.contains(":status:"));
        assert!(units::parse(&source.replace(":status: draft\n", ""), "model.md").is_err());
    }

    let current = render(
        "```{definition} model.current\n:lean: Model:initial\n\nCurrent definition.\n```",
        &files.lean(),
    )
    .unwrap();
    assert!(!current.contains("unit-status"));
    assert!(current.contains("value=\"lean\""));
}
}
mdbook-dada/tests/units.rs:draft_status_is_explicit_and_does_not_relax_citation_checks
#![allow(unused)]
fn main() {
#[test]
fn draft_status_is_explicit_and_does_not_relax_citation_checks() {
    let files = Sources::new();
    for options in [
        ":status:",
        ":status: checked",
        ":status: draft checked",
        ":status: draft\n:status: draft",
    ] {
        let source = format!("```{{definition}} invalid.status\n{options}\n\nText.\n```");
        let error = format!("{:#}", units::parse(&source, "model.md").unwrap_err());
        assert!(error.contains("model.md:1"), "{error}");
    }
    for (kind, citation) in [
        ("definition", ":lean: Model:missing"),
        ("definition", ":lean: Model:initial_is_empty"),
        ("theorem", ":lean: Model:initial"),
        ("theorem", ":rust: tool.rs:check"),
        ("example", ":lean: Model:initial_is_empty"),
    ] {
        let source =
            format!("```{{{kind}}} invalid.citation\n:status: draft\n{citation}\n\nText.\n```");
        assert!(render(&source, &files.lean()).is_err(), "{source}");
    }
    let output = render(
        "```{definition} model.draft\n:status: draft\n:lean: Model:initial\n\nProposed explanation.\n```",
        &files.lean(),
    )
    .unwrap();
    assert!(output.contains("value=\"lean\""));
    assert!(output.contains(">Draft</span>"));
}
}
mdbook-dada/tests/units.rs:removed_obligation_syntax_is_rejected_at_every_authoring_entry_point
#![allow(unused)]
fn main() {
#[test]
fn removed_obligation_syntax_is_rejected_at_every_authoring_entry_point() {
    let files = Sources::new();
    assert!(UnitKind::parse("{obligation}").is_none());
    assert!(serde_json::from_str::<UnitKind>("\"obligation\"").is_err());
    for source in [
        "```{obligation} model.pending\nUnfinished.\n```",
        "```{obligation} Model:initial\nUnfinished.\n```",
        "```{obligation}pending\nvars = variables()\nvars.x = uninitialized()\n```",
        "{obligation}`pending` Unfinished.",
        "> ```{obligation} pending\n> Unfinished.\n> ```",
        "- ```{obligation} pending\n  Unfinished.\n  ```",
        "```{definition} Model:initial\n{obligation}`pending` Unfinished.\n```",
        "````{definition} model.draft\n:status: draft\n\n```{obligation} pending\nUnfinished.\n```\n````",
    ] {
        let error = format!("{:#}", units::parse(source, "model.md").unwrap_err());
        assert!(error.contains("model.md"), "{error}");
        assert!(error.contains("{obligation} has been removed"), "{error}");
        assert!(error.contains(":status: draft"), "{error}");
        assert!(render(source, &files.lean()).is_err(), "{source}");
    }
}
}

A block’s header keeps its identity on the left and its view controls on the right. Rendered is selected initially. Lean-backed blocks offer Rendered/Lean; Rust-backed blocks offer Rendered/Rust; diagrams offer Rendered/Facts. Each selector controls its own block, including when blocks are nested.

A structured unit’s ID appears once, as a shield in its header. Draft status remains visible in both views. In legacy Markdown blocks, leading defining anchors move to the header; later anchors stay in the body. An unanchored legacy block shows its kind as a plain label. The source view identifies every citation and shows its selected text.

The selector supports comparison. It does not judge correspondence or check a proof. Header arrangement and visibility use the checked-in CSS; the cited asset test checks those rules without executing a browser.

mdbook-dada/src/lib.rs:selector_header
#![allow(unused)]
fn main() {
/// Shared header for every rendered/source pair. The heading is generated HTML;
/// labels, group names, and radio values are escaped here.
pub(crate) fn selector_header(
    label: &str,
    heading: Option<&str>,
    group: &str,
    rendered_value: &str,
    alternate: &str,
) -> String {
    let label = escape(label);
    let fallback = format!("<span class=\"block-label\">{label}</span>");
    let heading = heading.unwrap_or(&fallback);
    let group = escape(group);
    let rendered_value = escape(rendered_value);
    let alternate_value = escape(&alternate.to_ascii_lowercase());
    let alternate = escape(alternate);
    format!("<div class=\"lean-selector\" role=\"group\" aria-label=\"{label} view\"><div class=\"block-heading\">{heading}</div><div class=\"view-options\"><label><input type=\"radio\" name=\"{group}\" value=\"{rendered_value}\" checked> Rendered</label><label><input type=\"radio\" name=\"{group}\" value=\"{alternate_value}\"> {alternate}</label></div></div>")
}
}
mdbook-dada/src/lib.rs:markdown_heading
#![allow(unused)]
fn main() {
fn markdown_heading<'a>(
    source: &'a str,
    path: &str,
    anchors: &BTreeMap<String, String>,
    definition_label: &str,
) -> Result<(String, &'a str)> {
    let protected = protect_math(source);
    let mut heading = Vec::new();
    let mut end = 0;
    for role in roles(&protected)? {
        if !protected[end..role.range.start].trim().is_empty() || !role.definition {
            break;
        }
        heading.push(render_role(&role, path, anchors, definition_label)?);
        // A promoted role is preceded only by whitespace and other roles, so
        // math protection has not changed its source offsets.
        end = role.range.end;
    }
    Ok((heading.join(" "), &source[end..]))
}
}
mdbook-dada/src/lib.rs:render_unit
#![allow(unused)]
fn main() {
fn render_unit(
    unit: &units::SpecUnit,
    path: &str,
    anchors: &BTreeMap<String, String>,
    lean_root: Option<&Path>,
    project_root: Option<&Path>,
) -> Result<String> {
    let label = unit.kind.label();
    let lower_label = label.to_ascii_lowercase();
    let role = Role {
        range: unit.range.clone(),
        id: unit.id.clone(),
        definition: true,
        label: None,
        lean: false,
    };
    let mut heading = render_role(&role, path, anchors, &lower_label)?;
    if unit.draft {
        heading.push_str(" <span class=\"block-label unit-status\" title=\"Formalization and correspondence review pending\">Draft</span>");
    }
    let (alternate, cited_source) = if !unit.lean.is_empty() {
        let root = lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
        ("Lean", lean::selected_source(root, &unit.lean, unit.kind)?)
    } else if !unit.rust.is_empty() {
        let root = project_root.context("Rust citations require a configured project root")?;
        let mut cited = String::new();
        for target in unit.rust.iter().chain(&unit.tests) {
            let selected = crate::rust_source::select(root, target)?;
            cited.push_str(&format!(
                "<figcaption>{}</figcaption><pre><code class=\"language-rust\">{}</code></pre>",
                escape(target),
                escape(&selected.selected).replace('\n', "&#10;")
            ));
        }
        ("Rust", cited)
    } else {
        ("", String::new())
    };
    let header = if alternate.is_empty() {
        format!("<div class=\"lean-selector\"><div class=\"block-heading\">{heading}</div></div>")
    } else {
        selector_header(
            label,
            Some(&heading),
            &format!("unit-{}", unit.id),
            "rendered",
            alternate,
        )
    };
    let body = if unit.kind.is_math() {
        let tex = escape(unit.body.trim()).replace('\n', "&#10;");
        format!("<div class=\"lean-grammar\"><div class=\"math-display\">\\[{tex}\\]</div></div>")
    } else {
        let body = render(
            &unit.body,
            path,
            anchors,
            lean_root,
            project_root,
            &unit.id,
            &lower_label,
        )?;
        format!(
            "<div class=\"lean-markdown-body\">\n\n{}\n\n</div>",
            body.trim_matches('\n')
        )
    };
    let markdown_class = if unit.kind.is_math() {
        ""
    } else {
        " lean-markdown"
    };
    Ok(format!("\n<figure class=\"lean-declaration lean-group{markdown_class}\">{header}{body}<div class=\"lean-source\">{cited_source}</div></figure>\n\n"))
}
}
mdbook-dada/src/lib.rs:render
#![allow(unused)]
fn main() {
fn render(
    source: &str,
    path: &str,
    anchors: &BTreeMap<String, String>,
    lean_root: Option<&Path>,
    project_root: Option<&Path>,
    scope: &str,
    definition_label: &str,
) -> Result<String> {
    let protected = protect_math(source);
    let source = protected.as_str();
    let structured_units = units::parse(source, path)?;
    let mut edits = vec![];
    for role in roles(source)? {
        let rendered = render_role(&role, path, anchors, definition_label)?;
        edits.push((role.range, rendered));
    }
    for (event, range) in Parser::new(source).into_offset_iter() {
        if matches!(event, Event::Start(Tag::Paragraph)) {
            ensure!(
                !source[range.clone()].starts_with("{example} "),
                "the paragraph {{example}} marker has been replaced: use a fenced ```{{example}} path:anchor with a Markdown body and a Lean test, or label an unfinished scenario as informational"
            );
            if source[range.clone()].starts_with("{informational} ") {
                edits.push((
                    range.start..range.start + "{informational}".len(),
                    "<span class=\"informational-label\">Informational</span>".to_owned(),
                ));
            }
        }
    }

    for block in directive_blocks(source) {
        if let Some(unit) = structured_units
            .iter()
            .find(|unit| unit.range.start == block.range.start)
        {
            for dependency in &unit.uses {
                ensure!(
                    anchors.contains_key(dependency),
                    "unknown unit dependency `{dependency}`"
                );
            }
            edits.push((
                block.range,
                render_unit(unit, path, anchors, lean_root, project_root)?,
            ));
            continue;
        }
        let start = block.range.start;
        let kind = block.info;
        let facts = block.body;
        let (directive, argument) = kind.split_once(char::is_whitespace).unwrap_or((&kind, ""));
        ensure!(
            ![
                "{heap}",
                "{grammar}",
                "{rule}",
                "{judgment}",
                "{definition}",
                "{theorem}",
                "{lemma}",
                "{example}",
                "{future-note}"
            ]
            .iter()
            .any(|name| directive.starts_with(name) && directive != *name),
            "separate the directive name and citation with whitespace"
        );
        ensure!(!matches!(directive, "{lean.type}" | "{lean.judgment}" | "{lean.rule}"),
                        "{directive} has been replaced: use ```{{grammar}} path:Name, ```{{judgment}} path:Name, or ```{{rule}} path:Name.case with authored LaTeX in the body");
        let id = format!("{scope}-{start}");
        if let Some(markdown) = MarkdownDirective::parse(directive) {
            let name = markdown.name();
            let label = markdown.label();
            let citations = argument.split_whitespace().count();
            if matches!(markdown, MarkdownDirective::Definition) {
                ensure!(
                    citations > 0,
                    "definition requires at least one opening-line citation"
                );
            } else {
                ensure!(
                    citations == 1,
                    "{name} requires exactly one opening-line citation"
                );
            }
            ensure!(!facts.trim().is_empty(), "{name} requires a Markdown body");
            let root =
                lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
            let lean_source = match markdown {
                MarkdownDirective::Definition => lean::definition_source(root, argument)?,
                MarkdownDirective::Example => lean::example_source(root, argument.trim())?,
                MarkdownDirective::Theorem | MarkdownDirective::Lemma => {
                    lean::theorem_source(root, argument.trim())?
                }
            };
            let heading_label = if matches!(markdown, MarkdownDirective::Example) {
                "example"
            } else {
                markdown.definition_label()
            };
            let (heading, body) = markdown_heading(&facts, path, anchors, heading_label)?;
            ensure!(
                !body.trim().is_empty(),
                "{name} requires a Markdown body after its heading anchors"
            );
            let body = render(
                body,
                path,
                anchors,
                lean_root,
                project_root,
                &id,
                markdown.definition_label(),
            )?;
            let selector = selector_header(
                label,
                (!heading.is_empty()).then_some(heading.as_str()),
                &format!("{name}-{id}"),
                "rendered",
                "Lean",
            );
            // Blank lines terminate raw HTML blocks so mdBook renders the body
            // as Markdown, including its explicit math delimiters and proof prose.
            edits.push((block.range, format!(
                "\n<figure class=\"lean-declaration lean-group lean-markdown lean-{name}\">{selector}<div class=\"lean-markdown-body\">\n\n{}\n\n</div><div class=\"lean-source\">{lean_source}</div></figure>\n\n",
                body.trim_matches('\n')
            )));
            continue;
        }
        let view = match directive {
            "{grammar}" => Some(lean::View::Grammar),
            "{judgment}" => Some(lean::View::Judgment),
            "{rule}" => Some(lean::View::Rule),
            _ => None,
        };
        if let Some(view) = view {
            let root =
                lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
            edits.push((
                block.range,
                format!(
                    "\n{}\n",
                    lean::render_authored(root, argument.trim(), &facts, view, &id)?
                ),
            ));
            continue;
        }
        ensure!(
            argument.trim().is_empty(),
            "{directive} does not accept opening-line arguments"
        );
        let graph = graph::render(&facts)?;
        let selector = selector_header("Diagram", None, &format!("heap-{id}"), "rendered", "Facts");
        let source = escape(&facts).replace('\n', "&#10;");
        edits.push((block.range, format!("\n<figure class=\"heap-figure\">{selector}{graph}<pre class=\"heap-facts\"><code>{source}</code></pre></figure>\n")));
    }
    edits.sort_by_key(|(range, _)| range.start);
    let mut result = String::new();
    let mut end = 0;
    for (range, replacement) in edits {
        ensure!(range.start >= end, "overlapping markup");
        result.push_str(&source[end..range.start]);
        result.push_str(&replacement);
        end = range.end;
    }
    result.push_str(&source[end..]);
    Ok(result)
}
}
mdbook-dada/tests/book.rs:leading_declaration_shields_move_to_headers_without_losing_ids_or_body_markup
#![allow(unused)]
fn main() {
#[test]
fn leading_declaration_shields_move_to_headers_without_losing_ids_or_body_markup() {
    use pulldown_cmark::{Event, Parser, Tag};

    let root = lean_fixtures();
    for (kind, citation) in [
        ("definition", "Renderer:readSlot"),
        ("theorem", "Renderer:deallocVariable_requires_top"),
        ("lemma", "Renderer:deallocVariable_requires_top"),
        ("example", "Renderer:integer_primitive"),
    ] {
        let source = format!(
            "```{{{kind}}} {citation}\n\n {{anchor}}`lookup`\n{{definition}}`second` **Statement.** See {{anchor-ref}}`lookup`.\n\n\\\\[S(p)=s\\\\]\n\n{{anchor}}`later` Details.\n```"
        );
        let mut book = json!({"items": [
            chapter("intro.md", "See {anchor-ref}`lookup`."),
            chapter("model/state.md", &source)
        ]});
        mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
        let output = book["items"][1]["Chapter"]["content"].as_str().unwrap();
        let (header, body) = output
            .split_once("<div class=\"lean-markdown-body\">")
            .unwrap();
        assert!(header.contains("<div class=\"block-heading\"><a id=\"claim-lookup\""));
        assert!(header.contains("id=\"claim-second\""));
        assert!(header.contains(&format!("aria-label=\"{kind}: lookup\"")));
        assert!(header.contains("class=\"view-options\""));
        assert!(!header.contains("class=\"block-label\""));
        assert_eq!(output.matches("id=\"claim-lookup\"").count(), 1);
        assert_eq!(output.matches("id=\"claim-second\"").count(), 1);
        assert!(body.contains("id=\"claim-later\""));
        assert!(body.contains("href=\"#claim-lookup\""));
        assert!(body.contains("<div class=\"math-display\">\\[S(p)=s\\]</div>"));
        assert!(Parser::new(output).any(|event| matches!(event, Event::Start(Tag::Strong))));
        assert!(book["items"][0]["Chapter"]["content"]
            .as_str()
            .unwrap()
            .contains("model/state.html#claim-lookup"));
    }
}
}
mdbook-dada/tests/book.rs:nonheading_roles_and_nested_diagrams_stay_in_the_markdown_body
#![allow(unused)]
fn main() {
#[test]
fn nonheading_roles_and_nested_diagrams_stay_in_the_markdown_body() {
    let root = lean_fixtures();
    for prefix in [
        "Opening prose.\n\n{anchor}`body`",
        "{anchor-ref}`outside`\n\n{anchor}`body`",
        "`{anchor}`literal\n\n{anchor}`body`",
        "<!-- Heading comment. -->\n\n{anchor}`body`",
    ] {
        let source = format!(
            "{{anchor}}`outside`\n\n````{{definition}} Renderer:readSlot\n{prefix} Statement.\n\n```{{heap}}\nvars = variables()\nvars.x = uninitialized()\n```\n````"
        );
        let mut book = json!({"items": [chapter("state.md", &source)]});
        mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
        let output = book["items"][0]["Chapter"]["content"].as_str().unwrap();
        let (header, body) = output
            .split_once("<div class=\"lean-markdown-body\">")
            .unwrap();
        assert!(header.contains("<span class=\"block-label\">Definition</span>"));
        assert!(!header.contains("id=\"claim-body\""));
        assert!(body.contains("id=\"claim-body\""));
        assert!(body.contains("<span class=\"block-label\">Diagram</span>"));
        assert!(body.contains("<svg"));
        assert_eq!(output.matches("class=\"view-options\"").count(), 2);
    }
}
}
mdbook-dada/tests/book.rs:unanchored_rendered_blocks_share_named_headers_and_grouped_choices
#![allow(unused)]
fn main() {
#[test]
fn unanchored_rendered_blocks_share_named_headers_and_grouped_choices() {
    let root = lean_fixtures();
    let radio_names = regex::Regex::new(r#"type="radio" name="([^"]+)""#).unwrap();
    for (kind, label, citation, body, alternate) in [
        (
            "definition",
            "Definition",
            "Renderer:readSlot",
            "Statement.",
            "Lean",
        ),
        (
            "theorem",
            "Theorem",
            "Renderer:deallocVariable_requires_top",
            "Statement.",
            "Lean",
        ),
        (
            "lemma",
            "Lemma",
            "Renderer:deallocVariable_requires_top",
            "Statement.",
            "Lean",
        ),
        (
            "example",
            "Example",
            "Renderer:integer_primitive",
            "Statement.",
            "Lean",
        ),
        ("grammar", "Grammar", "Renderer:Slot", "s ::= r", "Lean"),
        ("judgment", "Judgment", "Renderer:Step", "S \\to S'", "Lean"),
        ("rule", "Rule", "Renderer:Step.allocVariable", "P", "Lean"),
        ("heap", "Diagram", "", "vars = variables()", "Facts"),
    ] {
        let source = format!("```{{{kind}}} {citation}\n{body}\n```");
        let mut book = json!({"items": [chapter("state.md", &source)]});
        mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
        let output = book["items"][0]["Chapter"]["content"].as_str().unwrap();
        assert!(output.contains(&format!("aria-label=\"{label} view\"")));
        assert!(output.contains(&format!("<div class=\"block-heading\"><span class=\"block-label\">{label}</span></div><div class=\"view-options\">")));
        assert_eq!(output.matches("> Rendered</label>").count(), 1);
        assert_eq!(output.matches(&format!("> {alternate}</label>")).count(), 1);
        let names: Vec<_> = radio_names
            .captures_iter(output)
            .map(|capture| capture[1].to_owned())
            .collect();
        assert_eq!(names.len(), 2);
        assert_eq!(names[0], names[1]);
    }
}
}
mdbook-dada/tests/units.rs:structured_units_render_identified_headers_and_exact_lean_views
#![allow(unused)]
fn main() {
#[test]
fn structured_units_render_identified_headers_and_exact_lean_views() {
    let files = Sources::new();
    for (kind, citation, body, expected) in [
        (
            "definition",
            "Model:initial",
            "The initial object is empty.",
            "def initial",
        ),
        (
            "grammar",
            "Model:Thing",
            "t ::= \\mathsf{empty}",
            "inductive Thing",
        ),
        ("judgment", "Model:Step", "t \\to t'", "inductive Step"),
        ("rule", "Model:Step.same", "\\frac{}{t \\to t}", "| same"),
        (
            "theorem",
            "Model:initial_is_empty",
            "The initial object is empty.",
            "theorem initial_is_empty",
        ),
        (
            "lemma",
            "Model:initial_is_empty",
            "The initial object is empty.",
            "theorem initial_is_empty",
        ),
        (
            "example",
            "Model:basic",
            "The initial object is empty.",
            "example : initial",
        ),
    ] {
        let source = format!("```{{{kind}}} model.unit\n:lean: {citation}\n\n{body}\n```\n\nSee {{anchor-ref}}`model.unit`.");
        let output = render(&source, &files.lean()).unwrap();
        assert_eq!(output.matches("id=\"claim-model.unit\"").count(), 1);
        assert!(output.contains("href=\"#claim-model.unit\""));
        assert!(output.contains("class=\"view-options\""));
        assert!(output.contains("value=\"lean\""));
        assert!(!output.contains(":lean:"));
        let selected = lean::select(
            &files.lean(),
            citation,
            UnitKind::parse(&format!("{{{kind}}}")).unwrap(),
        )
        .unwrap();
        assert!(
            selected.selected.contains(expected),
            "{}",
            selected.selected
        );
        assert!(selected.source.contains("theorem initial_is_empty"));
        assert!(selected.path.is_absolute());
    }
}
}
mdbook-dada/tests/units.rs:meta_units_show_named_rust_implementation_and_test
#![allow(unused)]
fn main() {
#[test]
fn meta_units_show_named_rust_implementation_and_test() {
    let files = Sources::new();
    let output = render("```{definition} meta.check\n:rust: tool.rs:check\n:tests: tool.rs:checks\n\nThe checker accepts this input.\n```", &files.lean()).unwrap();
    assert!(output.contains("value=\"rust\""));
    assert!(output.contains("pub fn check()"));
    assert!(output.contains("fn checks()"));
    assert!(!output.contains(":rust:"));
}
}
mdbook-dada/tests/renderer_contracts.rs:view_styles_keep_headers_and_nested_choices_independent
#![allow(unused)]
fn main() {
#[test]
fn view_styles_keep_headers_and_nested_choices_independent() {
    let css = read_asset("theme/dada.css");
    let options = css
        .split_once(".lean-selector .view-options {")
        .unwrap()
        .1
        .split_once('}')
        .unwrap()
        .0;
    assert!(options.contains("margin-left:auto"));
    // A nested diagram's radio button must not switch its enclosing Lean block.
    // The selector reaches the block's own header, then changes only its children.
    for pane in [".lean-source", ".lean-grammar", ".lean-markdown-body"] {
        assert!(css.contains(&format!(
            ".lean-group:has(> .lean-selector input:is([value=\"lean\"], [value=\"rust\"]):checked) > {pane}"
        )));
    }
    assert!(css.contains(
        ".heap-figure:has(input[value=\"facts\"]:checked) .heap-facts { display:block; }"
    ));
    assert!(css.contains(
        ".heap-figure:has(input[value=\"facts\"]:checked) .heap-diagram { display:none; }"
    ));
    for selector in [".lean-grammar", ".lean-source pre", ".heap-figure"] {
        let declaration = css
            .split_once(&format!("{selector} {{"))
            .unwrap()
            .1
            .split_once('}')
            .unwrap()
            .0;
        assert!(declaration.contains("overflow-x:auto"), "{selector}");
    }

    let mut book = json!({"items": [{"Chapter": {
        "path": "local.md", "content": "{anchor}`local.identity`\n\n{anchor-ref}`local.identity`", "sub_items": []
    }}]});
    process(&mut book).unwrap();
    let rendered = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert_eq!(rendered.matches("class=\"spec-shield\"").count(), 2);
    assert!(rendered.contains("href=\"#claim-local.identity\""));
    assert!(!rendered.contains("<img"));
    assert!(!rendered.contains("src="));
    assert!(
        !css.contains("url("),
        "shield styling must not fetch a remote badge"
    );
}
}

Authored mathematics

The renderer preserves authored mathematics. Grammar, judgment, and rule bodies are raw LaTeX; the renderer supplies display delimiters and does not interpret Markdown within them. Definition, theorem, lemma, and example bodies are Markdown and use explicit \\[ / \\] or \\( / \\) delimiters.

The preprocessor protects explicit math from Markdown escaping and smart punctuation, retaining TeX row breaks, primes, braces, and underscores. Code, links, and HTML literal contexts are excluded. Both mathematical text and source selections are escaped for HTML. MathJax typesets the result in the browser; the renderer does not translate Lean into mathematics or validate LaTeX as Lean.

definitionmeta.syntax.grammar.rendering A grammar’s ordered citations share one Rendered/Lean selector. Judgment and rule blocks use the same presentation, with their own authored notation.

mdbook-dada/src/lib.rs:protect_math
#![allow(unused)]
fn main() {
fn protect_math(source: &str) -> String {
    let literal: Vec<_> = Parser::new(source)
        .into_offset_iter()
        .filter_map(|(event, range)| match event {
            Event::Start(
                Tag::CodeBlock(_) | Tag::HtmlBlock | Tag::Link { .. } | Tag::Image { .. },
            )
            | Event::Code(_)
            | Event::Html(_)
            | Event::InlineHtml(_) => Some(range),
            _ => None,
        })
        .collect();
    let mut output = String::new();
    let mut end = 0;
    for (start, _) in source.match_indices(r"\\") {
        if start < end
            || source[..start].ends_with('\\')
            || literal.iter().any(|range| range.contains(&start))
        {
            continue;
        }
        let (display, closing) = match source.as_bytes().get(start + 2) {
            Some(b'[') => (true, r"\\]"),
            Some(b'(') => (false, r"\\)"),
            _ => continue,
        };
        let body_start = start + 3;
        let Some(close) = source[body_start..].find(closing).map(|i| body_start + i) else {
            continue;
        };
        if literal.iter().any(|range| range.contains(&close)) {
            continue;
        }
        let body = &source[body_start..close];
        output.push_str(&source[end..start]);
        if display {
            let tex = escape(body).replace('\n', "&#10;");
            output.push_str(&format!(
                "\n\n<div class=\"math-display\">\\[{tex}\\]</div>\n\n"
            ));
        } else {
            // Inline HTML does not suppress Markdown parsing of its contents.
            // Entities keep every TeX punctuation character out of that parser.
            let tex: String = format!("\\({body}\\)")
                .chars()
                .map(|c| {
                    if c.is_alphanumeric() || c == ' ' {
                        c.to_string()
                    } else {
                        format!("&#{};", u32::from(c))
                    }
                })
                .collect();
            output.push_str(&format!("<span class=\"math-inline\">{tex}</span>"));
        }
        end = close + closing.len();
    }
    output.push_str(&source[end..]);
    output
}
}
mdbook-dada/src/lib.rs:render_unit
#![allow(unused)]
fn main() {
fn render_unit(
    unit: &units::SpecUnit,
    path: &str,
    anchors: &BTreeMap<String, String>,
    lean_root: Option<&Path>,
    project_root: Option<&Path>,
) -> Result<String> {
    let label = unit.kind.label();
    let lower_label = label.to_ascii_lowercase();
    let role = Role {
        range: unit.range.clone(),
        id: unit.id.clone(),
        definition: true,
        label: None,
        lean: false,
    };
    let mut heading = render_role(&role, path, anchors, &lower_label)?;
    if unit.draft {
        heading.push_str(" <span class=\"block-label unit-status\" title=\"Formalization and correspondence review pending\">Draft</span>");
    }
    let (alternate, cited_source) = if !unit.lean.is_empty() {
        let root = lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
        ("Lean", lean::selected_source(root, &unit.lean, unit.kind)?)
    } else if !unit.rust.is_empty() {
        let root = project_root.context("Rust citations require a configured project root")?;
        let mut cited = String::new();
        for target in unit.rust.iter().chain(&unit.tests) {
            let selected = crate::rust_source::select(root, target)?;
            cited.push_str(&format!(
                "<figcaption>{}</figcaption><pre><code class=\"language-rust\">{}</code></pre>",
                escape(target),
                escape(&selected.selected).replace('\n', "&#10;")
            ));
        }
        ("Rust", cited)
    } else {
        ("", String::new())
    };
    let header = if alternate.is_empty() {
        format!("<div class=\"lean-selector\"><div class=\"block-heading\">{heading}</div></div>")
    } else {
        selector_header(
            label,
            Some(&heading),
            &format!("unit-{}", unit.id),
            "rendered",
            alternate,
        )
    };
    let body = if unit.kind.is_math() {
        let tex = escape(unit.body.trim()).replace('\n', "&#10;");
        format!("<div class=\"lean-grammar\"><div class=\"math-display\">\\[{tex}\\]</div></div>")
    } else {
        let body = render(
            &unit.body,
            path,
            anchors,
            lean_root,
            project_root,
            &unit.id,
            &lower_label,
        )?;
        format!(
            "<div class=\"lean-markdown-body\">\n\n{}\n\n</div>",
            body.trim_matches('\n')
        )
    };
    let markdown_class = if unit.kind.is_math() {
        ""
    } else {
        " lean-markdown"
    };
    Ok(format!("\n<figure class=\"lean-declaration lean-group{markdown_class}\">{header}{body}<div class=\"lean-source\">{cited_source}</div></figure>\n\n"))
}
}
mdbook-dada/src/lean.rs:render_authored
#![allow(unused)]
fn main() {
/// Check source citations and pair authored LaTeX with those source excerpts.
/// No mathematical syntax is generated from, or compared with, the Lean source.
pub fn render_authored(
    root: &Path,
    targets: &str,
    body: &str,
    view: View,
    group: &str,
) -> Result<String> {
    let targets: Vec<_> = targets.split_whitespace().collect();
    ensure!(!targets.is_empty(), "expected Lean citations on the directive opening line; use ```{{grammar}} path:Name with authored LaTeX in the body");
    ensure!(
        view == View::Grammar || targets.len() == 1,
        "judgment and rule directives require exactly one opening-line citation"
    );
    ensure!(
        !body.trim().is_empty(),
        "authored math directive requires a LaTeX body"
    );
    let mut source = String::new();
    for target in targets {
        let (file, selected) = read_source(root, target)?;
        let (name, case) = if view == View::Rule {
            let (name, case) = selected
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            (name, Some(case))
        } else {
            (selected.as_str(), None)
        };
        let declaration = extract(&file, name).with_context(|| target.to_owned())?;
        ensure!(
            !matches!(view, View::Judgment | View::Rule) || declaration.starts_with("inductive "),
            "judgment and rule citations must select inductive declarations"
        );
        let declaration = if let Some(case) = case {
            extract_case(&declaration, case)?
        } else {
            declaration
        };
        source.push_str(&format!(
            "<figcaption>{}</figcaption><pre><code class=\"language-lean\">{}</code></pre>",
            crate::escape(target),
            highlighted(&declaration)?
        ));
    }
    // Keep blank lines inside the raw HTML block so Markdown cannot reinterpret
    // the authored TeX. Escaping also keeps TeX text from becoming HTML markup.
    let tex = crate::escape(body.trim()).replace('\n', "&#10;");
    let rendered = format!("<div class=\"math-display\">\\[{tex}\\]</div>");
    let label = match view {
        View::Grammar => "Grammar",
        View::Judgment => "Judgment",
        View::Rule => "Rule",
    };
    Ok(selector(&rendered, &source, group, label))
}
}
mdbook-dada/src/lib.rs:escape
#![allow(unused)]
fn main() {
pub fn escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}
}
mdbook-dada/tests/book.rs:authored_grammar_keeps_math_and_groups_citations_in_order
#![allow(unused)]
fn main() {
#[test]
fn authored_grammar_keeps_math_and_groups_citations_in_order() {
    let root = lean_fixtures();
    let source = r"```{grammar} Renderer:Slot Renderer.lean:Object
\begin{aligned}
s &::= \bot \mid r \\
o &::= p \mid \{f \mapsto s\} \mid {\overline s}
\end{aligned}
```";
    let mut book = json!({"items": [chapter("state.md", source)]});
    mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
    let html = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(html.contains(r"s &amp;::= \bot \mid r"));
    assert!(html.contains(r"o &amp;::= p \mid \{f \mapsto s\} \mid {\overline s}"));
    assert!(html.find("Renderer:Slot").unwrap() < html.find("Renderer.lean:Object").unwrap());
    let lean = html.split("class=\"lean-source\"").nth(1).unwrap();
    assert!(lean.find("Slot").unwrap() < lean.find("Object").unwrap());
    assert!(lean.contains("| uninitialized"));
    assert!(lean.contains("| array"));
    assert!(lean.contains("lean-keyword"));
    assert_eq!(html.matches("class=\"lean-selector\"").count(), 1);
    assert_eq!(html.matches("> Rendered</label>").count(), 1);
    assert_eq!(html.matches("> Lean</label>").count(), 1);
    let rendered = html.split("class=\"lean-source\"").next().unwrap();
    assert!(!rendered.contains("uniqueKeys"));
    assert!(!rendered.contains("FiniteMap"));
}
}
mdbook-dada/tests/book.rs:authored_math_escapes_html_without_interpreting_placeholders
#![allow(unused)]
fn main() {
#[test]
fn authored_math_escapes_html_without_interpreting_placeholders() {
    let root = lean_fixtures();
    let source = r"```{rule} Renderer:Step.allocVariable
\frac{a < b & c > d}{${authorChosenName}}
```
";
    let mut book = json!({"items": [chapter("ops.md", source)]});
    mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
    let html = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(html.contains(r"\frac{a &lt; b &amp; c &gt; d}{${authorChosenName}}"));
    assert!(!html.contains("a < b & c > d"));
    let rendered = html.split("class=\"lean-source\"").next().unwrap();
    assert!(!rendered.contains(r"\xrightarrow"));
    assert!(!rendered.contains("insertFresh"));
}
}
mdbook-dada/tests/book.rs:explicit_math_survives_markdown_and_smart_punctuation_in_prose_and_proof_bodies
#![allow(unused)]
fn main() {
#[test]
fn explicit_math_survives_markdown_and_smart_punctuation_in_prose_and_proof_bodies() {
    use pulldown_cmark::{Event, Options, Parser};
    let root = lean_fixtures();
    let formula = r"\frac{S'=S[p\mapsto s]}{S'(q)=\begin{cases}s&q=p\\S(q)&q\ne p\end{cases}}";
    let body = format!(
        "**Statement.** The result is \\\\(S'_x \\ne S_x\\\\).\n\n\\\\[\n{formula}\n\\\\]\n\n**Proof outline.** Apply the rule."
    );
    for opening in [
        None,
        Some("{example} Renderer:integer_primitive"),
        Some("{definition} Renderer:readSlot"),
        Some("{theorem} Renderer:deallocVariable_requires_top"),
        Some("{lemma} Renderer:deallocVariable_requires_top"),
    ] {
        let source = opening.map_or_else(|| body.clone(), |info| format!("```{info}\n{body}\n```"));
        let mut book = json!({"items": [chapter("proofs.md", &source)]});
        mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
        let markdown = book["items"][0]["Chapter"]["content"].as_str().unwrap();
        let events: Vec<_> = Parser::new_ext(markdown, Options::ENABLE_SMART_PUNCTUATION).collect();
        let rendered: String = events
            .iter()
            .filter_map(|event| match event {
                Event::Text(text) | Event::Html(text) | Event::InlineHtml(text) => {
                    Some(text.as_ref())
                }
                _ => None,
            })
            .collect();
        assert!(
            rendered.contains(&format!(
                "<div class=\"math-display\">\\[&#10;{}&#10;\\]</div>",
                mdbook_dada::escape(formula)
            )),
            "{rendered}"
        );
        assert!(
            rendered.contains("<span class=\"math-inline\">\\(S'_x \\ne S_x\\)</span>"),
            "{rendered}"
        );
        assert!(rendered.contains("Statement."));
        assert!(rendered.contains("Proof outline."));
        assert!(!rendered.contains('’'));
    }
}
}
mdbook-dada/tests/book.rs:explicit_math_is_literal_in_code_links_and_html_and_does_not_define_roles
#![allow(unused)]
fn main() {
#[test]
fn explicit_math_is_literal_in_code_links_and_html_and_does_not_define_roles() {
    let literal = r"```text
\\[
S' \\ T
\\]
```

    \\(S'_x\\)

`\\(S'\\)` and [\\(S'\\)](somewhere.md).

<pre>\\[S'\\]</pre>

Escaped \\\(S'\\).
";
    let mut book = json!({"items": [chapter("literal.md", literal)]});
    process(&mut book).unwrap();
    assert_eq!(book["items"][0]["Chapter"]["content"], literal);
    let mut math = json!({"items": [chapter("math.md", r"\\[\text{{anchor}`literal`}\\] \n\\(\text{{definition}`literal`}\\)")]});
    process(&mut math).unwrap();
    let output = math["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(output.contains("math-display"));
    assert!(output.contains("math-inline"));
    assert!(!output.contains("spec-shield"));
}
}

The renderer emits MathJax delimiters for the runtime configured by book.toml and theme/mathjax.js. The bundled loader selects MathJax 4.1.3’s CommonHTML build; mdBook’s built-in MathJax loader is disabled. Local previews and published pages load that same script. Authored display breaks are retained, and wide mathematical blocks can scroll horizontally.

The loader uses a CDN, so browser typesetting requires network access. The source text and selectors remain available independently. The tests inspect configuration and emitted HTML/CSS; they do not guarantee CDN availability or verify the appearance of every possible formula.

mdbook-dada/src/lib.rs:protect_math
#![allow(unused)]
fn main() {
fn protect_math(source: &str) -> String {
    let literal: Vec<_> = Parser::new(source)
        .into_offset_iter()
        .filter_map(|(event, range)| match event {
            Event::Start(
                Tag::CodeBlock(_) | Tag::HtmlBlock | Tag::Link { .. } | Tag::Image { .. },
            )
            | Event::Code(_)
            | Event::Html(_)
            | Event::InlineHtml(_) => Some(range),
            _ => None,
        })
        .collect();
    let mut output = String::new();
    let mut end = 0;
    for (start, _) in source.match_indices(r"\\") {
        if start < end
            || source[..start].ends_with('\\')
            || literal.iter().any(|range| range.contains(&start))
        {
            continue;
        }
        let (display, closing) = match source.as_bytes().get(start + 2) {
            Some(b'[') => (true, r"\\]"),
            Some(b'(') => (false, r"\\)"),
            _ => continue,
        };
        let body_start = start + 3;
        let Some(close) = source[body_start..].find(closing).map(|i| body_start + i) else {
            continue;
        };
        if literal.iter().any(|range| range.contains(&close)) {
            continue;
        }
        let body = &source[body_start..close];
        output.push_str(&source[end..start]);
        if display {
            let tex = escape(body).replace('\n', "&#10;");
            output.push_str(&format!(
                "\n\n<div class=\"math-display\">\\[{tex}\\]</div>\n\n"
            ));
        } else {
            // Inline HTML does not suppress Markdown parsing of its contents.
            // Entities keep every TeX punctuation character out of that parser.
            let tex: String = format!("\\({body}\\)")
                .chars()
                .map(|c| {
                    if c.is_alphanumeric() || c == ' ' {
                        c.to_string()
                    } else {
                        format!("&#{};", u32::from(c))
                    }
                })
                .collect();
            output.push_str(&format!("<span class=\"math-inline\">{tex}</span>"));
        }
        end = close + closing.len();
    }
    output.push_str(&source[end..]);
    output
}
}
mdbook-dada/src/lean.rs:render_authored
#![allow(unused)]
fn main() {
/// Check source citations and pair authored LaTeX with those source excerpts.
/// No mathematical syntax is generated from, or compared with, the Lean source.
pub fn render_authored(
    root: &Path,
    targets: &str,
    body: &str,
    view: View,
    group: &str,
) -> Result<String> {
    let targets: Vec<_> = targets.split_whitespace().collect();
    ensure!(!targets.is_empty(), "expected Lean citations on the directive opening line; use ```{{grammar}} path:Name with authored LaTeX in the body");
    ensure!(
        view == View::Grammar || targets.len() == 1,
        "judgment and rule directives require exactly one opening-line citation"
    );
    ensure!(
        !body.trim().is_empty(),
        "authored math directive requires a LaTeX body"
    );
    let mut source = String::new();
    for target in targets {
        let (file, selected) = read_source(root, target)?;
        let (name, case) = if view == View::Rule {
            let (name, case) = selected
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            (name, Some(case))
        } else {
            (selected.as_str(), None)
        };
        let declaration = extract(&file, name).with_context(|| target.to_owned())?;
        ensure!(
            !matches!(view, View::Judgment | View::Rule) || declaration.starts_with("inductive "),
            "judgment and rule citations must select inductive declarations"
        );
        let declaration = if let Some(case) = case {
            extract_case(&declaration, case)?
        } else {
            declaration
        };
        source.push_str(&format!(
            "<figcaption>{}</figcaption><pre><code class=\"language-lean\">{}</code></pre>",
            crate::escape(target),
            highlighted(&declaration)?
        ));
    }
    // Keep blank lines inside the raw HTML block so Markdown cannot reinterpret
    // the authored TeX. Escaping also keeps TeX text from becoming HTML markup.
    let tex = crate::escape(body.trim()).replace('\n', "&#10;");
    let rendered = format!("<div class=\"math-display\">\\[{tex}\\]</div>");
    let label = match view {
        View::Grammar => "Grammar",
        View::Judgment => "Judgment",
        View::Rule => "Rule",
    };
    Ok(selector(&rendered, &source, group, label))
}
}
mdbook-dada/tests/renderer_contracts.rs:pinned_mathjax_configuration_uses_one_loader
#![allow(unused)]
fn main() {
#[test]
fn pinned_mathjax_configuration_uses_one_loader() {
    let config: toml::Value = toml::from_str(&read_asset("book.toml")).unwrap();
    let html = &config["output"]["html"];
    assert_eq!(html["mathjax-support"].as_bool(), Some(false));
    let scripts = html["additional-js"].as_array().unwrap();
    assert_eq!(
        scripts.len(),
        1,
        "review any added loader for duplicate MathJax initialization"
    );
    assert_eq!(scripts[0].as_str(), Some("theme/mathjax.js"));
    assert!(html["additional-css"]
        .as_array()
        .unwrap()
        .iter()
        .any(|path| path.as_str() == Some("theme/dada.css")));

    let script = read_asset("theme/mathjax.js");
    let urls = regex::Regex::new(r#"https://[^'"\s]+"#).unwrap();
    let urls: Vec<_> = urls.find_iter(&script).map(|m| m.as_str()).collect();
    assert_eq!(
        urls,
        ["https://cdn.jsdelivr.net/npm/mathjax@4.1.3/tex-chtml.js"]
    );
    assert_eq!(
        script.matches("document.createElement('script')").count(),
        1
    );
    assert_eq!(
        script
            .matches("document.head.appendChild(mathjaxScript)")
            .count(),
        1
    );
    assert!(script.find("window.MathJax =").unwrap() < script.find("appendChild").unwrap());
    assert!(script.contains("displayOverflow: 'overflow'"));
    assert!(script.contains("inlineMath: [['\\\\(', '\\\\)']]"));
    assert!(script.contains("displayMath: [['\\\\[', '\\\\]']]"));
}
}
mdbook-dada/tests/renderer_contracts.rs:view_styles_keep_headers_and_nested_choices_independent
#![allow(unused)]
fn main() {
#[test]
fn view_styles_keep_headers_and_nested_choices_independent() {
    let css = read_asset("theme/dada.css");
    let options = css
        .split_once(".lean-selector .view-options {")
        .unwrap()
        .1
        .split_once('}')
        .unwrap()
        .0;
    assert!(options.contains("margin-left:auto"));
    // A nested diagram's radio button must not switch its enclosing Lean block.
    // The selector reaches the block's own header, then changes only its children.
    for pane in [".lean-source", ".lean-grammar", ".lean-markdown-body"] {
        assert!(css.contains(&format!(
            ".lean-group:has(> .lean-selector input:is([value=\"lean\"], [value=\"rust\"]):checked) > {pane}"
        )));
    }
    assert!(css.contains(
        ".heap-figure:has(input[value=\"facts\"]:checked) .heap-facts { display:block; }"
    ));
    assert!(css.contains(
        ".heap-figure:has(input[value=\"facts\"]:checked) .heap-diagram { display:none; }"
    ));
    for selector in [".lean-grammar", ".lean-source pre", ".heap-figure"] {
        let declaration = css
            .split_once(&format!("{selector} {{"))
            .unwrap()
            .1
            .split_once('}')
            .unwrap()
            .0;
        assert!(declaration.contains("overflow-x:auto"), "{selector}");
    }

    let mut book = json!({"items": [{"Chapter": {
        "path": "local.md", "content": "{anchor}`local.identity`\n\n{anchor-ref}`local.identity`", "sub_items": []
    }}]});
    process(&mut book).unwrap();
    let rendered = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert_eq!(rendered.matches("class=\"spec-shield\"").count(), 2);
    assert!(rendered.contains("href=\"#claim-local.identity\""));
    assert!(!rendered.contains("<img"));
    assert!(!rendered.contains("src="));
    assert!(
        !css.contains("url("),
        "shield styling must not fetch a remote badge"
    );
}
}

Write an overbar inside a group, as in {\overline f}. The command must have an opening brace immediately before it and a literal ASCII space immediately after it. A tab or newline does not satisfy the space requirement. Longer command names are not matches.

The lint checks raw Markdown, including literal TeX samples, and reports a source path and line number for either violation. A repository test checks all Markdown below v2/md/, including files outside the table of contents. This is an adjacency check; it does not parse the TeX expression or balance its braces.

mdbook-dada/src/lint.rs:check_latex
#![allow(unused)]
fn main() {
/// Require an opening group immediately before each overbar command and a
/// literal space immediately after it. Longer TeX control words are separate commands.
pub fn check_latex(source: &str, path: &str) -> Result<()> {
    let overline = Regex::new(r"\\overline([^A-Za-z]|$)")?;
    for matched in overline.captures_iter(source) {
        let command = matched.get(0).expect("a regex match has a full capture");
        let line = source[..command.start()]
            .bytes()
            .filter(|&byte| byte == b'\n')
            .count()
            + 1;
        ensure!(
            source[..command.start()].ends_with('{') && &matched[1] == " ",
            "{path}:{line}: LaTeX style: use {{\\overline f}}; the command must be immediately preceded by `{{` and immediately followed by a literal space"
        );
    }
    Ok(())
}
}
mdbook-dada/tests/latex.rs:overbars_require_a_preceding_brace_and_following_literal_space
#![allow(unused)]
fn main() {
#[test]
fn overbars_require_a_preceding_brace_and_following_literal_space() {
    for source in [
        r"\overline f,x",
        r"{ \overline f}",
        r"\overline{f}",
        r"{\overline{f}}",
        "{\\overline\tf}",
        "{\\overline\nf}",
        "{\\overline\r\nf}",
        "{\\overline\u{a0}f}",
        r"\overline {f}",
        r"{\overline7}",
        r"{\overline\alpha}",
        r"{\overline}",
        r"{\overline",
        r"\overline",
    ] {
        let error = check_latex(source, "state.md").unwrap_err().to_string();
        assert!(error.contains("state.md:1:"), "{source:?}: {error}");
        assert!(error.contains(r"use {\overline f}"), "{error}");
    }
}
}
mdbook-dada/tests/latex.rs:grouped_overbars_and_other_control_words_are_allowed
#![allow(unused)]
fn main() {
#[test]
fn grouped_overbars_and_other_control_words_are_allowed() {
    for source in [
        r"{\overline f},x",
        r"{\overline {f_1, f_2}}",
        r"{\overline {\overline f}}",
        r"{\overline \alpha}",
        r"{\overline f} + {\overline g}",
        r"\overlineSomething f",
        r"\overlined f",
        "No math here.",
    ] {
        check_latex(source, "state.md").unwrap();
    }
}
}
mdbook-dada/tests/latex.rs:diagnostics_count_source_lines_including_unicode_and_crlf
#![allow(unused)]
fn main() {
#[test]
fn diagnostics_count_source_lines_including_unicode_and_crlf() {
    let source = "# α\r\n{\\overline f}\r\n\r\n\\overline f";
    let error = check_latex(source, "nested/chapter.md")
        .unwrap_err()
        .to_string();
    assert!(error.starts_with("nested/chapter.md:4:"), "{error}");
}
}
mdbook-dada/tests/latex.rs:book_build_checks_math_directives_examples_and_literal_tex
#![allow(unused)]
fn main() {
#[test]
fn book_build_checks_math_directives_examples_and_literal_tex() {
    for source in [
        r"Inline \\(\overline f\\).",
        "```{grammar} Heap.lean:Object\n\\overline f\n```",
        "````{example} Heap.lean:integer_primitive\n\\overline f\n````",
        "```latex\n\\overline f\n```",
    ] {
        let mut book = json!({"items": [{"Chapter": {
            "path": "intro.md", "content": "Introduction.", "sub_items": [
                {"Chapter": {"path": "nested/state.md", "content": source, "sub_items": []}}
            ]
        }}]});
        let error = process(&mut book).unwrap_err().to_string();
        assert!(error.contains("nested/state.md:"), "{error}");
        assert!(error.contains(r"use {\overline f}"), "{error}");
    }
}
}
mdbook-dada/tests/latex.rs:all_book_markdown_follows_latex_conventions
#![allow(unused)]
fn main() {
#[test]
fn all_book_markdown_follows_latex_conventions() -> Result<()> {
    fn scan(directory: &Path, errors: &mut Vec<String>, count: &mut usize) -> Result<()> {
        let mut entries = fs::read_dir(directory)
            .with_context(|| format!("read {}", directory.display()))?
            .collect::<std::io::Result<Vec<_>>>()?;
        entries.sort_by_key(|entry| entry.path());
        for entry in entries {
            let path = entry.path();
            if entry.file_type()?.is_dir() {
                scan(&path, errors, count)?;
            } else if path.extension().is_some_and(|extension| extension == "md") {
                *count += 1;
                let source = fs::read_to_string(&path)
                    .with_context(|| format!("read {}", path.display()))?;
                if let Err(error) = check_latex(&source, &path.display().to_string()) {
                    errors.push(error.to_string());
                }
            }
        }
        Ok(())
    }

    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../md");
    let mut errors = Vec::new();
    let mut count = 0;
    scan(&root, &mut errors, &mut count)?;
    assert!(count > 0, "no book Markdown found under {}", root.display());
    assert!(errors.is_empty(), "{}", errors.join("\n"));
    Ok(())
}
}

Lean selections

A completed definition selects one or more named def, abbrev, structure, or inductive declarations, in citation order, including their bodies. Theorems, axioms, anonymous examples, and constructor-only citations are not valid definition targets.

definitionmeta.lean.definitions.extraction Extraction recognizes column-zero declarations with indented continuations. Structures and inductives put where on their first line. Definitions may have multiline signatures and a := body, a where body, or indented equation clauses. Definition abbreviations may have an indented signature and := body. The scanner masks comments and literal contents to find boundaries, then retains the original source tokens. A matching word in a comment is not a declaration.

definitionmeta.lean.definitions.selection A grammar selects inductive, structure, or abbrev declarations. Its type names are unqualified; type abbreviations put := on their first line. Supported column-zero mutual inductives can be selected individually, as specified by refmeta.sources.exact_selection.

definitionmeta.syntax.grammar.declarations A structured grammar has an ID, one or more :lean: citations, and authored LaTeX. Surrounding prose defines its mathematical categories and notation.

definitionmeta.syntax.grammar.validation Citation lookup checks existence and supported declaration kinds. It does not parse an independent grammar language, resolve mathematical symbols, or establish correspondence with Lean.

mdbook-dada/src/lean.rs:select
#![allow(unused)]
fn main() {
/// Resolve a citation with the same declaration-kind checks as the renderer.
pub fn select(root: &Path, target: &str, kind: crate::units::UnitKind) -> Result<LeanSelection> {
    use crate::units::UnitKind;
    ensure!(
        kind != UnitKind::FutureNote,
        "future notes cannot have formalization citations"
    );
    let (source, name) = read_source(root, target)?;
    let selected = match kind {
        UnitKind::FutureNote => unreachable!("rejected above"),
        UnitKind::Definition => extract_definition(&source, &name),
        UnitKind::Theorem | UnitKind::Lemma => extract_theorem(&source, &name),
        UnitKind::Example => extract_example(&source, &name),
        UnitKind::Grammar => extract(&source, &name),
        UnitKind::Judgment => extract(&source, &name).and_then(|declaration| {
            ensure!(
                declaration.starts_with("inductive "),
                "judgment citation must select an inductive declaration"
            );
            Ok(declaration)
        }),
        UnitKind::Rule => {
            let (name, case) = name
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            extract(&source, name).and_then(|declaration| extract_case(&declaration, case))
        }
    }
    .with_context(|| target.to_owned())?;
    let (file, _) = target
        .rsplit_once(':')
        .context("expected path:Declaration")?;
    let mut relative = std::path::PathBuf::from(file);
    if relative.extension().is_none() {
        relative.set_extension("lean");
    }
    // read_source already checks canonical containment, including symlinks.
    let path = root.join(relative).canonicalize()?;
    Ok(LeanSelection {
        path,
        source,
        selected,
    })
}
}
mdbook-dada/src/lean.rs:extract_declaration
#![allow(unused)]
fn main() {
fn extract_declaration(source: &str, name: &str, selection: Selection) -> Result<String> {
    let simple_name = |component: &str| {
        !component.is_empty() && component.chars().all(|c| c.is_alphanumeric() || c == '_')
    };
    if selection != Selection::Type {
        ensure!(
            name.split('.').all(simple_name),
            "use a declaration name with nonempty identifier components separated by single dots"
        );
    } else {
        ensure!(
            simple_name(name),
            "use a simple unqualified declaration name"
        );
    }
    let masked = mask(source)?;
    validate_mutual_groups(&masked)?;
    let mut found = Vec::new();
    let mut offset = 0;
    let lines: Vec<_> = masked
        .split_inclusive('\n')
        .map(|line| {
            let start = offset;
            offset += line.len();
            (start, line)
        })
        .collect();
    let structure_field = regex::Regex::new(r"^[ \t]+[A-Za-z_][A-Za-z0-9_']*[ \t]*:(?:[^:=]|$)")?;
    for (i, &(start, line)) in lines.iter().enumerate() {
        let words: Vec<_> = line.split_whitespace().collect();
        if selection == Selection::Definition {
            let declaration: Vec<_> = words
                .iter()
                .copied()
                .skip_while(|word| {
                    matches!(
                        *word,
                        "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
                    )
                })
                .collect();
            // Literal names are intentionally not resolved through namespaces.
            // A same-named declaration of the wrong kind must not disappear
            // from an otherwise ambiguous citation.
            if declaration.get(1) == Some(&name)
                && matches!(
                    declaration.first(),
                    Some(
                        &"def"
                            | &"abbrev"
                            | &"structure"
                            | &"inductive"
                            | &"theorem"
                            | &"lemma"
                            | &"axiom"
                            | &"opaque"
                            | &"constant"
                            | &"class"
                    )
                )
            {
                ensure!(
                    declaration.len() == words.len(),
                    "declaration modifiers are unsupported"
                );
                ensure!(
                    matches!(declaration.first(), Some(&"def" | &"abbrev" | &"structure" | &"inductive")),
                    "definition citations must select def, abbrev, structure, or inductive declarations"
                );
            }
        }
        if words.get(1) != Some(&name) {
            continue;
        }
        let supported = match selection {
            Selection::Theorem => words.first() == Some(&"theorem"),
            Selection::Type => {
                matches!(words.first(), Some(&"inductive" | &"structure" | &"abbrev"))
            }
            Selection::Definition => matches!(
                words.first(),
                Some(&"def" | &"inductive" | &"structure" | &"abbrev")
            ),
        };
        if !supported {
            continue;
        }
        ensure!(
            !line.starts_with(char::is_whitespace),
            "selected Lean declarations must begin at column zero"
        );
        if let Some((_, previous)) = lines[..i].iter().rev().find(|(_, l)| !l.trim().is_empty()) {
            ensure!(
                !previous.trim_start().starts_with("@["),
                "declaration attributes are unsupported"
            );
        }
        if let Some((_, boundary)) = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
        {
            let mut words = boundary.split_whitespace();
            let first = words.next().unwrap_or("");
            let mut word = first;
            while matches!(
                word,
                "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
            ) {
                word = words.next().unwrap_or("");
            }
            ensure!(
                (word == first
                    || matches!(
                        word,
                        "inductive" | "structure" | "abbrev" | "def" | "theorem" | "instance"
                    ))
                    && matches!(
                        word,
                        "inductive"
                            | "structure"
                            | "abbrev"
                            | "def"
                            | "theorem"
                            | "lemma"
                            | "example"
                            | "instance"
                            | "end"
                            | "namespace"
                            | "section"
                            | "mutual"
                            | "variable"
                            | "open"
                            | "#check"
                    ),
                "unsupported declaration boundary `{}`; continuation lines must be indented",
                boundary.trim()
            );
        }
        let end = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
            .map(|(n, _)| *n)
            .unwrap_or(source.len());
        let body = &source[start..end];
        let text = &body[..scan(body)?.content_end];
        {
            let code = &masked[start..end];
            // A structure field such as `variables : Store` is not a command.
            // Only exempt a bare, indented field name followed by a type colon;
            // `variable (x : Nat)` and `def sibling := ...` remain commands.
            let commands = command_pattern()?
                .find_iter(code)
                .filter(|command| {
                    words[0] != "structure"
                        || !structure_field
                            .is_match(code[command.start()..].lines().next().unwrap_or(""))
                })
                .count();
            ensure!(
                commands == 1,
                "selected declaration must contain no other commands, even when indented"
            );
        }
        if selection == Selection::Theorem {
            ensure!(
                has_definition_body(&masked[start..end]),
                "theorem must include its proof body (`:=`)"
            );
        } else if selection == Selection::Definition && words[0] == "def" {
            ensure!(
                has_named_definition_body(&masked[start..end])?,
                "definition must include a body (`:=`, `where`, or indented equations with `=>`)"
            );
        } else if words[0] != "abbrev" {
            ensure!(
                line.contains("where"),
                "declaration header must contain `where` on its first line"
            );
        } else {
            if selection == Selection::Definition {
                ensure!(
                    has_definition_body(&masked[start..end]),
                    "abbreviation must include a body (`:=`)"
                );
            } else {
                ensure!(line.contains(":="), "abbreviation header must contain `:=`");
            }
        }
        found.push(text.to_owned());
    }
    ensure!(
        found.len() == 1,
        "expected one supported declaration `{name}`, found {}",
        found.len()
    );
    Ok(found.remove(0))
}
}
mdbook-dada/src/lean.rs:has_named_definition_body
#![allow(unused)]
fn main() {
fn has_named_definition_body(code: &str) -> Result<bool> {
    if has_definition_body(code) {
        return Ok(true);
    }
    let mut delimiters = Vec::new();
    for (offset, c) in code.char_indices() {
        match c {
            '(' | '{' | '[' | '⦃' => delimiters.push(c),
            ')' | '}' | ']' | '⦄' => {
                delimiters.pop();
            }
            'w' if delimiters.is_empty()
                && !follows_identifier(code, offset)
                && code[offset..].starts_with("where")
                && !code[offset + "where".len()..]
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '\'')) =>
            {
                return Ok(true);
            }
            '|' if delimiters.is_empty()
                && code[..offset]
                    .rsplit_once('\n')
                    .is_some_and(|(_, prefix)| !prefix.is_empty() && prefix.trim().is_empty()) =>
            {
                let arm = code[offset..].lines().next().unwrap_or("");
                ensure!(
                    arm.contains("=>"),
                    "equation arms must put `=>` on their first line"
                );
                return Ok(true);
            }
            _ => {}
        }
    }
    Ok(false)
}
}
mdbook-dada/src/lean.rs:definition_source
#![allow(unused)]
fn main() {
/// Select the complete declarations associated with an authored definition.
/// Citations name declarations literally; enclosing namespaces are not inferred.
pub fn definition_source(root: &Path, targets: &str) -> Result<String> {
    let targets: Vec<_> = targets.split_whitespace().collect();
    ensure!(
        !targets.is_empty(),
        "definition requires at least one opening-line citation"
    );
    let mut output = String::new();
    for target in targets {
        let (source, name) = read_source(root, target)?;
        let declaration = extract_definition(&source, &name).with_context(|| target.to_owned())?;
        output.push_str(&format!(
            "<figcaption>{}</figcaption><pre><code class=\"language-lean\">{}</code></pre>",
            crate::escape(target),
            highlighted(&declaration)?
        ));
    }
    Ok(output)
}
}
mdbook-dada/tests/book.rs:definition_blocks_select_multiple_complete_declarations_and_preserve_markdown
#![allow(unused)]
fn main() {
#[test]
fn definition_blocks_select_multiple_complete_declarations_and_preserve_markdown() {
    use pulldown_cmark::{Event, Parser, Tag};
    let root = lean_fixtures();
    let source = r"````{definition} Renderer:readSlot Renderer:Stored Renderer:AllocatedObject Renderer:State.initial Renderer:FieldName Renderer:VariableId Renderer:Slot
{anchor}`slot-lookup` Write **lookup** as \\(S(p)=s\\).

\\[
S(p)=s \iff \mathsf{readSlot}(S,p)=\mathsf{some}(s)
\\]

1. A variable selects a slot.
2. A missing place has no slot.

```{grammar} Renderer:Place
p ::= x
```
````";
    let input = json!({"items": [
        chapter("state.md", source),
        chapter("operations.md", "See {anchor-ref}`slot-lookup`."),
    ]});
    let mut first = input.clone();
    let mut second = input;
    mdbook_dada::process_with_lean(&mut first, Some(&root)).unwrap();
    mdbook_dada::process_with_lean(&mut second, Some(&root)).unwrap();
    assert_eq!(first, second, "selectors must be deterministic");
    let output = first["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(output.contains("aria-label=\"Definition view\""));
    assert!(!output.contains("class=\"block-label\">Definition</span>"));
    assert!(output.contains("aria-label=\"definition: slot-lookup\""));
    assert!(output.contains("lean-keyword\">def</span> readSlot"));
    assert!(output.contains("elements[index]?"));
    assert!(!output.contains("def</span> writeSlot"));
    assert!(!output.contains("A write never creates"));
    assert!(output.contains("lean-keyword\">def</span> Stored"));
    assert!(output.contains("lean-keyword\">def</span> AllocatedObject"));
    assert!(output.contains("lean-keyword\">def</span> State.initial"));
    assert!(output.contains("lean-keyword\">abbrev</span> FieldName"));
    assert!(output.contains("lean-keyword\">structure</span> VariableId"));
    assert!(output.contains("lean-keyword\">inductive</span> Slot"));
    assert_eq!(output.matches("class=\"math-display\"").count(), 2);
    assert!(output.contains("class=\"math-inline\""));
    let events: Vec<_> = Parser::new(output).collect();
    assert!(events
        .iter()
        .any(|event| matches!(event, Event::Start(Tag::Strong))));
    assert!(events
        .iter()
        .any(|event| matches!(event, Event::Start(Tag::List(Some(1))))));
    assert!(first["items"][1]["Chapter"]["content"]
        .as_str()
        .unwrap()
        .contains("state.html#claim-slot-lookup"));
    let mut duplicate = json!({"items": [chapter("state.md", source), chapter("other.md", "{anchor}`slot-lookup`")]});
    assert!(format!(
        "{:#}",
        mdbook_dada::process_with_lean(&mut duplicate, Some(&root)).unwrap_err()
    )
    .contains("duplicate anchor"));
}
}
mdbook-dada/tests/book.rs:definition_blocks_reject_missing_wrong_kind_and_malformed_citations
#![allow(unused)]
fn main() {
#[test]
fn definition_blocks_reject_missing_wrong_kind_and_malformed_citations() {
    let root = lean_fixtures();
    for source in [
        "```{definition}\nBody.\n```",
        "```{definition}Renderer:State\nBody.\n```",
        "```{definition} Renderer:State\n \n```",
        "```{definition} Renderer:deallocVariable_requires_top\nBody.\n```",
        "```{definition} Renderer:integer_primitive\nBody.\n```",
        "```{definition} Renderer:Step.allocVariable\nBody.\n```",
        "```{definition} Renderer:State Renderer:missing\nBody.\n```",
        "```{definition} ../Renderer:State\nBody.\n```",
        "```{definition} Missing:State\nBody.\n```",
    ] {
        let mut book = json!({"items": [chapter("state.md", source)]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap_err();
        assert!(format!("{error:#}").contains("state.md"), "{source}");
    }
    let mut no_root =
        json!({"items": [chapter("state.md", "```{definition} Renderer:State\nBody.\n```")]});
    assert!(process(&mut no_root).is_err());
    let literal = "````text\n```{definition} Missing:nope\nBody.\n```\n````\n\n    ```{definition} Missing:nope\n    Body.\n    ```";
    let mut book = json!({"items": [chapter("literal.md", literal)]});
    process(&mut book).unwrap();
    assert_eq!(book["items"][0]["Chapter"]["content"], literal);
}
}
mdbook-dada/src/lean.rs:tests::definitions_select_complete_equations_structure_literals_and_multiline_bodies
#![allow(unused)]
fn main() {
#[test]
    fn definitions_select_complete_equations_structure_literals_and_multiline_bodies() {
        let source = "namespace Outer\ndef State.initial : State Primitive :=\n  .state FiniteMap.empty FiniteMap.empty\ndef readSlot : State Primitive → Place → Option Slot\n  | .state _ variables, .variable id => variables.lookup id\n  | .state objects _, .field id name => do\n      let .aggregate fields ← objects.lookup id | none\n      fields.lookup name\ndef empty : Store where\n  entries := []\n  uniqueKeys := by\n    exact List.nodup_nil\nabbrev Value\n    (α : Type) :=\n  Option α\nend Outer\n";
        assert_eq!(
            extract_definition(source, "State.initial").unwrap(),
            "def State.initial : State Primitive :=\n  .state FiniteMap.empty FiniteMap.empty"
        );
        let read = extract_definition(source, "readSlot").unwrap();
        assert!(read.contains("  | .state _ variables"));
        assert!(read.ends_with("      fields.lookup name"));
        assert!(!read.contains("def empty"));
        assert!(extract_definition(source, "empty")
            .unwrap()
            .ends_with("    exact List.nodup_nil"));
        assert!(extract_definition(source, "Value")
            .unwrap()
            .ends_with("  Option α"));
        assert!(extract_definition(source, "initial").is_err());
        assert!(extract_definition(source, "Outer.State.initial").is_err());
        // The math-only grammar directive retains its original type contract.
        assert!(extract(source, "readSlot").is_err());
        assert!(extract(source, "Value").is_err());
        for source in [
            "structure Foo where\n  n : Nat",
            "inductive Foo where\n  | zero\n  | succ (previous : Foo)",
            "abbrev Foo := Nat",
        ] {
            assert_eq!(extract_definition(source, "Foo").unwrap(), source);
        }
    }
}
mdbook-dada/src/lean.rs:tests::definition_selection_ignores_comment_and_literal_decoys
#![allow(unused)]
fn main() {
#[test]
    fn definition_selection_ignores_comment_and_literal_decoys() {
        let source = r###"/- def selected := 0 /- def selected := 1 -/ -/
def text := r##"
def selected := 2
"##
def other := "
def selected := 3
"
-- def selected := 4
def selected : Nat :=
  let text := "def selected := 5"
  let c := '"'
  6
def next := 7
"###;
        let selected = extract_definition(source, "selected").unwrap();
        assert!(selected.starts_with("def selected : Nat :=\n"));
        assert!(selected.ends_with("  6"));
        assert!(selected.contains("let text"));
        assert!(!selected.contains("def next"));
    }
}
mdbook-dada/src/lean.rs:tests::definitions_reject_unsupported_incomplete_and_ambiguous_sources
#![allow(unused)]
fn main() {
#[test]
    fn definitions_reject_unsupported_incomplete_and_ambiguous_sources() {
        for source in [
            "theorem selected : True := by trivial",
            "axiom selected : Nat",
            "opaque selected : Nat := 0",
            "example : Nat := 0",
            "private def selected := 0",
            "@[simp]\ndef selected := 0",
            "  def selected := 0",
            "def selected : Nat",
            "def selected (n : Nat := 0) : Nat",
            "def selected : Nat -- := 0",
            "def selected : Nat /- where -/",
            "def selected : Nat :=\n0",
            "def selected : Nat → Nat\n| n => n",
            "def selected : Nat → Nat\n  | n\n    => n",
            "def selected := 0\ntermination_by 0",
            "def selected := 0\n  def sibling := 1",
            "def selected := 0\n  theorem sibling : True := by trivial",
            "def selected := 0\nmystery next",
            "def selected := 0\nnamespace Nested\ndef selected := 1\nend Nested",
            "namespace A\ndef selected := 0\nend A\nnamespace B\ndef selected := 1\nend B",
            "namespace A\ndef selected := 0\nend A\nnamespace B\ntheorem selected : True := by trivial\nend B",
            "namespace A\ndef selected := 0\nend A\nnamespace B\nprivate def selected := 1\nend B",
            "mutual\ndef selected := 0\nend",
        ] {
            assert!(extract_definition(source, "selected").is_err(), "{source}");
        }
        for name in [".selected", "selected.", "N..selected", "N:selected"] {
            assert!(extract_definition(&format!("def {name} := 0"), name).is_err());
        }
    }
}

A judgment selects one named inductive declaration. Its authored LaTeX presents the judgment; selecting it does not generate mathematical rules automatically.

definitionmeta.math.rule.selection A rule selects one Judgment.constructor and displays the inductive header and that constructor’s complete source. It does not include sibling constructors. The author supplies the mathematical premises, conclusion, and rule label.

The selector checks declaration kinds and constructor names. It does not interpret binder types, classify premises, or require that the declaration’s result is Prop.

mdbook-dada/src/lean.rs:select
#![allow(unused)]
fn main() {
/// Resolve a citation with the same declaration-kind checks as the renderer.
pub fn select(root: &Path, target: &str, kind: crate::units::UnitKind) -> Result<LeanSelection> {
    use crate::units::UnitKind;
    ensure!(
        kind != UnitKind::FutureNote,
        "future notes cannot have formalization citations"
    );
    let (source, name) = read_source(root, target)?;
    let selected = match kind {
        UnitKind::FutureNote => unreachable!("rejected above"),
        UnitKind::Definition => extract_definition(&source, &name),
        UnitKind::Theorem | UnitKind::Lemma => extract_theorem(&source, &name),
        UnitKind::Example => extract_example(&source, &name),
        UnitKind::Grammar => extract(&source, &name),
        UnitKind::Judgment => extract(&source, &name).and_then(|declaration| {
            ensure!(
                declaration.starts_with("inductive "),
                "judgment citation must select an inductive declaration"
            );
            Ok(declaration)
        }),
        UnitKind::Rule => {
            let (name, case) = name
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            extract(&source, name).and_then(|declaration| extract_case(&declaration, case))
        }
    }
    .with_context(|| target.to_owned())?;
    let (file, _) = target
        .rsplit_once(':')
        .context("expected path:Declaration")?;
    let mut relative = std::path::PathBuf::from(file);
    if relative.extension().is_none() {
        relative.set_extension("lean");
    }
    // read_source already checks canonical containment, including symlinks.
    let path = root.join(relative).canonicalize()?;
    Ok(LeanSelection {
        path,
        source,
        selected,
    })
}
}
mdbook-dada/src/lean.rs:extract_case
#![allow(unused)]
fn main() {
fn extract_case(declaration: &str, case: &str) -> Result<String> {
    ensure!(
        !case.is_empty() && case.chars().all(|c| c.is_alphanumeric() || c == '_'),
        "use a simple constructor name"
    );
    let masked = mask(declaration)?;
    let header = declaration
        .lines()
        .next()
        .context("missing declaration header")?;
    ensure!(
        header.starts_with("inductive "),
        "rule citation must select an inductive constructor"
    );
    let mut offset = 0;
    let mut candidates = Vec::new();
    for line in masked.split_inclusive('\n') {
        let trimmed = line.trim_start();
        let indent = line.len() - trimmed.len();
        if let Some(row) = trimmed.strip_prefix('|') {
            let name = row
                .trim_start()
                .split(|c: char| c.is_whitespace() || matches!(c, ':' | '(' | '{' | '['))
                .next()
                .unwrap_or("");
            candidates.push((offset, indent, name));
        }
        offset += line.len();
    }
    let indent = candidates
        .iter()
        .map(|(_, indent, _)| *indent)
        .min()
        .context("inductive has no constructors")?;
    let cases: Vec<_> = candidates
        .into_iter()
        .filter(|(_, i, _)| *i == indent)
        .collect();
    let found: Vec<_> = cases
        .iter()
        .enumerate()
        .filter(|(_, (_, _, n))| *n == case)
        .collect();
    ensure!(
        found.len() == 1,
        "expected one constructor `{case}`, found {}",
        found.len()
    );
    let (index, (start, _, _)) = found[0];
    let end = cases
        .get(index + 1)
        .map(|(start, _, _)| *start)
        .unwrap_or(declaration.len());
    // A comment introducing the next declaration is not part of this case.
    let selected = &declaration[*start..end];
    let selected = &selected[..scan(selected)?.content_end];
    Ok(format!("{header}\n{selected}"))
}
}
mdbook-dada/src/lean.rs:render_authored
#![allow(unused)]
fn main() {
/// Check source citations and pair authored LaTeX with those source excerpts.
/// No mathematical syntax is generated from, or compared with, the Lean source.
pub fn render_authored(
    root: &Path,
    targets: &str,
    body: &str,
    view: View,
    group: &str,
) -> Result<String> {
    let targets: Vec<_> = targets.split_whitespace().collect();
    ensure!(!targets.is_empty(), "expected Lean citations on the directive opening line; use ```{{grammar}} path:Name with authored LaTeX in the body");
    ensure!(
        view == View::Grammar || targets.len() == 1,
        "judgment and rule directives require exactly one opening-line citation"
    );
    ensure!(
        !body.trim().is_empty(),
        "authored math directive requires a LaTeX body"
    );
    let mut source = String::new();
    for target in targets {
        let (file, selected) = read_source(root, target)?;
        let (name, case) = if view == View::Rule {
            let (name, case) = selected
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            (name, Some(case))
        } else {
            (selected.as_str(), None)
        };
        let declaration = extract(&file, name).with_context(|| target.to_owned())?;
        ensure!(
            !matches!(view, View::Judgment | View::Rule) || declaration.starts_with("inductive "),
            "judgment and rule citations must select inductive declarations"
        );
        let declaration = if let Some(case) = case {
            extract_case(&declaration, case)?
        } else {
            declaration
        };
        source.push_str(&format!(
            "<figcaption>{}</figcaption><pre><code class=\"language-lean\">{}</code></pre>",
            crate::escape(target),
            highlighted(&declaration)?
        ));
    }
    // Keep blank lines inside the raw HTML block so Markdown cannot reinterpret
    // the authored TeX. Escaping also keeps TeX text from becoming HTML markup.
    let tex = crate::escape(body.trim()).replace('\n', "&#10;");
    let rendered = format!("<div class=\"math-display\">\\[{tex}\\]</div>");
    let label = match view {
        View::Grammar => "Grammar",
        View::Judgment => "Judgment",
        View::Rule => "Rule",
    };
    Ok(selector(&rendered, &source, group, label))
}
}
mdbook-dada/tests/book.rs:authored_judgments_and_rules_keep_tex_and_show_cited_source
#![allow(unused)]
fn main() {
#[test]
fn authored_judgments_and_rules_keep_tex_and_show_cited_source() {
    let root = lean_fixtures();
    let source = r"```{judgment} Renderer:Step
S \xrightarrow{op} S'
```

```{rule} Renderer.lean:Step.allocVariable
\frac{\mathrm{authorPremise}}{\mathrm{authorConclusion}}
```
";
    let mut book = json!({"items": [chapter("ops.md", source)]});
    mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
    let html = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(html.contains(r"S \xrightarrow{op} S&#39;"));
    assert!(html.contains(r"\frac{\mathrm{authorPremise}}{\mathrm{authorConclusion}}"));
    assert!(html.contains("Renderer:Step"));
    assert!(html.contains("Renderer.lean:Step.allocVariable"));
    assert!(html.contains("| allocVariable"));
    let selected_rule = html.rsplit("class=\"lean-source\"").next().unwrap();
    assert!(selected_rule.contains("| allocVariable"));
    assert!(!selected_rule.contains("| deallocVariable"));
    assert_eq!(html.matches("class=\"lean-selector\"").count(), 2);
    assert_eq!(html.matches("> Rendered</label>").count(), 2);
    assert_eq!(html.matches("> Lean</label>").count(), 2);

    // Each selector's two choices share a group, but different blocks do not.
    let names: Vec<_> = regex::Regex::new(r#"type="radio" name="([^"]+)""#)
        .unwrap()
        .captures_iter(html)
        .map(|captures| captures[1].to_owned())
        .collect();
    assert_eq!(names.len(), 4);
    assert_eq!(names[0], names[1]);
    assert_eq!(names[2], names[3]);
    assert_ne!(names[0], names[2]);

    // Selecting either a middle or final case must exclude its neighbors, even
    // when the judgment and operation have an explicit Primitive parameter.
    let cases = [
        "allocVariable",
        "deallocVariable",
        "createPrimitive",
        "createAggregate",
        "createArray",
    ];
    for case in cases {
        let source = format!("```{{rule}} Renderer:Step.{case}\nP\n```");
        let mut book = json!({"items": [chapter("ops.md", &source)]});
        mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
        let html = book["items"][0]["Chapter"]["content"].as_str().unwrap();
        assert!(html.contains("Operation Primitive"));
        for candidate in cases {
            assert_eq!(
                html.contains(&format!("| {candidate}")),
                candidate == case,
                "case {case} must select only its own constructor"
            );
        }
    }
}
}
mdbook-dada/tests/book.rs:authored_math_requires_one_opening_argument_and_a_body
#![allow(unused)]
fn main() {
#[test]
fn authored_math_requires_one_opening_argument_and_a_body() {
    let root = lean_fixtures();
    for source in [
        "```{rule}\nRenderer:Step.allocVariable\n\\frac{P}{Q}\n```",
        "```{judgment}\nRenderer:Step\nS \\to S'\n```",
        "```{rule} Renderer:Step.allocVariable\n```",
        "```{judgment} Renderer:Step\n  \n```",
        "```{rule} Renderer:Step.allocVariable Renderer:Step.allocVariable\nP\n```",
        "```{judgment}Renderer:Step\nP\n```",
    ] {
        let mut book = json!({"items": [chapter("ops.md", source)]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).expect_err(source);
        assert!(format!("{error:#}").contains("ops.md"), "{source}");
    }
    let mut book =
        json!({"items": [chapter("ops.md", "```{rule} Renderer:Step.allocVariable\nP\n```")]});
    assert!(
        process(&mut book).is_err(),
        "Lean selection requires a source root"
    );
}
}
mdbook-dada/tests/book.rs:authored_math_rejects_missing_or_wrong_kind_source_selections
#![allow(unused)]
fn main() {
#[test]
fn authored_math_rejects_missing_or_wrong_kind_source_selections() {
    let root = lean_fixtures();
    for (kind, target) in [
        ("judgment", "Missing:Step"),
        ("judgment", "Renderer:Missing"),
        ("judgment", "Renderer:VariableId"),
        ("rule", "Renderer:Step.missing"),
        ("rule", "Renderer:Step"),
        ("rule", "Renderer:VariableId.index"),
        ("rule", "../Renderer:Step.allocVariable"),
    ] {
        let mut book =
            json!({"items": [chapter("ops.md", &format!("```{{{kind}}} {target}\nP\n```"))]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains("ops.md"), "{kind} {target}");
        if target.starts_with("Renderer:VariableId") {
            assert!(
                message.contains("must select inductive declarations"),
                "{kind} {target}: {message}"
            );
        }
    }
}
}
mdbook-dada/src/lean.rs:tests::selects_a_case_without_interpreting_its_binders
#![allow(unused)]
fn main() {
#[test]
    fn selects_a_case_without_interpreting_its_binders() {
        let source = "inductive J : Nat → Prop where\n  -- | decoy : J 0\n  | first {n : Nat} (proof : Unknown n) :\n      J (match n with\n        | 0 => 0\n        | k => k)\n  | second : J 1\n";
        let first = extract_case(source, "first").unwrap();
        assert!(first.starts_with("inductive J : Nat → Prop where\n  | first"));
        assert!(first.contains("Unknown n"));
        assert!(first.contains("| k => k"));
        assert!(!first.contains("second"));
        assert!(extract_case(source, "decoy").is_err());
        assert!(!extract_case(
            "inductive J where\n  | r\n-- Next declaration documentation",
            "r"
        )
        .unwrap()
        .contains("documentation"));
        assert!(extract_case(source, "k").is_err());
        assert!(
            extract_case("inductive J : Prop where\n  | intro{n : Nat} : J", "intro")
                .unwrap()
                .contains("intro{n")
        );
        assert!(extract_case("inductive J where\n  | r\n  | r\n", "r").is_err());
    }
}

A theorem or lemma selects exactly one named Lean theorem, including its statement and := proof body. Definitions, axioms, and anonymous examples are rejected as targets. Multiline statements use indented continuations; neighboring declarations are excluded. The distinction between theorem and lemma is the author’s presentation choice.

definitionmeta.math.theorem.validation The renderer checks source selection, not the proof. Lean compilation and correspondence review are separate: Lean checks the proof; review compares the statement’s assumptions, quantifiers, and conclusion with the authored claim.

definitionmeta.syntax.nesting Definition, theorem, lemma, and example bodies cannot nest any of those four block kinds.

mdbook-dada/src/lean.rs:select
#![allow(unused)]
fn main() {
/// Resolve a citation with the same declaration-kind checks as the renderer.
pub fn select(root: &Path, target: &str, kind: crate::units::UnitKind) -> Result<LeanSelection> {
    use crate::units::UnitKind;
    ensure!(
        kind != UnitKind::FutureNote,
        "future notes cannot have formalization citations"
    );
    let (source, name) = read_source(root, target)?;
    let selected = match kind {
        UnitKind::FutureNote => unreachable!("rejected above"),
        UnitKind::Definition => extract_definition(&source, &name),
        UnitKind::Theorem | UnitKind::Lemma => extract_theorem(&source, &name),
        UnitKind::Example => extract_example(&source, &name),
        UnitKind::Grammar => extract(&source, &name),
        UnitKind::Judgment => extract(&source, &name).and_then(|declaration| {
            ensure!(
                declaration.starts_with("inductive "),
                "judgment citation must select an inductive declaration"
            );
            Ok(declaration)
        }),
        UnitKind::Rule => {
            let (name, case) = name
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            extract(&source, name).and_then(|declaration| extract_case(&declaration, case))
        }
    }
    .with_context(|| target.to_owned())?;
    let (file, _) = target
        .rsplit_once(':')
        .context("expected path:Declaration")?;
    let mut relative = std::path::PathBuf::from(file);
    if relative.extension().is_none() {
        relative.set_extension("lean");
    }
    // read_source already checks canonical containment, including symlinks.
    let path = root.join(relative).canonicalize()?;
    Ok(LeanSelection {
        path,
        source,
        selected,
    })
}
}
mdbook-dada/src/lean.rs:extract_declaration
#![allow(unused)]
fn main() {
fn extract_declaration(source: &str, name: &str, selection: Selection) -> Result<String> {
    let simple_name = |component: &str| {
        !component.is_empty() && component.chars().all(|c| c.is_alphanumeric() || c == '_')
    };
    if selection != Selection::Type {
        ensure!(
            name.split('.').all(simple_name),
            "use a declaration name with nonempty identifier components separated by single dots"
        );
    } else {
        ensure!(
            simple_name(name),
            "use a simple unqualified declaration name"
        );
    }
    let masked = mask(source)?;
    validate_mutual_groups(&masked)?;
    let mut found = Vec::new();
    let mut offset = 0;
    let lines: Vec<_> = masked
        .split_inclusive('\n')
        .map(|line| {
            let start = offset;
            offset += line.len();
            (start, line)
        })
        .collect();
    let structure_field = regex::Regex::new(r"^[ \t]+[A-Za-z_][A-Za-z0-9_']*[ \t]*:(?:[^:=]|$)")?;
    for (i, &(start, line)) in lines.iter().enumerate() {
        let words: Vec<_> = line.split_whitespace().collect();
        if selection == Selection::Definition {
            let declaration: Vec<_> = words
                .iter()
                .copied()
                .skip_while(|word| {
                    matches!(
                        *word,
                        "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
                    )
                })
                .collect();
            // Literal names are intentionally not resolved through namespaces.
            // A same-named declaration of the wrong kind must not disappear
            // from an otherwise ambiguous citation.
            if declaration.get(1) == Some(&name)
                && matches!(
                    declaration.first(),
                    Some(
                        &"def"
                            | &"abbrev"
                            | &"structure"
                            | &"inductive"
                            | &"theorem"
                            | &"lemma"
                            | &"axiom"
                            | &"opaque"
                            | &"constant"
                            | &"class"
                    )
                )
            {
                ensure!(
                    declaration.len() == words.len(),
                    "declaration modifiers are unsupported"
                );
                ensure!(
                    matches!(declaration.first(), Some(&"def" | &"abbrev" | &"structure" | &"inductive")),
                    "definition citations must select def, abbrev, structure, or inductive declarations"
                );
            }
        }
        if words.get(1) != Some(&name) {
            continue;
        }
        let supported = match selection {
            Selection::Theorem => words.first() == Some(&"theorem"),
            Selection::Type => {
                matches!(words.first(), Some(&"inductive" | &"structure" | &"abbrev"))
            }
            Selection::Definition => matches!(
                words.first(),
                Some(&"def" | &"inductive" | &"structure" | &"abbrev")
            ),
        };
        if !supported {
            continue;
        }
        ensure!(
            !line.starts_with(char::is_whitespace),
            "selected Lean declarations must begin at column zero"
        );
        if let Some((_, previous)) = lines[..i].iter().rev().find(|(_, l)| !l.trim().is_empty()) {
            ensure!(
                !previous.trim_start().starts_with("@["),
                "declaration attributes are unsupported"
            );
        }
        if let Some((_, boundary)) = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
        {
            let mut words = boundary.split_whitespace();
            let first = words.next().unwrap_or("");
            let mut word = first;
            while matches!(
                word,
                "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
            ) {
                word = words.next().unwrap_or("");
            }
            ensure!(
                (word == first
                    || matches!(
                        word,
                        "inductive" | "structure" | "abbrev" | "def" | "theorem" | "instance"
                    ))
                    && matches!(
                        word,
                        "inductive"
                            | "structure"
                            | "abbrev"
                            | "def"
                            | "theorem"
                            | "lemma"
                            | "example"
                            | "instance"
                            | "end"
                            | "namespace"
                            | "section"
                            | "mutual"
                            | "variable"
                            | "open"
                            | "#check"
                    ),
                "unsupported declaration boundary `{}`; continuation lines must be indented",
                boundary.trim()
            );
        }
        let end = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
            .map(|(n, _)| *n)
            .unwrap_or(source.len());
        let body = &source[start..end];
        let text = &body[..scan(body)?.content_end];
        {
            let code = &masked[start..end];
            // A structure field such as `variables : Store` is not a command.
            // Only exempt a bare, indented field name followed by a type colon;
            // `variable (x : Nat)` and `def sibling := ...` remain commands.
            let commands = command_pattern()?
                .find_iter(code)
                .filter(|command| {
                    words[0] != "structure"
                        || !structure_field
                            .is_match(code[command.start()..].lines().next().unwrap_or(""))
                })
                .count();
            ensure!(
                commands == 1,
                "selected declaration must contain no other commands, even when indented"
            );
        }
        if selection == Selection::Theorem {
            ensure!(
                has_definition_body(&masked[start..end]),
                "theorem must include its proof body (`:=`)"
            );
        } else if selection == Selection::Definition && words[0] == "def" {
            ensure!(
                has_named_definition_body(&masked[start..end])?,
                "definition must include a body (`:=`, `where`, or indented equations with `=>`)"
            );
        } else if words[0] != "abbrev" {
            ensure!(
                line.contains("where"),
                "declaration header must contain `where` on its first line"
            );
        } else {
            if selection == Selection::Definition {
                ensure!(
                    has_definition_body(&masked[start..end]),
                    "abbreviation must include a body (`:=`)"
                );
            } else {
                ensure!(line.contains(":="), "abbreviation header must contain `:=`");
            }
        }
        found.push(text.to_owned());
    }
    ensure!(
        found.len() == 1,
        "expected one supported declaration `{name}`, found {}",
        found.len()
    );
    Ok(found.remove(0))
}
}
mdbook-dada/src/lean.rs:theorem_source
#![allow(unused)]
fn main() {
/// Select exactly one named theorem, preserving its statement and complete proof.
/// Theorem and lemma Markdown blocks share this source-selection contract.
pub fn theorem_source(root: &Path, target: &str) -> Result<String> {
    let (source, name) = read_source(root, target)?;
    let theorem = extract_theorem(&source, &name).with_context(|| target.to_owned())?;
    Ok(format!(
        "<figcaption>{}</figcaption><pre><code class=\"language-lean\">{}</code></pre>",
        crate::escape(target),
        highlighted(&theorem)?
    ))
}
}
mdbook-dada/src/lib.rs:chapter_roles
#![allow(unused)]
fn main() {
fn chapter_roles(source: &str) -> Result<Vec<Role>> {
    let protected = protect_math(source);
    let mut found = roles(&protected)?;
    for unit in units::parse(source, "chapter")? {
        found.push(Role {
            range: unit.range,
            id: unit.id,
            definition: true,
            label: None,
            lean: false,
        });
    }
    for block in directive_blocks(&protected) {
        if block
            .info
            .split_whitespace()
            .next()
            .is_some_and(|name| MarkdownDirective::parse(name).is_some() || name == "{future-note}")
        {
            // These bodies are Markdown; grammar, judgment, and rule bodies are TeX.
            ensure!(
                !directive_blocks(&block.body).iter().any(|nested| {
                    ["{definition}", "{example}", "{theorem}", "{lemma}", "{future-note}"]
                        .iter()
                        .any(|name| nested.info.starts_with(name))
                }),
                "definition, example, theorem, and lemma directives cannot be nested within one another"
            );
            found.extend(roles(&protect_math(&block.body))?);
        }
    }
    Ok(found)
}
}
mdbook-dada/tests/book.rs:authored_theorems_show_the_exact_named_statement_and_proof
#![allow(unused)]
fn main() {
#[test]
fn authored_theorems_show_the_exact_named_statement_and_proof() {
    let root = lean_fixtures();
    let source = r"```{theorem} Renderer.lean:deallocVariable_requires_top
A successful deallocation removes the top slot.

\\[
S \xrightarrow{\mathsf{deallocVariable}(x)} S' \implies \operatorname{top}(V) = x
\\]

**Proof outline.** Inspect the deallocation constructor's top-slot premise.
```";
    let mut book = json!({"items": [chapter("invariants.md", source)]});
    mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
    let html = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(html.contains(r"\implies \operatorname{top}(V) = x"));
    assert!(html.contains("Renderer.lean:deallocVariable_requires_top"));
    assert!(html.contains("lean-keyword\">theorem</span> deallocVariable_requires_top"));
    assert!(html.contains("cases step"));
    assert!(!html.contains("theorem</span> deallocVariable_pops"));
    assert_eq!(html.matches("class=\"lean-selector\"").count(), 1);
    assert_eq!(html.matches("> Rendered</label>").count(), 1);
    assert_eq!(html.matches("> Lean</label>").count(), 1);
}
}
mdbook-dada/tests/book.rs:authored_theorems_select_literal_qualified_names
#![allow(unused)]
fn main() {
#[test]
fn authored_theorems_select_literal_qualified_names() {
    let root = lean_fixtures();
    let source = r"```{theorem} Renderer:Transfer.preserves_count
Copying a list preserves its length.

\\[P \implies Q\\]
```";
    let mut book = json!({"items": [chapter("moves.md", source)]});
    mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
    let html = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(html.contains("Renderer:Transfer.preserves_count"));
    assert!(html.contains("lean-keyword\">theorem</span> Transfer.preserves_count"));
    assert!(html.contains("copy_preserves_count written"));
    assert!(!html.contains("theorem</span> Transfer.read"));
    for citation in [
        "Renderer:RendererFixture.Transfer.preserves_count",
        "Renderer:Transfer..preserves_count",
        "Renderer:.Transfer.preserves_count",
        "Renderer:Transfer.preserves_count.",
    ] {
        let source = format!("```{{theorem}} {citation}\nP\n```");
        let mut book = json!({"items": [chapter("moves.md", &source)]});
        assert!(mdbook_dada::process_with_lean(&mut book, Some(&root)).is_err());
    }
}
}
mdbook-dada/tests/book.rs:authored_theorems_reject_wrong_kinds_and_malformed_directives
#![allow(unused)]
fn main() {
#[test]
fn authored_theorems_reject_wrong_kinds_and_malformed_directives() {
    let root = lean_fixtures();
    for source in [
        "```{theorem}\nP\n```",
        "```{theorem}Renderer:deallocVariable_requires_top\nP\n```",
        "```{theorem} Renderer:deallocVariable_requires_top Renderer:deallocVariable_pops\nP\n```",
        "```{theorem} Renderer:deallocVariable_requires_top\n \n```",
        "```{theorem} Renderer:Step\nP\n```",
        "```{theorem} Renderer:Step.allocVariable\nP\n```",
        "```{theorem} Renderer:integer_primitive\nP\n```",
        "```{theorem} Renderer:initialFields\nP\n```",
        "```{theorem} Renderer:missing\nP\n```",
        "```{theorem} Missing:theorem\nP\n```",
        "```{theorem} ../Renderer:deallocVariable_requires_top\nP\n```",
    ] {
        let mut book = json!({"items": [chapter("invariants.md", source)]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).expect_err(source);
        assert!(format!("{error:#}").contains("invariants.md"), "{source}");
    }
    let mut missing_root = json!({"items": [chapter("invariants.md", "```{theorem} Renderer:deallocVariable_requires_top\nP\n```")]});
    assert!(process(&mut missing_root).is_err());
    let literal = "````text\n```{theorem} Missing:nope\nP\n```\n````";
    let mut book = json!({"items": [chapter("invariants.md", literal)]});
    process(&mut book).unwrap();
    assert_eq!(book["items"][0]["Chapter"]["content"], literal);
}
}
mdbook-dada/tests/book.rs:markdown_proof_blocks_reject_invalid_targets_and_all_nested_proof_kinds
#![allow(unused)]
fn main() {
#[test]
fn markdown_proof_blocks_reject_invalid_targets_and_all_nested_proof_kinds() {
    let root = lean_fixtures();
    for kind in ["theorem", "lemma"] {
        for citation in [
            "",
            "Renderer:Step",
            "Renderer:Step.allocVariable",
            "Renderer:initialFields",
            "Renderer:integer_primitive",
            "Renderer:missing",
            "Missing:proof",
            "../Renderer:deallocVariable_requires_top",
            "Renderer:deallocVariable_requires_top Renderer:deallocVariable_pops",
        ] {
            let source = format!("```{{{kind}}} {citation}\nClaim.\n```");
            let mut book = json!({"items": [chapter("proofs.md", &source)]});
            assert!(
                mdbook_dada::process_with_lean(&mut book, Some(&root)).is_err(),
                "{source}"
            );
        }
        for source in [
            format!("```{{{kind}}}Renderer:deallocVariable_requires_top\nClaim.\n```"),
            format!("```{{{kind}}} Renderer:deallocVariable_requires_top\n \n```"),
        ] {
            let mut book = json!({"items": [chapter("proofs.md", &source)]});
            assert!(
                mdbook_dada::process_with_lean(&mut book, Some(&root)).is_err(),
                "{source}"
            );
        }
    }
    let targets = [
        ("definition", "Renderer:readSlot"),
        ("example", "Renderer:integer_primitive"),
        ("theorem", "Renderer:deallocVariable_requires_top"),
        ("lemma", "Renderer:deallocVariable_requires_top"),
    ];
    for (outer, outer_target) in targets {
        for (inner, inner_target) in targets {
            let source = format!(
                "````{{{outer}}} {outer_target}\n```{{{inner}}} {inner_target}\nNested.\n```\n````"
            );
            let mut book = json!({"items": [chapter("proofs.md", &source)]});
            let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap_err();
            assert!(
                format!("{error:#}").contains("cannot be nested"),
                "{source}"
            );
        }
    }
    let literal = "````text\n```{lemma} Missing:nope\nLiteral.\n```\n````";
    let mut book = json!({"items": [chapter("proofs.md", literal)]});
    process(&mut book).unwrap();
    assert_eq!(book["items"][0]["Chapter"]["content"], literal);
}
}
mdbook-dada/src/lean.rs:tests::selects_complete_named_theorems_without_comment_or_string_decoys
#![allow(unused)]
fn main() {
#[test]
    fn selects_complete_named_theorems_without_comment_or_string_decoys() {
        let source = r#"-- theorem preserves : False := by sorry
def text := "theorem preserves : False := by sorry"
/- theorem preserves : False := by sorry -/
theorem preserves
    (n : Nat)
    (h : n = 0) : n = 0 := by
  have same : n = 0 := h
  exact same
theorem next : True := by trivial
"#;
        let selected = extract_theorem(source, "preserves").unwrap();
        assert!(selected.starts_with("theorem preserves\n"));
        assert!(selected.ends_with("  exact same"));
        assert!(!selected.contains("sorry"));
        assert!(!selected.contains("theorem next"));
        assert_eq!(
            extract_theorem(source, "next").unwrap(),
            "theorem next : True := by trivial"
        );
        assert!(extract(source, "preserves").is_err());
    }
}
mdbook-dada/src/lean.rs:tests::rejects_wrong_kind_ambiguous_and_incomplete_theorem_selections
#![allow(unused)]
fn main() {
#[test]
    fn rejects_wrong_kind_ambiguous_and_incomplete_theorem_selections() {
        for source in [
            "def selected : True := by trivial",
            "axiom selected : True",
            "example : True := by trivial",
            "inductive selected : Prop where\n  | intro",
            "theorem selected : True := by trivial\ntheorem selected : True := by trivial",
            "theorem selected : True",
            "theorem selected (n : Nat := 0) : True",
            "@[simp]\ntheorem selected : True := by trivial",
            "  theorem selected : True := by trivial",
            "theorem selected : True := by\ntrivial",
            "theorem selected : True := by trivial\n  theorem next : True := by trivial",
            "theorem selected : True := by trivial\n  def next := 0",
        ] {
            assert!(extract_theorem(source, "selected").is_err(), "{source}");
        }
        assert!(extract_theorem("theorem selected : True := by trivial", "missing").is_err());
        assert!(extract_theorem("theorem selected : True := by trivial", "N.selected").is_err());
    }
}

An example citation selects a region between standalone Lean comments -- ANCHOR: name and -- ANCHOR_END: name. That region contains exactly one anonymous example proof, with optional comments and whitespace. The example and following command start at column zero; proof continuations are indented. The closing marker cannot truncate the proof or hide another command. Markers are excluded from displayed source. Their name is local to the file, not a Lean declaration name or a book ID.

definitionmeta.syntax.example A structured example has an ID, one :lean: citation, and an authored Markdown body. Its header says Example and initially displays the rendered body.

definitionmeta.examples.markdown The body supports paragraphs, lists, links, code, explicit math, roles, and heap diagrams. Longer enclosing fences permit literal fenced examples inside it. The nesting restrictions still apply.

definitionmeta.examples.validation Missing, duplicate, or malformed regions, unsupported proof forms, malformed citations, and empty bodies fail the build. Selecting the test does not elaborate or run it.

mdbook-dada/src/lean.rs:extract_example
#![allow(unused)]
fn main() {
fn extract_example(source: &str, name: &str) -> Result<String> {
    ensure!(
        valid_anchor_name(name),
        "invalid Lean example anchor `{name}`"
    );
    let (masked, comments) = mask_and_comments(source)?;
    let mut names = HashSet::new();
    let mut open = None;
    let mut selected = None;
    for offset in comments {
        let line_start = source[..offset].rfind('\n').map_or(0, |n| n + 1);
        if !source[line_start..offset].trim().is_empty() {
            continue;
        }
        let line_end = source[offset..]
            .find('\n')
            .map_or(source.len(), |n| offset + n);
        let comment = source[offset + 2..line_end].trim();
        let (end, anchor) = if let Some(anchor) = comment.strip_prefix("ANCHOR:") {
            (false, anchor.trim())
        } else if let Some(anchor) = comment.strip_prefix("ANCHOR_END:") {
            (true, anchor.trim())
        } else {
            continue;
        };
        ensure!(
            valid_anchor_name(anchor),
            "invalid Lean example anchor `{anchor}`"
        );
        if end {
            let (opened, start) = open.take().with_context(|| {
                format!("Lean example anchor `{anchor}` ends without a matching start")
            })?;
            ensure!(
                opened == anchor,
                "Lean example anchor `{opened}` ends with mismatched `{anchor}`"
            );
            if anchor == name {
                selected = Some((start..line_start, (line_end + 1).min(source.len())));
            }
        } else {
            ensure!(open.is_none(), "nested Lean example anchor `{anchor}`");
            ensure!(
                names.insert(anchor),
                "duplicate Lean example anchor `{anchor}`"
            );
            open = Some((anchor, (line_end + 1).min(source.len())));
        }
    }
    if let Some((anchor, _)) = open {
        anyhow::bail!("unterminated Lean example anchor `{anchor}`");
    }
    let (range, after) =
        selected.with_context(|| format!("missing Lean example anchor `{name}`"))?;
    if let Some(next) = masked[after..].lines().find(|line| !line.trim().is_empty()) {
        ensure!(
            !next.starts_with(char::is_whitespace),
            "Lean example anchor `{name}` ends before an indented continuation; place the end marker after the complete example and start the next command at column zero"
        );
    }
    let mut lines = masked[range.clone()]
        .lines()
        .filter(|line| !line.trim().is_empty());
    let header = lines
        .next()
        .with_context(|| format!("Lean example anchor `{name}` is empty"))?;
    let keyword = header
        .split(|c: char| c.is_whitespace() || matches!(c, ':' | '(' | '{' | '['))
        .next();
    ensure!(
        keyword == Some("example"),
        "Lean example anchor `{name}` must contain a column-zero anonymous `example`"
    );
    ensure!(
        lines.all(|line| line.starts_with(char::is_whitespace)),
        "Lean example anchor `{name}` must contain exactly one `example`; continuation lines must be indented"
    );
    // Lean allows sibling commands to be indented. Indentation alone therefore
    // cannot establish that a marked span contains only the selected example.
    // This restricted source style excludes command declarations inside proofs.
    let command = command_pattern()?;
    let declaration_count = command.find_iter(&masked[range.clone()]).count();
    let example_count = regex::Regex::new(r"\bexample\b")?
        .find_iter(&masked[range.clone()])
        .count();
    ensure!(
        declaration_count == 1 && example_count == 1,
        "Lean example anchor `{name}` must contain exactly one `example` and no other commands, even when indented"
    );
    ensure!(
        has_definition_body(&masked[range.clone()]),
        "Lean example anchor `{name}` must include the example body (`:=`)"
    );
    // Preserve code indentation while excluding surrounding blank lines and the
    // anchor markers. Comments documenting the example remain visible.
    Ok(source[range].trim_matches(['\n', '\r']).to_owned())
}
}
mdbook-dada/src/lean.rs:example_source
#![allow(unused)]
fn main() {
/// Select a marked anonymous Lean example and render its cited source.
/// This checks the marker structure, not Lean elaboration or prose agreement.
pub fn example_source(root: &Path, target: &str) -> Result<String> {
    let (source, anchor) = read_source(root, target)?;
    let example = extract_example(&source, &anchor).with_context(|| target.to_owned())?;
    Ok(format!(
        "<figcaption>{}</figcaption><pre><code class=\"language-lean\">{}</code></pre>",
        crate::escape(target),
        highlighted(&example)?
    ))
}
}
mdbook-dada/src/lib.rs:render
#![allow(unused)]
fn main() {
fn render(
    source: &str,
    path: &str,
    anchors: &BTreeMap<String, String>,
    lean_root: Option<&Path>,
    project_root: Option<&Path>,
    scope: &str,
    definition_label: &str,
) -> Result<String> {
    let protected = protect_math(source);
    let source = protected.as_str();
    let structured_units = units::parse(source, path)?;
    let mut edits = vec![];
    for role in roles(source)? {
        let rendered = render_role(&role, path, anchors, definition_label)?;
        edits.push((role.range, rendered));
    }
    for (event, range) in Parser::new(source).into_offset_iter() {
        if matches!(event, Event::Start(Tag::Paragraph)) {
            ensure!(
                !source[range.clone()].starts_with("{example} "),
                "the paragraph {{example}} marker has been replaced: use a fenced ```{{example}} path:anchor with a Markdown body and a Lean test, or label an unfinished scenario as informational"
            );
            if source[range.clone()].starts_with("{informational} ") {
                edits.push((
                    range.start..range.start + "{informational}".len(),
                    "<span class=\"informational-label\">Informational</span>".to_owned(),
                ));
            }
        }
    }

    for block in directive_blocks(source) {
        if let Some(unit) = structured_units
            .iter()
            .find(|unit| unit.range.start == block.range.start)
        {
            for dependency in &unit.uses {
                ensure!(
                    anchors.contains_key(dependency),
                    "unknown unit dependency `{dependency}`"
                );
            }
            edits.push((
                block.range,
                render_unit(unit, path, anchors, lean_root, project_root)?,
            ));
            continue;
        }
        let start = block.range.start;
        let kind = block.info;
        let facts = block.body;
        let (directive, argument) = kind.split_once(char::is_whitespace).unwrap_or((&kind, ""));
        ensure!(
            ![
                "{heap}",
                "{grammar}",
                "{rule}",
                "{judgment}",
                "{definition}",
                "{theorem}",
                "{lemma}",
                "{example}",
                "{future-note}"
            ]
            .iter()
            .any(|name| directive.starts_with(name) && directive != *name),
            "separate the directive name and citation with whitespace"
        );
        ensure!(!matches!(directive, "{lean.type}" | "{lean.judgment}" | "{lean.rule}"),
                        "{directive} has been replaced: use ```{{grammar}} path:Name, ```{{judgment}} path:Name, or ```{{rule}} path:Name.case with authored LaTeX in the body");
        let id = format!("{scope}-{start}");
        if let Some(markdown) = MarkdownDirective::parse(directive) {
            let name = markdown.name();
            let label = markdown.label();
            let citations = argument.split_whitespace().count();
            if matches!(markdown, MarkdownDirective::Definition) {
                ensure!(
                    citations > 0,
                    "definition requires at least one opening-line citation"
                );
            } else {
                ensure!(
                    citations == 1,
                    "{name} requires exactly one opening-line citation"
                );
            }
            ensure!(!facts.trim().is_empty(), "{name} requires a Markdown body");
            let root =
                lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
            let lean_source = match markdown {
                MarkdownDirective::Definition => lean::definition_source(root, argument)?,
                MarkdownDirective::Example => lean::example_source(root, argument.trim())?,
                MarkdownDirective::Theorem | MarkdownDirective::Lemma => {
                    lean::theorem_source(root, argument.trim())?
                }
            };
            let heading_label = if matches!(markdown, MarkdownDirective::Example) {
                "example"
            } else {
                markdown.definition_label()
            };
            let (heading, body) = markdown_heading(&facts, path, anchors, heading_label)?;
            ensure!(
                !body.trim().is_empty(),
                "{name} requires a Markdown body after its heading anchors"
            );
            let body = render(
                body,
                path,
                anchors,
                lean_root,
                project_root,
                &id,
                markdown.definition_label(),
            )?;
            let selector = selector_header(
                label,
                (!heading.is_empty()).then_some(heading.as_str()),
                &format!("{name}-{id}"),
                "rendered",
                "Lean",
            );
            // Blank lines terminate raw HTML blocks so mdBook renders the body
            // as Markdown, including its explicit math delimiters and proof prose.
            edits.push((block.range, format!(
                "\n<figure class=\"lean-declaration lean-group lean-markdown lean-{name}\">{selector}<div class=\"lean-markdown-body\">\n\n{}\n\n</div><div class=\"lean-source\">{lean_source}</div></figure>\n\n",
                body.trim_matches('\n')
            )));
            continue;
        }
        let view = match directive {
            "{grammar}" => Some(lean::View::Grammar),
            "{judgment}" => Some(lean::View::Judgment),
            "{rule}" => Some(lean::View::Rule),
            _ => None,
        };
        if let Some(view) = view {
            let root =
                lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
            edits.push((
                block.range,
                format!(
                    "\n{}\n",
                    lean::render_authored(root, argument.trim(), &facts, view, &id)?
                ),
            ));
            continue;
        }
        ensure!(
            argument.trim().is_empty(),
            "{directive} does not accept opening-line arguments"
        );
        let graph = graph::render(&facts)?;
        let selector = selector_header("Diagram", None, &format!("heap-{id}"), "rendered", "Facts");
        let source = escape(&facts).replace('\n', "&#10;");
        edits.push((block.range, format!("\n<figure class=\"heap-figure\">{selector}{graph}<pre class=\"heap-facts\"><code>{source}</code></pre></figure>\n")));
    }
    edits.sort_by_key(|(range, _)| range.start);
    let mut result = String::new();
    let mut end = 0;
    for (range, replacement) in edits {
        ensure!(range.start >= end, "overlapping markup");
        result.push_str(&source[end..range.start]);
        result.push_str(&replacement);
        end = range.end;
    }
    result.push_str(&source[end..]);
    Ok(result)
}
}
mdbook-dada/src/lib.rs:chapter_roles
#![allow(unused)]
fn main() {
fn chapter_roles(source: &str) -> Result<Vec<Role>> {
    let protected = protect_math(source);
    let mut found = roles(&protected)?;
    for unit in units::parse(source, "chapter")? {
        found.push(Role {
            range: unit.range,
            id: unit.id,
            definition: true,
            label: None,
            lean: false,
        });
    }
    for block in directive_blocks(&protected) {
        if block
            .info
            .split_whitespace()
            .next()
            .is_some_and(|name| MarkdownDirective::parse(name).is_some() || name == "{future-note}")
        {
            // These bodies are Markdown; grammar, judgment, and rule bodies are TeX.
            ensure!(
                !directive_blocks(&block.body).iter().any(|nested| {
                    ["{definition}", "{example}", "{theorem}", "{lemma}", "{future-note}"]
                        .iter()
                        .any(|name| nested.info.starts_with(name))
                }),
                "definition, example, theorem, and lemma directives cannot be nested within one another"
            );
            found.extend(roles(&protect_math(&block.body))?);
        }
    }
    Ok(found)
}
}
mdbook-dada/tests/book.rs:linked_examples_preserve_native_markdown_and_select_one_lean_test
#![allow(unused)]
fn main() {
#[test]
fn linked_examples_preserve_native_markdown_and_select_one_lean_test() {
    use pulldown_cmark::{Event, Parser, Tag};

    let root = lean_fixtures();
    let source = r"Before.

````{example} Renderer:integer_primitive
**Create an integer.** See [the state](state.md).

1. Allocate `x`.
2. Create the value.

```text
createPrimitive(22, x)
```

After the operation, the payload is \\(22\\).
````

After.
";
    let mut book = json!({"items": [chapter("examples.md", source)]});
    mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
    let output = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(output.contains("aria-label=\"Example view\""));
    assert!(output.contains("Renderer:integer_primitive"));
    assert!(output.contains("Step Int allocated (.createPrimitive 22 x) created"));
    assert!(!output.contains("createAggregate"));
    assert!(!output.contains("ANCHOR_END"));
    assert!(output.contains("<span class=\"math-inline\">&#92;&#40;22&#92;&#41;</span>"));
    // The HTML wrapper must leave the authored body to mdBook's Markdown parser.
    let events: Vec<_> = Parser::new(output).collect();
    assert!(events
        .iter()
        .any(|e| matches!(e, Event::Start(Tag::Strong))));
    assert!(events
        .iter()
        .any(|e| matches!(e, Event::Start(Tag::List(Some(1))))));
    assert!(events.iter().any(
        |e| matches!(e, Event::Start(Tag::Link { dest_url, .. }) if dest_url.as_ref() == "state.md")
    ));
    assert!(events
        .iter()
        .any(|e| matches!(e, Event::Start(Tag::CodeBlock(_)))));
    assert!(events
        .iter()
        .any(|e| matches!(e, Event::Text(text) if text.as_ref() == "After.")));

    let mut indented = json!({"items": [chapter("examples.md", "```{example} Renderer:integer_primitive\n    createPrimitive(22, x)\n```")]});
    mdbook_dada::process_with_lean(&mut indented, Some(&root)).unwrap();
    let output = indented["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(Parser::new(output).any(|e| matches!(
        e,
        Event::Start(Tag::CodeBlock(pulldown_cmark::CodeBlockKind::Indented))
    )));
}
}
mdbook-dada/tests/book.rs:linked_example_bodies_index_anchors_and_scope_nested_selectors
#![allow(unused)]
fn main() {
#[test]
fn linked_example_bodies_index_anchors_and_scope_nested_selectors() {
    let root = lean_fixtures();
    let example = r"````{example} Renderer:nested_variables
See {anchor-ref}`outer`.

{anchor}`inner` The inner scope is removed.

```{heap}
vars = variables()
vars.x = uninitialized()
```

```{grammar} Renderer:Slot
s ::= \bot
```
````";
    let mut book = json!({"items": [
        chapter("intro.md", "{anchor}`outer` See {anchor-ref}`inner`."),
        chapter("examples/scopes.md", example),
        chapter("examples/another.md", &example.replace("{anchor}`inner`", "{anchor-ref}`inner`"))
    ]});
    mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
    let text = book["items"][1]["Chapter"]["content"].as_str().unwrap();
    assert!(text.contains("../intro.html#claim-outer"));
    assert!(text.contains("id=\"claim-inner\""));
    assert!(text.contains("<svg"));
    assert!(text.contains("math-display"));
    assert!(book["items"][0]["Chapter"]["content"]
        .as_str()
        .unwrap()
        .contains("examples/scopes.html#claim-inner"));
    let all = book.to_string();
    let names: Vec<_> = regex::Regex::new(r#"type="radio" name="([^"]+)""#)
        .unwrap()
        .captures_iter(text)
        .map(|c| c[1].to_owned())
        .collect();
    assert_eq!(names.len(), 6);
    assert_eq!(
        names
            .iter()
            .collect::<std::collections::BTreeSet<_>>()
            .len(),
        3
    );
    assert!(all.contains("another.md"));

    let mut duplicate =
        json!({"items": [chapter("a.md", example), chapter("b.md", "{anchor}`inner`")]});
    assert!(format!(
        "{:#}",
        mdbook_dada::process_with_lean(&mut duplicate, Some(&root)).unwrap_err()
    )
    .contains("duplicate anchor"));
}
}
mdbook-dada/tests/book.rs:linked_examples_fail_on_invalid_citations_bodies_or_nesting
#![allow(unused)]
fn main() {
#[test]
fn linked_examples_fail_on_invalid_citations_bodies_or_nesting() {
    let root = lean_fixtures();
    for source in [
        "```{example}\nBody.\n```",
        "```{example}Renderer:integer_primitive\nBody.\n```",
        "```{example} Renderer:integer_primitive Renderer:empty_array\nBody.\n```",
        "```{example} Renderer:integer_primitive\n  \n```",
        "```{example} Renderer:missing\nBody.\n```",
        "```{example} Renderer:Step\nBody.\n```",
        "```{example} ../Renderer:integer_primitive\nBody.\n```",
        "````{example} Renderer:integer_primitive\n```{example} Renderer:empty_array\nNested.\n```\n````",
    ] {
        let mut book = json!({"items": [chapter("examples.md", source)]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).expect_err(source);
        assert!(format!("{error:#}").contains("examples.md"), "{source}");
    }
    let mut missing_root = json!({"items": [chapter("examples.md", "```{example} Renderer:integer_primitive\nBody.\n```")]});
    assert!(process(&mut missing_root).is_err());
    let literal = "````text\n```{example} Missing:nope\nLiteral.\n```\n````\n\n    ```{example} Missing:nope\n    Literal.\n    ```";
    let mut book = json!({"items": [chapter("examples.md", literal)]});
    process(&mut book).unwrap();
    assert_eq!(book["items"][0]["Chapter"]["content"], literal);
}
}
mdbook-dada/src/lean.rs:tests::ignores_anchor_decoys_in_strings_block_comments_and_inline_comments
#![allow(unused)]
fn main() {
#[test]
    fn ignores_anchor_decoys_in_strings_block_comments_and_inline_comments() {
        let source = r#"/-
-- ANCHOR: absent
  /- -- ANCHOR_END: mismatched -/
-- ANCHOR: actual
-/
def text := "
-- ANCHOR_END: absent
-- ANCHOR: actual
"
def inline := 0 -- ANCHOR: actual
-- A comment containing -- ANCHOR: actual
-- ANCHOR: actual
example : "-- ANCHOR_END: actual" = "-- ANCHOR_END: actual" := by
  rfl
-- ANCHOR_END: actual
"#;
        let example = extract_example(source, "actual").unwrap();
        assert!(example.starts_with("example :"));
        assert!(example.contains("  rfl"));
        assert!(extract_example(source, "absent").is_err());
    }
}
mdbook-dada/src/lean.rs:tests::requires_one_complete_anonymous_example
#![allow(unused)]
fn main() {
#[test]
    fn requires_one_complete_anonymous_example() {
        for (body, message) in [
            ("", "empty"),
            ("-- only a comment\n/- no proof -/", "empty"),
            ("def test := 0", "anonymous `example`"),
            ("  example : True := by trivial", "column-zero"),
            (
                "example : True := by trivial\nexample : True := by trivial",
                "exactly one",
            ),
            (
                "example : True := by trivial\ndef extra := 0",
                "exactly one",
            ),
            (
                "example : True := by trivial\n  example : True := by trivial",
                "exactly one",
            ),
            (
                "example : True := by trivial\n  def extra := 0",
                "exactly one",
            ),
            (
                "example : True := by trivial\n  private theorem extra : True := by trivial",
                "exactly one",
            ),
            ("example : True := by\ntrivial", "indented"),
            ("example : True", "example body"),
            ("example (n : Nat := 0) : n = n", "example body"),
            ("example : \"untrusted := text\" = \"text\"", "example body"),
        ] {
            let source = format!("-- ANCHOR: test\n{body}\n-- ANCHOR_END: test\n");
            let error = extract_example(&source, "test").unwrap_err().to_string();
            assert!(error.contains(message), "{body:?}: {error}");
        }
    }
}
mdbook-dada/src/lean.rs:tests::rejects_end_markers_that_cut_off_a_proof_continuation
#![allow(unused)]
fn main() {
#[test]
    fn rejects_end_markers_that_cut_off_a_proof_continuation() {
        for suffix in ["  trivial", "\n-- proof continues\n/- more -/\n  trivial"] {
            let source =
                format!("-- ANCHOR: test\nexample : True := by\n-- ANCHOR_END: test\n{suffix}\n");
            let error = extract_example(&source, "test").unwrap_err().to_string();
            assert!(error.contains("ends before an indented continuation"));
        }
        let complete = "-- ANCHOR: test\nexample : True := by\n  trivial\n-- ANCHOR_END: test\n-- Next command\ndef next := 0\n";
        assert!(extract_example(complete, "test").is_ok());
    }
}

Citations name files relative to the configured Lean source root and may omit .lean. Subdirectories are allowed; escaping the root, including through a symlink, is rejected. Source views identify each citation and retain its selected text. Imports, namespaces, and section variables remain in the retained source context; an excerpt is not a standalone Lean file.

Definition and theorem names may contain dots when that exact name is written in the declaration. The selector does not infer namespace qualification.

definitionmeta.lean.definitions.errors Missing files, missing or ambiguous declarations, unsupported extraction forms, and wrong kinds fail with the citation and target identified. A failed selection is not silently omitted or presented as complete.

definitionmeta.math.citations.validation Directive argument counts and nonempty bodies are also checked. These are syntactic checks; they establish neither mathematical correspondence nor proofs.

definitionmeta.math.unsupported Unsupported source forms need an extractor extension or a source change before citation. Attributes, declaration modifiers, nested mutual groups, and nested commands within a selected declaration are unsupported. New authored LaTeX needs no corresponding Lean-to-LaTeX translation rule.

mdbook-dada/src/lean.rs:read_source
#![allow(unused)]
fn main() {
fn read_source(root: &Path, target: &str) -> Result<(String, String)> {
    let (file, name) = target
        .rsplit_once(':')
        .context("expected path:Declaration")?;
    let mut relative = std::path::PathBuf::from(file);
    ensure!(
        !file.is_empty()
            && relative
                .components()
                .all(|c| matches!(c, Component::Normal(_))),
        "Lean path must be relative without traversal"
    );
    if relative.extension().is_none() {
        relative.set_extension("lean");
    }
    ensure!(
        relative.extension().is_some_and(|e| e == "lean"),
        "expected a .lean file"
    );
    let canonical_root = root.canonicalize().context("Lean source directory")?;
    let path = canonical_root
        .join(&relative)
        .canonicalize()
        .with_context(|| format!("Lean file {file}"))?;
    ensure!(
        path.starts_with(&canonical_root),
        "Lean source escapes configured directory"
    );
    let source = std::fs::read_to_string(path)?;
    Ok((source, name.to_owned()))
}
}
mdbook-dada/src/lean.rs:extract_declaration
#![allow(unused)]
fn main() {
fn extract_declaration(source: &str, name: &str, selection: Selection) -> Result<String> {
    let simple_name = |component: &str| {
        !component.is_empty() && component.chars().all(|c| c.is_alphanumeric() || c == '_')
    };
    if selection != Selection::Type {
        ensure!(
            name.split('.').all(simple_name),
            "use a declaration name with nonempty identifier components separated by single dots"
        );
    } else {
        ensure!(
            simple_name(name),
            "use a simple unqualified declaration name"
        );
    }
    let masked = mask(source)?;
    validate_mutual_groups(&masked)?;
    let mut found = Vec::new();
    let mut offset = 0;
    let lines: Vec<_> = masked
        .split_inclusive('\n')
        .map(|line| {
            let start = offset;
            offset += line.len();
            (start, line)
        })
        .collect();
    let structure_field = regex::Regex::new(r"^[ \t]+[A-Za-z_][A-Za-z0-9_']*[ \t]*:(?:[^:=]|$)")?;
    for (i, &(start, line)) in lines.iter().enumerate() {
        let words: Vec<_> = line.split_whitespace().collect();
        if selection == Selection::Definition {
            let declaration: Vec<_> = words
                .iter()
                .copied()
                .skip_while(|word| {
                    matches!(
                        *word,
                        "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
                    )
                })
                .collect();
            // Literal names are intentionally not resolved through namespaces.
            // A same-named declaration of the wrong kind must not disappear
            // from an otherwise ambiguous citation.
            if declaration.get(1) == Some(&name)
                && matches!(
                    declaration.first(),
                    Some(
                        &"def"
                            | &"abbrev"
                            | &"structure"
                            | &"inductive"
                            | &"theorem"
                            | &"lemma"
                            | &"axiom"
                            | &"opaque"
                            | &"constant"
                            | &"class"
                    )
                )
            {
                ensure!(
                    declaration.len() == words.len(),
                    "declaration modifiers are unsupported"
                );
                ensure!(
                    matches!(declaration.first(), Some(&"def" | &"abbrev" | &"structure" | &"inductive")),
                    "definition citations must select def, abbrev, structure, or inductive declarations"
                );
            }
        }
        if words.get(1) != Some(&name) {
            continue;
        }
        let supported = match selection {
            Selection::Theorem => words.first() == Some(&"theorem"),
            Selection::Type => {
                matches!(words.first(), Some(&"inductive" | &"structure" | &"abbrev"))
            }
            Selection::Definition => matches!(
                words.first(),
                Some(&"def" | &"inductive" | &"structure" | &"abbrev")
            ),
        };
        if !supported {
            continue;
        }
        ensure!(
            !line.starts_with(char::is_whitespace),
            "selected Lean declarations must begin at column zero"
        );
        if let Some((_, previous)) = lines[..i].iter().rev().find(|(_, l)| !l.trim().is_empty()) {
            ensure!(
                !previous.trim_start().starts_with("@["),
                "declaration attributes are unsupported"
            );
        }
        if let Some((_, boundary)) = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
        {
            let mut words = boundary.split_whitespace();
            let first = words.next().unwrap_or("");
            let mut word = first;
            while matches!(
                word,
                "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
            ) {
                word = words.next().unwrap_or("");
            }
            ensure!(
                (word == first
                    || matches!(
                        word,
                        "inductive" | "structure" | "abbrev" | "def" | "theorem" | "instance"
                    ))
                    && matches!(
                        word,
                        "inductive"
                            | "structure"
                            | "abbrev"
                            | "def"
                            | "theorem"
                            | "lemma"
                            | "example"
                            | "instance"
                            | "end"
                            | "namespace"
                            | "section"
                            | "mutual"
                            | "variable"
                            | "open"
                            | "#check"
                    ),
                "unsupported declaration boundary `{}`; continuation lines must be indented",
                boundary.trim()
            );
        }
        let end = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
            .map(|(n, _)| *n)
            .unwrap_or(source.len());
        let body = &source[start..end];
        let text = &body[..scan(body)?.content_end];
        {
            let code = &masked[start..end];
            // A structure field such as `variables : Store` is not a command.
            // Only exempt a bare, indented field name followed by a type colon;
            // `variable (x : Nat)` and `def sibling := ...` remain commands.
            let commands = command_pattern()?
                .find_iter(code)
                .filter(|command| {
                    words[0] != "structure"
                        || !structure_field
                            .is_match(code[command.start()..].lines().next().unwrap_or(""))
                })
                .count();
            ensure!(
                commands == 1,
                "selected declaration must contain no other commands, even when indented"
            );
        }
        if selection == Selection::Theorem {
            ensure!(
                has_definition_body(&masked[start..end]),
                "theorem must include its proof body (`:=`)"
            );
        } else if selection == Selection::Definition && words[0] == "def" {
            ensure!(
                has_named_definition_body(&masked[start..end])?,
                "definition must include a body (`:=`, `where`, or indented equations with `=>`)"
            );
        } else if words[0] != "abbrev" {
            ensure!(
                line.contains("where"),
                "declaration header must contain `where` on its first line"
            );
        } else {
            if selection == Selection::Definition {
                ensure!(
                    has_definition_body(&masked[start..end]),
                    "abbreviation must include a body (`:=`)"
                );
            } else {
                ensure!(line.contains(":="), "abbreviation header must contain `:=`");
            }
        }
        found.push(text.to_owned());
    }
    ensure!(
        found.len() == 1,
        "expected one supported declaration `{name}`, found {}",
        found.len()
    );
    Ok(found.remove(0))
}
}
mdbook-dada/src/lean.rs:select
#![allow(unused)]
fn main() {
/// Resolve a citation with the same declaration-kind checks as the renderer.
pub fn select(root: &Path, target: &str, kind: crate::units::UnitKind) -> Result<LeanSelection> {
    use crate::units::UnitKind;
    ensure!(
        kind != UnitKind::FutureNote,
        "future notes cannot have formalization citations"
    );
    let (source, name) = read_source(root, target)?;
    let selected = match kind {
        UnitKind::FutureNote => unreachable!("rejected above"),
        UnitKind::Definition => extract_definition(&source, &name),
        UnitKind::Theorem | UnitKind::Lemma => extract_theorem(&source, &name),
        UnitKind::Example => extract_example(&source, &name),
        UnitKind::Grammar => extract(&source, &name),
        UnitKind::Judgment => extract(&source, &name).and_then(|declaration| {
            ensure!(
                declaration.starts_with("inductive "),
                "judgment citation must select an inductive declaration"
            );
            Ok(declaration)
        }),
        UnitKind::Rule => {
            let (name, case) = name
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            extract(&source, name).and_then(|declaration| extract_case(&declaration, case))
        }
    }
    .with_context(|| target.to_owned())?;
    let (file, _) = target
        .rsplit_once(':')
        .context("expected path:Declaration")?;
    let mut relative = std::path::PathBuf::from(file);
    if relative.extension().is_none() {
        relative.set_extension("lean");
    }
    // read_source already checks canonical containment, including symlinks.
    let path = root.join(relative).canonicalize()?;
    Ok(LeanSelection {
        path,
        source,
        selected,
    })
}
}
mdbook-dada/src/lean.rs:highlighted
#![allow(unused)]
fn main() {
fn highlighted(declaration: &str) -> Result<String> {
    let masked = mask(declaration)?;
    let keywords = regex::Regex::new(
        r"\b(inductive|structure|abbrev|def|theorem|where|deriving|example|by|let|have|show|exact)\b",
    )?;
    let mut html = String::new();
    let mut last = 0;
    for m in keywords.find_iter(&masked) {
        html.push_str(&crate::escape(&declaration[last..m.start()]));
        html.push_str(&format!(
            "<span class=\"lean-keyword\">{}</span>",
            &declaration[m.range()]
        ));
        last = m.end();
    }
    html.push_str(&crate::escape(&declaration[last..]));
    Ok(html.replace('\n', "&#10;"))
}
}
mdbook-dada/tests/book.rs:authored_grammar_rejects_invalid_citations_and_missing_bodies
#![allow(unused)]
fn main() {
#[test]
fn authored_grammar_rejects_invalid_citations_and_missing_bodies() {
    let root = lean_fixtures();
    for target in [
        "Missing:Place",
        "Renderer:Missing",
        "Renderer:Step.allocVariable",
        "Renderer:allocVariable_contents",
        "../Renderer:Place",
        "Renderer:Object Renderer:Missing",
    ] {
        let mut book =
            json!({"items": [chapter("state.md", &format!("```{{grammar}} {target}\nP\n```"))]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).expect_err(target);
        assert!(format!("{error:#}").contains("state.md"), "{target}");
    }
    for source in [
        "```{grammar} Renderer:Object\n```",
        "```{grammar} Renderer:Object\n  \n```",
        "```{grammar}Renderer:Object\nP\n```",
    ] {
        let mut book = json!({"items": [chapter("state.md", source)]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).expect_err(source);
        assert!(format!("{error:#}").contains("state.md"), "{source}");
    }
    let mut book =
        json!({"items": [chapter("state.md", "```{grammar} Renderer:Slot\ns ::= r\n```")]});
    assert!(
        process(&mut book).is_err(),
        "Lean citations require a source root"
    );
}
}
mdbook-dada/tests/book.rs:linked_examples_fail_on_invalid_citations_bodies_or_nesting
#![allow(unused)]
fn main() {
#[test]
fn linked_examples_fail_on_invalid_citations_bodies_or_nesting() {
    let root = lean_fixtures();
    for source in [
        "```{example}\nBody.\n```",
        "```{example}Renderer:integer_primitive\nBody.\n```",
        "```{example} Renderer:integer_primitive Renderer:empty_array\nBody.\n```",
        "```{example} Renderer:integer_primitive\n  \n```",
        "```{example} Renderer:missing\nBody.\n```",
        "```{example} Renderer:Step\nBody.\n```",
        "```{example} ../Renderer:integer_primitive\nBody.\n```",
        "````{example} Renderer:integer_primitive\n```{example} Renderer:empty_array\nNested.\n```\n````",
    ] {
        let mut book = json!({"items": [chapter("examples.md", source)]});
        let error = mdbook_dada::process_with_lean(&mut book, Some(&root)).expect_err(source);
        assert!(format!("{error:#}").contains("examples.md"), "{source}");
    }
    let mut missing_root = json!({"items": [chapter("examples.md", "```{example} Renderer:integer_primitive\nBody.\n```")]});
    assert!(process(&mut missing_root).is_err());
    let literal = "````text\n```{example} Missing:nope\nLiteral.\n```\n````\n\n    ```{example} Missing:nope\n    Literal.\n    ```";
    let mut book = json!({"items": [chapter("examples.md", literal)]});
    process(&mut book).unwrap();
    assert_eq!(book["items"][0]["Chapter"]["content"], literal);
}
}
mdbook-dada/tests/book.rs:authored_theorems_select_literal_qualified_names
#![allow(unused)]
fn main() {
#[test]
fn authored_theorems_select_literal_qualified_names() {
    let root = lean_fixtures();
    let source = r"```{theorem} Renderer:Transfer.preserves_count
Copying a list preserves its length.

\\[P \implies Q\\]
```";
    let mut book = json!({"items": [chapter("moves.md", source)]});
    mdbook_dada::process_with_lean(&mut book, Some(&root)).unwrap();
    let html = book["items"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(html.contains("Renderer:Transfer.preserves_count"));
    assert!(html.contains("lean-keyword\">theorem</span> Transfer.preserves_count"));
    assert!(html.contains("copy_preserves_count written"));
    assert!(!html.contains("theorem</span> Transfer.read"));
    for citation in [
        "Renderer:RendererFixture.Transfer.preserves_count",
        "Renderer:Transfer..preserves_count",
        "Renderer:.Transfer.preserves_count",
        "Renderer:Transfer.preserves_count.",
    ] {
        let source = format!("```{{theorem}} {citation}\nP\n```");
        let mut book = json!({"items": [chapter("moves.md", &source)]});
        assert!(mdbook_dada::process_with_lean(&mut book, Some(&root)).is_err());
    }
}
}
mdbook-dada/src/lean.rs:tests::qualified_theorem_names_match_only_the_literal_declaration_name
#![allow(unused)]
fn main() {
#[test]
    fn qualified_theorem_names_match_only_the_literal_declaration_name() {
        let source = "namespace Outer\ntheorem MoveReference.dependent_follows : True := by\n  trivial\ntheorem other : True := by trivial\nend Outer\n";
        assert_eq!(
            extract_theorem(source, "MoveReference.dependent_follows").unwrap(),
            "theorem MoveReference.dependent_follows : True := by\n  trivial"
        );
        assert!(extract_theorem(source, "dependent_follows").is_err());
        assert!(extract_theorem(source, "Outer.MoveReference.dependent_follows").is_err());
        assert!(extract_theorem(source, "Outer.other").is_err());
        assert!(extract_theorem(source, "other").is_ok());
        assert!(extract(
            "inductive Qualified.Type where\n  | constructor",
            "Qualified.Type"
        )
        .is_err());
    }
}
mdbook-dada/src/lean.rs:tests::definitions_reject_unsupported_incomplete_and_ambiguous_sources
#![allow(unused)]
fn main() {
#[test]
    fn definitions_reject_unsupported_incomplete_and_ambiguous_sources() {
        for source in [
            "theorem selected : True := by trivial",
            "axiom selected : Nat",
            "opaque selected : Nat := 0",
            "example : Nat := 0",
            "private def selected := 0",
            "@[simp]\ndef selected := 0",
            "  def selected := 0",
            "def selected : Nat",
            "def selected (n : Nat := 0) : Nat",
            "def selected : Nat -- := 0",
            "def selected : Nat /- where -/",
            "def selected : Nat :=\n0",
            "def selected : Nat → Nat\n| n => n",
            "def selected : Nat → Nat\n  | n\n    => n",
            "def selected := 0\ntermination_by 0",
            "def selected := 0\n  def sibling := 1",
            "def selected := 0\n  theorem sibling : True := by trivial",
            "def selected := 0\nmystery next",
            "def selected := 0\nnamespace Nested\ndef selected := 1\nend Nested",
            "namespace A\ndef selected := 0\nend A\nnamespace B\ndef selected := 1\nend B",
            "namespace A\ndef selected := 0\nend A\nnamespace B\ntheorem selected : True := by trivial\nend B",
            "namespace A\ndef selected := 0\nend A\nnamespace B\nprivate def selected := 1\nend B",
            "mutual\ndef selected := 0\nend",
        ] {
            assert!(extract_definition(source, "selected").is_err(), "{source}");
        }
        for name in [".selected", "selected.", "N..selected", "N:selected"] {
            assert!(extract_definition(&format!("def {name} := 0"), name).is_err());
        }
    }
}
mdbook-dada/tests/renderer_contracts.rs:lean_citations_accept_subdirectories_but_reject_source_root_escapes
#![allow(unused)]
fn main() {
#[cfg(unix)]
#[test]
fn lean_citations_accept_subdirectories_but_reject_source_root_escapes() {
    use mdbook_dada::{lean, units::UnitKind};
    use std::os::unix::fs::symlink;

    struct Sources(PathBuf);
    impl Drop for Sources {
        fn drop(&mut self) {
            fs::remove_dir_all(&self.0).unwrap();
        }
    }
    let path = std::env::temp_dir().join(format!(
        "dada-renderer-paths-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    fs::create_dir(&path).unwrap();
    let fixture = Sources(path);
    let root = fixture.0.join("lean");
    fs::create_dir_all(root.join("nested")).unwrap();
    fs::create_dir(fixture.0.join("outside")).unwrap();
    for path in [
        root.join("nested/Model.lean"),
        root.join("nested/Model.txt"),
        fixture.0.join("outside/Model.lean"),
    ] {
        fs::write(path, "def answer : Nat := 7\n").unwrap();
    }
    let explicit = lean::select(&root, "nested/Model.lean:answer", UnitKind::Definition).unwrap();
    let inferred = lean::select(&root, "nested/Model:answer", UnitKind::Definition).unwrap();
    assert_eq!(explicit.selected, "def answer : Nat := 7");
    assert_eq!(inferred.selected, explicit.selected);
    assert_eq!(
        inferred.path,
        root.join("nested/Model.lean").canonicalize().unwrap()
    );

    symlink(
        fixture.0.join("outside/Model.lean"),
        root.join("file-link.lean"),
    )
    .unwrap();
    symlink(fixture.0.join("outside"), root.join("directory-link")).unwrap();
    let absolute = format!("{}:answer", root.join("nested/Model.lean").display());
    for (target, diagnostic) in [
        ("../outside/Model.lean:answer", "relative without traversal"),
        (absolute.as_str(), "relative without traversal"),
        ("nested/Model.txt:answer", "expected a .lean file"),
        ("file-link:answer", "escapes configured directory"),
        (
            "directory-link/Model:answer",
            "escapes configured directory",
        ),
    ] {
        let error = lean::select(&root, target, UnitKind::Definition).unwrap_err();
        assert!(
            format!("{error:#}").contains(diagnostic),
            "{target}: {error:#}"
        );
    }
}
}

Diagrams

definitionmeta.syntax.heap.state A heap diagram describes one graph using node declarations and slot assignments. It does not execute operations. Blank lines and lines beginning with # are ignored; forward references are allowed. Identifiers accept Unicode letters and digits, with a letter or underscore first. Quoted labels use JSON string escaping, and quoted arguments may contain commas.

definitionmeta.syntax.heap.constructors The supported node constructors are variables() or variables("name"), object(Type) or object(Type,"name"), primitive(value) or primitive(value,"name"), and array(length) or array(length,"name"). There is at most one variable-store group. It is a presentation aid, not an object.

definitionmeta.syntax.heap.slots Assignments use node.field or array[index]. A slot contains owned(target), showned(target), shlease(target), lease(edge), or uninitialized(). leased aliases lease; shared aliases shlease, never showned. Arrays begin with all slots empty.

The legacy borrow, primitive, and array forms are diagram syntax. Their availability does not introduce them into Given or Shared.

mdbook-dada/src/graph.rs:identifier
#![allow(unused)]
fn main() {
fn identifier(s: &str) -> bool {
    let mut chars = s.chars();
    chars.next().is_some_and(|c| c.is_alphabetic() || c == '_')
        && chars.all(|c| c.is_alphanumeric() || c == '_')
}
}
mdbook-dada/src/graph.rs:args
#![allow(unused)]
fn main() {
fn args(s: &str) -> Result<Vec<String>> {
    let mut parts = vec![];
    let (mut quoted, mut escaped, mut start) = (false, false, 0);
    for (i, c) in s.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if quoted && c == '\\' {
            escaped = true;
            continue;
        }
        if c == '"' {
            quoted = !quoted;
        }
        if c == ',' && !quoted {
            parts.push(s[start..i].trim().to_owned());
            start = i + 1;
        }
    }
    ensure!(!quoted, "unterminated quoted argument");
    if !s.trim().is_empty() {
        parts.push(s[start..].trim().to_owned());
    }
    Ok(parts)
}
}
mdbook-dada/src/graph.rs:label
#![allow(unused)]
fn main() {
fn label(s: &str) -> Result<String> {
    if s.starts_with('"') {
        Ok(serde_json::from_str::<String>(s)?)
    } else {
        ensure!(
            !s.is_empty() && !s.contains(['(', ')', '"']),
            "invalid argument `{s}`"
        );
        Ok(s.to_owned())
    }
}
}
mdbook-dada/src/graph.rs:parse
#![allow(unused)]
fn main() {
fn parse(source: &str) -> Result<Vec<Node>> {
    let mut nodes = Vec::<Node>::new();
    let mut assignments = vec![];
    for (line, text) in source.lines().enumerate() {
        let text = text.trim();
        if text.is_empty() || text.starts_with('#') {
            continue;
        }
        let result = (|| -> Result<()> {
            let (lhs, rhs) = text.split_once('=').context("expected an assignment")?;
            let lhs = lhs.trim();
            let (op, rest) = rhs
                .trim()
                .split_once('(')
                .context("expected constructor(arguments)")?;
            let op = op.trim();
            let arguments = args(
                rest.strip_suffix(')')
                    .context("expected closing parenthesis")?,
            )?;
            if lhs.contains('.') || lhs.contains('[') {
                assignments.push((lhs.to_owned(), op.to_owned(), arguments));
                return Ok(());
            }
            ensure!(identifier(lhs), "invalid node identifier `{lhs}`");
            ensure!(!nodes.iter().any(|n| n.id == lhs), "duplicate node `{lhs}`");
            let (kind, display) = match (op, arguments.as_slice()) {
                ("variables", []) => (Kind::Variables, "Variables".to_owned()),
                ("variables", [name]) => (Kind::Variables, label(name)?),
                ("object", [ty]) => (Kind::Object, format!("{} {lhs}", label(ty)?)),
                ("object", [ty, name]) => {
                    (Kind::Object, format!("{} {}", label(ty)?, label(name)?))
                }
                ("primitive", [value]) => (Kind::Primitive, format!("{lhs}: {}", label(value)?)),
                ("primitive", [value, name]) => (
                    Kind::Primitive,
                    format!("{}: {}", label(name)?, label(value)?),
                ),
                ("array", [length]) | ("array", [length, _]) => {
                    let length = length
                        .parse::<usize>()
                        .context("array length must be a nonnegative integer")?;
                    ensure!(length <= 64, "diagram arrays are limited to 64 slots");
                    let name = if arguments.len() == 2 {
                        label(&arguments[1])?
                    } else {
                        lhs.to_owned()
                    };
                    (Kind::Array(length), format!("{name} · length {length}"))
                }
                _ => bail!("unknown constructor or wrong arity: {op}"),
            };
            ensure!(
                !matches!(kind, Kind::Variables)
                    || !nodes
                        .iter()
                        .any(|node| matches!(node.kind, Kind::Variables)),
                "a heap diagram has at most one variable store"
            );
            let slots = if let Kind::Array(n) = kind {
                (0..n).map(|i| (format!("[{i}]"), None)).collect()
            } else {
                vec![]
            };
            nodes.push(Node {
                id: lhs.to_owned(),
                label: display,
                kind,
                slots,
            });
            Ok(())
        })();
        result.with_context(|| format!("heap facts line {}: {text}", line + 1))?;
    }
    ensure!(!nodes.is_empty(), "empty heap diagram");
    let mut seen = BTreeSet::new();
    for (lhs, op, args) in assignments {
        let (owner, slot, indexed) = if let Some((owner, index)) = lhs.split_once('[') {
            let index = index
                .strip_suffix(']')
                .context("expected closing array index")?
                .parse::<usize>()?;
            (owner, format!("[{index}]"), Some(index))
        } else {
            let (owner, slot) = lhs.split_once('.').context("expected node.slot")?;
            ensure!(identifier(slot), "invalid slot name `{slot}`");
            (owner, slot.to_owned(), None)
        };
        ensure!(
            seen.insert((owner.to_owned(), slot.clone())),
            "duplicate slot `{lhs}`"
        );
        let value = match (op.as_str(), args.as_slice()) {
            ("uninitialized", []) => None,
            ("lease" | "leased", [target]) => Some(("leased".to_owned(), target.clone())),
            ("owned" | "showned" | "shlease" | "shared", [target]) => {
                let target_node = nodes
                    .iter()
                    .find(|n| n.id == *target)
                    .with_context(|| format!("unknown target `{target}`"))?;
                ensure!(
                    !matches!(target_node.kind, Kind::Variables),
                    "reference cannot target variable store `{target}`"
                );
                // `shared` is a diagram shorthand for a shared lease. Ownership is
                // always spelled `showned`, never inferred from the other edges.
                Some((
                    if op == "shared" {
                        "shlease".to_owned()
                    } else {
                        op
                    },
                    target.clone(),
                ))
            }
            _ => bail!("unknown reference constructor or wrong arity in `{lhs}`"),
        };
        let node = nodes
            .iter_mut()
            .find(|n| n.id == owner)
            .with_context(|| format!("unknown slot owner `{owner}`"))?;
        match (&node.kind, indexed) {
            (Kind::Array(length), Some(index)) => {
                ensure!(index < *length, "array index out of bounds in `{lhs}`");
                node.slots[index].1 = value;
            }
            (Kind::Variables | Kind::Object, None) => node.slots.push((slot, value)),
            _ => bail!("invalid slot projection in `{lhs}`"),
        }
    }
    for node in &nodes {
        for (_, value) in &node.slots {
            if let Some((kind, target)) = value {
                if kind == "leased" {
                    let (n, slot) = edge_target(&nodes, target)?;
                    let edge = nodes[n].slots[slot]
                        .1
                        .as_ref()
                        .context("lease target is uninitialized")?;
                    ensure!(
                        matches!(edge.0.as_str(), "owned" | "leased"),
                        "lease target must be an owned or leased edge: {target}"
                    );
                }
            }
        }
    }
    Ok(nodes)
}
}
mdbook-dada/src/graph.rs:tests::facts_render_unicode_fields_and_reference_kinds
#![allow(unused)]
fn main() {
#[test]
    fn facts_render_unicode_fields_and_reference_kinds() {
        let facts="vars = variables()\nα = object(Point, \"α\")\nβ = primitive(22)\nvars.p = owned(α)\nvars.q = shared(α)\nα.x = owned(β)";
        let svg = render(facts).unwrap();
        assert!(svg.contains("Point α"));
        assert!(svg.contains("heap-edge shlease"));
        assert_eq!(svg.matches("<g class=\"heap-edge").count(), 3);
        assert_eq!(svg, render(facts).unwrap());
    }
}
mdbook-dada/src/graph.rs:tests::arrays_materialize_uninitialized_slots_and_validate_indices
#![allow(unused)]
fn main() {
#[test]
    fn arrays_materialize_uninitialized_slots_and_validate_indices() {
        let nodes = parse("a = array(2)\np = primitive(9)\na[0] = owned(p)").unwrap();
        assert_eq!(nodes[0].slots.len(), 2);
        assert!(nodes[0].slots[1].1.is_none());
        assert!(render("a = array(2)\na[2] = uninitialized()").is_err());
    }
}
mdbook-dada/src/graph.rs:tests::variable_store_groups_slots_without_becoming_a_reference_target
#![allow(unused)]
fn main() {
#[test]
    fn variable_store_groups_slots_without_becoming_a_reference_target() {
        let facts = "vars = variables()\na = primitive(1)\nvars.x = owned(a)\nvars.y = lease(vars.x)\nvars.z = uninitialized()";
        let nodes = parse(facts).unwrap();
        assert_eq!(nodes[0].label, "Variables");
        assert_eq!(nodes[0].slots.len(), 3);
        let svg = render(facts).unwrap();
        assert!(svg.contains("class=\"heap-variables\""));
        assert!(svg.contains("class=\"heap-junction\""));
        assert!(render(&format!("{facts}\nvars.bad = owned(vars)")).is_err());
        assert!(render("vars = variables(\"Live variables\")")
            .unwrap()
            .contains("Live variables"));
    }
}
mdbook-dada/src/graph.rs:tests::labels_are_escaped_and_quoted_commas_are_preserved
#![allow(unused)]
fn main() {
#[test]
    fn labels_are_escaped_and_quoted_commas_are_preserved() {
        let svg = render("a = object(Point, \"<script>, &\\\"\")").unwrap();
        assert!(!svg.contains("<script>"));
        assert!(svg.contains("&lt;script&gt;, &amp;&quot;"));
    }
}
mdbook-dada/tests/renderer_contracts.rs:diagram_forward_references_and_aliases_preserve_distinct_edges
#![allow(unused)]
fn main() {
#[test]
fn diagram_forward_references_and_aliases_preserve_distinct_edges() {
    let forward = r#"
References and lease supports may precede their declarations.
vars.α = owned(a)
vars.β = leased(vars.α)
vars.γ = shared(b)
vars.δ = showned(b)

vars = variables()
a = object(Container)
b = primitive(1)
"#;
    let canonical = "vars = variables()\na = object(Container)\nb = primitive(1)\nvars.α = owned(a)\nvars.β = lease(vars.α)\nvars.γ = shlease(b)\nvars.δ = showned(b)";
    let svg = graph::render(forward).unwrap();
    let canonical_svg = graph::render(canonical).unwrap();
    // The accessible description retains the authored facts; only the diagram
    // after that description should be identical across the two spellings.
    assert!(svg.contains(&format!("<desc>{}</desc>", mdbook_dada::escape(forward))));
    assert_eq!(
        svg.split_once("</desc>").unwrap().1,
        canonical_svg.split_once("</desc>").unwrap().1
    );
    for kind in ["owned", "leased", "shlease", "showned"] {
        assert_eq!(
            svg.matches(&format!("class=\"heap-edge {kind}\"")).count(),
            1
        );
    }
    assert_eq!(svg.matches("class=\"heap-junction\"").count(), 1);
    for field in ["α", "β", "γ", "δ"] {
        assert!(svg.contains(&format!(">{field}</text>")));
    }
}
}

Each node and explicitly assigned slot is declared once. Unknown targets, duplicate nodes or assignments, invalid projections, multiple variable stores, and out-of-bounds indices are rejected. Diagram arrays have at most 64 slots; that is a presentation limit, not a language bound.

Owned, showned, and shlease edges target objects, primitives, or arrays, never the variable-store group. A lease names an initialized owned or leased edge, such as α.f, vars.p, or items[0]. Its target may be declared later.

These checks validate diagram structure. Ownership cycles and conflicting owners are accepted so malformed language states can be illustrated. The parser does not establish language invariants or infer support edges.

mdbook-dada/src/graph.rs:parse
#![allow(unused)]
fn main() {
fn parse(source: &str) -> Result<Vec<Node>> {
    let mut nodes = Vec::<Node>::new();
    let mut assignments = vec![];
    for (line, text) in source.lines().enumerate() {
        let text = text.trim();
        if text.is_empty() || text.starts_with('#') {
            continue;
        }
        let result = (|| -> Result<()> {
            let (lhs, rhs) = text.split_once('=').context("expected an assignment")?;
            let lhs = lhs.trim();
            let (op, rest) = rhs
                .trim()
                .split_once('(')
                .context("expected constructor(arguments)")?;
            let op = op.trim();
            let arguments = args(
                rest.strip_suffix(')')
                    .context("expected closing parenthesis")?,
            )?;
            if lhs.contains('.') || lhs.contains('[') {
                assignments.push((lhs.to_owned(), op.to_owned(), arguments));
                return Ok(());
            }
            ensure!(identifier(lhs), "invalid node identifier `{lhs}`");
            ensure!(!nodes.iter().any(|n| n.id == lhs), "duplicate node `{lhs}`");
            let (kind, display) = match (op, arguments.as_slice()) {
                ("variables", []) => (Kind::Variables, "Variables".to_owned()),
                ("variables", [name]) => (Kind::Variables, label(name)?),
                ("object", [ty]) => (Kind::Object, format!("{} {lhs}", label(ty)?)),
                ("object", [ty, name]) => {
                    (Kind::Object, format!("{} {}", label(ty)?, label(name)?))
                }
                ("primitive", [value]) => (Kind::Primitive, format!("{lhs}: {}", label(value)?)),
                ("primitive", [value, name]) => (
                    Kind::Primitive,
                    format!("{}: {}", label(name)?, label(value)?),
                ),
                ("array", [length]) | ("array", [length, _]) => {
                    let length = length
                        .parse::<usize>()
                        .context("array length must be a nonnegative integer")?;
                    ensure!(length <= 64, "diagram arrays are limited to 64 slots");
                    let name = if arguments.len() == 2 {
                        label(&arguments[1])?
                    } else {
                        lhs.to_owned()
                    };
                    (Kind::Array(length), format!("{name} · length {length}"))
                }
                _ => bail!("unknown constructor or wrong arity: {op}"),
            };
            ensure!(
                !matches!(kind, Kind::Variables)
                    || !nodes
                        .iter()
                        .any(|node| matches!(node.kind, Kind::Variables)),
                "a heap diagram has at most one variable store"
            );
            let slots = if let Kind::Array(n) = kind {
                (0..n).map(|i| (format!("[{i}]"), None)).collect()
            } else {
                vec![]
            };
            nodes.push(Node {
                id: lhs.to_owned(),
                label: display,
                kind,
                slots,
            });
            Ok(())
        })();
        result.with_context(|| format!("heap facts line {}: {text}", line + 1))?;
    }
    ensure!(!nodes.is_empty(), "empty heap diagram");
    let mut seen = BTreeSet::new();
    for (lhs, op, args) in assignments {
        let (owner, slot, indexed) = if let Some((owner, index)) = lhs.split_once('[') {
            let index = index
                .strip_suffix(']')
                .context("expected closing array index")?
                .parse::<usize>()?;
            (owner, format!("[{index}]"), Some(index))
        } else {
            let (owner, slot) = lhs.split_once('.').context("expected node.slot")?;
            ensure!(identifier(slot), "invalid slot name `{slot}`");
            (owner, slot.to_owned(), None)
        };
        ensure!(
            seen.insert((owner.to_owned(), slot.clone())),
            "duplicate slot `{lhs}`"
        );
        let value = match (op.as_str(), args.as_slice()) {
            ("uninitialized", []) => None,
            ("lease" | "leased", [target]) => Some(("leased".to_owned(), target.clone())),
            ("owned" | "showned" | "shlease" | "shared", [target]) => {
                let target_node = nodes
                    .iter()
                    .find(|n| n.id == *target)
                    .with_context(|| format!("unknown target `{target}`"))?;
                ensure!(
                    !matches!(target_node.kind, Kind::Variables),
                    "reference cannot target variable store `{target}`"
                );
                // `shared` is a diagram shorthand for a shared lease. Ownership is
                // always spelled `showned`, never inferred from the other edges.
                Some((
                    if op == "shared" {
                        "shlease".to_owned()
                    } else {
                        op
                    },
                    target.clone(),
                ))
            }
            _ => bail!("unknown reference constructor or wrong arity in `{lhs}`"),
        };
        let node = nodes
            .iter_mut()
            .find(|n| n.id == owner)
            .with_context(|| format!("unknown slot owner `{owner}`"))?;
        match (&node.kind, indexed) {
            (Kind::Array(length), Some(index)) => {
                ensure!(index < *length, "array index out of bounds in `{lhs}`");
                node.slots[index].1 = value;
            }
            (Kind::Variables | Kind::Object, None) => node.slots.push((slot, value)),
            _ => bail!("invalid slot projection in `{lhs}`"),
        }
    }
    for node in &nodes {
        for (_, value) in &node.slots {
            if let Some((kind, target)) = value {
                if kind == "leased" {
                    let (n, slot) = edge_target(&nodes, target)?;
                    let edge = nodes[n].slots[slot]
                        .1
                        .as_ref()
                        .context("lease target is uninitialized")?;
                    ensure!(
                        matches!(edge.0.as_str(), "owned" | "leased"),
                        "lease target must be an owned or leased edge: {target}"
                    );
                }
            }
        }
    }
    Ok(nodes)
}
}
mdbook-dada/src/graph.rs:edge_target
#![allow(unused)]
fn main() {
fn edge_target(nodes: &[Node], target: &str) -> Result<(usize, usize)> {
    let (owner, slot) = if let Some((owner, slot)) = target.split_once('.') {
        (owner, slot.to_owned())
    } else if let Some((owner, index)) = target.split_once('[') {
        let index = index
            .strip_suffix(']')
            .context("expected array edge index")?
            .parse::<usize>()?;
        (owner, format!("[{index}]"))
    } else {
        bail!("lease target must name an edge, such as α.f or vars.p: {target}");
    };
    let n = nodes
        .iter()
        .position(|n| n.id == owner)
        .with_context(|| format!("unknown edge owner `{owner}`"))?;
    let s = nodes[n]
        .slots
        .iter()
        .position(|(name, _)| *name == slot)
        .with_context(|| format!("unknown edge `{target}`"))?;
    Ok((n, s))
}
}
mdbook-dada/src/graph.rs:tests::bad_facts_fail_instead_of_silently_changing_the_graph
#![allow(unused)]
fn main() {
#[test]
    fn bad_facts_fail_instead_of_silently_changing_the_graph() {
        for facts in [
            "a = variables()\na = variables()",
            "a = variables()\nb = variables()",
            "a = frame()",
            "a = variables()\na.p = owned(missing)",
            "a = variables()\na.p = owned(a)",
            "a = primitive(1)\na.x = uninitialized()",
            "a = variables()\na.p = uninitialized()\na.p = uninitialized()",
            "a = unknown()",
        ] {
            assert!(render(facts).is_err(), "{facts}");
        }
    }
}
mdbook-dada/src/graph.rs:tests::arrays_materialize_uninitialized_slots_and_validate_indices
#![allow(unused)]
fn main() {
#[test]
    fn arrays_materialize_uninitialized_slots_and_validate_indices() {
        let nodes = parse("a = array(2)\np = primitive(9)\na[0] = owned(p)").unwrap();
        assert_eq!(nodes[0].slots.len(), 2);
        assert!(nodes[0].slots[1].1.is_none());
        assert!(render("a = array(2)\na[2] = uninitialized()").is_err());
    }
}
mdbook-dada/src/graph.rs:lease_tests::leases_join_edges_and_shleases_target_objects
#![allow(unused)]
fn main() {
#[test]
    fn leases_join_edges_and_shleases_target_objects() {
        let facts = "vars = variables()\nα = object(C)\nβ = primitive(1)\nvars.p = owned(α)\nα.f = owned(β)\nvars.q = lease(α.f)\nvars.r = lease(vars.q)\nvars.s = shlease(β)";
        let svg = render(facts).unwrap();
        assert_eq!(svg.matches("class=\"heap-junction\"").count(), 2);
        assert!(svg.contains("heap-edge shlease"));
        for target in ["β", "α.missing", "vars.s", "α.empty"] {
            let bad = format!("{facts}\nα.empty = uninitialized()\nvars.bad = lease({target})");
            assert!(render(&bad).is_err(), "{target}");
        }
        assert!(render(
            "vars = variables()\na = array(1)\nb = primitive(2)\nvars.q = lease(a[0])\na[0] = owned(b)"
        )
        .is_ok());
        assert!(render(
            "vars = variables()\na = primitive(1)\nvars.p = owned(a)\nvars.q = shlease(vars.p)"
        )
        .is_err());
    }
}
mdbook-dada/src/graph.rs:cycle_tests::cycles_self_loops_and_disconnected_cycles_render_deterministically
#![allow(unused)]
fn main() {
#[test]
    fn cycles_self_loops_and_disconnected_cycles_render_deterministically() {
        let rect = regex::Regex::new(
            r#"<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)""#,
        )
        .unwrap();
        let paths = regex::Regex::new(r#"<path d="([^"]+)""#).unwrap();
        for facts in [
            "a = object(Node)\na.next = showned(a)",
            "a = object(Node)\nb = object(Node)\na.next = showned(b)\nb.next = showned(a)",
            "vars = variables()\na = object(Node)\nb = object(Node)\nvars.p = showned(a)\na.next = showned(b)\nb.next = showned(a)",
        ] {
            let svg = render(facts).unwrap();
            assert_eq!(svg, render(facts).unwrap());
            assert!(!svg.contains("NaN"));
            assert!(!svg.contains("heap-arrow"));
            let nodes = parse(facts).unwrap();
            let count = nodes.iter().flat_map(|n| &n.slots).filter(|(_, v)| v.is_some()).count();
            assert_eq!(svg.matches("class=\"heap-endpoint\"").count(), count);
            // Check every routed segment against every rendered rectangle, including
            // the source and destination: only boundary contact is permitted.
            let boxes: Vec<Vec<f64>> = rect.captures_iter(&svg).map(|c| (1..=4).map(|i| c[i].parse().unwrap()).collect()).collect();
            for c in paths.captures_iter(&svg) {
                let mut tokens = c[1].split_whitespace();
                let mut last = (0.0_f64, 0.0_f64);
                while let Some(op) = tokens.next() {
                    let x: f64 = tokens.next().unwrap().parse().unwrap();
                    let next = if op == "H" { (x,last.1) } else { (x,tokens.next().unwrap().parse().unwrap()) };
                    if op != "M" {
                        assert!(last.0 == next.0 || last.1 == next.1);
                        for b in &boxes {
                            let crosses = if last.0 == next.0 {
                                last.0 > b[0] && last.0 < b[0]+b[2] && last.1.min(next.1) < b[1]+b[3] && last.1.max(next.1) > b[1]
                            } else {
                                last.1 > b[1] && last.1 < b[1]+b[3] && last.0.min(next.0) < b[0]+b[2] && last.0.max(next.0) > b[0]
                            };
                            assert!(!crosses, "edge crosses box in {facts}");
                        }
                    }
                    last = next;
                }
            }
        }
    }
}
mdbook-dada/tests/renderer_contracts.rs:diagram_array_size_boundary_preserves_all_slots
#![allow(unused)]
fn main() {
#[test]
fn diagram_array_size_boundary_preserves_all_slots() {
    let empty = graph::render("a = array(0)").unwrap();
    assert!(empty.contains("length 0"));
    assert!(!empty.contains("uninitialized"));
    let maximum = graph::render("a = array(64)").unwrap();
    assert_eq!(maximum.matches(": uninitialized</text>").count(), 64);
    for index in 0..64 {
        assert!(maximum.contains(&format!(">[{index}]: uninitialized</text>")));
    }
    let last = graph::render("a = array(64)\na[63] = owned(b)\nb = primitive(1)").unwrap();
    assert_eq!(last.matches(": uninitialized</text>").count(), 63);
    assert_eq!(last.matches("class=\"heap-edge owned\"").count(), 1);
    let too_large = graph::render("a = array(65)").unwrap_err();
    assert!(format!("{too_large:#}").contains("limited to 64 slots"));
    assert!(graph::render("a = array(64)\na[64] = uninitialized()").is_err());
}
}

A diagram renders each stored reference as a labeled SVG edge. Explicit leases join their named supporting edge at a junction; object-targeting edges end at the target’s left boundary. Node and edge labels are HTML-escaped. The SVG description and Facts view retain the input facts.

Layout is deterministic for the same input. It places the variable group to the left of reachable objects when the graph allows it. It does not add graph edges or infer lease provenance.

mdbook-dada/src/graph.rs:render
#![allow(unused)]
fn main() {
pub fn render(source: &str) -> Result<String> {
    let nodes = parse(source)?;
    let lookup: BTreeMap<_, _> = nodes
        .iter()
        .enumerate()
        .map(|(i, n)| (n.id.as_str(), i))
        .collect();
    // Assign depth by first-discovered owning root path. Cycles and disconnected objects remain
    // renderable; the diagram language does not claim ownership well-formedness.
    let mut depths = vec![None; nodes.len()];
    for (i, n) in nodes.iter().enumerate() {
        if matches!(n.kind, Kind::Variables) {
            depths[i] = Some(0);
        }
    }
    for _ in 0..nodes.len() {
        let mut changed = false;
        for (i, n) in nodes.iter().enumerate() {
            if let Some(depth) = depths[i] {
                for (_, value) in &n.slots {
                    if let Some((kind, target)) = value {
                        if !matches!(kind.as_str(), "owned" | "showned") {
                            continue;
                        }
                        let j = lookup[target.as_str()];
                        if depths[j].is_none() {
                            depths[j] = Some(depth + 1);
                            changed = true;
                        }
                    }
                }
            }
        }
        if !changed {
            break;
        }
    }
    let width = nodes
        .iter()
        .map(|n| n.label.chars().count())
        .max()
        .unwrap_or(0)
        .max(18) as f64
        * 8.0
        + 32.0;
    let stride = width + 150.0;
    let mut bottoms = BTreeMap::<usize, f64>::new();
    let positions: Vec<_> = nodes
        .iter()
        .enumerate()
        .map(|(i, n)| {
            let depth = depths[i].unwrap_or(1);
            let y = *bottoms.entry(depth).or_insert(30.0);
            let height = 48.0 + 32.0 * n.slots.len() as f64;
            bottoms.insert(depth, y + height + 65.0);
            (30.0 + depth as f64 * stride, y, height)
        })
        .collect();
    let canvas_width = positions
        .iter()
        .map(|(x, _, _)| x + width + 90.0)
        .fold(0.0, f64::max);
    let canvas_height = bottoms.values().copied().fold(0.0, f64::max);
    let mut svg=format!("<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"heap-diagram\" role=\"img\" aria-label=\"Heap objects and references\" style=\"max-width:{canvas_width}px\" viewBox=\"0 0 {canvas_width} {canvas_height}\"><title>Heap objects and references</title><desc>{}</desc>",escape(source));
    for (i, n) in nodes.iter().enumerate() {
        let (x, y, height) = positions[i];
        let class = if matches!(n.kind, Kind::Variables) {
            "heap-variables"
        } else {
            "heap-object"
        };
        svg.push_str(&format!("<g class=\"{class}\"><rect x=\"{x}\" y=\"{y}\" width=\"{width}\" height=\"{height}\" rx=\"6\"/><text x=\"{}\" y=\"{}\" class=\"heap-title\">{}</text>",x+12.0,y+27.0,escape(&n.label)));
        for (s, (slot, value)) in n.slots.iter().enumerate() {
            let sy = y + 62.0 + s as f64 * 32.0;
            let contents = if value.is_none() {
                format!("{slot}: uninitialized")
            } else {
                slot.clone()
            };
            svg.push_str(&format!(
                "<text x=\"{}\" y=\"{sy}\">{}</text>",
                x + 12.0,
                escape(&contents)
            ));
        }
        svg.push_str("</g>");
    }
    for (i, n) in nodes.iter().enumerate() {
        let (x, y, _) = positions[i];
        for (s, (_, value)) in n.slots.iter().enumerate() {
            if let Some((kind, target)) = value {
                let sy = y + 57.0 + s as f64 * 32.0;
                let (tx, ey, edge_targeted) = if kind == "leased" {
                    let (n, slot) = edge_target(&nodes, target)?;
                    let (x, y, _) = positions[n];
                    (x + width + 12.0, y + 57.0 + slot as f64 * 32.0, true)
                } else {
                    let (x, y, height) = positions[lookup[target.as_str()]];
                    (x, sy.clamp(y + 12.0, y + height - 12.0), false)
                };
                let sx = x + width;
                let boxes: Vec<_> = positions
                    .iter()
                    .map(|&(x, y, h)| (x as i64, y as i64, width as i64, h as i64))
                    .collect();
                let route = crate::routing::route(
                    ((sx + 35.0) as i64, sy as i64),
                    (
                        (if edge_targeted { tx } else { tx - 20.0 }) as i64,
                        ey as i64,
                    ),
                    &boxes,
                )?;
                let mut d = format!("M {sx} {sy} H {}", sx + 35.0);
                for &(px, py) in route.iter().skip(1) {
                    d.push_str(&format!(" L {px} {py}"));
                }
                if !edge_targeted {
                    d.push_str(&format!(" L {tx} {ey}"));
                }
                let dot_class = if edge_targeted {
                    "heap-junction"
                } else {
                    "heap-endpoint"
                };
                svg.push_str(&format!("<g class=\"heap-edge {kind}\"><path d=\"{d}\"/><circle class=\"{dot_class}\" cx=\"{tx}\" cy=\"{ey}\" r=\"3\" fill=\"currentColor\"/><text x=\"{}\" y=\"{}\">{kind}</text></g>",sx+5.0,sy-7.0));
            }
        }
    }
    svg.push_str("</svg>");
    Ok(svg)
}
}
mdbook-dada/src/lib.rs:render
#![allow(unused)]
fn main() {
fn render(
    source: &str,
    path: &str,
    anchors: &BTreeMap<String, String>,
    lean_root: Option<&Path>,
    project_root: Option<&Path>,
    scope: &str,
    definition_label: &str,
) -> Result<String> {
    let protected = protect_math(source);
    let source = protected.as_str();
    let structured_units = units::parse(source, path)?;
    let mut edits = vec![];
    for role in roles(source)? {
        let rendered = render_role(&role, path, anchors, definition_label)?;
        edits.push((role.range, rendered));
    }
    for (event, range) in Parser::new(source).into_offset_iter() {
        if matches!(event, Event::Start(Tag::Paragraph)) {
            ensure!(
                !source[range.clone()].starts_with("{example} "),
                "the paragraph {{example}} marker has been replaced: use a fenced ```{{example}} path:anchor with a Markdown body and a Lean test, or label an unfinished scenario as informational"
            );
            if source[range.clone()].starts_with("{informational} ") {
                edits.push((
                    range.start..range.start + "{informational}".len(),
                    "<span class=\"informational-label\">Informational</span>".to_owned(),
                ));
            }
        }
    }

    for block in directive_blocks(source) {
        if let Some(unit) = structured_units
            .iter()
            .find(|unit| unit.range.start == block.range.start)
        {
            for dependency in &unit.uses {
                ensure!(
                    anchors.contains_key(dependency),
                    "unknown unit dependency `{dependency}`"
                );
            }
            edits.push((
                block.range,
                render_unit(unit, path, anchors, lean_root, project_root)?,
            ));
            continue;
        }
        let start = block.range.start;
        let kind = block.info;
        let facts = block.body;
        let (directive, argument) = kind.split_once(char::is_whitespace).unwrap_or((&kind, ""));
        ensure!(
            ![
                "{heap}",
                "{grammar}",
                "{rule}",
                "{judgment}",
                "{definition}",
                "{theorem}",
                "{lemma}",
                "{example}",
                "{future-note}"
            ]
            .iter()
            .any(|name| directive.starts_with(name) && directive != *name),
            "separate the directive name and citation with whitespace"
        );
        ensure!(!matches!(directive, "{lean.type}" | "{lean.judgment}" | "{lean.rule}"),
                        "{directive} has been replaced: use ```{{grammar}} path:Name, ```{{judgment}} path:Name, or ```{{rule}} path:Name.case with authored LaTeX in the body");
        let id = format!("{scope}-{start}");
        if let Some(markdown) = MarkdownDirective::parse(directive) {
            let name = markdown.name();
            let label = markdown.label();
            let citations = argument.split_whitespace().count();
            if matches!(markdown, MarkdownDirective::Definition) {
                ensure!(
                    citations > 0,
                    "definition requires at least one opening-line citation"
                );
            } else {
                ensure!(
                    citations == 1,
                    "{name} requires exactly one opening-line citation"
                );
            }
            ensure!(!facts.trim().is_empty(), "{name} requires a Markdown body");
            let root =
                lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
            let lean_source = match markdown {
                MarkdownDirective::Definition => lean::definition_source(root, argument)?,
                MarkdownDirective::Example => lean::example_source(root, argument.trim())?,
                MarkdownDirective::Theorem | MarkdownDirective::Lemma => {
                    lean::theorem_source(root, argument.trim())?
                }
            };
            let heading_label = if matches!(markdown, MarkdownDirective::Example) {
                "example"
            } else {
                markdown.definition_label()
            };
            let (heading, body) = markdown_heading(&facts, path, anchors, heading_label)?;
            ensure!(
                !body.trim().is_empty(),
                "{name} requires a Markdown body after its heading anchors"
            );
            let body = render(
                body,
                path,
                anchors,
                lean_root,
                project_root,
                &id,
                markdown.definition_label(),
            )?;
            let selector = selector_header(
                label,
                (!heading.is_empty()).then_some(heading.as_str()),
                &format!("{name}-{id}"),
                "rendered",
                "Lean",
            );
            // Blank lines terminate raw HTML blocks so mdBook renders the body
            // as Markdown, including its explicit math delimiters and proof prose.
            edits.push((block.range, format!(
                "\n<figure class=\"lean-declaration lean-group lean-markdown lean-{name}\">{selector}<div class=\"lean-markdown-body\">\n\n{}\n\n</div><div class=\"lean-source\">{lean_source}</div></figure>\n\n",
                body.trim_matches('\n')
            )));
            continue;
        }
        let view = match directive {
            "{grammar}" => Some(lean::View::Grammar),
            "{judgment}" => Some(lean::View::Judgment),
            "{rule}" => Some(lean::View::Rule),
            _ => None,
        };
        if let Some(view) = view {
            let root =
                lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
            edits.push((
                block.range,
                format!(
                    "\n{}\n",
                    lean::render_authored(root, argument.trim(), &facts, view, &id)?
                ),
            ));
            continue;
        }
        ensure!(
            argument.trim().is_empty(),
            "{directive} does not accept opening-line arguments"
        );
        let graph = graph::render(&facts)?;
        let selector = selector_header("Diagram", None, &format!("heap-{id}"), "rendered", "Facts");
        let source = escape(&facts).replace('\n', "&#10;");
        edits.push((block.range, format!("\n<figure class=\"heap-figure\">{selector}{graph}<pre class=\"heap-facts\"><code>{source}</code></pre></figure>\n")));
    }
    edits.sort_by_key(|(range, _)| range.start);
    let mut result = String::new();
    let mut end = 0;
    for (range, replacement) in edits {
        ensure!(range.start >= end, "overlapping markup");
        result.push_str(&source[end..range.start]);
        result.push_str(&replacement);
        end = range.end;
    }
    result.push_str(&source[end..]);
    Ok(result)
}
}
mdbook-dada/src/lib.rs:selector_header
#![allow(unused)]
fn main() {
/// Shared header for every rendered/source pair. The heading is generated HTML;
/// labels, group names, and radio values are escaped here.
pub(crate) fn selector_header(
    label: &str,
    heading: Option<&str>,
    group: &str,
    rendered_value: &str,
    alternate: &str,
) -> String {
    let label = escape(label);
    let fallback = format!("<span class=\"block-label\">{label}</span>");
    let heading = heading.unwrap_or(&fallback);
    let group = escape(group);
    let rendered_value = escape(rendered_value);
    let alternate_value = escape(&alternate.to_ascii_lowercase());
    let alternate = escape(alternate);
    format!("<div class=\"lean-selector\" role=\"group\" aria-label=\"{label} view\"><div class=\"block-heading\">{heading}</div><div class=\"view-options\"><label><input type=\"radio\" name=\"{group}\" value=\"{rendered_value}\" checked> Rendered</label><label><input type=\"radio\" name=\"{group}\" value=\"{alternate_value}\"> {alternate}</label></div></div>")
}
}
mdbook-dada/tests/book.rs:heap_fences_render_and_preserve_source
#![allow(unused)]
fn main() {
#[test]
fn heap_fences_render_and_preserve_source() {
    let mut book = json!({"sections":[chapter("a.md","Before.\n\n```{heap}\nvars = variables()\np = object(Point, \"α\")\nvars.p = owned(p)\n```\n\nAfter.")]});
    process(&mut book).unwrap();
    let text = book["sections"][0]["Chapter"]["content"].as_str().unwrap();
    assert!(text.contains("<svg"));
    assert!(text.contains("aria-label=\"Diagram view\""));
    assert!(text.contains("value=\"rendered\" checked"));
    assert!(text.contains("class=\"heap-facts\""));
    assert!(text.contains("vars.p = owned(p)&#10;"));
    assert!(text.contains("Before."));
    assert!(text.contains("After."));
    assert!(!text.contains("```{heap}"));
}
}
mdbook-dada/src/graph.rs:tests::facts_render_unicode_fields_and_reference_kinds
#![allow(unused)]
fn main() {
#[test]
    fn facts_render_unicode_fields_and_reference_kinds() {
        let facts="vars = variables()\nα = object(Point, \"α\")\nβ = primitive(22)\nvars.p = owned(α)\nvars.q = shared(α)\nα.x = owned(β)";
        let svg = render(facts).unwrap();
        assert!(svg.contains("Point α"));
        assert!(svg.contains("heap-edge shlease"));
        assert_eq!(svg.matches("<g class=\"heap-edge").count(), 3);
        assert_eq!(svg, render(facts).unwrap());
    }
}
mdbook-dada/src/graph.rs:lease_tests::leases_join_edges_and_shleases_target_objects
#![allow(unused)]
fn main() {
#[test]
    fn leases_join_edges_and_shleases_target_objects() {
        let facts = "vars = variables()\nα = object(C)\nβ = primitive(1)\nvars.p = owned(α)\nα.f = owned(β)\nvars.q = lease(α.f)\nvars.r = lease(vars.q)\nvars.s = shlease(β)";
        let svg = render(facts).unwrap();
        assert_eq!(svg.matches("class=\"heap-junction\"").count(), 2);
        assert!(svg.contains("heap-edge shlease"));
        for target in ["β", "α.missing", "vars.s", "α.empty"] {
            let bad = format!("{facts}\nα.empty = uninitialized()\nvars.bad = lease({target})");
            assert!(render(&bad).is_err(), "{target}");
        }
        assert!(render(
            "vars = variables()\na = array(1)\nb = primitive(2)\nvars.q = lease(a[0])\na[0] = owned(b)"
        )
        .is_ok());
        assert!(render(
            "vars = variables()\na = primitive(1)\nvars.p = owned(a)\nvars.q = shlease(vars.p)"
        )
        .is_err());
    }
}
mdbook-dada/src/graph.rs:cycle_tests::cycles_self_loops_and_disconnected_cycles_render_deterministically
#![allow(unused)]
fn main() {
#[test]
    fn cycles_self_loops_and_disconnected_cycles_render_deterministically() {
        let rect = regex::Regex::new(
            r#"<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)""#,
        )
        .unwrap();
        let paths = regex::Regex::new(r#"<path d="([^"]+)""#).unwrap();
        for facts in [
            "a = object(Node)\na.next = showned(a)",
            "a = object(Node)\nb = object(Node)\na.next = showned(b)\nb.next = showned(a)",
            "vars = variables()\na = object(Node)\nb = object(Node)\nvars.p = showned(a)\na.next = showned(b)\nb.next = showned(a)",
        ] {
            let svg = render(facts).unwrap();
            assert_eq!(svg, render(facts).unwrap());
            assert!(!svg.contains("NaN"));
            assert!(!svg.contains("heap-arrow"));
            let nodes = parse(facts).unwrap();
            let count = nodes.iter().flat_map(|n| &n.slots).filter(|(_, v)| v.is_some()).count();
            assert_eq!(svg.matches("class=\"heap-endpoint\"").count(), count);
            // Check every routed segment against every rendered rectangle, including
            // the source and destination: only boundary contact is permitted.
            let boxes: Vec<Vec<f64>> = rect.captures_iter(&svg).map(|c| (1..=4).map(|i| c[i].parse().unwrap()).collect()).collect();
            for c in paths.captures_iter(&svg) {
                let mut tokens = c[1].split_whitespace();
                let mut last = (0.0_f64, 0.0_f64);
                while let Some(op) = tokens.next() {
                    let x: f64 = tokens.next().unwrap().parse().unwrap();
                    let next = if op == "H" { (x,last.1) } else { (x,tokens.next().unwrap().parse().unwrap()) };
                    if op != "M" {
                        assert!(last.0 == next.0 || last.1 == next.1);
                        for b in &boxes {
                            let crosses = if last.0 == next.0 {
                                last.0 > b[0] && last.0 < b[0]+b[2] && last.1.min(next.1) < b[1]+b[3] && last.1.max(next.1) > b[1]
                            } else {
                                last.1 > b[1] && last.1 < b[1]+b[3] && last.0.min(next.0) < b[0]+b[2] && last.0.max(next.0) > b[0]
                            };
                            assert!(!crosses, "edge crosses box in {facts}");
                        }
                    }
                    last = next;
                }
            }
        }
    }
}

Diagram edges use horizontal and vertical segments ending in dots. Routing searches corridors around node rectangles, including gaps within a column, and penalizes distance and bends. It avoids box interiors; a missing route is an error. It does not guarantee that distinct edges or their labels never overlap. Lease junctions identify the explicitly named supporting edge.

mdbook-dada/src/routing.rs:route
#![allow(unused)]
fn main() {
pub fn route(start: Point, end: Point, boxes: &[Rect]) -> Result<Vec<Point>> {
    let mut xs = vec![start.0, end.0];
    let mut ys = vec![start.1, end.1];
    for &(x, y, w, h) in boxes {
        xs.extend([x - 20, x + w + 20]);
        ys.extend([y - 20, y + h + 20]);
    }
    xs.sort_unstable();
    xs.dedup();
    ys.sort_unstable();
    ys.dedup();
    let nx = xs.len();
    let index = |p: Point| -> Result<usize> {
        Ok(
            ys.binary_search(&p.1).ok().context("missing routing y")? * nx
                + xs.binary_search(&p.0).ok().context("missing routing x")?,
        )
    };
    let point = |i: usize| (xs[i % nx], ys[i / nx]);
    let initial = index(start)? * 2;
    let goal = index(end)?;
    let mut costs = vec![i64::MAX; nx * ys.len() * 2];
    let mut previous = vec![None; costs.len()];
    costs[initial] = 0;
    let mut queue = BinaryHeap::from([Reverse((0, initial))]);
    while let Some(Reverse((cost, state))) = queue.pop() {
        if cost != costs[state] {
            continue;
        }
        let node = state / 2;
        if node == goal {
            let mut path = vec![point(node)];
            let mut current = state;
            while let Some(parent) = previous[current] {
                path.push(point(parent / 2));
                current = parent;
            }
            path.reverse();
            let mut compact: Vec<Point> = Vec::new();
            for p in path {
                while compact.len() >= 2 {
                    let a = compact[compact.len() - 2];
                    let b = compact[compact.len() - 1];
                    if (a.0 == b.0 && b.0 == p.0) || (a.1 == b.1 && b.1 == p.1) {
                        compact.pop();
                    } else {
                        break;
                    }
                }
                compact.push(p);
            }
            return Ok(compact);
        }
        let x = node % nx;
        let y = node / nx;
        let neighbors = [
            (x.checked_sub(1).map(|x| y * nx + x), 0),
            ((x + 1 < nx).then_some(node + 1), 0),
            (y.checked_sub(1).map(|y| y * nx + x), 1),
            ((y + 1 < ys.len()).then_some(node + nx), 1),
        ];
        for (next, direction) in neighbors {
            let Some(next) = next else {
                continue;
            };
            let a = point(node);
            let b = point(next);
            if !clear(a, b, boxes) {
                continue;
            }
            let step =
                (a.0 - b.0).abs() + (a.1 - b.1).abs() + if state % 2 == direction { 0 } else { 25 };
            let next_state = next * 2 + direction;
            if cost + step < costs[next_state] {
                costs[next_state] = cost + step;
                previous[next_state] = Some(state);
                queue.push(Reverse((cost + step, next_state)));
            }
        }
    }
    anyhow::bail!("no obstacle-free diagram route from {start:?} to {end:?}")
}
}
mdbook-dada/src/routing.rs:clear
#![allow(unused)]
fn main() {
fn clear(a: Point, b: Point, boxes: &[Rect]) -> bool {
    !boxes.iter().any(|&(x, y, w, h)| {
        if a.0 == b.0 {
            a.0 > x && a.0 < x + w && a.1.min(b.1) < y + h && a.1.max(b.1) > y
        } else {
            a.1 > y && a.1 < y + h && a.0.min(b.0) < x + w && a.0.max(b.0) > x
        }
    })
}
}
mdbook-dada/src/graph.rs:render
#![allow(unused)]
fn main() {
pub fn render(source: &str) -> Result<String> {
    let nodes = parse(source)?;
    let lookup: BTreeMap<_, _> = nodes
        .iter()
        .enumerate()
        .map(|(i, n)| (n.id.as_str(), i))
        .collect();
    // Assign depth by first-discovered owning root path. Cycles and disconnected objects remain
    // renderable; the diagram language does not claim ownership well-formedness.
    let mut depths = vec![None; nodes.len()];
    for (i, n) in nodes.iter().enumerate() {
        if matches!(n.kind, Kind::Variables) {
            depths[i] = Some(0);
        }
    }
    for _ in 0..nodes.len() {
        let mut changed = false;
        for (i, n) in nodes.iter().enumerate() {
            if let Some(depth) = depths[i] {
                for (_, value) in &n.slots {
                    if let Some((kind, target)) = value {
                        if !matches!(kind.as_str(), "owned" | "showned") {
                            continue;
                        }
                        let j = lookup[target.as_str()];
                        if depths[j].is_none() {
                            depths[j] = Some(depth + 1);
                            changed = true;
                        }
                    }
                }
            }
        }
        if !changed {
            break;
        }
    }
    let width = nodes
        .iter()
        .map(|n| n.label.chars().count())
        .max()
        .unwrap_or(0)
        .max(18) as f64
        * 8.0
        + 32.0;
    let stride = width + 150.0;
    let mut bottoms = BTreeMap::<usize, f64>::new();
    let positions: Vec<_> = nodes
        .iter()
        .enumerate()
        .map(|(i, n)| {
            let depth = depths[i].unwrap_or(1);
            let y = *bottoms.entry(depth).or_insert(30.0);
            let height = 48.0 + 32.0 * n.slots.len() as f64;
            bottoms.insert(depth, y + height + 65.0);
            (30.0 + depth as f64 * stride, y, height)
        })
        .collect();
    let canvas_width = positions
        .iter()
        .map(|(x, _, _)| x + width + 90.0)
        .fold(0.0, f64::max);
    let canvas_height = bottoms.values().copied().fold(0.0, f64::max);
    let mut svg=format!("<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"heap-diagram\" role=\"img\" aria-label=\"Heap objects and references\" style=\"max-width:{canvas_width}px\" viewBox=\"0 0 {canvas_width} {canvas_height}\"><title>Heap objects and references</title><desc>{}</desc>",escape(source));
    for (i, n) in nodes.iter().enumerate() {
        let (x, y, height) = positions[i];
        let class = if matches!(n.kind, Kind::Variables) {
            "heap-variables"
        } else {
            "heap-object"
        };
        svg.push_str(&format!("<g class=\"{class}\"><rect x=\"{x}\" y=\"{y}\" width=\"{width}\" height=\"{height}\" rx=\"6\"/><text x=\"{}\" y=\"{}\" class=\"heap-title\">{}</text>",x+12.0,y+27.0,escape(&n.label)));
        for (s, (slot, value)) in n.slots.iter().enumerate() {
            let sy = y + 62.0 + s as f64 * 32.0;
            let contents = if value.is_none() {
                format!("{slot}: uninitialized")
            } else {
                slot.clone()
            };
            svg.push_str(&format!(
                "<text x=\"{}\" y=\"{sy}\">{}</text>",
                x + 12.0,
                escape(&contents)
            ));
        }
        svg.push_str("</g>");
    }
    for (i, n) in nodes.iter().enumerate() {
        let (x, y, _) = positions[i];
        for (s, (_, value)) in n.slots.iter().enumerate() {
            if let Some((kind, target)) = value {
                let sy = y + 57.0 + s as f64 * 32.0;
                let (tx, ey, edge_targeted) = if kind == "leased" {
                    let (n, slot) = edge_target(&nodes, target)?;
                    let (x, y, _) = positions[n];
                    (x + width + 12.0, y + 57.0 + slot as f64 * 32.0, true)
                } else {
                    let (x, y, height) = positions[lookup[target.as_str()]];
                    (x, sy.clamp(y + 12.0, y + height - 12.0), false)
                };
                let sx = x + width;
                let boxes: Vec<_> = positions
                    .iter()
                    .map(|&(x, y, h)| (x as i64, y as i64, width as i64, h as i64))
                    .collect();
                let route = crate::routing::route(
                    ((sx + 35.0) as i64, sy as i64),
                    (
                        (if edge_targeted { tx } else { tx - 20.0 }) as i64,
                        ey as i64,
                    ),
                    &boxes,
                )?;
                let mut d = format!("M {sx} {sy} H {}", sx + 35.0);
                for &(px, py) in route.iter().skip(1) {
                    d.push_str(&format!(" L {px} {py}"));
                }
                if !edge_targeted {
                    d.push_str(&format!(" L {tx} {ey}"));
                }
                let dot_class = if edge_targeted {
                    "heap-junction"
                } else {
                    "heap-endpoint"
                };
                svg.push_str(&format!("<g class=\"heap-edge {kind}\"><path d=\"{d}\"/><circle class=\"{dot_class}\" cx=\"{tx}\" cy=\"{ey}\" r=\"3\" fill=\"currentColor\"/><text x=\"{}\" y=\"{}\">{kind}</text></g>",sx+5.0,sy-7.0));
            }
        }
    }
    svg.push_str("</svg>");
    Ok(svg)
}
}
mdbook-dada/src/routing.rs:tests::routes_around_boxes_and_through_column_gaps
#![allow(unused)]
fn main() {
#[test]
    fn routes_around_boxes_and_through_column_gaps() {
        let boxes = [(100, 0, 80, 80), (100, 140, 80, 80)];
        for (start, end) in [
            ((0, 40), (240, 40)),
            ((0, 110), (240, 110)),
            ((240, 40), (0, 40)),
            ((200, 40), (200, 180)),
        ] {
            let path = route(start, end, &boxes).unwrap();
            assert_eq!(path.first(), Some(&start));
            assert_eq!(path.last(), Some(&end));
            for pair in path.windows(2) {
                assert!(pair[0].0 == pair[1].0 || pair[0].1 == pair[1].1);
                assert!(clear(pair[0], pair[1], &boxes));
            }
        }
        assert_eq!(
            route((0, 110), (240, 110), &boxes).unwrap(),
            vec![(0, 110), (240, 110)]
        );
    }
}
mdbook-dada/src/graph.rs:cycle_tests::cycles_self_loops_and_disconnected_cycles_render_deterministically
#![allow(unused)]
fn main() {
#[test]
    fn cycles_self_loops_and_disconnected_cycles_render_deterministically() {
        let rect = regex::Regex::new(
            r#"<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)""#,
        )
        .unwrap();
        let paths = regex::Regex::new(r#"<path d="([^"]+)""#).unwrap();
        for facts in [
            "a = object(Node)\na.next = showned(a)",
            "a = object(Node)\nb = object(Node)\na.next = showned(b)\nb.next = showned(a)",
            "vars = variables()\na = object(Node)\nb = object(Node)\nvars.p = showned(a)\na.next = showned(b)\nb.next = showned(a)",
        ] {
            let svg = render(facts).unwrap();
            assert_eq!(svg, render(facts).unwrap());
            assert!(!svg.contains("NaN"));
            assert!(!svg.contains("heap-arrow"));
            let nodes = parse(facts).unwrap();
            let count = nodes.iter().flat_map(|n| &n.slots).filter(|(_, v)| v.is_some()).count();
            assert_eq!(svg.matches("class=\"heap-endpoint\"").count(), count);
            // Check every routed segment against every rendered rectangle, including
            // the source and destination: only boundary contact is permitted.
            let boxes: Vec<Vec<f64>> = rect.captures_iter(&svg).map(|c| (1..=4).map(|i| c[i].parse().unwrap()).collect()).collect();
            for c in paths.captures_iter(&svg) {
                let mut tokens = c[1].split_whitespace();
                let mut last = (0.0_f64, 0.0_f64);
                while let Some(op) = tokens.next() {
                    let x: f64 = tokens.next().unwrap().parse().unwrap();
                    let next = if op == "H" { (x,last.1) } else { (x,tokens.next().unwrap().parse().unwrap()) };
                    if op != "M" {
                        assert!(last.0 == next.0 || last.1 == next.1);
                        for b in &boxes {
                            let crosses = if last.0 == next.0 {
                                last.0 > b[0] && last.0 < b[0]+b[2] && last.1.min(next.1) < b[1]+b[3] && last.1.max(next.1) > b[1]
                            } else {
                                last.1 > b[1] && last.1 < b[1]+b[3] && last.0.min(next.0) < b[0]+b[2] && last.0.max(next.0) > b[0]
                            };
                            assert!(!crosses, "edge crosses box in {facts}");
                        }
                    }
                    last = next;
                }
            }
        }
    }
}
mdbook-dada/src/graph.rs:lease_tests::leases_join_edges_and_shleases_target_objects
#![allow(unused)]
fn main() {
#[test]
    fn leases_join_edges_and_shleases_target_objects() {
        let facts = "vars = variables()\nα = object(C)\nβ = primitive(1)\nvars.p = owned(α)\nα.f = owned(β)\nvars.q = lease(α.f)\nvars.r = lease(vars.q)\nvars.s = shlease(β)";
        let svg = render(facts).unwrap();
        assert_eq!(svg.matches("class=\"heap-junction\"").count(), 2);
        assert!(svg.contains("heap-edge shlease"));
        for target in ["β", "α.missing", "vars.s", "α.empty"] {
            let bad = format!("{facts}\nα.empty = uninitialized()\nvars.bad = lease({target})");
            assert!(render(&bad).is_err(), "{target}");
        }
        assert!(render(
            "vars = variables()\na = array(1)\nb = primitive(2)\nvars.q = lease(a[0])\na[0] = owned(b)"
        )
        .is_ok());
        assert!(render(
            "vars = variables()\na = primitive(1)\nvars.p = owned(a)\nvars.q = shlease(vars.p)"
        )
        .is_err());
    }
}

Future notes

A future note is exploratory Markdown outside the current specification, introduced at chapter top level by {future-note} and a stable unit ID. Placement inside a list or blockquote is rejected. It must not declare an associated formalization: :lean:, :rust:, and :tests: are errors, as is a citation in place of the opening ID. Draft status is also rejected; a future note is not a specification unit waiting for approval. Nested specification units and legacy citation blocks remain forbidden.

Notes may refer to existing concepts through :uses: or links. Their IDs, references, authored bodies, and strict-chapter coverage are checked normally. The rendered header identifies a Future note, without a formalization selector or Draft badge. Literal authoring samples stay literal.

Evidence validation reports future note with correspondence not applicable. The absence of a formalization does not fail validation, but preparing or recording a correspondence review for a future note is an error. Draft specification units still require formalization and block evidence validation. The check rejects declared formalization associations; it does not infer that uncited code implements an idea.

mdbook-dada/src/units.rs:parse_block
#![allow(unused)]
fn main() {
fn parse_block(
    source: &str,
    path: &str,
    range: Range<usize>,
    info: &str,
) -> Result<Option<SpecUnit>> {
    let (directive, argument) = info.split_once(char::is_whitespace).unwrap_or((info, ""));
    let Some(kind) = UnitKind::parse(directive) else {
        return Ok(None);
    };
    // Legacy directives carry path:declaration on their opening line. Keep their
    // interpretation, but never mistake them for reviewed structured units.
    if argument.contains(':') {
        ensure!(
            kind != UnitKind::FutureNote,
            "future notes cannot have formalization citations; use a stable unit ID"
        );
        return Ok(None);
    }
    let id = argument.trim();
    if kind.is_math() && id.is_empty() {
        bail!(
            "{directive} requires a stable unit ID, a :lean: citation, and an authored LaTeX body"
        );
    }
    ensure!(
        valid_id(id),
        "expected one stable unit ID after {directive}"
    );
    let raw = &source[range.clone()];
    let opening_end = raw
        .find('\n')
        .context("unit has no body or closing fence")?
        + 1;
    let closing_start = raw
        .trim_end_matches(['\n', '\r'])
        .rfind('\n')
        .context("unit has no closing fence")?
        + 1;
    let opening = raw[..opening_end].trim_start();
    let marker = opening
        .chars()
        .next()
        .context("unit has no opening fence")?;
    let width = opening.chars().take_while(|c| *c == marker).count();
    let closing = raw[closing_start..].trim();
    ensure!(
        matches!(marker, '`' | '~')
            && closing.chars().all(|c| c == marker)
            && closing.len() >= width,
        "structured unit must have an explicit matching closing fence"
    );
    let contents = &raw[opening_end..closing_start];
    let mut unit = SpecUnit {
        id: id.to_owned(),
        kind,
        draft: false,
        source_path: path.to_owned(),
        range,
        body: String::new(),
        raw: raw.to_owned(),
        lean: vec![],
        rust: vec![],
        tests: vec![],
        uses: vec![],
    };
    let mut seen = BTreeSet::new();
    let mut body_start = 0;
    for line in contents.split_inclusive('\n') {
        let line_text = line.trim_end_matches(['\n', '\r']);
        if !line_text.starts_with(':') {
            break;
        }
        let (option, value) = line_text[1..]
            .split_once(':')
            .context("unit option must have the form :name: value")?;
        ensure!(seen.insert(option), "duplicate :{option}: option");
        let values: Vec<_> = value.split_whitespace().map(str::to_owned).collect();
        ensure!(!values.is_empty(), ":{option}: must not be empty");
        if option == "status" {
            ensure!(
                values == ["draft"],
                ":status: only accepts `draft`; omit it for units ready for correspondence review"
            );
            unit.draft = true;
            body_start += line.len();
            continue;
        }
        let target = match option {
            "lean" => &mut unit.lean,
            "rust" => &mut unit.rust,
            "tests" => &mut unit.tests,
            "uses" => &mut unit.uses,
            _ => bail!("unknown unit option :{option}:"),
        };
        let unique: BTreeSet<_> = values.iter().collect();
        ensure!(
            unique.len() == values.len(),
            "duplicate value in :{option}:"
        );
        *target = values;
        body_start += line.len();
    }
    unit.body = contents[body_start..].trim_matches(['\n', '\r']).to_owned();
    // mdBook expands these even inside fenced code. The packet must contain
    // exactly the authored content, not untracked external substitutions.
    let includes = regex::Regex::new(r"\{\{\s*#(?:include|rustdoc_include|playground)\b")?;
    ensure!(
        !includes.is_match(&unit.raw),
        "mdBook include, rustdoc_include, and playground directives are unsupported inside structured units; write the content directly or cite another unit"
    );
    for event in Parser::new(&unit.body) {
        if let Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(info))) = event {
            let (directive, argument) = info.split_once(char::is_whitespace).unwrap_or((&info, ""));
            ensure!(
                UnitKind::parse(directive).is_none() || !argument.contains(':'),
                "legacy citation directives cannot nest inside structured units; create a separate unit with :lean: and refer to it with :uses:"
            );
        }
    }
    ensure!(
        !unit.body.trim().is_empty(),
        "unit requires an authored body"
    );
    ensure!(
        !unit.body.starts_with(':'),
        "unit options must immediately follow the opening fence, before the blank line and body"
    );
    if kind == UnitKind::FutureNote {
        ensure!(
            unit.lean.is_empty() && unit.rust.is_empty() && unit.tests.is_empty(),
            "future notes cannot have formalization citations (:lean:, :rust:, or :tests:); use a specification unit for formalized content"
        );
        ensure!(!unit.draft, "future notes cannot have :status: draft; they are exploratory notes, not unfinished specification units");
    }
    ensure!(
        kind == UnitKind::FutureNote || unit.draft || !unit.lean.is_empty() || !unit.rust.is_empty(),
        "unit requires :lean: or :rust: citations; use :status: draft while its formalization is pending"
    );
    ensure!(
        unit.tests.is_empty() || !unit.rust.is_empty(),
        ":tests: requires a :rust: implementation citation"
    );
    ensure!(
        unit.lean.is_empty() || unit.rust.is_empty(),
        "a unit cannot mix :lean: and :rust: citations"
    );
    ensure!(
        !matches!(kind, UnitKind::Theorem | UnitKind::Lemma)
            || !unit.lean.is_empty()
            || (unit.draft && unit.rust.is_empty()),
        "theorem and lemma units require a Lean theorem; Rust tests are not proofs"
    );
    ensure!(
        !matches!(
            kind,
            UnitKind::Judgment
                | UnitKind::Rule
                | UnitKind::Theorem
                | UnitKind::Lemma
                | UnitKind::Example
        ) || unit.lean.is_empty()
            || unit.lean.len() == 1,
        "{} requires exactly one Lean citation",
        kind.label()
    );
    for dependency in &unit.uses {
        ensure!(valid_id(dependency), "invalid dependency ID `{dependency}`");
        ensure!(dependency != id, "unit cannot depend on itself");
    }
    ensure!(
        parse(&unit.body, path)?.is_empty(),
        "named units cannot nest; cite the other unit with :uses: or a link"
    );
    Ok(Some(unit))
}
}
mdbook-dada/src/units.rs:parse
#![allow(unused)]
fn main() {
/// Parse top-level ID-first units. Legacy citation-first directives are excluded.
pub fn parse(source: &str, path: &str) -> Result<Vec<SpecUnit>> {
    reject_removed_syntax(source, path)?;
    let mut units = Vec::new();
    let mut current = None;
    let mut depth = 0;
    for (event, range) in Parser::new(source).into_offset_iter() {
        match event {
            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(info)))
                if depth != 0 && info.split_whitespace().next() == Some("{future-note}") =>
            {
                let line = source[..range.start]
                    .bytes()
                    .filter(|b| *b == b'\n')
                    .count()
                    + 1;
                bail!("{path}:{line}: future notes must be top-level units, not nested in lists or blockquotes");
            }
            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(info))) if depth == 0 => {
                current = Some((range.start, info.into_string()));
                depth += 1;
            }
            Event::End(TagEnd::CodeBlock) if current.is_some() => {
                let (start, info) = current.take().expect("matched code block");
                let line = source[..start].bytes().filter(|b| *b == b'\n').count() + 1;
                if let Some(unit) = parse_block(source, path, start..range.end, &info)
                    .with_context(|| format!("{path}:{line}"))?
                {
                    ensure!(
                        !units.iter().any(|other: &SpecUnit| other.id == unit.id),
                        "{path}:{line}: duplicate unit ID `{}`",
                        unit.id
                    );
                    units.push(unit);
                }
                depth -= 1;
            }
            Event::Start(_) => depth += 1,
            Event::End(_) => depth -= 1,
            _ => {}
        }
    }
    Ok(units)
}
}
mdbook-dada/src/lib.rs:render_unit
#![allow(unused)]
fn main() {
fn render_unit(
    unit: &units::SpecUnit,
    path: &str,
    anchors: &BTreeMap<String, String>,
    lean_root: Option<&Path>,
    project_root: Option<&Path>,
) -> Result<String> {
    let label = unit.kind.label();
    let lower_label = label.to_ascii_lowercase();
    let role = Role {
        range: unit.range.clone(),
        id: unit.id.clone(),
        definition: true,
        label: None,
        lean: false,
    };
    let mut heading = render_role(&role, path, anchors, &lower_label)?;
    if unit.draft {
        heading.push_str(" <span class=\"block-label unit-status\" title=\"Formalization and correspondence review pending\">Draft</span>");
    }
    let (alternate, cited_source) = if !unit.lean.is_empty() {
        let root = lean_root.context("Lean directives require preprocessor.dada.lean-source")?;
        ("Lean", lean::selected_source(root, &unit.lean, unit.kind)?)
    } else if !unit.rust.is_empty() {
        let root = project_root.context("Rust citations require a configured project root")?;
        let mut cited = String::new();
        for target in unit.rust.iter().chain(&unit.tests) {
            let selected = crate::rust_source::select(root, target)?;
            cited.push_str(&format!(
                "<figcaption>{}</figcaption><pre><code class=\"language-rust\">{}</code></pre>",
                escape(target),
                escape(&selected.selected).replace('\n', "&#10;")
            ));
        }
        ("Rust", cited)
    } else {
        ("", String::new())
    };
    let header = if alternate.is_empty() {
        format!("<div class=\"lean-selector\"><div class=\"block-heading\">{heading}</div></div>")
    } else {
        selector_header(
            label,
            Some(&heading),
            &format!("unit-{}", unit.id),
            "rendered",
            alternate,
        )
    };
    let body = if unit.kind.is_math() {
        let tex = escape(unit.body.trim()).replace('\n', "&#10;");
        format!("<div class=\"lean-grammar\"><div class=\"math-display\">\\[{tex}\\]</div></div>")
    } else {
        let body = render(
            &unit.body,
            path,
            anchors,
            lean_root,
            project_root,
            &unit.id,
            &lower_label,
        )?;
        format!(
            "<div class=\"lean-markdown-body\">\n\n{}\n\n</div>",
            body.trim_matches('\n')
        )
    };
    let markdown_class = if unit.kind.is_math() {
        ""
    } else {
        " lean-markdown"
    };
    Ok(format!("\n<figure class=\"lean-declaration lean-group{markdown_class}\">{header}{body}<div class=\"lean-source\">{cited_source}</div></figure>\n\n"))
}
}
mdbook-dada/src/evidence.rs:ReviewBundle::prepare
#![allow(unused)]
fn main() {
pub fn prepare(inventory: &Inventory, unit: &str, extra: &[String]) -> Result<Self> {
        if !link_audit::is_subject(unit) {
            ensure!(
                inventory.unit(unit)?.kind != UnitKind::FutureNote,
                "future notes have no formalization to review"
            );
        }
        let mut inputs = inventory.inputs(unit)?;
        for path in extra {
            inputs.push(inventory.extra_input(path)?);
        }
        inputs.sort_by(|a, b| a.key.cmp(&b.key));
        let mut bundle = Self {
            schema: SCHEMA,
            unit: unit.to_owned(),
            inputs,
            digest: String::new(),
        };
        bundle.digest = bundle.content_digest()?;
        ensure!(
            bundle.integrity_errors().is_empty(),
            "duplicate inputs in bundle"
        );
        Ok(bundle)
    }
}
mdbook-dada/src/evidence.rs:record
#![allow(unused)]
fn main() {
/// Record a review only after checking the same current input set used by check.
/// Recording a mismatch is permitted and will cause required review checks to fail.
pub fn record(
    inventory: &Inventory,
    bundle: &ReviewBundle,
    review: &ReviewRecord,
) -> Result<PathBuf> {
    let current = Inventory::load(&inventory.root)?;
    let inventory = &current;
    if !link_audit::is_subject(&bundle.unit) {
        ensure!(
            inventory.unit(&bundle.unit)?.kind != UnitKind::FutureNote,
            "cannot record correspondence for a future note: it has no formalization"
        );
    }
    let mut errors = validate_bundle(inventory, bundle)?;
    errors.extend(validate_review(bundle, review));
    ensure!(
        errors.is_empty(),
        "cannot record review: {}",
        errors.join("; ")
    );
    ensure!(
        link_audit::is_subject(&bundle.unit) || !inventory.unit(&bundle.unit)?.draft,
        "cannot record review for draft unit {}: complete its formalization and matching citations, remove :status: draft, then prepare and review a new bundle",
        bundle.unit
    );
    for previous in &review.supersedes {
        ensure!(valid_digest(previous), "invalid superseded review digest");
        let old: ReviewRecord = read_json(
            &inventory
                .root
                .join("evidence/records")
                .join(&bundle.unit)
                .join(format!("{previous}.json")),
        )?;
        ensure!(
            old.digest()? == *previous,
            "superseded review contents differ"
        );
        let prior: ReviewBundle = read_json(
            &inventory
                .root
                .join("evidence/bundles")
                .join(format!("{}.json", old.bundle)),
        )?;
        ensure!(
            prior.unit == bundle.unit,
            "superseded review must concern the same unit"
        );
    }
    save_bundle(inventory, bundle)?;
    write_immutable(
        &inventory.root,
        &PathBuf::from("evidence/records")
            .join(&bundle.unit)
            .join(format!("{}.json", review.digest()?)),
        review,
    )
}
}
mdbook-dada/src/evidence.rs:check
#![allow(unused)]
fn main() {
/// Check all required units, including record presence, minimum inputs and freshness.
/// Neither the review's conclusion nor a passing result establishes a Lean proof.
pub fn check(inventory: &Inventory) -> Result<Report> {
    let mut report = Report::default();
    if let Err(error) = crate::mechanical::records(&inventory.root) {
        report.issues.push(Issue {
            unit: None,
            message: "malformed mechanical execution evidence".into(),
            details: vec![format!("{error:#}")],
        });
    }
    let mut bundles = BTreeMap::new();
    for path in json_files(&inventory.root, &inventory.root.join("evidence/bundles"))? {
        match read_json::<ReviewBundle>(&path) {
            Ok(bundle) => {
                let errors = bundle.integrity_errors();
                let name = path
                    .file_stem()
                    .and_then(|name| name.to_str())
                    .unwrap_or("");
                if !errors.is_empty() || name != bundle.digest {
                    report.issues.push(Issue {
                        unit: inventory
                            .units
                            .contains_key(&bundle.unit)
                            .then_some(bundle.unit.clone()),
                        message: format!("invalid evidence bundle {}", path.display()),
                        details: errors,
                    });
                } else {
                    bundles.insert(bundle.digest.clone(), bundle);
                }
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed evidence bundle".into(),
                details: vec![format!("{error:#}")],
            }),
        }
    }
    let audits = AuditInventory::build(inventory)?;
    // Parse every saved decision, including retired subjects. Removing a link or
    // unit retires its obligation, not the integrity checks on its history.
    let mut all_records: BTreeMap<String, BTreeMap<String, ReviewRecord>> = BTreeMap::new();
    let records_root = inventory.root.join("evidence/records");
    for path in json_tree(&inventory.root, &records_root)? {
        let parsed = (|| -> Result<(String, String, ReviewRecord)> {
            let review: ReviewRecord = read_json(&path)?;
            let digest = review.digest()?;
            ensure!(
                path.file_stem().and_then(|name| name.to_str()) == Some(&digest),
                "record filename does not match contents"
            );
            let bundle = bundles
                .get(&review.bundle)
                .context("record's bundle is missing or malformed")?;
            ensure!(
                path == records_root
                    .join(&bundle.unit)
                    .join(format!("{digest}.json")),
                "record filed under wrong subject"
            );
            let errors = validate_review(bundle, &review);
            ensure!(errors.is_empty(), "invalid review: {}", errors.join("; "));
            Ok((bundle.unit.clone(), digest, review))
        })();
        match parsed {
            Ok((subject, digest, review)) => {
                all_records
                    .entry(subject)
                    .or_default()
                    .insert(digest, review);
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed stored review".into(),
                details: vec![format!("{}: {error:#}", path.display())],
            }),
        }
    }
    for (id, records) in &all_records {
        for review in records.values() {
            for previous in &review.supersedes {
                if !records.contains_key(previous) {
                    report.issues.push(Issue {
                        unit: Some(id.clone()),
                        message: "review supersedes absent or unrelated evidence".into(),
                        details: vec![previous.clone()],
                    });
                }
            }
        }
    }
    let required_subjects: BTreeSet<_> = inventory
        .required
        .iter()
        .chain(audits.manifests.keys())
        .cloned()
        .collect();
    let mut current_active = BTreeMap::new();
    for id in &required_subjects {
        // Derive inputs even for drafts: malformed
        // citations never disappear because a formalization is unfinished.
        let required = match if link_audit::is_subject(id) {
            audits.inputs(inventory, id)
        } else {
            inventory.inputs(id)
        } {
            Ok(inputs) => inputs,
            Err(error) => {
                report.issues.push(Issue {
                    unit: Some(id.clone()),
                    message: "cannot resolve required evidence inputs".into(),
                    details: vec![format!("{error:#}")],
                });
                report.statuses.push(UnitStatus {
                    unit: id.clone(),
                    evidence: "invalid sources",
                    correspondence: "not checked",
                });
                continue;
            }
        };
        if inventory
            .units
            .get(id)
            .is_some_and(|unit| unit.kind == UnitKind::FutureNote)
        {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "future note",
                correspondence: "not applicable",
            });
            continue;
        }
        if inventory.units.get(id).is_some_and(|unit| unit.draft) {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "draft",
                correspondence: "not asserted",
            });
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("draft unit {id} requires formalization"),
                details: vec![
                    "draft status preserves the unit's semantic kind but cannot count as completed correspondence evidence".into(),
                ],
            });
            continue;
        }
        let mut current = BTreeSet::new();
        let mut stale = Vec::new();
        for bundle in bundles.values().filter(|bundle| &bundle.unit == id) {
            // Historical bundles compare with one independently derived current
            // manifest. Re-reading all sources for each past review made the
            // ordinary evidence test grow with the entire review history.
            let errors = validate_bundle_against(inventory, bundle, required.clone())?;
            if errors.is_empty() {
                current.insert(bundle.digest.clone());
            } else {
                stale.extend(errors);
            }
        }
        let empty_records = BTreeMap::new();
        let records = all_records.get(id).unwrap_or(&empty_records);
        let superseded: BTreeSet<_> = records
            .values()
            .flat_map(|review| review.supersedes.iter().cloned())
            .collect();
        let stale_active = records.iter().any(|(digest, review)| {
            !superseded.contains(digest) && !current.contains(&review.bundle)
        });
        let active: Vec<_> = records
            .iter()
            .filter(|(digest, review)| {
                current.contains(&review.bundle) && !superseded.contains(*digest)
            })
            .map(|(_, review)| review)
            .collect();
        // Cross-review order decisions may rely only on an entirely current,
        // positive subject; a conflicting or stale active record blocks it.
        if !stale_active
            && !active.is_empty()
            && active
                .iter()
                .all(|review| review.conclusion == Conclusion::Corresponds)
        {
            current_active.insert(
                id.clone(),
                active.iter().map(|review| (*review).clone()).collect(),
            );
        }
        let evidence = if stale_active {
            "stale"
        } else if !current.is_empty() {
            "current"
        } else if !stale.is_empty() {
            "stale"
        } else {
            "missing"
        };
        let correspondence = if stale_active {
            "stale decision"
        } else if active.is_empty() {
            "missing"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Mismatch)
        {
            "mismatch"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Inconclusive)
        {
            "inconclusive"
        } else {
            "corresponds"
        };
        report.statuses.push(UnitStatus {
            unit: id.clone(),
            evidence,
            correspondence,
        });
        if correspondence != "corresponds" {
            let mut details = if evidence == "stale" {
                stale
            } else {
                Vec::new()
            };
            details.sort();
            details.dedup();
            if evidence == "current" && active.is_empty() {
                details.push("preparing a bundle does not record a completed review".into());
            }
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("{evidence} evidence for {id}: correspondence {correspondence}"),
                details,
            });
        }
    }
    for (unit, message) in link_audit::cross_validate(&audits, &current_active) {
        report.issues.push(Issue {
            unit: Some(unit),
            message,
            details: Vec::new(),
        });
    }
    Ok(report)
}
}
mdbook-dada/tests/units.rs:future_notes_render_without_formalization_or_draft_status
#![allow(unused)]
fn main() {
#[test]
fn future_notes_render_without_formalization_or_draft_status() {
    let files = Sources::new();
    let source = "# Ideas\n\n````{future-note} future.views\n\nA possible **extension**.\n\n```dada\nclass Token {}\n```\n````\n\nSee {anchor-ref}`future.views`.";
    let parsed = units::parse(source, "model.md").unwrap();
    assert_eq!(parsed[0].kind, UnitKind::FutureNote);
    assert!(!parsed[0].draft);
    units::validate_coverage(&source[..source.find("\n\nSee").unwrap()], "model.md").unwrap();
    let output = render(source, &files.lean()).unwrap();
    assert!(output.contains("future note: future.views"));
    assert!(output.contains("href=\"#claim-future.views\""));
    assert!(output.contains("A possible **extension**."));
    assert!(output.contains("class Token {}"));
    assert!(!output.contains("type=\"radio\""));
    assert!(!output.contains("unit-status"));
}
}
mdbook-dada/tests/units.rs:future_notes_reject_formalizations_and_nested_specifications
#![allow(unused)]
fn main() {
#[test]
fn future_notes_reject_formalizations_and_nested_specifications() {
    let files = Sources::new();
    for option in [
        ":lean: Model:initial",
        ":rust: tool.rs:check",
        ":tests: tool.rs:checks",
        ":status: draft",
    ] {
        let source = format!("```{{future-note}} future.views\n{option}\n\nIdea.\n```");
        let error = format!("{:#}", units::parse(&source, "model.md").unwrap_err());
        assert!(error.contains("model.md:1"), "{error}");
        assert!(error.contains("future notes cannot have"), "{error}");
        assert!(render(&source, &files.lean()).is_err());
    }
    for source in [
        "```{future-note} Model:initial\nIdea.\n```",
        "> ```{future-note} future.views\n> :lean: Model:initial\n> \n> Idea.\n> ```",
        "- ```{future-note} future.views\n  :rust: tool.rs:check\n  \n  Idea.\n  ```",
        "````{future-note} future.views\n\n```{definition} Model:initial\nFormalized.\n```\n````",
        "````{future-note} future.views\n\n```{definition} nested\n:lean: Model:initial\n\nFormalized.\n```\n````",
    ] {
        assert!(units::parse(source, "model.md").is_err(), "{source}");
        assert!(render(source, &files.lean()).is_err(), "{source}");
    }
    assert!(lean::select(&files.lean(), "Model:initial", UnitKind::FutureNote).is_err());
    let literal =
        "````text\n```{future-note} sample\n:lean: NotAReal:Citation\n\nLiteral syntax.\n```\n````";
    assert!(units::parse(literal, "model.md").unwrap().is_empty());
    assert_eq!(render(literal, &files.lean()).unwrap(), literal);
}
}
mdbook-dada/tests/evidence_validation.rs:future_notes_are_publishable_but_cannot_receive_correspondence_reviews
#![allow(unused)]
fn main() {
#[test]
fn future_notes_are_publishable_but_cannot_receive_correspondence_reviews() {
    let fixture = Fixture::new();
    let note = "\n```{future-note} future.views\n:uses: model.variable\n\nExplore richer views of {anchor-ref}`model.variable`.\n```\n";
    fixture.write("md/model.md", &format!("{MODEL}{note}"));
    let inventory = fixture.inventory();
    assert!(inventory.required.contains("future.views"));
    assert!(inventory
        .inputs("future.views")
        .unwrap()
        .iter()
        .any(|input| input.key == "unit:model.variable"));
    for id in ["model.variable", "model.empty"] {
        let bundle = ReviewBundle::prepare(&inventory, id, &[]).unwrap();
        evidence::record(&inventory, &bundle, &review(&bundle)).unwrap();
    }
    for id in link_audit::subjects(&inventory).unwrap() {
        let bundle = ReviewBundle::prepare(&inventory, &id, &[]).unwrap();
        evidence::record(&inventory, &bundle, &review(&bundle)).unwrap();
    }
    let report = evidence::check(&inventory).unwrap();
    assert!(report.is_ok(), "{}", report.render(&inventory));
    let status = report
        .statuses
        .iter()
        .find(|s| s.unit == "future.views")
        .unwrap();
    assert_eq!(status.evidence, "future note");
    assert_eq!(status.correspondence, "not applicable");
    assert!(ReviewBundle::prepare(&inventory, "future.views", &[]).is_err());
    // Reusing an old specification approval cannot approve a future note.
    let bundle = ReviewBundle::prepare(&inventory, "model.variable", &[]).unwrap();
    fixture.write(
        "md/model.md",
        &format!(
            "{}{}",
            MODEL.replace(
                "```{definition} model.variable\n:lean: Fixture:Variable",
                "```{future-note} model.variable"
            ),
            note
        ),
    );
    let error = evidence::record(&fixture.inventory(), &bundle, &review(&bundle)).unwrap_err();
    assert!(error
        .to_string()
        .contains("cannot record correspondence for a future note"));
    fixture.write(
        "md/model.md",
        &format!(
            "{MODEL}{}",
            note.replace(":uses: model.variable", ":uses: missing.unit")
        ),
    );
    assert!(Inventory::load(&fixture.0).is_err());
}
}

Older versions of the semantics

This book is the current v2 exploration of Dada’s semantics. Earlier versions remain available as references while we explore new approaches to describing and checking the language.

v1: Rust and a-mir-formality

Read the v1 semantics book.

The original model implements Dada’s type system and interpreter in Rust, using formality-core from a-mir-formality to express syntax and inference rules. Its book connects explanations to the executable implementation and tests. The model and its documentation are preserved in the repository’s v1/ directory.

Version 2 explores an alternative: a literate specification combining prose, mathematical notation, examples, and Lean formalization. The Markdown can be read on its own, while links to Lean declarations and rules let readers inspect how the formalization corresponds to the mathematical presentation.

V2 contains two small languages, Given and Shared, with invariant and execution-correspondence proofs. The v1 implementation remains a useful reference, but its behavior and evidence do not establish claims about v2.