# Trocq / ParamTransfer — tactic, command, and attribute reference This reference covers every tactic, command, attribute, conv step, and Lean-mechanism integration the library exposes. For the architecture and the theory, see [`README.md`](README.md); this file is the call-site manual. The engine is **relational congruence closure over a registered relation**: the same job `grind` does for `=` and `gcongr` does for `≤`, generalized to an arbitrary registered relation `R` (including cross-head representation changes neither handles natively), emitting a kernel-checked proof term. Everything a tactic does decomposes into three rule kinds over `R`: * **atoms** — registered `@[param]` / `Related` / `RelatedBinOp` witnesses, plus context hypotheses of relatedness type; * **congruence (functoriality)** — from related arguments infer related applications (this is where cross-head `f ≠ g` lives); * **equivalence** — reflexivity, symmetry, transitivity of `R`. The default entry point, `param_auto`, coordinates all of them: it dispatches to each surface below, so one name closes goals living in different relations. The families are what it routes to — and what to name when you want one strategy by hand. There are four families, followed by the decision procedures and the deriving and level-inference commands: | Family | What it does | Section | |---|---|---| | **Transfer** | synthesize a transferred statement/term **and** its relatedness proof | [↓](#transfer-family) | | **Congruence** | discharge a *fixed* `Related`/`=` representation-change goal structurally | [↓](#congruence-family) | | **Conv / cast / coe** | plug transfer into native rewriting and elaboration | [↓](#conv--cast--coe-family) | | **Automation integration** | expose the engine through `grind` / `aesop` / `mvcgen` | [↓](#automation-integration-family) | | **Decision** | decide `ZMod m` identities by bounded computation | [↓](#decision-by-bounded-computation) | | **Deriving and level inference** | generate relations for data types; report and check goal levels | [↓](#deriving-and-level-inference) | Two relations coexist. The **`Param` engine** (`Param .map_k .map_l A B`, on `RArrow`/`Param`) follows Coq-Trocq's design and carries the term translation `⟦·⟧`. The **`Related` engine** (`Related enc a b`, definitionally `enc a = b`) serves the encoding-relation case. They meet in the example domains, where the same operations are registered as both `@[param]` witnesses and `RelatedBinOp` instances. Namespaces: the `Param`-engine entry points live in `Transfer.Param`; the `Related`-engine congruence tactics (`transfer`, `rcongr`, `hgcongr`, `param_cc`, `param_solve`) live in `Transfer`. --- ## The default coordinator — `param_auto` One name over every surface below. Reach for it first; drop to a specialized tactic only when you want one strategy by name. 1. **Purpose.** A single stable call site dispatching to the whole family — the engine tactics and the native relational tactics — so one name closes goals living in *different* relations. 2. **Applies to / produces.** Any relational goal. A `first`-cascade tries, in order, `rfl`, `param_solve` (descent + closure), `rcongr` (cross-head descent), `norm_cast` (the cast graph), `gcongr` (ordered congruence), `grind` (`Eq` closure), `assumption`; the first applicable surface closes the goal. 3. **Example.** One tactic, four relations: ```lean example (a : Nat) : a + 0 = a := by param_auto -- Eq example (a b : Nat) (h : a ≤ b) : a + 1 ≤ b + 1 := by param_auto -- ≤, via gcongr example (a b : Nat) : -- cast graph, via norm_cast ((a + b : Nat) : Int) = (a : Int) + b := by param_auto example (a b c : F) : -- registered rep. change, via rcongr a * b + c = bbFieldAdd (bbFieldMul a b) c := by param_auto ``` 4. **When to use vs alternatives.** The default when the closing strategy is unclear, or to keep a call site stable while the dispatch is tuned. Name a specific tactic (`param_solve`, `rcongr`, `param_cc`, `hgcongr`, …) for a single strategy — faster, with predictable subgoals. For a goal needing *two* extensions at once — cross-head descent **and** a native-cascade leaf — `param_compose` (`ParamCompose.lean`) is the composer. 5. **Gotchas.** The dispatch is a `first`-cascade, so the order of the alternatives is the only routing. A goal-directed router that inspects the relation head can replace it behind the same name. It never fabricates: an unhandled goal is left untouched rather than erroring. It inherits each surface's limits (e.g. `grind` timeouts on heavy arithmetic). 6. **File.** `ParamAuto.lean`. --- ## Transfer family These are the engine proper: each one *produces* a transferred object together with its relatedness proof, resolving witnesses from the registries. ### `#transfer t` 1. **Purpose.** Term-level parametricity translation: synthesize `⟦t⟧` (the transferred term) and a relatedness proof, resolving constants from the ambient `@[param]` registry. 2. **Applies to / produces.** A command on a `term` `t`. Logs `⟦t⟧ = t' ⊢ `. Handles the first-order fragment: `const`/`var`/`app`/`lam`/operator spines, with change-of-representation binders. 3. **Example.** ```lean #transfer (fun x : Nat => Nat.succ x * x) -- ⟦fun x ↦ x.succ * x⟧ = fun x' ↦ x'.succ.mul x' -- ⊢ ∀ (x x' : Nat), x = x' → x.succ.mul x = x'.succ.mul x' ``` `Nat.succ` resolves from the registry (`@[param] succWitFull`); `*` goes through the operator rule (`demoOpDB`, `HMul.hMul ↦ Nat.mul`). 4. **When to use vs alternatives.** Use to obtain the *synthesized term* and its proof, rather than to close an existing goal. To transfer an existing `∀`-goal, use `param_transfer`. To run the translation against a custom (not ambient) database, call `translateAll` directly. 5. **Gotchas.** Raises `translateAll: unregistered constant` on a constant with no `@[param]` witness — by design (the non-fabrication invariant). It does not name-guess, walk inductives/projections, or do dependent `Π`/recursor transfer (the `map4` univalence cap). The operator database is fixed to `demoOpDB` at the `#transfer` call site. 6. **File.** `ParamTranslateFull.lean` (`#transfer`, `translateAll`). The ambient registry materialiser `getParamDB` and the lower-level driver `#param_translate` are in `ParamDB.lean`. ### `param_transfer` 1. **Purpose.** Reduce a `∀`-implication between two representations to its pointwise obligation; the domain `Param` is resolved automatically. 2. **Applies to / produces.** A goal `(∀ a, P a) → (∀ a', P' a')`. Leaves the pointwise obligation `∀ a a' (_ : (TransferDom.dom).R a a'), P a → P' a'`. Refines by `forallTransferAuto`, which resolves the domain via the `TransferDom` class. 3. **Example.** ```lean example (P Q : ℕ → Prop) (h : ∀ n, P n → Q n) : (∀ n : ℕ, P n) → (∀ n : ℕ, Q n) := by param_transfer intro a a' (haa' : a = a') hPa exact haa' ▸ h a hPa ``` Change-of-representation works identically: `(∀ n : Num, 0 ≤ n) → (∀ k : ℕ, 0 ≤ k)` resolves through `TransferDom Num ℕ`, and `(∀ i : ℤ, …) → (∀ x : ZMod p, …)` through the `ℤ ↠ ZMod p` retraction (`ParamRetraction.lean`). 4. **When to use vs alternatives.** The standard entry point for transferring a universally-quantified statement. `transfer_auto` is a superset that also handles the arrow `app`-rule shape. `#transfer` is for synthesizing a *term*, not reducing a `∀`-goal. On an `RComp` goal `param_transfer` backtracks to `rcomp` (below) — one entry point for the pure and the effectful abstraction theorem. 5. **Gotchas.** Resolves the domain via `TransferDom`, so the source/target type pair must have a `TransferDom` instance — built-in are the diagonal (any `A A`, graph `Eq`), `Num ↦ ℕ`, and `ℤ/ℕ ↠ ZMod p`. For a new representation change, add a `TransferDom` instance. The pointwise obligation remains to discharge (usually by `intro`/`assumption`/`exact`, plus a rewrite along the relation). 6. **File.** `ParamTransfer.lean` (`param_transfer`, `TransferDom`, `forallTransferAuto`); the `RComp` alternative is in `ParamRComp.lean`. ### `rcomp` 1. **Purpose.** Assemble an `RComp` witness — the monad-level abstraction theorem — by structural descent, the effectful analogue of `transfer` / `rcongr`. It automates the hand `RComp.pure` / `RComp.bind` spelling. 2. **Applies to / produces.** A goal `RComp Rα c c'`. Applies the first matching rule — `RComp.refl` (diagonal), `RComp.pure` (a `pure` leaf, or a pure-reducible `Id` computation collapsed to one leaf), `RComp.bind` (a `bind` node, intermediate relation pinned to `Rα`), `RComp.forIn_list` (a loop) — recursing into the subgoals, and leaves each *value*-relatedness `Rα a a'` as a residual goal. 3. **Example.** ```lean -- assemble the witness; close the one value leaf (Id collapses to a single leaf) example (n m : Nat) : RComp (M := Id) (fun (a : Nat) (a' : Int) => (a : Int) = a') (natProg n m) (intProg (n : Int) (m : Int)) := by rcomp <;> norm_cast ``` 4. **When to use vs alternatives.** Use to build the `RComp` witness a `triple_transfer` consumes, instead of nesting `RComp.pure` / `RComp.bind` by hand. `param_transfer` calls it automatically on an `RComp` goal. For the `∀`-fragment (not a computation), use `param_transfer`'s `∀`-rule. 5. **Gotchas.** Descends only a *structurally parallel* pair (shared `pure` / `bind` / `forIn` skeleton, one uniform value relation) — a skeleton mismatch stays a residual `RComp` goal rather than being forced. It leaves the value leaves (non-fabrication); discharge them with the relation's arithmetic (`norm_cast` / `simp_all` / `push_cast; ring`). Over `Id` a pure program collapses to one leaf; an effectful monad descends its `bind` structure leaf by leaf. 6. **File.** `ParamRComp.lean` (`rcomp`, `rcompCore`). ### `rcomp_ok` 1. **Purpose.** Assemble an `RCompOk` witness by structural descent. `RCompOk Rα c c'` relates a computation `c` in a monad whose postcondition shape may carry exceptions (a model that fails) to a computation `c'` in a monad of shape `.pure` (a total model such as `Id`): every successful result of `c` is `Rα`-related to a result of `c'`. 2. **Applies to / produces.** A goal `RCompOk Rα c c'`. After introducing binders and `dsimp only`, it tries the supplied lemmas (`exact`, then `apply`), then the rule for the head of `c`: `RCompOk.bind` (intermediate relation from `using`, then from the enclosing goals, then equality), `RCompOk.ite` / `RCompOk.dite` when `c'` has the same head, `RCompOk.ite_left` / `RCompOk.dite_left` otherwise, `RCompOk.forIn_range` / `RCompOk.forIn_rco` / `RCompOk.forIn_list` for a loop, and `RCompOk.pure` otherwise. It recurses into the resulting `RCompOk` goals, closes `b ↔ b'` by `Iff.rfl` when possible, reduces an `RForInStep R` leaf on two `yield` steps to `R`, and leaves the value-relation leaves. 3. **Example.** ```lean -- a checked addition on the failing side, unbounded addition on the Id side theorem addChk_rcompOk {a b : Nat} {x y : Int} (hx : (a : Int) = x) (hy : (b : Int) = y) : RCompOk castRel (addChk a b) (pure (x + y) : Id Int) := by unfold addChk rcomp_ok [OkFail.rcompOk_fail] simp [castRel, ← hx, ← hy] ``` 4. **When to use vs alternatives.** Use when the left program can fail and the right one cannot; the witness feeds `RCompOk.transfer`, which moves a total-correctness fact about `c'` to every successful execution of `c` (the converse direction does not hold). For two programs in one monad sharing the failure barrel, use `rcomp`. `param_transfer` calls `rcomp_ok` on an `RCompOk` goal. 5. **Gotchas.** `rcomp_ok [h₁, …]` is the way to pass specifications of called functions and of failing primitives (`RCompOk.of_wp_false`); a lemma whose conclusion matches every goal (such as `RCompOk.mono`) is applied again at every node and the descent does not terminate, so pass leaf specifications only. A computation on the failing side with no counterpart on the total side other than a conditional (an assertion bound by `>>=`) needs `RCompOk.bind_left` by hand. `forIn_rco` applies only to monads on `Type`. 6. **File.** `ParamRCompOk.lean` (`rcomp_ok`, `rcompOkCore`); examples in `Examples/RCompOkExamples.lean`. ### `transfer_auto` 1. **Purpose.** Single unified transfer entry dispatching both the `∀`-rule and the `R_arrow` `app`-rule. 2. **Applies to / produces.** * a `∀`-implication goal → the `∀`-rule (`forallTransferAuto`, falling back to explicit-domain `forallTransfer`); * an `R_arrow PA PB f f'` goal → peeled to its pointwise codomain obligation. Runs at a fixed univalence-free output class. 3. **Example.** ```lean -- arrow-relatedness goal, same tactic: example (f f' : ℕ → ℕ) (h : ∀ a, f a = f' a) : R_arrow (paramEqDom ℕ) (paramEqCod ℕ) f f' := by transfer_auto rename_i a a' har show f a = f' a' cases har; exact h a ``` 4. **When to use vs alternatives.** Use when a proof mixes `∀`-goals and arrow `app`-goals and one tactic must handle both. For a `∀`-only proof, `param_transfer` is the more focused name. 5. **Gotchas.** Fixed output class (not per-occurrence minimal). Per-subterm level minimization is the job of `inferParamLevels`/`inferRootClass` (`ParamInfer.lean`); `transfer_auto` does not call the solver. 6. **File.** `ParamAutoWeaken.lean`. ### `param_resolve` 1. **Purpose.** Level-directed search closing a `Param m n A B` goal at any lattice-reachable level. 2. **Applies to / produces.** A goal `Param m n A B`. Tries, in order: a registered instance at the exact `(m,n)`; synthesize at a stronger registered level and `Param.weaken` down (discharging `⊑` by `decide`); decompose an arrow (`apply paramArrow`) and recurse; embedding/equivalence leaves. 3. **Example.** ```lean example : Param .map0 .map0 (Nat → Nat) (Nat → Nat) := by param_resolve -- synthesized at (map1,map1), weakened to (map0,map0) ``` 4. **When to use vs alternatives.** Use to obtain a `Param` *witness* at a specific level for a function/base type. For a *single* registered witness reused at lower levels, `auto_weaken` is simpler. `HasParam` instance resolution covers the fixed self-relation level directly. 5. **Gotchas.** The candidate stronger levels are a hardcoded list (`(map1,map1)`, `(map3,map0)`); the `map4` universe relation is unreachable by construction. Works over arrow/base structure, not arbitrary terms. 6. **File.** `ParamResolve.lean`. ### `auto_weaken` 1. **Purpose.** "Register high, use low": close a `Param m' n' A B` goal at any lattice-lower level from a single registration at the strongest level. 2. **Applies to / produces.** A goal `Param m' n' A B`. Resolves `RegisteredParam A B m n` and applies `Param.weaken (by decide) (by decide)` down to `(m', n')`. 3. **Example.** ```lean instance regNatNat : RegisteredParam Nat Nat .map3 .map0 where reg := { R := Eq, fwd := ⟨id, fun _ _ h => h, fun _ _ h => h⟩, bwd := ⟨⟩ } example : Param .map0 .map0 Nat Nat := by auto_weaken -- below the registration example : Param .map2b .map0 Nat Nat := by auto_weaken -- incomparable branch, still ⊑ map3 ``` 4. **When to use vs alternatives.** Use when one type pair carries a strong witness and lower-class goals must resolve without restating it. This mirrors upstream Trocq's `Trocq Use` "register every sub-class version". `param_resolve` is the broader search over structure; `auto_weaken` is the single-registration shortcut. 5. **Gotchas.** Needs a `RegisteredParam` instance (a *sibling* registry, **not** `@[param]`/`paramExt`); the level pair is an `outParam` recovered from `(A, B)`. The data-level enumerator `allWeakenings` returns the full below-set of a witness when it is needed as data (`belowList`/`mem_belowList` give the decidable below-set). 6. **File.** `ParamAutoWeaken.lean` (`auto_weaken`, `RegisteredParam`, `allWeakenings`). ### `synth_param` 1. **Purpose.** Close a closed-type `Param` goal by type-class synthesis, the Lean analogue of Trocq's automatic witness generation. 2. **Applies to / produces.** A goal `Param .map1 .map1 A B`. Expands to `exact (inferInstance : HasParam _ _ _ _).param`: the resolver composes the `HasParam` witness and the tactic projects its `.param` field. 3. **Example.** ```lean example : Param .map1 .map1 (Nat → Nat → Bool) (Nat → Nat → Bool) := by synth_param ``` 4. **When to use vs alternatives.** Use for a witness at the fixed `(map1, map1)` level of the `HasParam` resolver. For another level, use `param_resolve` or `auto_weaken`. 5. **Gotchas.** Fixed to `(map1, map1)`; fails when `HasParam` resolution finds no instance for the type. 6. **File.** `ParamSynth.lean`. ### `transfer_induction` 1. **Purpose.** Transported induction: prove a `∀ a : A, P a` goal by induction on `ℕ` through an equivalence `A ≃ ℕ`. 2. **Applies to / produces.** A goal `∀ a : A, P a` where `A` carries a `ReprEquivClass A ℕ`. Expands to `refine natEquivInduction _ ?_ ?_` and leaves two subgoals stated through the decoder: `h0` (the decoded zero) and `hs` (the decoded successor step). 3. **Example.** ```lean theorem demo_num_zero_le : ∀ n : Num, 0 ≤ n := by transfer_induction · rw [PeanoBinNat.num_le_iff_to_nat_le]; simp · intro k _; rw [PeanoBinNat.num_le_iff_to_nat_le]; simp ``` 4. **When to use vs alternatives.** Use to obtain the induction principle of a representation (`Num`, binary naturals) from that of `ℕ` without restating the combinator. The base and step subgoals are closed with the automation of the base type. 5. **Gotchas.** Requires a `ReprEquivClass A ℕ` instance (the equiv level); the decoder appears in both subgoals, so the base type's lemmas are applied after rewriting through it. 6. **File.** `TransferInduction.lean` (`natEquivInduction`, `transfer_induction`). ### `transfer` 1. **Purpose.** Automatic binder traversal plus per-leaf dispatch to the `Related` registry — no commuting square named at the call site. 2. **Applies to / produces.** A goal-shape-directed `elab` (`transferCore`). On the goal head: * `Iff` of two `∀`s → `forall_congr'`, `intro`, recurse; * `Eq` of functions → `funext`, recurse; * a `∀`/`→` → `intro`, recurse; * otherwise the leaf is dispatched (`transferLeaf`). 3. **Example.** ```lean example (c : F) : ∀ a b : F, a * b + c = bbFieldAdd (bbFieldMul a b) c := by transfer ``` When a square is bundled in a local realization structure, surface it with a `have` and the registry sweep picks it up: ```lean example (R : ByteGroupRealization prims) (init : P.GT) (l : List P.GT) : R.encT (l.foldl (· * ·) init) = (l.map R.encT).foldl prims.fp12Mul (R.encT init) := by have hsq := R.fp12Mul_commutes transfer ``` 4. **When to use vs alternatives.** Use to close an equation/`Iff`-of-`∀` whose cross-head op-tree leaf is a *single* registered composite. `rcongr`/`hgcongr` descend *into* the op-tree (first-class per-argument subgoals); `transfer` collapses the leaf inside one `inferInstance`. Compose them: `transfer` for the binder layer, `rcongr` for the op-tree. 5. **Gotchas.** `transferLeaf` swallows failure (leaves the goal rather than erroring) — the non-fabrication residual; a missing square stays a visible goal. The leaf cascade is `rfl | Iff.rfl | assumption | transferGround | simp only [transfer] | solve_by_elim [...] | grind`. Helper closers (`transferGround`, `transferLeaf`, `transferCore`, `transferRegistryLeaf`) are exposed for tactic authors; `transferRegistryLeaf` *propagates* failure (no `try`), so descent tactics can chain a heavier discharger after it. 6. **File.** `TransferTactic.lean`. --- ## Congruence family These discharge a **fixed** relatedness/representation-change goal `Related enc t t'` (or an `=` bridged to one) — the relational analogues of `congr`/`gcongr`/`grind`. They are four views of one rule system; pick by the shape of what closes the goal. | | strategy | rules | reaches | |---|---|---|---| | `rcongr`, `hgcongr` | top-down **descent** | congruence only | nested cross-head op-trees, per-arg subgoals | | `param_cc` | bottom-up **closure** | congruence + equivalence | transitivity / context-hypothesis chains | | `param_solve` | **descent + closure-leaf** | both | the union | ### `rcongr` 1. **Purpose.** Relational cross-head congruence *descent* over the `Related`/`RelatedBinOp` square database. 2. **Applies to / produces.** A goal `Related enc t t'` (or an `=` bridged via `transferGround`). At a binary node `op a b` ↔ `bop a' b'` linked by a registered `RelatedBinOp enc op bop`, applies `rcongrBinOp`, leaving per-argument relatedness subgoals `Related enc a a'`, `Related enc b b'`, and recurses; leaves close via the registry (`leaf`/`leafId`) or `rfl`. 3. **Example.** ```lean example (a b c : F) : a * b + c = bbFieldAdd (bbFieldMul a b) c := by rcongr ``` 4. **When to use vs alternatives.** Use for a pure cross-head op-tree goal that needs the *structural* descent (per-argument subgoals). `hgcongr` is the attribute-driven, relation-generic generalization; `rcongr` is its hard-wired specialization to `Related`/`RelatedBinOp` (no new attribute — it reuses the existing instance set). For transitivity/context chains, use `param_cc`. 5. **Gotchas.** Cannot close a pure transitivity goal: its leaf is `inferInstance | rfl`, which keys on the syntactic RHS and cannot bridge an intermediate `c`–`b` link. Adding a new realized op is a one-line `instance … : RelatedBinOp …`. 6. **File.** `RCongr.lean` (`rcongr`, `rcongrBinOp`, `rcongrCore`). ### `hgcongr` 1. **Purpose.** Heterogeneous (cross-head) generalized congruence: `gcongr` with the same-head constraint lifted, driven by a head-*pair*-keyed `@[hgcongr]` lemma database. 2. **Applies to / produces.** A goal `R (f a₁ … aₘ) (g b₁ … bₙ)` whose head pair `(f, g)` has a registered `@[hgcongr]` lemma (heads may differ; arities may differ). Reduces to the per-argument subgoals, recursing; leaves and reflexive steps close by `rfl`. The relation `R` is read off the lemma's conclusion (`Eq`, `≤`, `Related`, …), not fixed. 3. **Example.** ```lean @[hgcongr] theorem mul_bbFieldMul_hcongr {a₁ b₁ a₂ b₂ : F} (h₁ : a₁ = a₂) (h₂ : b₁ = b₂) : a₁ * b₁ = bbFieldMul a₂ b₂ := by subst h₁; subst h₂; exact (bbFieldMul_eq _ _).symm example (a b c : F) : a * b + c = bbFieldAdd (bbFieldMul a b) c := by hgcongr ``` The diagonal pair `(f, f)` recovers gcongr's homogeneous case, so a same-head `@[hgcongr]` lemma mixes freely with cross-head steps. 4. **When to use vs alternatives.** Use for the gcongr *architecture* (attribute-tagged lemmas, any relation) extended to cross-head correspondences. `rcongr` is the in-tree, `Related`-only specialization; `gcongr` cannot host cross-head at all (see `GCongrProbe`). 5. **Gotchas.** Requires the head correspondence to be tagged `@[hgcongr]`. The varying-argument pairs are recovered from the lemma's *hypotheses* (insensitive to `arity(f) ≠ arity(g)`, e.g. `HMul.hMul` arity 6 vs `bbFieldMul` arity 2), so the lemma must state each varying pair as a hypothesis `Rᵢ lᵢ rᵢ`; tagging fails with "no varying-argument hypotheses found" otherwise. 6. **File.** `HGCongr.lean` (correspondences + demos); engine — the head-pair env extension, the `@[hgcongr]` attribute (`makeHGCongrLemma`), and `hgcongrCore` — in `HGCongrInit.lean`. ### `param_cc` 1. **Purpose.** Saturating, context-incorporating relational congruence *closure* over `Related`. 2. **Applies to / produces.** A goal `Related enc s t` (or its underlying `enc s = t`). Surfaces every context hypothesis `h : Related enc a b` as its equation `h.rel : enc a = b` and every `h : RelatedBinOp enc op bop` as its square `h.comm`; reduces a `Related` goal to its equation; closes by `grind`, whose congruence closure composes the squares and surfaced equations transitively to a fixpoint. 3. **Example.** ```lean -- transitivity through a context hypothesis (out of rcongr's reach): example {A α : Type} (enc : A → α) (a : A) (c b : α) (hac : Related enc a c) (hcb : c = b) : Related enc a b := by param_cc -- saturating congruence over context hyps + a registered square: example {A α : Type} (enc : A → α) (op : A → A → A) (bop : α → α → α) [RelatedBinOp enc op bop] (x y : A) (x' y' : α) (z : A) (z' : α) (hx : Related enc x x') (hy : Related enc y y') (hz : Related enc z z') : Related enc (op (op x y) z) (bop (bop x' y') z') := by param_cc ``` 4. **When to use vs alternatives.** Use when the proof needs transitivity or chaining through context hypotheses — what `rcongr` provably cannot do. `param_solve` is the union (descent *and* closure); use `param_cc` standalone when there is no op-tree to descend. 5. **Gotchas.** Over the encoding relation, `Related enc a b` is definitionally `enc a = b`, so `param_cc` *is* `grind` plus a relation→equation prelude; its independent value appears only for a non-equational relation. Inherits `grind`'s limits (e.g. it can time out on heavy ENNReal/BitVec arithmetic); keep the emitted kernel opaque on the RHS of each square. 6. **File.** `ParamCongrClosure.lean` (`param_cc`, `paramCCCore`). ### `param_solve` 1. **Purpose.** The common generalization of `rcongr` (descent) and `param_cc` (closure): goal-directed cross-head descent with the saturating closure as the leaf discharger. 2. **Applies to / produces.** A goal `Related enc t t'` (or `=` bridged). At a binary op-tree node, apply `rcongrBinOp` and recurse (descent); at a leaf, try the registry/`rfl`, and on failure fall into `paramCCCore` (closure — surface context hypotheses, saturate with `grind`). Closes the **union** of what `rcongr` and `param_cc` close. 3. **Example.** ```lean -- cross-head descent AND a closure leaf together: example {A α : Type} (enc : A → α) (op : A → A → A) (bop : α → α → α) [RelatedBinOp enc op bop] (a b : A) (a' : α) (b'' c : α) (ha : Related enc a a') (hb : Related enc b b'') (hbc : b'' = c) : Related enc (op a b) (bop a' c) := by param_solve ``` 4. **When to use vs alternatives.** The default when it is unclear whether the goal needs descent, closure, or both. Use the narrower `rcongr`/`param_cc` for a single strategy (faster, more predictable subgoals). 5. **Gotchas.** Same encoding-relation collapse as `param_cc` (the closure leaf is `grind`). The descent backend is hardwired to `rcongrBinOp` (`Related`/`RelatedBinOp`); swapping in an `hgcongr` head-pair lookup is the pluggable general form but is not the default. A leaf the registry does not close is tried against the guarded squares (`paramSolveGuardedStep`) before the closure; the step succeeds only when `transfer_guard_disch` closes the guard. 6. **File.** `ParamSolve.lean` (`param_solve`, `paramSolveCore`, `paramSolveGuardedStep`). ### `param_guard` 1. **Purpose.** Descent through op-trees whose squares hold only under a side condition (no overflow, `b ≤ a`, a shift below the width). 2. **Applies to / produces.** A goal `Related enc t t'`, an equation `enc t = t'` (reshaped to `Related enc t t'` when `enc` changes the type, else bridged to `Related id`), or `r a b ↔ br a' b'`. At each node it tries the registry leaf, then `rcongrBinOpOn`, `rcongrUnOpOn` (or `rcongrRelOn` on an `↔`), recurses on the operands, and runs the discharger on the guard. Total squares take part with guard `True`. The guards the discharger does not close are the goals left. 3. **Example.** ```lean instance subRelatedOn : RelatedBinOpOn enc64 (fun x y => y ≤ x) (· - ·) (· - ·) := … instance shrRelatedOn : RelatedBinOpOn enc64 (fun x s => x < 2 ^ 64 ∧ s < 64) (· >>> ·) (· >>> ·) := … example (a b s : ℕ) (ha : a < 2 ^ 64) (hb : b ≤ a) (hs : s < 64) : enc64 ((a - b) >>> s) = (enc64 a - enc64 b) >>> enc64 s := by param_guard example (a b : ℕ) (h : b ≤ a) : enc64 (a - b) = enc64 a - enc64 b := by param_guard (disch := fail) -- leaves the goal `b ≤ a` exact h ``` 4. **Discharger.** `transfer_guard_disch`, by default `first | trivial | assumption | omega | bv_omega | decide`. A client adds an alternative with `macro_rules | `(tactic| transfer_guard_disch) => `(tactic| tac)`, tried before the default; `param_guard (disch := tac)` replaces it for one call. 5. **Failure.** A `Related` subgoal with no square and no leaf raises `param_guard: no registered square or leaf closes Related enc t t'`, followed by the abstract head, the encoded head and the encoding of that subgoal, not of the root. 6. **Gotchas.** The guard `P` of `RelatedBinOpOn`/`RelatedUnOpOn` is an `outParam`, so one guarded square is found per `(enc, op, bop)`; in `RelatedRelOn` the encoding is an `outParam` too, because an `↔` goal does not mention it. The guard of an inner node mentions the abstract subterms (for example `a - b < 2 ^ 64`), so the discharger reasons about abstract operations, not about encodings. 7. **File.** `Base/RelatedOn.lean` (classes, `rcongr*On`, `transfer_guard_disch`), `ParamGuard.lean` (`param_guard`, `paramGuardCore`); examples in `Examples/GuardedSquares.lean`. 8. **Reading a container.** `Base/RelatedFamily.lean` relates a family `s : Fin n → A` to a container entry by entry: `RelatedArray enc s a` (the array `a` holds `enc (s i)` at position `i`) and `RelatedFamily enc s f` (the reader `f : ℕ → α` returns `enc (s i)` at `i`). After the operation squares, `param_guard` tries `transfer_guard_leaf`, by default `refine rcongrGetElem ?_`, which closes `Related enc (s i) a[k]` under the guard `k = i`. A client registers the reading rule of another reader with `macro_rules | `(tactic| transfer_guard_leaf) => `(tactic| refine myRule ?_)`, where `myRule` is an instance of `rcongrFamily`. For rewriting from the encoded side, `RelatedFamily.apply_eq` and `RelatedArray.getElem_eq` give `f k = enc (s ⟨k, hk⟩)`; the encoding and the family are `outParam`s, found from the container. 9. **Changing carriers.** `Base/RelatedFun.lean` relates `f : A → B` to `g : α → β` along an argument encoding and a result encoding: `RelatedFun encA encB f g` (`encB (f a) = g (encA a)`), `RelatedFun2` and `RelatedFun3` for two and three arguments, and the guarded forms `RelatedFunOn`, `RelatedFun2On`, `RelatedFun3On`. The argument encodings and the guard are `outParam`s. Their rules `rcongrFunOn`, `rcongrFun2On`, `rcongrFun3On` and `rcongrIteLeaf` are alternatives of `transfer_guard_leaf`, so `param_guard` applies them at a `Related` goal that no same-carrier square closes. Data squares cover `Option`, `Prod`, `Except` and lists. Tests: `Base/RelatedFunTest.lean`. 10. **Constructor equations.** An equation whose left-hand side is a fully applied constructor is split into field equations (`paramGuardCtorSplit`): by constructor congruence when the right-hand side has the same constructor, by structure eta when it is no constructor application. `param_guard` descends into each field equation and, when that descent fails, falls back to the reshape of item 2. Tests: `Congruence/ParamGuardCtorTest.lean`. ### `param_leaf` 1. **Purpose.** The per-leaf discharger of `param_compose`: a native cascade in which every alternative must **close** the goal. 2. **Applies to / produces.** Any goal. Expands to `first | rfl | assumption | (simp; done) | grind | ring | (gcongr <;> done) | (norm_cast; done)`. The progress-only tactics are `done`-gated, so `first` cannot commit to an alternative that only made progress. 3. **Example.** `param_compose` descends a cross-head op-tree with `rcongrBinOp` and calls `param_leaf` on each leaf; `by param_leaf` also closes a leaf goal directly. 4. **When to use vs alternatives.** Use for a leaf that a native tactic closes but that the fixed registry/`grind` leaf of `param_solve` does not. For a whole op-tree whose leaves need native tactics, use `param_compose`. 5. **Gotchas.** A leaf that no alternative closes makes `param_leaf` fail; `param_compose` then leaves that leaf as an open goal. 6. **File.** `ParamCompose.lean` (`param_leaf`, `param_compose`). ### `hcongr_dep` / `hcongr_transport` 1. **Purpose.** Dependent heterogeneous congruence: reduce an applied-output goal across a representation change to its domain witness. 2. **Applies to / produces.** Given `h : R_forall PA PB f g`: `hcongr_dep h` reduces the relation form `(PB a a' aR).R (f a) (g a')` to `PA.R a a'` (`refine hcongr_hetero _ _ h ?_`); `hcongr_transport h` reduces the transport form `(PB a a' aR).fwd.map (f a) = g a'` (fiber `map2b` or above) to the same domain witness (`refine hcongr_hetero_transport _ _ h ?_`). 3. **Example.** ```lean example (a b : ℕ) (h : a = b) : (Fin.last a).val = (fun n => n) b := by hcongr_dep finLastWitness exact h example (a b : ℕ) (h : a = b) : Fin.val (Fin.last a) = (fun n => n) b := by hcongr_transport finLastWitness exact h ``` 4. **When to use vs alternatives.** Use when the two sides of an application live in *different* fiber types, where `congr`/`gcongr` do not apply. The residual domain-witness goal composes with `param_solve`/`rcongr`/`assumption`. 5. **Gotchas.** The witness `h` is passed explicitly; it pins `PA`, `PB`, `f`, `g`, so no higher-order unification is needed. 6. **File.** `HCongrConnection.lean`. ### The same-head restriction in `gcongr` — `GCongrProbe` `@[gcongr]` accepts **only** same-head monotonicity lemmas `f x₁…xₙ ∼ f x₁'…xₙ'`. `Mathlib.Tactic.GCongr.Core` enforces `lhsHead == rhsHead && arity ==` at three sites: lemma registration (`makeGCongrLemma`), the runtime descent (`Lean.MVarId.gcongr`), and the single-head lookup key (`GCongrKey`). A `RelatedBinOp`-shaped lemma cannot even be tagged. This is *why* the family needs `rcongr`/`hgcongr`. `GCongrProbe.lean` records the rejection with a control (`add_mono_probe`, accepted) and a cross-head record (`cross_head_realization`, left untagged); `HGCongr.lean`'s "Upstream patch" section carries the exact 3-site head-pair patch that lifts the restriction upstream. --- ## Conv / cast / coe family These plug transfer into native rewriting (`conv`), into `norm_cast`-style witnesses, and into elaboration-time coercion. ### `transferConv` (conv step) 1. **Purpose.** Rewrite a focused sub-term to its transferred form *inside a context*, justified by the `Related` instance composite. 2. **Applies to / produces.** A `conv` step. On the focus `t`: discover the transferred shape `t'` via the `@[transfer]` simp set, prove `t = t'` by synthesizing `Related id t t'` (composing registered `RelatedBinOp` squares, extracted via `transferGround`), and install that proof — **the typeclass composite, not the simp proof**. 3. **Example.** ```lean example (a b c : F) (P : F → Prop) (h : P (bbFieldAdd (bbFieldMul a b) c)) : P (a * b + c) := by conv in (a * b + c) => transferConv exact h ``` 4. **When to use vs alternatives.** Use to transfer one sub-term in the middle of a larger goal, alongside `rw`/`simp`/`gcongr`. For the whole goal, use `transfer`. For the simp proof (rather than the typeclass composite), use `transferSimpConv`. 5. **Gotchas.** Scope is the closed first-order, identity-encoding (`id`) op-tree fragment `Related.lean` covers — no binder traversal, no richer encodings. The focus type must live in a `Type u` universe (the proof is built at that level). The `Related id t t'` goal is elaborated *from source syntax* so `composeBinOp` keys on the source-elaborated `id` (a hand-assembled `mkApp` is defeq but does not match instance resolution). 6. **File.** `ParamConv.lean`. ### `transferSimpConv` (conv step) 1. **Purpose.** The simp-set-driven complement of `transferConv`. 2. **Applies to / produces.** A `conv` step; a thin wrapper for `simp only [transfer]` on the focus — the equational `@[transfer]` realization set with the simp proof. 3. **Example.** ```lean example (a b c : F) (P : F → Prop) (h : P (bbFieldAdd (bbFieldMul a b) c)) : P (a * b + c) := by conv in (a * b + c) => transferSimpConv exact h ``` 4. **When to use vs alternatives.** Use when the simp rewrite suffices and the typeclass-composite proof of `transferConv` is unneeded. It is the `conv`-mode form of `repr_transfer`. 5. **Gotchas.** Only as strong as the `@[transfer]` equational set; carries no relatedness proof beyond the simp justification. 6. **File.** `ParamConv.lean`. ### `repr_transfer` / `repr_transfer!` 1. **Purpose.** Whole-goal Phase-1 transfer: rewrite the goal's abstract operations into their registered emitted kernels. 2. **Applies to / produces.** `repr_transfer` ≡ `simp only [transfer]`; `repr_transfer!` ≡ `simp only [transfer] <;> rfl` (also closes by reflexivity). 3. **Example.** `by repr_transfer!` closes a goal whose two sides differ only by registered `@[transfer]` realizations. 4. **When to use vs alternatives.** The simplest "compile to the emitted leaf" driver. `transfer` adds binder traversal and a richer leaf cascade; the `param_*` tactics add cross-head descent and closure. 5. **Gotchas.** Pure simp — no proof-term parametricity, no level tracking, no cross-head descent. Only the registered equational set. 6. **File.** `Core.lean`. ### `norm_cast` move-lemmas as `Param` witnesses 1. **Purpose.** A `@[norm_cast]` move lemma `↑(a ⋄ b) = ↑a ⋄ ↑b` **is** a Trocq `Param` binary relatedness witness for the cast graph `R a a' := (↑a = a')`. 2. **Applies to / produces.** Not a tactic — a *correspondence* the translator consumes. `addCastWit` (from `Nat.cast_add`) and `mulCastWit` (from `Nat.cast_mul`) are `RArrow NatIntR (RArrow NatIntR NatIntR) op op'` witnesses; `paramWitOfCastHom` exhibits the generic equivalence (a cast-homomorphism property *is* the curried `RArrow` witness). 3. **Example.** Wired into `castOpDB`/`castTyDB`, the translator transfers a whole `ℕ`-term across `ℕ ↦ ℤ`: ```lean translateAll castOpDB castTyDB {} {} ⟦fun n : ℕ => n + n * n⟧ -- ⊢ ∀ n n', ↑n = n' → ↑(n + n * n) = n' + n' * n' ``` 4. **When to use vs alternatives.** Use to transfer across a coercion graph using the existing `norm_cast` lemma set as operator witnesses — Trocq is `norm_cast` generalized from coercions to arbitrary registered representations. 5. **Gotchas.** Demonstrated for the binary case over `ℕ → ℤ` with `+`/`*`; the `n`-ary generalization is the same operator-spine stripping. The witnesses feed the term translator, not the `Related`-engine tactics directly. 6. **File.** `ParamNormCast.lean`. ### `Coe` / `CoeTC` from a `Param` forward map 1. **Purpose.** Derive a Lean coercion from a `Param` witness's forward map, so a representation change fires during elaboration. 2. **Applies to / produces.** Instances, not a tactic. `coeOfParam`/`Param.fwdMap` project the forward function `A → B`; `coeTCOfHasParam` is a **scoped** blanket `CoeTC A B` from a synthesized `HasParam .map1 .map1 A B`. 3. **Example.** ```lean instance coeNatWrap : Coe Nat Wrap where coe := coeOfParam natWrapParam example (a : Nat) : Wrap := a -- Wrap.mk inserted by the elaborator example (a : Nat) : ((a : Wrap)) = Wrap.mk a := rfl ``` The scoped blanket fires under `open scoped Transfer.Param`: `example (b : Boxed) : Nat := b`. 4. **When to use vs alternatives.** Use for transparent, per-pair representation insertion at elaboration. To *also* keep the relatedness proof (not just the function), use `param_transfer` — a coercion drops the proof. 5. **Gotchas.** Lean has **no** general coercion-fallback hook (unlike Coq-Elpi's `trocqoercion`), so this is per-`(A, B)`, keyed on the instance cache. The blanket is `scoped` (opt-in) on purpose: a global version over-fires (every `idHasParam`, re-entrant arrow search) on any type mismatch. A specific `Coe` is the safest form. 6. **File.** `ParamCoe.lean`. --- ## Automation integration family These expose the engine through `grind`, `aesop`, and `mvcgen`/`Std.Do` wp. ### `grind` integration (`@[grind =]` dual-tagging) 1. **Purpose.** Make `grind` a transfer leaf-discharger by dual-tagging realization squares into its database. 2. **Applies to / produces.** `attribute [grind =] mul_repr add_repr` adds the already-`@[transfer]` realization lemmas as `grind` rewrite candidates; `grind` then composes them through its congruence closure. 3. **Example.** ```lean attribute [grind =] mul_repr add_repr theorem grind_leaf (a b c : F) : a * b + c = bbFieldAdd (bbFieldMul a b) c := by grind ``` 4. **When to use vs alternatives.** Use to close transfer *leaf* equations (the closed first-order composites) in one `grind`, with no positional `rw` chain. This dual-tag is what makes `param_cc`'s closure work — the registered squares are already in `grind`'s DB. `transfer`'s leaf cascade falls back to `grind` last. 5. **Gotchas.** Safe only when the emitted kernel is **opaque** on the RHS of each square (so `grind` never chases the underlying `BitVec 64` arithmetic, which it can time out on). The dual-tag pattern is per realization lemma. 6. **File.** `GrindIntegration.lean`. ### The `Transfer` aesop rule set 1. **Purpose.** An opt-in aesop rule set bundling the transfer machinery as aesop rules. 2. **Applies to / produces.** `transferGround` as a **safe apply** rule; `transferCore` (the `transfer` driver) as an **unsafe 50% tactic** rule. Invoked with `aesop (rule_sets := [Transfer])`. 3. **Example.** ```lean example (a b c : F) : a * b + c = bbFieldAdd (bbFieldMul a b) c := by aesop (rule_sets := [Transfer]) example (c : F) : ∀ a b : F, a * b + c = bbFieldAdd (bbFieldMul a b) c := by aesop (rule_sets := [Transfer]) ``` 4. **When to use vs alternatives.** Use when aesop's search should dispatch transfer-shaped goals (ground composites + quantified/function-equality shapes). For a single goal, the dedicated tactics are more direct. 5. **Gotchas.** The set is **OFF by default and never folded into the default set**: aesop fails open, so an always-on transfer rule could mask a *missing* square (the exact failure the layer surfaces). A rule set declared with `declare_aesop_rule_sets` is invisible in the declaring file, so the declaration (`AesopRuleSet.lean`) is split from the registrations and uses (`AesopIntegration.lean`); register rules and invoke the named set only from an importer. 6. **File.** `AesopIntegration.lean` (registrations + demos); declaration in `AesopRuleSet.lean`. ### `mvcgen` / `Std.Do` `wp` triple transfer (`RComp`) 1. **Purpose.** Transfer a Hoare/`wp` triple along a value relation, lifted to computations through the Kleisli relation `RComp`. 2. **Applies to / produces.** Lemmas, not a tactic. `RComp Rα c c'` is `wp`-refinement modulo `Rα`; `RComp.pure`/`RComp.bind`/`RComp.refl` are the compositional core; `triple_transfer` turns `⦃P⦄ c ⦃Q, E⦄` into `⦃P⦄ c' ⦃Q', E⦄` given an `RComp`-witness and postcondition relatedness. 3. **Example.** A concrete `SPComp` instantiation (`SPComp.triple_transfer`) transfers the triple of `SPComp.pure true` to that of `SPComp.pure false` across `Rα b b' := (b = true ∧ b' = false)`. 4. **When to use vs alternatives.** Use to transport a Hoare triple between two monadic programs related at the value level — the abstraction theorem at the monad level. For pure `∀`-statements, use `param_transfer`. 5. **Gotchas.** The `RComp`-witness is assembled by `rcomp` (above) — or by hand from `RComp.pure`/`RComp.bind` for a non-structurally-parallel program; full `mvcgen`-driven witness generation is not provided. Scope is `Prop`-predicate `wp` triples; the quantitative/`Advantage` route is out of scope (expectation transformers are monotone but not conjunctive). 6. **File.** `ParamTripleTransfer.lean`. --- ## Decision by bounded computation These tactics decide identities over `ZMod m` by transferring them to a bounded computation on integer representatives and checking it with a kernel `decide`. Neither uses `Lean.ofReduceBool`. ### `decide_zmod` 1. **Purpose.** Close a ground ring identity over `ZMod m` by bounded residue computation. 2. **Applies to / produces.** An equation between two closed `ZMod m` terms built from numerals, `+`, `-`, `*`, negation and `^` with a literal exponent. Reifies both sides into `RingExpr` and discharges the goal through `RingExpr.decide_transfer` and a kernel `decide` on the reduced integer residues. 3. **Example.** ```lean example : (((2 : ZMod 7) ^ 3 + 3 * 4) - 5 : ZMod 7) = (1 : ZMod 7) := by decide_zmod ``` 4. **When to use vs alternatives.** Use for a ground modular identity whose modulus or operands are too large for `decide` on `ZMod m` itself. For an identity with a variable, use `decide_zmod_poly`. 5. **Gotchas.** Every leaf must be a numeral; a free `ZMod m` variable or a non-literal exponent is rejected. 6. **File.** `Examples/ZModDecide.lean`. ### `decide_zmod_poly` 1. **Purpose.** Close a univariate polynomial identity over `ZMod m` by bounded coefficient-list computation. 2. **Applies to / produces.** A goal `∀ x : ZMod m, p x = q x`. Introduces `x`, reifies both sides into `PolyExpr`, and discharges the goal through `PolyExpr.decide_transfer_poly` and a kernel `decide` on the reduced coefficient lists. 3. **Example.** ```lean example : ∀ x : ZMod 13, (x - 3) * (x + 3) = x ^ 2 - 9 := by decide_zmod_poly ``` 4. **When to use vs alternatives.** Use for a polynomial identity in one variable over a concrete modulus. For a ground identity, `decide_zmod` is sufficient. 5. **Gotchas.** Every leaf must be the bound variable or a numeral, and exponents must be literals. 6. **File.** `Examples/ZModPolyDecide.lean`. --- ## Deriving and level inference ### `deriving Param` / `@[derive Param]` 1. **Purpose.** Generate the parametricity lift of an inductive from its constructor signatures. 2. **Applies to / produces.** A `deriving Param` clause (or `deriving instance Param for T`). Emits the constructor-wise relation `T.R_param`; for **non-recursive** inductives (records/enums) and **uniform-recursive** ones (List/Tree-shape) it additionally synthesizes the forward map `T.paramMap` and a full `Param .map3 .map0` instance `T.param_instance` (so the result feeds `castViaParam`). 3. **Example.** ```lean structure ElGamalCt (G : Type) where c1 : G c2 : G deriving Param -- generated ElGamalCt.R_param: two ciphertexts related iff components are theorem elgamal_ct_related {G G' : Type} (P : G → G' → Prop) (a1 a2 : G) (b1 b2 : G') (h1 : P a1 b1) (h2 : P a2 b2) : ElGamalCt.R_param P (ElGamalCt.mk a1 a2) (ElGamalCt.mk b1 b2) := ElGamalCt.R_param.mk h1 h2 ``` 4. **When to use vs alternatives.** Use to obtain a `Param` lift mechanically for a crypto record/enum or a uniform-recursive container, instead of hand-porting it (`R_prod`/`R_list` shapes). For arbitrary terms, use `#transfer`. 5. **Gotchas.** Rejects **mixed-variance** inductives (a parameter in both co- and contravariant position, e.g. a field `A → A`) with `NonExample (Mixed variance)`, and purely contravariant occurrences likewise. Declines **nested/reflexive/indexed** inductives up front (`isNested || isReflexive || numIndices ≠ 0` → handler returns `false`) — no faux fallback. The handler is live only in *downstream* files (the `initialize` registration takes effect after import). 6. **File.** `ParamDeriveHandler.lean` (the handler, `IndDesc`, variance guard); `ParamDerive.lean`/`ParamData.lean` carry the hand-ported shapes (`R_sum`/`R_nat`/`R_prod`/`R_option`/`R_list`). ### Level inference for tactic authors — `inferRootClass` / `inferRootClassExpr` 1. **Purpose.** Compute the minimal `MapClass` an occurrence requires — the constraint-graph least-fixpoint solver over the proven lattice. 2. **Applies to / produces.** Pure/`MetaM` functions, not a tactic. `inferParamLevels : TyShape → (Nat × Assign)` and `inferRootClass : TyShape → MapClass` work on the simplified `TyShape` core (`base`/`arrow`/`forallT`); `inferParamLevelsExpr`/`inferRootClassExpr` are the `Expr` front-ends (walking a real Lean type via `exprToTyShape`, with `@[param]`-registry lower bounds and an override table). 3. **Example.** ```lean example : inferRootClass (.arrow .leaf .leaf) = .map0 := by native_decide example : inferRootClass (.arrow .leaf (.base (some .map3))) = .map3 := by native_decide ``` 4. **When to use vs alternatives.** Use when building a level-directed tactic: read off `inferRootClass` for the (shape-abstracted) type, synthesize at that class, then `Param.weaken`/`auto_weaken` down. This generalizes the fixed output class of `transfer_auto`. 5. **Gotchas.** An unconstrained shape minimizes to `map0` (never the inconsistent `map4`). The traversal treats an operator or higher-order application spine as a leaf at its head, and a `Sort` level as a `map0` leaf; a registered head with no machine-readable class defaults to `map1` (override-refinable via the `Std.HashMap Name MapClass` override). 6. **File.** `ParamInfer.lean`. ### `derive_param_congr T` / `deriving ParamCongr` 1. **Purpose.** Generate the constructor congruence that lets the `Related` kernel cross a structure boundary. 2. **Applies to / produces.** A command on a single-constructor, non-indexed structure `T` with at least one field. Reads the constructor's fields and emits a `ParamEnc T α` instance, the product encoding `enc x = (ParamEnc.enc x.f₁, …, ParamEnc.enc x.fₙ)`, and the constructor congruence `Related ParamEnc.enc (T.mk a₁ … aₙ) (a₁', …, aₙ')` from the per-field `Related ParamEnc.enc aᵢ aᵢ'` facts. Field encodings resolve through `ParamEnc`, so nested derived structures compose. 3. **Example.** `derive_param_congr T` in the file that declares `T`, or `deriving instance ParamCongr for T` in a downstream file; instance resolution then transports a value of `T` with the constructor congruence on top and the `RelatedBinOp` squares of the field carrier underneath. 4. **When to use vs alternatives.** Use for the `Related` engine. For the `Param` engine's constructor-wise relation, use `deriving Param`. 5. **Gotchas.** Declines a multi-constructor or indexed inductive and a structure with no fields. The `deriving` form is available only in files that import `ParamCongr.lean`. 6. **File.** `Deriving/ParamCongr.lean`. ### `#transfer_level t` and `transfer!` 1. **Purpose.** Report, and act on, the relatedness level a goal requires. 2. **Applies to / produces.** `#transfer_level t` is a command on a type `t`: it infers the goal's level from its `Expr` and logs the level and whether the univalence-free guard permits it. `transfer!` is the tactic form: it infers the level of the current goal and either refuses with the guard's report or logs the level and runs `transfer`. 3. **Example.** ```lean #transfer_level (∀ a b : Nat, a + b = b + a) #transfer_level ((ULift.{0} Bool) = Bool) example (a b c : F) : a * b + c = bbFieldAdd (bbFieldMul a b) c := by transfer! ``` 4. **When to use vs alternatives.** Use `#transfer_level` to inspect a goal without running a proof, and `transfer!` in place of `transfer` when a goal at the refused `map4` level should fail with a report. 5. **Gotchas.** The guard refuses the `equiv` level (`map4`), where type-level univalence stated through `Eq` is inconsistent (`LevelRefusal.lean`). 6. **File.** `Base/TransferLevel.lean`. --- ## Registration attributes | Attribute / clause | Registers | Consumed by | File | |---|---|---|---| | `@[param]` | a `RArrow PA PB c c'` witness lemma: `c ↦ (c', lemma)` in the persistent constant DB | `#transfer` / `translateAll` (`const` rule) | `ParamDB.lean` | | `@[transfer]` | an `abstract-op = emitted-kernel` simp lemma (e.g. `a * b = bbFieldMul a b`) | `repr_transfer`, `transfer`'s leaf cascade, `transferConv` shape discovery, `transferSimpConv` | `Core.lean` | | `@[hgcongr]` | a cross-head congruence lemma `R (f a..) (g b..)`, keyed on the head pair `(f, g)` + relation | `hgcongr` | `HGCongrInit.lean` | | `@[grind =]` (dual-tag) | a realization square into `grind`'s rewrite DB | `grind`, `param_cc`'s closure leaf | `GrindIntegration.lean` | | `deriving Param` / `@[derive Param]` | the constructor-wise lift `T.R_param` (+ `Param .map3 .map0` instance for non/uniform-recursive) | downstream uses of the generated relation/instance | `ParamDeriveHandler.lean` | | `Transfer` aesop rule set | `transferGround` (safe apply) + `transferCore` (unsafe tactic) | `aesop (rule_sets := [Transfer])` | `AesopRuleSet.lean` (decl), `AesopIntegration.lean` (rules) | | `RegisteredParam` instance | one `Param m n A B` witness at its strongest class (`(m,n)` an `outParam`) | `auto_weaken` | `ParamAutoWeaken.lean` | | `TransferDom` instance | the domain `Param .map0 .map2a A A'` for a representation change | `param_transfer` / `transfer_auto` | `ParamTransfer.lean`, `ParamRetraction.lean` | Notes: * `@[param]` peels the `RArrow PA PB c c'` from the lemma type's last two of its eight application arguments; the lemma type must be a literal `RArrow …` (it is not `whnf`'d). The DB is cross-file persistent. * The simp attribute is named `transfer` (not `repr`) to avoid clashing with `Repr.repr` (`register_simp_attr transfer`, `Core.lean`). * `@[hgcongr]` rejects a lemma with no varying-argument hypothesis. The diagonal pair `(f, f)` is exactly a `@[gcongr]`-shaped lemma, so `@[hgcongr]` subsumes the homogeneous case. * `register_simp_attr` / `declare_aesop_rule_sets` / `initialize` env-extensions are invisible in their declaring file — each lives in a small module imported by its consumers (`Core.lean`, `AesopRuleSet.lean`, `HGCongrInit.lean`, `ParamDB.lean`). --- ## Tactic selection | Given | Use | |---|---| | a relational goal, closing strategy unclear (or a stable call site wanted) | `param_auto` | | a fixed equation between two representations (cross-head op-tree) | `rcongr` (or `param_solve`) | | a relatedness goal needing transitivity / context-hypothesis chaining | `param_cc` (or `param_solve`) | | a goal that might need either descent or chaining (don't know which) | `param_solve` | | an op-tree whose squares hold only on a range (overflow, `b ≤ a`, shift width) | `param_guard` | | cross-head congruence with attribute-tagged, relation-generic lemmas | `hgcongr` | | transfer a `∀`-statement to another representation | `param_transfer` | | transfer a `∀`-statement *or* an `R_arrow` `app`-goal, one entry | `transfer_auto` | | synthesize the transferred *term* + its proof | `#transfer` | | a `Param m n A B` witness at a specific level | `param_resolve` | | a low-class `Param` goal from one strong registration | `auto_weaken` | | close an equation/`Iff`-of-`∀` by binder traversal + registry leaf | `transfer` | | rewrite one sub-term inside a larger goal | `transferConv` (typeclass proof) / `transferSimpConv` (simp proof) | | compile a whole goal to emitted kernels | `repr_transfer` / `repr_transfer!` | | close a transfer leaf equation by congruence closure | `grind` (with `@[grind =]` squares) | | the `Param` lift of a data type | `deriving Param` | | assemble an `RComp` witness for two structurally parallel programs | `rcomp` (or `param_transfer`) | | transfer a Hoare/`wp` triple between related programs | `triple_transfer` (via `RComp`) | | relate a failing program to a total one, success-restricted | `rcomp_ok` (or `param_transfer`), then `RCompOk.transfer` | | a `Param .map1 .map1` witness for a closed type | `synth_param` | | induction on a representation equivalent to `ℕ` | `transfer_induction` | | a leaf closed by a native tactic, inside a cross-head descent | `param_leaf` / `param_compose` | | congruence across *different* fiber types | `hcongr_dep` / `hcongr_transport` | | a ground or univariate polynomial identity over `ZMod m` | `decide_zmod` / `decide_zmod_poly` | | constructor congruence for the `Related` engine | `derive_param_congr` | | the level a goal requires | `#transfer_level` / `transfer!` | Two cautions that recur: * **`gcongr` cannot do cross-head** (different head functions left vs right) — the reason `rcongr`/`hgcongr` exist (`GCongrProbe.lean`). * **Over the encoding relation `param_cc`/`param_solve` overlap `grind`**, since `Related enc a b` is definitionally `enc a = b`; their independent value is for a non-equational relation. The descent/closure split is the distinction that survives that collapse.