5.5. Targeted Lowerings
@[crush_lower target] registers a handler only for applications whose head is
target.
The handler receives the original Lean arguments and recursive emitTerm and
emitSort callbacks.
The head and arguments are syntactic and are not weak-head-normalized before
dispatch; use the available MetaM operations when a handler needs reduction.
An argument may be a variable standing for a shared let value; ctx.openLet
replaces it by its value and keeps the variables inside. A handler that declines
is retried with the values substituted, and a subterm it translates that is still
a let value translates as that variable.
It returns some term when it recognizes an application and none to defer:
open Crush
def clampNonnegative (x : Int) : Int :=
if x < 0 then 0 else x
@[crush_lower clampNonnegative high]
def lowerClampNonnegative : LoweringHandler := fun ctx => do
let #[x] := ctx.args | return none
let sx ← ctx.emitTerm x
return some (smt| (ite (< $sx 0) 0 $sx))
example (x : Int) (hx : 0 ≤ x) :
clampNonnegative x = x := x:Inthx:0 ≤ x⊢ clampNonnegative x = x
All goals completed! 🐙
Multiple handlers may target the same declaration.
As shown by lowerClampNonnegative, a numeric priority or high/low controls
their order in the same style as simp.
Unrelated heads never invoke a targeted handler. Use ctx.declare when its
encoding needs fresh SMT declarations.
A handler must decline any shape it cannot encode exactly.
In particular, lowerings for overloaded operations should verify argument types
and call ctx.hasExpectedInstance with the exact dictionary whose semantics they
implement before assigning a standard typeclass operation its SMT meaning.
ctx.hasCanonicalInstance is deprecated: it recognizes only the fixed built-in
operator dictionaries and returns false for other operators. Custom lowerings
must use ctx.hasExpectedInstance with a mkConst expression naming their own
dictionary declaration. Comparing against ambient typeclass synthesis is unsafe:
a higher-priority instance can change the operation's meaning.
ctx.hasInstanceHead is available for dependent dictionaries whose proof
parameters make full definitional equality impractical.