fact
stringlengths 7
4.04k
| type
stringclasses 6
values | library
stringclasses 2
values | imports
listlengths 1
5
| filename
stringlengths 11
30
| symbolic_name
stringlengths 1
23
| docstring
stringclasses 5
values |
|---|---|---|---|---|---|---|
f (x : Prop) [Decidable x] : Int :=
by_elabq
Lean.logInfo x
Lean.logInfo x.ty
return q(if $x then 2 else 3)
```
See also: `run_tacq`.
-/
scoped
elab "by_elabq" e:doSeq : term <= expectedType => do
let lctx ← getLCtx
let levelNames := (← Term.getLevelNames).reverse -- these are backwards!
let (quotedCtx, assignments, quotedGoal) ← liftMetaM <| StateT.run'
(s := { mayPostpone := false }) do
let (quotedCtx, assignments) ← Impl.quoteLCtx lctx levelNames
let expectedType ← instantiateMVars expectedType
let quotedGoal : Q(Type) ←
if expectedType.hasMVar then pure q(TermElabM Expr)
else
let expectedTypeQ : Q(Expr) ← Qq.Impl.quoteExpr expectedType
pure <| q(TermElabM (Quoted $expectedTypeQ))
return (quotedCtx, assignments, quotedGoal)
let codeExpr : Expr ← withLCtx quotedCtx #[] do
let body ← Term.elabTermEnsuringType (← `(do $e)) quotedGoal
Term.synthesizeSyntheticMVarsNoPostponing
let body ← instantiateMVars body
if (← Term.logUnassignedUsingErrorInfos (← getMVars body)) then throwAbortTerm
mkLetFVarsFromValues assignments body
let code ← unsafe evalExpr (TermElabM Expr) q(TermElabM Expr) codeExpr
code
/--
`run_tacq` is the Qq analogue to `run_tac` which allows executing arbitrary `TacticM` code.
In contrast to `run_tac`, the local context of the main goal can be directly accessed as quoted
expressions. Optionally, the annotated goal can also be saved using the syntax `run_tacq $g =>`.
Example:
```
|
def
|
Qq
|
[
"Qq.Macro",
"Lean"
] |
Qq/Commands.lean
|
f
| null |
MVarSynth | term (quotedType : Expr) (unquotedMVar : MVarId) --> Quoted.unsafeMk _ _
| type (unquotedMVar : MVarId) --> Quoted _
| level (unquotedMVar : LMVarId) --> Level
meta structure UnquoteState where
/--
Quoted mvars in the outside lctx (of type `Level`, `Quoted _`, or `Type`).
The outside mvars can also be of the form `?m x y z`.
-/
mvars : List (Expr × MVarSynth) := []
/-- Maps quoted expressions (of type Level) in the old context to level parameter names in the new context -/
levelSubst : Std.HashMap Expr Level := {}
/-- Maps quoted expressions (of type Expr) in the old context to expressions in the new context -/
exprSubst : Std.HashMap Expr Expr := {}
/-- New unquoted local context -/
unquoted := LocalContext.empty
/-- Maps free variables in the new context to expressions in the old context (of type Expr) -/
exprBackSubst : Std.HashMap Expr ExprBackSubstResult := {}
/-- Maps free variables in the new context to levels in the old context (of type Level) -/
levelBackSubst : Std.HashMap Level Expr := {}
/-- New free variables in the new context that were newly introduced for irreducible expressions. -/
abstractedFVars : Array FVarId := #[]
levelNames : List Name := []
mayPostpone : Bool
|
inductive
|
Qq
|
[
"Lean"
] |
Qq/Macro.lean
|
MVarSynth
| null |
UnquoteM := StateT UnquoteState MetaM
|
abbrev
|
Qq
|
[
"Lean"
] |
Qq/Macro.lean
|
UnquoteM
| null |
QuoteM := ReaderT UnquoteState MetaM
meta instance : MonadLift QuoteM UnquoteM where
monadLift k := do k (← get)
meta def determineLocalInstances (lctx : LocalContext) : MetaM LocalInstances := do
let mut localInsts : LocalInstances := {}
for ldecl in lctx do
match (← isClass? ldecl.type) with
| some c => localInsts := localInsts.push { className := c, fvar := ldecl.toExpr }
| none => pure ()
pure localInsts
meta def withUnquotedLCtx [MonadControlT MetaM m] [Monad m] [MonadLiftT QuoteM m] (k : m α) : m α := do
let unquoted := (← (read : QuoteM _)).unquoted
withLCtx unquoted (← (determineLocalInstances unquoted : QuoteM _)) k
open Name in
meta def addDollar : Name → Name
| anonymous => str anonymous "$"
| str anonymous s => str anonymous ("$" ++ s)
| str n s => str (addDollar n) s
| num n i => num (addDollar n) i
open Name in
meta def removeDollar : Name → Option Name
| anonymous => none
| str anonymous "$" => some anonymous
| str anonymous s =>
if s.startsWith "$" then str anonymous (s.drop 1).copy else none
| str n s => (removeDollar n).map (str . s)
| num n i => (removeDollar n).map (num . i)
open Name in
meta def stripDollars : Name → Name
| anonymous => anonymous
| str n "$" => stripDollars n
| str anonymous s =>
let s := s.dropWhile '$'
if s.isEmpty then anonymous else str anonymous s.copy
| str n s => str (stripDollars n) s
| num n i => num (stripDollars n) i
meta def addSyntaxDollar : Syntax → Syntax
| .ident info rawVal val preresolved =>
.ident info rawVal (addDollar val) preresolved
| stx => panic! s!"addSyntaxDollar {stx}"
meta def mkAbstractedLevelName (e : Expr) : MetaM Name :=
return e.getAppFn.constName?.getD `udummy ++ (← mkFreshId)
meta def isAssignablePattern (e : Expr) : MetaM Bool := do
let e ← instantiateMVars (← whnf e)
let .mvar mvarId := e.getAppFn | return false
unless ← mvarId.isAssignable do return false
if (← mvarId.getKind) matches .synthetic then return false
return e.getAppArgs.all (·.isFVar) && e.getAppArgs.allDiff
meta def isBad (e : Expr) : Bool := Id.run do
if let .const (.str _ "rec") _ := e.getAppFn then
return true
return false
-- https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/How.20to.20WHNF.20without.20exposing.20recursors.3F/near/249743042
meta partial def whnf (e : Expr) (e0 : Expr := e) : MetaM Expr := do
let e ← whnfCore e
let e0 := if isBad e then e0 else e
match ← unfoldDefinition? e with
| some e => whnf e (if isBad e then e0 else e)
| none => pure e0
meta def whnfR (e : Expr) : MetaM Expr :=
withReducible (whnf e)
mutual
meta partial def unquoteLevel (e : Expr) : UnquoteM Level := do
let e ← whnf e
if let some l := (← get).levelSubst[e]? then
return l
if e.isAppOfArity ``Level.zero 0 then pure .zero
else if e.isAppOfArity ``Level.succ 1 then return .succ (← unquoteLevel (e.getArg! 0))
else if e.isAppOfArity ``Level.max 2 then return .max (← unquoteLevel (e.getArg! 0)) (← unquoteLevel (e.getArg! 1))
else if e.isAppOfArity ``Level.imax 2 then return .imax (← unquoteLevel (e.getArg! 0)) (← unquoteLevel (e.getArg! 1))
else if e.isAppOfArity ``Level.param 1 then return .param (← reduceEval (e.getArg! 0))
else if e.isAppOfArity ``Level.mvar 1 then return .mvar (← reduceEval (e.getArg! 0))
else
if ← isAssignablePattern e then
return ← unquoteLevelMVar e
if (← get).mayPostpone && e.getAppFn.isMVar then
Elab.throwPostpone
let name ← mkAbstractedLevelName e
let l := .param name
modify fun s => { s with
levelSubst := s.levelSubst.insert e l
levelBackSubst := s.levelBackSubst.insert l e
}
pure l
meta partial def unquoteLevelMVar (mvar : Expr) : UnquoteM Level := do
let newMVar ← mkFreshLevelMVar
modify fun s => { s with
levelSubst := s.levelSubst.insert mvar newMVar
levelBackSubst := s.levelBackSubst.insert newMVar mvar
mvars := (mvar, .level newMVar.mvarId!) :: s.mvars
}
return newMVar
|
abbrev
|
Qq
|
[
"Lean"
] |
Qq/Macro.lean
|
QuoteM
| null |
isCanonicalAdd {u : Level} {α : Q(Type u)} (inst : Q(Add $α)) (x : Q($α)) :
MetaM <| Option (Q($α) × Q($α)) := do
match x with
| ~q($a + $b) => return some (a, b)
| _ => return none
```
Here, the `~q($a + $b)` match is specifically matching the addition against the provided `inst`
instance, as this is what is being used to elaborate the `+`.
If the intent is to match an _arbitrary_ `Add α` instance in `x`,
then you must match this with a `$inst` antiquotation:
```
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
isCanonicalAdd
| null |
isAdd {u : Level} {α : Q(Type u)} (x : Q($α)) :
MetaM <| Option (Q(Add $α) × Q($α) × Q($α)) := do
match x with
| ~q(@HAdd.hAdd _ _ _ (@instHAdd _ $inst) $a $b) => return some (inst, a, b)
| _ => return none
```
## Matching `Expr`s
By itself, `~q()` can only match against terms of the form `Q($α)`.
To match an `Expr`, it must first be converted to Qq with `Qq.inferTypeQ`.
For instance, to match an arbitrary expression for `n + 37` where `n : Nat`,
we can write
```
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
isAdd
| null |
isAdd37 (e : Expr) : MetaM (Option Q(Nat)) := do
let ⟨1, ~q(Nat), ~q($n + 37)⟩ ← inferTypeQ e | return none
return some n
```
This is performing three sequential matches: first that `e` is in `Sort 1`,
then that the type of `e` is `Nat`,
then finally that `e` is of the right form.
This syntax can be used in `match` too.
-/
open Lean Elab Term Meta
open Parser.Term
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
isAdd37
| null |
mkInstantiateMVars (decls : List PatVarDecl) : List PatVarDecl → MetaM Q(MetaM $(mkIsDefEqType decls))
| [] => return q(return $(mkIsDefEqResult true decls))
-- https://github.com/leanprover/lean4/issues/501
| { ty := none, fvarId := fvarId, userName := userName } :: rest => do
let decl : PatVarDecl := { ty := none, fvarId := fvarId, userName := userName }
let instMVars : Q(Level → MetaM $(mkIsDefEqType decls)) ←
mkLambdaQ _ decl.fvar q($(← mkInstantiateMVars decls rest))
return q(Bind.bind (instantiateLevelMVars $(decl.fvar)) $instMVars)
| { ty := some ty, fvarId := fvarId, userName := userName } :: rest => do
let decl : PatVarDecl := { ty := some ty, fvarId := fvarId, userName := userName }
let instMVars : Q(Expr → MetaM $(mkIsDefEqType decls)) ←
mkLambdaQ _ decl.fvar q($(← mkInstantiateMVars decls rest))
return q(Bind.bind (instantiateMVars $(decl.fvar)) $instMVars)
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
mkInstantiateMVars
| null |
mkIsDefEqCore (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)))
| { 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)))
| [] => do
let instMVars ← mkInstantiateMVars decls decls
return q(do
let matches? ← withReducible $ isDefEq $pat $discr
(if matches? then $instMVars else return $(mkIsDefEqResult false decls)))
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
mkIsDefEqCore
| null |
mkIsDefEq (decls : List PatVarDecl) (pat discr : Q(Expr)) : MetaM Q(MetaM $(mkIsDefEqType decls)) := do
return q(withNewMCtxDepth $(← mkIsDefEqCore decls pat discr decls))
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
mkIsDefEq
| null |
withLetHave [Monad m] [MonadControlT MetaM m] [MonadLiftT MetaM m] [MonadLCtx m]
(fvarId : FVarId) (userName : Name) (val : (Quoted α)) (k : (Quoted α) → m (Quoted β)) : m (Quoted β) := do
withExistingLocalDecls [LocalDecl.cdecl default fvarId userName α .default .default] do
return Quoted.unsafeMk $ ← mkLet' userName (.fvar fvarId) α val (← k (.fvar fvarId))
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
withLetHave
| null |
mkQqLets {γ : Q(Type)} : (decls : List PatVarDecl) → Q($(mkIsDefEqType decls)) →
TermElabM Q($γ) → TermElabM Q($γ)
| { ty := none, fvarId := fvarId, userName := userName } :: decls, acc, cb =>
withLetHave fvarId userName (α := q(Level)) q($acc.1) fun _ => mkQqLets decls q($acc.2) cb
| { ty := some ty, fvarId := fvarId, userName := userName } :: decls, acc, cb =>
withLetHave fvarId userName (α := q(Quoted $ty)) q($acc.1) fun _ => mkQqLets decls q($acc.2) cb
| [], _, cb => cb
-- FIXME: we're reusing fvarids here
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
mkQqLets
| null |
replaceTempExprsByQVars : List PatVarDecl → Expr → Expr
| [], e => e
| { ty := some _, fvarId, .. } :: decls, e =>
((replaceTempExprsByQVars decls e).abstract #[.fvar fvarId]).instantiate #[.fvar fvarId]
| { ty := none, .. } :: decls, e =>
replaceTempExprsByQVars decls e
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
replaceTempExprsByQVars
| null |
makeMatchCode {γ : Q(Type)} {m : Q(Type → Type v)} (_instLift : Q(MonadLiftT MetaM $m)) (_instBind : Q(Bind $m))
(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
let nextDecls : List PatVarDecl :=
decls.map fun decl => { decl with ty := decl.ty.map fun e => replaceTempExprsByQVars decls e }
let next ← withLocalDecl (← mkFreshBinderName) default (mkIsDefEqType decls) (kind := .implDetail) fun fv => do
let fv : Q($(mkIsDefEqType decls)) := fv
-- note: cannot inline into `$body` due to leanprover/lean4#3827
let body ← mkQqLets nextDecls fv do
have pat : Q(Quoted $ty) := replaceTempExprsByQVars decls pat
let (_, s) ← unquoteLCtx.run { mayPostpone := (← read).mayPostpone }
let _discr' ← (unquoteExpr discr).run' s
let _pat' ← (unquoteExpr pat).run' s
withLocalDeclDQ (← mkFreshUserName `match_eq) q(QuotedDefEq $discr $pat) fun h => do
let res ← k expectedType
let res : Q($m $γ) ← instantiateMVars res
let res : Q($m $γ) := (← res.abstractM #[h]).instantiate #[q(⟨⟩ : QuotedDefEq $discr $pat)]
return res
let next : Q($m $γ) :=
q(if $(mkIsDefEqResultVal decls fv) then
$body
else
$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)
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
makeMatchCode
| null |
unquoteForMatch (et : Expr) : UnquoteM (LocalContext × LocalInstances × Expr) := do
unquoteLCtx
let newET ← unquoteExpr et
let newLCtx := (← get).unquoted
return (newLCtx, ← determineLocalInstances newLCtx, newET)
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
unquoteForMatch
| null |
mkNAryFunctionType : Nat → MetaM Expr
| 0 => mkFreshTypeMVar
| n+1 => do withLocalDeclD `x (← mkFreshTypeMVar) fun x => do
mkForallFVars #[x] (← mkNAryFunctionType n)
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
mkNAryFunctionType
| null |
PatternVar where
name : Name
/-- Pattern variables can be functions; if so, this is their arity. -/
arity : Nat
mvar : Expr
stx : Term
|
structure
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
PatternVar
| null |
getPatVars (pat : Term) : StateT (Array PatternVar) TermElabM Term := do
match pat with
| `($fn $args*) => if isPatVar fn then return ← mkMVar fn args
| _ => if isPatVar pat then return ← mkMVar pat #[]
match pat with
| ⟨.node info kind args⟩ => return ⟨.node info kind (← args.mapM (getPatVars ⟨·⟩))⟩
| pat => return pat
where
isPatVar (fn : Syntax) : Bool :=
fn.isAntiquot && !fn.isEscapedAntiquot && fn.getAntiquotTerm.isIdent &&
fn.getAntiquotTerm.getId.isAtomic
mkMVar (fn : Syntax) (args : Array Term) : StateT _ TermElabM Term := do
let args ← args.mapM getPatVars
let id := fn.getAntiquotTerm.getId
withFreshMacroScope do
if let some p := (← get).find? fun p => p.name == id then
return ← `($(p.stx) $args*)
let mvar ← elabTerm (← `(?m)).1.stripPos (← mkNAryFunctionType args.size)
modify (·.push ⟨id, args.size, mvar, ← `(?m)⟩)
`(?m $args*)
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
getPatVars
| null |
elabPat (pat : Term) (lctx : LocalContext) (localInsts : LocalInstances) (ty : Expr)
(levelNames : List Name) : TermElabM (Expr × Array LocalDecl × Array Name) :=
withLCtx lctx localInsts do
withLevelNames levelNames do
let (pat, patVars) ← getPatVars pat #[]
let pat ← Lean.Elab.Term.elabTerm pat ty
let pat ← ensureHasType ty pat
synthesizeSyntheticMVars (postpone := .no)
let pat ← instantiateMVars pat
let mctx ← getMCtx
let levelNames ← getLevelNames
let r := mctx.levelMVarToParam levelNames.elem (fun _ => false) pat `u 1
setMCtx r.mctx
let mut newDecls := #[]
for patVar in patVars do
assert! patVar.mvar.isMVar
let fvarId := FVarId.mk (← mkFreshId)
let type ← inferType patVar.mvar
newDecls := newDecls.push $
LocalDecl.cdecl default fvarId patVar.name type .default .default
patVar.mvar.mvarId!.assign (.fvar fvarId)
for newMVar in ← getMVars pat do
let fvarId := FVarId.mk (← mkFreshId)
let type ← instantiateMVars (← newMVar.getDecl).type
let userName ← mkFreshBinderName
newDecls := newDecls.push $
LocalDecl.cdecl default fvarId userName type .default .default
newMVar.assign (.fvar fvarId)
withExistingLocalDecls newDecls.toList do
return (← instantiateMVars pat,
← 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
let emr ← extractBind expectedType
let alt ← elabTermEnsuringType alt expectedType
let argLvlExpr ← mkFreshExprMVarQ q(Level)
let argTyExpr ← mkFreshExprMVarQ q(Quoted (.sort $argLvlExpr))
let e' ← elabTermEnsuringTypeQ e q(Quoted $argTyExpr)
let argTyExpr ← instantiateMVarsQ argTyExpr
let ((lctx, localInsts, type), s) ← (unquoteForMatch argTyExpr).run { mayPostpone := (← read).mayPostpone }
let (pat, patVarDecls, newLevels) ← elabPat pat lctx localInsts type s.levelNames
let mut s := s
let mut oldPatVarDecls : List PatVarDecl := []
for newLevel in newLevels do
let fvarId := FVarId.mk (← mkFreshId)
oldPatVarDecls := oldPatVarDecls ++ [{ ty := none, fvarId := fvarId, userName := newLevel }]
s := { s with levelBackSubst := s.levelBackSubst.insert (.param newLevel) (.fvar fvarId) }
for ldecl in patVarDecls do
let qty ← (quoteExpr ldecl.type).run s
oldPatVarDecls := oldPatVarDecls ++ [{ ty := some qty, fvarId := ldecl.fvarId, userName := ldecl.userName }]
s := { s with exprBackSubst := s.exprBackSubst.insert ldecl.toExpr (.quoted ldecl.toExpr) }
have m : Q(Type → Type) := emr.m
have γ : Q(Type) := emr.returnType
let inst ← synthInstanceQ q(Bind $m)
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 =>
return Quoted.unsafeMk (← elabTerm body expectedType)
scoped syntax "_qq_match" term " := " term " | " doSeq : term
macro_rules
| `(assert! (_qq_match $pat := $e | $alt); $x) => `(_qq_match $pat ← $e | (do $alt) in $x)
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
elabPat
| null |
isIrrefutablePattern : Term → Bool
| `(($stx)) => isIrrefutablePattern stx
| `(⟨$args,*⟩) => args.getElems.all isIrrefutablePattern
| `(($a, $b)) => isIrrefutablePattern a && isIrrefutablePattern b
| `(_) => true
| `(true) => false | `(false) => false -- TODO properly
| stx => stx.1.isIdent
scoped elab "_comefrom" n:ident "do" b:doSeq " in " body:term : term <= expectedType => do
let _ ← extractBind expectedType
let ty ← exprToSyntax expectedType
elabTerm (← `(have $n:ident : $ty := (do $b:doSeq); $body)) expectedType
scoped syntax "_comefrom" ident "do" doSeq : term
macro_rules | `(assert! (_comefrom $n do $b); $body) => `(_comefrom $n do $b in $body)
scoped macro "comefrom" n:ident "do" b:doSeq : doElem =>
`(doElem| assert! (_comefrom $n do $b))
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
isIrrefutablePattern
| null |
mkLetDoSeqItem [Monad m] [MonadQuotation m] (pat : Term) (rhs : TSyntax `term) (alt : TSyntax ``doSeq) : m (List (TSyntax ``doSeqItem)) := do
match pat with
| `(_) => return []
| _ =>
if isIrrefutablePattern pat then
return [← `(doSeqItem| let $pat:term := $rhs)]
else
return [← `(doSeqItem| let $pat:term := $rhs | $alt)]
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
mkLetDoSeqItem
| null |
Impl.hasQMatch : Syntax → Bool
| `(~q($_)) => true
| stx => stx.getArgs.any hasQMatch
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
Impl.hasQMatch
| null |
Impl.floatQMatch (alt : TSyntax ``doSeq) : Term → StateT (List (TSyntax ``doSeqItem)) MacroM Term
| `(~q($term)) =>
withFreshMacroScope do
let auxDoElem ← `(doSeqItem| let ~q($term) := x | $alt)
modify fun s => s ++ [auxDoElem]
`(x)
| stx => do match stx with
| ⟨.node i k args⟩ => return ⟨.node i k (← args.mapM (floatQMatch alt ⟨·⟩))⟩
| stx => return stx
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
Impl.floatQMatch
| null |
push (i : TSyntax ``doSeqItem) : StateT (Array (TSyntax ``doSeqItem)) MacroM Unit :=
modify fun s => s.push i
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
push
| null |
unpackParensIdent : Syntax → Option Syntax
| `(($stx)) => unpackParensIdent stx
| stx => if stx.isIdent then some stx else none
private partial def floatLevelAntiquot (stx : Syntax.Level) : StateT (Array (TSyntax ``doSeqItem)) MacroM Syntax.Level :=
if stx.1.isAntiquot && !stx.1.isEscapedAntiquot then
if !stx.1.getAntiquotTerm.isIdent then
withFreshMacroScope do
push <| ← `(doSeqItem| let u : Level := $(⟨stx.1.getAntiquotTerm⟩))
`(level| u)
else
pure stx
else
match stx with
| ⟨.node i k args⟩ => return ⟨Syntax.node i k (← args.mapM (floatLevelAntiquot ⟨·⟩))⟩
| stx => return stx
private partial def floatExprAntiquot (depth : Nat) : Term → StateT (Array (TSyntax ``doSeqItem)) MacroM Term
| `(Q($x)) => do `(Q($(← floatExprAntiquot (depth + 1) x)))
| `(q($x)) => do `(q($(← floatExprAntiquot (depth + 1) x)))
| `(Type $term) => do `(Type $(← floatLevelAntiquot term))
| `(Sort $term) => do `(Sort $(← floatLevelAntiquot term))
| stx => do
if stx.1.isAntiquot && !stx.1.isEscapedAntiquot then
let term : Term := ⟨stx.1.getAntiquotTerm⟩
if term.1.isIdent then
return stx
else if depth > 0 then
return ⟨.mkAntiquotNode stx.1.antiquotKind?.get!.1 (← floatExprAntiquot (depth - 1) term)⟩
else
match unpackParensIdent stx.1.getAntiquotTerm with
| some id =>
if id.getId.isAtomic then
return ⟨addSyntaxDollar id⟩
| none => pure ()
withFreshMacroScope do
push <| ← `(doSeqItem| let a : Quoted _ := $term)
return ⟨addSyntaxDollar (← `(a))⟩
else
match stx with
| ⟨.node i k args⟩ => return ⟨.node i k (← args.mapM (floatExprAntiquot depth ⟨·⟩))⟩
| stx => return stx
macro_rules
| `(doElem| let $pat:term := $_) => do
if !hasQMatch pat then Macro.throwUnsupported
Macro.throwError "let-bindings with ~q(.) require an explicit alternative"
| `(doElem| let $pat:term := $rhs:term | $alt:doSeq) => do
if !hasQMatch pat then Macro.throwUnsupported
match pat with
| `(~q($pat)) =>
let (pat, lifts) ← floatExprAntiquot 0 pat #[]
let t ← `(doSeqItem| do assert! (_qq_match $pat := $rhs | $alt))
`(doElem| do $(lifts.push t):doSeqItem*)
| _ =>
let (pat', auxs) ← floatQMatch (← `(doSeq| __alt)) pat []
let items :=
#[← `(doSeqItem| comefrom __alt do $alt:doSeq)] ++
(← mkLetDoSeqItem pat' rhs alt) ++
auxs
`(doElem| do $items:doSeqItem*)
| `(match $[$gen:generalizingParam]? $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do
if !patss.any (·.any (hasQMatch ·)) then Macro.throwUnsupported
`(do match $[$gen]? $[$discrs:term],* with $[| $[$patss:term],* => $rhss:term]*)
| `(doElem| match $[$gen:generalizingParam]? $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do
if !patss.any (·.any (hasQMatch ·)) then Macro.throwUnsupported
-- only `generalizing := true` (the default) is supported
if let some stx := gen then
match stx with
| `(generalizingParam| (generalizing := true)) => pure ()
| _ => Macro.throwErrorAt stx "not supported in ~q matching"
let mut items := #[]
items := items.push (← `(doSeqItem| comefrom __alt do throwError "nonexhaustive match"))
for pats in patss.reverse, rhs in rhss.reverse do
let mut subItems : Array (TSyntax ``doSeqItem) := #[]
for discr in discrs, pat in pats do
subItems := subItems ++ (← mkLetDoSeqItem pat discr (← `(doSeq| __alt)))
subItems := subItems.push (← `(doSeqItem| do $rhs))
items := items.push (← `(doSeqItem| comefrom __alt do $subItems:doSeqItem*))
items := items.push (← `(doSeqItem| __alt))
`(doElem| (do $items:doSeqItem*))
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls"
] |
Qq/Match.lean
|
unpackParensIdent
| null |
Lean.Syntax.stripPos : Syntax → Syntax
| atom _ a => atom .none a
| ident _ r v p => ident .none r v p
| node _ kind args => node .none kind (args.map stripPos)
| missing => missing
open Lean Elab Term Meta
open Parser.Term
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls",
"Qq.Typ"
] |
Qq/MatchImpl.lean
|
Lean.Syntax.stripPos
| null |
PatVarDecl where
ty : Option Q(Expr)
fvarId : FVarId
userName : Name
@[expose] def PatVarDecl.fvarTy : PatVarDecl → Q(Type)
| { ty := none, .. } => q(Level)
| { ty := some _, .. } => q(Expr)
|
structure
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls",
"Qq.Typ"
] |
Qq/MatchImpl.lean
|
PatVarDecl
| null |
PatVarDecl.fvar (decl : PatVarDecl) : Q($((decl.fvarTy))) :=
Expr.fvar decl.fvarId
@[expose] def mkIsDefEqType : List PatVarDecl → Q(Type)
| [] => q(Bool)
| decl :: decls => q($(decl.fvarTy) × $(mkIsDefEqType decls))
@[expose] def mkIsDefEqResult (val : Bool) : (decls : List PatVarDecl) → Q($(mkIsDefEqType decls))
| [] => show Q(Bool) from q($val)
| decl :: decls => q(($(decl.fvar), $(mkIsDefEqResult val decls)))
@[expose] def mkIsDefEqResultVal : (decls : List PatVarDecl) → Q($(mkIsDefEqType decls)) → Q(Bool)
| [], val => q($val)
| _ :: decls, val => mkIsDefEqResultVal decls q($val.2)
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls",
"Qq.Typ"
] |
Qq/MatchImpl.lean
|
PatVarDecl.fvar
| null |
mkLambda' (n : Name) (fvar : Expr) (ty : Expr) (body : Expr) : MetaM Expr :=
return mkLambda n BinderInfo.default ty (← body.abstractM #[fvar])
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls",
"Qq.Typ"
] |
Qq/MatchImpl.lean
|
mkLambda'
| null |
mkLet' (n : Name) (fvar : Expr) (ty : Expr) (val : Expr) (body : Expr) : MetaM Expr :=
return mkLet n ty val (← body.abstractM #[fvar])
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls",
"Qq.Typ"
] |
Qq/MatchImpl.lean
|
mkLet'
| null |
mkLambdaQ (n : Name) (fvar : Quoted α) (body : Quoted β) : MetaM (Quoted (.forallE n α β .default)) :=
return mkLambda n BinderInfo.default α (← body.abstractM #[fvar])
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.MetaM",
"Qq.ForLean.Do",
"Qq.SortLocalDecls",
"Qq.Typ"
] |
Qq/MatchImpl.lean
|
mkLambdaQ
| null |
mkFreshExprMVarQ (ty : Q(Sort u)) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Q($ty) := do
mkFreshExprMVar (some ty) kind userName
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
mkFreshExprMVarQ
| null |
withLocalDeclDQ [Monad n] [MonadControlT MetaM n] (name : Name) (β : Q(Sort u)) (k : Q($β) → n α) : n α :=
withLocalDeclD name β k
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
withLocalDeclDQ
| null |
withLocalDeclQ [Monad n] [MonadControlT MetaM n] (name : Name) (bi : BinderInfo) (β : Q(Sort u)) (k : Q($β) → n α) : n α :=
withLocalDecl name bi β k
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
withLocalDeclQ
| null |
trySynthInstanceQ (α : Q(Sort u)) : MetaM (LOption Q($α)) := do
trySynthInstance α
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
trySynthInstanceQ
| null |
synthInstanceQ (α : Q(Sort u)) : MetaM Q($α) := do
synthInstance α
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
synthInstanceQ
| null |
instantiateMVarsQ {α : Q(Sort u)} (e : Q($α)) : MetaM Q($α) := do
instantiateMVars e
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
instantiateMVarsQ
| null |
elabTermEnsuringTypeQ (stx : Syntax) (expectedType : Q(Sort u))
(catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) :
TermElabM Q($expectedType) := do
elabTermEnsuringType stx (some expectedType) catchExPostpone implicitLambda errorMsgHeader?
/--
A `Qq`-ified version of `Lean.Meta.inferType`
Instead of writing `let α ← inferType e`, this allows writing `let ⟨u, α, e⟩ ← inferTypeQ e`,
which results in a context of
```
e✝ : Expr
u : Level
α : Q(Type u)
e : Q($α)
```
Here, the new `e` is defeq to the old one, but now has `Qq`-ascribed type information.
This is frequently useful when using the `~q` matching from `QQ/Match.lean`,
as it allows an `Expr` to be turned into something that can be matched upon.
-/
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
elabTermEnsuringTypeQ
| null |
inferTypeQ (e : Expr) : MetaM ((u : Level) × (α : Q(Sort $u)) × Q($α)) := do
let α ← inferType e
let .sort u ← whnf (← inferType α) | throwError "not a type{indentExpr α}"
pure ⟨u, α, e⟩
/-- If `e` is a `ty`, then view it as a term of `Q($ty)`. -/
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
inferTypeQ
| null |
checkTypeQ (e : Expr) (ty : Q(Sort $u)) : MetaM (Option Q($ty)) := do
if ← isDefEq (← inferType e) ty then
return some e
else
return none
/-- The result of `Qq.isDefEqQ`; `MaybeDefEq a b` is an optional version of `$a =Q $b`. -/
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
checkTypeQ
| null |
MaybeDefEq {α : Q(Sort $u)} (a b : Q($α)) where
| defEq : QuotedDefEq a b → MaybeDefEq a b
| notDefEq : MaybeDefEq a b
|
inductive
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
MaybeDefEq
| null |
isDefEqQ {α : Q(Sort $u)} (a b : Q($α)) : MetaM (MaybeDefEq a b) := do
if ← isDefEq a b then
return .defEq ⟨⟩
else
return .notDefEq
/-- Like `Qq.isDefEqQ`, but throws an error if not defeq. -/
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
isDefEqQ
|
A version of `Lean.Meta.isDefEq` which returns a strongly-typed witness rather than a bool.
|
assertDefEqQ {α : Q(Sort $u)} (a b : Q($α)) : MetaM (PLift (QuotedDefEq a b)) := do
match ← isDefEqQ a b with
| .defEq witness => return ⟨witness⟩
| .notDefEq => throwError "{a} is not definitionally equal to{indentExpr b}"
/-- The result of `Qq.isLevelDefEqQ`; `MaybeLevelDefEq u v` is an optional version of `$u =QL $v`. -/
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
assertDefEqQ
| null |
MaybeLevelDefEq (u v : Level) where
| defEq : QuotedLevelDefEq u v → MaybeLevelDefEq u v
| notDefEq : MaybeLevelDefEq u v
|
inductive
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
MaybeLevelDefEq
| null |
isLevelDefEqQ (u v : Level) : MetaM (MaybeLevelDefEq u v) := do
if ← isLevelDefEq u v then
return .defEq ⟨⟩
else
return .notDefEq
/-- Like `Qq.isLevelDefEqQ`, but throws an error if not defeq. -/
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
isLevelDefEqQ
|
A version of `Lean.Meta.isLevelDefEq` which returns a strongly-typed witness rather than a bool.
|
assertLevelDefEqQ (u v : Level) : MetaM (PLift (QuotedLevelDefEq u v)) := do
match ← isLevelDefEqQ u v with
| .defEq witness => return ⟨witness⟩
| .notDefEq => throwError "{u} and {v} are not definitionally equal"
|
def
|
Qq
|
[
"Qq.Macro",
"Qq.Delab",
"Qq.Typ"
] |
Qq/MetaM.lean
|
assertLevelDefEqQ
| null |
ResultQ (_e : Q($α)) : Type := Lean.Meta.Simp.Result
/-- A copy of `Meta.Simp.Result.mk` with explicit types. -/
@[inline] def ResultQ.mk {e : Q($α)}
(expr : Q($α))
(proof? : Option Q($e = $expr))
(cache : Bool := true) : ResultQ e :=
{expr, proof?, cache}
/-- A copy of `Meta.Simp.Step` with explicit types. -/
@[expose] def StepQ (_e : Q($α)) : Type := Step
@[inherit_doc Step.done, inline]
|
def
|
Qq
|
[
"Qq.MetaM"
] |
Qq/Simp.lean
|
ResultQ
|
A copy of `Meta.Simp.Result` with explicit types.
|
StepQ.done {e : Q($α)} (r : ResultQ e) : StepQ e := Step.done r
@[inherit_doc Step.visit, inline]
|
def
|
Qq
|
[
"Qq.MetaM"
] |
Qq/Simp.lean
|
StepQ.done
| null |
StepQ.visit {e : Q($α)} (r : ResultQ e) : StepQ e := Step.visit r
@[inherit_doc Step.continue, inline]
|
def
|
Qq
|
[
"Qq.MetaM"
] |
Qq/Simp.lean
|
StepQ.visit
| null |
StepQ.continue {e : Q($α)} (r : Option (ResultQ e) := none) : StepQ e := Step.continue r
/-- A copy of `Lean.Meta.Simproc` with explicit types.
See `Simproc.ofQ` to construct terms of this type. -/
|
def
|
Qq
|
[
"Qq.MetaM"
] |
Qq/Simp.lean
|
StepQ.continue
| null |
SimprocQ : Type := ∀ (u : Level) (α : Q(Sort u)) (e : Q($α)), Meta.SimpM (StepQ e)
/-- Build a simproc with Qq-enabled typechecking of inputs and outputs.
This calls `inferTypeQ` on the expression and passes the arguments to `proc`. -/
@[inline] def Simproc.ofQ (proc : SimprocQ) : Simproc := fun e => do
let ⟨u, α, e⟩ ← inferTypeQ e
proc u α e
|
abbrev
|
Qq
|
[
"Qq.MetaM"
] |
Qq/Simp.lean
|
SimprocQ
| null |
Context where
localDecls : NameMap LocalDecl := {}
|
structure
|
Qq
|
[
"Lean.Meta.Basic"
] |
Qq/SortLocalDecls.lean
|
Context
| null |
State where
visited : NameSet := {}
result : Array LocalDecl := #[]
|
structure
|
Qq
|
[
"Lean.Meta.Basic"
] |
Qq/SortLocalDecls.lean
|
State
| null |
M := ReaderT Context $ StateRefT State MetaM
mutual
partial def visitExpr (e : Expr) : M Unit := do
match e with
| .proj _ _ e => visitExpr e
| .forallE _ d b _ => visitExpr d; visitExpr b
| .lam _ d b _ => visitExpr d; visitExpr b
| .letE _ t v b _ => visitExpr t; visitExpr v; visitExpr b
| .app f a => visitExpr f; visitExpr a
| .mdata _ b => visitExpr b
| .mvar _ => let v ← instantiateMVars e; unless v.isMVar do visitExpr v
| .fvar fvarId => if let some localDecl := (← read).localDecls.find? fvarId.name then visitLocalDecl localDecl
| _ => return ()
partial def visitLocalDecl (localDecl : LocalDecl) : M Unit := do
unless (← get).visited.contains localDecl.fvarId.name do
modify fun s => { s with visited := s.visited.insert localDecl.fvarId.name }
visitExpr localDecl.type
if let some val := localDecl.value? then
visitExpr val
modify fun s => { s with result := s.result.push localDecl }
|
abbrev
|
Qq
|
[
"Lean.Meta.Basic"
] |
Qq/SortLocalDecls.lean
|
M
| null |
sortLocalDecls (localDecls : Array LocalDecl) : MetaM (Array LocalDecl) :=
let aux : M (Array LocalDecl) := do localDecls.forM visitLocalDecl; return (← get).result
aux.run { localDecls := localDecls.foldl (init := {}) fun s d => s.insert d.fvarId.name d } |>.run' {}
|
def
|
Qq
|
[
"Lean.Meta.Basic"
] |
Qq/SortLocalDecls.lean
|
sortLocalDecls
| null |
Quoted (α : Expr) := Expr
/--
Creates a quoted expression. Requires that `e` has type `α`.
You should usually write this using the notation `q($e)`.
-/
@[expose] protected def Quoted.unsafeMk (e : Expr) : Quoted α := e
|
def
|
Qq
|
[
"Lean"
] |
Qq/Typ.lean
|
Quoted
|
`Quoted α` is the type of Lean expressions having type `α`. You should usually write this using the notation `Q($α)`.
|
Quoted.ty (t : Quoted α) : Expr := α
/--
`QuotedDefEq lhs rhs` says that the expressions `lhs` and `rhs` are definitionally equal.
You should usually write this using the notation `$lhs =Q $rhs`.
-/
|
abbrev
|
Qq
|
[
"Lean"
] |
Qq/Typ.lean
|
Quoted.ty
|
Gets the type of a quoted expression.
|
QuotedDefEq {α : Quoted (.sort u)} (lhs rhs : Quoted α) : Prop where
/-- For a safer constructor, see `Qq.assertDefEqQ`. -/
unsafeIntro ::
/--
`QuotedLevelDefEq u v` says that the levels `u` and `v` are definitionally equal.
You should usually write this using the notation `$u =QL $v`.
-/
|
structure
|
Qq
|
[
"Lean"
] |
Qq/Typ.lean
|
QuotedDefEq
| null |
QuotedLevelDefEq (u v : Level) : Prop where
/-- For a safer constructor, see `Qq.assertLevelDefEqQ`. -/
unsafeIntro ::
open Meta in
/-- Check that a term `e : Q(α)` really has type `α`. -/
|
structure
|
Qq
|
[
"Lean"
] |
Qq/Typ.lean
|
QuotedLevelDefEq
| null |
Quoted.check (e : Quoted α) : MetaM Unit := do
let α' ← inferType e
unless ← isDefEq α α' do
throwError "type mismatch{indentExpr e}\n{← mkHasTypeButIsExpectedMsg α' α}"
open Meta in
/-- Check that the claim `$lhs =Q $rhs` is actually true; that the two terms are defeq. -/
|
def
|
Qq
|
[
"Lean"
] |
Qq/Typ.lean
|
Quoted.check
| null |
QuotedDefEq.check (e : @QuotedDefEq u α lhs rhs) : MetaM Unit := do
α.check
lhs.check
rhs.check
unless ← isDefEq lhs rhs do
throwError "{lhs} and {rhs} are not defeq"
open Meta in
/-- Check that the claim `$u =QL $v` is actually true; that the two levels are defeq. -/
|
def
|
Qq
|
[
"Lean"
] |
Qq/Typ.lean
|
QuotedDefEq.check
| null |
QuotedLevelDefEq.check (e : QuotedLevelDefEq lhs rhs) : MetaM Unit := do
unless ← isLevelDefEq lhs rhs do
throwError "{lhs} and {rhs} are not defeq"
|
def
|
Qq
|
[
"Lean"
] |
Qq/Typ.lean
|
QuotedLevelDefEq.check
| null |
betterApp {α : Q(Sort $u)} {β : Q($α → Sort $v)}
(f : Q((a : $α) → $β a)) (a : Q($α)) : Q($β $a) :=
q($f $a)
/--
info: (Lean.Expr.const `Int.toNat []).app
((((Lean.Expr.const `OfNat.ofNat [Lean.Level.zero]).app (Lean.Expr.const `Int [])).app
(Lean.Expr.lit (Lean.Literal.natVal 42))).app
((Lean.Expr.const `instOfNat []).app (Lean.Expr.lit (Lean.Literal.natVal 42))))
-/
#guard_msgs in
#eval betterApp q(Int.toNat) q(42)
/--
info: betterApp q(fun a => ⟨a, ⋯⟩) q(42) : Q(Fin (42 + 1))
-/
#guard_msgs in
#check betterApp (β := q(fun n : Nat => Fin (n+1))) q(fun a => ⟨a, Nat.lt_succ_self _⟩) q(42)
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/betterApp.lean
|
betterApp
| null |
or1 : List Q(Prop) → Q(Prop)
| [] => q(False)
| [p] => q($p)
| p::ps => q($p ∨ $(or1 ps))
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/clauseConvertProp.lean
|
or1
| null |
or2 : List Q(Prop) → Q(Prop)
| [] => q(False)
| p::ps => q($p ∨ $(or2 ps))
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/clauseConvertProp.lean
|
or2
| null |
orChange : (ps : List Q(Prop)) → Q($(or1 ps) → $(or2 ps))
| [] => q(id)
| [p] => q(Or.inl)
| p::(ps1::ps2) => q(by
intro h
cases h with
| inl h => exact Or.inl h
| inr h => exact Or.inr ($(orChange (ps1::ps2)) h))
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/clauseConvertProp.lean
|
orChange
| null |
orLevel : (ps : List ((u : Level) × Q(Type u))) → Level
| [] => .zero
| ⟨u, _⟩ :: ps => .max u (orLevel ps)
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/clauseConvertType.lean
|
orLevel
| null |
or1 : (ps : List ((u : Level) × Q(Type u))) → Q(Type $(orLevel ps))
| [] => q(Empty)
| [⟨_, p⟩] => q($p)
| ⟨u, p⟩::ps => q(Sum $p $(or1 ps))
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/clauseConvertType.lean
|
or1
| null |
or2 : (ps : List ((u : Level) × Q(Type u))) → Q(Type $(orLevel ps))
| [] => q(Empty)
| ⟨u, p⟩ :: ps => q(Sum $p $(or2 ps))
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/clauseConvertType.lean
|
or2
| null |
orChange : (ps : List ((u : Level) × Q(Type u))) → Q($(or1 ps) → $(or2 ps))
| [] => q(id)
| [⟨_, _⟩] => q(Sum.inl)
| ⟨_, _⟩::(ps1::ps2) =>
let h := orChange (ps1::ps2)
q(fun h => match h with
| Sum.inl l => Sum.inl l
| Sum.inr r => Sum.inr ($h r))
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/clauseConvertType.lean
|
orChange
| null |
f₁ (x : Prop) [Decidable x] : Int :=
by_elabq
trace_return q(if $x then 2 else 3)
|
def
|
QqTest
|
[
"Qq.Commands",
"Qq.Delab"
] |
QqTest/commandTest.lean
|
f₁
| null |
add_self_37 {α : Type u} [Add α] (a : α) : α :=
by_elabq return (List.range 36).foldr (init := q($a)) fun _ acc => q($acc + $a)
/-- info: f₁ (x : Prop) [Decidable x] : Int -/
#guard_msgs in
#check f₁
-- without goal type
/--
trace: _x : Q(Int)
⊢ TermElabM Expr
-/
#guard_msgs in
|
def
|
QqTest
|
[
"Qq.Commands",
"Qq.Delab"
] |
QqTest/commandTest.lean
|
add_self_37
| null |
f₂ (_x : Int) := by_elabq
trace_return q(5)
/-- info: f₂ (_x : Int) : Nat -/
#guard_msgs in
#check f₂
-- tactic without capturing the goal
/--
trace: a b : Q(Nat)
_h : Q(«$a» = «$b»)
p : Q(Prop) := q(«$a» = «$b»)
⊢ TacticM PUnit
-/
#guard_msgs in
|
def
|
QqTest
|
[
"Qq.Commands",
"Qq.Delab"
] |
QqTest/commandTest.lean
|
f₂
| null |
assignQ {α : Q(Sort u)} (mvar : Q($α)) (val : Q($α)) : Meta.MetaM Unit :=
mvar.mvarId!.assign val
-- tactic with capturing the goal
/--
info: true
---
info: a = b
-/
#guard_msgs in
|
def
|
QqTest
|
[
"Qq.Commands",
"Qq.Delab"
] |
QqTest/commandTest.lean
|
assignQ
| null |
turnExistsIntoForall : Q(Prop) → MetaM Q(Prop)
| ~q(∃ x y, $p x y) => return q(∀ x y, $p x y)
| e => return e
/-- info: ∀ (x : String) (y : Nat), x.length ≤ y + 42 -/
#guard_msgs in
run_cmd Elab.Command.liftTermElabM do
Lean.logInfo <| ← turnExistsIntoForall q(∃ a b, String.length a ≤ b + 42)
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/hoMatching.lean
|
turnExistsIntoForall
| null |
introQ {α : Q(Sort u)} {β : Q($α → Sort v)} (mvar : Q(∀ a, $β a)) (n : Name) :
MetaM ((a : Q($α)) × Q($β $a)) := do
let (f, v) ← mvar.mvarId!.intro n
pure ⟨.fvar f, .mvar v⟩
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/introQ.lean
|
introQ
| null |
assignQ {α : Q(Sort u)} (mvar : Q($α)) (val : Q($α)) : MetaM Unit :=
mvar.mvarId!.assign val
elab "demo" : term => do
let P ← mkFreshExprMVarQ q(∀ {n : Nat}, n = 1)
let ⟨_, m⟩ ← introQ q(@$P) `n
m.mvarId!.withContext do
assignQ q($m) q(sorry)
instantiateMVars P
/--
info: fun {n} => sorry : ∀ {n : Nat}, n = 1
-/
#guard_msgs in
#check demo
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/introQ.lean
|
assignQ
| null |
summands {α : Q(Type $u)} (inst : Q(Add $α)) :
Q($α) → MetaM (List Q($α))
| ~q($x + $y) => return (← summands inst x) ++ (← summands inst y)
| n => return [n]
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
summands
| null |
k : Nat
|
opaque
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
k
| null |
m : Nat
|
opaque
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
m
| null |
double (a : Nat) := a + a
/-- info: [Expr.const `k [], Expr.const `k [], Expr.const `m []] -/
#guard_msgs in
#eval summands q(inferInstance) q(double k + m)
/--
info: false
---
trace: x : Q(Nat) := q(k + m)
a b : Q(Nat)
match_eq✝ : (k + m) =Q «$a».add «$b»
⊢ Bool
-/
#guard_msgs in
#eval show MetaM Bool from do
let x : Q(Nat) := q(k + m)
match x with
| ~q(Nat.add $a $b) => return by trace_state; exact true
| _ => return false
|
abbrev
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
double
| null |
square (a : Nat) :=
have : Add Nat := ⟨(· * ·)⟩
a + a
/-- info: 100 -/
#guard_msgs in
#eval square 10
/--
info: [Expr.const `k [], (Expr.const `square []).app ((Expr.const `square []).app (Expr.const `k []))]
-/
#guard_msgs in
#eval summands q(inferInstance) q(k + square (square k))
/--
info: [((((((Expr.const `HMul.hMul [Level.zero, Level.zero, Level.zero]).app (Expr.const `Nat [])).app
(Expr.const `Nat [])).app
(Expr.const `Nat [])).app
(((Expr.const `instHMul [Level.zero]).app (Expr.const `Nat [])).app (Expr.const `instMulNat []))).app
(Expr.const `k [])).app
((Expr.const `square []).app ((Expr.const `square []).app (Expr.const `k [])))]
-/
#guard_msgs in
#eval summands q(⟨(· * ·)⟩) q(k * square (square k))
|
abbrev
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
square
| null |
matchProd (e : Nat × Q(Nat)) : MetaM Bool := do
let (2, ~q(1)) := e | return false
return true
#eval do guard <| (←matchProd (2, q(1))) == true
#eval do guard <| (←matchProd (1, q(1))) == false
#eval do guard <| (←matchProd (2, q(2))) == false
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
matchProd
| null |
matchNatSigma (e : (n : Q(Type)) × Q($n)) : MetaM (Option Q(Nat)) := do
let ⟨~q(Nat), ~q($n)⟩ := e | return none
return some n
#eval do guard <| (← matchNatSigma ⟨q(Nat), q(1)⟩) == some q(1)
#eval do guard <| (← matchNatSigma ⟨q(Nat), q(2)⟩) == some q(2)
#eval do guard <| (← matchNatSigma ⟨q(Int), q(2)⟩) == none
/-- Given `x + y` of Nat, returns `(x, y)`. Otherwise fail. -/
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
matchNatSigma
| null |
getNatAdd (e : Expr) : MetaM (Option (Q(Nat) × Q(Nat))) := do
let ⟨Level.succ Level.zero, ~q(Nat), ~q($a + $b)⟩ ← inferTypeQ e | return none
return some (a, b)
#eval do guard <| (← getNatAdd q(1 + 2)) == some (q(1), q(2))
#eval do guard <| (← getNatAdd q((1 + 2 : Int))) == none
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
getNatAdd
| null |
pairLit (u : Lean.Level) (α : Q(Type u)) (a : Q($α)) : MetaM Q($α × $α) := do
match u, α, a with
| 0, ~q(Nat), n => return q(($n, $n))
| 0, ~q(Int), z => return q(($z, $z))
| _, _, _ => failure
#eval show MetaM Unit from do guard <| (←pairLit _ _ q(2)) == q((2, 2))
-- `generalizing := true` is a no-op
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
pairLit
| null |
pairLit' (u : Lean.Level) (α : Q(Type u)) (a : Q($α)) : MetaM Q($α × $α) := do
match (generalizing := true) u, α, a with
| 0, ~q(Nat), n => return q(($n, $n))
| 0, ~q(Int), z => return q(($z, $z))
| _, _, _ => failure
#eval show MetaM Unit from do guard <| (←pairLit' _ _ q(2)) == q((2, 2))
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/matching.lean
|
pairLit'
| null |
provePositive (n : Q(Nat)) : MetaM Q(0 < $n) :=
showTerm match n with
| ~q($m + 1) => pure q(Nat.lt_of_le_of_lt (Nat.zero_le _) (Nat.lt_succ_self _))
| ~q(1 + $m) => pure q(by
show 0 < 1 + $m
rw [Nat.add_comm]
exact Nat.lt_of_le_of_lt (Nat.zero_le _) (Nat.lt_succ_self _))
| _ => throwError "cannot prove positive: {n}"
/--
info: (((((Expr.const `Nat.lt_of_le_of_lt []).app
((((Expr.const `OfNat.ofNat [Level.zero]).app (Expr.const `Nat [])).app
(Expr.lit (Literal.natVal 0))).app
((Expr.const `instOfNatNat []).app (Expr.lit (Literal.natVal 0))))).app
((((Expr.const `OfNat.ofNat [Level.zero]).app (Expr.const `Nat [])).app
(Expr.lit (Literal.natVal 41))).app
((Expr.const `instOfNatNat []).app (Expr.lit (Literal.natVal 41))))).app
((((Expr.const `OfNat.ofNat [Level.zero]).app (Expr.const `Nat [])).app (Expr.lit (Literal.natVal 42))).app
((Expr.const `instOfNatNat []).app (Expr.lit (Literal.natVal 42))))).app
((Expr.const `Nat.zero_le []).app
((((Expr.const `OfNat.ofNat [Level.zero]).app (Expr.const `Nat [])).app (Expr.lit (Literal.natVal 41))).app
((Expr.const `instOfNatNat []).app (Expr.lit (Literal.natVal 41)))))).app
((Expr.const `Nat.lt_succ_self []).app
((((Expr.const `OfNat.ofNat [Level.zero]).app (Expr.const `Nat [])).app (Expr.lit (Literal.natVal 41))).app
((Expr.const `instOfNatNat []).app (Expr.lit (Literal.natVal 41)))))
-/
#guard_msgs in
#eval provePositive q(42) >>= fun proof => pure proof <* proof.check
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/matchMotive.lean
|
provePositive
| null |
bar {α : Q(Type u)} (a : Q($α)) : Q(Prop) := q($a = $a)
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/misc.lean
|
bar
| null |
bar2 {α : Q(Sort u)} (a : Q($α)) : Q($a = $a) := q(by simp)
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/misc.lean
|
bar2
| null |
baz (u : Level) : Type := Q(Sort u)
#guard_msgs(drop info, warning, error) in
#eval bar2 q([1,2, 4])
/-- info: q(∀ (x : Nat), x = x + 0) : Q(Prop) -/
#guard_msgs in
#check q(∀ x, x = x + 0)
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/misc.lean
|
baz
| null |
foo' (n : Nat) : Q(Q($($n) = $($n))) := q(q(by simp))
#guard_msgs(drop info, warning, error) in
#eval foo' 3
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/misc.lean
|
foo'
| null |
mkPairwiseEquality {α : Q(Sort u)} : List Q($α) → Q(Prop)
| [a, b] => q($a = $b)
| a :: b :: cs => q($a = $b ∧ $(mkPairwiseEquality (b :: cs)))
| _ => q(True)
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/mkPairwiseEquality.lean
|
mkPairwiseEquality
| null |
Semigroup (M) extends Mul M where
mul_assoc {a b c : M} : (a*b)*c = a*(b*c)
export Semigroup (mul_assoc)
|
class
|
QqTest
|
[
"Qq"
] |
QqTest/strengthenInstance.lean
|
Semigroup
| null |
maybeReassoc {M : Q(Type $u)} (mul : Q(Mul $M)) (a b : Q($M)) :
MetaM (Option Q($a*($b*$b) = ($a*$b)*$b)) := do
let .some inst ← trySynthInstanceQ q(Semigroup $M) | return none
assertInstancesCommute
return some q(by rw [mul_assoc])
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/strengthenInstance.lean
|
maybeReassoc
| null |
maybeReassocAlt {M : Q(Type $u)} (mul : Q(Mul $M)) (a b : Q($M)) :
MetaM (Option Q($a*($b*$b) = ($a*$b)*$b)) := do
let .some inst ← trySynthInstanceQ q(Semigroup $M) | return none
assumeInstancesCommute
return some q(by rw [mul_assoc])
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/strengthenInstance.lean
|
maybeReassocAlt
| null |
maybeReassocPure {M : Q(Type $u)} (mul : Q(Mul $M)) (a b : Q($M)) (semigroup : Q(Semigroup $M)) :
Q($a*($b*$b) = ($a*$b)*$b) :=
assumeInstancesCommute'
q(by rw [mul_assoc])
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/strengthenInstance.lean
|
maybeReassocPure
| null |
typeClassArgument (α : Q(Sort u)) (inst : Q(Inhabited $α)) : Q($α) :=
q(Inhabited.default)
|
def
|
QqTest
|
[
"Qq"
] |
QqTest/typeclass.lean
|
typeClassArgument
| null |
mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do
let u ← getDecLevel type
let id := Lean.mkConst ``Id [u]
pure { m := id, returnType := type, expectedType := mkApp id type }
|
def
|
Qq
|
[
"Lean"
] |
Qq/ForLean/Do.lean
|
mkIdBindFor
| null |
extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do
match expectedType? with
| none => throwError "invalid 'do' notation, expected type is not available"
| some expectedType =>
let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match type with
| .app m returnType =>
return some { m, returnType, expectedType }
| _ =>
return none
let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match (← extractStep? type) with
| some r => return r
| none =>
let typeNew ← whnfCore type
if typeNew != type then
extract? typeNew
else
if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available"
match (← unfoldDefinition? typeNew) with
| some typeNew => extract? typeNew
| none => return none
match (← extract? expectedType) with
| some r => return r
| none => mkIdBindFor expectedType
|
def
|
Qq
|
[
"Lean"
] |
Qq/ForLean/Do.lean
|
extractBind
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.