blob: 78a534372c1bd8f473ef5aeb5dd08dced228e444 [file]
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Gabriel Ebner, Mario Carneiro
-/
module
prelude
public import Lean.Meta.Tactic.TryThis
public import Lean.Elab.Tactic.Simp
public import Lean.Elab.App
public section
namespace Lean
/--
Enables the 'unnecessary `simpa`' linter. This will report if a use of
`simpa` could be proven using `simp` or `simp at h` instead.
-/
register_builtin_option linter.unnecessarySimpa : Bool := {
defValue := true
descr := "enable the 'unnecessary simpa' linter"
}
end Lean
namespace Lean.Elab.Tactic.Simpa
open Lean Parser.Tactic Elab Meta Term Tactic Simp Linter
/-- Gets the value of the `linter.unnecessarySimpa` option. -/
def getLinterUnnecessarySimpa (o : LinterOptions) : Bool :=
getLinterValue linter.unnecessarySimpa o
private def logUnnecessarySimpa (initialState : SavedState) (ref : Syntax)
(replacement : TSyntax `tactic) : TacticM Unit := do
let mut msg := m!"`simp` already closes the goal"
if ← Meta.Tactic.TryThis.isValidTactic initialState replacement then
let suggestion : Meta.Hint.Suggestion := {
suggestion := replacement
span? := ref
diffGranularity := .none
}
let hint ← MessageData.hint "Use `simp` instead of `simpa`:" #[suggestion] (ref? := ref)
msg := msg ++ hint
logLint linter.unnecessarySimpa ref msg
/--
Core implementation of the `simpa` tactic, parameterized by whether the final
unification of the simplified `using` term against the simplified goal should
be performed at reducible transparency (`useReducible := true`, used by
`simpa using h`) or at the ambient default/semireducible transparency
(`useReducible := false`, used by `simpa using! h`).
-/
private def evalSimpaCore (useReducible : Bool) : Tactic := fun stx => do
match stx with
| `(tactic| simpa%$tk $[?%$squeeze]? $[!%$unfold]? $cfg:optConfig $(disch)? $[only%$only]?
$[[$args,*]]? $[using%$usingTk? $usingArg]?) => Elab.Tactic.focus do withSimpDiagnostics do
let initialState ← saveState
let mkSimpReplacement (loc : Option (TSyntax ``Parser.Tactic.location)) :
TacticM (TSyntax `tactic) := do
match squeeze.isSome, unfold.isSome with
| false, false =>
`(tactic| simp $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]? $[$loc]?)
| false, true =>
`(tactic| simp! $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]? $[$loc]?)
| true, false =>
`(tactic| simp? $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]? $[$loc]?)
| true, true =>
`(tactic| simp?! $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]? $[$loc]?)
let stx ← `(tactic| simp $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]?)
let stats ← do
let { ctx, simprocs, dischargeWrapper, .. } ← withMainContext <| mkSimpContext stx (eraseLocal := false)
let ctx := if unfold.isSome then ctx.setAutoUnfold else ctx
-- TODO: have `simpa` fail if it doesn't use `simp`.
let ctx := ctx.setFailIfUnchanged false
dischargeWrapper.with fun discharge? => do
-- When there is a `using` clause we add tactic info showing the simplified goal.
-- The span is `simpa ... using`.
let mkInfo ← mkInitialTacticInfo (mkNullNode #[tk, usingTk?.getD .missing])
let (some (_, g), stats) ← simpGoal (← getMainGoal) ctx (simprocs := simprocs) (simplifyTarget := true) (discharge? := discharge?)
| if getLinterUnnecessarySimpa (← getLinterOptions) then
let ref ← getRef
logUnnecessarySimpa initialState ref (← mkSimpReplacement none)
return {}
-- Replace the goal; captured by `mkInfo` in `using` case below.
replaceMainGoal [g]
g.withContext do
if let some stx := usingArg then
if (← getInfoState).enabled then
let trees ← getResetInfoTrees
withInfoContext (mkInfo := mkInfo) do
-- Re-nest info trees so far into tactic info node
modifyInfoState fun st => { st with trees }
let mvarCounterSaved := (← getMCtx).mvarCounter
let e ← Tactic.elabTerm stx none (mayPostpone := true)
unless ← occursCheck g e do
throwError "Occurs check failed: Expression{indentExpr e}\ncontains the goal {Expr.mvar g}"
-- Copy the goal. We want to defer assigning `g := g'` to prevent `MVarId.note` from
-- partially assigning the goal in case we need to log unassigned metavariables.
-- Without deferring, this can cause `logUnassignedAndAbort` to report that `g` could not
-- be synthesized; recall that this function reports that a metavariable could not be
-- synthesized if, after mvar instantiation, it contains one of the provided mvars.
let gCopy ← mkFreshExprSyntheticOpaqueMVar (← g.getType) (← g.getTag)
let (h, g') ← gCopy.mvarId!.note `h e
let (result?, stats) ← simpGoal g' ctx (simprocs := simprocs) (fvarIdsToSimp := #[h])
(simplifyTarget := false) (stats := stats) (discharge? := discharge?)
match result? with
| some (xs, g') =>
let h := xs[0]?.getD h
let name ← mkFreshUserName `h
let g' ← g'.rename h name
g'.withContext do
let gType ← g'.getType
let h ← Term.elabTerm (mkIdent name) gType
Term.synthesizeSyntheticMVarsNoPostponing
let hType ← inferType h
let isCompatible : MetaM Bool :=
withAssignableSyntheticOpaque <| isDefEq gType hType
unless (← if useReducible then withReducible isCompatible else isCompatible) do
-- `e` still is valid in this new local context
Term.throwTypeMismatchError gType hType h
(header? := some m!"Type mismatch: After simplification, term{indentExpr e}\n")
logUnassignedAndAbort (← filterOldMVars (← getMVars e) mvarCounterSaved)
pushGoal g'
closeMainGoal `simpa (checkUnassigned := false) h
| none =>
if getLinterUnnecessarySimpa (← getLinterOptions) then
if let .fvar h := e then
if let some name := (← getLCtx).getRoundtrippingUserName? h then
let hStx : TSyntax `term := ⟨mkIdent name⟩
let hyp ← `(locationHyp| $hStx:term)
let loc ← `(location| at $hyp:locationHyp)
let ref ← getRef
logUnnecessarySimpa initialState ref (← mkSimpReplacement (some loc))
g.assign gCopy
pure stats
else if let some ldecl := (← getLCtx).findFromUserName? `this then
if let (some (_, g), stats) ← simpGoal g ctx (simprocs := simprocs)
(fvarIdsToSimp := #[ldecl.fvarId]) (simplifyTarget := false) (stats := stats)
(discharge? := discharge?) then
g.assumption
pure stats
else
pure stats
else
g.assumption
pure stats
if tactic.simp.trace.get (← getOptions) || squeeze.isSome then
let usingArg : Option Term := usingArg.map (⟨·.raw.unsetTrailing⟩)
let stx ← match ← mkSimpOnly stx.raw.unsetTrailing stats.usedTheorems with
| `(tactic| simp $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]?) =>
match unfold.isSome, useReducible, usingArg with
| true, true, _ => `(tactic| simpa! $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]? $[using $usingArg]?)
| false, true, _ => `(tactic| simpa $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]? $[using $usingArg]?)
| true, false, some ua => `(tactic| simpa ! $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]? using! $ua)
| false, false, some ua => `(tactic| simpa $cfg:optConfig $(disch)? $[only%$only]? $[[$args,*]]? using! $ua)
| _, false, none => unreachable! -- `using!` requires a term
| _ => unreachable!
TryThis.addSuggestion tk stx (origSpan? := ← getRef)
return stats.diag
| _ => throwUnsupportedSyntax
@[builtin_tactic Lean.Parser.Tactic.simpa] def evalSimpa : Tactic :=
evalSimpaCore (useReducible := true)
@[builtin_tactic Lean.Parser.Tactic.simpaUsingBang] def evalSimpaUsingBang : Tactic := fun stx => do
-- The `simpa ... using! e` syntax is identical to `simpa ... using e` except for
-- the trailing `using!` vs `using`. Rewrite to the `simpa` shape and dispatch
-- to the shared core, opting into the permissive default-transparency close.
match stx with
| `(tactic| simpa%$tk $[?%$squeeze]? $[!%$unfold]? $cfg:optConfig $(disch)? $[only%$only]?
$[[$args,*]]? using! $usingArg) => do
let stx' ← `(tactic| simpa%$tk $[?%$squeeze]? $[!%$unfold]? $cfg:optConfig $(disch)? $[only%$only]?
$[[$args,*]]? using $usingArg)
evalSimpaCore (useReducible := false) stx'
| _ => throwUnsupportedSyntax
end Lean.Elab.Tactic.Simpa