fact
stringlengths
6
3.84k
type
stringclasses
11 values
library
stringclasses
32 values
imports
listlengths
1
14
filename
stringlengths
20
95
symbolic_name
stringlengths
1
90
docstring
stringlengths
7
20k
partial copyMetaData (cfg : Config) (src tgt : Name) (argInfo : ArgInfo) : CoreM (Array Name) := do if let some eqns := eqnsAttribute.find? (← getEnv) src then unless (eqnsAttribute.find? (← getEnv) tgt).isSome do for eqn in eqns do _ ← addToAdditiveAttr eqn cfg eqnsAttribute.add tgt (eqns.map (findTranslation? (← getEnv) · |>.get!)) else /- We need to generate all equation lemmas for `src` and `tgt`, even for non-recursive definitions. If we don't do that, the equation lemma for `src` might be generated later when doing a `rw`, but it won't be generated for `tgt`. -/ additivizeLemmas #[src, tgt] argInfo "equation lemmas" fun nm ↦ (·.getD #[]) <$> MetaM.run' (getEqnsFor? nm) MetaM.run' <| Elab.Term.TermElabM.run' <| applyAttributes cfg.ref cfg.attrs `to_additive src tgt argInfo
def
Tactic
[ "Batteries.Tactic.Trans", "Lean.Compiler.NoncomputableAttr", "Lean.Elab.Tactic.Ext", "Lean.Meta.Tactic.Rfl", "Lean.Meta.Tactic.Symm", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.Array.Defs", "Mathlib.Data.Nat.Notation", "Mathlib.Lean.Expr.ReplaceRec", "Mathlib.Lean.Meta.Simp", "Mathlib.Lean.Name",...
Mathlib/Tactic/ToAdditive/Frontend.lean
copyMetaData
Copies equation lemmas and attributes from `src` to `tgt`
partial transformDecl (cfg : Config) (src tgt : Name) (argInfo : ArgInfo := {}) : CoreM (Array Name) := do transformDeclAux cfg src tgt src copyMetaData cfg src tgt argInfo
def
Tactic
[ "Batteries.Tactic.Trans", "Lean.Compiler.NoncomputableAttr", "Lean.Elab.Tactic.Ext", "Lean.Meta.Tactic.Rfl", "Lean.Meta.Tactic.Symm", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.Array.Defs", "Mathlib.Data.Nat.Notation", "Mathlib.Lean.Expr.ReplaceRec", "Mathlib.Lean.Meta.Simp", "Mathlib.Lean.Name",...
Mathlib/Tactic/ToAdditive/Frontend.lean
transformDecl
Make a new copy of a declaration, replacing fragments of the names of identifiers in the type and the body using the `translations` dictionary. This is used to implement `@[to_additive]`.
partial checkExistingType (src tgt : Name) (reorder : List (List Nat)) (dont : List Ident) : MetaM Unit := do let mut srcDecl ← getConstInfo src let tgtDecl ← getConstInfo tgt if 0 ∈ reorder.flatten then srcDecl := srcDecl.updateLevelParams srcDecl.levelParams.swapFirstTwo unless srcDecl.levelParams.length == tgtDecl.levelParams.length do throwError "`to_additive` validation failed:\n expected {srcDecl.levelParams.length} universe \ levels, but '{tgt}' has {tgtDecl.levelParams.length} universe levels" let type := srcDecl.type.instantiateLevelParams srcDecl.levelParams (tgtDecl.levelParams.map mkLevelParam) let tgtType := tgtDecl.type.instantiateLevelParams tgtDecl.levelParams (tgtDecl.levelParams.map mkLevelParam) let dont ← getDontTranslates dont type let type ← reorderForall reorder <| ← applyReplacementForall dont <| ← unfoldAuxLemmas type unless ← withReducible <| isDefEq type tgtType do throwError "`to_additive` validation failed: expected{indentExpr type}\nbut '{tgt}' has \ type{indentExpr tgtType}"
def
Tactic
[ "Batteries.Tactic.Trans", "Lean.Compiler.NoncomputableAttr", "Lean.Elab.Tactic.Ext", "Lean.Meta.Tactic.Rfl", "Lean.Meta.Tactic.Symm", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.Array.Defs", "Mathlib.Data.Nat.Notation", "Mathlib.Lean.Expr.ReplaceRec", "Mathlib.Lean.Meta.Simp", "Mathlib.Lean.Name",...
Mathlib/Tactic/ToAdditive/Frontend.lean
checkExistingType
Verify that the type of given `srcDecl` translates to that of `tgtDecl`.
partial addToAdditiveAttr (src : Name) (cfg : Config) (kind := AttributeKind.global) : AttrM (Array Name) := do if (kind != AttributeKind.global) then throwError "`to_additive` can only be used as a global attribute" withOptions (· |>.updateBool `trace.to_additive (cfg.trace || ·)) <| do if let some tgt := findTranslation? (← getEnv) src then if cfg.reorder != [] then modifyEnv (reorderAttr.addEntry · (src, cfg.reorder)) return #[tgt] if let some relevantArg := cfg.relevantArg? then modifyEnv (relevantArgAttr.addEntry · (src, relevantArg)) return #[tgt] let tgt ← targetName cfg src let alreadyExists := (← getEnv).contains tgt if cfg.existing != alreadyExists && !(← isInductive src) then Linter.logLintIf linter.toAdditiveExisting cfg.ref <| if alreadyExists then m!"The additive declaration already exists. Please specify this explicitly using \ `@[to_additive existing]`." else "The additive declaration doesn't exist. Please remove the option `existing`." if alreadyExists then MetaM.run' <| checkExistingType src tgt cfg.reorder cfg.dontTranslate let relevantArg ← cfg.relevantArg?.getDM <| MetaM.run' <| findMultiplicativeArg src let argInfo := { reorder := cfg.reorder, relevantArg } insertTranslationAndInfo src tgt argInfo alreadyExists let nestedNames ← if alreadyExists then trace[to_additive_detail] "declaration {tgt} already exists." proceedFields src tgt argInfo copyMetaData cfg src tgt argInfo else transformDecl cfg src tgt argInfo pushInfoLeaf <| .ofTermInfo { elaborator := .anonymous, lctx := {}, expectedType? := none, isBinder := !alreadyExists, stx := cfg.ref, expr := ← mkConstWithLevelParams tgt } if let some doc := cfg.doc then addDocStringCore tgt doc return nestedNames.push tgt
def
Tactic
[ "Batteries.Tactic.Trans", "Lean.Compiler.NoncomputableAttr", "Lean.Elab.Tactic.Ext", "Lean.Meta.Tactic.Rfl", "Lean.Meta.Tactic.Symm", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.Array.Defs", "Mathlib.Data.Nat.Notation", "Mathlib.Lean.Expr.ReplaceRec", "Mathlib.Lean.Meta.Simp", "Mathlib.Lean.Name",...
Mathlib/Tactic/ToAdditive/Frontend.lean
addToAdditiveAttr
`addToAdditiveAttr src cfg` adds a `@[to_additive]` attribute to `src` with configuration `cfg`. See the attribute implementation for more details. It returns an array with names of additive declarations (usually 1, but more if there are nested `to_additive` calls.
endCapitalNames : TreeMap String (List String) compare := .ofList [("LE", [""]), ("LT", [""]), ("WF", [""]), ("Coe", ["TC", "T", "HTCT"])] open String in
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
endCapitalNames
A set of strings of names that end in a capital letter. * If the string contains a lowercase letter, the string should be split between the first occurrence of a lower-case letter followed by an upper-case letter. * If multiple strings have the same prefix, they should be grouped by prefix * In this case, the second list should be prefix-free (no element can be a prefix of a later element) Todo: automate the translation from `String` to an element in this `TreeMap` (but this would require having something similar to the `rb_lmap` from Lean 3).
partial _root_.String.splitCase (s : String) (i₀ : Pos := 0) (r : List String := []) : List String := Id.run do let i₁ := s.next i₀ if s.atEnd i₁ then let r := s::r return r.reverse /- We split the string in three cases * We split on both sides of `_` to keep them there when rejoining the string; * We split after a name in `endCapitalNames`; * We split after a lower-case letter that is followed by an upper-case letter (unless it is part of a name in `endCapitalNames`). -/ if s.get i₀ == '_' || s.get i₁ == '_' then return splitCase (s.extract i₁ s.endPos) 0 <| (s.extract 0 i₁)::r if (s.get i₁).isUpper then if let some strs := endCapitalNames[s.extract 0 i₁]? then if let some (pref, newS) := strs.findSome? fun x : String ↦ (s.extract i₁ s.endPos).dropPrefix? x |>.map (x, ·.toString) then return splitCase newS 0 <| (s.extract 0 i₁ ++ pref)::r if !(s.get i₀).isUpper then return splitCase (s.extract i₁ s.endPos) 0 <| (s.extract 0 i₁)::r return splitCase s i₁ r
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
_root_.String.splitCase
This function takes a String and splits it into separate parts based on the following [naming conventions](https://github.com/leanprover-community/mathlib4/wiki#naming-convention). E.g. `#eval "InvHMulLEConjugate₂SMul_ne_top".splitCase` yields `["Inv", "HMul", "LE", "Conjugate₂", "SMul", "_", "ne", "_", "top"]`.
partial capitalizeLikeAux (s : String) (i : String.Pos := 0) (p : String) : String := if p.atEnd i || s.atEnd i then p else let j := p.next i if (s.get i).isLower then capitalizeLikeAux s j <| p.set i (p.get i |>.toLower) else if (s.get i).isUpper then capitalizeLikeAux s j <| p.set i (p.get i |>.toUpper) else capitalizeLikeAux s j p
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
capitalizeLikeAux
Helper for `capitalizeLike`.
capitalizeLike (r : String) (s : String) := capitalizeLikeAux r 0 s
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
capitalizeLike
Capitalizes `s` char-by-char like `r`. If `s` is longer, it leaves the tail untouched.
capitalizeFirstLike (s : String) : List String → List String | x :: r => capitalizeLike s x :: r | [] => []
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
capitalizeFirstLike
Capitalize First element of a list like `s`. Note that we need to capitalize multiple characters in some cases, in examples like `HMul` or `hAdd`.
nameDict : String → List String | "one" => ["zero"] | "mul" => ["add"] | "smul" => ["vadd"] | "inv" => ["neg"] | "div" => ["sub"] | "prod" => ["sum"] | "hmul" => ["hadd"] | "hsmul" => ["hvadd"] | "hdiv" => ["hsub"] | "hpow" => ["hsmul"] | "finprod" => ["finsum"] | "tprod" => ["tsum"] | "pow" => ["nsmul"] | "npow" => ["nsmul"] | "zpow" => ["zsmul"] | "mabs" => ["abs"] | "monoid" => ["add", "Monoid"] | "submonoid" => ["add", "Submonoid"] | "group" => ["add", "Group"] | "subgroup" => ["add", "Subgroup"] | "semigroup" => ["add", "Semigroup"] | "magma" => ["add", "Magma"] | "haar" => ["add", "Haar"] | "prehaar" => ["add", "Prehaar"] | "unit" => ["add", "Unit"] | "units" => ["add", "Units"] | "cyclic" => ["add", "Cyclic"] | "rootable" => ["divisible"] | "semigrp" => ["add", "Semigrp"] | "grp" => ["add", "Grp"] | "commute" => ["add", "Commute"] | "semiconj" => ["add", "Semiconj"] | "zpowers" => ["zmultiples"] | "powers" => ["multiples"] | "multipliable" => ["summable"] | "gpfree" => ["apfree"] | "quantale" => ["add", "Quantale"] | "square" => ["even"] | "mconv" => ["conv"] | "irreducible" => ["add", "Irreducible"] | "mlconvolution" => ["lconvolution"] | x => [x]
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
nameDict
Dictionary used by `guessName` to autogenerate names. Note: `guessName` capitalizes first element of the output according to capitalization of the input. Input and first element should therefore be lower-case, 2nd element should be capitalized properly.
applyNameDict : List String → List String | x :: s => (capitalizeFirstLike x (nameDict x.toLower)) ++ applyNameDict s | [] => []
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
applyNameDict
Turn each element to lower-case, apply the `nameDict` and capitalize the output like the input.
fixAbbreviation : List String → List String | "is" :: "Cancel" :: "Add" :: s => "isCancelAdd" :: fixAbbreviation s | "Is" :: "Cancel" :: "Add" :: s => "IsCancelAdd" :: fixAbbreviation s | "is" :: "Left" :: "Cancel" :: "Add" :: s => "isLeftCancelAdd" :: fixAbbreviation s | "Is" :: "Left" :: "Cancel" :: "Add" :: s => "IsLeftCancelAdd" :: fixAbbreviation s | "is" :: "Right" :: "Cancel" :: "Add" :: s => "isRightCancelAdd" :: fixAbbreviation s | "Is" :: "Right" :: "Cancel" :: "Add" :: s => "IsRightCancelAdd" :: fixAbbreviation s | "cancel" :: "Add" :: s => "addCancel" :: fixAbbreviation s | "Cancel" :: "Add" :: s => "AddCancel" :: fixAbbreviation s | "left" :: "Cancel" :: "Add" :: s => "addLeftCancel" :: fixAbbreviation s | "Left" :: "Cancel" :: "Add" :: s => "AddLeftCancel" :: fixAbbreviation s | "right" :: "Cancel" :: "Add" :: s => "addRightCancel" :: fixAbbreviation s | "Right" :: "Cancel" :: "Add" :: s => "AddRightCancel" :: fixAbbreviation s | "cancel" :: "Comm" :: "Add" :: s => "addCancelComm" :: fixAbbreviation s | "Cancel" :: "Comm" :: "Add" :: s => "AddCancelComm" :: fixAbbreviation s | "comm" :: "Add" :: s => "addComm" :: fixAbbreviation s | "Comm" :: "Add" :: s => "AddComm" :: fixAbbreviation s | "Zero" :: "LE" :: s => "Nonneg" :: fixAbbreviation s | "zero" :: "_" :: "le" :: s => "nonneg" :: fixAbbreviation s | "zero" :: "LE" :: s => "nonneg" :: fixAbbreviation s | "Zero" :: "LT" :: s => "Pos" :: fixAbbreviation s | "zero" :: "_" :: "lt" :: s => "pos" :: fixAbbreviation s | "zero" :: "LT" :: s => "pos" :: fixAbbreviation s | "LE" :: "Zero" :: s => "Nonpos" :: fixAbbreviation s | "le" :: "_" :: "zero" :: s => "nonpos" :: fixAbbreviation s | "LT" :: "Zero" :: s => "Neg" :: fixAbbreviation s | "lt" :: "_" :: "zero" :: s => "neg" :: fixAbbreviation s | "Add" :: "Single" :: s => "Single" :: fixAbbreviation s | "add" :: "Single" :: s => "single" :: fixAbbreviation s | "add" :: "_" :: "single" :: s => "single" :: fixAbbreviation s | "Add" :: "Support" :: s => "Support" :: fixAbbreviation s | "add" :: "Support" :: s => "support" :: fixAbbreviation s | "add" :: "_" :: "support" :: s => "support" :: fixAbbreviation s | "Add" :: "TSupport" :: s => "TSupport" :: fixAbbreviation s | "add" :: "TSupport" :: s => "tsupport" :: fixAbbreviation s | "add" :: "_" :: "tsupport" :: s => "tsupport" :: fixAbbreviation s | "Add" :: "Indicator" :: s => "Indicator" :: fixAbbreviation s | "add" :: "Indicator" :: s => "indicator" :: fixAbbreviation s | "add" :: "_" :: "indicator" :: s => "indicator" :: fixAbbreviation s | "is" :: "Even" :: s => "even" :: fixAbbreviation s | "Is" :: "Even" :: s => "Even" :: fixAbbreviation s | "is" :: "Regular" :: s => "isAddRegular" :: fixAbbreviation s | "Is" :: "Regular" :: s => "IsAddRegular" :: fixAbbreviation s | "is" :: "Left" :: "Regular" :: s => "isAddLeftRegular" :: fixAbbreviation s | "Is" :: "Left" :: "Regular" :: s => "IsAddLeftRegular" :: fixAbbreviation s | "is" :: "Right" :: "Regular" :: s => "isAddRightRegular" :: fixAbbreviation s | "Is" :: "Right" :: "Regular" :: s => "IsAddRightRegular" :: fixAbbreviation s | "Has" :: "Fundamental" :: "Domain" :: s => "HasAddFundamentalDomain" :: fixAbbreviation s | "has" :: "Fundamental" :: "Domain" :: s => "hasAddFundamentalDomain" :: fixAbbreviation s | "Quotient" :: "Measure" :: s => "AddQuotientMeasure" :: fixAbbreviation s | "quotient" :: "Measure" :: s => "addQuotientMeasure" :: fixAbbreviation s ...
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
fixAbbreviation
There are a few abbreviations we use. For example "Nonneg" instead of "ZeroLE" or "addComm" instead of "commAdd". Note: The input to this function is case sensitive! Todo: A lot of abbreviations here are manual fixes and there might be room to improve the naming logic to reduce the size of `fixAbbreviation`.
guessName : String → String := String.mapTokens '\'' <| fun s => String.join <| fixAbbreviation <| applyNameDict <| s.splitCase
def
Tactic
[ "Std.Data.TreeMap.Basic", "Mathlib.Data.String.Defs" ]
Mathlib/Tactic/ToAdditive/GuessName.lean
guessName
Autogenerate additive name. This runs in several steps: 1) Split according to capitalisation rule and at `_`. 2) Apply word-by-word translation rules. 3) Fix up abbreviations that are not word-by-word translations, like "addComm" or "Nonneg".
@[tactic_code_action calcTactic] createCalc : TacticCodeAction := fun _params _snap ctx _stack node => do let .node (.ofTacticInfo info) _ := node | return #[] if info.goalsBefore.isEmpty then return #[] let eager := { title := s!"Generate a calc block." kind? := "quickfix" } let doc ← readDoc return #[{ eager lazy? := some do let tacPos := doc.meta.text.utf8PosToLspPos info.stx.getPos?.get! let endPos := doc.meta.text.utf8PosToLspPos info.stx.getTailPos?.get! let goal := info.goalsBefore[0]! let goalFmt ← ctx.runMetaM {} <| goal.withContext do Meta.ppExpr (← goal.getType) return { eager with edit? := some <|.ofTextEdit doc.versionedIdentifier { range := ⟨tacPos, endPos⟩, newText := s!"calc {goalFmt} := by sorry" } } }]
def
Tactic
[ "Lean.Elab.Tactic.Calc", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.String.Defs", "Mathlib.Tactic.Widget.SelectPanelUtils", "Batteries.CodeAction.Attr", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Calc.lean
createCalc
Code action to create a `calc` tactic from the current goal.
CalcParams extends SelectInsertParams where /-- Is this the first calc step? -/ isFirst : Bool /-- indentation level of the calc block. -/ indent : Nat deriving SelectInsertParamsClass, RpcEncodable
structure
Tactic
[ "Lean.Elab.Tactic.Calc", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.String.Defs", "Mathlib.Tactic.Widget.SelectPanelUtils", "Batteries.CodeAction.Attr", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Calc.lean
CalcParams
Parameters for the calc widget.
suggestSteps (pos : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (params : CalcParams) : MetaM (String × String × Option (String.Pos × String.Pos)) := do let subexprPos := getGoalLocations pos let some (rel, lhs, rhs) ← Lean.Elab.Term.getCalcRelation? goalType | throwError "invalid 'calc' step, relation expected{indentExpr goalType}" let relApp := mkApp2 rel (← mkFreshExprMVar none) (← mkFreshExprMVar none) let some relStr := ((← Meta.ppExpr relApp) |> toString |>.splitOn)[1]? | throwError "could not find relation symbol in {relApp}" let isSelectedLeft := subexprPos.any (fun L ↦ #[0, 1].isPrefixOf L.toArray) let isSelectedRight := subexprPos.any (fun L ↦ #[1].isPrefixOf L.toArray) let mut goalType := goalType for pos in subexprPos do goalType ← insertMetaVar goalType pos let some (_, newLhs, newRhs) ← Lean.Elab.Term.getCalcRelation? goalType | throwError "invalid 'calc' step, relation expected{indentExpr goalType}" let lhsStr := (toString <| ← Meta.ppExpr lhs).renameMetaVar let newLhsStr := (toString <| ← Meta.ppExpr newLhs).renameMetaVar let rhsStr := (toString <| ← Meta.ppExpr rhs).renameMetaVar let newRhsStr := (toString <| ← Meta.ppExpr newRhs).renameMetaVar let spc := String.replicate params.indent ' ' let insertedCode := match isSelectedLeft, isSelectedRight with | true, true => if params.isFirst then s!"{lhsStr} {relStr} {newLhsStr} := by sorry\n{spc}_ {relStr} {newRhsStr} := by sorry\n\ {spc}_ {relStr} {rhsStr} := by sorry" else s!"_ {relStr} {newLhsStr} := by sorry\n{spc}\ _ {relStr} {newRhsStr} := by sorry\n{spc}\ _ {relStr} {rhsStr} := by sorry" | false, true => if params.isFirst then s!"{lhsStr} {relStr} {newRhsStr} := by sorry\n{spc}_ {relStr} {rhsStr} := by sorry" else s!"_ {relStr} {newRhsStr} := by sorry\n{spc}_ {relStr} {rhsStr} := by sorry" | true, false => if params.isFirst then s!"{lhsStr} {relStr} {newLhsStr} := by sorry\n{spc}_ {relStr} {rhsStr} := by sorry" else s!"_ {relStr} {newLhsStr} := by sorry\n{spc}_ {relStr} {rhsStr} := by sorry" | false, false => "This should not happen" let stepInfo := match isSelectedLeft, isSelectedRight with | true, true => "Create two new steps" | true, false | false, true => "Create a new step" | false, false => "This should not happen" let pos : String.Pos := insertedCode.find (fun c => c == '?') return (stepInfo, insertedCode, some (pos, ⟨pos.byteIdx + 2⟩) )
def
Tactic
[ "Lean.Elab.Tactic.Calc", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.String.Defs", "Mathlib.Tactic.Widget.SelectPanelUtils", "Batteries.CodeAction.Attr", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Calc.lean
suggestSteps
Return the link text and inserted text above and below of the calc widget.
@[server_rpc_method] CalcPanel.rpc := mkSelectionPanelRPC suggestSteps "Please select subterms using Shift-click." "Calc 🔍"
def
Tactic
[ "Lean.Elab.Tactic.Calc", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.String.Defs", "Mathlib.Tactic.Widget.SelectPanelUtils", "Batteries.CodeAction.Attr", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Calc.lean
CalcPanel.rpc
Rpc function for the calc widget.
@[widget_module] CalcPanel : Component CalcParams := mk_rpc_widget% CalcPanel.rpc
def
Tactic
[ "Lean.Elab.Tactic.Calc", "Lean.Meta.Tactic.TryThis", "Mathlib.Data.String.Defs", "Mathlib.Tactic.Widget.SelectPanelUtils", "Batteries.CodeAction.Attr", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Calc.lean
CalcPanel
The calc widget.
@[inline] _root_.Lean.Expr.app7? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr × Expr × Expr × Expr × Expr) := if e.isAppOfArity fName 7 then some ( e.appFn!.appFn!.appFn!.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg! ) else none
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
_root_.Lean.Expr.app7
If the expression is a function application of `fName` with 7 arguments, return those arguments. Otherwise return `none`.
homType? (e : Expr) : Option (Expr × Expr) := do let some (_, _, A, B) := e.app4? ``Quiver.Hom | none return (A, B)
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
homType
Given a Hom type `α ⟶ β`, return `(α, β)`. Otherwise `none`.
homComp? (f : Expr) : Option (Expr × Expr) := do let some (_, _, _, _, _, f, g) := f.app7? ``CategoryStruct.comp | none return (f, g)
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
homComp
Given composed homs `g ≫ h`, return `(g, h)`. Otherwise `none`.
ExprEmbeds := Array (String × Expr) /-! ## Widget for general commutative diagrams -/ open scoped Jsx in
abbrev
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
ExprEmbeds
Expressions to display as labels in a diagram.
mkCommDiag (sub : String) (embeds : ExprEmbeds) : MetaM Html := do let embeds ← embeds.mapM fun (s, h) => return (s, <InteractiveCode fmt={← Widget.ppExprTagged h} />) return ( <PenroseDiagram embeds={embeds} dsl={include_str ".."/".."/".."/"widget"/"src"/"penrose"/"commutative.dsl"} sty={include_str ".."/".."/".."/"widget"/"src"/"penrose"/"commutative.sty"} sub={sub} />) /-! ## Commutative triangles -/
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
mkCommDiag
Construct a commutative diagram from a Penrose `sub`stance program and expressions `embeds` to display as labels in the diagram.
subTriangle := include_str ".."/".."/".."/"widget"/"src"/"penrose"/"triangle.sub"
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
subTriangle
Triangle with `homs = [f,g,h]` and `objs = [A,B,C]` ``` A f B h g C ```
commTriangleM? (e : Expr) : MetaM (Option Html) := do let e ← instantiateMVars e let some (_, lhs, rhs) := e.eq? | return none if let some (f, g) := homComp? lhs then let some (A, C) := homType? (← inferType rhs) | return none let some (_, B) := homType? (← inferType f) | return none return some <| ← mkCommDiag subTriangle #[("A", A), ("B", B), ("C", C), ("f", f), ("g", g), ("h", rhs)] let some (f, g) := homComp? rhs | return none let some (A, C) := homType? (← inferType lhs) | return none let some (_, B) := homType? (← inferType f) | return none return some <| ← mkCommDiag subTriangle #[("A", A), ("B", B), ("C", C), ("f", f), ("g", g), ("h", lhs)]
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
commTriangleM
Given a commutative triangle `f ≫ g = h` or `e ≡ h = f ≫ g`, return a triangle diagram. Otherwise `none`.
@[expr_presenter] commutativeTrianglePresenter : ExprPresenter where userName := "Commutative triangle" layoutKind := .block present type := do if let some d ← commTriangleM? type then return d throwError "Couldn't find a commutative triangle." /-! ## Commutative squares -/
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
commutativeTrianglePresenter
Presenter for a commutative triangle
subSquare := include_str ".."/".."/".."/"widget"/"src"/"penrose"/"square.sub"
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
subSquare
Square with `homs = [f,g,h,i]` and `objs = [A,B,C,D]` ``` A f B i g D h C ```
commSquareM? (e : Expr) : MetaM (Option Html) := do let e ← instantiateMVars e let some (_, lhs, rhs) := e.eq? | return none let some (f, g) := homComp? lhs | return none let some (i, h) := homComp? rhs | return none let some (A, B) := homType? (← inferType f) | return none let some (D, C) := homType? (← inferType h) | return none some <$> mkCommDiag subSquare #[("A", A), ("B", B), ("C", C), ("D", D), ("f", f), ("g", g), ("h", h), ("i", i)]
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
commSquareM
Given a commutative square `f ≫ g = i ≫ h`, return a square diagram. Otherwise `none`.
@[expr_presenter] commutativeSquarePresenter : ExprPresenter where userName := "Commutative square" layoutKind := .block present type := do if let some d ← commSquareM? type then return d throwError "Couldn't find a commutative square."
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Presentation.Expr", "Mathlib.CategoryTheory.Category.Basic" ]
Mathlib/Tactic/Widget/CommDiag.lean
commutativeSquarePresenter
Presenter for a commutative square
@[nolint unusedArguments] makeCongrMString (pos : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (_ : SelectInsertParams) : MetaM (String × String × Option (String.Pos × String.Pos)) := do let subexprPos := getGoalLocations pos unless goalType.isAppOf ``Eq || goalType.isAppOf ``Iff do throwError "The goal must be an equality or iff." let mut goalTypeWithMetaVars := goalType for pos in subexprPos do goalTypeWithMetaVars ← insertMetaVar goalTypeWithMetaVars pos let side := if subexprPos[0]!.toArray[0]! = 0 then 1 else 2 let sideExpr := goalTypeWithMetaVars.getAppArgs[side]! let res := "congrm " ++ (toString (← Meta.ppExpr sideExpr)).renameMetaVar return (res, res, none)
def
Tactic
[ "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Tactic.CongrM", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/CongrM.lean
makeCongrMString
Return the link text and inserted text above and below of the congrm widget.
@[server_rpc_method] CongrMSelectionPanel.rpc := mkSelectionPanelRPC makeCongrMString "Use shift-click to select sub-expressions in the goal that should become holes in congrm." "CongrM 🔍"
def
Tactic
[ "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Tactic.CongrM", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/CongrM.lean
CongrMSelectionPanel.rpc
Rpc function for the congrm widget.
@[widget_module] CongrMSelectionPanel : Component SelectInsertParams := mk_rpc_widget% CongrMSelectionPanel.rpc open scoped Json in
def
Tactic
[ "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Tactic.CongrM", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/CongrM.lean
CongrMSelectionPanel
The congrm widget.
private SolveReturn where expr : Expr val? : Option String listRest : List Nat
structure
Tactic
[ "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Data.String.Defs", "Batteries.Tactic.Lint", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Conv.lean
SolveReturn
null
private solveLevel (expr : Expr) (path : List Nat) : MetaM SolveReturn := match expr with | Expr.app _ _ => do let mut descExp := expr let mut count := 0 let mut explicitList := [] while descExp.isApp do if (← Lean.Meta.inferType descExp.appFn!).bindingInfo!.isExplicit then explicitList := true::explicitList count := count + 1 else explicitList := false::explicitList descExp := descExp.appFn! let mut mutablePath := path let mut length := count explicitList := List.reverse explicitList while !mutablePath.isEmpty && mutablePath.head! == 0 do if explicitList.head! == true then count := count - 1 explicitList := explicitList.tail! mutablePath := mutablePath.tail! let mut nextExp := expr while length > count do nextExp := nextExp.appFn! length := length - 1 nextExp := nextExp.appArg! let pathRest := if mutablePath.isEmpty then [] else mutablePath.tail! return { expr := nextExp, val? := toString count, listRest := pathRest } | Expr.lam n _ b _ => do let name := match n with | Name.str _ s => s | _ => panic! "no name found" return { expr := b, val? := name, listRest := path.tail! } | Expr.forallE n _ b _ => do let name := match n with | Name.str _ s => s | _ => panic! "no name found" return { expr := b, val? := name, listRest := path.tail! } | Expr.mdata _ b => do match b with | Expr.mdata _ _ => return { expr := b, val? := none, listRest := path } | _ => return { expr := b.appFn!.appArg!, val? := none, listRest := path.tail!.tail! } | _ => do return { expr := ← (Lean.Core.viewSubexpr path.head! expr) val? := toString (path.head! + 1) listRest := path.tail! } open Lean Syntax in
def
Tactic
[ "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Data.String.Defs", "Batteries.Tactic.Lint", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Conv.lean
solveLevel
null
@[nolint unusedArguments] insertEnter (locations : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (params : SelectInsertParams) : MetaM (String × String × Option (String.Pos × String.Pos)) := do let some pos := locations[0]? | throwError "You must select something." let (fvar, subexprPos) ← match pos with | ⟨_, .target subexprPos⟩ => pure (none, subexprPos) | ⟨_, .hypType fvar subexprPos⟩ => pure (some fvar, subexprPos) | ⟨_, .hypValue fvar subexprPos⟩ => pure (some fvar, subexprPos) | _ => throwError "You must select something in the goal or in a local value." let mut list := (SubExpr.Pos.toArray subexprPos).toList let mut expr := goalType let mut retList := [] while !list.isEmpty do let res ← solveLevel expr list expr := res.expr retList := match res.val? with | none => retList | some val => val::retList list := res.listRest retList := List.reverse retList let spc := String.replicate (SelectInsertParamsClass.replaceRange params).start.character ' ' let loc ← match fvar with | some fvarId => pure s!"at {← fvarId.getUserName} " | none => pure "" let mut enterval := s!"conv {loc}=>\n{spc} enter {retList}" if enterval.contains '0' then enterval := "Error: Not a valid conv target" if retList.isEmpty then enterval := "" return ("Generate conv", enterval, none)
def
Tactic
[ "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Data.String.Defs", "Batteries.Tactic.Lint", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Conv.lean
insertEnter
Return the link text and inserted text above and below of the conv widget.
@[server_rpc_method] ConvSelectionPanel.rpc := mkSelectionPanelRPC insertEnter "Use shift-click to select one sub-expression in the goal that you want to zoom on." "Conv 🔍" (onlyGoal := false) (onlyOne := true)
def
Tactic
[ "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Data.String.Defs", "Batteries.Tactic.Lint", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Conv.lean
ConvSelectionPanel.rpc
Rpc function for the conv widget.
@[widget_module] ConvSelectionPanel : Component SelectInsertParams := mk_rpc_widget% ConvSelectionPanel.rpc open scoped Json in
def
Tactic
[ "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Data.String.Defs", "Batteries.Tactic.Lint", "Batteries.Lean.Position" ]
Mathlib/Tactic/Widget/Conv.lean
ConvSelectionPanel
The conv widget.
@[nolint unusedArguments] makeGCongrString (pos : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) (_ : SelectInsertParams) : MetaM (String × String × Option (String.Pos × String.Pos)) := do let subexprPos := getGoalLocations pos unless goalType.isAppOf ``LE.le || goalType.isAppOf ``LT.lt || goalType.isAppOf `Int.ModEq do panic! "The goal must be a ≤ or < or ≡." let mut goalTypeWithMetaVars := goalType for pos in subexprPos do goalTypeWithMetaVars ← insertMetaVar goalTypeWithMetaVars pos let side := if goalType.isAppOf `Int.ModEq then if subexprPos[0]!.toArray[0]! = 0 then 1 else 2 else if subexprPos[0]!.toArray[0]! = 0 then 2 else 3 let sideExpr := goalTypeWithMetaVars.getAppArgs[side]! let res := "gcongr " ++ (toString (← Meta.ppExpr sideExpr)).renameMetaVar return (res, res, none)
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Tactic.GCongr" ]
Mathlib/Tactic/Widget/GCongr.lean
makeGCongrString
Return the link text and inserted text above and below of the gcongr widget.
@[server_rpc_method] GCongrSelectionPanel.rpc := mkSelectionPanelRPC makeGCongrString "Use shift-click to select sub-expressions in the goal that should become holes in gcongr." "GCongr 🔍"
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Tactic.GCongr" ]
Mathlib/Tactic/Widget/GCongr.lean
GCongrSelectionPanel.rpc
Rpc function for the gcongr widget.
@[widget_module] GCongrSelectionPanel : Component SelectInsertParams := mk_rpc_widget% GCongrSelectionPanel.rpc open scoped Json in
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Tactic.GCongr" ]
Mathlib/Tactic/Widget/GCongr.lean
GCongrSelectionPanel
The gcongr widget.
unfoldProjDefaultInst? (e : Expr) : MetaM (Option Expr) := do let .const declName _ := e.getAppFn | return none let some { fromClass := true, ctorName, .. } ← getProjectionFnInfo? declName | return none let some (ConstantInfo.ctorInfo ci) := (← getEnv).find? ctorName | return none let defaults ← getDefaultInstances ci.induct if defaults.isEmpty then return none let some e ← withDefault <| unfoldDefinition? e | return none let .proj _ i c := e.getAppFn | return none let .const inst _ := c.getAppFn | return none unless defaults.any (·.1 == inst) do return none let some r ← withReducibleAndInstances <| project? c i | return none return mkAppN r e.getAppArgs |>.headBeta
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
unfoldProjDefaultInst
Unfold a class projection if the instance is tagged with `@[default_instance]`. This is used in the `unfold?` tactic in order to not show these unfolds to the user. Similar to `Lean.Meta.unfoldProjInst?`.
partial unfolds (e : Expr) : MetaM (Array Expr) := do let e' ← whnfCore e go e' (if e == e' then #[] else #[e']) where /-- Append the unfoldings of `e` to `acc`. Assume `e` is in `whnfCore` form. -/ go (e : Expr) (acc : Array Expr) : MetaM (Array Expr) := tryCatchRuntimeEx (withIncRecDepth do if let some e := e.etaExpandedStrict? then let e ← whnfCore e return ← go e (acc.push e) if let some e ← reduceNat? e then return acc.push e if let some e ← reduceNative? e then return acc.push e if let some e ← unfoldProjDefaultInst? e then let e ← whnfCore e return ← go e acc if let some e ← unfoldDefinition? e then let e ← whnfCore e return ← go e (acc.push e) return acc) fun _ => return acc
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
unfolds
Return the consecutive unfoldings of `e`.
isUserFriendly (e : Expr) : Bool := !e.foldConsts (init := false) (fun name => (· || name.isInternalDetail))
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
isUserFriendly
Determine whether `e` contains no internal names.
filteredUnfolds (e : Expr) : MetaM (Array Expr) := return (← unfolds e).filter isUserFriendly
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
filteredUnfolds
Return the consecutive unfoldings of `e` that are user friendly.
mkRewrite (occ : Option Nat) (symm : Bool) (e : Term) (loc : Option Name) : CoreM (TSyntax `tactic) := do let loc ← loc.mapM fun h => `(Lean.Parser.Tactic.location| at $(mkIdent h):term) let rule ← if symm then `(Parser.Tactic.rwRule| ← $e) else `(Parser.Tactic.rwRule| $e:term) match occ with | some n => `(tactic| nth_rw $(Syntax.mkNatLit n):num [$rule] $(loc)?) | none => `(tactic| rw [$rule] $(loc)?)
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
mkRewrite
Return syntax for the rewrite tactic `rw [e]`.
tacticPasteString (tac : TSyntax `tactic) (range : Lsp.Range) : CoreM String := do let column := range.start.character let indent := column return (← PrettyPrinter.ppTactic tac).pretty 100 indent column
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
tacticPasteString
Given tactic syntax `tac` that we want to paste into the editor, return it as a string. This function respects the 100 character limit for long lines.
tacticSyntax (e eNew : Expr) (occ : Option Nat) (loc : Option Name) : MetaM (TSyntax `tactic) := do let e ← PrettyPrinter.delab e let eNew ← PrettyPrinter.delab eNew let fromRfl ← `(show $e = $eNew from $(mkIdent `rfl)) mkRewrite occ false fromRfl loc
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
tacticSyntax
Return the tactic string that does the unfolding.
renderUnfolds (e : Expr) (occ : Option Nat) (loc : Option Name) (range : Lsp.Range) (doc : FileWorker.EditableDocument) : MetaM (Option Html) := do let results ← filteredUnfolds e if results.isEmpty then return none let core ← results.mapM fun unfold => do let tactic ← tacticSyntax e unfold occ loc let tactic ← tacticPasteString tactic range return <li> { .element "p" #[] <| #[<span className="font-code" style={json% { "white-space" : "pre-wrap" }}> { Html.ofComponent MakeEditLink (.ofReplaceRange doc.meta range tactic) #[.text <| Format.pretty <| (← Meta.ppExpr unfold)] } </span>] } </li> return <details «open»={true}> <summary className="mv2 pointer"> {.text "Definitional rewrites:"} </summary> {.element "ul" #[("style", json% { "padding-left" : "30px"})] core} </details> @[server_rpc_method_cancellable]
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
renderUnfolds
Render the unfolds of `e` as given by `filteredUnfolds`, with buttons at each suggestion for pasting the rewrite tactic. Return `none` when there are no unfolds.
private rpc (props : SelectInsertParams) : RequestM (RequestTask Html) := RequestM.asTask do let doc ← RequestM.readDoc let some loc := props.selectedLocations.back? | return .text "unfold?: Please shift-click an expression." if loc.loc matches .hypValue .. then return .text "unfold? doesn't work on the value of a let-bound free variable." let some goal := props.goals[0]? | return .text "There is no goal to solve!" if loc.mvarId != goal.mvarId then return .text "The selected expression should be in the main goal." goal.ctx.val.runMetaM {} do let md ← goal.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do let rootExpr ← loc.rootExpr let some (subExpr, occ) ← withReducible <| viewKAbstractSubExpr rootExpr loc.pos | return .text "expressions with bound variables are not supported" unless ← kabstractIsTypeCorrect rootExpr subExpr loc.pos do return .text <| "The selected expression cannot be rewritten, because the motive is " ++ "not type correct. This usually occurs when trying to rewrite a term that appears " ++ "as a dependent argument." let location ← loc.fvarId?.mapM FVarId.getUserName let html ← renderUnfolds subExpr occ location props.replaceRange doc return html.getD <span> No unfolds found for {<InteractiveCode fmt={← ppExprTagged subExpr}/>} </span>
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
rpc
null
@[widget_module] UnfoldComponent : Component SelectInsertParams := mk_rpc_widget% InteractiveUnfold.rpc
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
UnfoldComponent
The component called by the `unfold?` tactic
@[command_elab unfoldCommand] elabUnfoldCommand : Command.CommandElab := fun stx => withoutModifyingEnv <| Command.runTermElabM fun _ => Term.withDeclName `_unfold do let e ← Term.elabTerm stx[1] none Term.synthesizeSyntheticMVarsNoPostponing let e ← Term.levelMVarToParam (← instantiateMVars e) let e ← instantiateMVars e let unfolds ← filteredUnfolds e if unfolds.isEmpty then logInfo m! "No unfolds found for {e}" else let unfolds := unfolds.toList.map (m! "· {·}") logInfo (m! "Unfolds for {e}:\n" ++ .joinSep unfolds "\n")
def
Tactic
[ "Batteries.Lean.Position", "Mathlib.Tactic.NthRewrite", "Mathlib.Tactic.Widget.SelectPanelUtils", "Mathlib.Lean.GoalsLocation", "Mathlib.Lean.Meta.KAbstractPositions" ]
Mathlib/Tactic/Widget/InteractiveUnfold.lean
elabUnfoldCommand
Replace the selected expression with a definitional unfolding. - After each unfolding, we apply `whnfCore` to simplify the expression. - Explicit natural number expressions are evaluated. - Unfolds of class projections of instances marked with `@[default_instance]` are not shown. This is relevant for notational type classes like `+`: we don't want to suggest `Add.add a b` as an unfolding of `a + b`. Similarly for `OfNat n : Nat` which unfolds into `n : Nat`. To use `unfold?`, shift-click an expression in the tactic state. This gives a list of rewrite suggestions for the selected expression. Click on a suggestion to replace `unfold?` by a tactic that performs this rewrite. -/ elab stx:"unfold?" : tactic => do let some range := (← getFileMap).rangeOfStx? stx | return Widget.savePanelWidgetInfo (hash UnfoldComponent.javascript) (pure <| json% { replaceRange : $range }) stx /-- `#unfold? e` gives all unfolds of `e`. In tactic mode, use `unfold?` instead. -/ syntax (name := unfoldCommand) "#unfold? " term : command open Elab /-- Elaborate a `#unfold?` command.
RewriteLemma where /-- The name of the lemma -/ name : Name /-- `symm` is `true` when rewriting from right to left -/ symm : Bool deriving BEq, Inhabited
structure
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
RewriteLemma
The structure for rewrite lemmas stored in the `RefinedDiscrTree`.
isMVarSwap (t s : Expr) : Bool := go t s {} |>.isSome where /-- The main loop of `isMVarSwap`. Returning `none` corresponds to a failure. -/ go (t s : Expr) (swaps : List (MVarId × MVarId)) : Option (List (MVarId × MVarId)) := do let isTricky e := e.hasExprMVar || e.hasLevelParam if isTricky t then guard (isTricky s) match t, s with | .const n₁ _ , .const n₂ _ => guard (n₁ == n₂); some swaps | .sort _ , .sort _ => some swaps | .forallE _ d₁ b₁ _, .forallE _ d₂ b₂ _ => go d₁ d₂ swaps >>= go b₁ b₂ | .lam _ d₁ b₁ _ , .lam _ d₂ b₂ _ => go d₁ d₂ swaps >>= go b₁ b₂ | .mdata d₁ e₁ , .mdata d₂ e₂ => guard (d₁ == d₂); go e₁ e₂ swaps | .letE _ t₁ v₁ b₁ _, .letE _ t₂ v₂ b₂ _ => go t₁ t₂ swaps >>= go v₁ v₂ >>= go b₁ b₂ | .app f₁ a₁ , .app f₂ a₂ => go f₁ f₂ swaps >>= go a₁ a₂ | .proj n₁ i₁ e₁ , .proj n₂ i₂ e₂ => guard (n₁ == n₂ && i₁ == i₂); go e₁ e₂ swaps | .fvar fvarId₁ , .fvar fvarId₂ => guard (fvarId₁ == fvarId₂); some swaps | .lit v₁ , .lit v₂ => guard (v₁ == v₂); some swaps | .bvar i₁ , .bvar i₂ => guard (i₁ == i₂); some swaps | .mvar mvarId₁ , .mvar mvarId₂ => match swaps.find? (·.1 == mvarId₁) with | none => guard (swaps.all (·.2 != mvarId₂)) let swaps := (mvarId₁, mvarId₂) :: swaps if mvarId₁ == mvarId₂ then some swaps else some <| (mvarId₂, mvarId₁) :: swaps | some (_, mvarId) => guard (mvarId == mvarId₂); some swaps | _ , _ => none else guard (t == s); some swaps
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
isMVarSwap
Return `true` if `s` and `t` are equal up to changing the `MVarId`s.
@[inline] eqOrIff? (e : Expr) : Option (Expr × Expr) := match e.eq? with | some (_, lhs, rhs) => some (lhs, rhs) | none => e.iff?
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
eqOrIff
Extract the left and right-hand sides of an equality or iff statement.
addRewriteEntry (name : Name) (cinfo : ConstantInfo) : MetaM (List (RewriteLemma × List (Key × LazyEntry))) := do let .const head _ := cinfo.type.getForallBody.getAppFn | return [] unless head == ``Eq || head == ``Iff do return [] setMCtx {} -- recall that the metavariable context is not guaranteed to be empty at the start let (_, _, eqn) ← forallMetaTelescope cinfo.type let some (lhs, rhs) := eqOrIff? eqn | return [] let badMatch e := e.getAppFn.isMVar || e.eq?.any fun (α, l, r) => α.getAppFn.isMVar && l.getAppFn.isMVar && r.getAppFn.isMVar && l != r if badMatch lhs then if badMatch rhs then return [] else return [({ name, symm := true }, ← initializeLazyEntryWithEta rhs)] else let result := ({ name, symm := false }, ← initializeLazyEntryWithEta lhs) if badMatch rhs || isMVarSwap lhs rhs then return [result] else return [result, ({ name, symm := true }, ← initializeLazyEntryWithEta rhs)]
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
addRewriteEntry
Try adding the lemma to the `RefinedDiscrTree`.
addLocalRewriteEntry (decl : LocalDecl) : MetaM (List ((FVarId × Bool) × List (Key × LazyEntry))) := withReducible do let (_, _, eqn) ← forallMetaTelescope decl.type let some (lhs, rhs) := eqOrIff? eqn | return [] let result := ((decl.fvarId, false), ← initializeLazyEntryWithEta lhs) return [result, ((decl.fvarId, true), ← initializeLazyEntryWithEta rhs)]
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
addLocalRewriteEntry
Try adding the local hypothesis to the `RefinedDiscrTree`.
private ExtState := IO.Ref (Option (RefinedDiscrTree RewriteLemma)) private initialize ExtState.default : ExtState ← IO.mkRef none
abbrev
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
ExtState
null
getImportCandidates (e : Expr) : MetaM (Array (Array RewriteLemma)) := do let matchResult ← findImportMatches importedRewriteLemmasExt addRewriteEntry /- 5000 constants seems to be approximately the right number of tasks Too many means the tasks are too long. Too few means less cache can be reused and more time is spent on combining different results. With 5000 constants per task, we set the `HashMap` capacity to 256, which is the largest capacity it gets to reach. -/ (constantsPerTask := 5000) (capacityPerTask := 256) e return matchResult.flatten
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
getImportCandidates
Get all potential rewrite lemmas from the imported environment. By setting the `librarySearch.excludedModules` option, all lemmas from certain modules can be excluded.
getModuleCandidates (e : Expr) : MetaM (Array (Array RewriteLemma)) := do let moduleTreeRef ← createModuleTreeRef addRewriteEntry let matchResult ← findModuleMatches moduleTreeRef e return matchResult.flatten
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
getModuleCandidates
Get all potential rewrite lemmas from the current file. Exclude lemmas from modules in the `librarySearch.excludedModules` option.
Rewrite where /-- `symm` is `true` when rewriting from right to left -/ symm : Bool /-- The proof of the rewrite -/ proof : Expr /-- The replacement expression obtained from the rewrite -/ replacement : Expr /-- The size of the replacement when printed -/ stringLength : Nat /-- The extra goals created by the rewrite -/ extraGoals : Array (MVarId × BinderInfo) /-- Whether the rewrite introduces a new metavariable in the replacement expression. -/ makesNewMVars : Bool
structure
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
Rewrite
A rewrite lemma that has been applied to an expression.
checkRewrite (thm e : Expr) (symm : Bool) : MetaM (Option Rewrite) := do withTraceNodeBefore `rw?? (return m! "rewriting {e} by {if symm then "← " else ""}{thm}") do let (mvars, binderInfos, eqn) ← forallMetaTelescope (← inferType thm) let some (lhs, rhs) := eqOrIff? eqn | return none let (lhs, rhs) := if symm then (rhs, lhs) else (lhs, rhs) let unifies ← withTraceNodeBefore `rw?? (return m! "unifying {e} =?= {lhs}") (withReducible (isDefEq lhs e)) unless unifies do return none let lhs ← instantiateMVars lhs if lhs.toHeadIndex != e.toHeadIndex || lhs.headNumArgs != e.headNumArgs then return none synthAppInstances `rw?? default mvars binderInfos false false let mut extraGoals := #[] for mvar in mvars, bi in binderInfos do unless ← mvar.mvarId!.isAssigned do extraGoals := extraGoals.push (mvar.mvarId!, bi) let replacement ← instantiateMVars rhs let stringLength := (← ppExpr replacement).pretty.length let makesNewMVars := (replacement.findMVar? fun mvarId => mvars.any (·.mvarId! == mvarId)).isSome let proof ← instantiateMVars (mkAppN thm mvars) return some { symm, proof, replacement, stringLength, extraGoals, makesNewMVars } initialize registerTraceClass `rw??
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
checkRewrite
If `thm` can be used to rewrite `e`, return the rewrite.
checkAndSortRewriteLemmas (e : Expr) (rewrites : Array RewriteLemma) : MetaM (Array (Rewrite × Name)) := do let rewrites ← rewrites.filterMapM fun rw => tryCatchRuntimeEx do let thm ← mkConstWithFreshMVarLevels rw.name Option.map (·, rw.name) <$> checkRewrite thm e rw.symm fun _ => return none let lt (a b : (Rewrite × Name)) := Ordering.isLT <| (compare a.1.extraGoals.size b.1.extraGoals.size).then <| (compare a.1.symm b.1.symm).then <| (compare a.2.toString.length b.2.toString.length).then <| (compare a.1.stringLength b.1.stringLength).then <| (Name.cmp a.2 b.2) return rewrites.qsort lt
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
checkAndSortRewriteLemmas
Try to rewrite `e` with each of the rewrite lemmas, and sort the resulting rewrites.
getImportRewrites (e : Expr) : MetaM (Array (Array (Rewrite × Name))) := do (← getImportCandidates e).mapM (checkAndSortRewriteLemmas e)
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
getImportRewrites
Return all applicable library rewrites of `e`. Note that the result may contain duplicate rewrites. These can be removed with `filterRewrites`.
getModuleRewrites (e : Expr) : MetaM (Array (Array (Rewrite × Name))) := do (← getModuleCandidates e).mapM (checkAndSortRewriteLemmas e) /-! ### Rewriting by hypotheses -/
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
getModuleRewrites
Same as `getImportRewrites`, but for lemmas from the current file.
getHypotheses (except : Option FVarId) : MetaM (RefinedDiscrTree (FVarId × Bool)) := do let mut tree : PreDiscrTree (FVarId × Bool) := {} for decl in ← getLCtx do if !decl.isImplementationDetail && except.all (· != decl.fvarId) then for (val, entries) in ← addLocalRewriteEntry decl do for (key, entry) in entries do tree := tree.push key (entry, val) return tree.toRefinedDiscrTree
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
getHypotheses
Construct the `RefinedDiscrTree` of all local hypotheses.
getHypothesisRewrites (e : Expr) (except : Option FVarId) : MetaM (Array (Array (Rewrite × FVarId))) := do let (candidates, _) ← (← getHypotheses except).getMatch e (unify := false) (matchRootStar := true) let candidates := (← MonadExcept.ofExcept candidates).flatten candidates.mapM <| Array.filterMapM fun (fvarId, symm) => tryCatchRuntimeEx do Option.map (·, fvarId) <$> checkRewrite (.fvar fvarId) e symm fun _ => return none /-! ### Filtering out duplicate lemmas -/
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
getHypothesisRewrites
Return all applicable hypothesis rewrites of `e`. Similar to `getImportRewrites`.
getBinderInfos (fn : Expr) (args : Array Expr) : MetaM (Array BinderInfo) := do let mut fnType ← inferType fn let mut result := Array.mkEmpty args.size let mut j := 0 for i in [:args.size] do unless fnType.isForall do fnType ← whnfD (fnType.instantiateRevRange j i args) j := i let .forallE _ _ b bi := fnType | throwError m! "expected function type {indentExpr fnType}" fnType := b result := result.push bi return result
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
getBinderInfos
Get the `BinderInfo`s for the arguments of `mkAppN fn args`.
partial isExplicitEq (t s : Expr) : MetaM Bool := do if t == s then return true unless t.getAppNumArgs == s.getAppNumArgs && t.getAppFn == s.getAppFn do return false let tArgs := t.getAppArgs let sArgs := s.getAppArgs let bis ← getBinderInfos t.getAppFn tArgs t.getAppNumArgs.allM fun i _ => if bis[i]!.isExplicit then isExplicitEq tArgs[i]! sArgs[i]! else isDefEq tArgs[i]! sArgs[i]!
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
isExplicitEq
Determine whether the explicit parts of two expressions are equal, and the implicit parts are definitionally equal.
@[specialize] filterRewrites {α} (e : Expr) (rewrites : Array α) (replacement : α → Expr) (makesNewMVars : α → Bool) : MetaM (Array α) := withNewMCtxDepth do let mut filtered := #[] for rw in rewrites do if makesNewMVars rw then continue if ← isExplicitEq (replacement rw) e then trace[rw??] "discarded reflexive rewrite {replacement rw}" continue if ← filtered.anyM (isExplicitEq (replacement rw) <| replacement ·) then trace[rw??] "discarded duplicate rewrite {replacement rw}" continue filtered := filtered.push rw return filtered /-! ### User interface -/
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
filterRewrites
Filter out duplicate rewrites, reflexive rewrites or rewrites that have metavariables in the replacement expression.
tacticSyntax (rw : Rewrite) (occ : Option Nat) (loc : Option Name) : MetaM (TSyntax `tactic) := withoutModifyingMCtx do for (mvarId, _) in rw.extraGoals do mvarId.setTag .anonymous let proof ← withOptions (pp.mvars.anonymous.set · false) (PrettyPrinter.delab rw.proof) mkRewrite occ rw.symm proof loc open Widget ProofWidgets Jsx Server
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
tacticSyntax
Return the rewrite tactic that performs the rewrite.
RewriteInterface where /-- `symm` is `true` when rewriting from right to left -/ symm : Bool /-- The rewrite tactic string that performs the rewrite -/ tactic : String /-- The replacement expression obtained from the rewrite -/ replacement : Expr /-- The replacement expression obtained from the rewrite -/ replacementString : String /-- The extra goals created by the rewrite -/ extraGoals : Array CodeWithInfos /-- The lemma name with hover information -/ prettyLemma : CodeWithInfos /-- The type of the lemma -/ lemmaType : Expr /-- Whether the rewrite introduces new metavariables with the replacement. -/ makesNewMVars : Bool
structure
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
RewriteInterface
The structure with all data necessary for rendering a rewrite suggestion
Rewrite.toInterface (rw : Rewrite) (name : Name ⊕ FVarId) (occ : Option Nat) (loc : Option Name) (range : Lsp.Range) : MetaM RewriteInterface := do let tactic ← tacticSyntax rw occ loc let tactic ← tacticPasteString tactic range let replacementString := Format.pretty (← ppExpr rw.replacement) let mut extraGoals := #[] for (mvarId, bi) in rw.extraGoals do if bi.isExplicit then let extraGoal ← ppExprTagged (← instantiateMVars (← mvarId.getType)) extraGoals := extraGoals.push extraGoal match name with | .inl name => let prettyLemma := match ← ppExprTagged (← mkConstWithLevelParams name) with | .tag tag _ => .tag tag (.text s!"{name}") | code => code let lemmaType := (← getConstInfo name).type return { rw with tactic, replacementString, extraGoals, prettyLemma, lemmaType } | .inr fvarId => let prettyLemma ← ppExprTagged (.fvar fvarId) let lemmaType ← fvarId.getType return { rw with tactic, replacementString, extraGoals, prettyLemma, lemmaType }
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
Rewrite.toInterface
Construct the `RewriteInterface` from a `Rewrite`.
Kind where /-- A rewrite with a local hypothesis -/ | hypothesis /-- A rewrite with a lemma from the current file -/ | fromFile /-- A rewrite with a lemma from an imported file -/ | fromCache
inductive
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
Kind
The kind of rewrite
getRewriteInterfaces (e : Expr) (occ : Option Nat) (loc : Option Name) (except : Option FVarId) (range : Lsp.Range) : MetaM (Array (Array RewriteInterface × Kind) × Array (Array RewriteInterface × Kind)) := do let mut filtr := #[] let mut all := #[] for rewrites in ← getHypothesisRewrites e except do let rewrites ← rewrites.mapM fun (rw, fvarId) => rw.toInterface (.inr fvarId) occ loc range all := all.push (rewrites, .hypothesis) filtr := filtr.push (← filterRewrites e rewrites (·.replacement) (·.makesNewMVars), .hypothesis) for rewrites in ← getModuleRewrites e do let rewrites ← rewrites.mapM fun (rw, name) => rw.toInterface (.inl name) occ loc range all := all.push (rewrites, .fromFile) filtr := filtr.push (← filterRewrites e rewrites (·.replacement) (·.makesNewMVars), .fromFile) for rewrites in ← getImportRewrites e do let rewrites ← rewrites.mapM fun (rw, name) => rw.toInterface (.inl name) occ loc range all := all.push (rewrites, .fromCache) filtr := filtr.push (← filterRewrites e rewrites (·.replacement) (·.makesNewMVars), .fromCache) return (filtr, all)
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
getRewriteInterfaces
Return the Interfaces for rewriting `e`, both filtered and unfiltered.
pattern {α} (type : Expr) (symm : Bool) (k : Expr → MetaM α) : MetaM α := do forallTelescope type fun _ e => do let some (lhs, rhs) := eqOrIff? e | throwError "Expected equation, not {indentExpr e}" k (if symm then rhs else lhs)
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
pattern
Render the matching side of the rewrite lemma. This is shown at the header of each section of rewrite results.
renderRewrites (e : Expr) (results : Array (Array RewriteInterface × Kind)) (init : Option Html) (range : Lsp.Range) (doc : FileWorker.EditableDocument) (showNames : Bool) : MetaM Html := do let htmls ← results.filterMapM (renderSection showNames) let htmls := match init with | some html => #[html] ++ htmls | none => htmls if htmls.isEmpty then return <p> No rewrites found for <InteractiveCode fmt={← ppExprTagged e}/> </p> else return .element "div" #[("style", json% {"marginLeft" : "4px"})] htmls where /-- Render one section of rewrite results. -/ renderSection (showNames : Bool) (sec : Array RewriteInterface × Kind) : MetaM (Option Html) := do let some head := sec.1[0]? | return none let suffix := match sec.2 with | .hypothesis => " (local hypotheses)" | .fromFile => " (lemmas from current file)" | .fromCache => "" return <details «open»={true}> <summary className="mv2 pointer"> Pattern {← pattern head.lemmaType head.symm (return <InteractiveCode fmt={← ppExprTagged ·}/>)} {.text suffix} </summary> {renderSectionCore showNames sec.1} </details> /-- Render the list of rewrite results in one section. -/ renderSectionCore (showNames : Bool) (sec : Array RewriteInterface) : Html := .element "ul" #[("style", json% { "padding-left" : "30px"})] <| sec.map fun rw => <li> { .element "p" #[] <| let button := <span className="font-code"> { Html.ofComponent MakeEditLink (.ofReplaceRange doc.meta range rw.tactic) #[.text rw.replacementString] } </span> let extraGoals := rw.extraGoals.flatMap fun extraGoal => #[<br/>, <strong className="goal-vdash">⊢ </strong>, <InteractiveCode fmt={extraGoal}/>] #[button] ++ extraGoals ++ if showNames then #[<br/>, <InteractiveCode fmt={rw.prettyLemma}/>] else #[] } </li> @[server_rpc_method_cancellable]
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
renderRewrites
Render the given rewrite results.
private rpc (props : SelectInsertParams) : RequestM (RequestTask Html) := RequestM.asTask do let doc ← RequestM.readDoc let some loc := props.selectedLocations.back? | return .text "rw??: Please shift-click an expression." if loc.loc matches .hypValue .. then return .text "rw??: cannot rewrite in the value of a let variable." let some goal := props.goals[0]? | return .text "rw??: there is no goal to solve!" if loc.mvarId != goal.mvarId then return .text "rw??: the selected expression should be in the main goal." goal.ctx.val.runMetaM {} do let md ← goal.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do let rootExpr ← loc.rootExpr let some (subExpr, occ) ← withReducible <| viewKAbstractSubExpr rootExpr loc.pos | return .text "rw??: expressions with bound variables are not yet supported" unless ← kabstractIsTypeCorrect rootExpr subExpr loc.pos do return .text <| "rw??: the selected expression cannot be rewritten, \ because the motive is not type correct. \ This usually occurs when trying to rewrite a term that appears as a dependent argument." let location ← loc.fvarId?.mapM FVarId.getUserName let unfoldsHtml ← InteractiveUnfold.renderUnfolds subExpr occ location props.replaceRange doc let (filtered, all) ← getRewriteInterfaces subExpr occ location loc.fvarId? props.replaceRange let filtered ← renderRewrites subExpr filtered unfoldsHtml props.replaceRange doc false let all ← renderRewrites subExpr all unfoldsHtml props.replaceRange doc true return <FilterDetails summary={.text "Rewrite suggestions:"} all={all} filtered={filtered} initiallyFiltered={true} />
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
rpc
null
@[widget_module] LibraryRewriteComponent : Component SelectInsertParams := mk_rpc_widget% LibraryRewrite.rpc
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
LibraryRewriteComponent
The component called by the `rw??` tactic
Rewrite.toMessageData (rw : Rewrite) (name : Name) : MetaM MessageData := do let extraGoals ← rw.extraGoals.filterMapM fun (mvarId, bi) => do if bi.isExplicit then return some m! "⊢ {← mvarId.getType}" return none let list := [m! "{rw.replacement}"] ++ extraGoals.toList ++ [m! "{name}"] return .group <| .nest 2 <| "· " ++ .joinSep list "\n"
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
Rewrite.toMessageData
`rw??` is an interactive tactic that suggests rewrites for any expression selected by the user. To use it, shift-click an expression in the goal or a hypothesis that you want to rewrite. Clicking on one of the rewrite suggestions will paste the relevant rewrite tactic into the editor. The rewrite suggestions are grouped and sorted by the pattern that the rewrite lemmas match with. Rewrites that don't change the goal and rewrites that create the same goal as another rewrite are filtered out, as well as rewrites that have new metavariables in the replacement expression. To see all suggestions, click on the filter button (▼) in the top right. -/ elab stx:"rw??" : tactic => do let some range := (← getFileMap).rangeOfStx? stx | return Widget.savePanelWidgetInfo (hash LibraryRewriteComponent.javascript) (pure <| json% { replaceRange : $range }) stx /-- Represent a `Rewrite` as `MessageData`.
SectionToMessageData (sec : Array (Rewrite × Name) × Bool) : MetaM (Option MessageData) := do let rewrites ← sec.1.toList.mapM fun (rw, name) => rw.toMessageData name let rewrites : MessageData := .group (.joinSep rewrites "\n") let some (rw, name) := sec.1[0]? | return none let head ← pattern (← getConstInfo name).type rw.symm (addMessageContext m! "{·}") return some <| "Pattern " ++ head ++ "\n" ++ rewrites
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
SectionToMessageData
Represent a section of rewrites as `MessageData`.
@[command_elab rw??Command] elabrw??Command : Command.CommandElab := fun stx => withoutModifyingEnv <| Command.runTermElabM fun _ => do let e ← Term.elabTerm stx[2] none Term.synthesizeSyntheticMVarsNoPostponing let e ← Term.levelMVarToParam (← instantiateMVars e) let filter := stx[1].isNone let mut rewrites := #[] for rws in ← getModuleRewrites e do let rws ← if filter then filterRewrites e rws (·.1.replacement) (·.1.makesNewMVars) else pure rws rewrites := rewrites.push (rws, true) for rws in ← getImportRewrites e do let rws ← if filter then filterRewrites e rws (·.1.replacement) (·.1.makesNewMVars) else pure rws rewrites := rewrites.push (rws, false) let sections ← liftMetaM <| rewrites.filterMapM SectionToMessageData if sections.isEmpty then logInfo m! "No rewrites found for {e}" else logInfo (.joinSep sections.toList "\n\n")
def
Tactic
[ "Mathlib.Lean.Meta.RefinedDiscrTree", "Mathlib.Tactic.Widget.InteractiveUnfold", "ProofWidgets.Component.FilterDetails" ]
Mathlib/Tactic/Widget/LibraryRewrite.lean
elabrw
`#rw?? e` gives all possible rewrites of `e`. It is a testing command for the `rw??` tactic -/ syntax (name := rw??Command) "#rw??" (&"all")? term : command open Elab /-- Elaborate a `#rw??` command.
SelectInsertParamsClass (α : Type) where /-- Cursor position in the file at which the widget is being displayed. -/ pos : α → Lsp.Position /-- The current tactic-mode goals. -/ goals : α → Array Widget.InteractiveGoal /-- Locations currently selected in the goal state. -/ selectedLocations : α → Array SubExpr.GoalsLocation /-- The range in the source document where the command will be inserted. -/ replaceRange : α → Lsp.Range
class
Tactic
[ "Mathlib.Init", "Lean.Widget.InteractiveGoal", "Lean.Elab.Deriving.Basic" ]
Mathlib/Tactic/Widget/SelectInsertParamsClass.lean
SelectInsertParamsClass
Structures providing parameters for a Select and insert widget.
private mkSelectInsertParamsInstance (declName : Name) : TermElabM Syntax.Command := `(command|instance : SelectInsertParamsClass (@$(mkCIdent declName)) := ⟨fun prop => prop.pos, fun prop => prop.goals, fun prop => prop.selectedLocations, fun prop => prop.replaceRange⟩)
def
Tactic
[ "Mathlib.Init", "Lean.Widget.InteractiveGoal", "Lean.Elab.Deriving.Basic" ]
Mathlib/Tactic/Widget/SelectInsertParamsClass.lean
mkSelectInsertParamsInstance
null
mkSelectInsertParamsInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if (← declNames.allM isInductive) then for declName in declNames do elabCommand (← liftTermElabM do mkSelectInsertParamsInstance declName) return true else return false initialize registerDerivingHandler ``SelectInsertParamsClass mkSelectInsertParamsInstanceHandler
def
Tactic
[ "Mathlib.Init", "Lean.Widget.InteractiveGoal", "Lean.Elab.Deriving.Basic" ]
Mathlib/Tactic/Widget/SelectInsertParamsClass.lean
mkSelectInsertParamsInstanceHandler
Handler deriving a `SelectInsertParamsClass` instance.
getGoalLocations (locations : Array GoalsLocation) : Array SubExpr.Pos := Id.run do let mut res := #[] for location in locations do if let .target pos := location.loc then res := res.push pos return res
def
Tactic
[ "Lean.Meta.ExprLens", "ProofWidgets.Component.MakeEditLink", "ProofWidgets.Component.OfRpcMethod -- needed in all files using this one.", "Mathlib.Tactic.Widget.SelectInsertParamsClass" ]
Mathlib/Tactic/Widget/SelectPanelUtils.lean
getGoalLocations
Given a `Array GoalsLocation` return the array of `SubExpr.Pos` for all locations in the targets of the relevant goals.
insertMetaVar (e : Expr) (pos : SubExpr.Pos) : MetaM Expr := replaceSubexpr (fun _ ↦ do mkFreshExprMVar none .synthetic) pos e
def
Tactic
[ "Lean.Meta.ExprLens", "ProofWidgets.Component.MakeEditLink", "ProofWidgets.Component.OfRpcMethod -- needed in all files using this one.", "Mathlib.Tactic.Widget.SelectInsertParamsClass" ]
Mathlib/Tactic/Widget/SelectPanelUtils.lean
insertMetaVar
Replace the sub-expression at the given position by a fresh meta-variable.
String.renameMetaVar (s : String) : String := match s.splitOn "?m." with | [] => "" | [s] => s | head::tail => head ++ "?_" ++ "?_".intercalate (tail.map fun s ↦ s.dropWhile Char.isDigit) open ProofWidgets
def
Tactic
[ "Lean.Meta.ExprLens", "ProofWidgets.Component.MakeEditLink", "ProofWidgets.Component.OfRpcMethod -- needed in all files using this one.", "Mathlib.Tactic.Widget.SelectInsertParamsClass" ]
Mathlib/Tactic/Widget/SelectPanelUtils.lean
String.renameMetaVar
Replace all meta-variable names by "?_".
SelectInsertParams where /-- Cursor position in the file at which the widget is being displayed. -/ pos : Lsp.Position /-- The current tactic-mode goals. -/ goals : Array Widget.InteractiveGoal /-- Locations currently selected in the goal state. -/ selectedLocations : Array SubExpr.GoalsLocation /-- The range in the source document where the command will be inserted. -/ replaceRange : Lsp.Range deriving SelectInsertParamsClass, RpcEncodable open scoped Jsx in open SelectInsertParamsClass Lean.SubExpr in
structure
Tactic
[ "Lean.Meta.ExprLens", "ProofWidgets.Component.MakeEditLink", "ProofWidgets.Component.OfRpcMethod -- needed in all files using this one.", "Mathlib.Tactic.Widget.SelectInsertParamsClass" ]
Mathlib/Tactic/Widget/SelectPanelUtils.lean
SelectInsertParams
Structures providing parameters for a Select and insert widget.
mkSelectionPanelRPC {Params : Type} [SelectInsertParamsClass Params] (mkCmdStr : (pos : Array GoalsLocation) → (goalType : Expr) → Params → MetaM (String × String × Option (String.Pos × String.Pos))) (helpMsg : String) (title : String) (onlyGoal := true) (onlyOne := false) : (params : Params) → RequestM (RequestTask Html) := fun params ↦ RequestM.asTask do let doc ← RequestM.readDoc if h : 0 < (goals params).size then let mainGoal := (goals params)[0] let mainGoalName := mainGoal.mvarId.name let all := if onlyOne then "The selected sub-expression" else "All selected sub-expressions" let be_where := if onlyGoal then "in the main goal." else "in the main goal or its context." let errorMsg := s!"{all} should be {be_where}" let inner : Html ← (do if onlyOne && (selectedLocations params).size > 1 then return <span>{.text "You should select only one sub-expression"}</span> for selectedLocation in selectedLocations params do if selectedLocation.mvarId.name != mainGoalName then return <span>{.text errorMsg}</span> else if onlyGoal then if !(selectedLocation.loc matches (.target _)) then return <span>{.text errorMsg}</span> if (selectedLocations params).isEmpty then return <span>{.text helpMsg}</span> mainGoal.ctx.val.runMetaM {} do let md ← mainGoal.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do let (linkText, newCode, range?) ← mkCmdStr (selectedLocations params) md.type.consumeMData params return .ofComponent MakeEditLink (.ofReplaceRange doc.meta (replaceRange params) newCode range?) #[ .text linkText ]) return <details «open»={true}> <summary className="mv2 pointer">{.text title}</summary> <div className="ml1">{inner}</div> </details> else return <span>{.text "There is no goal to solve!"}</span> -- This shouldn't happen.
def
Tactic
[ "Lean.Meta.ExprLens", "ProofWidgets.Component.MakeEditLink", "ProofWidgets.Component.OfRpcMethod -- needed in all files using this one.", "Mathlib.Tactic.Widget.SelectInsertParamsClass" ]
Mathlib/Tactic/Widget/SelectPanelUtils.lean
mkSelectionPanelRPC
Helper function to create a widget allowing to select parts of the main goal and then display a link that will insert some tactic call. The main argument is `mkCmdStr` which is a function creating the link text and the tactic call text. The `helpMsg` argument is displayed when nothing is selected and `title` is used as a panel title. The `onlyGoal` argument says whether the selected has to be in the goal. Otherwise it can be in the local context. The `onlyOne` argument says whether one should select only one sub-expression. In every cases, all selected subexpressions should be in the main goal or its local context. The last arguments `params` should not be provided so that the output has type `Params → RequestM (RequestTask Html)` and can be fed to the `mk_rpc_widget%` elaborator. Note that the `pos` and `goalType` arguments to `mkCmdStr` could be extracted for the `Params` argument but that extraction would happen in every example, hence it is factored out here. We also make sure `mkCmdStr` is executed in the right context.
AtomNode : Type where /-- The vertical position of the node in the string diagram. -/ vPos : ℕ /-- The horizontal position of the node in the string diagram, counting strings in domains. -/ hPosSrc : ℕ /-- The horizontal position of the node in the string diagram, counting strings in codomains. -/ hPosTar : ℕ /-- The underlying expression of the node. -/ atom : Atom
structure
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
AtomNode
Nodes for 2-morphisms in a string diagram.
IdNode : Type where /-- The vertical position of the node in the string diagram. -/ vPos : ℕ /-- The horizontal position of the node in the string diagram, counting strings in domains. -/ hPosSrc : ℕ /-- The horizontal position of the node in the string diagram, counting strings in codomains. -/ hPosTar : ℕ /-- The underlying expression of the node. -/ id : Atom₁
structure
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
IdNode
Nodes for identity 2-morphisms in a string diagram.
Node : Type | atom : AtomNode → Node | id : IdNode → Node
inductive
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Node
Nodes in a string diagram.
Node.e : Node → Expr | Node.atom n => n.atom.e | Node.id n => n.id.e
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Node.e
The underlying expression of a node.
Node.srcList : Node → List (Node × Atom₁) | Node.atom n => n.atom.src.toList.map (fun f ↦ (.atom n, f)) | Node.id n => [(.id n, n.id)]
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Node.srcList
The domain of the 2-morphism associated with a node as a list (the first component is the node itself).
Node.tarList : Node → List (Node × Atom₁) | Node.atom n => n.atom.tgt.toList.map (fun f ↦ (.atom n, f)) | Node.id n => [(.id n, n.id)]
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Node.tarList
The codomain of the 2-morphism associated with a node as a list (the first component is the node itself).
Node.vPos : Node → ℕ | Node.atom n => n.vPos | Node.id n => n.vPos
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Node.vPos
The vertical position of a node in a string diagram.
Node.hPosSrc : Node → ℕ | Node.atom n => n.hPosSrc | Node.id n => n.hPosSrc
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Node.hPosSrc
The horizontal position of a node in a string diagram, counting strings in domains.
Node.hPosTar : Node → ℕ | Node.atom n => n.hPosTar | Node.id n => n.hPosTar
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Node.hPosTar
The horizontal position of a node in a string diagram, counting strings in codomains.
Strand : Type where /-- The horizontal position of the strand in the string diagram. -/ hPos : ℕ /-- The start point of the strand in the string diagram. -/ startPoint : Node /-- The end point of the strand in the string diagram. -/ endPoint : Node /-- The underlying expression of the strand. -/ atom₁ : Atom₁
structure
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Strand
Strings in a string diagram.
Strand.vPos (s : Strand) : ℕ := s.startPoint.vPos
def
Tactic
[ "ProofWidgets.Component.PenroseDiagram", "ProofWidgets.Component.Panel.Basic", "ProofWidgets.Presentation.Expr", "ProofWidgets.Component.HtmlDisplay", "Mathlib.Tactic.CategoryTheory.Bicategory.Normalize", "Mathlib.Tactic.CategoryTheory.Monoidal.Normalize" ]
Mathlib/Tactic/Widget/StringDiagram.lean
Strand.vPos
The vertical position of a strand in a string diagram.