Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 77 additions & 15 deletions Qq/Match.lean
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ Compare to the builtin `match_expr` and `let_expr`, `~q()` matching:
* matches by definitional equality, rather than expression equality
* supports compound expressions, not just a single application

The variant `~q!(<pattern>)` matches by structural equality instead: no definitions
(not even `@[reducible]` ones) are unfolded during the match test.

See `Qq.matcher` for a brief syntax summary.

## Matching typeclass instances
Expand Down Expand Up @@ -79,22 +82,30 @@ def mkInstantiateMVars (decls : List PatVarDecl) : List PatVarDecl → MetaM Q(M
mkLambdaQ _ decl.fvar q($(← mkInstantiateMVars decls rest))
return q(Bind.bind (instantiateMVars $(decl.fvar)) $instMVars)

def mkIsDefEqCore (decls : List PatVarDecl) (pat discr : Q(Expr)) :
def mkIsDefEqCore (structural : Bool) (decls : List PatVarDecl) (pat discr : Q(Expr)) :
List PatVarDecl → MetaM Q(MetaM $(mkIsDefEqType decls))
| { ty := none, fvarId := fvarId, userName := userName } :: rest =>
let decl : PatVarDecl := { ty := none, fvarId := fvarId, userName := userName }
return q(Bind.bind mkFreshLevelMVar $(← mkLambdaQ `x decl.fvar (← mkIsDefEqCore decls pat discr rest)))
return q(Bind.bind mkFreshLevelMVar $(← mkLambdaQ `x decl.fvar (← mkIsDefEqCore structural decls pat discr rest)))
| { ty := some ty, fvarId := fvarId, userName := userName } :: rest =>
let decl : PatVarDecl := { ty := some ty, fvarId := fvarId, userName := userName }
return q(Bind.bind (mkFreshExprMVar $ty) $(← mkLambdaQ `x decl.fvar (← mkIsDefEqCore decls pat discr rest)))
return q(Bind.bind (mkFreshExprMVar $ty) $(← mkLambdaQ `x decl.fvar (← mkIsDefEqCore structural decls pat discr rest)))
| [] => do
let instMVars ← mkInstantiateMVars decls decls
return q(do
let matches? ← withReducible $ isDefEq $pat $discr
(if matches? then $instMVars else return $(mkIsDefEqResult false decls)))
if structural then
-- `.none` transparency performs no delta-unfolding at all, so constants compare
-- by name and the match is purely structural (modulo β/η and metavariable
-- assignment for the antiquotations).
return q(do
let matches? ← withTransparency .none $ isDefEq $pat $discr
(if matches? then $instMVars else return $(mkIsDefEqResult false decls)))
else
return q(do
let matches? ← withReducible $ isDefEq $pat $discr
(if matches? then $instMVars else return $(mkIsDefEqResult false decls)))

def mkIsDefEq (decls : List PatVarDecl) (pat discr : Q(Expr)) : MetaM Q(MetaM $(mkIsDefEqType decls)) := do
return q(withNewMCtxDepth $(← mkIsDefEqCore decls pat discr decls))
def mkIsDefEq (structural : Bool) (decls : List PatVarDecl) (pat discr : Q(Expr)) : MetaM Q(MetaM $(mkIsDefEqType decls)) := do
return q(withNewMCtxDepth $(← mkIsDefEqCore structural decls pat discr decls))

def withLetHave [Monad m] [MonadControlT MetaM m] [MonadLiftT MetaM m] [MonadLCtx m]
(fvarId : FVarId) (userName : Name) (val : (Quoted α)) (k : (Quoted α) → m (Quoted β)) : m (Quoted β) := do
Expand All @@ -118,6 +129,7 @@ def replaceTempExprsByQVars : List PatVarDecl → Expr → Expr
replaceTempExprsByQVars decls e

def makeMatchCode {γ : Q(Type)} {m : Q(Type → Type v)} (_instLift : Q(MonadLiftT MetaM $m)) (_instBind : Q(Bind $m))
(structural : Bool)
(decls : List PatVarDecl) (uTy : Q(Level)) (ty : Q(Quoted (.sort $uTy)))
(pat discr : Q(Quoted $ty)) (alt : Q($m $γ)) (expectedType : Expr)
(k : Expr → TermElabM Q($m $γ)) : TermElabM Q($m $γ) := do
Expand All @@ -143,7 +155,7 @@ def makeMatchCode {γ : Q(Type)} {m : Q(Type → Type v)} (_instLift : Q(MonadLi
$alt)
return show Q($(mkIsDefEqType decls) → $m $γ) from
Quoted.unsafeMk $ ← mkLambda' `__result fv (mkIsDefEqType decls) next
pure q(Bind.bind $(← mkIsDefEq decls pat discr) $next)
pure q(Bind.bind $(← mkIsDefEq structural decls pat discr) $next)

def unquoteForMatch (et : Expr) : UnquoteM (LocalContext × LocalInstances × Expr) := do
unquoteLCtx
Expand Down Expand Up @@ -224,7 +236,8 @@ def elabPat (pat : Term) (lctx : LocalContext) (localInsts : LocalInstances) (ty
← sortLocalDecls (← newDecls.mapM fun d => instantiateLocalDeclMVars d),
r.newParamNames)

scoped elab "_qq_match" pat:term " ← " e:term " | " alt:term " in " body:term : term <= expectedType => do
def elabQqMatch (structural : Bool) (pat e alt body : Term) (expectedType : Expr) :
TermElabM Expr := do
let emr ← extractBind expectedType
let alt ← elabTermEnsuringType alt expectedType

Expand Down Expand Up @@ -254,13 +267,23 @@ scoped elab "_qq_match" pat:term " ← " e:term " | " alt:term " in " body:term
let inst2 ← synthInstanceQ q(MonadLiftT MetaM $m)
have synthed : Q(Expr) := (← quoteExpr (← instantiateMVars pat) s)
let alt : Q($m $γ) := alt
makeMatchCode q($inst2) inst oldPatVarDecls argLvlExpr argTyExpr synthed q($e') alt expectedType fun expectedType =>
makeMatchCode q($inst2) inst structural oldPatVarDecls argLvlExpr argTyExpr synthed q($e') alt expectedType fun expectedType =>
return Quoted.unsafeMk (← elabTerm body expectedType)

scoped elab "_qq_match" pat:term " ← " e:term " | " alt:term " in " body:term : term <= expectedType =>
elabQqMatch false pat e alt body expectedType

/-- Structural variant of `_qq_match`: no definition unfolding during the match test. -/
scoped elab "_qq_match_struct" pat:term " ← " e:term " | " alt:term " in " body:term : term <= expectedType =>
elabQqMatch true pat e alt body expectedType

scoped syntax "_qq_match" term " := " term " | " doSeqIndent : term
scoped syntax "_qq_match_struct" term " := " term " | " doSeqIndent : term
macro_rules
| `(assert! (_qq_match $pat := $e | $alt); $x) =>
`(_qq_match $pat ← $e | (do $alt:doSeqIndent) in $x)
| `(assert! (_qq_match_struct $pat := $e | $alt); $x) =>
`(_qq_match_struct $pat ← $e | (do $alt:doSeqIndent) in $x)

partial def isIrrefutablePattern : Term → Bool
| `(($stx)) => isIrrefutablePattern stx
Expand Down Expand Up @@ -323,15 +346,38 @@ in the example above `~q` also inserts into the context a term of type `$n =Q Na
-/
scoped syntax (name := matcher) "~q(" term ")" : term

/--
`Qq`s *structural* expression matching in `MetaM`, a variant of `~q`.

`~q!(<pattern>)` behaves exactly like `~q(<pattern>)`, except that the match test compares
the pattern with the discriminant without unfolding any definitions
(`withTransparency .none`): constants compare by name, and `@[reducible]` definitions are
*not* unfolded. Antiquotations still capture subexpressions as usual
(metavariable assignment, β/η are unaffected by the transparency setting).

Use this when only exact syntactic matches are desired; besides being more predictable,
it avoids the definition unfolding that `~q` performs (at reducible transparency),
which can be significantly cheaper for large expressions.

Like `~q`, this syntax is valid in `match`, `let`, and `if let`.
-/
scoped syntax (name := matcherStructural) "~q!(" term ")" : term

partial def Impl.hasQMatch : Syntax → Bool
| `(~q($_)) => true
| `(~q!($_)) => true
| stx => stx.getArgs.any hasQMatch

partial def Impl.floatQMatchPairs : Term → StateT (Array (Term × Ident)) MacroM Term
partial def Impl.floatQMatchPairs : Term → StateT (Array (Term × Ident × Bool)) MacroM Term
| `(~q($term)) =>
withFreshMacroScope do
let x : Ident ← `(x)
modify (·.push (term, x))
modify (·.push (term, x, false))
`($x)
| `(~q!($term)) =>
withFreshMacroScope do
let x : Ident ← `(x)
modify (·.push (term, x, true))
`($x)
| stx => do match stx with
| ⟨.node i k args⟩ => return ⟨.node i k (← args.mapM (floatQMatchPairs ⟨·⟩))⟩
Expand Down Expand Up @@ -406,13 +452,20 @@ private def buildPatternTerm (discr : Term) (pat : Term) (body : Term) : MacroM
-- directly preserves the type at the relevant elaboration phase.
let (inner, lifts) ← (floatExprAntiquot 0 inner).run #[]
liftsToTermLet lifts (← `(_qq_match $inner ← $discr | __alt in $body))
| `(~q!($inner)) =>
-- Whole-pattern `~q!(...)`: same fast path, routed to the structural variant.
let (inner, lifts) ← (floatExprAntiquot 0 inner).run #[]
liftsToTermLet lifts (← `(_qq_match_struct $inner ← $discr | __alt in $body))
| _ =>
if hasQMatch pat then
let (pat', auxPairs) ← (floatQMatchPairs pat).run #[]
let mut body := body
for (innerPat, varName) in auxPairs.reverse do
for (innerPat, varName, structural) in auxPairs.reverse do
let (innerPat, lifts) ← (floatExprAntiquot 0 innerPat).run #[]
body ← liftsToTermLet lifts (← `(_qq_match $innerPat ← $varName | __alt in $body))
if structural then
body ← liftsToTermLet lifts (← `(_qq_match_struct $innerPat ← $varName | __alt in $body))
else
body ← liftsToTermLet lifts (← `(_qq_match $innerPat ← $varName | __alt in $body))
if isIrrefutablePattern pat' then
-- Multi-q irrefutable case (e.g. `(~q(X), ~q(Y))`): the let destructures `discr`
-- via the pattern, which propagates component types to the inner `_qq_match`s.
Expand Down Expand Up @@ -442,6 +495,15 @@ macro_rules
items := items.push (← `(doSeqItem| do $body:doSeqIndent))
`(doElem| do $items:doSeqItem*)

| `(~q!($pat)) =>
-- Same direct route for the structural variant.
let (pat, lifts) ← floatExprAntiquot 0 pat #[]
let t ← `(doSeqItem| assert! (_qq_match_struct $pat := $rhs | $alt))
let mut items := (← liftsToDoItems lifts).push t
if let some body := body? then
items := items.push (← `(doSeqItem| do $body:doSeqIndent))
`(doElem| do $items:doSeqItem*)

| _ =>
let body ← match body? with
| some body => `(do $body:doSeqIndent)
Expand Down
178 changes: 178 additions & 0 deletions QqTest/structuralMatch.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import Qq
import Lean.Elab.Command
open Qq Lean Meta

/-!
# `~q!` structural matching

`~q!(<pattern>)` matches like `~q(<pattern>)`, but the match test runs at
`TransparencyMode.none`: no definitions (not even `@[reducible]` ones) are unfolded,
so constants compare by name.
-/

opaque k : Nat
opaque m : Nat

abbrev double (a : Nat) : Nat := a + a

@[reducible] def addRed (a b : Nat) : Nat := Nat.add a b

def addDef (a b : Nat) : Nat := Nat.add a b

/-- Structural variant: matches only the literal `Nat.add` head. -/
def matchAdd! (e : Q(Nat)) : MetaM (Option (Q(Nat) × Q(Nat))) := do
match e with
| ~q!(Nat.add $x $y) => return some (x, y)
| _ => return none

/-- Reducible-defeq control (`~q`). -/
def matchAdd (e : Q(Nat)) : MetaM (Option (Q(Nat) × Q(Nat))) := do
match e with
| ~q(Nat.add $x $y) => return some (x, y)
| _ => return none

/-- `+` pattern, structural variant. -/
def matchPlus! (e : Q(Nat)) : MetaM (Option (Q(Nat) × Q(Nat))) := do
match e with
| ~q!($x + $y) => return some (x, y)
| _ => return none

/-- `+` pattern, reducible-defeq control. -/
def matchPlus (e : Q(Nat)) : MetaM (Option (Q(Nat) × Q(Nat))) := do
match e with
| ~q($x + $y) => return some (x, y)
| _ => return none

/-- Pattern with a reducible constant head, structural variant. -/
def matchAddRed! (e : Q(Nat)) : MetaM (Option (Q(Nat) × Q(Nat))) := do
match e with
| ~q!(addRed $x $y) => return some (x, y)
| _ => return none

/-- Pattern with a reducible constant head, reducible-defeq control. -/
def matchAddRed (e : Q(Nat)) : MetaM (Option (Q(Nat) × Q(Nat))) := do
match e with
| ~q(addRed $x $y) => return some (x, y)
| _ => return none

-- TODO: this linter crashes on the `def` below (same as QqTest/hoMatching.lean)
set_option linter.constructorNameAsVariable false in
/-- Higher-order capture must still work structurally (mvar assignment is unaffected). -/
def matchExists! (e : Q(Prop)) : MetaM (Option Q(Nat → Nat → Prop)) := do
match e with
| ~q!(∃ x y, $p x y) => return some p
| _ => return none

/-- Literal constant matching at a higher universe in the structural variant. -/
def matchType3! (e : Q(Type 4)) : MetaM Bool := do
match e with
| ~q!(Type 3) => return true
| _ => return false

/-- Reducible-defeq control for `matchType3!`. -/
def matchType3 (e : Q(Type 4)) : MetaM Bool := do
match e with
| ~q(Type 3) => return true
| _ => return false

/-- A reducible alias for `Type 3`. -/
abbrev MyTy : Type 4 := Type 3

/-- `let ~q!` form. -/
def letMatch! (e : Q(Nat)) : MetaM Nat := do
let ~q!(Nat.add $x $_y) := e | return 0
if x == q(k) then return 1 else return 2

/-- `if let ~q!` form. -/
def ifLetMatch! (e : Q(Nat)) : MetaM Nat := do
if let ~q!($x + $y) := e then
if x == q(k) && y == q(k) then return 1 else return 2
else
return 0

/-- `~q!` nested inside an ordinary constructor pattern (exercises `floatQMatchPairs`). -/
def matchPair! (p : Q(Nat) × Bool) : MetaM Nat := do
match p with
| (~q!(Nat.add $x $_y), true) => if x == q(k) then return 1 else return 2
| _ => return 0

/-- info: true -/
#guard_msgs in
#eval show MetaM Bool from do
-- `~q` unfolds the `abbrev double` (reducible) and sees through to `k + k`
let x : Q(Nat) := q(double k)
match x with
| ~q($a + $b) => return true
| _ => return false

/-- info: false -/
#guard_msgs in
#eval show MetaM Bool from do
-- `~q!` compares structurally: `double k` is not an `HAdd.hAdd` application
let x : Q(Nat) := q(double k)
match x with
| ~q!($a + $b) => return true
| _ => return false

/-- info: some (Expr.const `k [], Expr.const `m []) -/
#guard_msgs in
#eval show MetaM (Option (Q(Nat) × Q(Nat))) from do
matchAdd! q(Nat.add k m)

/-- info: none -/
#guard_msgs in
#eval show MetaM (Option (Q(Nat) × Q(Nat))) from do
-- `k + m` elaborates to `HAdd.hAdd`; structurally different from `Nat.add`
matchAdd! q(k + m)

run_cmd Lean.Elab.Command.runTermElabM fun _ => do
let check (msg : String) (b : Bool) : MetaM Unit := unless b do throwError msg

-- 1. structural match on the exact head, with captures
let some (x, y) ← matchAdd! q(Nat.add k m) | throwError "1: no match"
check "1: capture x" (x == q(k))
check "1: capture y" (y == q(m))

-- 2. `HAdd.hAdd` vs `Nat.add`: neither variant matches (already true for `~q`)
check "2: ~q! HAdd" (← matchAdd! q(k + m)).isNone
check "2: ~q HAdd" (← matchAdd q(k + m)).isNone

-- 3. reducible definition in the *discriminant* is not unfolded by `~q!`
check "3: ~q! addRed discr" (← matchAdd! q(addRed k m)).isNone
check "3: ~q addRed discr" (← matchAdd q(addRed k m)).isSome

-- 4. reducible definition in the *pattern* is not unfolded by `~q!`
check "4: ~q! addRed pat" (← matchAddRed! q(Nat.add k m)).isNone
check "4: ~q addRed pat" (← matchAddRed q(Nat.add k m)).isSome

-- 5. default-transparency definitions are never unfolded (same for both)
check "5: ~q! addDef" (← matchAdd! q(addDef k m)).isNone
check "5: ~q addDef" (← matchAdd q(addDef k m)).isNone

-- 6. abbrev unfolding (`double k` is `k + k`): control difference
check "6: ~q! double" (← matchPlus! q(double k)).isNone
let some (x, _) ← matchPlus q(double k) | throwError "6: ~q double: no match"
check "6: ~q double capture" (x == q(k))

-- 7. higher-order capture `$p x y` still works structurally
let some p ← matchExists! q(∃ x y, x + 1 ≤ y) | throwError "7: no match"
-- `p` is captured partially applied (`fun x => LE.le (x + 1)`); applying it to
-- arguments recovers the body.
check "7: capture p" (q($p 37 42) == q(37 + 1 ≤ 42))
check "7: non-match" (← matchExists! q(∀ x : Nat, 0 ≤ x)).isNone

-- 8. matching at a higher universe (`Type 3` is `Sort 4`)
check "8: match" (← matchType3! q(Type 3))
check "8: ~q! abbrev non-match" (not (← matchType3! q(MyTy)))
check "8: ~q abbrev match (control)" (← matchType3 q(MyTy))

-- 9. `let ~q!` and `if let ~q!` forms
check "9: let (match)" ((← letMatch! q(Nat.add k m)) == 1)
check "9: let (no match)" ((← letMatch! q(addRed k m)) == 0)
check "9: if-let (match)" ((← ifLetMatch! q(k + k)) == 1)
check "9: if-let (no unfold)" ((← ifLetMatch! q(double k)) == 0)

-- 10. `~q!` nested in a constructor pattern
check "10: pair (match)" ((← matchPair! (q(Nat.add k m), true)) == 1)
check "10: pair (no match)" ((← matchPair! (q(addRed k m), true)) == 0)
check "10: pair (other)" ((← matchPair! (q(Nat.add k m), false)) == 0)
2 changes: 1 addition & 1 deletion lean-toolchain
Original file line number Diff line number Diff line change
@@ -1 +1 @@
leanprover/lean4:v4.36.0-rc1
leanprover/lean4:v4.37.0-rc1