source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/mathlib/Mathlib/Tactic/Linter/Multigoal.lean | import Lean.Elab.Command
-- Import this linter explicitly to ensure that
-- this file has a valid copyright header and module docstring.
import Mathlib.Tactic.Linter.Header
/-!
# The "multiGoal" linter
The "multiGoal" linter emits a warning where there is more than a single goal in scope.
There is an exception: a tactic that closes *all* remaining goals is allowed.
There are a few tactics, such as `skip`, `swap` or the `try` combinator, that are intended to work
specifically in such a situation.
Otherwise, the mathlib style guide ask that goals be focused until there is only one active goal
at a time.
If this focusing does not happen, the linter emits a warning.
Typically, the focusing is achieved by the `cdot`: `·`, but, e.g., `focus` or `on_goal x`
also serve a similar purpose.
TODO:
* Should the linter flag unnecessary scoping as well?
For instance, should
```lean
example : True := by
· · exact .intro
```
raise a warning?
* Custom support for "accumulating side-goals", so that once they are all in scope
they can be solved in bulk via `all_goals` or a similar tactic.
* In development, `on_goal` has been partly used as a way of silencing the linter
precisely to allow the accumulation referred to in the previous item.
Maybe revisit usages of `on_goal` and also nested `induction` and `cases`.
-/
open Lean Elab Linter
namespace Mathlib.Linter
/-- The "multiGoal" linter emits a warning when there are multiple active goals. -/
register_option linter.style.multiGoal : Bool := {
defValue := false
descr := "enable the multiGoal linter"
}
namespace Style.multiGoal
/-- The `SyntaxNodeKind`s in `exclusions` correspond to tactics that the linter allows,
even though there are multiple active goals.
Reasons for admitting a kind in `exclusions` include
* the tactic focuses on one goal, e.g. `·`, `focus`, `on_goal i =>`, ...;
* the tactic is reordering the goals, e.g. `swap`, `rotate_left`, ...;
* the tactic is structuring a proof, e.g. `skip`, `<;>`, ...;
* the tactic is creating new goals, e.g. `constructor`, `cases`, `induction`, ....
There is some overlap in scope between `ignoreBranch` and `exclusions`.
Tactic combinators like `repeat` or `try` are a mix of both.
-/
abbrev exclusions : Std.HashSet SyntaxNodeKind := .ofArray #[
-- structuring a proof
``Lean.Parser.Term.cdot,
``cdot,
``cdotTk,
``Lean.Parser.Tactic.tacticSeqBracketed,
`«;»,
`«<;>»,
``Lean.Parser.Tactic.«tactic_<;>_»,
`«{»,
`«]»,
`null,
`then,
`else,
``Lean.Parser.Tactic.«tacticNext_=>_»,
``Lean.Parser.Tactic.tacticSeq1Indented,
``Lean.Parser.Tactic.tacticSeq,
`focus,
``Lean.Parser.Tactic.focus,
-- re-ordering goals
`Batteries.Tactic.tacticSwap,
``Lean.Parser.Tactic.rotateLeft,
``Lean.Parser.Tactic.rotateRight,
``Lean.Parser.Tactic.skip,
`Batteries.Tactic.«tacticOn_goal-_=>_»,
`Mathlib.Tactic.«tacticSwap_var__,,»,
-- tactic combinators
``Lean.Parser.Tactic.tacticRepeat_,
``Lean.Parser.Tactic.tacticTry_,
-- creating new goals
``Lean.Parser.Tactic.paren,
``Lean.Parser.Tactic.case,
``Lean.Parser.Tactic.constructor,
`Mathlib.Tactic.tacticAssumption',
``Lean.Parser.Tactic.induction,
``Lean.Parser.Tactic.cases,
``Lean.Parser.Tactic.intros,
``Lean.Parser.Tactic.injections,
``Lean.Parser.Tactic.substVars,
`Batteries.Tactic.«tacticPick_goal-_»,
``Lean.Parser.Tactic.case',
`«tactic#adaptation_note_»,
`tacticSleep_heartbeats_
]
/-- The `SyntaxNodeKind`s in `ignoreBranch` correspond to tactics that disable the linter from
their first application until the corresponding proof branch is closed.
Reasons for ignoring these tactics include
* the linter gets confused by the proof management, e.g. `conv`;
* the tactics are *intended* to act on multiple goals, e.g. `repeat`, `any_goals`, `all_goals`, ...
There is some overlap in scope between `exclusions` and `ignoreBranch`.
-/
abbrev ignoreBranch : Std.HashSet SyntaxNodeKind := .ofArray #[
``Lean.Parser.Tactic.Conv.conv,
`Mathlib.Tactic.Conv.convLHS,
`Mathlib.Tactic.Conv.convRHS,
``Lean.Parser.Tactic.first,
``Lean.Parser.Tactic.repeat',
``Lean.Parser.Tactic.tacticIterate____,
``Lean.Parser.Tactic.anyGoals,
``Lean.Parser.Tactic.allGoals,
``Lean.Parser.Tactic.failIfSuccess,
`Mathlib.Tactic.successIfFailWithMsg
]
/-- `getManyGoals t` returns the syntax nodes of the `InfoTree` `t` corresponding to tactic calls
which
* leave at least one goal that was present before it ran
(with the exception of tactics that leave the sole goal unchanged);
* are not excluded through `exclusions` or `ignoreBranch`;
together with the number of goals before the tactic,
the number of goals after the tactic, and the number of unaffected goals.
-/
partial
def getManyGoals : InfoTree → Array (Syntax × Nat × Nat × Nat)
| .node info args =>
let kargs := (args.map getManyGoals).toArray.flatten
if let .ofTacticInfo info := info then
if ignoreBranch.contains info.stx.getKind then #[]
-- Ideal case: one goal, and it might or might not be closed.
else if info.goalsBefore.length == 1 && info.goalsAfter.length ≤ 1 then kargs
else if let .original .. := info.stx.getHeadInfo then
let backgroundGoals := info.goalsAfter.filter (info.goalsBefore.contains ·)
if backgroundGoals.length != 0 && !exclusions.contains info.stx.getKind then
kargs.push (info.stx,
info.goalsBefore.length, info.goalsAfter.length, backgroundGoals.length)
else kargs
else kargs
else kargs
| .context _ t => getManyGoals t
| _ => default
@[inherit_doc Mathlib.Linter.linter.style.multiGoal]
def multiGoalLinter : Linter where run := withSetOptionIn fun _stx ↦ do
unless getLinterValue linter.style.multiGoal (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
let trees ← getInfoTrees
for t in trees do
for (s, before, after, n) in getManyGoals t do
let goals (k : Nat) := if k == 1 then f!"1 goal" else f!"{k} goals"
let fmt ← Command.liftCoreM
try PrettyPrinter.ppTactic ⟨s⟩ catch _ => pure f!"(failed to pretty print)"
Linter.logLint linter.style.multiGoal s m!"\
The following tactic starts with {goals before} and ends with {goals after}, \
{n} of which {if n == 1 then "is" else "are"} not operated on.\
{indentD fmt}\n\
Please focus on the current goal, for instance using `·` (typed as \"\\.\")."
initialize addLinter multiGoalLinter
end Style.multiGoal
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/FindDeprecations.lean | import Mathlib.Init -- `import ImportGraph.Imports` is enough
/-!
# The `#clear_deprecations` command
This file defines the `#clear_deprecations date₁ date₂ really` command.
This function is intended for automated use by the `remove_deprecations` automation.
It removes declarations that have been deprecated in the time range starting from `date₁` and
ending with `date₂`.
See the doc-string for the command for more information.
-/
open Lean Elab Command
namespace Mathlib.Tactic
/-- A convenience instance to print a `String.Range` as the corresponding pair of `String.Pos`. -/
local instance : ToString String.Range where
toString | ⟨s, e⟩ => s!"({s}, {e})"
/--
These are the names of the directories containing all the files that should be inspected.
For reporting, the script assumes there is no sub-dir of the `repo` dir that contains
`repo` as a substring.
However, the script should still remove old deprecations correctly even if that happens.
-/
def repos : NameSet := .ofArray #[`Mathlib, `Archive, `Counterexamples]
/--
The main structure containing the information a deprecated declaration.
* `module` is the name of the module containing the deprecated declaration;
* `decl` is the name of the deprecated declaration;
* `rgStart` is the `Position` where the deprecated declaration starts;
* `rgStop` is the `Position` where the deprecated declaration ends;
* `since` is the date when the declaration was deprecated.
-/
structure DeprecationInfo where
/-- `module` is the name of the module containing the deprecated declaration. -/
module : Name
/-- `decl` is the name of the deprecated declaration. -/
decl : Name
/-- `rgStart` is the `Position` where the deprecated declaration starts. -/
rgStart : Position
/-- `rgStop` is the `Position` where the deprecated declaration ends. -/
rgStop : Position
/-- `since` is the date when the declaration was deprecated. -/
since : String
/--
`getPosAfterImports fname` parses the imports of `fname` and returns the position just after them.
This position is after all trailing whitespace and comments that may follow the imports of `fname`.
-/
def getPosAfterImports (fname : String) : CommandElabM String.Pos.Raw := do
let file ← IO.FS.readFile fname
let fm := file.toFileMap
let (_, fileStartPos, _) ← parseImports fm.source (← getFileName)
return fm.ofPosition fileStartPos
/--
`addAfterImports fname s` returns the content of the file `fname`, with the string `s` added
after the imports of `fname`.
-/
def addAfterImports (fname s : String) : CommandElabM String := do
let pos ← getPosAfterImports fname
let file ← IO.FS.readFile fname
let fileSubstring := file.toSubstring
return {fileSubstring with stopPos := pos}.toString ++ s ++
{fileSubstring with startPos := pos}.toString
/--
If `nm` is the name of a declaration, then `getDeprecatedInfo nm` returns the
`DeprecationInfo` data for `nm`.
Otherwise, it returns `none`.
If the `verbose?` input is `true`, then the command also summarizes what the data is.
-/
def getDeprecatedInfo (nm : Name) (verbose? : Bool) :
CommandElabM (Option DeprecationInfo) := do
let env ← getEnv
-- if there is a `since` in the deprecation
if let some {since? := some since, ..} := Linter.deprecatedAttr.getParam? env nm
then
-- retrieve the `range` for the declaration
if let some {range := rg, ..} ← findDeclarationRanges? nm
then
-- retrieve the module where the declaration is located
if let some mod ← findModuleOf? nm
then
-- We filter here based on the top dir of the declaration.
unless repos.contains mod.getRoot do
return none
if verbose? then
logInfo
s!"In the module '{mod}', the declaration {nm} at {rg.pos}--{rg.endPos} \
is deprecated since {since}"
return some { module := mod
decl := nm
rgStart := rg.pos
rgStop := rg.endPos
since := since }
return none
/--
The output is the `HashMap` whose keys are the names of the files containing
deprecated declarations, and whose values are the arrays of ranges
corresponding to the deprecated declarations in that file.
The input `oldDate` and `newDate` are strings of the form "YYYY-MM-DD".
The output contains all the declarations that were deprecated after `oldDate`
and before `newDate`.
-/
def deprecatedHashMap (oldDate newDate : String) :
CommandElabM (Std.HashMap (Name × String) (Array (Name × String.Range))) := do
let mut fin := ∅
--let searchPath ← getSrcSearchPath
for (nm, _) in (← getEnv).constants.map₁ do
if let some ⟨modName, decl, rgStart, rgStop, since⟩ ← getDeprecatedInfo nm false
then
unless repos.contains modName.getRoot do continue
if !(oldDate ≤ since && since ≤ newDate) then
continue
-- Ideally, `lean` would be computed by `← findLean (← getSrcSearchPath) modName`
-- However, while this works locally, CI throws the error ` unknown module prefix 'Mathlib'`
let lean := (modName.components.foldl (init := "")
fun a b => (a.push System.FilePath.pathSeparator) ++ b.toString) ++ ".lean" |>.drop 1
--let lean ← findLean searchPath modName
let file ← IO.FS.readFile lean
let fm := FileMap.ofString file
let rg : String.Range := ⟨fm.ofPosition rgStart, fm.ofPosition rgStop⟩
fin := fin.alter (modName, lean) fun a =>
(a.getD #[]).binInsert (·.2.1 < ·.2.1) (decl, rg)
return fin
/--
`removeRanges file rgs` removes from the string `file` the substrings whose ranges are in the array
`rgs`.
*Notes*.
* The command makes the assumption that `rgs` is *sorted*.
* The command removes all consecutive whitespace following the end of each range.
-/
def removeRanges (file : String) (rgs : Array String.Range) : String := Id.run do
let mut curr : String.Pos.Raw := 0
let mut fileSubstring := file.toSubstring
let mut tot := ""
let last := fileSubstring.stopPos
for next in rgs.push ⟨last, last⟩ do
if next.start < curr then continue
let part := {fileSubstring with stopPos := next.start}.toString
tot := tot ++ part
curr := next.start
fileSubstring := {fileSubstring with startPos := next.stop}.trimLeft
return tot
/--
`removeDeprecations fname rgs` reads the content of `fname` and removes from it the substrings
whose ranges are in the array `rgs`.
The command makes the assumption that `rgs` is *sorted*.
-/
def removeDeprecations (fname : String) (rgs : Array String.Range) : IO String :=
return removeRanges (← IO.FS.readFile fname) rgs
/--
`parseLine line` assumes that the input string is of the form
```
info: File/Path.lean:12:0: [362, 398, 399]
```
and extracts `[362, 398, 399]`.
It makes the assumption that there is a unique `: [` substring and then retrieves the numbers.
Note that this is the output of `Mathlib.Linter.CommandRanges.commandRangesLinter`
that the script here is parsing.
-/
def parseLine (line : String) : Option (List String.Pos.Raw) :=
match (line.dropRight 1).splitOn ": [" with
| [_, rest] =>
let nums := rest.splitOn ", "
if nums == [""] then some [] else
some <| nums.map fun s => ⟨s.toNat?.getD 0⟩
| _ => none
/--
Takes as input a file path `fname` and an array of pairs `(declName, range of declaration)`.
The `declName` is mostly for printing information, but is not used essentially by the function.
It returns the pair `(temp file name, file without the commands that generated the declarations)`.
In the course of doing so, the function creates a temporary file from `fname`, by
* adding the import `Mathlib.Tactic.Linter.CommandRanges` and
* setting the `linter.commandRanges` option to `true`.
It parses the temporary file, capturing the output and uses the command ranges to remove the
ranges of the *commands* that generated the passed declaration ranges.
-/
def rewriteOneFile (fname : String) (rgs : Array (Name × String.Range)) :
CommandElabM (String × String) := do
-- `option` is the extra text that we add to the files that contain deprecations.
-- We save these modified files with a different name then their originals, so that all their
-- dependencies still have valid `olean`s and we build them to collect the ranges of the commands
-- in each one of them.
let option :=
s!"\nimport Mathlib.Tactic.Linter.CommandRanges\n\
set_option linter.commandRanges true\n"
-- `offset` represents the difference between a position in the modified file and the
-- corresponding position in the original file.
-- Since we added the modification right after the imports, the command positions of the old file
-- are always smaller than the command positions of the new file.
let offset := option.toSubstring.stopPos
let fileWithOptionAdded ← addAfterImports fname option
let fname_with_option := fname.dropRight ".lean".length ++ "_with_option.lean"
let file ← IO.FS.readFile fname
let fm := file.toFileMap
let rgsPos := rgs.map fun (decl, ⟨s, e⟩) =>
m!"* {.ofConstName decl} {(fm.toPosition s, fm.toPosition e)}"
let rgsStringPos := rgs.map (m!"{·.2}")
let combinedRanges := rgsPos.zipWith (· ++ m!" " ++ ·) rgsStringPos |>.toList
logInfo m!"Adding '{option}' to '{fname}'\nWriting to {indentD fname_with_option}\n\
Removing the following declarations\n{m!"\n".joinSep combinedRanges}"
IO.FS.writeFile fname_with_option fileWithOptionAdded
let ranges := rgs.map (·.2)
logInfo m!"Retrieving command positions from '{fname_with_option}'"
let commandPositions ←
IO.Process.output {cmd := "lake", args := #["build", fname_with_option]}
-- `stringPositions` consists of lists of the form `[p₁, p₂, p₃]`, where
-- * `p₁` is the start of a command;
-- * `p₂` is the end of the command, excluding trailing whitespace and comments;
-- * `p₁` is the end of the command, including trailing whitespace and comments.
let stringPositions := (commandPositions.stdout.splitOn "\n").map parseLine |>.reduceOption
let mut removals : Std.HashSet (List String.Pos.Raw) := ∅
-- For each range `rg` in `ranges`, we isolate the unique entry of `stringPositions` that
-- entirely contains `rg`. This helps catching the full range of `open Nat in @[deprecated] ...`,
-- rather than just the `@[deprecated] ...` range.
let : Sub String.Pos.Raw := ⟨fun | ⟨a⟩, ⟨b⟩ => ⟨a - b⟩⟩
for rg in ranges do
let candidate := stringPositions.filterMap (fun arr ↦
let a := arr.head! - offset
let b := arr[arr.length - 1]! - offset
if a ≤ rg.start ∧ rg.stop ≤ b then some (arr.map (· - offset)) else none)
match candidate with
| [d@([_, _, _])] => removals := removals.insert d
| _ => logInfo "Something went wrong!"
-- We only remember the `start` and `end` of each command, ignoring trailing whitespace and
-- comments. This means that we may err on the side of preserving comments that may have to be
-- manually removed, instead of having to manually add them back later on.
let rems : Std.HashSet _ := removals.fold (init := ∅) fun tot ↦ fun
| [a, b, _c] => tot.insert (⟨a, b⟩ : String.Range)
| _ => tot
return (fname_with_option, ← removeDeprecations fname (rems.toArray.qsort (·.1 < ·.1)))
/-- The `<` partial order on modules: `importLT env mod₁ mod₂` means that `mod₂` imports `mod₁`. -/
def importLT (env : Environment) (f1 f2 : Name) : Bool :=
(env.findRedundantImports #[f1, f2]).contains f1
/--
`#clear_deprecations "YYYY₁-MM₁-DD₁" "YYYY₂-MM₂-DD₂" really` computes the declarations that have
the `@[deprecated]` attribute and the `since` field satisfies
`YYYY₁-MM₁-DD₁ ≤ since ≤ YYYY₂-MM₂-DD₂`.
For each one of them, it retrieves the command that generated it and removes it.
It also verbosely logs various steps of the computation.
Running `#clear_deprecations "YYYY₁-MM₁-DD₁" "YYYY₂-MM₂-DD₂"`, without the trailing `really` skips
the removal, but still emits the same verbose output.
This function is intended for automated use by the `remove_deprecations` automation.
-/
elab "#clear_deprecations " oldDate:str ppSpace newDate:str really?:(&" really")? : command => do
let oldDate := oldDate.getString
let newDate := newDate.getString
let fmap ← deprecatedHashMap oldDate newDate
let mut filesToRemove := #[]
let env ← getEnv
let sortedFMap := fmap.toArray.qsort fun ((a, _), _) ((b, _), _) => importLT env b a
if sortedFMap.isEmpty then
logInfo m!"No deprecations in the range from {oldDate} to {newDate}"
return
for ((modName, fname), noDeprs) in sortedFMap do
let (toRemove, fileWithoutDeprecations) ← rewriteOneFile fname noDeprs
let message :=
m!"Click to see the file with the deprecations in the date range \
{oldDate} to {newDate} removed"
let collapsibleMessage := .trace {cls := modName} message #[fileWithoutDeprecations]
logInfo collapsibleMessage
if really?.isSome then
IO.FS.writeFile fname fileWithoutDeprecations
filesToRemove := filesToRemove.push toRemove
logInfo
m!"Removing the temporary files\n* {m!"\n* ".joinSep (filesToRemove.map (m!"{·}")).toList}"
for tmp in filesToRemove do
IO.FS.removeFile tmp
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/Linter/UpstreamableDecl.lean | import ImportGraph.Meta
import Mathlib.Init
/-! # The `upstreamableDecl` linter
The `upstreamableDecl` linter detects declarations that could be moved to a file higher up in the
import hierarchy. This is intended to assist with splitting files.
-/
open Lean Elab Command Linter
/-- Does this declaration come from the current file? -/
def Lean.Name.isLocal (env : Environment) (decl : Name) : Bool :=
(env.getModuleIdxFor? decl).isNone
open Mathlib.Command.MinImports
/-- Does the declaration with this name depend on definitions in the current file?
Here, "definition" means everything that is not a theorem, and so includes `def`,
`structure`, `inductive`, etc.
-/
def Lean.Environment.localDefinitionDependencies (env : Environment) (stx id : Syntax) :
CommandElabM Bool := do
let declName ← getDeclName stx
let immediateDeps ← getAllDependencies stx id
-- Drop all the unresolvable constants, otherwise `transitivelyUsedConstants` fails.
let immediateDeps : NameSet := immediateDeps.foldl (init := ∅) fun s n =>
if (env.find? n).isSome then s.insert n else s
let deps ← liftCoreM <| immediateDeps.transitivelyUsedConstants
let constInfos := deps.toList.filterMap env.find?
-- We allow depending on theorems and constructors.
-- We explicitly allow constructors since `inductive` declarations are reported to depend on their
-- own constructors, and we want inductives to behave the same as definitions, so place one
-- warning on the inductive itself but nothing on its downstream uses.
-- (There does not seem to be an easy way to determine, given `Syntax` and `ConstInfo`,
-- whether the `ConstInfo` is a constructor declared in this piece of `Syntax`.)
let defs := constInfos.filter (fun constInfo => !(constInfo matches .thmInfo _ | .ctorInfo _))
return defs.any fun constInfo => declName != constInfo.name && constInfo.name.isLocal env
namespace Mathlib.Linter
/--
The `upstreamableDecl` linter detects declarations that could be moved to a file higher up in the
import hierarchy. If this is the case, it emits a warning.
By default, this linter will not fire on definitions, nor private declarations:
see options `linter.upstreamableDecl.defs` and `linter.upstreamableDecl.private`.
This is intended to assist with splitting files.
-/
register_option linter.upstreamableDecl : Bool := {
defValue := false
descr := "enable the upstreamableDecl linter"
}
/--
If set to `true`, the `upstreamableDecl` linter will add warnings on definitions.
The linter does not place a warning on any declaration depending on a definition in the current file
(while it does place a warning on the definition itself), since we often create a new file for a
definition on purpose.
-/
register_option linter.upstreamableDecl.defs : Bool := {
defValue := false
descr := "upstreamableDecl warns on definitions"
}
/--
If set to `true`, the `upstreamableDecl` linter will add warnings on private declarations.
-/
register_option linter.upstreamableDecl.private : Bool := {
defValue := false
descr := "upstreamableDecl warns on private declarations"
}
namespace DoubleImports
@[inherit_doc Mathlib.Linter.linter.upstreamableDecl]
def upstreamableDeclLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.upstreamableDecl (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
let skipDef := !getLinterValue linter.upstreamableDecl.defs (← getLinterOptions)
let skipPrivate := !getLinterValue linter.upstreamableDecl.private (← getLinterOptions)
if stx == (← `(command| set_option $(mkIdent `linter.upstreamableDecl) true)) then return
let env ← getEnv
let id ← getId stx
if id != .missing then
-- Skip defs and private decls by default.
let name ← getDeclName stx
if (skipDef && if let some constInfo := env.find? name
then !(constInfo matches .thmInfo _ | .ctorInfo _)
else true) ||
(skipPrivate && isPrivateName name) then
return
let minImports := getIrredundantImports env (← getAllImports stx id)
match minImports.size, minImports.min? with
| 1, some upstream => do
if !(← env.localDefinitionDependencies stx id) then
let p : GoToModuleLinkProps := { modName := upstream }
let widget : MessageData := .ofWidget
(← liftCoreM <| Widget.WidgetInstance.ofHash
GoToModuleLink.javascriptHash <|
Server.RpcEncodable.rpcEncode p)
(toString upstream)
Linter.logLint linter.upstreamableDecl id
m!"Consider moving this declaration to the module {widget}."
| _, _ => pure ()
initialize addLinter upstreamableDeclLinter
end DoubleImports
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/DocPrime.lean | import Lean.Elab.Command
-- Import this linter explicitly to ensure that
-- this file has a valid copyright header and module docstring.
import Mathlib.Tactic.Linter.Header
/-!
# The "docPrime" linter
The "docPrime" linter emits a warning on declarations that have no doc-string and whose
name ends with a `'`. Such declarations are expected to have a documented explanation
for the presence of a `'` in their name. This may consist of discussion of the difference relative
to an unprimed version of that declaration, or an explanation as to why no better naming scheme
is possible.
-/
open Lean Elab Linter
namespace Mathlib.Linter
/--
The "docPrime" linter emits a warning on declarations that have no doc-string and whose
name ends with a `'`.
The file `scripts/nolints_prime_decls.txt` contains a list of temporary exceptions to this linter.
This list should not be appended to, and become emptied over time.
-/
register_option linter.docPrime : Bool := {
defValue := false
descr := "enable the docPrime linter"
}
namespace DocPrime
@[inherit_doc Mathlib.Linter.linter.docPrime]
def docPrimeLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.docPrime (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
unless [``Lean.Parser.Command.declaration, `lemma].contains stx.getKind do return
-- ignore private declarations
if (stx.find? (·.isOfKind ``Lean.Parser.Command.private)).isSome then return
-- ignore examples
if (stx.find? (·.isOfKind ``Lean.Parser.Command.example)).isSome then return
let docstring := stx[0][0]
-- The current declaration's id, possibly followed by a list of universe names.
let declId :=
if stx[1].isOfKind ``Lean.Parser.Command.instance then
stx[1][3][0]
else
stx[1][1]
if let .missing := declId then return
-- The name of the current declaration, with namespaces resolved.
let declName : Name :=
if let `_root_ :: rest := declId[0].getId.components then
rest.foldl (· ++ ·) default
else (← getCurrNamespace) ++ declId[0].getId
let msg := m!"`{declName}` is missing a doc-string, please add one.\n\
Declarations whose name ends with a `'` are expected to contain an explanation for the \
presence of a `'` in their doc-string. This may consist of discussion of the difference \
relative to the unprimed version, or an explanation as to why no better naming scheme \
is possible."
if docstring[0][1].getAtomVal.isEmpty && declName.toString.back == '\'' then
if ← System.FilePath.pathExists "scripts/nolints_prime_decls.txt" then
if (← IO.FS.lines "scripts/nolints_prime_decls.txt").contains declName.toString then
return
else
Linter.logLint linter.docPrime declId msg
else
Linter.logLint linter.docPrime declId msg
initialize addLinter docPrimeLinter
end DocPrime
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/TextBased.lean | import Batteries.Data.String.Matcher
import Mathlib.Data.Nat.Notation
import Lake.Util.Casing
-- Don't warn about the lake import: the above file has almost no imports, and this PR has been
-- benchmarked.
set_option linter.style.header false
/-!
## Text-based linters
This file defines various mathlib linters which are based on reading the source code only.
In practice, all such linters check for code style issues.
Currently, this file contains linters checking
- if the string "adaptation note" is used instead of the command #adaptation_note,
- for lines with windows line endings,
- for lines containing trailing whitespace,
- for module names to be in upper camel case,
- for module names to be valid Windows filenames, and containing no forbidden characters such as
`!`, `.` or spaces.
For historic reasons, some further such checks are written in a Python script `lint-style.py`:
these are gradually being rewritten in Lean.
This linter has a file for style exceptions (to avoid false positives in the implementation),
or for downstream projects to allow a gradual adoption of this linter.
An executable running all these linters is defined in `scripts/lint-style.lean`.
-/
open Lean.Linter System
namespace Mathlib.Linter.TextBased
/-- Different kinds of "broad imports" that are linted against. -/
inductive BroadImports
/-- Importing the entire "Mathlib.Tactic" folder -/
| TacticFolder
/-- Importing any module in `Lake`, unless carefully measured
This has caused unexpected regressions in the past. -/
| Lake
deriving BEq
/-- Possible errors that text-based linters can report. -/
-- We collect these in one inductive type to centralise error reporting.
inductive StyleError where
/-- The bare string "Adaptation note" (or variants thereof):
instead, the #adaptation_note command should be used. -/
| adaptationNote
/-- A line ends with windows line endings (\r\n) instead of unix ones (\n). -/
| windowsLineEnding
/-- A line contains trailing whitespace. -/
| trailingWhitespace
/-- A line contains a space before a semicolon -/
| semicolon
deriving BEq
/-- How to format style errors -/
inductive ErrorFormat
/-- Produce style error output aimed at humans: no error code, clickable file name -/
| humanReadable : ErrorFormat
/-- Produce an entry in the style-exceptions file: mention the error code, slightly uglier
than human-readable output -/
| exceptionsFile : ErrorFormat
/-- Produce output suitable for Github error annotations: in particular,
duplicate the file path, line number and error code -/
| github : ErrorFormat
deriving BEq
/-- Create the underlying error message for a given `StyleError`. -/
def StyleError.errorMessage (err : StyleError) : String := match err with
| StyleError.adaptationNote =>
"Found the string \"Adaptation note:\", please use the #adaptation_note command instead"
| windowsLineEnding => "This line ends with a windows line ending (\r\n): please use Unix line\
endings (\n) instead"
| trailingWhitespace => "This line ends with some whitespace: please remove this"
| semicolon => "This line contains a space before a semicolon"
/-- The error code for a given style error. Keep this in sync with `parse?_errorContext` below! -/
-- FUTURE: we're matching the old codes in `lint-style.py` for compatibility;
-- in principle, we could also print something more readable.
def StyleError.errorCode (err : StyleError) : String := match err with
| StyleError.adaptationNote => "ERR_ADN"
| StyleError.windowsLineEnding => "ERR_WIN"
| StyleError.trailingWhitespace => "ERR_TWS"
| StyleError.semicolon => "ERR_SEM"
/-- Context for a style error: the actual error, the line number in the file we're reading
and the path to the file. -/
structure ErrorContext where
/-- The underlying `StyleError` -/
error : StyleError
/-- The line number of the error (1-based) -/
lineNumber : ℕ
/-- The path to the file which was linted -/
path : FilePath
/-- Possible results of comparing an `ErrorContext` to an `existing` entry:
most often, they are different --- if the existing entry covers the new exception,
depending on the error, we prefer the new or the existing entry. -/
inductive ComparisonResult
/-- The contexts describe different errors: two separate style exceptions are required
to cover both. -/
| Different
/-- The existing exception also covers the new error:
we keep the existing exception. -/
| Comparable
deriving BEq
/-- Determine whether a `new` `ErrorContext` is covered by an `existing` exception,
and, if it is, if we prefer replacing the new exception or keeping the previous one. -/
def compare (existing new : ErrorContext) : ComparisonResult :=
-- Two comparable error contexts must have the same path.
-- To avoid issues with different path separators across different operating systems,
-- we compare the set of path components instead.
if existing.path.components != new.path.components then ComparisonResult.Different
-- We entirely ignore their line numbers: not sure if this is best.
-- NB: keep the following in sync with `parse?_errorContext` below.
-- Generally, comparable errors must have equal `StyleError`s.
else
if existing.error == new.error then ComparisonResult.Comparable else ComparisonResult.Different
/-- Find the first style exception in `exceptions` (if any) which covers a style exception `e`. -/
def ErrorContext.find?_comparable (e : ErrorContext) (exceptions : Array ErrorContext) :
Option ErrorContext :=
(exceptions).find? (fun new ↦ compare e new == ComparisonResult.Comparable)
/-- Output the formatted error message, containing its context.
`style` specifies if the error should be formatted for humans to read, github problem matchers
to consume, or for the style exceptions file. -/
def outputMessage (errctx : ErrorContext) (style : ErrorFormat) : String :=
let errorMessage := errctx.error.errorMessage
match style with
| ErrorFormat.github =>
-- We are outputting for github: duplicate file path, line number and error code,
-- so that they are also visible in the plain text output.
let path := errctx.path
let nr := errctx.lineNumber
let code := errctx.error.errorCode
s!"::ERR file={path},line={nr},code={code}::{path}:{nr} {code}: {errorMessage}"
| ErrorFormat.exceptionsFile =>
-- Produce an entry in the exceptions file: with error code and "line" in front of the number.
s!"{errctx.path} : line {errctx.lineNumber} : {errctx.error.errorCode} : {errorMessage}"
| ErrorFormat.humanReadable =>
-- Print for humans: clickable file name and omit the error code
s!"error: {errctx.path}:{errctx.lineNumber}: {errorMessage}"
/-- Try parsing an `ErrorContext` from a string: return `some` if successful, `none` otherwise. -/
def parse?_errorContext (line : String) : Option ErrorContext := Id.run do
let parts := line.splitToList (· == ' ')
match parts with
| filename :: ":" :: "line" :: lineNumber :: ":" :: errorCode :: ":" :: _errorMessage =>
-- Turn the filename into a path. In general, this is ambiguous if we don't know if we're
-- dealing with e.g. Windows or POSIX paths. In our setting, this is fine, since no path
-- component contains any path separator.
let path := mkFilePath (filename.splitToList (FilePath.pathSeparators.contains ·))
-- Parse the error kind from the error code, ugh.
-- NB: keep this in sync with `StyleError.errorCode` above!
let err : Option StyleError := match errorCode with
-- Use default values for parameters which are ignored for comparing style exceptions.
-- NB: keep this in sync with `compare` above!
| "ERR_ADN" => some (StyleError.adaptationNote)
| "ERR_SEM" => some (StyleError.semicolon)
| "ERR_TWS" => some (StyleError.trailingWhitespace)
| "ERR_WIN" => some (StyleError.windowsLineEnding)
| _ => none
match String.toNat? lineNumber with
| some n => err.map fun e ↦ (ErrorContext.mk e n path)
| _ => none
-- It would be nice to print an error on any line which doesn't match the above format,
-- but is awkward to do so (this `def` is not in any IO monad). Hopefully, this is not necessary
-- anyway as the style exceptions file is mostly automatically generated.
| _ => none
/-- Parse all style exceptions for a line of input.
Return an array of all exceptions which could be parsed: invalid input is ignored. -/
def parseStyleExceptions (lines : Array String) : Array ErrorContext := Id.run do
-- We treat all lines starting with "--" as a comment and ignore them.
Array.filterMap (parse?_errorContext ·) (lines.filter (fun line ↦ !line.startsWith "--"))
/-- Print information about all errors encountered to standard output.
`style` specifies if the error should be formatted for humans to read, github problem matchers
to consume, or for the style exceptions file. -/
def formatErrors (errors : Array ErrorContext) (style : ErrorFormat) : IO Unit := do
for e in errors do
IO.println (outputMessage e style)
/-- Core logic of a text based linter: given a collection of lines,
return an array of all style errors with line numbers. If possible,
also return the collection of all lines, changed as needed to fix the linter errors.
(Such automatic fixes are only possible for some kinds of `StyleError`s.)
-/
abbrev TextbasedLinter := LinterOptions → Array String →
Array (StyleError × ℕ) × (Option (Array String))
/-! Definitions of the actual text-based linters. -/
section
/-- Lint on any occurrences of the string "Adaptation note:" or variants thereof. -/
register_option linter.adaptationNote : Bool := { defValue := true }
@[inherit_doc linter.adaptationNote]
def adaptationNoteLinter : TextbasedLinter := fun opts lines ↦ Id.run do
unless getLinterValue linter.adaptationNote opts do return (#[], none)
let mut errors := Array.mkEmpty 0
for h : idx in [:lines.size] do
-- We make this shorter to catch "Adaptation note", "adaptation note" and a missing colon.
if lines[idx].containsSubstr "daptation note" then
errors := errors.push (StyleError.adaptationNote, idx + 1)
return (errors, none)
/-- Lint a collection of input strings if one of them contains trailing whitespace. -/
register_option linter.trailingWhitespace : Bool := { defValue := true }
@[inherit_doc linter.trailingWhitespace]
def trailingWhitespaceLinter : TextbasedLinter := fun opts lines ↦ Id.run do
unless getLinterValue linter.trailingWhitespace opts do return (#[], none)
let mut errors := Array.mkEmpty 0
let mut fixedLines : Vector String lines.size := lines.toVector
for h : idx in [:lines.size] do
let line := lines[idx]
if line.back == ' ' then
errors := errors.push (StyleError.trailingWhitespace, idx + 1)
fixedLines := fixedLines.set idx line.trimRight
return (errors, if errors.size > 0 then some fixedLines.toArray else none)
/-- Lint a collection of input strings for a semicolon preceded by a space. -/
register_option linter.whitespaceBeforeSemicolon : Bool := { defValue := true }
@[inherit_doc linter.whitespaceBeforeSemicolon]
def semicolonLinter : TextbasedLinter := fun opts lines ↦ Id.run do
unless getLinterValue linter.whitespaceBeforeSemicolon opts do return (#[], none)
let mut errors := Array.mkEmpty 0
let mut fixedLines := lines
for h : idx in [:lines.size] do
let line := lines[idx]
let pos := line.find (· == ';')
-- Future: also lint for a semicolon *not* followed by a space or ⟩.
if pos != line.endPos && (pos.prev line).get line == ' ' then
errors := errors.push (StyleError.semicolon, idx + 1)
-- We spell the bad string pattern this way to avoid the linter firing on itself.
fixedLines := fixedLines.set! idx (line.replace [' ', ';'].asString ";")
return (errors, if errors.size > 0 then some fixedLines else none)
/-- Whether a collection of lines consists *only* of imports, blank lines and single-line comments.
In practice, this means it's an imports-only file and exempt from almost all linting. -/
def isImportsOnlyFile (lines : Array String) : Bool :=
-- The Python version also excluded multi-line comments: for all files generated by `mk_all`,
-- this is in fact not necessary. (It is needed for `Tactic/Linter.lean`, though.)
lines.all (fun line ↦ line.startsWith "import " || line == "" || line.startsWith "-- ")
end
/-- All text-based linters registered in this file. -/
def allLinters : Array TextbasedLinter := #[
adaptationNoteLinter, semicolonLinter, trailingWhitespaceLinter
]
/-- Read a file and apply all text-based linters.
Return a list of all unexpected errors, and, if some errors could be fixed automatically,
the collection of all lines with every automatic fix applied.
`exceptions` are any pre-existing style exceptions for this file. -/
def lintFile (opts : LinterOptions) (path : FilePath) (exceptions : Array ErrorContext) :
IO (Array ErrorContext × Option (Array String)) := do
let mut errors := #[]
-- Whether any changes were made by auto-fixes.
let mut changes_made := false
-- Check for windows line endings first: as `FS.lines` treats Unix and Windows lines the same,
-- we need to analyse the actual file contents.
let contents ← IO.FS.readFile path
let replaced := contents.crlfToLf
if replaced != contents then
changes_made := true
errors := errors.push (ErrorContext.mk StyleError.windowsLineEnding 1 path)
let lines := (replaced.splitOn "\n").toArray
-- We don't need to run any further checks on imports-only files.
if isImportsOnlyFile lines then
return (errors, if changes_made then some lines else none)
-- All further style errors raised in this file.
let mut allOutput := #[]
-- A working copy of the lines in this file, modified by applying the auto-fixes.
let mut changed := lines
for lint in allLinters do
let (err, changes) := lint opts changed
allOutput := allOutput.append (Array.map (fun (e, n) ↦ #[(ErrorContext.mk e n path)]) err)
-- TODO: auto-fixes do not take style exceptions into account
if let some c := changes then
changed := c
changes_made := true
-- This list is not sorted: for github, this is fine.
errors := errors.append
(allOutput.flatten.filter (fun e ↦ (e.find?_comparable exceptions).isNone))
return (errors, if changes_made then some changed else none)
/-- Enables the old Python-based style linters. -/
-- TODO: these linters assume they are being run in `./scripts` and do not work on
-- downstream projects. Fix this before re-enabling them by default.
-- Or better yet: port them to Lean 4.
register_option linter.pythonStyle : Bool := { defValue := false }
/-- Lint a collection of modules for style violations.
Print formatted errors for all unexpected style violations to standard output;
correct automatically fixable style errors if configured so.
Return the number of files which had new style errors.
`opts` contains the options defined in the Lakefile, determining which linters to enable.
`nolints` is a list of style exceptions to take into account.
`moduleNames` are the names of all the modules to lint,
`mode` specifies what kind of output this script should produce,
`fix` configures whether fixable errors should be corrected in-place. -/
def lintModules (opts : LinterOptions) (nolints : Array String) (moduleNames : Array Lean.Name)
(style : ErrorFormat) (fix : Bool) : IO UInt32 := do
let styleExceptions := parseStyleExceptions nolints
let mut numberErrorFiles : UInt32 := 0
let mut allUnexpectedErrors := #[]
for module in moduleNames do
-- Convert the module name to a file name, then lint that file.
let path := mkFilePath (module.components.map toString)|>.addExtension "lean"
let (errors, changed) := ← lintFile opts path styleExceptions
if let some c := changed then
if fix then
let _ := ← IO.FS.writeFile path ("\n".intercalate c.toList)
if errors.size > 0 then
allUnexpectedErrors := allUnexpectedErrors.append errors
numberErrorFiles := numberErrorFiles + 1
-- Passing Lean options to Python files seems like a lot of work for something we want to
-- run entirely inside of Lean in the end anyway.
-- So for now, we enable/disable all of them with a single switch.
if getLinterValue linter.pythonStyle opts then
-- Run the remaining python linters. It is easier to just run on all files.
-- If this poses an issue, I can either filter the output
-- or wait until lint-style.py is fully rewritten in Lean.
let args := if fix then #["--fix"] else #[]
let output ← IO.Process.output { cmd := "./scripts/print-style-errors.sh", args := args }
if output.exitCode != 0 then
numberErrorFiles := numberErrorFiles + 1
IO.eprintln s!"error: `print-style-error.sh` exited with code {output.exitCode}"
IO.eprint output.stderr
else if output.stdout != "" then
numberErrorFiles := numberErrorFiles + 1
IO.eprint output.stdout
formatErrors allUnexpectedErrors style
if allUnexpectedErrors.size > 0 then
IO.eprintln s!"error: found {allUnexpectedErrors.size} new style error(s)"
return numberErrorFiles
/-- Verify that all modules are named in `UpperCamelCase` -/
register_option linter.modulesUpperCamelCase : Bool := { defValue := true }
/-- Verifies that all modules in `modules` are named in `UpperCamelCase`
(except for explicitly discussed exceptions, which are hard-coded here).
Return the number of modules violating this. -/
def modulesNotUpperCamelCase (opts : LinterOptions) (modules : Array Lean.Name) : IO Nat := do
unless getLinterValue linter.modulesUpperCamelCase opts do return 0
-- Exceptions to this list should be discussed on zulip!
let exceptions := [
`Mathlib.Analysis.CStarAlgebra.lpSpace,
`Mathlib.Analysis.InnerProductSpace.l2Space,
`Mathlib.Analysis.Normed.Lp.lpSpace
]
-- We allow only names in UpperCamelCase, possibly with a trailing underscore.
let badNames := modules.filter fun name ↦
let upperCamelName := Lake.toUpperCamelCase name
!exceptions.contains name &&
upperCamelName != name && s!"{upperCamelName}_" != name.toString
for bad in badNames do
let upperCamelName := Lake.toUpperCamelCase bad
let good := if bad.toString.endsWith "_" then s!"{upperCamelName}_" else upperCamelName.toString
IO.eprintln
s!"error: module name '{bad}' is not in 'UpperCamelCase': it should be '{good}' instead"
return badNames.size
/-- Verify that no module name is forbidden according to Windows' filename rules. -/
register_option linter.modulesForbiddenWindows : Bool := { defValue := true }
/-- Verifies that no module in `modules` contains CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5,
COM6, COM7, COM8, COM9, COM¹, COM², COM³, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9,
LPT¹, LPT² or LPT³ in its filename, as these are forbidden on Windows.
Also verify that module names contain no forbidden characters such as `*`, `?` (Windows),
`!` (forbidden on Nix OS) or `.` (might result from confusion with a module name).
Source: https://learn.microsoft.com/en-gb/windows/win32/fileio/naming-a-file.
Return the number of module names violating this rule. -/
def modulesOSForbidden (opts : LinterOptions) (modules : Array Lean.Name) : IO Nat := do
unless getLinterValue linter.modulesUpperCamelCase opts do return 0
let forbiddenNames := [
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
"COM9", "COM¹", "COM²", "COM³", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8",
"LPT9", "LPT¹", "LPT²", "LPT³"
]
-- We also check for the exclamation mark (which is not forbidden on Windows, but e.g. on Nix OS),
-- but do so below (with a custom error message).
let forbiddenCharacters := [
'<', '>', '"', '/', '\\', '|', '?', '*',
]
let mut badNamesNum := 0
for name in modules do
let mut isBad := false
let mut badComps : List String := []
let mut badChars : List String := []
for comp in name.componentsRev do
let .str .anonymous s := comp | continue
if forbiddenNames.contains s.toUpper then
badComps := s :: badComps
else
if s.contains '!' then
isBad := true
IO.eprintln s!"error: module name '{name}' contains forbidden character '!'"
else if s.contains '.' then
isBad := true
IO.eprintln s!"error: module name '{name}' contains forbidden character '.'"
else if s.contains ' ' || s.contains '\t' || s.contains '\n' then
isBad := true
IO.eprintln s!"error: module name '{name}' contains a whitespace character"
for c in forbiddenCharacters do
if s.contains c then
badChars := c.toString :: badChars
if !badComps.isEmpty || !badChars.isEmpty then
isBad := true
if isBad then badNamesNum := badNamesNum + 1
if !badComps.isEmpty then
IO.eprintln s!"error: module name '{name}' contains \
component{if badComps.length > 1 then "s" else ""} '{badComps}', \
which {if badComps.length > 1 then "are" else "is"} forbidden in Windows filenames."
if !badChars.isEmpty then
IO.eprintln s!"error: module name '{name}' contains \
character{if badChars.length > 1 then "s" else ""} '{badChars}', \
which {if badChars.length > 1 then "are" else "is"} forbidden in Windows filenames."
return badNamesNum
end Mathlib.Linter.TextBased |
.lake/packages/mathlib/Mathlib/Tactic/Linter/GlobalAttributeIn.lean | import Lean.Elab.Command
-- Import this linter explicitly to ensure that
-- this file has a valid copyright header and module docstring.
import Mathlib.Tactic.Linter.Header
/-!
# Linter for `attribute [...] in` declarations
Linter for global attributes created via `attribute [...] in` declarations.
The syntax `attribute [instance] instName in` can be used to accidentally create a global instance.
This is **not** obvious from reading the code, and in fact happened twice during the port,
hence, we lint against it.
*Example*: before this was discovered, `Mathlib/Topology/Category/TopCat/Basic.lean`
contained the following code:
```
attribute [instance] HasForget.instFunLike in
instance (X Y : TopCat.{u}) : CoeFun (X ⟶ Y) fun _ => X → Y where
coe f := f
```
Despite the `in`, this makes `HasForget.instFunLike` a global instance.
This seems to apply to all attributes. For example:
```lean
theorem what : False := sorry
attribute [simp] what in
#guard true
-- the `simp` attribute persists
example : False := by simp -- `simp` finds `what`
theorem who {x y : Nat} : x = y := sorry
attribute [ext] who in
#guard true
-- the `ext` attribute persists
example {x y : Nat} : x = y := by ext
```
Therefore, we lint against this pattern on all instances.
For *removing* attributes, the `in` works as expected.
```lean
/--
error: failed to synthesize
Add Nat
-/
#guard_msgs in
attribute [-instance] instAddNat in
#synth Add Nat
-- the `instance` persists
/-- info: instAddNat -/
#guard_msgs in
#synth Add Nat
@[simp]
theorem what : False := sorry
/-- error: simp made no progress -/
#guard_msgs in
attribute [-simp] what in
example : False := by simp
-- the `simp` attribute persists
#guard_msgs in
example : False := by simp
```
-/
open Lean Elab Command Linter
namespace Mathlib.Linter
/-- Lint on any occurrence of `attribute [...] name in` which is not `local` or `scoped`:
these are a footgun, as the attribute is applied *globally* (despite the `in`). -/
register_option linter.globalAttributeIn : Bool := {
defValue := true
descr := "enable the globalAttributeIn linter"
}
namespace globalAttributeInLinter
/-- Gets the value of the `linter.globalAttributeIn` option. -/
def getLinterGlobalAttributeIn (o : LinterOptions) : Bool :=
getLinterValue linter.globalAttributeIn o
/--
`getGlobalAttributesIn? cmd` assumes that `cmd` represents a `attribute [...] id in ...` command.
If this is the case, then it returns `(id, #[non-local nor scoped attributes])`.
Otherwise, it returns `default`.
-/
def getGlobalAttributesIn? : Syntax → Option (Ident × Array (TSyntax `attr))
| `(attribute [$x,*] $id in $_) =>
let xs := x.getElems.filterMap fun a => match a.raw with
| `(Parser.Command.eraseAttr| -$_) => none
| `(Parser.Term.attrInstance| local $_attr:attr) => none
| `(Parser.Term.attrInstance| scoped $_attr:attr) => none
| `(attr| $a) => some a
(id, xs)
| _ => default
/-- The `globalAttributeInLinter` linter flags any global attributes generated by an
`attribute [...] in` declaration. (This includes the `instance`, `simp` and `ext` attributes.)
Despite the `in`, these define *global* instances, which can be rather misleading.
Instead, remove the `in` or mark them with `local`.
-/
def globalAttributeIn : Linter where run := withSetOptionIn fun stx => do
unless getLinterGlobalAttributeIn (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
for s in stx.topDown do
if let some (id, nonScopedNorLocal) := getGlobalAttributesIn? s then
for attr in nonScopedNorLocal do
Linter.logLint linter.globalAttributeIn attr m!
"Despite the `in`, the attribute '{attr}' is added globally to '{id}'\n\
please remove the `in` or make this a `local {attr}`"
initialize addLinter globalAttributeIn
end globalAttributeInLinter
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/FlexibleLinter.lean | import Lean.Elab.Command
import Mathlib.Tactic.Linter.Header
/-!
# The "flexible" linter
The "flexible" linter makes sure that a "rigid" tactic (such as `rw`) does not act on the
output of a "flexible" tactic (such as `simp`).
For example, this ensures that, if you want to use `simp [...]` in the middle of a proof,
then you should replace `simp [...]` by one of
* a `suffices \"expr after simp\" by simpa` line;
* the output of `simp? [...]`, so that the final code contains `simp only [...]`;
* something else that does not involve `simp`!
Otherwise, the linter will complain.
Simplifying and appealing to a geometric intuition, you can imagine a (tactic) proof like a
directed graph, where
* each node is a local hypothesis or a goal in some metavariable and
* two hypotheses/goals are connected by an arrow if there is a tactic that modifies the source
of the arrow into the target (this does not apply well to all tactics, but it does apply to
a large number of them).
With this in mind, a tactic like `rw [lemma]` takes a *very specific* input and return a
*very predictable* output.
Such a tactic is "rigid". Any tactic is rigid, unless it is in `flexible` or `stoppers`.
Conversely, a tactic like `simp` acts on a wide variety of inputs and returns an output that
is possibly unpredictable: if later modifications adds a `simp`-lemma or some internals of
`simp` changes, the output of `simp` may change as well.
Such a tactic is `flexible`. Other examples are `split`, `abel`, `norm_cast`,...
Let's go back to the graph picture above.
* ✅️ [`rigid` --> `flexible`]
A sequence `rw [lemma]; simp` is unlikely to break, since `rw [lemma]` produces the same output
unless some *really major* change happens!
* ❌️ [`flexible` --> `rigid`]
A sequence `simp; rw [lemma]` is instead more likely to break, since the goal after `simp` is
subject to change by even a small, likely, modification of the `simp` set.
* ✅️ [`flexible` --> `flexible`]
A sequence `simp; linarith` is also quite stable, since if `linarith` was able to close the
goal with a "weaker" `simp`, it will likely still be able to close the goal with a `simp`
that takes one further step.
* ✅️ [`flexible` --> `stopper`]
Finally, a sequence `simp; ring_nf` is stable and, moreover, the output of `ring_nf` is a
"normal form", which means that it is likely to produce an unchanged result, even if the initial
input is different from the proof in its initial form.
A stopper can be followed by a rigid tactic, "stopping" the spread of the flexible reach.
What the linter does is keeping track of nodes that are connected by `flexible` tactics and
makes sure that only `flexible` or `stoppers` follow them.
Such nodes are `Stained`.
Whenever it reaches a `stopper` edge, the target node is no longer `Stained` and it is
available again to `rigid` tactics.
Currently, the only tactics that "start" the bookkeeping are most forms of non-`only` `simp`s.
These are encoded by the `flexible?` predicate.
Future modifications of the linter may increase the scope of the `flexible?` predicate and
forbid a wider range of combinations.
## TODO
The example
```lean
example (h : 0 = 0) : True := by
simp at h
assumption
```
should trigger the linter, since `assumption` uses `h` that has been "stained" by `simp at h`.
However, `assumption` contains no syntax information for the location `h`, so the linter in its
current form does not catch this.
## Implementation notes
A large part of the code is devoted to tracking `FVar`s and `MVar`s between tactics.
For the `FVar`s, this follows the following heuristic:
* if the unique name of the `FVar` is preserved, then we use that;
* otherwise, if the `userName` of the `FVar` is preserved, then we use that;
* if neither is preserved, we drop the ball and stop tracking the `FVarId`.
For the `MVar`s, we use the information of `Lean.Elab.TacticInfo.goalsBefore` and
`Lean.Elab.TacticInfo.goalsAfter`.
By looking at the `mvar`s that are either only "before" or only "after", we focus on the
"active" goals.
We then propagate all the `FVarId`s that were present in the "before" goals to the "after" goals,
while leaving untouched the ones in the "inert" goals.
-/
open Lean Elab Linter
namespace Mathlib.Linter
/-- The flexible linter makes sure that "rigid" tactics do not follow "flexible" tactics. -/
register_option linter.flexible : Bool := {
defValue := false
descr := "enable the flexible linter"
}
/-- `flexible? stx` is `true` if `stx` is syntax for a tactic that takes a "wide" variety of
inputs and modifies them in possibly unpredictable ways.
The prototypical flexible tactic is `simp`.
The prototypical non-flexible tactic `rw`.
`simp only` is also non-flexible. -/
-- TODO: adding more entries here, allows to consider more tactics to be flexible
def flexible? : Syntax → Bool
| .node _ ``Lean.Parser.Tactic.simp #[_, _, _, only?, _, _] => only?[0].getAtomVal != "only"
| .node _ ``Lean.Parser.Tactic.simpAll #[_, _, _, only?, _] => only?[0].getAtomVal != "only"
| _ => false
end Mathlib.Linter
section goals_heuristic
namespace Lean.Elab.TacticInfo
/-!
### Heuristics for determining goals that a tactic modifies and what they become
The two definitions `goalsTargetedBy`, `goalsCreatedBy` extract a list of
`MVarId`s attempting to determine on which goals the tactic `t` is acting and what are the
resulting modified goals.
This is mostly based on the heuristic that the tactic will "change" an `MVarId`.
-/
/-- `goalsTargetedBy t` are the `MVarId`s before the `TacticInfo` `t` that "disappear" after it.
They should correspond to the goals in which the tactic `t` performs some action. -/
def goalsTargetedBy (t : TacticInfo) : List MVarId :=
t.goalsBefore.filter (·.name ∉ t.goalsAfter.map (·.name))
/-- `goalsCreatedBy t` are the `MVarId`s after the `TacticInfo` `t` that were not present before.
They should correspond to the goals created or changed by the tactic `t`. -/
def goalsCreatedBy (t : TacticInfo) : List MVarId :=
t.goalsAfter.filter (·.name ∉ t.goalsBefore.map (·.name))
end Lean.Elab.TacticInfo
end goals_heuristic
namespace Mathlib.Linter.Flexible
variable (take? : Syntax → Bool) in
/-- `extractCtxAndGoals take? tree` takes as input a function `take? : Syntax → Bool` and
an `InfoTree` and returns the array of pairs `(stx, mvars)`,
where `stx` is a syntax node such that `take? stx` is `true` and
`mvars` indicates the goal state:
* the context before `stx`
* the context after `stx`
* a list of metavariables closed by `stx`
* a list of metavariables created by `stx`
A typical usage is to find the goals following a `simp` application.
-/
partial
def extractCtxAndGoals : InfoTree →
Array (Syntax × MetavarContext × MetavarContext × List MVarId × List MVarId)
| .node k args =>
let kargs := (args.map extractCtxAndGoals).foldl (· ++ ·) #[]
if let .ofTacticInfo i := k then
if take? i.stx && (i.stx.getRange? true).isSome then
#[(i.stx, i.mctxBefore, i.mctxAfter, i.goalsTargetedBy, i.goalsCreatedBy)] ++ kargs
else kargs
else kargs
| .context _ t => extractCtxAndGoals t
| _ => default
/-- `Stained` is the type of the stained locations: it can be
* a `Name` (typically of associated to the `FVarId` of a local declaration);
* the goal (`⊢`);
* the "wildcard" -- all the declaration in context (`*`).
-/
inductive Stained
| name : Name → Stained
| goal : Stained
| wildcard : Stained
deriving Repr, Inhabited, DecidableEq, Hashable
/-- Converting a `Stained` to a `String`:
* a `Name` is represented by the corresponding string;
* `goal` is represented by `⊢`;
* `wildcard` is represented by `*`.
-/
instance : ToString Stained where
toString | .name n => n.toString | .goal => "⊢" | .wildcard => "*"
/--
`toStained stx` scans the input `Syntax` `stx` extracting identifiers and atoms, making an effort
to convert them to `Stained`.
The function is used to extract "location" information about `stx`: either explicit locations as in
`rw [] at locations` or implicit ones as `rw [h]`.
Whether or not what this function extracts really is a location will be determined by the linter
using data embedded in the `InfoTree`s. -/
partial
def toStained : Syntax → Std.HashSet Stained
| .node _ _ arg => (arg.map toStained).foldl (.union) {}
| .ident _ _ val _ => {.name val}
| .atom _ val => match val with
| "*" => {.wildcard}
| "⊢" => {.goal}
| "|" => {.goal}
| _ => {}
| _ => {}
/-- `getStained stx` expects `stx` to be an argument of a node of `SyntaxNodeKind`
`Lean.Parser.Tactic.location`.
Typically, we apply `getStained` to the output of `getLocs`.
See `getStained!` for a similar function. -/
partial
def getStained (stx : Syntax) (all? : Syntax → Bool := fun _ ↦ false) : Std.HashSet Stained :=
match stx with
| stx@(.node _ ``Lean.Parser.Tactic.location loc) =>
if all? stx then {} else (loc.map toStained).foldl (·.union) {}
| .node _ _ args => (args.map (getStained · all?)).foldl (·.union) {}
| _ => default
/-- `getStained! stx` expects `stx` to be an argument of a node of `SyntaxNodeKind`
`Lean.Parser.Tactic.location`.
Typically, we apply `getStained!` to the output of `getLocs`.
It returns the `HashSet` of `Stained` determined by the locations in `stx`.
The only difference with `getStained stx`, is that `getStained!` never returns `{}`:
if `getStained stx = {}`, then `getStained' stx = {.goal}`.
This means that tactics that do not have an explicit "`at`" in their syntax will be treated as
acting on the main goal. -/
def getStained! (stx : Syntax) (all? : Syntax → Bool := fun _ ↦ false) : Std.HashSet Stained :=
let out := getStained stx all?
if out.size == 0 then {.goal} else out
/-- `Stained.toFMVarId mv lctx st` takes a metavariable `mv`, a local context `lctx` and
a `Stained` `st` and returns the array of pairs `(FVarId, mv)`s that `lctx` assigns to `st`
(the second component is always `mv`):
* if `st` "is" a `Name`, returns the singleton of the `FVarId` with the name carried by `st`;
* if `st` is `.goal`, returns the singleton `#[default]`;
* if `st` is `.wildcard`, returns the array of all the `FVarId`s in `lctx` with also `default`
(to keep track of the `goal`).
-/
def Stained.toFMVarId (mv : MVarId) (lctx: LocalContext) : Stained → Array (FVarId × MVarId)
| name n => match lctx.findFromUserName? n with
| none => #[]
| some decl => #[(decl.fvarId, mv)]
| goal => #[(default, mv)]
| wildcard => (lctx.getFVarIds.push default).map (·, mv)
/-- `SyntaxNodeKind`s that are mostly "formatting": mostly they are ignored
because we do not want the linter to spend time on them.
The nodes that they contain will be visited by the linter anyway.
The nodes that *follow* them, though, will *not* be visited by the linter.
-/
def stoppers : Std.HashSet Name :=
{ -- "properly stopper tactics": the effect of these tactics is to return a normal form
-- (or possibly be finishing tactics -- the ultimate normal form!
-- finishing tactics could equally well be considered as `flexible`, but as there is
-- no possibility of a follower anyway, it does not make a big difference.)
``Lean.Parser.Tactic.tacticSorry,
``Lean.Parser.Tactic.tacticRepeat_,
``Lean.Parser.Tactic.tacticStop_,
`Mathlib.Tactic.Abel.abelNF,
`Mathlib.Tactic.Abel.tacticAbel_nf!__,
`Mathlib.Tactic.RingNF.ringNF,
`Mathlib.Tactic.RingNF.tacticRing_nf!__,
`Mathlib.Tactic.Group.group,
`Mathlib.Tactic.FieldSimp.fieldSimp,
`Mathlib.Tactic.FieldSimp.field,
`finiteness_nonterminal,
-- "continuators": the *effect* of these tactics is similar the "properly stoppers" above,
-- though they typically wrap other tactics inside them.
-- The linter ignores the wrapper, but does recurse into the enclosed tactics
``Lean.Parser.Tactic.tacticSeq1Indented,
``Lean.Parser.Tactic.tacticSeq,
``Lean.Parser.Term.byTactic,
`by,
``Lean.Parser.Tactic.tacticTry_,
`choice, -- involved in `first`
``Lean.Parser.Tactic.allGoals,
`Std.Tactic.«tacticOn_goal-_=>_»,
``Lean.Parser.Tactic.«tactic_<;>_»,
``cdotTk,
``cdot }
/-- `SyntaxNodeKind`s that are allowed to follow a flexible tactic:
`simp`, `simp_all`, `simpa`, `dsimp`, `grind`, `constructor`, `congr`, `done`, `rfl`,
`omega` and `cutsat`, `grobner`
`abel` and `abel!`, `group`, `ring` and `ring!`, `module`, `field_simp` and `field`, `norm_num`,
`linarith`, `nlinarith` and `nlinarith!`, `norm_cast`, `tauto`,
`aesop`, `cfc_tac` (and `cfc_zero_tac` and `cfc_cont_tac`),
`continuity` and `measurability`, `finiteness`, `finiteness?`,
`split`, `split_ifs`.
-/
def flexible : Std.HashSet Name :=
{ ``Lean.Parser.Tactic.simp,
``Lean.Parser.Tactic.simpAll,
``Lean.Parser.Tactic.simpa,
``Lean.Parser.Tactic.dsimp,
``Lean.Parser.Tactic.constructor,
``Lean.Parser.Tactic.congr,
``Lean.Parser.Tactic.done,
``Lean.Parser.Tactic.tacticRfl,
``Lean.Parser.Tactic.omega,
`Mathlib.Tactic.Abel.abel,
`Mathlib.Tactic.Abel.tacticAbel!,
`Mathlib.Tactic.Group.group,
`Mathlib.Tactic.RingNF.ring,
`Mathlib.Tactic.RingNF.tacticRing!,
`Mathlib.Tactic.Ring.ring1,
`Mathlib.Tactic.Ring.tacticRing1!,
`Mathlib.Tactic.RingNF.ring1NF,
`Mathlib.Tactic.RingNF.tacticRing1_nf!_,
`Mathlib.Tactic.RingNF.ring1NF!,
`Mathlib.Tactic.Module.tacticModule,
`Mathlib.Tactic.FieldSimp.fieldSimp,
`Mathlib.Tactic.FieldSimp.field,
``Lean.Parser.Tactic.grind,
``Lean.Parser.Tactic.grobner,
``Lean.Parser.Tactic.cutsat,
`Mathlib.Tactic.normNum,
`Mathlib.Tactic.linarith,
`Mathlib.Tactic.nlinarith,
`Mathlib.Tactic.tacticNlinarith!_,
`Mathlib.Tactic.LinearCombination.linearCombination,
``Lean.Parser.Tactic.tacticNorm_cast__,
`Aesop.Frontend.Parser.aesopTactic,
-- `cfc_tac` and `cfc_zero_tac` use `aesop` under the hood,
-- `cfc_cont_tactic` uses `fun_prop`: in practice, this should be robust enough.
`cfcTac,
`cfcZeroTac,
`cfcContTac,
-- `continuity` and `measurability` also use `aesop` under the hood.
`tacticContinuity,
`tacticMeasurability,
`finiteness,
`finiteness?,
`Mathlib.Tactic.Tauto.tauto,
`Lean.Parser.Tactic.split,
`Mathlib.Tactic.splitIfs }
/-- By default, if a `SyntaxNodeKind` is not special-cased here, then the linter assumes that
the tactic will use the goal as well: this heuristic works well with `exact`, `refine`, `apply`.
For tactics such as `cases` this is not true: for these tactics, `usesGoal?` yields `false. -/
def usesGoal? : SyntaxNodeKind → Bool
| ``Lean.Parser.Tactic.cases => false
| `Mathlib.Tactic.cases' => false
| ``Lean.Parser.Tactic.obtain => false
| ``Lean.Parser.Tactic.tacticHave__ => false
| ``Lean.Parser.Tactic.rcases => false
| ``Lean.Parser.Tactic.specialize => false
| ``Lean.Parser.Tactic.subst => false
| ``«tacticBy_cases_:_» => false
| ``Lean.Parser.Tactic.induction => false
| _ => true
/-- `getFVarIdCandidates fv name lctx` takes an input an `FVarId`, a `Name` and a `LocalContext`.
It returns an array of guesses for a "best fit" `FVarId` in the given `LocalContext`.
The first entry of the array is the input `FVarId` `fv`, if it is present.
The next entry of the array is the `FVarId` with the given `Name`, if present.
Usually, the first entry of the returned array is "the best approximation" to `(fv, name)`. -/
def getFVarIdCandidates (fv : FVarId) (name : Name) (lctx : LocalContext) : Array FVarId :=
#[lctx.find? fv, lctx.findFromUserName? name].reduceOption.map (·.fvarId)
/-!
Tactics often change the name of the current `MVarId`, as well as the names of the `FVarId`s
appearing in their local contexts.
The function `reallyPersist` makes an attempt at "tracking" pairs `(fvar, mvar)` across a
simultaneous change represented by an "old" list of `MVarId`s and the corresponding
`MetavarContext` and a new one.
This arises in the context of the information encoded in the `InfoTree`s when processing a
tactic proof.
-/
/-- `persistFVars` is one step in persisting: track a single `FVarId` between two `LocalContext`s.
If an `FVarId` with the same unique name exists in the new context, use it.
Otherwise, if an `FVarId` with the same `userName` exists in the new context, use it.
If both of these fail, return `default` (i.e. "fail"). -/
def persistFVars (fv : FVarId) (before after : LocalContext) : FVarId :=
let ldecl := (before.find? fv).getD default
(getFVarIdCandidates fv ldecl.userName after).getD 0 default
/-- `reallyPersist` converts an array of pairs `(fvar, mvar)` to another array of the same type. -/
def reallyPersist
(fmvars : Array (FVarId × MVarId)) (mvs0 mvs1 : List MVarId) (ctx0 ctx1 : MetavarContext) :
Array (FVarId × MVarId) := Id.run do
-- split the input `fmvars` into
-- * the `active` ones, whose `mvar` appears in `mvs0` and
-- * the `inert` ones, the rest.
-- `inert` gets copied unchanged, while we transform `active`
let (active, inert) := fmvars.partition fun (_, mv) => mvs0.contains mv
let mut new := #[]
for (fvar, mvar) in active do -- for each `active` pair `(fvar, mvar)`
match ctx0.decls.find? mvar with -- check if `mvar` is managed by `ctx0` (it should be)
| none => -- the `mvar` is not managed by `ctx0`: no change
new := new.push (fvar, mvar)
| some mvDecl0 => -- the `mvar` *is* managed by `ctx0`: push the pair `(fvar, mvar)` through
for mv1 in mvs1 do -- for each new `MVarId` in `mvs1`
match ctx1.decls.find? mv1 with -- check if `mv1` is managed by `ctx1` (it should be)
| none => dbg_trace "'really_persist' could this happen?" default -- ??? maybe `.push`?
| some mvDecl1 => -- we found a "new" declaration
let persisted_fv := persistFVars fvar mvDecl0.lctx mvDecl1.lctx -- persist `fv`
new := new.push (persisted_fv, mv1)
return inert ++ new
/-- The main implementation of the flexible linter. -/
def flexibleLinter : Linter where run := withSetOptionIn fun _stx => do
unless getLinterValue linter.flexible (← getLinterOptions) && (← getInfoState).enabled do
return
if (← MonadState.get).messages.hasErrors then
return
let trees ← getInfoTrees
let x := trees.map (extractCtxAndGoals (fun _ => true))
-- `stains` records pairs `(location, mvar)`, where
-- * `location` is either a hypothesis or the main goal modified by a flexible tactic and
-- * `mvar` is the metavariable containing the modified location
let mut stains : Array ((FVarId × MVarId) × (Stained × Syntax)) := #[]
let mut msgs : Array (Syntax × Syntax × Stained) := #[]
for d in x do for (s, ctx0, ctx1, mvs0, mvs1) in d do
let skind := s.getKind
if stoppers.contains skind then continue
let shouldStain? := flexible? s && mvs1.length == mvs0.length
for d in getStained! s do
if shouldStain? then
for currMVar1 in mvs1 do
let lctx1 := (ctx1.decls.findD currMVar1 default).lctx
let locsAfter := d.toFMVarId currMVar1 lctx1
stains := stains ++ locsAfter.map (fun l ↦ (l, (d, s)))
else
let stained_in_syntax := if usesGoal? skind then (toStained s).insert d else toStained s
if !flexible.contains skind then
for currMv0 in mvs0 do
let lctx0 := (ctx0.decls.findD currMv0 default).lctx
let mut foundFvs : Std.HashSet (FVarId × MVarId):= {}
for st in stained_in_syntax do
for d in st.toFMVarId currMv0 lctx0 do
if !foundFvs.contains d then foundFvs := foundFvs.insert d
for l in foundFvs do
if let some (_stdLoc, (st, kind)) := stains.find? (Prod.fst · == l) then
msgs := msgs.push (s, kind, st)
-- tactics often change the name of the current `MVarId`, so we migrate the `FvarId`s
-- in the "old" `mvars` to the "same" `FVarId` in the "new" `mvars`
let mut new : Array ((FVarId × MVarId) × (Stained × Syntax)) := .empty
for (fv, (stLoc, kd)) in stains do
let psisted := reallyPersist #[fv] mvs0 mvs1 ctx0 ctx1
if psisted == #[] && mvs1 != [] then
new := new.push (fv, (stLoc, kd))
dbg_trace "lost {((fv.1.name, fv.2.name), stLoc, kd)}"
for p in psisted do new := new.push (p, (stLoc, kd))
stains := new
for (s, stainStx, d) in msgs do
Linter.logLint linter.flexible stainStx m!"'{stainStx}' is a flexible tactic modifying '{d}'…"
logInfoAt s m!"… and '{s}' uses '{d}'!"
initialize addLinter flexibleLinter
end Mathlib.Linter.Flexible |
.lake/packages/mathlib/Mathlib/Tactic/Linter/HashCommandLinter.lean | import Lean.Elab.Command
-- Import this linter explicitly to ensure that
-- this file has a valid copyright header and module docstring.
import Mathlib.Tactic.Linter.Header
/-!
# `#`-command linter
The `#`-command linter produces a warning when a command starting with `#` is used *and*
* either the command emits no message;
* or `warningAsError` is set to `true`.
The rationale behind this is that `#`-commands are intended to be transient:
they provide useful information in development, but are not intended to be present in final code.
Most of them are noisy and get picked up anyway by CI, but even the quiet ones are not expected to
outlive their in-development status.
-/
namespace Mathlib.Linter
/--
The linter emits a warning on any command beginning with `#` that itself emits no message.
For example, `#guard true` and `#check_tactic True ~> True by skip` trigger a message.
There is a list of silent `#`-command that are allowed.
-/
register_option linter.hashCommand : Bool := {
defValue := false
descr := "enable the `#`-command linter"
}
namespace HashCommandLinter
open Lean Elab Linter
open Command in
/-- Exactly like `withSetOptionIn`, but recursively discards nested uses of `in`.
Intended to be used in the `hashCommand` linter, where we want to enter `set_option` `in` commands.
-/
private partial def withSetOptionIn' (cmd : CommandElab) : CommandElab := fun stx => do
if stx.getKind == ``Lean.Parser.Command.in then
if stx[0].getKind == ``Lean.Parser.Command.set_option then
let opts ← Elab.elabSetOption stx[0][1] stx[0][3]
withScope (fun scope => { scope with opts }) do
withSetOptionIn' cmd stx[2]
else
withSetOptionIn' cmd stx[2]
else
cmd stx
/-- `allowed_commands` is the `HashSet` of `#`-commands that are allowed in 'Mathlib'. -/
private abbrev allowed_commands : Std.HashSet String := { "#adaptation_note" }
/-- Checks that no command beginning with `#` is present in 'Mathlib',
except for the ones in `allowed_commands`.
If `warningAsError` is `true`, then the linter logs an info (rather than a warning).
This means that CI will eventually fail on `#`-commands, but does not stop it from continuing.
However, in order to avoid local clutter, when `warningAsError` is `false`, the linter
logs a warning only for the `#`-commands that do not already emit a message. -/
def hashCommandLinter : Linter where run := withSetOptionIn' fun stx => do
if getLinterValue linter.hashCommand (← getLinterOptions) &&
((← get).messages.reportedPlusUnreported.isEmpty || warningAsError.get (← getOptions))
then
if let some sa := stx.getHead? then
let a := sa.getAtomVal
if (a.front == '#' && ! allowed_commands.contains a) then
let msg := m!"`#`-commands, such as '{a}', are not allowed in 'Mathlib'"
if warningAsError.get (← getOptions) then
logInfoAt sa (msg ++ " [linter.hashCommand]")
else Linter.logLint linter.hashCommand sa msg
initialize addLinter hashCommandLinter
end HashCommandLinter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/DocString.lean | import Mathlib.Tactic.Linter.Header
/-!
# The "DocString" style linter
The "DocString" linter validates style conventions regarding doc-string formatting.
-/
open Lean Elab Linter
namespace Mathlib.Linter
/--
The "DocString" linter validates style conventions regarding doc-string formatting.
-/
register_option linter.style.docString : Bool := {
defValue := false
descr := "enable the style.docString linter"
}
/--
The "empty doc string" warns on empty doc-strings.
-/
register_option linter.style.docString.empty : Bool := {
defValue := true
descr := "enable the style.docString.empty linter"
}
/--
Extract all `declModifiers` from the input syntax. We later extract the `docstring` from it,
but we avoid extracting directly the `docComment` node, to skip `#adaptation_note`s.
-/
def getDeclModifiers : Syntax → Array Syntax
| s@(.node _ kind args) =>
(if kind == ``Parser.Command.declModifiers then #[s] else #[]) ++ args.flatMap getDeclModifiers
| _ => #[]
/--
Currently, this function simply removes `currIndent` spaces after each `\n`
in the input string `docString`.
If/when the `docString` linter expands, it may take on more string processing.
-/
def deindentString (currIndent : Nat) (docString : String) : String :=
let indent : String := ('\n' :: List.replicate currIndent ' ').asString
docString.replace indent " "
namespace Style
@[inherit_doc Mathlib.Linter.linter.style.docString]
def docStringLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.style.docString (← getLinterOptions) ||
getLinterValue linter.style.docString.empty (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
let fm ← getFileMap
for declMods in getDeclModifiers stx do
-- `docStx` extracts the `Lean.Parser.Command.docComment` node from the declaration modifiers.
-- In particular, this ignores parsing `#adaptation_note`s.
let docStx := declMods[0][0]
let some pos := docStx.getPos? | continue
let currIndent := fm.toPosition pos |>.column
if docStx.isMissing then continue -- this is probably superfluous, thanks to `some pos` above.
-- `docString` contains e.g. trailing spaces before the `-/`, but does not contain
-- any leading whitespace before the actual string starts.
let docString ← try getDocStringText ⟨docStx⟩ catch _ => continue
if docString.trim.isEmpty then
Linter.logLintIf linter.style.docString.empty docStx m!"warning: this doc-string is empty"
continue
-- `startSubstring` is the whitespace between `/--` and the actual doc-string text.
let startSubstring := match docStx with
| .node _ _ #[(.atom si ..), _] => si.getTrailing?.getD default
| _ => default
-- We replace all line-breaks followed by `currIndent` spaces with a single space.
let start := deindentString currIndent startSubstring.toString
if !#["\n", " "].contains start then
let startRange := {start := startSubstring.startPos, stop := startSubstring.stopPos}
Linter.logLintIf linter.style.docString (.ofRange startRange)
s!"error: doc-strings should start with a single space or newline"
let deIndentedDocString := deindentString currIndent docString
let docTrim := deIndentedDocString.trimRight
let tail := docTrim.length
-- `endRange` creates an 0-wide range `n` characters from the end of `docStx`
let endRange (n : Nat) : Syntax := .ofRange
{start := docStx.getTailPos?.get!.unoffsetBy ⟨n⟩, stop := docStx.getTailPos?.get!.unoffsetBy ⟨n⟩}
if docTrim.takeRight 1 == "," then
Linter.logLintIf linter.style.docString (endRange (docString.length - tail + 3))
s!"error: doc-strings should not end with a comma"
if tail + 1 != deIndentedDocString.length then
Linter.logLintIf linter.style.docString (endRange 3)
s!"error: doc-strings should end with a single space or newline"
initialize addLinter docStringLinter
end Style
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/Header.lean | import Lean.Elab.Command
import Lean.Elab.ParseImportsFast
import Mathlib.Tactic.Linter.DirectoryDependency
/-!
# The "header" linter
The "header" style linter checks that a file starts with
```
import statements*
module doc-string*
remaining file
```
It emits a warning if
* the copyright statement is malformed;
* `Mathlib.Tactic` is imported;
* any import in `Lake` is present;
* the first non-`import` command is not a module doc-string.
The linter allows `import`-only files and does not require a copyright statement in `Mathlib.Init`.
## Implementation
The strategy used by the linter is as follows.
The linter computes the end position of the first module doc-string of the file,
resorting to the end of the file, if there is no module doc-string.
Next, the linter tries to parse the file up to the position determined above.
If the parsing is successful, the linter checks the resulting `Syntax` and behaves accordingly.
If the parsing is not successful, this already means there is some "problematic" command
after the imports. In particular, there is a command that is not a module doc-string
immediately following the last import: the file should be flagged by the linter.
Hence, the linter then falls back to parsing the header of the file, adding a spurious `section`
after it.
This makes it possible for the linter to check the entire header of the file, emit warnings that
could arise from this part and also flag that the file should contain a module doc-string after
the `import` statements.
-/
open Lean Elab Command Linter
namespace Mathlib.Linter
/--
`firstNonImport? stx` assumes that the input `Syntax` is of kind `Lean.Parser.Module.module`.
It returns
* `none`, if `stx` consists only of `import` statements,
* the first non-`import` command in `stx`, otherwise.
The intended use-case is to use the output of `testParseModule` as the input of
`firstNonImport?`.
-/
def firstNonImport? : Syntax → Option Syntax
| .node _ ``Lean.Parser.Module.module #[_header, .node _ `null args] => args[0]?
| _=> some .missing -- this is unreachable, if the input comes from `testParseModule`
/-- `getImportIds s` takes as input `s : Syntax`.
It returns the array of all `import` identifiers in `s`. -/
-- We cannot use `importsOf` instead, as
-- - that function is defined in the `ImportGraph` project; we would like to minimise imports
-- to Mathlib.Init (where this linter is imported)
-- - that function does not return the Syntax corresponding to each import,
-- which we use to log more precise warnings.
partial
def getImportIds (s : Syntax) : Array Syntax :=
let rest : Array Syntax := (s.getArgs.map getImportIds).flatten
if let `(Lean.Parser.Module.import| import $n) := s then
rest.push n
else
rest
/--
`parseUpToHere pos post` takes as input `pos : String.Pos` and the optional `post : String`.
It parses the current file from the beginning until `pos`, appending `post` at the end.
It returns a syntax node of kind `Lean.Parser.Module.module`.
The option of appending a final string to the text gives more control to avoid syntax errors,
for instance in the presence of `#guard_msgs in` or `set_option ... in`.
Note that this parsing will *not* be successful on every file. However, if the linter is
parsing the file linearly, it will only need to parse
* the imports (that are always parseable) and
* the first non-import command that is supposed to be a module doc-string (so again always
parseable).
In conclusion, either the parsing is successful, and the linter can continue with its analysis,
or the parsing is not successful and the linter will flag a missing module doc-string!
-/
def parseUpToHere (pos : String.Pos.Raw) (post : String := "") : CommandElabM Syntax := do
let upToHere : Substring := { str := (← getFileMap).source, startPos := ⟨0⟩, stopPos := pos }
-- Append a further string after the content of `upToHere`.
Parser.testParseModule (← getEnv) "linter.style.header" (upToHere.toString ++ post)
/-- `toSyntax s pattern` converts the two input strings into a `Syntax`, assuming that `pattern`
is a substring of `s`:
the syntax is an atom with value `pattern` whose the range is the range of `pattern` in `s`. -/
def toSyntax (s pattern : String) (offset : String.Pos.Raw := 0) : Syntax :=
let beg := ((s.splitOn pattern).getD 0 "").endPos.offsetBy offset
let fin := (((s.splitOn pattern).getD 0 "") ++ pattern).endPos.offsetBy offset
mkAtomFrom (.ofRange ⟨beg, fin⟩) pattern
/-- Return if `line` looks like a correct authors line in a copyright header.
The `offset` input is used to shift the position information of the `Syntax` that the command
produces.
`authorsLineChecks` computes a position for its warning *relative to `line`*.
The `offset` input passes on the starting position of `line` in the whole file.
-/
def authorsLineChecks (line : String) (offset : String.Pos.Raw) : Array (Syntax × String) :=
Id.run do
-- We cannot reasonably validate the author names, so we look only for a few common mistakes:
-- the line starting wrongly, double spaces, using ' and ' between names,
-- and ending the line with a period.
let mut stxs := #[]
if !line.startsWith "Authors: " then
stxs := stxs.push
(toSyntax line (line.take "Authors: ".length) offset,
s!"The authors line should begin with 'Authors: '")
if (line.splitOn " ").length != 1 then
stxs := stxs.push (toSyntax line " " offset, s!"Double spaces are not allowed.")
if (line.splitOn " and ").length != 1 then
stxs := stxs.push (toSyntax line " and " offset, s!"Please, do not use 'and'; use ',' instead.")
if line.back == '.' then
stxs := stxs.push
(toSyntax line "." offset,
s!"Please, do not end the authors' line with a period.")
-- If there are no previous exceptions, then we try to validate the names.
if !stxs.isEmpty then
return stxs
if (line.drop "Authors:".length).trim.isEmpty then
return #[(toSyntax line "Authors:" offset,
s!"Please, add at least one author!")]
else
return #[]
/-- The main function to validate the copyright string.
The input is the copyright string, the output is an array of `Syntax × String` encoding:
* the `Syntax` factors are atoms whose ranges are "best guesses" for where the changes should
take place; the embedded string is the current text that the linter flagged;
* the `String` factor is the linter message.
The linter checks that
* the first and last line of the copyright are a `("/-", "-/")` pair, each on its own line;
* the first line is begins with `Copyright (c) 20` and ends with `. All rights reserved.`;
* the second line is `Released under Apache 2.0 license as described in the file LICENSE.`;
* the remainder of the string begins with `Authors: `, does not end with `.` and
contains no ` and ` nor a double space, except possibly after a line break.
-/
def copyrightHeaderChecks (copyright : String) : Array (Syntax × String) := Id.run do
-- First, we merge lines ending in `,`: two spaces after the line-break are ok,
-- but so is only one or none. We take care of *not* adding more consecutive spaces, though.
-- This is to allow the copyright or authors' lines to span several lines.
let preprocessCopyright := (copyright.replace ",\n " ", ").replace ",\n" ","
-- Filter out everything after the first isolated `-/`.
let pieces := preprocessCopyright.splitOn "\n-/"
let copyright := (pieces.getD 0 "") ++ "\n-/"
let stdText (s : String) :=
s!"Malformed or missing copyright header: `{s}` should be alone on its own line."
let mut output := #[]
if (pieces.getD 1 "\n").take 1 != "\n" then
output := output.push (toSyntax copyright "-/", s!"{stdText "-/"}")
let lines := copyright.splitOn "\n"
let closeComment := lines.getLastD ""
match lines with
| openComment :: copyrightAuthor :: license :: authorsLines =>
-- The header should start and end with blank comments.
match openComment, closeComment with
| "/-", "-/" => output := output
| "/-", _ =>
output := output.push (toSyntax copyright closeComment, s!"{stdText "-/"}")
| _, _ =>
output := output.push (toSyntax copyright openComment, s!"{stdText ("/".push '-')}")
-- Validate the first copyright line.
let copStart := "Copyright (c) 20"
let copStop := ". All rights reserved."
if !copyrightAuthor.startsWith copStart then
output := output.push
(toSyntax copyright (copyrightAuthor.take copStart.length),
s!"Copyright line should start with 'Copyright (c) YYYY'")
let author := (copyrightAuthor.drop (copStart.length + 2))
if output.isEmpty && author.take 1 != " " then
output := output.push
(toSyntax copyright (copyrightAuthor.drop (copStart.length + 2)),
s!"'Copyright (c) YYYY' should be followed by a space")
if output.isEmpty && #["", ".", ","].contains ((author.drop 1).take 1).trim then
output := output.push
(toSyntax copyright (copyrightAuthor.drop (copStart.length + 3)),
s!"There should be at least one copyright author, separated from the year by exactly one space.")
if !copyrightAuthor.endsWith copStop then
output := output.push
(toSyntax copyright (copyrightAuthor.takeRight copStop.length),
s!"Copyright line should end with '. All rights reserved.'")
-- Validate the authors line(s). The last line is the closing comment: trim that off right away.
let authorsLines := authorsLines.dropLast
-- Complain about a missing authors line.
if authorsLines.length == 0 then
output := output.push (toSyntax copyright "-/", s!"Copyright too short!")
else
-- If the list of authors spans multiple lines, all but the last line should end with a trailing
-- comma. This excludes e.g. other comments in the copyright header.
let authorsLine := "\n".intercalate authorsLines
let authorsStart := (("\n".intercalate [openComment, copyrightAuthor, license, ""])).endPos
if authorsLines.length > 1 && !authorsLines.dropLast.all (·.endsWith ",") then
output := output.push ((toSyntax copyright authorsLine),
"If an authors line spans multiple lines, \
each line but the last must end with a trailing comma")
output := output.append (authorsLineChecks authorsLine authorsStart)
let expectedLicense := "Released under Apache 2.0 license as described in the file LICENSE."
if license != expectedLicense then
output := output.push (toSyntax copyright license,
s!"Second copyright line should be \"{expectedLicense}\"")
| _ =>
output := output.push (toSyntax copyright "-/", s!"Copyright too short!")
return output
/--
`isInMathlib modName` returns `true` if `Mathlib.lean` imports the file `modName` and `false`
otherwise.
This is used by the `Header` linter as a heuristic of whether it should inspect the file or not.
-/
def isInMathlib (modName : Name) : IO Bool := do
let mlPath := ("Mathlib" : System.FilePath).addExtension "lean"
if ← mlPath.pathExists then
let res ← parseImports' (← IO.FS.readFile mlPath) ""
return (res.imports.map (·.module == modName)).any (·)
else return false
/-- `inMathlibRef` is
* `none` at initialization time;
* `some true` if the `header` linter has already discovered that the current file
is imported in `Mathlib.lean`;
* `some false` if the `header` linter has already discovered that the current file
is *not* imported in `Mathlib.lean`.
-/
initialize inMathlibRef : IO.Ref (Option Bool) ← IO.mkRef none
/--
The "header" style linter checks that a file starts with
```
import statements*
module doc-string*
remaining file
```
It emits a warning if
* the copyright statement is malformed;
* `Mathlib.Tactic` is imported;
* any import in `Lake` is present;
* the first non-`import` command is not a module doc-string.
The linter allows `import`-only files and does not require a copyright statement in `Mathlib.Init`.
-/
register_option linter.style.header : Bool := {
defValue := false
descr := "enable the header style linter"
}
namespace Style.header
/-- Check the `Syntax` `imports` for broad imports:
`Mathlib.Tactic`, any import starting with `Lake`, or `Mathlib.Tactic.{Have,Replace}`. -/
def broadImportsCheck (imports : Array Syntax) (mainModule : Name) : CommandElabM Unit := do
for i in imports do
match i.getId with
| `Mathlib.Tactic =>
Linter.logLint linter.style.header i "Files in mathlib cannot import the whole tactic folder."
| `Mathlib.Tactic.Replace =>
if mainModule != `Mathlib.Tactic then
Linter.logLint linter.style.header i
"'Mathlib.Tactic.Replace' defines a deprecated form of the 'replace' tactic; \
please do not use it in mathlib."
| `Mathlib.Tactic.Have =>
if ![`Mathlib.Tactic, `Mathlib.Tactic.Replace].contains mainModule then
Linter.logLint linter.style.header i
"'Mathlib.Tactic.Have' defines a deprecated form of the 'have' tactic; \
please do not use it in mathlib."
| modName =>
if modName.getRoot == `Lake then
Linter.logLint linter.style.header i
"In the past, importing 'Lake' in mathlib has led to dramatic slow-downs of the linter \
(see e.g. https://github.com/leanprover-community/mathlib4/pull/13779). Please consider carefully if this import is useful and \
make sure to benchmark it. If this is fine, feel free to silence this linter."
/-- Check the syntax `imports` for syntactically duplicate imports.
The output is an array of `Syntax` atoms whose ranges are the import statements,
and the embedded strings are the error message of the linter.
-/
def duplicateImportsCheck (imports : Array Syntax) : CommandElabM Unit := do
let mut importsSoFar := #[]
for i in imports do
if importsSoFar.contains i then
Linter.logLint linter.style.header i m!"Duplicate imports: '{i}' already imported"
else importsSoFar := importsSoFar.push i
@[inherit_doc Mathlib.Linter.linter.style.header]
def headerLinter : Linter where run := withSetOptionIn fun stx ↦ do
let mainModule ← getMainModule
let inMathlib? := ← match ← inMathlibRef.get with
| some d => return d
| none => do
let val ← isInMathlib mainModule
-- We store the answer to the question "is this file in `Mathlib.lean`?" in `inMathlibRef`
-- to avoid recomputing its value on every command. This is a performance optimisation.
inMathlibRef.set (some val)
return val
-- The linter skips files not imported in `Mathlib.lean`, to avoid linting "scratch files".
-- It is however active in the test files for the linter itself.
unless inMathlib? ||
mainModule == `MathlibTest.Header || mainModule == `MathlibTest.DirectoryDependencyLinter.Test do return
unless getLinterValue linter.style.header (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
-- `Mathlib.lean` imports `Mathlib.Tactic`, which the broad imports check below would flag.
-- Since that file is imports-only, we can simply skip linting it.
if mainModule == `Mathlib then return
let fm ← getFileMap
let md := (getMainModuleDoc (← getEnv)).toArray
-- The end of the first module doc-string, or the end of the file if there is none.
let firstDocModPos := match md[0]? with
| none => fm.positions.back!
| some doc => fm.ofPosition doc.declarationRange.endPos
unless stx.getTailPos?.getD default ≤ firstDocModPos do
return
-- We try to parse the file up to `firstDocModPos`.
let upToStx ← parseUpToHere firstDocModPos <|> (do
-- If parsing failed, there is some command which is not a module docstring.
-- In that case, we parse until the end of the imports and add an extra `section` afterwards,
-- so we trigger a "no module doc-string" warning.
let fil ← getFileName
let (stx, _) ← Parser.parseHeader { inputString := fm.source, fileName := fil, fileMap := fm }
parseUpToHere (stx.raw.getTailPos?.getD default) "\nsection")
let importIds := getImportIds upToStx
-- Report on broad or duplicate imports.
broadImportsCheck importIds mainModule
duplicateImportsCheck importIds
let errors ← directoryDependencyCheck mainModule
if errors.size > 0 then
let mut msgs := ""
for msg in errors do
msgs := msgs ++ "\n\n" ++ (← msg.toString)
Linter.logLint linter.directoryDependency stx msgs.trimLeft
let afterImports := firstNonImport? upToStx
if afterImports.isNone then return
let copyright := match upToStx.getHeadInfo with
| .original lead .. => lead.toString
| _ => ""
-- Report any errors about the copyright line.
if mainModule != `Mathlib.Init then
for (stx, m) in copyrightHeaderChecks copyright do
Linter.logLint linter.style.header stx m!"* '{stx.getAtomVal}':\n{m}\n"
-- Report a missing module doc-string.
match afterImports with
| none => return
| some (.node _ ``Lean.Parser.Command.moduleDoc _) => return
| some rest =>
Linter.logLint linter.style.header rest
m!"The module doc-string for a file should be the first command after the imports.\n\
Please, add a module doc-string before `{stx}`."
initialize addLinter headerLinter
end Style.header
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/UnusedTacticExtension.lean | -- Import this linter explicitly to ensure that
-- this file has a valid copyright header and module docstring.
import Mathlib.Tactic.Linter.Header
/-!
This file defines the environment extension to keep track of which tactics are allowed to leave
the tactic state unchanged and not trigger the unused tactic linter.
-/
open Lean Elab Command
namespace Mathlib.Linter.UnusedTactic
/--
Defines the `allowedUnusedTacticExt` extension for adding a `HashSet` of `allowedUnusedTactic`s
to the environment.
-/
initialize allowedUnusedTacticExt :
SimplePersistentEnvExtension SyntaxNodeKind (Std.HashSet SyntaxNodeKind) ←
registerSimplePersistentEnvExtension {
addImportedFn := fun as => as.foldl Std.HashSet.insertMany {}
addEntryFn := .insert
}
/--
`addAllowedUnusedTactic stxNodes` takes as input a `HashSet` of `SyntaxNodeKind`s and extends the
`allowedUnusedTacticExt` environment extension with its content.
These are tactics that the unused tactic linter will ignore, since they are expected to not change
the tactic state.
See the `#allow_unused_tactic! ids` command for dynamically extending the extension as a user-facing
command.
-/
def addAllowedUnusedTactic {m : Type → Type} [Monad m] [MonadEnv m]
(stxNodes : Std.HashSet SyntaxNodeKind) :
m Unit :=
stxNodes.foldM (init := ()) fun _ d => modifyEnv (allowedUnusedTacticExt.addEntry · d)
/-- `Parser`s allowed to not change the tactic state.
This can be increased dynamically, using `#allow_unused_tactic`.
-/
initialize allowedRef : IO.Ref (Std.HashSet SyntaxNodeKind) ←
IO.mkRef <| .ofArray #[
`Mathlib.Tactic.Says.says,
`Batteries.Tactic.«tacticOn_goal-_=>_»,
`by,
`null,
`«]»,
`Lean.Parser.Tactic.show,
-- the following `SyntaxNodeKind`s play a role in silencing `test`s
`Mathlib.Tactic.successIfFailWithMsg,
`Mathlib.Tactic.failIfNoProgress,
`Mathlib.Tactic.ExtractGoal.extractGoal,
`Mathlib.Tactic.Propose.propose',
`Lean.Parser.Tactic.traceState,
`Mathlib.Tactic.tacticMatch_target_,
`change?,
`«tactic#adaptation_note_»,
`tacticSleep_heartbeats_,
`Mathlib.Tactic.«tacticRename_bvar_→__»
]
/--
`#allow_unused_tactic` takes as input a space-separated list of identifiers.
These identifiers are then allowed by the unused tactic linter:
even if these tactics do not modify goals, there will be no warning emitted.
Note: for this to work, these identifiers should be the `SyntaxNodeKind` of each tactic.
For instance, you can allow the `done` and `skip` tactics using
```lean
#allow_unused_tactic Lean.Parser.Tactic.done Lean.Parser.Tactic.skip
```
This change is file-local. If you want a *persistent* change, then use the `!`-flag:
the command `#allow_unused_tactic! ids` makes the change the linter continues to ignore these
tactics also in files importing a file where this command is issued.
The command `#show_kind tac` may help to find the `SyntaxNodeKind`.
-/
elab "#allow_unused_tactic" pers:("!")? ppSpace colGt ids:ident* : command => do
try
let ids ← liftCoreM do ids.mapM realizeGlobalConstNoOverload
if pers.isSome then
addAllowedUnusedTactic (.ofArray ids)
else
allowedRef.modify (·.insertMany ids)
catch e => match e with
| .error ref md =>
logErrorAt ref (md ++ m!"\n\
The command `#show_kind {ref}` may help to find the correct `SyntaxNodeKind`.")
| _ => logError e.toMessageData
/--
`#show_kind tac` takes as input the syntax of a tactic and returns the `SyntaxNodeKind`
at the head of the tactic syntax tree.
The input syntax needs to parse, though it can be *extremely* elided.
For instance, to see the `SyntaxNodeKind` of the `refine` tactic, you could use
```lean
#show_kind refine _
```
The trailing underscore `_` makes the syntax valid, since `refine` expects something else.
-/
elab "#show_kind " t:tactic : command => do
let stx ← `(tactic| $t)
Lean.logInfoAt t m!"The `SyntaxNodeKind` is '{stx.raw.getKind}'."
end Mathlib.Linter.UnusedTactic |
.lake/packages/mathlib/Mathlib/Tactic/Linter/CommandStart.lean | import Mathlib.Tactic.Linter.Header
/-!
# The `commandStart` linter
The `commandStart` linter emits a warning if
* either a command does not start at the beginning of a line;
* or the "hypotheses segment" of a declaration does not coincide with its pretty-printed version.
-/
open Lean Elab Command Linter
namespace Mathlib.Linter
/--
The `commandStart` linter emits a warning if
* either a command does not start at the beginning of a line;
* or the "hypotheses segment" of a declaration does not coincide with its pretty-printed version.
In practice, this makes sure that the spacing in a typical declaration looks like
```lean
example (a : Nat) {R : Type} [Add R] : <not linted part>
```
as opposed to
```lean
example (a: Nat) {R:Type} [Add R] : <not linted part>
```
-/
register_option linter.style.commandStart : Bool := {
defValue := false
descr := "enable the commandStart linter"
}
/-- If the `linter.style.commandStart.verbose` option is `true`, the `commandStart` linter
reports some helpful diagnostic information. -/
register_option linter.style.commandStart.verbose : Bool := {
defValue := false
descr := "enable the commandStart linter"
}
/--
`CommandStart.endPos stx` returns the position up until the `commandStart` linter checks the
formatting.
This is every declaration until the type-specification, if there is one, or the value,
as well as all `variable` commands.
-/
def CommandStart.endPos (stx : Syntax) : Option String.Pos.Raw :=
if let some cmd := stx.find? (#[``Parser.Command.declaration, `lemma].contains ·.getKind) then
if let some ind := cmd.find? (·.isOfKind ``Parser.Command.inductive) then
match ind.find? (·.isOfKind ``Parser.Command.optDeclSig) with
| none => dbg_trace "unreachable?"; none
| some sig => sig.getTailPos?
else
match cmd.find? (·.isOfKind ``Parser.Term.typeSpec) with
| some s => s[0].getTailPos? -- `s[0]` is the `:` separating hypotheses and the type
| none => match cmd.find? (·.isOfKind ``Parser.Command.declValSimple) with
| some s => s.getPos?
| none => none
else if stx.isOfKind ``Parser.Command.variable || stx.isOfKind ``Parser.Command.omit then
stx.getTailPos?
else none
/--
A `FormatError` is the main structure tracking how some surface syntax differs from its
pretty-printed version.
In case of deviations, it contains the deviation's location within an ambient string.
-/
-- Some of the information contained in `FormatError` is redundant, however, it is useful to convert
-- between the `String.pos` and `String` length conveniently.
structure FormatError where
/-- The distance to the end of the source string, as number of characters -/
srcNat : Nat
/-- The distance to the end of the source string, as number of string positions -/
srcEndPos : String.Pos.Raw
/-- The distance to the end of the formatted string, as number of characters -/
fmtPos : Nat
/-- The kind of formatting error. For example: `extra space`, `remove line break` or
`missing space`.
Strings starting with `Oh no` indicate an internal error.
-/
msg : String
/-- The length of the mismatch, as number of characters. -/
length : Nat
/-- The starting position of the mismatch, as a `String.pos`. -/
srcStartPos : String.Pos.Raw
deriving Inhabited
instance : ToString FormatError where
toString f :=
s!"srcNat: {f.srcNat}, srcPos: {f.srcEndPos}, fmtPos: {f.fmtPos}, \
msg: {f.msg}, length: {f.length}\n"
/--
Produces a `FormatError` from the input data. It expects
* `ls` to be a "user-typed" string;
* `ms` to be a "pretty-printed" string;
* `msg` to be a custom error message, such as `extra space` or `remove line break`;
* `length` (optional with default `1`), how many characters the error spans.
In particular, it extracts the position information within the string, both as number of characters
and as `String.Pos`.
-/
def mkFormatError (ls ms : String) (msg : String) (length : Nat := 1) : FormatError where
srcNat := ls.length
srcEndPos := ls.endPos
fmtPos := ms.length
msg := msg
length := length
srcStartPos := ls.endPos
/--
Add a new `FormatError` `f` to the array `fs`, trying, as much as possible, to merge the new
`FormatError` with the last entry of `fs`.
-/
def pushFormatError (fs : Array FormatError) (f : FormatError) : Array FormatError :=
-- If there are no errors already, we simply add the new one.
if fs.isEmpty then fs.push f else
let back := fs.back!
-- If the latest error is of a different kind than the new one, we simply add the new one.
if back.msg != f.msg || back.srcNat - back.length != f.srcNat then fs.push f else
-- Otherwise, we are adding a further error of the same kind and we therefore merge the two.
fs.pop.push {back with length := back.length + f.length, srcStartPos := f.srcEndPos}
/--
Scan the two input strings `L` and `M`, assuming `M` is the pretty-printed version of `L`.
This almost means that `L` and `M` only differ in whitespace.
While scanning the two strings, accumulate any discrepancies --- with some heuristics to avoid
flagging some line-breaking changes.
(The pretty-printer does not always produce desirably formatted code.)
-/
partial
def parallelScanAux (as : Array FormatError) (L M : String) : Array FormatError :=
if M.trim.isEmpty then as else
-- We try as hard as possible to scan the strings one character at a time.
-- However, single line comments introduced with `--` pretty-print differently than `/--`.
-- So, we first look ahead for `/--`: the linter will later ignore doc-strings, so it does not
-- matter too much what we do here and we simply drop `/--` from the original string and the
-- pretty-printed one, before continuing.
-- Next, if we already dealt with `/--`, finding a `--` means that this is a single line comment
-- (or possibly a comment embedded in a doc-string, which is ok, since we eventually discard
-- doc-strings). In this case, we drop everything until the following line break in the
-- original syntax, and for the same amount of characters in the pretty-printed one, since the
-- pretty-printer *erases* the line break at the end of a single line comment.
if L.take 3 == "/--" && M.take 3 == "/--" then
parallelScanAux as (L.drop 3) (M.drop 3) else
if L.take 2 == "--" then
let newL := L.dropWhile (· != '\n')
let diff := L.length - newL.length
-- Assumption: if `L` contains an embedded inline comment, so does `M`
-- (modulo additional whitespace).
-- This holds because we call this function with `M` being a pretty-printed version of `L`.
-- If the pretty-printer changes in the future, this code may need to be adjusted.
let newM := M.dropWhile (· != '-') |>.drop diff
parallelScanAux as newL.trimLeft newM.trimLeft else
if L.take 2 == "-/" then
let newL := L.drop 2 |>.trimLeft
let newM := M.drop 2 |>.trimLeft
parallelScanAux as newL newM else
let ls := L.drop 1
let ms := M.drop 1
match L.front, M.front with
| ' ', m =>
if m.isWhitespace then
parallelScanAux as ls ms.trimLeft
else
parallelScanAux (pushFormatError as (mkFormatError L M "extra space")) ls M
| '\n', m =>
if m.isWhitespace then
parallelScanAux as ls.trimLeft ms.trimLeft
else
parallelScanAux (pushFormatError as (mkFormatError L M "remove line break")) ls.trimLeft M
| l, m => -- `l` is not whitespace
if l == m then
parallelScanAux as ls ms
else
if m.isWhitespace then
parallelScanAux (pushFormatError as (mkFormatError L M "missing space")) L ms.trimLeft
else
-- If this code is reached, then `L` and `M` differ by something other than whitespace.
-- This should not happen in practice.
pushFormatError as (mkFormatError ls ms "Oh no! (Unreachable?)")
@[inherit_doc parallelScanAux]
def parallelScan (src fmt : String) : Array FormatError :=
parallelScanAux ∅ src fmt
namespace Style.CommandStart
/--
`unlintedNodes` contains the `SyntaxNodeKind`s for which there is no clear formatting preference:
if they appear in surface syntax, the linter will ignore formatting.
Currently, the unlined nodes are mostly related to `Subtype`, `Set` and `Finset` notation and
list notation.
-/
abbrev unlintedNodes := #[
-- # set-like notations, have extra spaces around the braces `{` `}`
-- subtype, the pretty-printer prefers `{ a // b }`
``«term{_:_//_}»,
-- set notation, the pretty-printer prefers `{ a | b }`
`«term{_}»,
-- empty set, the pretty-printer prefers `{ }`
``«term{}»,
-- set builder notation, the pretty-printer prefers `{ a : X | p a }`
`Mathlib.Meta.setBuilder,
-- # misc exceptions
-- We ignore literal strings.
`str,
-- list notation, the pretty-printer prefers `a :: b`
``«term_::_»,
-- negation, the pretty-printer prefers `¬a`
``«term¬_»,
-- declaration name, avoids dealing with guillemets pairs `«»`
``Parser.Command.declId,
`Mathlib.Tactic.superscriptTerm, `Mathlib.Tactic.subscript,
-- notation for `Bundle.TotalSpace.proj`, the total space of a bundle
-- the pretty-printer prefers `π FE` over `π F E` (which we want)
`Bundle.termπ__,
-- notation for `Finset.slice`, the pretty-printer prefers `𝒜 #r` over `𝒜 # r` (mathlib style)
`Finset.«term_#_»,
-- The docString linter already takes care of formatting doc-strings.
``Parser.Command.docComment,
-- The pretty-printer adds a space between the backticks and the actual name.
``Parser.Term.doubleQuotedName,
]
/--
Given an array `a` of `SyntaxNodeKind`s, we accumulate the ranges of the syntax nodes of the
input syntax whose kind is in `a`.
The linter uses this information to avoid emitting a warning for nodes with kind contained in
`unlintedNodes`.
-/
def getUnlintedRanges (a : Array SyntaxNodeKind) :
Std.HashSet String.Range → Syntax → Std.HashSet String.Range
| curr, s@(.node _ kind args) =>
let new := args.foldl (init := curr) (·.union <| getUnlintedRanges a curr ·)
if a.contains kind then
new.insert (s.getRange?.getD default)
else
new
-- We special case `where` statements, since they may be followed by an indented doc-string.
| curr, .atom info "where" =>
if let some trail := info.getRangeWithTrailing? then
curr.insert trail
else
curr
| curr, _ => curr
/-- Given a `HashSet` of `String.Range`s `rgs` and a further `String.Range` `rg`,
`isOutside rgs rg` returns `false` if and only if `rgs` contains a range that completely contains
`rg`.
The linter uses this to figure out which nodes should be ignored.
-/
def isOutside (rgs : Std.HashSet String.Range) (rg : String.Range) : Bool :=
rgs.all fun {start := a, stop := b} ↦ !(a ≤ rg.start && rg.stop ≤ b)
/-- `mkWindow orig start ctx` extracts from `orig` a string that starts at the first
non-whitespace character before `start`, then expands to cover `ctx` more characters
and continues still until the first non-whitespace character.
In essence, it extracts the substring of `orig` that begins at `start`, continues for `ctx`
characters plus expands left and right until it encounters the first whitespace character,
to avoid cutting into "words".
*Note*. `start` is the number of characters *from the right* where our focus is!
-/
def mkWindow (orig : String) (start ctx : Nat) : String :=
let head := orig.dropRight (start + 1) -- `orig`, up to one character before the discrepancy
let middle := orig.takeRight (start + 1)
let headCtx := head.takeRightWhile (!·.isWhitespace)
let tail := middle.drop ctx |>.takeWhile (!·.isWhitespace)
s!"{headCtx}{middle.take ctx}{tail}"
@[inherit_doc Mathlib.Linter.linter.style.commandStart]
def commandStartLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless Linter.getLinterValue linter.style.commandStart (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
if stx.find? (·.isOfKind ``runCmd) |>.isSome then
return
-- If a command does not start on the first column, emit a warning.
if let some pos := stx.getPos? then
let colStart := ((← getFileMap).toPosition pos).column
if colStart ≠ 0 then
Linter.logLint linter.style.commandStart stx
m!"'{stx}' starts on column {colStart}, \
but all commands should start at the beginning of the line."
-- We skip `macro_rules`, since they cause parsing issues.
if stx.find? (·.isOfKind `Lean.Parser.Command.macro_rules) |>.isSome then
return
let some upTo := CommandStart.endPos stx | return
let fmt : Option Format := ←
try
liftCoreM <| PrettyPrinter.ppCategory `command stx
catch _ =>
Linter.logLintIf linter.style.commandStart.verbose (stx.getHead?.getD stx)
m!"The `commandStart` linter had some parsing issues: \
feel free to silence it and report this error!"
return none
if let some fmt := fmt then
let st := fmt.pretty
let origSubstring := stx.getSubstring?.getD default
let orig := origSubstring.toString
let scan := parallelScan orig st
let docStringEnd := stx.find? (·.isOfKind ``Parser.Command.docComment) |>.getD default
let docStringEnd := docStringEnd.getTailPos? |>.getD default
let forbidden := getUnlintedRanges unlintedNodes ∅ stx
for s in scan do
let center := origSubstring.stopPos.unoffsetBy s.srcEndPos
let rg : String.Range := ⟨center, center |>.offsetBy s.srcEndPos |>.unoffsetBy s.srcStartPos |>.increaseBy 1⟩
if s.msg.startsWith "Oh no" then
Linter.logLintIf linter.style.commandStart.verbose (.ofRange rg)
m!"This should not have happened: please report this issue!"
Linter.logLintIf linter.style.commandStart.verbose (.ofRange rg)
m!"Formatted string:\n{fmt}\nOriginal string:\n{origSubstring}"
continue
unless isOutside forbidden rg do
continue
unless rg.stop ≤ upTo do return
unless docStringEnd ≤ rg.start do return
let ctx := 4 -- the number of characters after the mismatch that linter prints
let srcWindow := mkWindow orig s.srcNat (ctx + s.length)
let expectedWindow := mkWindow st s.fmtPos (ctx + (1))
Linter.logLint linter.style.commandStart (.ofRange rg)
m!"{s.msg} in the source\n\n\
This part of the code\n '{srcWindow}'\n\
should be written as\n '{expectedWindow}'\n"
Linter.logLintIf linter.style.commandStart.verbose (.ofRange rg)
m!"Formatted string:\n{fmt}\nOriginal string:\n{origSubstring}"
initialize addLinter commandStartLinter
end Style.CommandStart
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/DeprecatedModule.lean | import Std.Time.Format
import Mathlib.Init
/-!
# The `deprecated.module` linter
The `deprecated.module` linter emits a warning when a file that has been renamed or split
is imported.
The usage is as follows. Write
```lean
import B
...
import Z
deprecated_module "Optional string here with further details" (since := "yyyy-mm-dd")
```
in module `A` with the expectation that `A` contains nothing else.
This triggers the `deprecated.module` linter to notify every file with `import A`
to instead import the *direct imports* of `A`, that is `B, ..., Z`.
-/
open Lean Elab Command Linter
namespace Mathlib.Linter
/--
The `deprecated.module` linter emits a warning when a file that has been renamed or split
is imported.
The default value is `true`, since this linter is designed to warn projects downstream of `Mathlib`
of refactors and deprecations in `Mathlib` itself.
-/
register_option linter.deprecated.module : Bool := {
defValue := true
descr := "enable the `deprecated.module` linter"
}
/--
Defines the `deprecatedModuleExt` extension for adding a `HashSet` of triples of
* a module `Name` that has been deprecated and
* an array of `Name`s of modules that should be imported instead
* an optional `String` containing further messages to be displayed with the deprecation
to the environment.
-/
initialize deprecatedModuleExt :
SimplePersistentEnvExtension
(Name × Array Name × Option String) (Std.HashSet (Name × Array Name × Option String)) ←
registerSimplePersistentEnvExtension {
addImportedFn := (·.foldl Std.HashSet.insertMany {})
addEntryFn := .insert
}
/--
`addModuleDeprecation` adds to the `deprecatedModuleExt` extension the pair consisting of the
current module name and the array of its direct imports.
It ignores the `Init` import, since this is a special module that is expected to be imported
by all files.
It also ignores the `Mathlib/Tactic/Linter/DeprecatedModule.lean` import (namely, the current file),
since there is no need to import this module.
-/
def addModuleDeprecation {m : Type → Type} [Monad m] [MonadEnv m]
(msg? : Option String) : m Unit := do
let modName ← getMainModule
modifyEnv (deprecatedModuleExt.addEntry ·
(modName, (← getEnv).imports.filterMap fun i ↦
if i.module == `Init ||
i.module == `Mathlib.Tactic.Linter.DeprecatedModule then none else i.module, msg?))
/--
`deprecated_module "Optional string" (since := "yyyy-mm-dd")` deprecates the current module `A`
in favour of its direct imports.
This means that any file that directly imports `A` will get a notification on the `import A` line
suggesting to instead import the *direct imports* of `A`.
-/
elab (name := deprecated_modules)
"deprecated_module " msg?:(str ppSpace)? "(" &"since " ":= " date:str ")" : command => do
if let .error _parsedDate := Std.Time.PlainDate.fromLeanDateString date.getString then
throwError "Invalid date: the expected format is \"{← Std.Time.PlainDate.now}\""
addModuleDeprecation <| msg?.map (·.getString)
-- Disable the linter, so that it does not complain in the file with the deprecation.
elabCommand <| mkNullNode #[← `(set_option linter.style.header false),
← `(set_option linter.deprecated.module false)]
/--
A utility command to show the current entries of the `deprecatedModuleExt` in the format:
```
Deprecated modules
'MathlibTest.DeprecatedModule' deprecates to
#[Mathlib.Tactic.Linter.DocPrime, Mathlib.Tactic.Linter.DocString]
with message 'We can also give more details about the deprecation'
...
```
-/
elab "#show_deprecated_modules" : command => do
let directImports := deprecatedModuleExt.getState (← getEnv)
logInfo <| "\n".intercalate <|
directImports.fold (init := ["Deprecated modules\n"]) fun nms (i, deps, msg?) ↦
let msg := match msg? with | some str => s!"message '{str}'" | none => "no message"
nms ++ [s!"'{i}' deprecates to\n{deps}\nwith {msg}\n"]
namespace DeprecatedModule
/--
`IsLaterCommand` is an `IO.Ref` that starts out being `false`.
As soon as a (non-import) command in a file is processed, the `deprecated.module` linter`
sets it to `true`.
If it is `false`, then the `deprecated.module` linter will check for deprecated modules.
This is used to ensure that the linter performs the deprecation checks only once per file.
There are possible concurrency issues, but they should not be particularly worrying:
* the linter check should be relatively quick;
* the only way in which the linter could change what it reports is if the imports are changed
and a change in imports triggers a rebuild of the whole file anyway, resetting the `IO.Ref`.
-/
initialize IsLaterCommand : IO.Ref Bool ← IO.mkRef false
@[inherit_doc Mathlib.Linter.linter.deprecated.module]
def deprecated.moduleLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.deprecated.module (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
let laterCommand ← IsLaterCommand.get
-- If `laterCommand` is `true`, then the linter already did what it was supposed to do.
-- If `laterCommand` is `false` at the end of file, the file is an import-only file and
-- the linter should not do anything.
if laterCommand || (Parser.isTerminalCommand stx && !laterCommand) then
return
IsLaterCommand.set true
let deprecations := deprecatedModuleExt.getState (← getEnv)
if deprecations.isEmpty then
return
if stx.isOfKind ``Linter.deprecated_modules then return
let fm ← getFileMap
let (importStx, _) ←
Parser.parseHeader { inputString := fm.source, fileName := ← getFileName, fileMap := fm }
let modulesWithNames := (getImportIds importStx).map fun i ↦ (i, i.getId)
for (i, preferred, msg?) in deprecations do
for (nmStx, _) in modulesWithNames.filter (·.2 == i) do
Linter.logLint linter.deprecated.module nmStx
m!"{msg?.getD ""}\n\
'{nmStx}' has been deprecated: please replace this import by\n\n\
{String.join (preferred.foldl (·.push s!"import {·}\n") #[]).toList}"
initialize addLinter deprecated.moduleLinter
end DeprecatedModule
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/OldObtain.lean | import Lean.Elab.Command
-- Import this linter explicitly to ensure that
-- this file has a valid copyright header and module docstring.
import Mathlib.Tactic.Linter.Header
/-!
# The `oldObtain` linter, against stream-of-consciousness `obtain`
The `oldObtain` linter flags any occurrences of "stream-of-consciousness" `obtain`,
i.e. uses of the `obtain` tactic which do not immediately provide a proof.
## Example
There are six different kinds of `obtain` uses. In one example, they look like this.
```
theorem foo : True := by
-- These cases are fine.
obtain := trivial
obtain h := trivial
obtain : True := trivial
obtain h : True := trivial
-- These are linted against.
obtain : True
· trivial
obtain h : True
· trivial
```
We allow the first four (since an explicit proof is provided), but lint against the last two.
## Why is this bad?
This is similar to removing all uses of `Tactic.Replace` and `Tactic.Have`
from mathlib: in summary,
- this version is a Lean3-ism, which can be unlearned now
- the syntax `obtain foo : type := proof` is slightly shorter;
particularly so when the first tactic of the proof is `exact`
- when using the old syntax as `obtain foo : type; · proof`, there is an intermediate state with
multiple goals right before the focusing dot. This can be confusing.
(This gets amplified with the in-flight "multiple goal linter", which seems generally desired ---
for many reasons, including teachability. Granted, the linter could be tweaked to not lint in this
case... but by now, the "old" syntax is not clearly better.)
- the old syntax *could* be slightly nicer when deferring goals: however, this is rare.
In the 30 replacements of the last PR, this occurred twice. In both cases, the `suffices` tactic
could also be used, as was in fact clearer. -/
open Lean Elab Linter
namespace Mathlib.Linter.Style
/-- Whether a syntax element is an `obtain` tactic call without a provided proof. -/
def isObtainWithoutProof : Syntax → Bool
-- Using the `obtain` tactic without a proof requires proving a type;
-- a pattern is optional.
| `(tactic|obtain : $_type) | `(tactic|obtain $_pat : $_type) => true
| _ => false
/-- The `oldObtain` linter emits a warning upon uses of the "stream-of-consciousness" variants
of the `obtain` tactic, i.e. with the proof postponed. -/
register_option linter.oldObtain : Bool := {
defValue := false
descr := "enable the `oldObtain` linter"
}
/-- The `oldObtain` linter: see docstring above -/
def oldObtainLinter : Linter where run := withSetOptionIn fun stx => do
unless getLinterValue linter.oldObtain (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
if let some head := stx.find? isObtainWithoutProof then
Linter.logLint linter.oldObtain head m!"Please remove stream-of-consciousness `obtain` syntax"
initialize addLinter oldObtainLinter
end Mathlib.Linter.Style |
.lake/packages/mathlib/Mathlib/Tactic/Linter/HaveLetLinter.lean | import Mathlib.Init
import Lean.Elab.Command
import Lean.Server.InfoUtils
import Mathlib.Tactic.DeclarationNames
/-!
# The `have` vs `let` linter
The `have` vs `let` linter flags uses of `have` to introduce a hypothesis whose Type is not `Prop`.
The option for this linter is a natural number, but really there are only 3 settings:
* `0` -- inactive;
* `1` -- active only on noisy declarations;
* `2` or more -- always active.
TODO:
* Also lint `let` vs `have`.
* `haveI` may need to change to `let/letI`?
* `replace`, `classical!`, `classical`, `tauto` internally use `have`:
should the linter act on them as well?
-/
open Lean Elab Command Meta
namespace Mathlib.Linter
/-- The `have` vs `let` linter emits a warning on `have`s introducing a hypothesis whose
Type is not `Prop`.
There are three settings:
* `0` -- inactive;
* `1` -- active only on noisy declarations;
* `2` or more -- always active.
The default value is `1`.
-/
register_option linter.haveLet : Nat := {
defValue := 0
descr := "enable the `have` vs `let` linter:\n\
* 0 -- inactive;\n\
* 1 -- active only on noisy declarations;\n\
* 2 or more -- always active."
}
namespace haveLet
/-- find the `have` syntax. -/
def isHave? : Syntax → Bool
| .node _ ``Lean.Parser.Tactic.tacticHave__ _ => true
| _ => false
end haveLet
end Mathlib.Linter
namespace Mathlib.Linter.haveLet
/-- a monadic version of `Lean.Elab.InfoTree.foldInfo`.
Used to infer types inside a `CommandElabM`. -/
def InfoTree.foldInfoM {α m} [Monad m] (f : ContextInfo → Info → α → m α) (init : α) :
InfoTree → m α :=
InfoTree.foldInfo (fun ctx i ma => do f ctx i (← ma)) (pure init)
/-- given a `ContextInfo`, a `LocalContext` and an `Array` of `Expr`essions `es` with a `Name`,
`toFormat_propTypes` creates a `MetaM` context, and returns an array of
the pretty-printed `Format` of `e`, together with the (unchanged) name
for each `Expr`ession `e` in `es` whose type is a `Prop`.
Concretely, `toFormat_propTypes` runs `inferType` in `CommandElabM`.
This is the kind of monadic lift that `nonPropHaves` uses to decide whether the Type of a `have`
is in `Prop` or not.
The output `Format` is just so that the linter displays a better message. -/
def toFormat_propTypes (ctx : ContextInfo) (lc : LocalContext) (es : Array (Expr × Name)) :
CommandElabM (Array (Format × Name)) := do
ctx.runMetaM lc do
es.filterMapM fun (e, name) ↦ do
let typ ← inferType (← instantiateMVars e)
if typ.isProp then return none else return (← ppExpr e, name)
/-- returns the `have` syntax whose corresponding hypothesis does not have Type `Prop` and
also a `Format`ted version of the corresponding Type. -/
partial
def nonPropHaves : InfoTree → CommandElabM (Array (Syntax × Format)) :=
InfoTree.foldInfoM (init := #[]) fun ctx info args => return args ++ (← do
let .ofTacticInfo i := info | return #[]
let stx := i.stx
let .original .. := stx.getHeadInfo | return #[]
unless isHave? stx do return #[]
let mctx := i.mctxAfter
let mvdecls := i.goalsAfter.filterMap (mctx.decls.find? ·)
-- We extract the `MetavarDecl` with largest index after a `have`, since this one
-- holds information about the metavariable where `have` introduces the new hypothesis,
-- and determine the relevant `LocalContext`.
let lc := mvdecls.toArray.getMax? (·.index < ·.index) |>.getD default |>.lctx
-- we also accumulate all `fvarId`s from all local contexts before the use of `have`
-- so that we can then isolate the `fvarId`s that are created by `have`
let oldMvdecls := i.goalsBefore.filterMap (mctx.decls.find? ·)
let oldFVars := (oldMvdecls.map (·.lctx.decls.toList.reduceOption)).flatten.map (·.fvarId)
-- `newDecls` are the local declarations whose `FVarID` did not exist before the `have`.
-- Effectively they are the declarations that we want to test for being in `Prop` or not.
let newDecls := lc.decls.toList.reduceOption.filter (! oldFVars.contains ·.fvarId)
-- Now, we get the `MetaM` state up and running to find the types of each entry of `newDecls`.
-- For each entry which is a `Type`, we print a warning on `have`.
let fmts ← toFormat_propTypes ctx lc (newDecls.map (fun e ↦ (e.type, e.userName))).toArray
return fmts.map fun (fmt, na) ↦ (stx, f!"{na} : {fmt}"))
/-- The main implementation of the `have` vs `let` linter. -/
def haveLetLinter : Linter where run := withSetOptionIn fun _stx => do
let gh := linter.haveLet.get (← getOptions)
unless gh != 0 && (← getInfoState).enabled do
return
unless gh == 1 && (← MonadState.get).messages.unreported.isEmpty do
let trees ← getInfoTrees
for t in trees do
for (s, fmt) in ← nonPropHaves t do
logLint0Disable linter.haveLet s
m!"'{fmt}' is a Type and not a Prop. Consider using 'let' instead of 'have'."
initialize addLinter haveLetLinter
end haveLet
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/Style.lean | import Lean.Elab.Command
import Lean.Server.InfoUtils
-- Import this linter explicitly to ensure that
-- this file has a valid copyright header and module docstring.
import Mathlib.Tactic.Linter.Header
import Mathlib.Tactic.DeclarationNames
/-!
## Style linters
This file contain linters about stylistic aspects: these are only about coding style,
but do not affect correctness nor global coherence of mathlib.
Historically, some of these were ported from the `lint-style.py` Python script.
This file defines the following linters:
- the `setOption` linter checks for the presence of `set_option` commands activating
options disallowed in mathlib: these are meant to be temporary, and not for polished code.
It also checks for `maxHeartbeats` options being present which are not scoped to single commands.
- the `missingEnd` linter checks for sections or namespaces which are not closed by the end
of the file: enforcing this invariant makes minimising files or moving code between files easier
- the `cdotLinter` linter checks for focusing dots `·` which are typed using a `.` instead:
this is allowed Lean syntax, but it is nicer to be uniform
- the `dollarSyntax` linter checks for use of the dollar sign `$` instead of the `<|` pipe operator:
similarly, both symbols have the same meaning, but mathlib prefers `<|` for the symmetry with
the `|>` symbol
- the `lambdaSyntax` linter checks for uses of the `λ` symbol for anonymous functions,
instead of the `fun` keyword: mathlib prefers the latter for reasons of readability
- the `longFile` linter checks for files which have more than 1500 lines
- the `longLine` linter checks for lines which have more than 100 characters
- the `openClassical` linter checks for `open (scoped) Classical` statements which are not
scoped to a single declaration
- the `show` linter checks for `show`s that change the goal and should be replaced by `change`
All of these linters are enabled in mathlib by default, but disabled globally
since they enforce conventions which are inherently subjective.
-/
open Lean Parser Elab Command Meta Linter
namespace Mathlib.Linter
/-- The `setOption` linter emits a warning on a `set_option` command, term or tactic
which sets a `pp`, `profiler` or `trace` option.
It also warns on an option containing `maxHeartbeats`
(as these should be scoped as `set_option ... in` instead). -/
register_option linter.style.setOption : Bool := {
defValue := false
descr := "enable the `setOption` linter"
}
namespace Style.setOption
/-- Whether a syntax element is a `set_option` command, tactic or term:
Return the name of the option being set, if any. -/
def parseSetOption : Syntax → Option Name
-- This handles all four possibilities of `_val`: a string, number, `true` and `false`.
| `(command|set_option $name:ident $_val) => some name.getId
| `(set_option $name:ident $_val in $_x) => some name.getId
| `(tactic|set_option $name:ident $_val in $_x) => some name.getId
| _ => none
/-- Whether a given piece of syntax is a `set_option` command, tactic or term. -/
def isSetOption : Syntax → Bool :=
fun stx ↦ parseSetOption stx matches some _name
/-- The `setOption` linter: this lints any `set_option` command, term or tactic
which sets a `debug`, `pp`, `profiler` or `trace` option.
This also warns if an option containing `maxHeartbeats` (typically, the `maxHeartbeats` or
`synthInstance.maxHeartbeats` option) is set.
**Why is this bad?** The `debug`, `pp`, `profiler` and `trace` options are good for debugging,
but should not be used in production code.
`maxHeartbeats` options should be scoped as `set_option opt in ...` (and be followed by a comment
explaining the need for them; another linter enforces this).
**How to fix this?** The `maxHeartbeats` options can be scoped to individual commands, if they
are truly necessary.
The `debug`, `pp`, `profiler` and `trace` are usually not necessary for production code,
so you can simply remove them. (Some tests will intentionally use one of these options;
in this case, simply allow the linter.)
-/
def setOptionLinter : Linter where run := withSetOptionIn fun stx => do
unless getLinterValue linter.style.setOption (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
if let some head := stx.find? isSetOption then
if let some name := parseSetOption head then
let forbidden := [`debug, `pp, `profiler, `trace]
if forbidden.contains name.getRoot then
Linter.logLint linter.style.setOption head
m!"Setting options starting with '{"', '".intercalate (forbidden.map (·.toString))}' \
is only intended for development and not for final code. \
If you intend to submit this contribution to the Mathlib project, \
please remove 'set_option {name}'."
else if name.components.contains `maxHeartbeats then
Linter.logLint linter.style.setOption head m!"Unscoped option {name} is not allowed:\n\
Please scope this to individual declarations, as in\n```\nset_option {name} in\n\
-- comment explaining why this is necessary\n\
example : ... := ...\n```"
initialize addLinter setOptionLinter
end Style.setOption
/-!
# The "missing end" linter
The "missing end" linter emits a warning on non-closed `section`s and `namespace`s.
It allows the "outermost" `noncomputable section` to be left open (whether or not it is named).
-/
open Lean Elab Command
/-- The "missing end" linter emits a warning on non-closed `section`s and `namespace`s.
It allows the "outermost" `noncomputable section` to be left open (whether or not it is named).
-/
register_option linter.style.missingEnd : Bool := {
defValue := false
descr := "enable the missing end linter"
}
namespace Style.missingEnd
@[inherit_doc Mathlib.Linter.linter.style.missingEnd]
def missingEndLinter : Linter where run := withSetOptionIn fun stx ↦ do
-- Only run this linter at the end of a module.
unless stx.isOfKind ``Lean.Parser.Command.eoi do return
if getLinterValue linter.style.missingEnd (← getLinterOptions) &&
!(← MonadState.get).messages.hasErrors then
let sc ← getScopes
-- The last scope is always the "base scope", corresponding to no active `section`s or
-- `namespace`s. We are interested in any *other* unclosed scopes.
if sc.length == 1 then return
let ends := sc.dropLast.map fun s ↦ (s.header, s.isNoncomputable)
-- If the outermost scope corresponds to a `noncomputable section`, we ignore it.
let ends := if ends.getLast!.2 then ends.dropLast else ends
-- If there are any further un-closed scopes, we emit a warning.
if !ends.isEmpty then
let ending := (ends.map Prod.fst).foldl (init := "") fun a b ↦
a ++ s!"\n\nend{if b == "" then "" else " "}{b}"
Linter.logLint linter.style.missingEnd stx
m!"unclosed sections or namespaces; expected: '{ending}'"
initialize addLinter missingEndLinter
end Style.missingEnd
/-!
### The `cdot` linter
The `cdot` linter is a syntax-linter that flags uses of the "cdot" `·` that are achieved
by typing a character different from `·`.
For instance, a "plain" dot `.` is allowed syntax, but is flagged by the linter.
It also flags "isolated cdots", i.e. when the `·` is on its own line.
-/
/--
The `cdot` linter flags uses of the "cdot" `·` that are achieved by typing a character
different from `·`.
For instance, a "plain" dot `.` is allowed syntax, but is flagged by the linter.
It also flags "isolated cdots", i.e. when the `·` is on its own line. -/
register_option linter.style.cdot : Bool := {
defValue := false
descr := "enable the `cdot` linter"
}
/-- `isCDot? stx` checks whether `stx` is a `Syntax` node corresponding to a `cdot` typed with
the character `·`. -/
def isCDot? : Syntax → Bool
| .node _ ``cdotTk #[.node _ `patternIgnore #[.node _ _ #[.atom _ v]]] => v == "·"
| .node _ ``Lean.Parser.Term.cdot #[.atom _ v, _] => v == "·"
| _ => false
/--
`findCDot stx` extracts from `stx` the syntax nodes of `kind` `Lean.Parser.Term.cdot` or `cdotTk`.
-/
partial
def findCDot : Syntax → Array Syntax
| stx@(.node _ kind args) =>
let dargs := (args.map findCDot).flatten
match kind with
| ``Lean.Parser.Term.cdot | ``cdotTk => dargs.push stx
| _ => dargs
|_ => #[]
/-- `unwanted_cdot stx` returns an array of syntax atoms within `stx`
corresponding to `cdot`s that are not written with the character `·`.
This is precisely what the `cdot` linter flags.
-/
def unwanted_cdot (stx : Syntax) : Array Syntax :=
(findCDot stx).filter (!isCDot? ·)
namespace Style
@[inherit_doc linter.style.cdot]
def cdotLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.style.cdot (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
for s in unwanted_cdot stx do
Linter.logLint linter.style.cdot s
m!"Please, use '·' (typed as `\\.`) instead of '.' as 'cdot'."
-- We also check for isolated cdot's, i.e. when the cdot is on its own line.
for cdot in Mathlib.Linter.findCDot stx do
match cdot.find? (·.isOfKind `token.«· ») with
| some (.node _ _ #[.atom (.original _ _ afterCDot _) _]) =>
if (afterCDot.takeWhile (·.isWhitespace)).contains '\n' then
Linter.logLint linter.style.cdot cdot
m!"This central dot `·` is isolated; please merge it with the next line."
| _ => return
initialize addLinter cdotLinter
end Style
/-!
### The `dollarSyntax` linter
The `dollarSyntax` linter flags uses of `<|` that are achieved by typing `$`.
These are disallowed by the mathlib style guide, as using `<|` pairs better with `|>`.
-/
/-- The `dollarSyntax` linter flags uses of `<|` that are achieved by typing `$`.
These are disallowed by the mathlib style guide, as using `<|` pairs better with `|>`. -/
register_option linter.style.dollarSyntax : Bool := {
defValue := false
descr := "enable the `dollarSyntax` linter"
}
namespace Style.dollarSyntax
/-- `findDollarSyntax stx` extracts from `stx` the syntax nodes of `kind` `$`. -/
partial
def findDollarSyntax : Syntax → Array Syntax
| stx@(.node _ kind args) =>
let dargs := (args.map findDollarSyntax).flatten
match kind with
| ``«term_$__» => dargs.push stx
| _ => dargs
|_ => #[]
@[inherit_doc linter.style.dollarSyntax]
def dollarSyntaxLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.style.dollarSyntax (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
for s in findDollarSyntax stx do
Linter.logLint linter.style.dollarSyntax s
m!"Please use '<|' instead of '$' for the pipe operator."
initialize addLinter dollarSyntaxLinter
end Style.dollarSyntax
/-!
### The `lambdaSyntax` linter
The `lambdaSyntax` linter is a syntax linter that flags uses of the symbol `λ` to define anonymous
functions, as opposed to the `fun` keyword. These are syntactically equivalent; mathlib style
prefers the latter as it is considered more readable.
-/
/--
The `lambdaSyntax` linter flags uses of the symbol `λ` to define anonymous functions.
This is syntactically equivalent to the `fun` keyword; mathlib style prefers using the latter.
-/
register_option linter.style.lambdaSyntax : Bool := {
defValue := false
descr := "enable the `lambdaSyntax` linter"
}
namespace Style.lambdaSyntax
/--
`findLambdaSyntax stx` extracts from `stx` all syntax nodes of `kind` `Term.fun`. -/
partial
def findLambdaSyntax : Syntax → Array Syntax
| stx@(.node _ kind args) =>
let dargs := (args.map findLambdaSyntax).flatten
match kind with
| ``Parser.Term.fun => dargs.push stx
| _ => dargs
|_ => #[]
@[inherit_doc linter.style.lambdaSyntax]
def lambdaSyntaxLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.style.lambdaSyntax (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
for s in findLambdaSyntax stx do
if let .atom _ "λ" := s[0] then
Linter.logLint linter.style.lambdaSyntax s[0] m!"\
Please use 'fun' and not 'λ' to define anonymous functions.\n\
The 'λ' syntax is deprecated in mathlib4."
initialize addLinter lambdaSyntaxLinter
end Style.lambdaSyntax
/-!
### The "longFile" linter
The "longFile" linter emits a warning on files which are longer than a certain number of lines
(1500 by default).
-/
/--
The "longFile" linter emits a warning on files which are longer than a certain number of lines
(`linter.style.longFileDefValue` by default on mathlib, no limit for downstream projects).
If this option is set to `N` lines, the linter warns once a file has more than `N` lines.
A value of `0` silences the linter entirely.
-/
register_option linter.style.longFile : Nat := {
defValue := 0
descr := "enable the longFile linter"
}
/-- The number of lines that the `longFile` linter considers the default. -/
register_option linter.style.longFileDefValue : Nat := {
defValue := 1500
descr := "a soft upper bound on the number of lines of each file"
}
namespace Style.longFile
@[inherit_doc Mathlib.Linter.linter.style.longFile]
def longFileLinter : Linter where run := withSetOptionIn fun stx ↦ do
let linterBound := linter.style.longFile.get (← getOptions)
if linterBound == 0 then
return
let defValue := linter.style.longFileDefValue.get (← getOptions)
let smallOption := match stx with
| `(set_option linter.style.longFile $x) => TSyntax.getNat ⟨x.raw⟩ ≤ defValue
| _ => false
if smallOption then
logLint0Disable linter.style.longFile stx
m!"The default value of the `longFile` linter is {defValue}.\n\
The current value of {linterBound} does not exceed the allowed bound.\n\
Please, remove the `set_option linter.style.longFile {linterBound}`."
else
-- Thanks to the above check, the linter option is either not set (and hence equal
-- to the default) or set to some value *larger* than the default.
-- `Parser.isTerminalCommand` allows `stx` to be `#exit`: this is useful for tests.
unless Parser.isTerminalCommand stx do return
-- We exclude `Mathlib.lean` from the linter: it exceeds linter's default number of allowed
-- lines, and it is an auto-generated import-only file.
-- TODO: if there are more such files, revise the implementation.
if (← getMainModule) == `Mathlib then return
if let some init := stx.getTailPos? then
-- the last line: we subtract 1, since the last line is expected to be empty
let lastLine := ((← getFileMap).toPosition init).line
-- In this case, the file has an allowed length, and the linter option is unnecessarily set.
if lastLine ≤ defValue && defValue < linterBound then
logLint0Disable linter.style.longFile stx
m!"The default value of the `longFile` linter is {defValue}.\n\
This file is {lastLine} lines long which does not exceed the allowed bound.\n\
Please, remove the `set_option linter.style.longFile {linterBound}`."
else
-- `candidate` is divisible by `100` and satisfies `lastLine + 100 < candidate ≤ lastLine + 200`
-- note that either `lastLine ≤ defValue` and `defValue = linterBound` hold or
-- `candidate` is necessarily bigger than `lastLine` and hence bigger than `defValue`
let candidate := (lastLine / 100) * 100 + 200
let candidate := max candidate defValue
-- In this case, the file is longer than the default and also than what the option says.
if defValue ≤ linterBound && linterBound < lastLine then
logLint0Disable linter.style.longFile stx
m!"This file is {lastLine} lines long, but the limit is {linterBound}.\n\n\
You can extend the allowed length of the file using \
`set_option linter.style.longFile {candidate}`.\n\
You can completely disable this linter by setting the length limit to `0`."
else
-- Finally, the file exceeds the default value, but not the option: we only allow the value
-- of the option to be `candidate` or `candidate + 100`.
-- In particular, this flags any option that is set to an unnecessarily high value.
if linterBound == candidate || linterBound + 100 == candidate then return
else
logLint0Disable linter.style.longFile stx
m!"This file is {lastLine} lines long. \
The current limit is {linterBound}, but it is expected to be {candidate}:\n\
`set_option linter.style.longFile {candidate}`."
initialize addLinter longFileLinter
end Style.longFile
/-! ### The "longLine linter" -/
/-- The "longLine" linter emits a warning on lines longer than 100 characters.
We allow lines containing URLs to be longer, though. -/
register_option linter.style.longLine : Bool := {
defValue := false
descr := "enable the longLine linter"
}
namespace Style.longLine
@[inherit_doc Mathlib.Linter.linter.style.longLine]
def longLineLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.style.longLine (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
-- The linter ignores the `#guard_msgs` command, in particular its doc-string.
-- The linter still lints the message guarded by `#guard_msgs`.
if stx.isOfKind ``Lean.guardMsgsCmd then
return
-- if the linter reached the end of the file, then we scan the `import` syntax instead
let stx := ← do
if stx.isOfKind ``Lean.Parser.Command.eoi then
let fileMap ← getFileMap
-- `impMods` is the syntax for the modules imported in the current file
let (impMods, _) ← Parser.parseHeader
{ inputString := fileMap.source, fileName := ← getFileName, fileMap := fileMap }
return impMods.raw
else return stx
let sstr := stx.getSubstring?
let fm ← getFileMap
let longLines := ((sstr.getD default).splitOn "\n").filter fun line ↦
(100 < (fm.toPosition line.stopPos).column)
for line in longLines do
if (line.splitOn "http").length ≤ 1 then
let stringMsg := if line.contains '"' then
"\nYou can use \"string gaps\" to format long strings: within a string quotation, \
using a '\\' at the end of a line allows you to continue the string on the following \
line, removing all intervening whitespace."
else ""
Linter.logLint linter.style.longLine (.ofRange ⟨line.startPos, line.stopPos⟩)
m!"This line exceeds the 100 character limit, please shorten it!{stringMsg}"
initialize addLinter longLineLinter
end Style.longLine
/-- The `nameCheck` linter emits a warning on declarations whose name is non-standard style.
(Currently, this only includes declarations whose name includes a double underscore.)
**Why is this bad?** Double underscores in theorem names can be considered non-standard style and
probably have been introduced by accident.
**How to fix this?** Use single underscores to separate parts of a name, following standard naming
conventions.
-/
register_option linter.style.nameCheck : Bool := {
defValue := true
descr := "enable the `nameCheck` linter"
}
namespace Style.nameCheck
@[inherit_doc linter.style.nameCheck]
def doubleUnderscore : Linter where run := withSetOptionIn fun stx => do
unless getLinterValue linter.style.nameCheck (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
let mut aliases := #[]
if let some exp := stx.find? (·.isOfKind `Lean.Parser.Command.export) then
aliases ← getAliasSyntax exp
for id in aliases.push ((stx.find? (·.isOfKind ``declId)).getD default)[0] do
let declName := id.getId
if id.getPos? == some default then continue
if declName.hasMacroScopes then continue
if id.getKind == `ident then
-- Check whether the declaration name contains "__".
if 1 < (declName.toString.splitOn "__").length then
Linter.logLint linter.style.nameCheck id
m!"The declaration '{id}' contains '__', which does not follow the mathlib naming \
conventions. Consider using single underscores instead."
initialize addLinter doubleUnderscore
end Style.nameCheck
/-! ### The "openClassical" linter -/
/-- The "openClassical" linter emits a warning on `open Classical` statements which are not
scoped to a single declaration. A non-scoped `open Classical` can hide that some theorem statements
would be better stated with explicit decidability statements.
-/
register_option linter.style.openClassical : Bool := {
defValue := false
descr := "enable the openClassical linter"
}
namespace Style.openClassical
/-- If `stx` is syntax describing an `open` command, `extractOpenNames stx`
returns an array of the syntax corresponding to the opened names,
omitting any renamed or hidden items.
This only checks independent `open` commands: for `open ... in ...` commands,
this linter returns an empty array.
-/
def extractOpenNames : Syntax → Array (TSyntax `ident)
| `(command|$_ in $_) => #[] -- redundant, for clarity
| `(command|open $decl:openDecl) => match decl with
| `(openDecl| $arg hiding $_*) => #[arg]
| `(openDecl| $arg renaming $_,*) => #[arg]
| `(openDecl| $arg ($_*)) => #[arg]
| `(openDecl| $args*) => args
| `(openDecl| scoped $args*) => args
| _ => unreachable!
| _ => #[]
@[inherit_doc Mathlib.Linter.linter.style.openClassical]
def openClassicalLinter : Linter where run stx := do
unless getLinterValue linter.style.openClassical (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
-- If `stx` describes an `open` command, extract the list of opened namespaces.
for stxN in (extractOpenNames stx).filter (·.getId == `Classical) do
Linter.logLint linter.style.openClassical stxN "\
please avoid 'open (scoped) Classical' statements: this can hide theorem statements \
which would be better stated with explicit decidability statements.\n\
Instead, use `open Classical in` for definitions or instances, the `classical` tactic \
for proofs.\nFor theorem statements, \
either add missing decidability assumptions or use `open Classical in`."
initialize addLinter openClassicalLinter
end Style.openClassical
/-! ### The "show" linter -/
/--
The "show" linter emits a warning if the `show` tactic changed the goal. `show` should only be used
to indicate intermediate goal states for proof readability. When the goal is actually changed,
`change` should be preferred.
-/
register_option linter.style.show : Bool := {
defValue := false
descr := "enable the show linter"
}
namespace Style.show
@[inherit_doc Mathlib.Linter.linter.style.show]
def showLinter : Linter where run := withSetOptionIn fun stx => do
unless getLinterValue linter.style.show (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
for tree in (← getInfoTrees) do
tree.foldInfoM (init := ()) fun ci i _ => do
let .ofTacticInfo tac := i | return
unless tac.stx.isOfKind ``Lean.Parser.Tactic.show do return
let some _ := tac.stx.getRange? true | return
let (goal :: goals) := tac.goalsBefore | return
let (goal' :: goals') := tac.goalsAfter | return
if goals != goals' then return -- `show` didn't act on first goal -> can't replace with `change`
if goal == goal' then return -- same goal, no need to check
let diff ← ci.runCoreM do
let before ← (do instantiateMVars (← goal.getType)).run' {} { mctx := tac.mctxBefore }
let after ← (do instantiateMVars (← goal'.getType)).run' {} { mctx := tac.mctxAfter }
return before != after
if diff then
logLint linter.style.show tac.stx m!"\
The `show` tactic should only be used to indicate intermediate goal states for \
readability.\nHowever, this tactic invocation changed the goal. Please use `change` \
instead for these purposes."
initialize addLinter showLinter
end Style.show
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/MinImports.lean | import ImportGraph.Imports
import Mathlib.Tactic.MinImports
/-! # The `minImports` linter
The `minImports` linter incrementally computes the minimal imports needed for each file to build.
Whenever it detects that a new command requires an increase in the (transitive) imports that it
computed so far, it emits a warning mentioning the bigger minimal imports.
Unlike the related `#min_imports` command, the linter takes into account notation and tactic
information.
It also works incrementally, accumulating increasing import information.
This is better suited, for instance, to split files.
-/
open Lean Elab Command Linter
/-!
### The "minImports" linter
The "minImports" linter tracks information about minimal imports over several commands.
-/
namespace Mathlib.Linter
/--
`ImportState` is the structure keeping track of the data that the `minImports` linter uses.
* `transClosure` is the import graph of the current file.
* `minImports` is the `NameSet` of minimal imports to build the file up to the current command.
* `importSize` is the number of transitive imports to build the file up to the current command.
-/
structure ImportState where
/-- The transitive closure of the import graph of the current file. The value is `none` only at
initialization time, as the linter immediately sets it to its value for the current file. -/
transClosure : Option (NameMap NameSet) := none
/-- The minimal imports needed to build the file up to the current command. -/
minImports : NameSet := {}
/-- The number of transitive imports needed to build the file up to the current command. -/
importSize : Nat := 0
deriving Inhabited
/--
`minImportsRef` keeps track of cumulative imports across multiple commands, using `ImportState`.
-/
initialize minImportsRef : IO.Ref ImportState ← IO.mkRef {}
/-- `#reset_min_imports` sets to empty the current list of cumulative imports. -/
elab "#reset_min_imports" : command => minImportsRef.set {}
/--
The `minImports` linter incrementally computes the minimal imports needed for each file to build.
Whenever it detects that a new command requires an increase in the (transitive) imports that it
computed so far, it emits a warning mentioning the bigger minimal imports.
Unlike the related `#min_imports` command, the linter takes into account notation and tactic
information.
It also works incrementally, providing information that is better suited, for instance, to split
files.
Another important difference is that the `minImports` *linter* starts counting imports from
where the option is set to `true` *downwards*, whereas the `#min_imports` *command* looks at the
imports needed from the command *upwards*.
-/
register_option linter.minImports : Bool := {
defValue := false
descr := "enable the minImports linter"
}
/-- The `linter.minImports.increases` regulates whether the `minImports` linter reports the
change in number of imports, when it reports import changes.
Setting this option to `false` helps with test stability.
-/
register_option linter.minImports.increases : Bool := {
defValue := true
descr := "enable reporting increase-size change in the minImports linter"
}
namespace MinImports
open Mathlib.Command.MinImports
/-- `importsBelow tc ms` takes as input a `NameMap NameSet` `tc`, representing the
`transitiveClosure` of the imports of the current module, and a `NameSet` of module names `ms`.
It returns the modules that are transitively imported by `ms`, using the data in `tc`.
-/
def importsBelow (tc : NameMap NameSet) (ms : NameSet) : NameSet :=
ms.foldl (·.append <| tc.getD · default) ms
@[inherit_doc Mathlib.Linter.linter.minImports]
macro "#import_bumps" : command => `(
-- We emit a message to prevent the `#`-command linter from flagging `#import_bumps`.
run_cmd logInfo "Counting imports from here."
set_option Elab.async false
set_option linter.minImports true)
@[inherit_doc Mathlib.Linter.linter.minImports]
def minImportsLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.minImports (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
if stx == (← `(command| #import_bumps)) then return
if stx == (← `(command| set_option $(mkIdent `linter.minImports) true)) then
logInfo "Try using '#import_bumps', instead of manually setting the linter option: \
the linter works best with linear parsing of the file and '#import_bumps' \
also sets the `Elab.async` option to `false`."
return
let env ← getEnv
-- the first time `minImportsRef` is read, it has `transClosure = none`;
-- in this case, we set it to be the `transClosure` for the file.
if (← minImportsRef.get).transClosure.isNone then
minImportsRef.modify ({· with transClosure := env.importGraph.transitiveClosure})
let impState ← minImportsRef.get
let (importsSoFar, oldCumulImps) := (impState.minImports, impState.importSize)
-- when the linter reaches the end of the file or `#exit`, it gives a report
if #[``Parser.Command.eoi, ``Lean.Parser.Command.exit].contains stx.getKind then
let explicitImportsInFile : NameSet :=
.ofArray ((env.imports.map (·.module)).erase `Init)
let newImps := importsSoFar \ explicitImportsInFile
let currentlyUnneededImports := explicitImportsInFile \ importsSoFar
-- we read the current file, to do a custom parsing of the imports:
-- this is a hack to obtain some `Syntax` information for the `import X` commands
let fname ← getFileName
let contents ← IO.FS.readFile fname
-- `impMods` is the syntax for the modules imported in the current file
let (impMods, _) ← Parser.parseHeader (Parser.mkInputContext contents fname)
for i in currentlyUnneededImports do
match impMods.raw.find? (·.getId == i) with
| some impPos => logWarningAt impPos m!"unneeded import '{i}'"
| _ => dbg_trace f!"'{i}' not found" -- this should be unreachable
-- if the linter found new imports that should be added (likely to *reduce* the dependencies)
if !newImps.isEmpty then
-- format the imports prepending `import ` to each module name
let withImport := (newImps.toArray.qsort Name.lt).map (s!"import {·}")
-- log a warning at the first `import`, if there is one.
logWarningAt ((impMods.raw.find? (·.isOfKind `import)).getD default)
m!"-- missing imports\n{"\n".intercalate withImport.toList}"
let id ← getId stx
let newImports := getIrredundantImports env (← getAllImports stx id)
let tot := (newImports.append importsSoFar)
let redundant := env.findRedundantImports tot.toArray
let currImports := tot \ redundant
let currImpArray := currImports.toArray.qsort Name.lt
if currImpArray != #[] &&
currImpArray ≠ importsSoFar.toArray.qsort Name.lt then
let newCumulImps := -- We should always be in the situation where `getD` finds something
(importsBelow (impState.transClosure.getD env.importGraph.transitiveClosure) tot).size
minImportsRef.modify ({· with minImports := currImports, importSize := newCumulImps})
let new := currImpArray.filter (!importsSoFar.contains ·)
let redundant := importsSoFar.toArray.filter (!currImports.contains ·)
-- to make `test` files more stable, we suppress the exact count of import changes if
-- the `linter.minImports.increases` option is `false`
let byCount := if getLinterValue linter.minImports.increases (← getLinterOptions) then
m!"by {newCumulImps - oldCumulImps} "
else
m!""
Linter.logLint linter.minImports stx <|
m!"Imports increased {byCount}to\n{currImpArray}\n\n\
New imports: {new}\n" ++
if redundant.isEmpty then m!"" else m!"\nNow redundant: {redundant}\n"
initialize addLinter minImportsLinter
end MinImports
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/CommandRanges.lean | import Mathlib.Init -- `import Lean.Elab.Command` is enough
/-!
# The "commandRanges" linter
The "commandRanges" linter simply logs the `getRange?` and the `getRangeWithTrailing?`
for each command.
This is useful for the "removeDeprecations" automation, since it helps identifying the exact range
of each declaration that should be removed.
This linter is strictly tied to the `#clear_deprecations` command in
`Mathlib/Tactic/Linter/FindDeprecations.lean`.
-/
open Lean Elab Linter
namespace Mathlib.Linter
/--
The "commandRanges" linter logs the `getRange?` and the `getRangeWithTrailing?` for each command.
The format is `[start, end, trailing]`, where
* `start` is the start of the command,
* `end` is the end of the command, not including trailing whitespace and comments,
* `trailing` is the "syntactic end" of the command, so it contains all trailing whitespace and
comments.
Thus, assuming that there has been no tampering with positions/synthetic syntax,
if the current command is followed by another command, then `trailing` for the previous command
coincides with `start` of the following.
-/
register_option linter.commandRanges : Bool := {
defValue := false
descr := "enable the commandRanges linter"
}
namespace CommandRanges
@[inherit_doc Mathlib.Linter.linter.commandRanges]
def commandRangesLinter : Linter where run stx := do
unless Linter.getLinterValue linter.commandRanges (← getLinterOptions) do
return
if Parser.isTerminalCommand stx then
return
let ranges :=
if let some rg := stx.getRange? then #[rg.start, rg.stop] else #[]
let ranges : Array String.Pos.Raw :=
if let some rg := stx.getRangeWithTrailing? then ranges.push rg.stop else ranges
logInfo m!"{ranges}"
initialize addLinter commandRangesLinter
end CommandRanges
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Tactic/Linter/DeprecatedSyntaxLinter.lean | import Lean.Elab.Command
-- Import this linter explicitly to ensure that
-- this file has a valid copyright header and module docstring.
import Mathlib.Tactic.Linter.Header
/-!
# Linter against deprecated syntax
`refine'`, `cases'` and `induction'` provide backward-compatible implementations of their
unprimed equivalents in Lean 3 –`refine`, `cases` and `induction` respectively.
They have been superseded by Lean 4 tactics:
* `refine` and `apply` replace `refine'`. While they are similar, they handle metavariables
slightly differently; this means that they are not completely interchangeable, nor can one
completely replace another. However, `refine` and `apply` are more readable and (heuristically)
tend to be more efficient on average.
* `obtain`, `rcases` and `cases` replace `cases'`. Unlike the replacement tactics, `cases'`
does not require the variables it introduces to be separated by case, which hinders readability.
* `induction` replaces `induction'` for similar reasons to `cases` and `cases'`.
The `admit` tactic is a synonym for the much more common `sorry`, so the latter should be preferred.
The `native_decide` tactic is not allowed in mathlib, as it trusts the entire Lean compiler
(and not just the Lean kernel). Because the latter is large and complicated, at present it is
probably possible to prove `False` using `native_decide`.
This linter is an incentive to discourage uses of such deprecated syntax, without being a ban.
It is not inherently limited to tactics.
-/
open Lean Elab Linter
namespace Mathlib.Linter.Style
/-- The option `linter.style.refine` of the deprecated syntax linter flags usages of
the `refine'` tactic.
The tactics `refine`, `apply` and `refine'` are similar, but they handle metavariables slightly
differently. This means that they are not completely interchangeable, nor can one completely
replace another. However, `refine` and `apply` are more readable and (heuristically) tend to be
more efficient on average.
-/
register_option linter.style.refine : Bool := {
defValue := false
descr := "enable the refine linter"
}
/-- The option `linter.style.cases` of the deprecated syntax linter flags usages of
the `cases'` tactic, which is a backward-compatible version of Lean 3's `cases` tactic.
Unlike `obtain`, `rcases` and Lean 4's `cases`, variables introduced by `cases'` are not
required to be separated by case, which hinders readability.
-/
register_option linter.style.cases : Bool := {
defValue := false
descr := "enable the cases linter"
}
/-- The option `linter.style.induction` of the deprecated syntax linter flags usages of
the `induction'` tactic, which is a backward-compatible version of Lean 3's `induction` tactic.
Unlike Lean 4's `induction`, variables introduced by `induction'` are not
required to be separated by case, which hinders readability.
-/
register_option linter.style.induction : Bool := {
defValue := false
descr := "enable the induction linter"
}
/-- The option `linter.style.admit` of the deprecated syntax linter flags usages of
the `admit` tactic, which is a synonym for the much more common `sorry`. -/
register_option linter.style.admit : Bool := {
defValue := false
descr := "enable the admit linter"
}
/-- The option `linter.style.nativeDecide` of the deprecated syntax linter flags usages of
the `native_decide` tactic, which is disallowed in mathlib. -/
-- Note: this linter is purely for user information. Running `lean4checker` in CI catches *any*
-- additional axioms that are introduced (not just `ofReduceBool`): the point of this check is to
-- alert the user quickly, not to be airtight.
register_option linter.style.nativeDecide : Bool := {
defValue := false
descr := "enable the nativeDecide linter"
}
/-- The option `linter.style.maxHeartbeats` of the deprecated syntax linter flags usages of
`set_option <name-containing-maxHeartbeats> n in cmd` that do not add a comment explaining
the reason for the modification of the `maxHeartbeats`.
This includes `set_option maxHeartbeats n in` and `set_option synthInstance.maxHeartbeats n in`.
-/
register_option linter.style.maxHeartbeats : Bool := {
defValue := false
descr := "enable the maxHeartbeats linter"
}
/-- If the input syntax is of the form `set_option <option> num in <string> cmd`,
where `<option>` contains `maxHeartbeats`, then it returns
* the `<option>`, as a name (typically, `maxHeartbeats` or `synthInstance.maxHeartbeats`);
* the number `num` and
* whatever is in `<string>`. Note that `<string>` can only consist of whitespace and comments.
Otherwise, it returns `none`.
-/
def getSetOptionMaxHeartbeatsComment : Syntax → Option (Name × Nat × Substring)
| stx@`(command|set_option $mh $n:num in $_) =>
let opt := mh.getId
if !opt.components.contains `maxHeartbeats then
none
else
if let some inAtom := stx.find? (·.getAtomVal == "in") then
inAtom.getTrailing?.map (opt, n.getNat, ·)
else
-- This branch should be unreachable.
some default
| _ => none
/-- Whether a given piece of syntax represents a `decide` tactic call with the `native` option
enabled. This may have false negatives for `decide (config := {<options>})` syntax). -/
def isDecideNative (stx : Syntax ) : Bool :=
match stx with
| .node _ ``Lean.Parser.Tactic.decide args =>
-- The configuration passed to the tactic call.
let config := args[1]![0]
-- Check all configuration arguments in order to determine the final
-- toggling of the native decide option.
if let (.node _ _ config_args) := config then
let natives := config_args.filterMap (match ·[0] with
| `(Parser.Tactic.posConfigItem| +native) => some true
| `(Parser.Tactic.negConfigItem| -native) => some false
| `(Parser.Tactic.valConfigItem| (config := {native := true})) => some true
| `(Parser.Tactic.valConfigItem| (config := {native := false})) => some false
| _ => none)
natives.back? == some true
else
false
| _ => false
/-- `getDeprecatedSyntax t` returns all usages of deprecated syntax in the input syntax `t`. -/
partial
def getDeprecatedSyntax : Syntax → Array (SyntaxNodeKind × Syntax × MessageData)
| stx@(.node _ kind args) =>
let rargs := args.flatMap getDeprecatedSyntax
match kind with
| ``Lean.Parser.Tactic.refine' =>
rargs.push (kind, stx,
"The `refine'` tactic is discouraged: \
please strongly consider using `refine` or `apply` instead.")
| `Mathlib.Tactic.cases' =>
rargs.push (kind, stx,
"The `cases'` tactic is discouraged: \
please strongly consider using `obtain`, `rcases` or `cases` instead.")
| `Mathlib.Tactic.induction' =>
rargs.push (kind, stx,
"The `induction'` tactic is discouraged: \
please strongly consider using `induction` instead.")
| ``Lean.Parser.Tactic.tacticAdmit =>
rargs.push (kind, stx,
"The `admit` tactic is discouraged: \
please strongly consider using the synonymous `sorry` instead.")
| ``Lean.Parser.Tactic.decide =>
if isDecideNative stx then
rargs.push (kind, stx, "Using `decide +native` is not allowed in mathlib: \
because it trusts the entire Lean compiler (not just the Lean kernel), \
it could quite possibly be used to prove false.")
else
rargs
| ``Lean.Parser.Tactic.nativeDecide =>
rargs.push (kind, stx, "Using `native_decide` is not allowed in mathlib: \
because it trusts the entire Lean compiler (not just the Lean kernel), \
it could quite possibly be used to prove false.")
| ``Lean.Parser.Command.in =>
match getSetOptionMaxHeartbeatsComment stx with
| none => rargs
| some (opt, n, trailing) =>
-- Since we are now seeing the currently outermost `maxHeartbeats` option,
-- we remove all subsequent potential flags and only decide whether to lint or not
-- based on whether the current option has a comment.
let rargs := rargs.filter (·.1 != `MaxHeartbeats)
if trailing.toString.trimLeft.isEmpty then
rargs.push (`MaxHeartbeats, stx,
s!"Please, add a comment explaining the need for modifying the maxHeartbeat limit, \
as in\nset_option {opt} {n} in\n-- reason for change\n...")
else
rargs
| _ => rargs
| _ => default
/-- The deprecated syntax linter flags usages of deprecated syntax and suggests
replacement syntax. For each individual case, linting can be turned on or off separately.
* `refine'`, superseded by `refine` and `apply` (controlled by `linter.style.refine`)
* `cases'`, superseded by `obtain`, `rcases` and `cases` (controlled by `linter.style.cases`)
* `induction'`, superseded by `induction` (controlled by `linter.style.induction`)
* `admit`, superseded by `sorry` (controlled by `linter.style.admit`)
* `set_option maxHeartbeats`, should contain an explanatory comment
(controlled by `linter.style.maxHeartbeats`)
-/
def deprecatedSyntaxLinter : Linter where run stx := do
unless getLinterValue linter.style.refine (← getLinterOptions) ||
getLinterValue linter.style.cases (← getLinterOptions) ||
getLinterValue linter.style.induction (← getLinterOptions) ||
getLinterValue linter.style.admit (← getLinterOptions) ||
getLinterValue linter.style.maxHeartbeats (← getLinterOptions) ||
getLinterValue linter.style.nativeDecide (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
let deprecations := getDeprecatedSyntax stx
-- Using `withSetOptionIn` here, allows the linter to parse also the "leading" `set_option`s
-- but then flagging them only if the corresponding option is still set after elaborating the
-- leading `set_option`s.
-- In particular, this means that the linter "sees" `set_option maxHeartbeats 10 in ...`,
-- records it in `deprecations` and then acts on it, according to the correct options.
(withSetOptionIn fun _ ↦ do
for (kind, stx', msg) in deprecations do
match kind with
| ``Lean.Parser.Tactic.refine' => Linter.logLintIf linter.style.refine stx' msg
| `Mathlib.Tactic.cases' => Linter.logLintIf linter.style.cases stx' msg
| `Mathlib.Tactic.induction' => Linter.logLintIf linter.style.induction stx' msg
| ``Lean.Parser.Tactic.tacticAdmit => Linter.logLintIf linter.style.admit stx' msg
| ``Lean.Parser.Tactic.nativeDecide | ``Lean.Parser.Tactic.decide =>
Linter.logLintIf linter.style.nativeDecide stx' msg
| `MaxHeartbeats => Linter.logLintIf linter.style.maxHeartbeats stx' msg
| _ => continue) stx
initialize addLinter deprecatedSyntaxLinter
end Mathlib.Linter.Style |
.lake/packages/mathlib/Mathlib/Tactic/FieldSimp/Lemmas.lean | import Mathlib.Algebra.BigOperators.Group.List.Basic
import Mathlib.Algebra.Field.Power
import Mathlib.Algebra.Order.GroupWithZero.Unbundled.Basic
import Mathlib.Util.Qq
/-! # Lemmas for the field_simp tactic
-/
open List
namespace Mathlib.Tactic.FieldSimp
section zpow'
variable {α : Type*}
section
variable [GroupWithZero α]
open Classical in
/-- This is a variant of integer exponentiation, defined for internal use in the `field_simp` tactic
implementation. It differs from the usual integer exponentiation in that `0 ^ 0` is `0`, not `1`.
With this choice, the function `n ↦ a ^ n` is always a homomorphism (`a ^ (n + m) = a ^ n * a ^ m`),
even if `a` is zero. -/
noncomputable def zpow' (a : α) (n : ℤ) : α :=
if a = 0 ∧ n = 0 then 0 else a ^ n
theorem zpow'_add (a : α) (m n : ℤ) :
zpow' a (m + n) = zpow' a m * zpow' a n := by
by_cases ha : a = 0
· simp [zpow', ha]
by_cases hn : n = 0
· simp +contextual [hn, zero_zpow]
· simp +contextual [hn, zero_zpow]
· simp [zpow', ha, zpow_add₀]
theorem zpow'_of_ne_zero_right (a : α) (n : ℤ) (hn : n ≠ 0) : zpow' a n = a ^ n := by
simp [zpow', hn]
theorem zpow'_of_ne_zero_left (a : α) (n : ℤ) (ha : a ≠ 0) : zpow' a n = a ^ n := by
simp [zpow', ha]
@[simp]
lemma zero_zpow' (n : ℤ) : zpow' (0 : α) n = 0 := by
simp +contextual only [zpow', true_and, ite_eq_left_iff]
intro hn
exact zero_zpow n hn
lemma zpow'_eq_zero_iff (a : α) (n : ℤ) : zpow' a n = 0 ↔ a = 0 := by
obtain rfl | hn := eq_or_ne n 0
· simp [zpow']
· simp [zpow', zpow_eq_zero_iff hn]
tauto
@[simp]
lemma one_zpow' (n : ℤ) : zpow' (1 : α) n = 1 := by
simp [zpow']
@[simp]
lemma zpow'_one (a : α) : zpow' a 1 = a := by
simp [zpow']
lemma zpow'_zero_eq_div (a : α) : zpow' a 0 = a / a := by
simp [zpow']
by_cases h : a = 0
· simp [h]
· simp [h]
lemma zpow'_zero_of_ne_zero {a : α} (ha : a ≠ 0) : zpow' a 0 = 1 := by simp [zpow', ha]
lemma zpow'_neg (a : α) (n : ℤ) : zpow' a (-n) = (zpow' a n)⁻¹ := by
simp +contextual [zpow', apply_ite]
split_ifs with h
· tauto
· tauto
lemma zpow'_mul (a : α) (m n : ℤ) : zpow' a (m * n) = zpow' (zpow' a m) n := by
by_cases ha : a = 0
· simp [ha]
by_cases hn : n = 0
· rw [hn]
simp [zpow', ha, zpow_ne_zero ]
by_cases hm : m = 0
· rw [hm]
simp [zpow', ha]
simpa [zpow', ha, hm, hn] using zpow_mul a m n
lemma zpow'_ofNat (a : α) {n : ℕ} (hn : n ≠ 0) : zpow' a n = a ^ n := by
rw [zpow'_of_ne_zero_right]
· simp
exact_mod_cast hn
end
lemma mul_zpow' [CommGroupWithZero α] (n : ℤ) (a b : α) :
zpow' (a * b) n = zpow' a n * zpow' b n := by
by_cases ha : a = 0
· simp [ha]
by_cases hb : b = 0
· simp [hb]
simpa [zpow', ha, hb] using mul_zpow a b n
theorem list_prod_zpow' [CommGroupWithZero α] {r : ℤ} {l : List α} :
zpow' (prod l) r = prod (map (fun x ↦ zpow' x r) l) :=
let fr : α →* α := ⟨⟨fun b ↦ zpow' b r, one_zpow' r⟩, (mul_zpow' r)⟩
map_list_prod fr l
end zpow'
theorem subst_add {M : Type*} [Semiring M] {x₁ x₂ X₁ X₂ Y y a : M}
(h₁ : x₁ = a * X₁) (h₂ : x₂ = a * X₂) (H_atom : X₁ + X₂ = Y) (hy : a * Y = y) :
x₁ + x₂ = y := by
subst h₁ h₂ H_atom hy
simp [mul_add]
theorem subst_sub {M : Type*} [Ring M] {x₁ x₂ X₁ X₂ Y y a : M}
(h₁ : x₁ = a * X₁) (h₂ : x₂ = a * X₂) (H_atom : X₁ - X₂ = Y) (hy : a * Y = y) :
x₁ - x₂ = y := by
subst h₁ h₂ H_atom hy
simp [mul_sub]
theorem eq_div_of_eq_one_of_subst {M : Type*} [DivInvOneMonoid M] {l l_n n : M} (h : l = l_n / 1)
(hn : l_n = n) :
l = n := by
rw [h, hn, div_one]
theorem eq_div_of_eq_one_of_subst' {M : Type*} [DivInvOneMonoid M] {l l_d d : M} (h : l = 1 / l_d)
(hn : l_d = d) :
l = d⁻¹ := by
rw [h, hn, one_div]
theorem eq_div_of_subst {M : Type*} [Div M] {l l_n l_d n d : M} (h : l = l_n / l_d) (hn : l_n = n)
(hd : l_d = d) :
l = n / d := by
rw [h, hn, hd]
theorem eq_mul_of_eq_eq_eq_mul {M : Type*} [Mul M] {a b c D e f : M}
(h₁ : a = b) (h₂ : b = c) (h₃ : c = D * e) (h₄ : e = f) :
a = D * f := by
rw [h₁, h₂, h₃, h₄]
theorem eq_eq_cancel_eq {M : Type*} [CancelMonoidWithZero M] {e₁ e₂ f₁ f₂ L : M}
(H₁ : e₁ = L * f₁) (H₂ : e₂ = L * f₂) (HL : L ≠ 0) :
(e₁ = e₂) = (f₁ = f₂) := by
subst H₁ H₂
rw [mul_right_inj' HL]
theorem le_eq_cancel_le {M : Type*} [CancelMonoidWithZero M] [PartialOrder M] [PosMulMono M]
[PosMulReflectLE M] {e₁ e₂ f₁ f₂ L : M}
(H₁ : e₁ = L * f₁) (H₂ : e₂ = L * f₂) (HL : 0 < L) :
(e₁ ≤ e₂) = (f₁ ≤ f₂) := by
subst H₁ H₂
apply Iff.eq
exact mul_le_mul_iff_right₀ HL
theorem lt_eq_cancel_lt {M : Type*} [CancelMonoidWithZero M] [PartialOrder M] [PosMulStrictMono M]
[PosMulReflectLT M] {e₁ e₂ f₁ f₂ L : M}
(H₁ : e₁ = L * f₁) (H₂ : e₂ = L * f₂) (HL : 0 < L) :
(e₁ < e₂) = (f₁ < f₂) := by
subst H₁ H₂
apply Iff.eq
exact mul_lt_mul_iff_of_pos_left HL
/-! ### Theory of lists of pairs (exponent, atom)
This section contains the lemmas which are orchestrated by the `field_simp` tactic
to prove goals in fields. The basic object which these lemmas concern is `NF M`, a type synonym
for a list of ordered pairs in `ℤ × M`, where typically `M` is a field.
-/
/-- Basic theoretical "normal form" object of the `field_simp` tactic: a type
synonym for a list of ordered pairs in `ℤ × M`, where typically `M` is a field. This is the
form to which the tactics reduce field expressions. -/
def NF (M : Type*) := List (ℤ × M)
namespace NF
variable {M : Type*}
/-- Augment a `FieldSimp.NF M` object `l`, i.e. a list of pairs in `ℤ × M`, by prepending another
pair `p : ℤ × M`. -/
@[match_pattern]
def cons (p : ℤ × M) (l : NF M) : NF M := p :: l
@[inherit_doc cons] infixl:100 " ::ᵣ " => cons
/-- Evaluate a `FieldSimp.NF M` object `l`, i.e. a list of pairs in `ℤ × M`, to an element of `M`,
by forming the "multiplicative linear combination" it specifies: raise each `M` term to the power of
the corresponding `ℤ` term, then multiply them all together. -/
noncomputable def eval [GroupWithZero M] (l : NF M) : M :=
(l.map (fun (⟨r, x⟩ : ℤ × M) ↦ zpow' x r)).prod
@[simp] theorem eval_cons [CommGroupWithZero M] (p : ℤ × M) (l : NF M) :
(p ::ᵣ l).eval = l.eval * zpow' p.2 p.1 := by
unfold eval cons
simp [mul_comm]
theorem cons_ne_zero [GroupWithZero M] (r : ℤ) {x : M} (hx : x ≠ 0) {l : NF M} (hl : l.eval ≠ 0) :
((r, x) ::ᵣ l).eval ≠ 0 := by
unfold eval cons
apply mul_ne_zero ?_ hl
simp [zpow'_eq_zero_iff, hx]
theorem cons_pos [GroupWithZero M] [PartialOrder M] [PosMulStrictMono M] [PosMulReflectLT M]
[ZeroLEOneClass M] (r : ℤ) {x : M} (hx : 0 < x) {l : NF M} (hl : 0 < l.eval) :
0 < ((r, x) ::ᵣ l).eval := by
unfold eval cons
apply mul_pos ?_ hl
simp only
rw [zpow'_of_ne_zero_left _ _ hx.ne']
apply zpow_pos hx
theorem atom_eq_eval [GroupWithZero M] (x : M) : x = NF.eval [(1, x)] := by simp [eval]
variable (M) in
theorem one_eq_eval [GroupWithZero M] : (1:M) = NF.eval (M := M) [] := rfl
theorem mul_eq_eval₁ [CommGroupWithZero M] (a₁ : ℤ × M) {a₂ : ℤ × M} {l₁ l₂ l : NF M}
(h : l₁.eval * (a₂ ::ᵣ l₂).eval = l.eval) :
(a₁ ::ᵣ l₁).eval * (a₂ ::ᵣ l₂).eval = (a₁ ::ᵣ l).eval := by
simp only [eval_cons, ← h]
ac_rfl
theorem mul_eq_eval₂ [CommGroupWithZero M] (r₁ r₂ : ℤ) (x : M) {l₁ l₂ l : NF M}
(h : l₁.eval * l₂.eval = l.eval) :
((r₁, x) ::ᵣ l₁).eval * ((r₂, x) ::ᵣ l₂).eval = ((r₁ + r₂, x) ::ᵣ l).eval := by
simp only [eval_cons, ← h, zpow'_add]
ac_rfl
theorem mul_eq_eval₃ [CommGroupWithZero M] {a₁ : ℤ × M} (a₂ : ℤ × M) {l₁ l₂ l : NF M}
(h : (a₁ ::ᵣ l₁).eval * l₂.eval = l.eval) :
(a₁ ::ᵣ l₁).eval * (a₂ ::ᵣ l₂).eval = (a₂ ::ᵣ l).eval := by
simp only [eval_cons, ← h]
ac_rfl
theorem mul_eq_eval [GroupWithZero M] {l₁ l₂ l : NF M} {x₁ x₂ : M} (hx₁ : x₁ = l₁.eval)
(hx₂ : x₂ = l₂.eval) (h : l₁.eval * l₂.eval = l.eval) :
x₁ * x₂ = l.eval := by
rw [hx₁, hx₂, h]
theorem div_eq_eval₁ [CommGroupWithZero M] (a₁ : ℤ × M) {a₂ : ℤ × M} {l₁ l₂ l : NF M}
(h : l₁.eval / (a₂ ::ᵣ l₂).eval = l.eval) :
(a₁ ::ᵣ l₁).eval / (a₂ ::ᵣ l₂).eval = (a₁ ::ᵣ l).eval := by
simp only [eval_cons, ← h, div_eq_mul_inv]
ac_rfl
theorem div_eq_eval₂ [CommGroupWithZero M] (r₁ r₂ : ℤ) (x : M) {l₁ l₂ l : NF M}
(h : l₁.eval / l₂.eval = l.eval) :
((r₁, x) ::ᵣ l₁).eval / ((r₂, x) ::ᵣ l₂).eval = ((r₁ - r₂, x) ::ᵣ l).eval := by
simp only [← h, eval_cons, div_eq_mul_inv, mul_inv, ← zpow'_neg, sub_eq_add_neg, zpow'_add]
ac_rfl
theorem div_eq_eval₃ [CommGroupWithZero M] {a₁ : ℤ × M} (a₂ : ℤ × M) {l₁ l₂ l : NF M}
(h : (a₁ ::ᵣ l₁).eval / l₂.eval = l.eval) :
(a₁ ::ᵣ l₁).eval / (a₂ ::ᵣ l₂).eval = ((-a₂.1, a₂.2) ::ᵣ l).eval := by
simp only [eval_cons, ← h, zpow'_neg, div_eq_mul_inv, mul_inv, mul_assoc]
theorem div_eq_eval [GroupWithZero M] {l₁ l₂ l : NF M} {x₁ x₂ : M} (hx₁ : x₁ = l₁.eval)
(hx₂ : x₂ = l₂.eval) (h : l₁.eval / l₂.eval = l.eval) :
x₁ / x₂ = l.eval := by
rw [hx₁, hx₂, h]
theorem eval_mul_eval_cons [CommGroupWithZero M] (n : ℤ) (e : M) {L l l' : NF M}
(h : L.eval * l.eval = l'.eval) :
L.eval * ((n, e) ::ᵣ l).eval = ((n, e) ::ᵣ l').eval := by
rw [eval_cons, eval_cons, ← h, mul_assoc]
theorem eval_mul_eval_cons_zero [CommGroupWithZero M] {e : M} {L l l' l₀ : NF M}
(h : L.eval * l.eval = l'.eval) (h' : ((0, e) ::ᵣ l).eval = l₀.eval) :
L.eval * l₀.eval = ((0, e) ::ᵣ l').eval := by
rw [← eval_mul_eval_cons 0 e h, h']
theorem eval_cons_mul_eval [CommGroupWithZero M] (n : ℤ) (e : M) {L l l' : NF M}
(h : L.eval * l.eval = l'.eval) :
((n, e) ::ᵣ L).eval * l.eval = ((n, e) ::ᵣ l').eval := by
rw [eval_cons, eval_cons, ← h]
ac_rfl
theorem eval_cons_mul_eval_cons_neg [CommGroupWithZero M] (n : ℤ) {e : M} (he : e ≠ 0)
{L l l' : NF M} (h : L.eval * l.eval = l'.eval) :
((n, e) ::ᵣ L).eval * ((-n, e) ::ᵣ l).eval = l'.eval := by
rw [mul_eq_eval₂ n (-n) e h]
simp [zpow'_zero_of_ne_zero he]
theorem cons_eq_div_of_eq_div [CommGroupWithZero M] (n : ℤ) (e : M) {t t_n t_d : NF M}
(h : t.eval = t_n.eval / t_d.eval) :
((n, e) ::ᵣ t).eval = ((n, e) ::ᵣ t_n).eval / t_d.eval := by
simp only [eval_cons, h, div_eq_mul_inv]
ac_rfl
theorem cons_eq_div_of_eq_div' [CommGroupWithZero M] (n : ℤ) (e : M) {t t_n t_d : NF M}
(h : t.eval = t_n.eval / t_d.eval) :
((-n, e) ::ᵣ t).eval = t_n.eval / ((n, e) ::ᵣ t_d).eval := by
simp only [eval_cons, h, zpow'_neg, div_eq_mul_inv, mul_inv]
ac_rfl
theorem cons_zero_eq_div_of_eq_div [CommGroupWithZero M] (e : M) {t t_n t_d : NF M}
(h : t.eval = t_n.eval / t_d.eval) :
((0, e) ::ᵣ t).eval = ((1, e) ::ᵣ t_n).eval / ((1, e) ::ᵣ t_d).eval := by
simp only [eval_cons, h, div_eq_mul_inv, mul_inv, ← zpow'_neg, ← add_neg_cancel (1:ℤ), zpow'_add]
ac_rfl
instance : Inv (NF M) where
inv l := l.map fun (a, x) ↦ (-a, x)
theorem eval_inv [CommGroupWithZero M] (l : NF M) : (l⁻¹).eval = l.eval⁻¹ := by
simp only [NF.eval, List.map_map, NF.instInv, List.prod_inv]
congr! 2
ext p
simp [zpow'_neg]
theorem one_div_eq_eval [CommGroupWithZero M] (l : NF M) : 1 / l.eval = (l⁻¹).eval := by
simp [eval_inv]
theorem inv_eq_eval [CommGroupWithZero M] {l : NF M} {x : M} (h : x = l.eval) :
x⁻¹ = (l⁻¹).eval := by
rw [h, eval_inv]
instance : Pow (NF M) ℤ where
pow l r := l.map fun (a, x) ↦ (r * a, x)
@[simp] theorem zpow_apply (r : ℤ) (l : NF M) : l ^ r = l.map fun (a, x) ↦ (r * a, x) := rfl
theorem eval_zpow' [CommGroupWithZero M] (l : NF M) (r : ℤ) :
(l ^ r).eval = zpow' l.eval r := by
unfold NF.eval at ⊢
simp only [zpow_apply, list_prod_zpow', map_map]
congr! 2
ext p
simp [← zpow'_mul, mul_comm]
theorem zpow_eq_eval [CommGroupWithZero M] {l : NF M} {r : ℤ} (hr : r ≠ 0) {x : M}
(hx : x = l.eval) :
x ^ r = (l ^ r).eval := by
rw [← zpow'_of_ne_zero_right x r hr, eval_zpow', hx]
instance : Pow (NF M) ℕ where
pow l r := l.map fun (a, x) ↦ (r * a, x)
@[simp] theorem pow_apply (r : ℕ) (l : NF M) : l ^ r = l.map fun (a, x) ↦ (r * a, x) :=
rfl
theorem eval_pow [CommGroupWithZero M] (l : NF M) (r : ℕ) : (l ^ r).eval = zpow' l.eval r :=
eval_zpow' l r
theorem pow_eq_eval [CommGroupWithZero M] {l : NF M} {r : ℕ} (hr : r ≠ 0) {x : M}
(hx : x = l.eval) :
x ^ r = (l ^ r).eval := by
rw [eval_pow, hx]
rw [zpow'_ofNat _ hr]
theorem eval_cons_of_pow_eq_zero [CommGroupWithZero M] {r : ℤ} (hr : r = 0) {x : M} (hx : x ≠ 0)
(l : NF M) :
((r, x) ::ᵣ l).eval = NF.eval l := by
simp [hr, zpow'_zero_of_ne_zero hx]
theorem eval_cons_eq_eval_of_eq_of_eq [CommGroupWithZero M] (r : ℤ) (x : M) {t t' l' : NF M}
(h : NF.eval t = NF.eval t') (h' : ((r, x) ::ᵣ t').eval = NF.eval l') :
((r, x) ::ᵣ t).eval = NF.eval l' := by
rw [← h', eval_cons, eval_cons, h]
end NF
/-! ### Negations of algebraic operations -/
section Sign
open Lean Qq
variable {v : Level} {M : Q(Type v)}
/-- Inductive type representing the options for the sign of an element in a type-expression `M`
If the sign is "-", then we also carry an expression for a field instance on `M`, to allow us to
construct that negation when needed. -/
inductive Sign (M : Q(Type v))
| plus
| minus (iM : Q(Field $M))
/-- Given an expression `e : Q($M)`, construct an expression which is morally "± `e`", with the
choice between + and - determined by an object `g : Sign M`. -/
def Sign.expr : Sign M → Q($M) → Q($M)
| plus, a => a
| minus _, a => q(-$a)
/-- Given an expression `y : Q($M)` with specified sign (either + or -), construct a proof that
the product with `c` of (± `y`) (here taking the specified sign) is ± `c * y`. -/
def Sign.mulRight (iM : Q(CommGroupWithZero $M)) (c y : Q($M)) (g : Sign M) :
MetaM Q($(g.expr q($c * $y)) = $c * $(g.expr y)) := do
match g with
| .plus => pure q(rfl)
| .minus _ =>
assumeInstancesCommute
pure q(Eq.symm (mul_neg $c _))
/-- Given expressions `y₁ y₂ : Q($M)` with specified signs (either + or -), construct a proof that
the product of (± `y₁`) and (± `y₂`) (here taking the specified signs) is ± `y₁ * y₂`; return this
proof and the computed sign. -/
def Sign.mul (iM : Q(CommGroupWithZero $M)) (y₁ y₂ : Q($M)) (g₁ g₂ : Sign M) :
MetaM (Σ (G : Sign M), Q($(g₁.expr y₁) * $(g₂.expr y₂) = $(G.expr q($y₁ * $y₂)))) := do
match g₁, g₂ with
| .plus, .plus => pure ⟨.plus, q(rfl)⟩
| .plus, .minus i =>
assumeInstancesCommute
pure ⟨.minus i, q(mul_neg $y₁ $y₂)⟩
| .minus i, .plus =>
assumeInstancesCommute
pure ⟨.minus i, q(neg_mul $y₁ $y₂)⟩
| .minus _, .minus _ =>
assumeInstancesCommute
pure ⟨.plus, q(neg_mul_neg $y₁ $y₂)⟩
/-- Given an expression `y : Q($M)` with specified sign (either + or -), construct a proof that
the inverse of (± `y`) (here taking the specified sign) is ± `y⁻¹`. -/
def Sign.inv (iM : Q(CommGroupWithZero $M)) (y : Q($M)) (g : Sign M) :
MetaM (Q($(g.expr y)⁻¹ = $(g.expr q($y⁻¹)))) := do
match g with
| .plus => pure q(rfl)
| .minus _ =>
assumeInstancesCommute
pure q(inv_neg (a := $y))
/-- Given expressions `y₁ y₂ : Q($M)` with specified signs (either + or -), construct a proof that
the quotient of (± `y₁`) and (± `y₂`) (here taking the specified signs) is ± `y₁ / y₂`; return this
proof and the computed sign. -/
def Sign.div (iM : Q(CommGroupWithZero $M)) (y₁ y₂ : Q($M)) (g₁ g₂ : Sign M) :
MetaM (Σ (G : Sign M), Q($(g₁.expr y₁) / $(g₂.expr y₂) = $(G.expr q($y₁ / $y₂)))) := do
match g₁, g₂ with
| .plus, .plus => pure ⟨.plus, q(rfl)⟩
| .plus, .minus i =>
assumeInstancesCommute
pure ⟨.minus i, q(div_neg $y₁ (b := $y₂))⟩
| .minus i, .plus =>
assumeInstancesCommute
pure ⟨.minus i, q(neg_div $y₂ $y₁)⟩
| .minus _, .minus _ =>
assumeInstancesCommute
pure ⟨.plus, q(neg_div_neg_eq $y₁ $y₂)⟩
/-- Given an expression `y : Q($M)` with specified sign (either + or -), construct a proof that
the negation of (± `y`) (here taking the specified sign) is ∓ `y`. -/
def Sign.neg (iM : Q(Field $M)) (y : Q($M)) (g : Sign M) :
MetaM (Σ (G : Sign M), Q(-$(g.expr y) = $(G.expr y))) := do
match g with
| .plus => pure ⟨.minus iM, q(rfl)⟩
| .minus _ =>
assumeInstancesCommute
pure ⟨.plus, q(neg_neg $y)⟩
/-- Given an expression `y : Q($M)` with specified sign (either + or -), construct a proof that
the exponentiation to power `s : ℕ` of (± `y`) (here taking the specified signs) is ± `y ^ s`;
return this proof and the computed sign. -/
def Sign.pow (iM : Q(CommGroupWithZero $M)) (y : Q($M)) (g : Sign M) (s : ℕ) :
MetaM (Σ (G : Sign M), Q($(g.expr y) ^ $s = $(G.expr q($y ^ $s)))) := do
match g with
| .plus => pure ⟨.plus, q(rfl)⟩
| .minus i =>
assumeInstancesCommute
if Even s then
let pf_s ← mkDecideProofQ q(Even $s)
pure ⟨.plus, q(Even.neg_pow $pf_s $y)⟩
else
let pf_s ← mkDecideProofQ q(Odd $s)
pure ⟨.minus i, q(Odd.neg_pow $pf_s $y)⟩
/-- Given an expression `y : Q($M)` with specified sign (either + or -), construct a proof that
the exponentiation to power `s : ℤ` of (± `y`) (here taking the specified signs) is ± `y ^ s`;
return this proof and the computed sign. -/
def Sign.zpow (iM : Q(CommGroupWithZero $M)) (y : Q($M)) (g : Sign M) (s : ℤ) :
MetaM (Σ (G : Sign M), Q($(g.expr y) ^ $s = $(G.expr q($y ^ $s)))) := do
match g with
| .plus => pure ⟨.plus, q(rfl)⟩
| .minus i =>
assumeInstancesCommute
if Even s then
let pf_s ← mkDecideProofQ q(Even $s)
pure ⟨.plus, q(Even.neg_zpow $pf_s $y)⟩
else
let pf_s ← mkDecideProofQ q(Odd $s)
pure ⟨.minus i, q(Odd.neg_zpow $pf_s $y)⟩
/-- Given a proof that two expressions `y₁ y₂ : Q($M)` are equal, construct a proof that (± `y₁`)
and (± `y₂`) are equal, where the same sign is taken in both expression. -/
def Sign.congr {y y' : Q($M)} (g : Sign M) (pf : Q($y = $y')) : Q($(g.expr y)= $(g.expr y')) :=
match g with
| .plus => pf
| .minus _ => q(congr_arg Neg.neg $pf)
/-- If `a` = ± `b`, `b = C * d`, and `d = e`, construct a proof that `a` = `C` * ± `e`. -/
def Sign.mkEqMul (iM : Q(CommGroupWithZero $M)) {a b C d e : Q($M)} {g : Sign M}
(pf₁ : Q($a = $(g.expr b))) (pf₂ : Q($b = $C * $d))
(pf₃ : Q($d = $e)) : MetaM Q($a = $C * $(g.expr e)) := do
let pf₂' : Q($(g.expr b) = $(g.expr q($C * $d))) := g.congr pf₂
let pf' ← Sign.mulRight iM C d g
pure q(eq_mul_of_eq_eq_eq_mul $pf₁ $pf₂' $pf' $(g.congr pf₃))
end Sign
end Mathlib.Tactic.FieldSimp |
.lake/packages/mathlib/Mathlib/Tactic/FieldSimp/Attr.lean | import Mathlib.Init
/-! # Attribute grouping the `field_simp` simprocs -/
open Lean Meta
/-- Initialize the attribute `field` grouping the simprocs associated to the field_simp tactic. -/
initialize fieldSimpExt : Simp.SimprocExtension
← Simp.registerSimprocAttr `field
"Attribute grouping the simprocs associated to the field_simp tactic" none |
.lake/packages/mathlib/Mathlib/Tactic/FieldSimp/Discharger.lean | import Mathlib.Tactic.Positivity.Core
import Mathlib.Util.DischargerAsTactic
/-!
# Discharger for `field_simp` tactic
The `field_simp` tactic (implemented downstream from this file) clears denominators in algebraic
expressions. In order to do this, the denominators need to be certified as nonzero. This file
contains the discharger which carries out these checks.
Currently the discharger tries four strategies:
1. `assumption`
2. `positivity`
3. `norm_num`
4. `simp` with the same simp-context as the `field_simp` call which invoked it
TODO: Ideally the discharger would be just `positivity` (which, despite the name, has robust
handling of general `≠ 0` goals, not just `> 0` goals). We need the other strategies currently to
get (a cheap approximation of) `positivity` on fields without a partial order.
The refactor of `positivity` to avoid a partial order assumption would be large but not
fundamentally difficult.
### Main declarations
* `Mathlib.Tactic.FieldSimp.discharge`: the discharger, of type `Expr → SimpM (Option Expr)`
* `field_simp_discharge`: tactic syntax for the discharger (most useful for testing/debugging)
-/
namespace Mathlib.Tactic.FieldSimp
open Lean Elab.Tactic Parser.Tactic Lean.Meta
open Qq
/-- Constructs a trace message for the `discharge` function. -/
private def dischargerTraceMessage {ε : Type*} (prop : Expr) :
Except ε (Option Expr) → SimpM MessageData
| .error _ | .ok none => return m!"{crossEmoji} discharge {prop}"
| .ok (some _) => return m!"{checkEmoji} discharge {prop}"
open private Simp.dischargeUsingAssumption? from Lean.Meta.Tactic.Simp.Rewrite
/-- Discharge strategy for the `field_simp` tactic. -/
partial def discharge (prop : Expr) : SimpM (Option Expr) :=
withTraceNode `Tactic.field_simp (dischargerTraceMessage prop) do
-- Discharge strategy 1: Use assumptions
if let some r ← Simp.dischargeUsingAssumption? prop then
return some r
-- Discharge strategy 2: Normalize inequalities using NormNum
let prop : Q(Prop) ← (do pure prop)
let pf? ← match prop with
| ~q(($e : $α) ≠ $b) =>
try
let res ← Mathlib.Meta.NormNum.derive prop
match res with
| .isTrue pf => pure (some pf)
| _ => pure none
catch _ =>
pure none
| _ => pure none
if let some pf := pf? then return some pf
-- Discharge strategy 3: Use positivity
let pf? ←
try some <$> Mathlib.Meta.Positivity.solve prop
catch _ => pure none
if let some pf := pf? then return some pf
-- Discharge strategy 4: Use the simplifier
Simp.withIncDischargeDepth do
let ctx ← readThe Simp.Context
-- these lemmas allow `simp` to function as a cheap approximation to `positivity` in fields
-- where `positivity` is not available (e.g. through lack of a `≤`)
let lems := [``two_ne_zero, ``three_ne_zero, ``four_ne_zero, ``mul_ne_zero, ``pow_ne_zero,
``zpow_ne_zero, ``Nat.cast_add_one_ne_zero]
let ctx' := ctx.setSimpTheorems <| ctx.simpTheorems.push <|
← lems.foldlM (SimpTheorems.addConst · · (post := false)) {}
let stats : Simp.Stats := { (← get) with }
-- Porting note: mathlib3's analogous field_simp discharger `field_simp.ne_zero`
-- does not explicitly call `simp` recursively like this. It's unclear to me
-- whether this is because
-- 1) Lean 3 simp dischargers automatically call `simp` recursively. (Do they?),
-- 2) mathlib3 norm_num1 is able to handle any needed discharging, or
-- 3) some other reason?
let ⟨simpResult, stats'⟩ ←
simp prop ctx' #[(← Simp.getSimprocs)]
discharge stats
set { (← get) with usedTheorems := stats'.usedTheorems, diag := stats'.diag }
if simpResult.expr.isConstOf ``True then
try
return some (← mkOfEqTrue (← simpResult.getProof))
catch _ =>
return none
else
return none
@[inherit_doc discharge]
elab "field_simp_discharge" : tactic => wrapSimpDischarger Mathlib.Tactic.FieldSimp.discharge
end Mathlib.Tactic.FieldSimp |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/ModEq.lean | import Mathlib.Tactic.NormNum.DivMod
import Mathlib.Data.Int.ModEq
/-!
# `norm_num` extensions for `Nat.ModEq` and `Int.ModEq`
In this file we define `norm_num` extensions for `a ≡ b [MOD n]` and `a ≡ b [ZMOD n]`.
-/
namespace Mathlib.Meta.NormNum
open Qq
/-- `norm_num` extension for `Nat.ModEq`. -/
@[norm_num _ ≡ _ [MOD _]]
def evalNatModEq : NormNumExt where eval {u αP} e := do
match u, αP, e with
| 0, ~q(Prop), ~q($a ≡ $b [MOD $n]) =>
let ⟨b, pb⟩ ← deriveBoolOfIff _ e q(Nat.modEq_iff_dvd.symm)
return .ofBoolResult pb
| _, _, _ => failure
/-- `norm_num` extension for `Int.ModEq`. -/
@[norm_num _ ≡ _ [ZMOD _]]
def evalIntModEq : NormNumExt where eval {u αP} e := do
match u, αP, e with
| 0, ~q(Prop), ~q($a ≡ $b [ZMOD $n]) =>
let ⟨b, pb⟩ ← deriveBoolOfIff _ e q(Int.modEq_iff_dvd.symm)
return .ofBoolResult pb
| _, _, _ => failure
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/DivMod.lean | import Mathlib.Tactic.NormNum.Basic
import Mathlib.Tactic.NormNum.Ineq
/-!
# `norm_num` extension for integer div/mod and divides
This file adds support for the `%`, `/`, and `∣` (divisibility) operators on `ℤ`
to the `norm_num` tactic.
-/
namespace Mathlib
open Lean
open Meta
namespace Meta.NormNum
open Qq
lemma isInt_ediv_zero : ∀ {a b r : ℤ}, IsInt a r → IsNat b (nat_lit 0) → IsNat (a / b) (nat_lit 0)
| _, _, _, ⟨rfl⟩, ⟨rfl⟩ => ⟨by simp [Int.ediv_zero]⟩
lemma isInt_ediv {a b q m a' : ℤ} {b' r : ℕ}
(ha : IsInt a a') (hb : IsNat b b')
(hm : q * b' = m) (h : r + m = a') (h₂ : Nat.blt r b' = true) :
IsInt (a / b) q := ⟨by
obtain ⟨⟨rfl⟩, ⟨rfl⟩⟩ := ha, hb
simp only [Nat.blt_eq] at h₂; simp only [← h, ← hm, Int.cast_id]
rw [Int.add_mul_ediv_right _ _ (Int.ofNat_ne_zero.2 ((Nat.zero_le ..).trans_lt h₂).ne')]
rw [Int.ediv_eq_zero_of_lt, zero_add] <;> [simp; simpa using h₂]⟩
lemma isInt_ediv_neg {a b q q' : ℤ} (h : IsInt (a / -b) q) (hq : -q = q') : IsInt (a / b) q' :=
⟨by rw [Int.cast_id, ← hq, ← @Int.cast_id q, ← h.out, ← Int.ediv_neg, Int.neg_neg]⟩
lemma isNat_neg_of_isNegNat {a : ℤ} {b : ℕ} (h : IsInt a (.negOfNat b)) : IsNat (-a) b :=
⟨by simp [h.out]⟩
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `Int.ediv a b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num (_ : ℤ) / _, Int.ediv _ _]
partial def evalIntDiv : NormNumExt where eval {u α} e := do
let .app (.app f (a : Q(ℤ))) (b : Q(ℤ)) ← whnfR e | failure
-- We assert that the default instance for `HDiv` is `Int.div` when the first parameter is `ℤ`.
guard <|← withNewMCtxDepth <| isDefEq f q(HDiv.hDiv (α := ℤ))
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℤ := ⟨⟩
haveI' : $e =Q ($a / $b) := ⟨⟩
let rℤ : Q(Ring ℤ) := q(Int.instRing)
let ⟨za, na, pa⟩ ← (← derive a).toInt rℤ
match ← derive (u := .zero) b with
| .isNat inst nb pb =>
assumeInstancesCommute
if nb.natLit! == 0 then
have _ : $nb =Q nat_lit 0 := ⟨⟩
return .isNat q(instAddMonoidWithOne) q(nat_lit 0) q(isInt_ediv_zero $pa $pb)
else
let ⟨zq, q, p⟩ := core a na za pa b nb pb
return .isInt rℤ q zq p
| .isNegNat _ nb pb =>
assumeInstancesCommute
let ⟨zq, q, p⟩ := core a na za pa q(-$b) nb q(isNat_neg_of_isNegNat $pb)
have q' := mkRawIntLit (-zq)
have : Q(-$q = $q') := (q(Eq.refl $q') :)
return .isInt rℤ q' (-zq) q(isInt_ediv_neg $p $this)
| _ => failure
where
/-- Given a result for evaluating `a b` in `ℤ` where `b > 0`, evaluate `a / b`. -/
core (a na : Q(ℤ)) (za : ℤ) (pa : Q(IsInt $a $na))
(b : Q(ℤ)) (nb : Q(ℕ)) (pb : Q(IsNat $b $nb)) :
ℤ × (q : Q(ℤ)) × Q(IsInt ($a / $b) $q) :=
let b := nb.natLit!
let q := za / b
have nq := mkRawIntLit q
let r := za.natMod b
have nr : Q(ℕ) := mkRawNatLit r
let m := q * b
have nm := mkRawIntLit m
have pf₁ : Q($nq * $nb = $nm) := (q(Eq.refl $nm) :)
have pf₂ : Q($nr + $nm = $na) := (q(Eq.refl $na) :)
have pf₃ : Q(Nat.blt $nr $nb = true) := (q(Eq.refl true) :)
⟨q, nq, q(isInt_ediv $pa $pb $pf₁ $pf₂ $pf₃)⟩
lemma isInt_emod_zero : ∀ {a b r : ℤ}, IsInt a r → IsNat b (nat_lit 0) → IsInt (a % b) r
| _, _, _, e, ⟨rfl⟩ => by simp [e]
lemma isInt_emod {a b q m a' : ℤ} {b' r : ℕ}
(ha : IsInt a a') (hb : IsNat b b')
(hm : q * b' = m) (h : r + m = a') (h₂ : Nat.blt r b' = true) :
IsNat (a % b) r := ⟨by
obtain ⟨⟨rfl⟩, ⟨rfl⟩⟩ := ha, hb
simp only [← h, ← hm, Int.add_mul_emod_self_right]
rw [Int.emod_eq_of_lt] <;> [simp; simpa using h₂]⟩
lemma isInt_emod_neg {a b : ℤ} {r : ℕ} (h : IsNat (a % -b) r) : IsNat (a % b) r :=
⟨by rw [← Int.emod_neg, h.out]⟩
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `Int.emod a b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num (_ : ℤ) % _, Int.emod _ _]
partial def evalIntMod : NormNumExt where eval {u α} e := do
let .app (.app f (a : Q(ℤ))) (b : Q(ℤ)) ← whnfR e | failure
-- We assert that the default instance for `HMod` is `Int.mod` when the first parameter is `ℤ`.
guard <|← withNewMCtxDepth <| isDefEq f q(HMod.hMod (α := ℤ))
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℤ := ⟨⟩
haveI' : $e =Q ($a % $b) := ⟨⟩
let rℤ : Q(Ring ℤ) := q(Int.instRing)
let some ⟨za, na, pa⟩ := (← derive a).toInt rℤ | failure
go a na za pa b (← derive (u := .zero) b)
where
/-- Given a result for evaluating `a b` in `ℤ`, evaluate `a % b`. -/
go (a na : Q(ℤ)) (za : ℤ) (pa : Q(IsInt $a $na))
(b : Q(ℤ)) : Result b → Option (Result q($a % $b))
| .isNat inst nb pb => do
assumeInstancesCommute
if nb.natLit! == 0 then
have _ : $nb =Q nat_lit 0 := ⟨⟩
return .isInt q(Int.instRing) na za q(isInt_emod_zero $pa $pb)
else
let ⟨r, p⟩ := core a na za pa b nb pb
return .isNat q(instAddMonoidWithOne) r p
| .isNegNat _ nb pb => do
assumeInstancesCommute
let ⟨r, p⟩ := core a na za pa q(-$b) nb q(isNat_neg_of_isNegNat $pb)
return .isNat q(instAddMonoidWithOne) r q(isInt_emod_neg $p)
| _ => none
/-- Given a result for evaluating `a b` in `ℤ` where `b > 0`, evaluate `a % b`. -/
core (a na : Q(ℤ)) (za : ℤ) (pa : Q(IsInt $a $na))
(b : Q(ℤ)) (nb : Q(ℕ)) (pb : Q(IsNat $b $nb)) :
(r : Q(ℕ)) × Q(IsNat ($a % $b) $r) :=
let b := nb.natLit!
let q := za / b
have nq := mkRawIntLit q
let r := za.natMod b
have nr : Q(ℕ) := mkRawNatLit r
let m := q * b
have nm := mkRawIntLit m
have pf₁ : Q($nq * $nb = $nm) := (q(Eq.refl $nm) :)
have pf₂ : Q($nr + $nm = $na) := (q(Eq.refl $na) :)
have pf₃ : Q(Nat.blt $nr $nb = true) := (q(Eq.refl true) :)
⟨nr, q(isInt_emod $pa $pb $pf₁ $pf₂ $pf₃)⟩
theorem isInt_dvd_true : {a b : ℤ} → {a' b' c : ℤ} →
IsInt a a' → IsInt b b' → Int.mul a' c = b' → a ∣ b
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨_, rfl⟩
theorem isInt_dvd_false : {a b : ℤ} → {a' b' : ℤ} →
IsInt a a' → IsInt b b' → Int.emod b' a' != 0 → ¬a ∣ b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, e => mt Int.emod_eq_zero_of_dvd (by simpa using e)
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `(a : ℤ) ∣ b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num (_ : ℤ) ∣ _] def evalIntDvd : NormNumExt where eval {u α} e := do
let .app (.app f (a : Q(ℤ))) (b : Q(ℤ)) ← whnfR e | failure
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q Prop := ⟨⟩
haveI' : $e =Q ($a ∣ $b) := ⟨⟩
-- We assert that the default instance for `Dvd` is `Int.dvd` when the first parameter is `ℕ`.
guard <|← withNewMCtxDepth <| isDefEq f q(Dvd.dvd (α := ℤ))
let rℤ : Q(Ring ℤ) := q(Int.instRing)
let ⟨za, na, pa⟩ ← (← derive a).toInt rℤ
let ⟨zb, nb, pb⟩ ← (← derive b).toInt rℤ
if zb % za == 0 then
let zc := zb / za
have c := mkRawIntLit zc
haveI' : Int.mul $na $c =Q $nb := ⟨⟩
return .isTrue q(isInt_dvd_true $pa $pb (.refl $nb))
else
have : Q(Int.emod $nb $na != 0) := (q(Eq.refl true) : Expr)
return .isFalse q(isInt_dvd_false $pa $pb $this)
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Ineq.lean | import Mathlib.Tactic.NormNum.Eq
import Mathlib.Algebra.Order.Invertible
import Mathlib.Algebra.Order.Monoid.WithTop
import Mathlib.Algebra.Order.Ring.Cast
/-!
# `norm_num` extensions for inequalities.
-/
open Lean Meta Qq
namespace Mathlib.Meta.NormNum
variable {u : Level}
/-- Helper function to synthesize typed `Semiring α` `PartialOrder α` `IsOrderedSemiring α`
expressions. -/
def inferOrderedSemiring (α : Q(Type u)) : MetaM <|
(_ : Q(Semiring $α)) × (_ : Q(PartialOrder $α)) × Q(IsOrderedRing $α) :=
let go := do
let semiring ← synthInstanceQ q(Semiring $α)
let partialOrder ← synthInstanceQ q(PartialOrder $α)
let isOrderedRing ← synthInstanceQ q(IsOrderedRing $α)
return ⟨semiring, partialOrder, isOrderedRing⟩
go <|> throwError "not an ordered semiring"
/-- Helper function to synthesize typed `Ring α` `PartialOrder α` `IsOrderedSemiring α`
expressions. -/
def inferOrderedRing (α : Q(Type u)) : MetaM <|
(_ : Q(Ring $α)) × (_ : Q(PartialOrder $α)) × Q(IsOrderedRing $α) :=
let go := do
let ring ← synthInstanceQ q(Ring $α)
let partialOrder ← synthInstanceQ q(PartialOrder $α)
let isOrderedRing ← synthInstanceQ q(IsOrderedRing $α)
return ⟨ring, partialOrder, isOrderedRing⟩
go <|> throwError "not an ordered ring"
/-- Helper function to synthesize typed `Semifield α` `LinearOrder α` `IsStrictOrderedRing α`
expressions. -/
def inferLinearOrderedSemifield (α : Q(Type u)) : MetaM <|
(_ : Q(Semifield $α)) × (_ : Q(LinearOrder $α)) × Q(IsStrictOrderedRing $α) :=
let go := do
let semifield ← synthInstanceQ q(Semifield $α)
let linearOrder ← synthInstanceQ q(LinearOrder $α)
let isStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $α)
return ⟨semifield, linearOrder, isStrictOrderedRing⟩
go <|> throwError "not a linear ordered semifield"
/-- Helper function to synthesize typed `Field α` `LinearOrder α` `IsStrictOrderedRing α`
expressions. -/
def inferLinearOrderedField (α : Q(Type u)) : MetaM <|
(_ : Q(Field $α)) × (_ : Q(LinearOrder $α)) × Q(IsStrictOrderedRing $α) :=
let go := do
let field ← synthInstanceQ q(Field $α)
let linearOrder ← synthInstanceQ q(LinearOrder $α)
let isStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $α)
return ⟨field, linearOrder, isStrictOrderedRing⟩
go <|> throwError "not a linear ordered field"
variable {α : Type*}
theorem isNat_le_true [Semiring α] [PartialOrder α] [IsOrderedRing α] : {a b : α} → {a' b' : ℕ} →
IsNat a a' → IsNat b b' → Nat.ble a' b' = true → a ≤ b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Nat.mono_cast (Nat.le_of_ble_eq_true h)
theorem isNat_lt_false [Semiring α] [PartialOrder α] [IsOrderedRing α] {a b : α} {a' b' : ℕ}
(ha : IsNat a a') (hb : IsNat b b') (h : Nat.ble b' a' = true) : ¬a < b :=
not_lt_of_ge (isNat_le_true hb ha h)
theorem isNNRat_le_true [Semiring α] [LinearOrder α] [IsStrictOrderedRing α] :
{a b : α} → {na nb : ℕ} → {da db : ℕ} →
IsNNRat a na da → IsNNRat b nb db →
decide (Nat.mul na (db) ≤ Nat.mul nb (da)) → a ≤ b
| _, _, _, _, da, db, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by
have h := (Nat.cast_le (α := α)).mpr <| of_decide_eq_true h
have ha : 0 ≤ ⅟(da : α) := invOf_nonneg.mpr <| Nat.cast_nonneg da
have hb : 0 ≤ ⅟(db : α) := invOf_nonneg.mpr <| Nat.cast_nonneg db
have h := (mul_le_mul_of_nonneg_left · hb) <| mul_le_mul_of_nonneg_right h ha
rw [← mul_assoc, Nat.commute_cast] at h
simp only [Nat.mul_eq, Nat.cast_mul, mul_invOf_cancel_right'] at h
rwa [Nat.commute_cast] at h
theorem isNNRat_lt_true [Semiring α] [LinearOrder α] [IsStrictOrderedRing α] [Nontrivial α] :
{a b : α} → {na nb : ℕ} → {da db : ℕ} →
IsNNRat a na da → IsNNRat b nb db → decide (na * db < nb * da) → a < b
| _, _, _, _, da, db, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by
have h := (Nat.cast_lt (α := α)).mpr <| of_decide_eq_true h
have ha : 0 < ⅟(da : α) := pos_invOf_of_invertible_cast da
have hb : 0 < ⅟(db : α) := pos_invOf_of_invertible_cast db
have h := (mul_lt_mul_of_pos_left · hb) <| mul_lt_mul_of_pos_right h ha
rw [← mul_assoc, Nat.commute_cast] at h
simp? at h says simp only [Nat.cast_mul, mul_invOf_cancel_right'] at h
rwa [Nat.commute_cast] at h
theorem isNNRat_le_false [Semiring α] [LinearOrder α] [IsStrictOrderedRing α] [Nontrivial α]
{a b : α} {na nb : ℕ} {da db : ℕ}
(ha : IsNNRat a na da) (hb : IsNNRat b nb db) (h : decide (nb * da < na * db)) : ¬a ≤ b :=
not_le_of_gt (isNNRat_lt_true hb ha h)
theorem isNNRat_lt_false [Semiring α] [LinearOrder α] [IsStrictOrderedRing α]
{a b : α} {na nb : ℕ} {da db : ℕ}
(ha : IsNNRat a na da) (hb : IsNNRat b nb db) (h : decide (nb * da ≤ na * db)) : ¬a < b :=
not_lt_of_ge (isNNRat_le_true hb ha h)
theorem isRat_le_true [Ring α] [LinearOrder α] [IsStrictOrderedRing α] :
{a b : α} → {na nb : ℤ} → {da db : ℕ} →
IsRat a na da → IsRat b nb db →
decide (Int.mul na (.ofNat db) ≤ Int.mul nb (.ofNat da)) → a ≤ b
| _, _, _, _, da, db, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by
have h := Int.cast_mono (R := α) <| of_decide_eq_true h
have ha : 0 ≤ ⅟(da : α) := invOf_nonneg.mpr <| Nat.cast_nonneg da
have hb : 0 ≤ ⅟(db : α) := invOf_nonneg.mpr <| Nat.cast_nonneg db
have h := (mul_le_mul_of_nonneg_left · hb) <| mul_le_mul_of_nonneg_right h ha
rw [← mul_assoc, Int.commute_cast] at h
simp only [Int.ofNat_eq_coe, Int.mul_def, Int.cast_mul, Int.cast_natCast,
mul_invOf_cancel_right'] at h
rwa [Int.commute_cast] at h
theorem isRat_lt_true [Ring α] [LinearOrder α] [IsStrictOrderedRing α] [Nontrivial α] :
{a b : α} → {na nb : ℤ} → {da db : ℕ} →
IsRat a na da → IsRat b nb db → decide (na * db < nb * da) → a < b
| _, _, _, _, da, db, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by
have h := Int.cast_strictMono (R := α) <| of_decide_eq_true h
have ha : 0 < ⅟(da : α) := pos_invOf_of_invertible_cast da
have hb : 0 < ⅟(db : α) := pos_invOf_of_invertible_cast db
have h := (mul_lt_mul_of_pos_left · hb) <| mul_lt_mul_of_pos_right h ha
rw [← mul_assoc, Int.commute_cast] at h
simp? at h says simp only [Int.cast_mul, Int.cast_natCast, mul_invOf_cancel_right'] at h
rwa [Int.commute_cast] at h
theorem isRat_le_false [Ring α] [LinearOrder α] [IsStrictOrderedRing α] [Nontrivial α]
{a b : α} {na nb : ℤ} {da db : ℕ}
(ha : IsRat a na da) (hb : IsRat b nb db) (h : decide (nb * da < na * db)) : ¬a ≤ b :=
not_le_of_gt (isRat_lt_true hb ha h)
theorem isRat_lt_false [Ring α] [LinearOrder α] [IsStrictOrderedRing α]
{a b : α} {na nb : ℤ} {da db : ℕ}
(ha : IsRat a na da) (hb : IsRat b nb db) (h : decide (nb * da ≤ na * db)) : ¬a < b :=
not_lt_of_ge (isRat_le_true hb ha h)
/-! ### (In)equalities -/
theorem isNat_lt_true [Semiring α] [PartialOrder α] [IsOrderedRing α] [CharZero α] :
{a b : α} → {a' b' : ℕ} →
IsNat a a' → IsNat b b' → Nat.ble b' a' = false → a < b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h =>
Nat.cast_lt.2 <| ble_eq_false.1 h
theorem isNat_le_false [Semiring α] [PartialOrder α] [IsOrderedRing α] [CharZero α]
{a b : α} {a' b' : ℕ}
(ha : IsNat a a') (hb : IsNat b b') (h : Nat.ble a' b' = false) : ¬a ≤ b :=
not_le_of_gt (isNat_lt_true hb ha h)
theorem isInt_le_true [Ring α] [PartialOrder α] [IsOrderedRing α] : {a b : α} → {a' b' : ℤ} →
IsInt a a' → IsInt b b' → decide (a' ≤ b') → a ≤ b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Int.cast_mono <| of_decide_eq_true h
theorem isInt_lt_true [Ring α] [PartialOrder α] [IsOrderedRing α] [Nontrivial α] :
{a b : α} → {a' b' : ℤ} →
IsInt a a' → IsInt b b' → decide (a' < b') → a < b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Int.cast_lt.2 <| of_decide_eq_true h
theorem isInt_le_false [Ring α] [PartialOrder α] [IsOrderedRing α] [Nontrivial α]
{a b : α} {a' b' : ℤ}
(ha : IsInt a a') (hb : IsInt b b') (h : decide (b' < a')) : ¬a ≤ b :=
not_le_of_gt (isInt_lt_true hb ha h)
theorem isInt_lt_false [Ring α] [PartialOrder α] [IsOrderedRing α] {a b : α} {a' b' : ℤ}
(ha : IsInt a a') (hb : IsInt b b') (h : decide (b' ≤ a')) : ¬a < b :=
not_lt_of_ge (isInt_le_true hb ha h)
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `a ≤ b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num _ ≤ _] def evalLE : NormNumExt where eval {v β} e := do
haveI' : v =QL 0 := ⟨⟩; haveI' : $β =Q Prop := ⟨⟩
let .app (.app f a) b ← whnfR e | failure
let ⟨u, α, a⟩ ← inferTypeQ' a
have b : Q($α) := b
let ra ← derive a; let rb ← derive b
let lα ← synthInstanceQ q(LE $α)
guard <|← withNewMCtxDepth <| isDefEq f q(LE.le (α := $α))
core lα ra rb
where
/-- Identify (as `true` or `false`) expressions of the form `a ≤ b`, where `a` and `b` are numeric
expressions whose evaluations to `NormNum.Result` have already been computed. -/
core {u : Level} {α : Q(Type u)} (lα : Q(LE $α)) {a b : Q($α)}
(ra : NormNum.Result a) (rb : NormNum.Result b) : MetaM (NormNum.Result q($a ≤ $b)) := do
let e := q($a ≤ $b)
let rec intArm : MetaM (Result e) := do
let ⟨_ir, _, _i⟩ ← inferOrderedRing α
haveI' : $e =Q ($a ≤ $b) := ⟨⟩
let ⟨za, na, pa⟩ ← ra.toInt q($_ir)
let ⟨zb, nb, pb⟩ ← rb.toInt q($_ir)
assumeInstancesCommute
if decide (za ≤ zb) then
let r : Q(decide ($na ≤ $nb) = true) := (q(Eq.refl true) : Expr)
return .isTrue q(isInt_le_true $pa $pb $r)
else if let .some _i ← trySynthInstanceQ q(Nontrivial $α) then
let r : Q(decide ($nb < $na) = true) := (q(Eq.refl true) : Expr)
return .isFalse q(isInt_le_false $pa $pb $r)
else
failure
let rec ratArm : MetaM (Result e) := do
let ⟨_if, _, _i⟩ ← inferLinearOrderedField α
haveI' : $e =Q ($a ≤ $b) := ⟨⟩
let ⟨qa, na, da, pa⟩ ← ra.toRat' q(Field.toDivisionRing)
let ⟨qb, nb, db, pb⟩ ← rb.toRat' q(Field.toDivisionRing)
assumeInstancesCommute
if decide (qa ≤ qb) then
let r : Q(decide ($na * $db ≤ $nb * $da) = true) := (q(Eq.refl true) : Expr)
return (.isTrue q(isRat_le_true $pa $pb $r))
else
let _i : Q(Nontrivial $α) := q(IsStrictOrderedRing.toNontrivial)
let r : Q(decide ($nb * $da < $na * $db) = true) := (q(Eq.refl true) : Expr)
return .isFalse q(isRat_le_false $pa $pb $r)
match ra, rb with
| .isBool .., _ | _, .isBool .. => failure
| .isNNRat _ .., _ | _, .isNNRat _ .. => ratArm
| .isNegNNRat _ .., _ | _, .isNegNNRat _ .. => ratArm
| .isNegNat _ .., _ | _, .isNegNat _ .. => intArm
| .isNat ra na pa, .isNat rb nb pb =>
let ⟨_, _, _i⟩ ← inferOrderedSemiring α
haveI' : $ra =Q by clear! $ra $rb; infer_instance := ⟨⟩
haveI' : $rb =Q by clear! $ra $rb; infer_instance := ⟨⟩
haveI' : $e =Q ($a ≤ $b) := ⟨⟩
assumeInstancesCommute
if na.natLit! ≤ nb.natLit! then
let r : Q(Nat.ble $na $nb = true) := (q(Eq.refl true) : Expr)
return .isTrue q(isNat_le_true $pa $pb $r)
else if let .some _i ← trySynthInstanceQ q(CharZero $α) then
let r : Q(Nat.ble $na $nb = false) := (q(Eq.refl false) : Expr)
return .isFalse q(isNat_le_false $pa $pb $r)
else -- Nats can appear in an `OrderedRing` without `CharZero`.
intArm
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `a < b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num _ < _] def evalLT : NormNumExt where eval {v β} e := do
haveI' : v =QL 0 := ⟨⟩; haveI' : $β =Q Prop := ⟨⟩
let .app (.app f a) b ← whnfR e | failure
let ⟨u, α, a⟩ ← inferTypeQ' a
have b : Q($α) := b
let ra ← derive a; let rb ← derive b
let lα ← synthInstanceQ q(LT $α)
guard <|← withNewMCtxDepth <| isDefEq f q(LT.lt (α := $α))
core lα ra rb
where
/-- Identify (as `true` or `false`) expressions of the form `a < b`, where `a` and `b` are numeric
expressions whose evaluations to `NormNum.Result` have already been computed. -/
core {u : Level} {α : Q(Type u)} (lα : Q(LT $α)) {a b : Q($α)}
(ra : NormNum.Result a) (rb : NormNum.Result b) : MetaM (NormNum.Result q($a < $b)) := do
let e := q($a < $b)
let rec intArm : MetaM (Result e) := do
let ⟨_ir, _, _i⟩ ← inferOrderedRing α
haveI' : $e =Q ($a < $b) := ⟨⟩
let ⟨za, na, pa⟩ ← ra.toInt q($_ir)
let ⟨zb, nb, pb⟩ ← rb.toInt q($_ir)
assumeInstancesCommute
if za < zb then
if let .some _i ← trySynthInstanceQ q(Nontrivial $α) then
let r : Q(decide ($na < $nb) = true) := (q(Eq.refl true) : Expr)
return .isTrue q(isInt_lt_true $pa $pb $r)
else
failure
else
let r : Q(decide ($nb ≤ $na) = true) := (q(Eq.refl true) : Expr)
return .isFalse q(isInt_lt_false $pa $pb $r)
let rec nnratArm : MetaM (Result e) := do
-- We need a division ring with an order, and `LinearOrderedField` is the closest mathlib has.
/-
NOTE: after the ordered algebra refactor, this is not true anymore,
so there may be a better typeclass
-/
let ⟨_, _, _⟩ ← inferLinearOrderedSemifield α
assumeInstancesCommute
haveI' : $e =Q ($a < $b) := ⟨⟩
let ⟨qa, na, da, pa⟩ ← ra.toNNRat' q(Semifield.toDivisionSemiring)
let ⟨qb, nb, db, pb⟩ ← rb.toNNRat' q(Semifield.toDivisionSemiring)
if qa < qb then
let r : Q(decide ($na * $db < $nb * $da) = true) := (q(Eq.refl true) : Expr)
return .isTrue q(isNNRat_lt_true $pa $pb $r)
else
let r : Q(decide ($nb * $da ≤ $na * $db) = true) := (q(Eq.refl true) : Expr)
return .isFalse q(isNNRat_lt_false $pa $pb $r)
let rec ratArm : MetaM (Result e) := do
-- We need a division ring with an order, and `LinearOrderedField` is the closest mathlib has.
/-
NOTE: after the ordered algebra refactor, this is not true anymore,
so there may be a better typeclass
-/
let ⟨_, _, _i⟩ ← inferLinearOrderedField α
assumeInstancesCommute
haveI' : $e =Q ($a < $b) := ⟨⟩
let ⟨qa, na, da, pa⟩ ← ra.toRat' q(Field.toDivisionRing)
let ⟨qb, nb, db, pb⟩ ← rb.toRat' q(Field.toDivisionRing)
if qa < qb then
let r : Q(decide ($na * $db < $nb * $da) = true) := (q(Eq.refl true) : Expr)
return .isTrue q(isRat_lt_true $pa $pb $r)
else
let r : Q(decide ($nb * $da ≤ $na * $db) = true) := (q(Eq.refl true) : Expr)
return .isFalse q(isRat_lt_false $pa $pb $r)
match ra, rb with
| .isBool .., _ | _, .isBool .. => failure
| .isNegNNRat _ .., _ | _, .isNegNNRat _ .. => ratArm
-- mixing positive rationals and negative naturals means we need to use the full rat handler
| .isNNRat _ .., .isNegNat _ .. | .isNegNat _ .., .isNNRat _ .. => ratArm
| .isNNRat _ .., _ | _, .isNNRat _ .. => nnratArm
| .isNegNat _ .., _ | _, .isNegNat _ .. => intArm
| .isNat ra na pa, .isNat rb nb pb =>
let ⟨_, _, _i⟩ ← inferOrderedSemiring α
haveI' : $ra =Q by clear! $ra $rb; infer_instance := ⟨⟩
haveI' : $rb =Q by clear! $ra $rb; infer_instance := ⟨⟩
haveI' : $e =Q ($a < $b) := ⟨⟩
assumeInstancesCommute
if na.natLit! < nb.natLit! then
if let .some _i ← trySynthInstanceQ q(CharZero $α) then
let r : Q(Nat.ble $nb $na = false) := (q(Eq.refl false) : Expr)
return .isTrue q(isNat_lt_true $pa $pb $r)
else -- Nats can appear in an `OrderedRing` without `CharZero`.
intArm
else
let r : Q(Nat.ble $nb $na = true) := (q(Eq.refl true) : Expr)
return .isFalse q(isNat_lt_false $pa $pb $r)
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/NatFib.lean | import Mathlib.Data.Nat.Fib.Basic
import Mathlib.Tactic.NormNum
/-! # `norm_num` extension for `Nat.fib`
This `norm_num` extension uses a strategy parallel to that of `Nat.fastFib`, but it instead
produces proofs of what `Nat.fib` evaluates to.
-/
namespace Mathlib.Meta.NormNum
open Qq Lean Elab.Tactic
open Nat
/-- Auxiliary definition for `proveFib` extension. -/
def IsFibAux (n a b : ℕ) :=
fib n = a ∧ fib (n + 1) = b
theorem isFibAux_zero : IsFibAux 0 0 1 :=
⟨fib_zero, fib_one⟩
theorem isFibAux_one : IsFibAux 1 1 1 :=
⟨fib_one, fib_two⟩
theorem isFibAux_two_mul {n a b n' a' b' : ℕ} (H : IsFibAux n a b)
(hn : 2 * n = n') (h1 : a * (2 * b - a) = a') (h2 : a * a + b * b = b') :
IsFibAux n' a' b' :=
⟨by rw [← hn, fib_two_mul, H.1, H.2, ← h1],
by rw [← hn, fib_two_mul_add_one, H.1, H.2, pow_two, pow_two, add_comm, h2]⟩
theorem isFibAux_two_mul_add_one {n a b n' a' b' : ℕ} (H : IsFibAux n a b)
(hn : 2 * n + 1 = n') (h1 : a * a + b * b = a') (h2 : b * (2 * a + b) = b') :
IsFibAux n' a' b' :=
⟨by rw [← hn, fib_two_mul_add_one, H.1, H.2, pow_two, pow_two, add_comm, h1],
by rw [← hn, fib_two_mul_add_two, H.1, H.2, h2]⟩
partial def proveNatFibAux (en' : Q(ℕ)) : (ea' eb' : Q(ℕ)) × Q(IsFibAux $en' $ea' $eb') :=
match en'.natLit! with
| 0 =>
have : $en' =Q nat_lit 0 := ⟨⟩;
⟨q(nat_lit 0), q(nat_lit 1), q(isFibAux_zero)⟩
| 1 =>
have : $en' =Q nat_lit 1 := ⟨⟩;
⟨q(nat_lit 1), q(nat_lit 1), q(isFibAux_one)⟩
| n' =>
have en : Q(ℕ) := mkRawNatLit <| n' / 2
let ⟨ea, eb, H⟩ := proveNatFibAux en
let a := ea.natLit!
let b := eb.natLit!
if n' % 2 == 0 then
have hn : Q(2 * $en = $en') := (q(Eq.refl $en') : Expr)
have ea' : Q(ℕ) := mkRawNatLit <| a * (2 * b - a)
have eb' : Q(ℕ) := mkRawNatLit <| a * a + b * b
have h1 : Q($ea * (2 * $eb - $ea) = $ea') := (q(Eq.refl $ea') : Expr)
have h2 : Q($ea * $ea + $eb * $eb = $eb') := (q(Eq.refl $eb') : Expr)
⟨ea', eb', q(isFibAux_two_mul $H $hn $h1 $h2)⟩
else
have hn : Q(2 * $en + 1 = $en') := (q(Eq.refl $en') : Expr)
have ea' : Q(ℕ) := mkRawNatLit <| a * a + b * b
have eb' : Q(ℕ) := mkRawNatLit <| b * (2 * a + b)
have h1 : Q($ea * $ea + $eb * $eb = $ea') := (q(Eq.refl $ea') : Expr)
have h2 : Q($eb * (2 * $ea + $eb) = $eb') := (q(Eq.refl $eb') : Expr)
⟨ea', eb', q(isFibAux_two_mul_add_one $H $hn $h1 $h2)⟩
theorem isFibAux_two_mul_done {n a b n' a' : ℕ} (H : IsFibAux n a b)
(hn : 2 * n = n') (h : a * (2 * b - a) = a') : fib n' = a' :=
(isFibAux_two_mul H hn h rfl).1
theorem isFibAux_two_mul_add_one_done {n a b n' a' : ℕ} (H : IsFibAux n a b)
(hn : 2 * n + 1 = n') (h : a * a + b * b = a') : fib n' = a' :=
(isFibAux_two_mul_add_one H hn h rfl).1
/-- Given the natural number literal `ex`, returns `Nat.fib ex` as a natural number literal
and an equality proof. Panics if `ex` isn't a natural number literal. -/
def proveNatFib (en' : Q(ℕ)) : (em : Q(ℕ)) × Q(Nat.fib $en' = $em) :=
match en'.natLit! with
| 0 => have : $en' =Q nat_lit 0 := ⟨⟩; ⟨q(nat_lit 0), q(Nat.fib_zero)⟩
| 1 => have : $en' =Q nat_lit 1 := ⟨⟩; ⟨q(nat_lit 1), q(Nat.fib_one)⟩
| 2 => have : $en' =Q nat_lit 2 := ⟨⟩; ⟨q(nat_lit 1), q(Nat.fib_two)⟩
| n' =>
have en : Q(ℕ) := mkRawNatLit <| n' / 2
let ⟨ea, eb, H⟩ := proveNatFibAux en
let a := ea.natLit!
let b := eb.natLit!
if n' % 2 == 0 then
have hn : Q(2 * $en = $en') := (q(Eq.refl $en') : Expr)
have ea' : Q(ℕ) := mkRawNatLit <| a * (2 * b - a)
have h1 : Q($ea * (2 * $eb - $ea) = $ea') := (q(Eq.refl $ea') : Expr)
⟨ea', q(isFibAux_two_mul_done $H $hn $h1)⟩
else
have hn : Q(2 * $en + 1 = $en') := (q(Eq.refl $en') : Expr)
have ea' : Q(ℕ) := mkRawNatLit <| a * a + b * b
have h1 : Q($ea * $ea + $eb * $eb = $ea') := (q(Eq.refl $ea') : Expr)
⟨ea', q(isFibAux_two_mul_add_one_done $H $hn $h1)⟩
theorem isNat_fib : {x nx z : ℕ} → IsNat x nx → Nat.fib nx = z → IsNat (Nat.fib x) z
| _, _, _, ⟨rfl⟩, rfl => ⟨rfl⟩
/-- Evaluates the `Nat.fib` function. -/
@[norm_num Nat.fib _]
def evalNatFib : NormNumExt where eval {_ _} e := do
let .app _ (x : Q(ℕ)) ← Meta.whnfR e | failure
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨ex, p⟩ ← deriveNat x sℕ
let ⟨ey, pf⟩ := proveNatFib ex
let pf' : Q(IsNat (Nat.fib $x) $ey) := q(isNat_fib $p $pf)
return .isNat sℕ ey pf'
end NormNum
end Meta
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Pow.lean | import Mathlib.Data.Int.Cast.Lemmas
import Mathlib.Tactic.NormNum.Basic
/-!
## `norm_num` plugin for `^`.
-/
assert_not_exists RelIso
namespace Mathlib
open Lean
open Meta
namespace Meta.NormNum
open Qq
variable {a b c : ℕ}
theorem natPow_zero : Nat.pow a (nat_lit 0) = nat_lit 1 := rfl
theorem natPow_one : Nat.pow a (nat_lit 1) = a := Nat.pow_one _
theorem zero_natPow : Nat.pow (nat_lit 0) (Nat.succ b) = nat_lit 0 := rfl
theorem one_natPow : Nat.pow (nat_lit 1) b = nat_lit 1 := Nat.one_pow _
/-- This is an opaque wrapper around `Nat.pow` to prevent lean from unfolding the definition of
`Nat.pow` on numerals. The arbitrary precondition `p` is actually a formula of the form
`Nat.pow a' b' = c'` but we usually don't care to unfold this proposition so we just carry a
reference to it. -/
structure IsNatPowT (p : Prop) (a b c : Nat) : Prop where
/-- Unfolds the assertion. -/
run' : p → Nat.pow a b = c
theorem IsNatPowT.run
(p : IsNatPowT (Nat.pow a (nat_lit 1) = a) a b c) : Nat.pow a b = c := p.run' (Nat.pow_one _)
/-- This is the key to making the proof proceed as a balanced tree of applications instead of
a linear sequence. It is just modus ponens after unwrapping the definitions. -/
theorem IsNatPowT.trans {p : Prop} {b' c' : ℕ} (h1 : IsNatPowT p a b c)
(h2 : IsNatPowT (Nat.pow a b = c) a b' c') : IsNatPowT p a b' c' :=
⟨h2.run' ∘ h1.run'⟩
theorem IsNatPowT.bit0 : IsNatPowT (Nat.pow a b = c) a (nat_lit 2 * b) (Nat.mul c c) :=
⟨fun h1 => by simp [two_mul, pow_add, ← h1]⟩
theorem IsNatPowT.bit1 :
IsNatPowT (Nat.pow a b = c) a (nat_lit 2 * b + nat_lit 1) (Nat.mul c (Nat.mul c a)) :=
⟨fun h1 => by simp [two_mul, pow_add, mul_assoc, ← h1]⟩
/--
Proves `Nat.pow a b = c` where `a` and `b` are raw nat literals. This could be done by just
`rfl` but the kernel does not have a special case implementation for `Nat.pow` so this would
proceed by unary recursion on `b`, which is too slow and also leads to deep recursion.
We instead do the proof by binary recursion, but this can still lead to deep recursion,
so we use an additional trick to do binary subdivision on `log2 b`. As a result this produces
a proof of depth `log (log b)` which will essentially never overflow before the numbers involved
themselves exceed memory limits.
-/
partial def evalNatPow (a b : Q(ℕ)) : OptionT CoreM ((c : Q(ℕ)) × Q(Nat.pow $a $b = $c)) := do
if b.natLit! = 0 then
haveI : $b =Q 0 := ⟨⟩
return ⟨q(nat_lit 1), q(natPow_zero)⟩
else if a.natLit! = 0 then
haveI : $a =Q 0 := ⟨⟩
have b' : Q(ℕ) := mkRawNatLit (b.natLit! - 1)
haveI : $b =Q Nat.succ $b' := ⟨⟩
return ⟨q(nat_lit 0), q(zero_natPow)⟩
else if a.natLit! = 1 then
haveI : $a =Q 1 := ⟨⟩
return ⟨q(nat_lit 1), q(one_natPow)⟩
else if b.natLit! = 1 then
haveI : $b =Q 1 := ⟨⟩
return ⟨a, q(natPow_one)⟩
else
guard <| ← Lean.checkExponent b.natLit!
let ⟨c, p⟩ := go b.natLit!.log2 a q(nat_lit 1) a b _ .rfl
return ⟨c, q(($p).run)⟩
where
/-- Invariants: `a ^ b₀ = c₀`, `depth > 0`, `b >>> depth = b₀`, `p := Nat.pow $a $b₀ = $c₀` -/
go (depth : Nat) (a b₀ c₀ b : Q(ℕ)) (p : Q(Prop)) (hp : $p =Q (Nat.pow $a $b₀ = $c₀)) :
(c : Q(ℕ)) × Q(IsNatPowT $p $a $b $c) :=
let b' := b.natLit!
if depth ≤ 1 then
let a' := a.natLit!
let c₀' := c₀.natLit!
if b' &&& 1 == 0 then
have c : Q(ℕ) := mkRawNatLit (c₀' * c₀')
haveI : $c =Q Nat.mul $c₀ $c₀ := ⟨⟩
haveI : $b =Q 2 * $b₀ := ⟨⟩
⟨c, q(IsNatPowT.bit0)⟩
else
have c : Q(ℕ) := mkRawNatLit (c₀' * (c₀' * a'))
haveI : $c =Q Nat.mul $c₀ (Nat.mul $c₀ $a) := ⟨⟩
haveI : $b =Q 2 * $b₀ + 1 := ⟨⟩
⟨c, q(IsNatPowT.bit1)⟩
else
let d := depth >>> 1
have hi : Q(ℕ) := mkRawNatLit (b' >>> d)
let ⟨c1, p1⟩ := go (depth - d) a b₀ c₀ hi p (by exact hp)
let ⟨c2, p2⟩ := go d a hi c1 b q(Nat.pow $a $hi = $c1) ⟨⟩
⟨c2, q(($p1).trans $p2)⟩
theorem intPow_ofNat (h1 : Nat.pow a b = c) :
Int.pow (Int.ofNat a) b = Int.ofNat c := by simp [← h1]
theorem intPow_negOfNat_bit0 {b' c' : ℕ} (h1 : Nat.pow a b' = c')
(hb : nat_lit 2 * b' = b) (hc : c' * c' = c) :
Int.pow (Int.negOfNat a) b = Int.ofNat c := by
rw [← hb, Int.negOfNat_eq, Int.pow_eq, pow_mul, neg_pow_two, ← pow_mul, two_mul, pow_add, ← hc,
← h1]
simp
theorem intPow_negOfNat_bit1 {b' c' : ℕ} (h1 : Nat.pow a b' = c')
(hb : nat_lit 2 * b' + nat_lit 1 = b) (hc : c' * (c' * a) = c) :
Int.pow (Int.negOfNat a) b = Int.negOfNat c := by
rw [← hb, Int.negOfNat_eq, Int.negOfNat_eq, Int.pow_eq, pow_succ, pow_mul, neg_pow_two, ← pow_mul,
two_mul, pow_add, ← hc, ← h1]
simp [mul_comm, mul_left_comm]
/-- Evaluates `Int.pow a b = c` where `a` and `b` are raw integer literals. -/
partial def evalIntPow (za : ℤ) (a : Q(ℤ)) (b : Q(ℕ)) :
OptionT CoreM (ℤ × (c : Q(ℤ)) × Q(Int.pow $a $b = $c)) := do
have a' : Q(ℕ) := a.appArg!
if 0 ≤ za then
have : $a =Q .ofNat $a' := ⟨⟩
let ⟨c, p⟩ ← evalNatPow a' b
return ⟨c.natLit!, q(.ofNat $c), q(intPow_ofNat $p)⟩
else
have : $a =Q .negOfNat $a' := ⟨⟩
let b' := b.natLit!
have b₀ : Q(ℕ) := mkRawNatLit (b' >>> 1)
let ⟨c₀, p⟩ := ← evalNatPow a' b₀
let c' := c₀.natLit!
if b' &&& 1 == 0 then
have c : Q(ℕ) := mkRawNatLit (c' * c')
have pc : Q($c₀ * $c₀ = $c) := (q(Eq.refl $c) : Expr)
have pb : Q(2 * $b₀ = $b) := (q(Eq.refl $b) : Expr)
return ⟨c.natLit!, q(.ofNat $c), q(intPow_negOfNat_bit0 $p $pb $pc)⟩
else
have c : Q(ℕ) := mkRawNatLit (c' * (c' * a'.natLit!))
have pc : Q($c₀ * ($c₀ * $a') = $c) := (q(Eq.refl $c) : Expr)
have pb : Q(2 * $b₀ + 1 = $b) := (q(Eq.refl $b) : Expr)
return ⟨-c.natLit!, q(.negOfNat $c), q(intPow_negOfNat_bit1 $p $pb $pc)⟩
-- see note [norm_num lemma function equality]
theorem isNat_pow {α} [Semiring α] : ∀ {f : α → ℕ → α} {a : α} {b a' b' c : ℕ},
f = HPow.hPow → IsNat a a' → IsNat b b' → Nat.pow a' b' = c → IsNat (f a b) c
| _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨by simp⟩
-- see note [norm_num lemma function equality]
theorem isInt_pow {α} [Ring α] : ∀ {f : α → ℕ → α} {a : α} {b : ℕ} {a' : ℤ} {b' : ℕ} {c : ℤ},
f = HPow.hPow → IsInt a a' → IsNat b b' → Int.pow a' b' = c → IsInt (f a b) c
| _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨by simp⟩
-- see note [norm_num lemma function equality]
theorem isRat_pow {α} [Ring α] {f : α → ℕ → α} {a : α} {an cn : ℤ} {ad b b' cd : ℕ} :
f = HPow.hPow → IsRat a an ad → IsNat b b' →
Int.pow an b' = cn → Nat.pow ad b' = cd →
IsRat (f a b) cn cd := by
rintro rfl ⟨_, rfl⟩ ⟨rfl⟩ (rfl : an ^ b = _) (rfl : ad ^ b = _)
have := invertiblePow (ad:α) b
rw [← Nat.cast_pow] at this
use this; simp [invOf_pow, Commute.mul_pow]
theorem isNNRat_pow {α} [Semiring α] {f : α → ℕ → α} {a : α} {an cn : ℕ} {ad b b' cd : ℕ} :
f = HPow.hPow → IsNNRat a an ad → IsNat b b' →
Nat.pow an b' = cn → Nat.pow ad b' = cd →
IsNNRat (f a b) cn cd := by
rintro rfl ⟨_, rfl⟩ ⟨rfl⟩ (rfl : an ^ b = _) (rfl : ad ^ b = _)
have := invertiblePow (ad:α) b
rw [← Nat.cast_pow] at this
use this; simp [invOf_pow, Commute.mul_pow, Nat.cast_commute]
/-- Main part of `evalPow`. -/
def evalPow.core {u : Level} {α : Q(Type u)} (e : Q(«$α»)) (f : Q(«$α» → ℕ → «$α»)) (a : Q(«$α»))
(b nb : Q(ℕ)) (pb : Q(IsNat «$b» «$nb»)) (sα : Q(Semiring «$α»)) (ra : Result a) :
OptionT CoreM (Result e) := do
haveI' : $e =Q $a ^ $b := ⟨⟩
haveI' : $f =Q HPow.hPow := ⟨⟩
match ra with
| .isBool .. => failure
| .isNat sα na pa =>
assumeInstancesCommute
let ⟨c, r⟩ ← evalNatPow na nb
return .isNat sα c q(isNat_pow (f := $f) (.refl $f) $pa $pb $r)
| .isNegNat rα .. =>
assumeInstancesCommute
let ⟨za, na, pa⟩ ← OptionT.mk <| pure (ra.toInt rα)
let ⟨zc, c, r⟩ ← evalIntPow za na nb
return .isInt rα c zc q(isInt_pow (f := $f) (.refl $f) $pa $pb $r)
| .isNNRat dα _qa na da pa =>
assumeInstancesCommute
let ⟨nc, r1⟩ ← evalNatPow na nb
let ⟨dc, r2⟩ ← evalNatPow da nb
let qc := mkRat nc.natLit! dc.natLit!
return .isNNRat dα qc nc dc q(isNNRat_pow (f := $f) (.refl $f) $pa $pb $r1 $r2)
| .isNegNNRat dα qa na da pa =>
assumeInstancesCommute
let ⟨zc, nc, r1⟩ ← evalIntPow qa.num q(Int.negOfNat $na) nb
let ⟨dc, r2⟩ ← evalNatPow da nb
let qc := mkRat zc dc.natLit!
return .isRat dα qc nc dc q(isRat_pow (f := $f) (.refl $f) $pa $pb $r1 $r2)
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `a ^ b`,
such that `norm_num` successfully recognises both `a` and `b`, with `b : ℕ`. -/
@[norm_num _ ^ (_ : ℕ)]
def evalPow : NormNumExt where eval {u α} e := do
let .app (.app (f : Q($α → ℕ → $α)) (a : Q($α))) (b : Q(ℕ)) ← whnfR e | failure
let ⟨nb, pb⟩ ← deriveNat b q(instAddMonoidWithOneNat)
let sα ← inferSemiring α
let ra ← derive a
guard <|← withDefault <| withNewMCtxDepth <| isDefEq f q(HPow.hPow (α := $α))
haveI' : $e =Q $a ^ $b := ⟨⟩
haveI' : $f =Q HPow.hPow := ⟨⟩
let .some r ←
liftM <| OptionT.run (evalPow.core q($e) q($f) q($a) q($b) q($nb) q($pb) q($sα) ra) | failure
return r
theorem isNat_zpow_pos {α : Type*} [DivisionSemiring α] {a : α} {b : ℤ} {nb ne : ℕ}
(pb : IsNat b nb) (pe' : IsNat (a ^ nb) ne) :
IsNat (a ^ b) ne := by
rwa [pb.out, zpow_natCast]
theorem isNat_zpow_neg {α : Type*} [DivisionSemiring α] {a : α} {b : ℤ} {nb ne : ℕ}
(pb : IsInt b (Int.negOfNat nb)) (pe' : IsNat (a ^ nb)⁻¹ ne) :
IsNat (a ^ b) ne := by
rwa [pb.out, Int.cast_negOfNat, zpow_neg, zpow_natCast]
theorem isInt_zpow_pos {α : Type*} [DivisionRing α] {a : α} {b : ℤ} {nb ne : ℕ}
(pb : IsNat b nb) (pe' : IsInt (a ^ nb) (Int.negOfNat ne)) :
IsInt (a ^ b) (Int.negOfNat ne) := by
rwa [pb.out, zpow_natCast]
theorem isInt_zpow_neg {α : Type*} [DivisionRing α] {a : α} {b : ℤ} {nb ne : ℕ}
(pb : IsInt b (Int.negOfNat nb)) (pe' : IsInt (a ^ nb)⁻¹ (Int.negOfNat ne)) :
IsInt (a ^ b) (Int.negOfNat ne) := by
rwa [pb.out, Int.cast_negOfNat, zpow_neg, zpow_natCast]
theorem isNNRat_zpow_pos {α : Type*} [DivisionSemiring α] {a : α} {b : ℤ} {nb : ℕ}
{num : ℕ} {den : ℕ}
(pb : IsNat b nb) (pe' : IsNNRat (a ^ nb) num den) :
IsNNRat (a^b) num den := by
rwa [pb.out, zpow_natCast]
theorem isNNRat_zpow_neg {α : Type*} [DivisionSemiring α] {a : α} {b : ℤ} {nb : ℕ}
{num : ℕ} {den : ℕ}
(pb : IsInt b (Int.negOfNat nb)) (pe' : IsNNRat ((a ^ nb)⁻¹) num den) :
IsNNRat (a^b) num den := by
rwa [pb.out, Int.cast_negOfNat, zpow_neg, zpow_natCast]
theorem isRat_zpow_pos {α : Type*} [DivisionRing α] {a : α} {b : ℤ} {nb : ℕ}
{num : ℤ} {den : ℕ}
(pb : IsNat b nb) (pe' : IsRat (a ^ nb) num den) :
IsRat (a ^ b) num den := by
rwa [pb.out, zpow_natCast]
theorem isRat_zpow_neg {α : Type*} [DivisionRing α] {a : α} {b : ℤ} {nb : ℕ}
{num : ℤ} {den : ℕ}
(pb : IsInt b (Int.negOfNat nb)) (pe' : IsRat ((a ^ nb)⁻¹) num den) :
IsRat (a ^ b) num den := by
rwa [pb.out, Int.cast_negOfNat, zpow_neg, zpow_natCast]
#adaptation_note /-- https://github.com/leanprover/lean4/pull/4096
the two
```
have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩
h.check
```
blocks below were not necessary: we just did it once outside the `match rb with` block.
-/
/-- The `norm_num` extension which identifies expressions of the form `a ^ b`,
such that `norm_num` successfully recognises both `a` and `b`, with `b : ℤ`. -/
@[norm_num _ ^ (_ : ℤ)]
def evalZPow : NormNumExt where eval {u α} e := do
let .app (.app (f : Q($α → ℤ → $α)) (a : Q($α))) (b : Q(ℤ)) ← whnfR e | failure
let _c ← synthInstanceQ q(DivisionSemiring $α)
let rb ← derive (α := q(ℤ)) b
match rb with
| .isBool .. | .isNNRat _ .. | .isNegNNRat _ .. => failure
| .isNat sβ nb pb =>
have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩
h.check
match ← derive q($a ^ $nb) with
| .isBool .. => failure
| .isNat sα' ne' pe' =>
assumeInstancesCommute
return .isNat sα' ne' q(isNat_zpow_pos $pb $pe')
| .isNegNat sα' ne' pe' =>
let _c ← synthInstanceQ q(DivisionRing $α)
assumeInstancesCommute
return .isNegNat sα' ne' q(isInt_zpow_pos $pb $pe')
| .isNNRat dsα' qe' nume' dene' pe' =>
assumeInstancesCommute
return .isNNRat dsα' qe' nume' dene' q(isNNRat_zpow_pos $pb $pe')
| .isNegNNRat dα' qe' nume' dene' pe' =>
assumeInstancesCommute
let proof := q(isRat_zpow_pos $pb $pe')
return .isRat dα' qe' nume' dene' proof
| .isNegNat sβ nb pb =>
have h : $e =Q (HPow.hPow (γ := $α) $a $b) := ⟨⟩
h.check
match ← derive q(($a ^ $nb)⁻¹) with
| .isBool .. => failure
| .isNat sα' ne' pe' =>
assumeInstancesCommute
return .isNat sα' ne' q(isNat_zpow_neg $pb $pe')
| .isNegNat sα' ne' pe' =>
let _c ← synthInstanceQ q(DivisionRing $α)
assumeInstancesCommute
return .isNegNat sα' ne' q(isInt_zpow_neg $pb $pe')
| .isNNRat dsα' qe' nume' dene' pe' =>
assumeInstancesCommute
return .isNNRat dsα' qe' nume' dene' q(isNNRat_zpow_neg $pb $pe')
| .isNegNNRat dα' qe' nume' dene' pe' =>
assumeInstancesCommute
return .isRat dα' qe' q(.negOfNat $nume') dene' q(isRat_zpow_neg $pb $pe')
end NormNum
end Meta
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/GCD.lean | import Mathlib.Algebra.Ring.Divisibility.Basic
import Mathlib.Data.Int.GCD
import Mathlib.Tactic.NormNum
/-! # `norm_num` extensions for GCD-adjacent functions
This module defines some `norm_num` extensions for functions such as
`Nat.gcd`, `Nat.lcm`, `Int.gcd`, and `Int.lcm`.
Note that `Nat.coprime` is reducible and defined in terms of `Nat.gcd`, so the `Nat.gcd` extension
also indirectly provides a `Nat.coprime` extension.
-/
namespace Tactic
namespace NormNum
theorem int_gcd_helper' {d : ℕ} {x y : ℤ} (a b : ℤ) (h₁ : (d : ℤ) ∣ x) (h₂ : (d : ℤ) ∣ y)
(h₃ : x * a + y * b = d) : Int.gcd x y = d := by
refine Nat.dvd_antisymm ?_ (Int.natCast_dvd_natCast.1 (Int.dvd_coe_gcd h₁ h₂))
rw [← Int.natCast_dvd_natCast, ← h₃]
apply dvd_add
· exact (Int.gcd_dvd_left ..).mul_right _
· exact (Int.gcd_dvd_right ..).mul_right _
theorem nat_gcd_helper_dvd_left (x y : ℕ) (h : y % x = 0) : Nat.gcd x y = x :=
Nat.gcd_eq_left (Nat.dvd_of_mod_eq_zero h)
theorem nat_gcd_helper_dvd_right (x y : ℕ) (h : x % y = 0) : Nat.gcd x y = y :=
Nat.gcd_eq_right (Nat.dvd_of_mod_eq_zero h)
theorem nat_gcd_helper_2 (d x y a b : ℕ) (hu : x % d = 0) (hv : y % d = 0)
(h : x * a = y * b + d) : Nat.gcd x y = d := by
rw [← Int.gcd_natCast_natCast]
apply int_gcd_helper' a (-b)
(Int.natCast_dvd_natCast.mpr (Nat.dvd_of_mod_eq_zero hu))
(Int.natCast_dvd_natCast.mpr (Nat.dvd_of_mod_eq_zero hv))
rw [mul_neg, ← sub_eq_add_neg, sub_eq_iff_eq_add']
exact mod_cast h
theorem nat_gcd_helper_1 (d x y a b : ℕ) (hu : x % d = 0) (hv : y % d = 0)
(h : y * b = x * a + d) : Nat.gcd x y = d :=
(Nat.gcd_comm _ _).trans <| nat_gcd_helper_2 _ _ _ _ _ hv hu h
theorem nat_gcd_helper_1' (x y a b : ℕ) (h : y * b = x * a + 1) :
Nat.gcd x y = 1 :=
nat_gcd_helper_1 1 _ _ _ _ (Nat.mod_one _) (Nat.mod_one _) h
theorem nat_gcd_helper_2' (x y a b : ℕ) (h : x * a = y * b + 1) :
Nat.gcd x y = 1 :=
nat_gcd_helper_2 1 _ _ _ _ (Nat.mod_one _) (Nat.mod_one _) h
theorem nat_lcm_helper (x y d m : ℕ) (hd : Nat.gcd x y = d)
(d0 : Nat.beq d 0 = false)
(dm : x * y = d * m) : Nat.lcm x y = m :=
mul_right_injective₀ (Nat.ne_of_beq_eq_false d0) <| by
dsimp only
rw [← dm, ← hd, Nat.gcd_mul_lcm]
theorem int_gcd_helper {x y : ℤ} {x' y' d : ℕ}
(hx : x.natAbs = x') (hy : y.natAbs = y') (h : Nat.gcd x' y' = d) :
Int.gcd x y = d := by subst_vars; rw [Int.gcd_def]
theorem int_lcm_helper {x y : ℤ} {x' y' d : ℕ}
(hx : x.natAbs = x') (hy : y.natAbs = y') (h : Nat.lcm x' y' = d) :
Int.lcm x y = d := by subst_vars; rw [Int.lcm_def]
open Qq Lean Elab.Tactic Mathlib.Meta.NormNum
theorem isNat_gcd : {x y nx ny z : ℕ} →
IsNat x nx → IsNat y ny → Nat.gcd nx ny = z → IsNat (Nat.gcd x y) z
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩
theorem isNat_lcm : {x y nx ny z : ℕ} →
IsNat x nx → IsNat y ny → Nat.lcm nx ny = z → IsNat (Nat.lcm x y) z
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩
theorem isInt_gcd : {x y nx ny : ℤ} → {z : ℕ} →
IsInt x nx → IsInt y ny → Int.gcd nx ny = z → IsNat (Int.gcd x y) z
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩
theorem isInt_lcm : {x y nx ny : ℤ} → {z : ℕ} →
IsInt x nx → IsInt y ny → Int.lcm nx ny = z → IsNat (Int.lcm x y) z
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩
/-- Given natural number literals `ex` and `ey`, return their GCD as a natural number literal
and an equality proof. Panics if `ex` or `ey` aren't natural number literals. -/
def proveNatGCD (ex ey : Q(ℕ)) : (ed : Q(ℕ)) × Q(Nat.gcd $ex $ey = $ed) :=
match ex.natLit!, ey.natLit! with
| 0, _ => have : $ex =Q nat_lit 0 := ⟨⟩; ⟨ey, q(Nat.gcd_zero_left $ey)⟩
| _, 0 => have : $ey =Q nat_lit 0 := ⟨⟩; ⟨ex, q(Nat.gcd_zero_right $ex)⟩
| 1, _ => have : $ex =Q nat_lit 1 := ⟨⟩; ⟨q(nat_lit 1), q(Nat.gcd_one_left $ey)⟩
| _, 1 => have : $ey =Q nat_lit 1 := ⟨⟩; ⟨q(nat_lit 1), q(Nat.gcd_one_right $ex)⟩
| x, y =>
let (d, a, b) := Nat.xgcdAux x 1 0 y 0 1
if d = x then
have pq : Q(Nat.mod $ey $ex = 0) := (q(Eq.refl (nat_lit 0)) : Expr)
⟨ex, q(nat_gcd_helper_dvd_left $ex $ey $pq)⟩
else if d = y then
have pq : Q(Nat.mod $ex $ey = 0) := (q(Eq.refl (nat_lit 0)) : Expr)
⟨ey, q(nat_gcd_helper_dvd_right $ex $ey $pq)⟩
else
have ea' : Q(ℕ) := mkRawNatLit a.natAbs
have eb' : Q(ℕ) := mkRawNatLit b.natAbs
if d = 1 then
if a ≥ 0 then
have pt : Q($ex * $ea' = $ey * $eb' + 1) := (q(Eq.refl ($ex * $ea')) : Expr)
⟨q(nat_lit 1), q(nat_gcd_helper_2' $ex $ey $ea' $eb' $pt)⟩
else
have pt : Q($ey * $eb' = $ex * $ea' + 1) := (q(Eq.refl ($ey * $eb')) : Expr)
⟨q(nat_lit 1), q(nat_gcd_helper_1' $ex $ey $ea' $eb' $pt)⟩
else
have ed : Q(ℕ) := mkRawNatLit d
have pu : Q(Nat.mod $ex $ed = 0) := (q(Eq.refl (nat_lit 0)) : Expr)
have pv : Q(Nat.mod $ey $ed = 0) := (q(Eq.refl (nat_lit 0)) : Expr)
if a ≥ 0 then
have pt : Q($ex * $ea' = $ey * $eb' + $ed) := (q(Eq.refl ($ex * $ea')) : Expr)
⟨ed, q(nat_gcd_helper_2 $ed $ex $ey $ea' $eb' $pu $pv $pt)⟩
else
have pt : Q($ey * $eb' = $ex * $ea' + $ed) := (q(Eq.refl ($ey * $eb')) : Expr)
⟨ed, q(nat_gcd_helper_1 $ed $ex $ey $ea' $eb' $pu $pv $pt)⟩
/-- Evaluate the `Nat.gcd` function. -/
@[norm_num Nat.gcd _ _]
def evalNatGCD : NormNumExt where eval {u α} e := do
let .app (.app _ (x : Q(ℕ))) (y : Q(ℕ)) ← Meta.whnfR e | failure
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q Nat.gcd $x $y := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨ex, p⟩ ← deriveNat x sℕ
let ⟨ey, q⟩ ← deriveNat y sℕ
let ⟨ed, pf⟩ := proveNatGCD ex ey
return .isNat sℕ ed q(isNat_gcd $p $q $pf)
/-- Given natural number literals `ex` and `ey`, return their LCM as a natural number literal
and an equality proof. Panics if `ex` or `ey` aren't natural number literals. -/
def proveNatLCM (ex ey : Q(ℕ)) : (ed : Q(ℕ)) × Q(Nat.lcm $ex $ey = $ed) :=
match ex.natLit!, ey.natLit! with
| 0, _ =>
show (ed : Q(ℕ)) × Q(Nat.lcm 0 $ey = $ed) from ⟨q(nat_lit 0), q(Nat.lcm_zero_left $ey)⟩
| _, 0 =>
show (ed : Q(ℕ)) × Q(Nat.lcm $ex 0 = $ed) from ⟨q(nat_lit 0), q(Nat.lcm_zero_right $ex)⟩
| 1, _ => show (ed : Q(ℕ)) × Q(Nat.lcm 1 $ey = $ed) from ⟨ey, q(Nat.lcm_one_left $ey)⟩
| _, 1 => show (ed : Q(ℕ)) × Q(Nat.lcm $ex 1 = $ed) from ⟨ex, q(Nat.lcm_one_right $ex)⟩
| x, y =>
let ⟨ed, pd⟩ := proveNatGCD ex ey
have p0 : Q(Nat.beq $ed 0 = false) := (q(Eq.refl false) : Expr)
have em : Q(ℕ) := mkRawNatLit (x * y / ed.natLit!)
have pm : Q($ex * $ey = $ed * $em) := (q(Eq.refl ($ex * $ey)) : Expr)
⟨em, q(nat_lcm_helper $ex $ey $ed $em $pd $p0 $pm)⟩
/-- Evaluates the `Nat.lcm` function. -/
@[norm_num Nat.lcm _ _]
def evalNatLCM : NormNumExt where eval {u α} e := do
let .app (.app _ (x : Q(ℕ))) (y : Q(ℕ)) ← Meta.whnfR e | failure
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q Nat.lcm $x $y := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨ex, p⟩ ← deriveNat x sℕ
let ⟨ey, q⟩ ← deriveNat y sℕ
let ⟨ed, pf⟩ := proveNatLCM ex ey
return .isNat sℕ ed q(isNat_lcm $p $q $pf)
/-- Given two integers, return their GCD and an equality proof.
Panics if `ex` or `ey` aren't integer literals. -/
def proveIntGCD (ex ey : Q(ℤ)) : (ed : Q(ℕ)) × Q(Int.gcd $ex $ey = $ed) :=
let ⟨ex', hx⟩ := rawIntLitNatAbs ex
let ⟨ey', hy⟩ := rawIntLitNatAbs ey
let ⟨ed, pf⟩ := proveNatGCD ex' ey'
⟨ed, q(int_gcd_helper $hx $hy $pf)⟩
/-- Evaluates the `Int.gcd` function. -/
@[norm_num Int.gcd _ _]
def evalIntGCD : NormNumExt where eval {u α} e := do
let .app (.app _ (x : Q(ℤ))) (y : Q(ℤ)) ← Meta.whnfR e | failure
let ⟨ex, p⟩ ← deriveInt x _
let ⟨ey, q⟩ ← deriveInt y _
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q Int.gcd $x $y := ⟨⟩
let ⟨ed, pf⟩ := proveIntGCD ex ey
return .isNat _ ed q(isInt_gcd $p $q $pf)
/-- Given two integers, return their LCM and an equality proof.
Panics if `ex` or `ey` aren't integer literals. -/
def proveIntLCM (ex ey : Q(ℤ)) : (ed : Q(ℕ)) × Q(Int.lcm $ex $ey = $ed) :=
let ⟨ex', hx⟩ := rawIntLitNatAbs ex
let ⟨ey', hy⟩ := rawIntLitNatAbs ey
let ⟨ed, pf⟩ := proveNatLCM ex' ey'
⟨ed, q(int_lcm_helper $hx $hy $pf)⟩
/-- Evaluates the `Int.lcm` function. -/
@[norm_num Int.lcm _ _]
def evalIntLCM : NormNumExt where eval {u α} e := do
let .app (.app _ (x : Q(ℤ))) (y : Q(ℤ)) ← Meta.whnfR e | failure
let ⟨ex, p⟩ ← deriveInt x _
let ⟨ey, q⟩ ← deriveInt y _
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q Int.lcm $x $y := ⟨⟩
let ⟨ed, pf⟩ := proveIntLCM ex ey
return .isNat _ ed q(isInt_lcm $p $q $pf)
theorem isInt_ratNum : ∀ {q : ℚ} {n : ℤ} {n' : ℕ} {d : ℕ},
IsRat q n d → n.natAbs = n' → n'.gcd d = 1 → IsInt q.num n
| _, n, _, d, ⟨hi, rfl⟩, rfl, h => by
constructor
have : 0 < d := Nat.pos_iff_ne_zero.mpr <| by simpa using hi.ne_zero
simp_rw [Rat.mul_num, Rat.den_intCast, invOf_eq_inv,
Rat.inv_natCast_den_of_pos this, Rat.inv_natCast_num_of_pos this,
Rat.num_intCast, one_mul, mul_one, h, Nat.cast_one, Int.ediv_one, Int.cast_id]
theorem isNat_ratDen : ∀ {q : ℚ} {n : ℤ} {n' : ℕ} {d : ℕ},
IsRat q n d → n.natAbs = n' → n'.gcd d = 1 → IsNat q.den d
| _, n, _, d, ⟨hi, rfl⟩, rfl, h => by
constructor
have : 0 < d := Nat.pos_iff_ne_zero.mpr <| by simpa using hi.ne_zero
simp_rw [Rat.mul_den, Rat.den_intCast, invOf_eq_inv,
Rat.inv_natCast_den_of_pos this, Rat.inv_natCast_num_of_pos this,
Rat.num_intCast, one_mul, mul_one, Nat.cast_id, h, Nat.div_one]
/-- Evaluates the `Rat.num` function. -/
@[nolint unusedHavesSuffices, norm_num Rat.num _]
def evalRatNum : NormNumExt where eval {u α} e := do
let .proj _ _ (q : Q(ℚ)) ← Meta.whnfR e | failure
have : u =QL 0 := ⟨⟩; have : $α =Q ℤ := ⟨⟩; have : $e =Q Rat.num $q := ⟨⟩
let ⟨q', n, d, eq⟩ ← deriveRat q (_inst := q(inferInstance))
let ⟨n', hn⟩ := rawIntLitNatAbs n
-- deriveRat ensures these are coprime, so the gcd will be 1
let ⟨gcd, pf⟩ := proveNatGCD q($n') q($d)
have : $gcd =Q nat_lit 1 := ⟨⟩
return .isInt _ n q'.num q(isInt_ratNum $eq $hn $pf)
/-- Evaluates the `Rat.den` function. -/
@[nolint unusedHavesSuffices, norm_num Rat.den _]
def evalRatDen : NormNumExt where eval {u α} e := do
let .proj _ _ (q : Q(ℚ)) ← Meta.whnfR e | failure
have : u =QL 0 := ⟨⟩; have : $α =Q ℕ := ⟨⟩; have : $e =Q Rat.den $q := ⟨⟩
let ⟨q', n, d, eq⟩ ← deriveRat q (_inst := q(inferInstance))
let ⟨n', hn⟩ := rawIntLitNatAbs n
-- deriveRat ensures these are coprime, so the gcd will be 1
let ⟨gcd, pf⟩ := proveNatGCD q($n') q($d)
have : $gcd =Q nat_lit 1 := ⟨⟩
return .isNat _ d q(isNat_ratDen $eq $hn $pf)
end NormNum
end Tactic |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Core.lean | import Mathlib.Lean.Expr.Rat
import Mathlib.Tactic.Hint
import Mathlib.Tactic.NormNum.Result
import Mathlib.Util.AtLocation
import Mathlib.Util.Qq
import Lean.Elab.Tactic.Location
/-!
## `norm_num` core functionality
This file sets up the `norm_num` tactic and the `@[norm_num]` attribute,
which allow for plugging in new normalization functionality around a simp-based driver.
The actual behavior is in `@[norm_num]`-tagged definitions in `Tactic.NormNum.Basic`
and elsewhere.
-/
open Lean
open Lean.Meta Qq Lean.Elab Term
/-- Attribute for identifying `norm_num` extensions. -/
syntax (name := norm_num) "norm_num " term,+ : attr
namespace Mathlib
namespace Meta.NormNum
initialize registerTraceClass `Tactic.norm_num
/--
An extension for `norm_num`.
-/
structure NormNumExt where
/-- The extension should be run in the `pre` phase when used as simp plugin. -/
pre := true
/-- The extension should be run in the `post` phase when used as simp plugin. -/
post := true
/-- Attempts to prove an expression is equal to some explicit number of the relevant type. -/
eval {u : Level} {α : Q(Type u)} (e : Q($α)) : MetaM (Result e)
/-- The name of the `norm_num` extension. -/
name : Name := by exact decl_name%
variable {u : Level}
/-- Read a `norm_num` extension from a declaration of the right type. -/
def mkNormNumExt (n : Name) : ImportM NormNumExt := do
let { env, opts, .. } ← read
IO.ofExcept <| unsafe env.evalConstCheck NormNumExt opts ``NormNumExt n
/-- Each `norm_num` extension is labelled with a collection of patterns
which determine the expressions to which it should be applied. -/
abbrev Entry := Array (Array DiscrTree.Key) × Name
/-- The state of the `norm_num` extension environment -/
structure NormNums where
/-- The tree of `norm_num` extensions. -/
tree : DiscrTree NormNumExt := {}
/-- Erased `norm_num`s. -/
erased : PHashSet Name := {}
deriving Inhabited
/-- Environment extensions for `norm_num` declarations -/
initialize normNumExt : ScopedEnvExtension Entry (Entry × NormNumExt) NormNums ←
-- we only need this to deduplicate entries in the DiscrTree
have : BEq NormNumExt := ⟨fun _ _ ↦ false⟩
/- Insert `v : NormNumExt` into the tree `dt` on all key sequences given in `kss`. -/
let insert kss v dt := kss.foldl (fun dt ks ↦ dt.insertCore ks v) dt
registerScopedEnvExtension {
mkInitial := pure {}
ofOLeanEntry := fun _ e@(_, n) ↦ return (e, ← mkNormNumExt n)
toOLeanEntry := (·.1)
addEntry := fun { tree, erased } ((kss, n), ext) ↦
{ tree := insert kss ext tree, erased := erased.erase n }
}
/-- Run each registered `norm_num` extension on an expression, returning a `NormNum.Result`. -/
def derive {α : Q(Type u)} (e : Q($α)) (post := false) : MetaM (Result e) := do
if e.isRawNatLit then
let lit : Q(ℕ) := e
return .isNat (q(instAddMonoidWithOneNat) : Q(AddMonoidWithOne ℕ))
lit (q(IsNat.raw_refl $lit) : Expr)
profileitM Exception "norm_num" (← getOptions) do
let s ← saveState
let normNums := normNumExt.getState (← getEnv)
let arr ← normNums.tree.getMatch e
for ext in arr do
if (bif post then ext.post else ext.pre) && ! normNums.erased.contains ext.name then
try
let new ← withReducibleAndInstances <| ext.eval e
trace[Tactic.norm_num] "{ext.name}:\n{e} ==> {new}"
return new
catch err =>
trace[Tactic.norm_num] "{ext.name} failed {e}: {err.toMessageData}"
s.restore
throwError "{e}: no norm_nums apply"
/-- Run each registered `norm_num` extension on a typed expression `e : α`,
returning a typed expression `lit : ℕ`, and a proof of `isNat e lit`. -/
def deriveNat {α : Q(Type u)} (e : Q($α))
(_inst : Q(AddMonoidWithOne $α) := by with_reducible assumption) :
MetaM ((lit : Q(ℕ)) × Q(IsNat $e $lit)) := do
let .isNat _ lit proof ← derive e | failure
pure ⟨lit, proof⟩
/-- Run each registered `norm_num` extension on a typed expression `e : α`,
returning a typed expression `lit : ℤ`, and a proof of `IsInt e lit` in expression form. -/
def deriveInt {α : Q(Type u)} (e : Q($α))
(_inst : Q(Ring $α) := by with_reducible assumption) :
MetaM ((lit : Q(ℤ)) × Q(IsInt $e $lit)) := do
let some ⟨_, lit, proof⟩ := (← derive e).toInt | failure
pure ⟨lit, proof⟩
/-- Run each registered `norm_num` extension on a typed expression `e : α`,
returning a rational number, typed expressions `n : ℤ` and `d : ℕ` for the numerator and
denominator, and a proof of `IsRat e n d` in expression form. -/
def deriveRat {α : Q(Type u)} (e : Q($α))
(_inst : Q(DivisionRing $α) := by with_reducible assumption) :
MetaM (ℚ × (n : Q(ℤ)) × (d : Q(ℕ)) × Q(IsRat $e $n $d)) := do
let some res := (← derive e).toRat' | failure
pure res
/-- Run each registered `norm_num` extension on a typed expression `p : Prop`,
and returning the truth or falsity of `p' : Prop` from an equivalence `p ↔ p'`. -/
def deriveBool (p : Q(Prop)) : MetaM ((b : Bool) × BoolResult p b) := do
let .isBool b prf ← derive q($p) | failure
pure ⟨b, prf⟩
/-- Run each registered `norm_num` extension on a typed expression `p : Prop`,
and returning the truth or falsity of `p' : Prop` from an equivalence `p ↔ p'`. -/
def deriveBoolOfIff (p p' : Q(Prop)) (hp : Q($p ↔ $p')) :
MetaM ((b : Bool) × BoolResult p' b) := do
let ⟨b, pb⟩ ← deriveBool p
match b with
| true => return ⟨true, q(Iff.mp $hp $pb)⟩
| false => return ⟨false, q((Iff.not $hp).mp $pb)⟩
/-- Run each registered `norm_num` extension on an expression,
returning a `Simp.Result`. -/
def eval (e : Expr) (post := false) : MetaM Simp.Result := do
if e.isExplicitNumber then return { expr := e }
let ⟨_, _, e⟩ ← inferTypeQ' e
(← derive e post).toSimpResult
/-- Erases a name marked `norm_num` by adding it to the state's `erased` field and
removing it from the state's list of `Entry`s. -/
def NormNums.eraseCore (d : NormNums) (declName : Name) : NormNums :=
{ d with erased := d.erased.insert declName }
/--
Erase a name marked as a `norm_num` attribute.
Check that it does in fact have the `norm_num` attribute by making sure it names a `NormNumExt`
found somewhere in the state's tree, and is not erased.
-/
def NormNums.erase {m : Type → Type} [Monad m] [MonadError m] (d : NormNums) (declName : Name) :
m NormNums := do
unless d.tree.values.any (·.name == declName) && ! d.erased.contains declName
do
throwError "'{declName}' does not have [norm_num] attribute"
return d.eraseCore declName
initialize registerBuiltinAttribute {
name := `norm_num
descr := "adds a norm_num extension"
applicationTime := .afterCompilation
add := fun declName stx kind ↦ match stx with
| `(attr| norm_num $es,*) => do
let env ← getEnv
unless (env.getModuleIdxFor? declName).isNone do
throwError "invalid attribute 'norm_num', declaration is in an imported module"
if (IR.getSorryDep env declName).isSome then return -- ignore in progress definitions
let ext ← mkNormNumExt declName
let keys ← MetaM.run' <| es.getElems.mapM fun stx ↦ do
let e ← TermElabM.run' <| withSaveInfoContext <| withAutoBoundImplicit <|
withReader ({ · with ignoreTCFailures := true }) do
let e ← elabTerm stx none
let (_, _, e) ← lambdaMetaTelescope (← mkLambdaFVars (← getLCtx).getFVars e)
return e
DiscrTree.mkPath e
normNumExt.add ((keys, declName), ext) kind
| _ => throwUnsupportedSyntax
erase := fun declName => do
let s := normNumExt.getState (← getEnv)
let s ← s.erase declName
modifyEnv fun env => normNumExt.modifyState env fun _ => s
}
/-- A simp plugin which calls `NormNum.eval`. -/
def tryNormNum (post := false) (e : Expr) : SimpM Simp.Step := do
try
return .done (← eval e post)
catch _ =>
return .continue
variable (ctx : Simp.Context) (useSimp := true) in
mutual
/-- A discharger which calls `norm_num`. -/
partial def discharge (e : Expr) : SimpM (Option Expr) := do (← deriveSimp e).ofTrue
/-- A `Methods` implementation which calls `norm_num`. -/
partial def methods : Simp.Methods :=
if useSimp then {
pre := Simp.preDefault #[] >> tryNormNum
post := Simp.postDefault #[] >> tryNormNum (post := true)
discharge? := discharge
} else {
pre := tryNormNum
post := tryNormNum (post := true)
discharge? := discharge
}
/-- Traverses the given expression using simp and normalises any numbers it finds. -/
partial def deriveSimp (e : Expr) : MetaM Simp.Result :=
(·.1) <$> Simp.main e ctx (methods := methods)
end
open Tactic in
/-- Constructs a simp context from the simp argument syntax. -/
def getSimpContext (cfg args : Syntax) (simpOnly := false) : TacticM Simp.Context := do
let config ← elabSimpConfigCore cfg
let simpTheorems ←
if simpOnly then simpOnlyBuiltins.foldlM (·.addConst ·) {} else getSimpTheorems
let { ctx, .. } ←
elabSimpArgs args[0] (eraseLocal := false) (kind := .simp) (simprocs := {})
(← Simp.mkContext config (simpTheorems := #[simpTheorems])
(congrTheorems := ← getSimpCongrTheorems))
return ctx
open Elab Tactic in
/--
Elaborates a call to `norm_num only? [args]` or `norm_num1`.
* `args`: the `(simpArgs)?` syntax for simp arguments
* `loc`: the `(location)?` syntax for the optional location argument
* `simpOnly`: true if `only` was used in `norm_num`
* `useSimp`: false if `norm_num1` was used, in which case only the structural parts
of `simp` will be used, not any of the post-processing that `simp only` does without lemmas
-/
def elabNormNum (cfg args loc : Syntax) (simpOnly := false) (useSimp := true) :
TacticM Unit := withMainContext do
let ctx ← getSimpContext cfg args (!useSimp || simpOnly)
let loc := expandOptLocation loc
transformAtNondepPropLocation (fun e ctx ↦ deriveSimp ctx useSimp e) "norm_num" loc
(failIfUnchanged := false) (mayCloseGoalFromHyp := true) ctx
end Meta.NormNum
namespace Tactic
open Lean.Parser.Tactic Meta.NormNum
/--
Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `⁻¹` `^` and `%`
over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types,
and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are
numerical expressions. It also has a relatively simple primality prover.
-/
elab (name := normNum)
"norm_num" cfg:optConfig only:&" only"? args:(simpArgs ?) loc:(location ?) : tactic =>
elabNormNum cfg args loc (simpOnly := only.isSome) (useSimp := true)
/-- Basic version of `norm_num` that does not call `simp`. -/
elab (name := normNum1) "norm_num1" loc:(location ?) : tactic =>
elabNormNum mkNullNode mkNullNode loc (simpOnly := true) (useSimp := false)
open Lean Elab Tactic
@[inherit_doc normNum1] syntax (name := normNum1Conv) "norm_num1" : conv
/-- Elaborator for `norm_num1` conv tactic. -/
@[tactic normNum1Conv] def elabNormNum1Conv : Tactic := fun _ ↦ withMainContext do
let ctx ← getSimpContext mkNullNode mkNullNode true
Conv.applySimpResult (← deriveSimp ctx (← instantiateMVars (← Conv.getLhs)) (useSimp := false))
@[inherit_doc normNum] syntax (name := normNumConv)
"norm_num" optConfig &" only"? (simpArgs)? : conv
/-- Elaborator for `norm_num` conv tactic. -/
@[tactic normNumConv] def elabNormNumConv : Tactic := fun stx ↦ withMainContext do
let ctx ← getSimpContext stx[1] stx[3] !stx[2].isNone
Conv.applySimpResult (← deriveSimp ctx (← instantiateMVars (← Conv.getLhs)) (useSimp := true))
/--
The basic usage is `#norm_num e`, where `e` is an expression,
which will print the `norm_num` form of `e`.
Syntax: `#norm_num` (`only`)? (`[` simp lemma list `]`)? `:`? expression
This accepts the same options as the `#simp` command.
You can specify additional simp lemmas as usual, for example using `#norm_num [f, g] : e`.
(The colon is optional but helpful for the parser.)
The `only` restricts `norm_num` to using only the provided lemmas, and so
`#norm_num only : e` behaves similarly to `norm_num1`.
Unlike `norm_num`, this command does not fail when no simplifications are made.
`#norm_num` understands local variables, so you can use them to introduce parameters.
-/
macro (name := normNumCmd) "#norm_num" cfg:optConfig o:(&" only")?
args:(Parser.Tactic.simpArgs)? " :"? ppSpace e:term : command =>
`(command| #conv norm_num $cfg:optConfig $[only%$o]? $(args)? => $e)
end Mathlib.Tactic
/-!
We register `norm_num` with the `hint` tactic.
-/
register_hint 1000 norm_num |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/PowMod.lean | import Mathlib.Tactic.NormNum.Pow
/-!
# `norm_num` handling for expressions of the form `a ^ b % m`.
These expressions can often be evaluated efficiently in cases where first evaluating `a ^ b` and
then reducing mod `m` is not feasible. We provide a function `evalNatPowMod` which is used by the
`reduce_mod_char` tactic to efficiently evaluate powers in rings with positive characteristic.
The approach taken here is identical to (and copied from) the development in `NormNum/Pow.lean`.
## TODO
* Adapt the `norm_num` extensions for `Nat.mod` and `Int.emod` to efficiently evaluate expressions
of the form `a ^ b % m` using `evalNatPowMod`.
-/
assert_not_exists RelIso
set_option autoImplicit true
namespace Mathlib
open Lean
open Meta
namespace Meta.NormNum
open Qq
/-- Represents and proves equalities of the form `a^b % m = c` for natural numbers. -/
structure IsNatPowModT (p : Prop) (a b m c : Nat) : Prop where
run' : p → Nat.mod (Nat.pow a b) m = c
theorem IsNatPowModT.run
(p : IsNatPowModT (Nat.mod (Nat.pow a (nat_lit 1)) m = Nat.mod a m) a b m c) :
Nat.mod (Nat.pow a b) m = c := p.run' (congr_arg (fun x => x % m) (Nat.pow_one a))
theorem IsNatPowModT.trans (h1 : IsNatPowModT p a b m c)
(h2 : IsNatPowModT (Nat.mod (Nat.pow a b) m = c) a b' m c') : IsNatPowModT p a b' m c' :=
⟨h2.run' ∘ h1.run'⟩
theorem IsNatPowModT.bit0 :
IsNatPowModT (Nat.mod (Nat.pow a b) m = c) a (nat_lit 2 * b) m (Nat.mod (Nat.mul c c) m) :=
⟨fun h1 => by simp only [two_mul, Nat.pow_eq, pow_add, ← h1, Nat.mul_eq]; exact Nat.mul_mod ..⟩
theorem natPow_zero_natMod_zero : Nat.mod (Nat.pow a (nat_lit 0)) (nat_lit 0) = nat_lit 1 := by
simp [Nat.mod, Nat.modCore]
theorem natPow_zero_natMod_one : Nat.mod (Nat.pow a (nat_lit 0)) (nat_lit 1) = nat_lit 0 := by
simp [Nat.mod, Nat.modCore_eq]
theorem natPow_zero_natMod_succ_succ :
Nat.mod (Nat.pow a (nat_lit 0)) (Nat.succ (Nat.succ m)) = nat_lit 1 := by
rfl
theorem natPow_one_natMod : Nat.mod (Nat.pow a (nat_lit 1)) m = Nat.mod a m := by rw [natPow_one]
theorem IsNatPowModT.bit1 :
IsNatPowModT (Nat.mod (Nat.pow a b) m = c) a (nat_lit 2 * b + 1) m
(Nat.mod (Nat.mul c (Nat.mod (Nat.mul c a) m)) m) :=
⟨by
rintro rfl
change a ^ (2 * b + 1) % m = (a ^ b % m) * ((a ^ b % m * a) % m) % m
rw [pow_add, two_mul, pow_add, pow_one, Nat.mul_mod (a ^ b % m) a, Nat.mod_mod,
← Nat.mul_mod (a ^ b) a, ← Nat.mul_mod, mul_assoc]⟩
/-- Evaluates and proves `a^b % m` for natural numbers using fast modular exponentiation. -/
partial def evalNatPowMod (a b m : Q(ℕ)) : (c : Q(ℕ)) × Q(Nat.mod (Nat.pow $a $b) $m = $c) :=
if b.natLit! = 0 then
haveI : $b =Q 0 := ⟨⟩
if m.natLit! = 0 then -- a ^ 0 % 0 = 1
haveI : $m =Q 0 := ⟨⟩
⟨q(nat_lit 1), q(natPow_zero_natMod_zero)⟩
else
have m' : Q(ℕ) := mkRawNatLit (m.natLit! - 1)
if m'.natLit! = 0 then -- a ^ 0 % 1 = 0
haveI : $m =Q 1 := ⟨⟩
⟨q(nat_lit 0), q(natPow_zero_natMod_one)⟩
else -- a ^ 0 % m = 1
have m'' : Q(ℕ) := mkRawNatLit (m'.natLit! - 1)
haveI : $m =Q Nat.succ (Nat.succ $m'') := ⟨⟩
⟨q(nat_lit 1), q(natPow_zero_natMod_succ_succ)⟩
else if b.natLit! = 1 then -- a ^ 1 % m = a % m
have c : Q(ℕ) := mkRawNatLit (a.natLit! % m.natLit!)
haveI : $b =Q 1 := ⟨⟩
haveI : $c =Q Nat.mod $a $m := ⟨⟩
⟨c, q(natPow_one_natMod)⟩
else
have c₀ : Q(ℕ) := mkRawNatLit (a.natLit! % m.natLit!)
haveI : $c₀ =Q Nat.mod $a $m := ⟨⟩
let ⟨c, p⟩ := go b.natLit!.log2 a m q(nat_lit 1) c₀ b _ .rfl
⟨c, q(($p).run)⟩
where
/-- Invariants: `a ^ b₀ % m = c₀`, `depth > 0`, `b >>> depth = b₀` -/
go (depth : Nat) (a m b₀ c₀ b : Q(ℕ))
(p : Q(Prop)) (hp : $p =Q (Nat.mod (Nat.pow $a $b₀) $m = $c₀)) :
(c : Q(ℕ)) × Q(IsNatPowModT $p $a $b $m $c) :=
let b' := b.natLit!
let m' := m.natLit!
if depth ≤ 1 then
let a' := a.natLit!
let c₀' := c₀.natLit!
if b' &&& 1 == 0 then
have c : Q(ℕ) := mkRawNatLit ((c₀' * c₀') % m')
haveI : $c =Q Nat.mod (Nat.mul $c₀ $c₀) $m := ⟨⟩
haveI : $b =Q 2 * $b₀ := ⟨⟩
⟨c, q(IsNatPowModT.bit0)⟩
else
have c : Q(ℕ) := mkRawNatLit ((c₀' * ((c₀' * a') % m')) % m')
haveI : $c =Q Nat.mod (Nat.mul $c₀ (Nat.mod (Nat.mul $c₀ $a) $m)) $m := ⟨⟩
haveI : $b =Q 2 * $b₀ + 1 := ⟨⟩
⟨c, q(IsNatPowModT.bit1)⟩
else
let d := depth >>> 1
have hi : Q(ℕ) := mkRawNatLit (b' >>> d)
let ⟨c1, p1⟩ := go (depth - d) a m b₀ c₀ hi p (by exact hp)
let ⟨c2, p2⟩ := go d a m hi c1 b q(Nat.mod (Nat.pow $a $hi) $m = $c1) ⟨⟩
⟨c2, q(($p1).trans $p2)⟩
end NormNum
end Meta
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/NatSqrt.lean | import Mathlib.Tactic.NormNum
/-! # `norm_num` extension for `Nat.sqrt`
This module defines a `norm_num` extension for `Nat.sqrt`.
-/
namespace Tactic
namespace NormNum
open Qq Lean Elab.Tactic Mathlib.Meta.NormNum
lemma nat_sqrt_helper {x y r : ℕ} (hr : y * y + r = x) (hle : Nat.ble r (2 * y)) :
Nat.sqrt x = y := by
rw [← hr, ← pow_two]
rw [two_mul] at hle
exact Nat.sqrt_add_eq' _ (Nat.le_of_ble_eq_true hle)
theorem isNat_sqrt : {x nx z : ℕ} → IsNat x nx → Nat.sqrt nx = z → IsNat (Nat.sqrt x) z
| _, _, _, ⟨rfl⟩, rfl => ⟨rfl⟩
/-- Given the natural number literal `ex`, returns its square root as a natural number literal
and an equality proof. Panics if `ex` isn't a natural number literal. -/
def proveNatSqrt (ex : Q(ℕ)) : (ey : Q(ℕ)) × Q(Nat.sqrt $ex = $ey) :=
match ex.natLit! with
| 0 => have : $ex =Q nat_lit 0 := ⟨⟩; ⟨q(nat_lit 0), q(Nat.sqrt_zero)⟩
| 1 => have : $ex =Q nat_lit 1 := ⟨⟩; ⟨q(nat_lit 1), q(Nat.sqrt_one)⟩
| x =>
let y := Nat.sqrt x
have ey : Q(ℕ) := mkRawNatLit y
have er : Q(ℕ) := mkRawNatLit (x - y * y)
have hr : Q($ey * $ey + $er = $ex) := (q(Eq.refl $ex) : Expr)
have hle : Q(Nat.ble $er (2 * $ey)) := (q(Eq.refl true) : Expr)
⟨ey, q(nat_sqrt_helper $hr $hle)⟩
/-- Evaluates the `Nat.sqrt` function. -/
@[norm_num Nat.sqrt _]
def evalNatSqrt : NormNumExt where eval {_ _} e := do
let .app _ (x : Q(ℕ)) ← Meta.whnfR e | failure
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨ex, p⟩ ← deriveNat x sℕ
let ⟨ey, pf⟩ := proveNatSqrt ex
let pf' : Q(IsNat (Nat.sqrt $x) $ey) := q(isNat_sqrt $p $pf)
return .isNat sℕ ey pf'
end NormNum
end Tactic |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/LegendreSymbol.lean | import Mathlib.NumberTheory.LegendreSymbol.JacobiSymbol
/-!
# A `norm_num` extension for Jacobi and Legendre symbols
We extend the `norm_num` tactic so that it can be used to provably compute
the value of the Jacobi symbol `J(a | b)` or the Legendre symbol `legendreSym p a` when
the arguments are numerals.
## Implementation notes
We use the Law of Quadratic Reciprocity for the Jacobi symbol to compute the value of `J(a | b)`
efficiently, roughly comparable in effort with the Euclidean algorithm for the computation
of the gcd of `a` and `b`. More precisely, the computation is done in the following steps.
* Use `J(a | 0) = 1` (an artifact of the definition) and `J(a | 1) = 1` to deal
with corner cases.
* Use `J(a | b) = J(a % b | b)` to reduce to the case that `a` is a natural number.
We define a version of the Jacobi symbol restricted to natural numbers for use in
the following steps; see `NormNum.jacobiSymNat`. (But we'll continue to write `J(a | b)`
in this description.)
* Remove powers of two from `b`. This is done via `J(2a | 2b) = 0` and
`J(2a+1 | 2b) = J(2a+1 | b)` (another artifact of the definition).
* Now `0 ≤ a < b` and `b` is odd. If `b = 1`, then the value is `1`.
If `a = 0` (and `b > 1`), then the value is `0`. Otherwise, we remove powers of two from `a`
via `J(4a | b) = J(a | b)` and `J(2a | b) = ±J(a | b)`, where the sign is determined
by the residue class of `b` mod 8, to reduce to `a` odd.
* Once `a` is odd, we use Quadratic Reciprocity (QR) in the form
`J(a | b) = ±J(b % a | a)`, where the sign is determined by the residue classes
of `a` and `b` mod 4. We are then back in the previous case.
We provide customized versions of these results for the various reduction steps,
where we encode the residue classes mod 2, mod 4, or mod 8 by using hypotheses like
`a % n = b`. In this way, the only divisions we have to compute and prove
are the ones occurring in the use of QR above.
-/
section Lemmas
namespace Mathlib.Meta.NormNum
/-- The Jacobi symbol restricted to natural numbers in both arguments. -/
def jacobiSymNat (a b : ℕ) : ℤ :=
jacobiSym a b
/-!
### API Lemmas
We repeat part of the API for `jacobiSym` with `NormNum.jacobiSymNat` and without implicit
arguments, in a form that is suitable for constructing proofs in `norm_num`.
-/
/-- Base cases: `b = 0`, `b = 1`, `a = 0`, `a = 1`. -/
theorem jacobiSymNat.zero_right (a : ℕ) : jacobiSymNat a 0 = 1 := by
rw [jacobiSymNat, jacobiSym.zero_right]
theorem jacobiSymNat.one_right (a : ℕ) : jacobiSymNat a 1 = 1 := by
rw [jacobiSymNat, jacobiSym.one_right]
theorem jacobiSymNat.zero_left (b : ℕ) (hb : Nat.beq (b / 2) 0 = false) : jacobiSymNat 0 b = 0 := by
rw [jacobiSymNat, Nat.cast_zero, jacobiSym.zero_left ?_]
calc
1 < 2 * 1 := by decide
_ ≤ 2 * (b / 2) :=
Nat.mul_le_mul_left _ (Nat.succ_le.mpr (Nat.pos_of_ne_zero (Nat.ne_of_beq_eq_false hb)))
_ ≤ b := Nat.mul_div_le b 2
theorem jacobiSymNat.one_left (b : ℕ) : jacobiSymNat 1 b = 1 := by
rw [jacobiSymNat, Nat.cast_one, jacobiSym.one_left]
/-- Turn a Legendre symbol into a Jacobi symbol. -/
theorem LegendreSym.to_jacobiSym (p : ℕ) (pp : Fact p.Prime) (a r : ℤ)
(hr : IsInt (jacobiSym a p) r) : IsInt (legendreSym p a) r := by
rwa [@jacobiSym.legendreSym.to_jacobiSym p pp a]
/-- The value depends only on the residue class of `a` mod `b`. -/
theorem JacobiSym.mod_left (a : ℤ) (b ab' : ℕ) (ab r b' : ℤ) (hb' : (b : ℤ) = b')
(hab : a % b' = ab) (h : (ab' : ℤ) = ab) (hr : jacobiSymNat ab' b = r) : jacobiSym a b = r := by
rw [← hr, jacobiSymNat, jacobiSym.mod_left, hb', hab, ← h]
theorem jacobiSymNat.mod_left (a b ab : ℕ) (r : ℤ) (hab : a % b = ab) (hr : jacobiSymNat ab b = r) :
jacobiSymNat a b = r := by
rw [← hr, jacobiSymNat, jacobiSymNat, _root_.jacobiSym.mod_left a b, ← hab]; rfl
/-- The symbol vanishes when both entries are even (and `b / 2 ≠ 0`). -/
theorem jacobiSymNat.even_even (a b : ℕ) (hb₀ : Nat.beq (b / 2) 0 = false) (ha : a % 2 = 0)
(hb₁ : b % 2 = 0) : jacobiSymNat a b = 0 := by
refine jacobiSym.eq_zero_iff.mpr
⟨ne_of_gt ((Nat.pos_of_ne_zero (Nat.ne_of_beq_eq_false hb₀)).trans_le (Nat.div_le_self b 2)),
fun hf => ?_⟩
have h : 2 ∣ a.gcd b := Nat.dvd_gcd (Nat.dvd_of_mod_eq_zero ha) (Nat.dvd_of_mod_eq_zero hb₁)
change 2 ∣ (a : ℤ).gcd b at h
rw [hf, ← even_iff_two_dvd] at h
exact Nat.not_even_one h
/-- When `a` is odd and `b` is even, we can replace `b` by `b / 2`. -/
theorem jacobiSymNat.odd_even (a b c : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 2 = 0) (hc : b / 2 = c)
(hr : jacobiSymNat a c = r) : jacobiSymNat a b = r := by
have ha' : legendreSym 2 a = 1 := by
simp only [legendreSym.mod 2 a, Int.ofNat_mod_ofNat, ha]
decide
rcases eq_or_ne c 0 with (rfl | hc')
· rw [← hr, Nat.eq_zero_of_dvd_of_div_eq_zero (Nat.dvd_of_mod_eq_zero hb) hc]
· haveI : NeZero c := ⟨hc'⟩
-- for `jacobiSym.mul_right`
rwa [← Nat.mod_add_div b 2, hb, hc, Nat.zero_add, jacobiSymNat, jacobiSym.mul_right,
← jacobiSym.legendreSym.to_jacobiSym, ha', one_mul]
/-- If `a` is divisible by `4` and `b` is odd, then we can remove the factor `4` from `a`. -/
theorem jacobiSymNat.double_even (a b c : ℕ) (r : ℤ) (ha : a % 4 = 0) (hb : b % 2 = 1)
(hc : a / 4 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by
simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat]
exact (jacobiSym.div_four_left (mod_cast ha) hb).symm
/-- If `a` is even and `b` is odd, then we can remove a factor `2` from `a`,
but we may have to change the sign, depending on `b % 8`.
We give one version for each of the four odd residue classes mod `8`. -/
theorem jacobiSymNat.even_odd₁ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 1)
(hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by
simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat]
rw [← jacobiSym.even_odd (mod_cast ha), if_neg (by simp [hb])]
rw [← Nat.mod_mod_of_dvd, hb]; simp
theorem jacobiSymNat.even_odd₇ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 7)
(hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = r := by
simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat]
rw [← jacobiSym.even_odd (mod_cast ha), if_neg (by simp [hb])]
rw [← Nat.mod_mod_of_dvd, hb]; simp
theorem jacobiSymNat.even_odd₃ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 3)
(hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = -r := by
simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat]
rw [← jacobiSym.even_odd (mod_cast ha), if_pos (by simp [hb])]
rw [← Nat.mod_mod_of_dvd, hb]; simp
theorem jacobiSymNat.even_odd₅ (a b c : ℕ) (r : ℤ) (ha : a % 2 = 0) (hb : b % 8 = 5)
(hc : a / 2 = c) (hr : jacobiSymNat c b = r) : jacobiSymNat a b = -r := by
simp only [jacobiSymNat, ← hr, ← hc, Int.natCast_ediv, Nat.cast_ofNat]
rw [← jacobiSym.even_odd (mod_cast ha), if_pos (by simp [hb])]
rw [← Nat.mod_mod_of_dvd, hb]; simp
/-- Use quadratic reciprocity to reduce to smaller `b`. -/
theorem jacobiSymNat.qr₁ (a b : ℕ) (r : ℤ) (ha : a % 4 = 1) (hb : b % 2 = 1)
(hr : jacobiSymNat b a = r) : jacobiSymNat a b = r := by
rwa [jacobiSymNat, jacobiSym.quadratic_reciprocity_one_mod_four ha (Nat.odd_iff.mpr hb)]
theorem jacobiSymNat.qr₁_mod (a b ab : ℕ) (r : ℤ) (ha : a % 4 = 1) (hb : b % 2 = 1)
(hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = r :=
jacobiSymNat.qr₁ _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr
theorem jacobiSymNat.qr₁' (a b : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 4 = 1)
(hr : jacobiSymNat b a = r) : jacobiSymNat a b = r := by
rwa [jacobiSymNat, ← jacobiSym.quadratic_reciprocity_one_mod_four hb (Nat.odd_iff.mpr ha)]
theorem jacobiSymNat.qr₁'_mod (a b ab : ℕ) (r : ℤ) (ha : a % 2 = 1) (hb : b % 4 = 1)
(hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = r :=
jacobiSymNat.qr₁' _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr
theorem jacobiSymNat.qr₃ (a b : ℕ) (r : ℤ) (ha : a % 4 = 3) (hb : b % 4 = 3)
(hr : jacobiSymNat b a = r) : jacobiSymNat a b = -r := by
rwa [jacobiSymNat, jacobiSym.quadratic_reciprocity_three_mod_four ha hb, neg_inj]
theorem jacobiSymNat.qr₃_mod (a b ab : ℕ) (r : ℤ) (ha : a % 4 = 3) (hb : b % 4 = 3)
(hab : b % a = ab) (hr : jacobiSymNat ab a = r) : jacobiSymNat a b = -r :=
jacobiSymNat.qr₃ _ _ _ ha hb <| jacobiSymNat.mod_left _ _ ab r hab hr
theorem isInt_jacobiSym : {a na : ℤ} → {b nb : ℕ} → {r : ℤ} →
IsInt a na → IsNat b nb → jacobiSym na nb = r → IsInt (jacobiSym a b) r
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩
theorem isInt_jacobiSymNat : {a na : ℕ} → {b nb : ℕ} → {r : ℤ} →
IsNat a na → IsNat b nb → jacobiSymNat na nb = r → IsInt (jacobiSymNat a b) r
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩
end Mathlib.Meta.NormNum
end Lemmas
section Evaluation
/-!
### Certified evaluation of the Jacobi symbol
The following functions recursively evaluate a Jacobi symbol and construct the
corresponding proof term.
-/
namespace Mathlib.Meta.NormNum
open Lean Elab Tactic Qq
/-- This evaluates `r := jacobiSymNat a b` recursively using quadratic reciprocity
and produces a proof term for the equality, assuming that `a < b` and `b` is odd. -/
partial def proveJacobiSymOdd (ea eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSymNat $ea $eb = $er) :=
match eb.natLit! with
| 1 =>
haveI : $eb =Q 1 := ⟨⟩
⟨mkRawIntLit 1, q(jacobiSymNat.one_right $ea)⟩
| b =>
match ea.natLit! with
| 0 =>
haveI : $ea =Q 0 := ⟨⟩
have hb : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr)
⟨mkRawIntLit 0, q(jacobiSymNat.zero_left $eb $hb)⟩
| 1 =>
haveI : $ea =Q 1 := ⟨⟩
⟨mkRawIntLit 1, q(jacobiSymNat.one_left $eb)⟩
| a =>
match a % 2 with
| 0 =>
match a % 4 with
| 0 =>
have ha : Q(Nat.mod $ea 4 = 0) := (q(Eq.refl 0) : Expr)
have hb : Q(Nat.mod $eb 2 = 1) := (q(Eq.refl 1) : Expr)
have ec : Q(ℕ) := mkRawNatLit (a / 4)
have hc : Q(Nat.div $ea 4 = $ec) := (q(Eq.refl $ec) : Expr)
have ⟨er, p⟩ := proveJacobiSymOdd ec eb
⟨er, q(jacobiSymNat.double_even $ea $eb $ec $er $ha $hb $hc $p)⟩
| _ =>
have ha : Q(Nat.mod $ea 2 = 0) := (q(Eq.refl 0) : Expr)
have ec : Q(ℕ) := mkRawNatLit (a / 2)
have hc : Q(Nat.div $ea 2 = $ec) := (q(Eq.refl $ec) : Expr)
have ⟨er, p⟩ := proveJacobiSymOdd ec eb
match b % 8 with
| 1 =>
have hb : Q(Nat.mod $eb 8 = 1) := (q(Eq.refl 1) : Expr)
⟨er, q(jacobiSymNat.even_odd₁ $ea $eb $ec $er $ha $hb $hc $p)⟩
| 3 =>
have er' := mkRawIntLit (-er.intLit!)
have hb : Q(Nat.mod $eb 8 = 3) := (q(Eq.refl 3) : Expr)
show (_ : Q(ℤ)) × Q(jacobiSymNat $ea $eb = -$er) from
⟨er', q(jacobiSymNat.even_odd₃ $ea $eb $ec $er $ha $hb $hc $p)⟩
| 5 =>
have er' := mkRawIntLit (-er.intLit!)
haveI : $er' =Q -$er := ⟨⟩
have hb : Q(Nat.mod $eb 8 = 5) := (q(Eq.refl 5) : Expr)
⟨er', q(jacobiSymNat.even_odd₅ $ea $eb $ec $er $ha $hb $hc $p)⟩
| _ =>
have hb : Q(Nat.mod $eb 8 = 7) := (q(Eq.refl 7) : Expr)
⟨er, q(jacobiSymNat.even_odd₇ $ea $eb $ec $er $ha $hb $hc $p)⟩
| _ =>
have eab : Q(ℕ) := mkRawNatLit (b % a)
have hab : Q(Nat.mod $eb $ea = $eab) := (q(Eq.refl $eab) : Expr)
have ⟨er, p⟩ := proveJacobiSymOdd eab ea
match a % 4 with
| 1 =>
have ha : Q(Nat.mod $ea 4 = 1) := (q(Eq.refl 1) : Expr)
have hb : Q(Nat.mod $eb 2 = 1) := (q(Eq.refl 1) : Expr)
⟨er, q(jacobiSymNat.qr₁_mod $ea $eb $eab $er $ha $hb $hab $p)⟩
| _ =>
match b % 4 with
| 1 =>
have ha : Q(Nat.mod $ea 2 = 1) := (q(Eq.refl 1) : Expr)
have hb : Q(Nat.mod $eb 4 = 1) := (q(Eq.refl 1) : Expr)
⟨er, q(jacobiSymNat.qr₁'_mod $ea $eb $eab $er $ha $hb $hab $p)⟩
| _ =>
have er' := mkRawIntLit (-er.intLit!)
haveI : $er' =Q -$er := ⟨⟩
have ha : Q(Nat.mod $ea 4 = 3) := (q(Eq.refl 3) : Expr)
have hb : Q(Nat.mod $eb 4 = 3) := (q(Eq.refl 3) : Expr)
⟨er', q(jacobiSymNat.qr₃_mod $ea $eb $eab $er $ha $hb $hab $p)⟩
/-- This evaluates `r := jacobiSymNat a b` and produces a proof term for the equality
by removing powers of `2` from `b` and then calling `proveJacobiSymOdd`. -/
partial def proveJacobiSymNat (ea eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSymNat $ea $eb = $er) :=
match eb.natLit! with
| 0 =>
haveI : $eb =Q 0 := ⟨⟩
⟨mkRawIntLit 1, q(jacobiSymNat.zero_right $ea)⟩
| 1 =>
haveI : $eb =Q 1 := ⟨⟩
⟨mkRawIntLit 1, q(jacobiSymNat.one_right $ea)⟩
| b =>
match b % 2 with
| 0 =>
match ea.natLit! with
| 0 =>
have hb : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr)
show (er : Q(ℤ)) × Q(jacobiSymNat 0 $eb = $er) from
⟨mkRawIntLit 0, q(jacobiSymNat.zero_left $eb $hb)⟩
| 1 =>
show (er : Q(ℤ)) × Q(jacobiSymNat 1 $eb = $er) from
⟨mkRawIntLit 1, q(jacobiSymNat.one_left $eb)⟩
| a =>
match a % 2 with
| 0 =>
have hb₀ : Q(Nat.beq ($eb / 2) 0 = false) := (q(Eq.refl false) : Expr)
have ha : Q(Nat.mod $ea 2 = 0) := (q(Eq.refl 0) : Expr)
have hb₁ : Q(Nat.mod $eb 2 = 0) := (q(Eq.refl 0) : Expr)
⟨mkRawIntLit 0, q(jacobiSymNat.even_even $ea $eb $hb₀ $ha $hb₁)⟩
| _ =>
have ha : Q(Nat.mod $ea 2 = 1) := (q(Eq.refl 1) : Expr)
have hb : Q(Nat.mod $eb 2 = 0) := (q(Eq.refl 0) : Expr)
have ec : Q(ℕ) := mkRawNatLit (b / 2)
have hc : Q(Nat.div $eb 2 = $ec) := (q(Eq.refl $ec) : Expr)
have ⟨er, p⟩ := proveJacobiSymOdd ea ec
⟨er, q(jacobiSymNat.odd_even $ea $eb $ec $er $ha $hb $hc $p)⟩
| _ =>
have a := ea.natLit!
if b ≤ a then
have eab : Q(ℕ) := mkRawNatLit (a % b)
have hab : Q(Nat.mod $ea $eb = $eab) := (q(Eq.refl $eab) : Expr)
have ⟨er, p⟩ := proveJacobiSymOdd eab eb
⟨er, q(jacobiSymNat.mod_left $ea $eb $eab $er $hab $p)⟩
else
proveJacobiSymOdd ea eb
/-- This evaluates `r := jacobiSym a b` and produces a proof term for the equality.
This is done by reducing to `r := jacobiSymNat (a % b) b`. -/
partial def proveJacobiSym (ea : Q(ℤ)) (eb : Q(ℕ)) : (er : Q(ℤ)) × Q(jacobiSym $ea $eb = $er) :=
match eb.natLit! with
| 0 =>
haveI : $eb =Q 0 := ⟨⟩
⟨mkRawIntLit 1, q(jacobiSym.zero_right $ea)⟩
| 1 =>
haveI : $eb =Q 1 := ⟨⟩
⟨mkRawIntLit 1, q(jacobiSym.one_right $ea)⟩
| b =>
have eb' := mkRawIntLit b
have hb' : Q(($eb : ℤ) = $eb') := (q(Eq.refl $eb') : Expr)
have ab := ea.intLit! % b
have eab := mkRawIntLit ab
have hab : Q(Int.emod $ea $eb' = $eab) := (q(Eq.refl $eab) : Expr)
have eab' : Q(ℕ) := mkRawNatLit ab.toNat
have hab' : Q(($eab' : ℤ) = $eab) := (q(Eq.refl $eab) : Expr)
have ⟨er, p⟩ := proveJacobiSymNat eab' eb
⟨er, q(JacobiSym.mod_left $ea $eb $eab' $eab $er $eb' $hb' $hab $hab' $p)⟩
end Mathlib.Meta.NormNum
end Evaluation
section Tactic
/-!
### The `norm_num` plug-in
-/
namespace Tactic
namespace NormNum
open Lean Elab Tactic Qq Mathlib.Meta.NormNum
/-- This is the `norm_num` plug-in that evaluates Jacobi symbols. -/
@[norm_num jacobiSym _ _]
def evalJacobiSym : NormNumExt where eval {u α} e := do
let .app (.app _ (a : Q(ℤ))) (b : Q(ℕ)) ← Meta.whnfR e | failure
let ⟨ea, pa⟩ ← deriveInt a _
let ⟨eb, pb⟩ ← deriveNat b _
haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩
have ⟨er, pr⟩ := proveJacobiSym ea eb
haveI' : $e =Q jacobiSym $a $b := ⟨⟩
return .isInt _ er er.intLit! q(isInt_jacobiSym $pa $pb $pr)
/-- This is the `norm_num` plug-in that evaluates Jacobi symbols on natural numbers. -/
@[norm_num jacobiSymNat _ _]
def evalJacobiSymNat : NormNumExt where eval {u α} e := do
let .app (.app _ (a : Q(ℕ))) (b : Q(ℕ)) ← Meta.whnfR e | failure
let ⟨ea, pa⟩ ← deriveNat a _
let ⟨eb, pb⟩ ← deriveNat b _
haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩
have ⟨er, pr⟩ := proveJacobiSymNat ea eb
haveI' : $e =Q jacobiSymNat $a $b := ⟨⟩
return .isInt _ er er.intLit! q(isInt_jacobiSymNat $pa $pb $pr)
/-- This is the `norm_num` plug-in that evaluates Legendre symbols. -/
@[norm_num legendreSym _ _]
def evalLegendreSym : NormNumExt where eval {u α} e := do
let .app (.app (.app _ (p : Q(ℕ))) (fp : Q(Fact (Nat.Prime $p)))) (a : Q(ℤ)) ← Meta.whnfR e |
failure
let ⟨ea, pa⟩ ← deriveInt a _
let ⟨ep, pp⟩ ← deriveNat p _
haveI' : u =QL 0 := ⟨⟩ haveI' : $α =Q ℤ := ⟨⟩
have ⟨er, pr⟩ := proveJacobiSym ea ep
haveI' : $e =Q legendreSym $p $a := ⟨⟩
return .isInt _ er er.intLit!
q(LegendreSym.to_jacobiSym $p $fp $a $er (isInt_jacobiSym $pa $pp $pr))
end NormNum
end Tactic
end Tactic |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Basic.lean | import Mathlib.Algebra.GroupWithZero.Invertible
import Mathlib.Algebra.Ring.Int.Defs
import Mathlib.Data.Nat.Cast.Basic
import Mathlib.Data.Nat.Cast.Commute
import Mathlib.Tactic.NormNum.Core
import Mathlib.Tactic.HaveI
import Mathlib.Tactic.ClearExclamation
/-!
# `norm_num` basic plugins
This file adds `norm_num` plugins for
* constructors and constants
* `Nat.cast`, `Int.cast`, and `mkRat`
* `+`, `-`, `*`, and `/`
* `Nat.succ`, `Nat.sub`, `Nat.mod`, and `Nat.div`.
See other files in this directory for many more plugins.
-/
universe u
namespace Mathlib
open Lean
open Meta
namespace Meta.NormNum
open Qq
theorem IsInt.raw_refl (n : ℤ) : IsInt n n := ⟨rfl⟩
/-! ### Constructors and constants -/
theorem isNat_zero (α) [AddMonoidWithOne α] : IsNat (Zero.zero : α) (nat_lit 0) :=
⟨Nat.cast_zero.symm⟩
/-- The `norm_num` extension which identifies the expression `Zero.zero`, returning `0`. -/
@[norm_num Zero.zero] def evalZero : NormNumExt where eval {u α} e := do
let sα ← inferAddMonoidWithOne α
match e with
| ~q(Zero.zero) => return .isNat sα q(nat_lit 0) q(isNat_zero $α)
theorem isNat_one (α) [AddMonoidWithOne α] : IsNat (One.one : α) (nat_lit 1) := ⟨Nat.cast_one.symm⟩
/-- The `norm_num` extension which identifies the expression `One.one`, returning `1`. -/
@[norm_num One.one] def evalOne : NormNumExt where eval {u α} e := do
let sα ← inferAddMonoidWithOne α
match e with
| ~q(One.one) => return .isNat sα q(nat_lit 1) q(isNat_one $α)
theorem isNat_ofNat (α : Type u) [AddMonoidWithOne α] {a : α} {n : ℕ}
(h : n = a) : IsNat a n := ⟨h.symm⟩
/-- The `norm_num` extension which identifies an expression `OfNat.ofNat n`, returning `n`. -/
@[norm_num OfNat.ofNat _] def evalOfNat : NormNumExt where eval {u α} e := do
let sα ← inferAddMonoidWithOne α
match e with
| ~q(@OfNat.ofNat _ $n $oα) =>
let n : Q(ℕ) ← whnf n
guard n.isRawNatLit
let ⟨a, (pa : Q($n = $e))⟩ ← mkOfNat α sα n
guard <|← isDefEq a e
return .isNat sα n q(isNat_ofNat $α $pa)
theorem isNat_intOfNat : {n n' : ℕ} → IsNat n n' → IsNat (Int.ofNat n) n'
| _, _, ⟨rfl⟩ => ⟨rfl⟩
/-- The `norm_num` extension which identifies the constructor application `Int.ofNat n` such that
`norm_num` successfully recognizes `n`, returning `n`. -/
@[norm_num Int.ofNat _] def evalIntOfNat : NormNumExt where eval {u α} e := do
let .app (.const ``Int.ofNat _) (n : Q(ℕ)) ← whnfR e | failure
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q Int := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let sℤ : Q(AddMonoidWithOne ℤ) := q(instAddMonoidWithOne)
let ⟨n', p⟩ ← deriveNat n sℕ
haveI' x : $e =Q Int.ofNat $n := ⟨⟩
return .isNat sℤ n' q(isNat_intOfNat $p)
theorem isInt_negOfNat (m n : ℕ) (h : IsNat m n) : IsInt (Int.negOfNat m) (.negOfNat n) :=
⟨congr_arg Int.negOfNat h.1⟩
/-- `norm_num` extension for `Int.negOfNat`.
It's useful for calling `derive` with the numerator of an `.isNegNNRat` branch. -/
@[norm_num Int.negOfNat _]
def evalNegOfNat : NormNumExt where eval {u αZ} e := do
match u, αZ, e with
| 0, ~q(ℤ), ~q(Int.negOfNat $a) =>
let ⟨n, pn⟩ ← deriveNat (u := 0) a q(inferInstance)
return .isNegNat q(inferInstance) n q(isInt_negOfNat $a $n $pn)
| _ => failure
theorem isNat_natAbs_pos : {n : ℤ} → {a : ℕ} → IsNat n a → IsNat n.natAbs a
| _, _, ⟨rfl⟩ => ⟨rfl⟩
theorem isNat_natAbs_neg : {n : ℤ} → {a : ℕ} → IsInt n (.negOfNat a) → IsNat n.natAbs a
| _, _, ⟨rfl⟩ => ⟨by simp⟩
/-- The `norm_num` extension which identifies the expression `Int.natAbs n` such that
`norm_num` successfully recognizes `n`. -/
@[norm_num Int.natAbs (_ : ℤ)] def evalIntNatAbs : NormNumExt where eval {u α} e := do
let .app (.const ``Int.natAbs _) (x : Q(ℤ)) ← whnfR e | failure
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q Int.natAbs $x := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
match ← derive (u := .zero) x with
| .isNat _ a p => assumeInstancesCommute; return .isNat sℕ a q(isNat_natAbs_pos $p)
| .isNegNat _ a p => assumeInstancesCommute; return .isNat sℕ a q(isNat_natAbs_neg $p)
| _ => failure
/-! ### Casts -/
theorem isNat_natCast {R} [AddMonoidWithOne R] (n m : ℕ) :
IsNat n m → IsNat (n : R) m := by rintro ⟨⟨⟩⟩; exact ⟨rfl⟩
/-- The `norm_num` extension which identifies an expression `Nat.cast n`, returning `n`. -/
@[norm_num Nat.cast _, NatCast.natCast _] def evalNatCast : NormNumExt where eval {u α} e := do
let sα ← inferAddMonoidWithOne α
let .app n (a : Q(ℕ)) ← whnfR e | failure
guard <|← withNewMCtxDepth <| isDefEq n q(Nat.cast (R := $α))
let ⟨na, pa⟩ ← deriveNat a q(instAddMonoidWithOneNat)
haveI' : $e =Q $a := ⟨⟩
return .isNat sα na q(isNat_natCast $a $na $pa)
theorem isNat_intCast {R} [Ring R] (n : ℤ) (m : ℕ) :
IsNat n m → IsNat (n : R) m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩
theorem isintCast {R} [Ring R] (n m : ℤ) :
IsInt n m → IsInt (n : R) m := by rintro ⟨⟨⟩⟩; exact ⟨rfl⟩
/-- The `norm_num` extension which identifies an expression `Int.cast n`, returning `n`. -/
@[norm_num Int.cast _, IntCast.intCast _] def evalIntCast : NormNumExt where eval {u α} e := do
let rα ← inferRing α
let .app i (a : Q(ℤ)) ← whnfR e | failure
guard <|← withNewMCtxDepth <| isDefEq i q(Int.cast (R := $α))
match ← derive (α := q(ℤ)) a with
| .isNat _ na pa =>
assumeInstancesCommute
haveI' : $e =Q Int.cast $a := ⟨⟩
return .isNat _ na q(isNat_intCast $a $na $pa)
| .isNegNat _ na pa =>
assumeInstancesCommute
haveI' : $e =Q Int.cast $a := ⟨⟩
return .isNegNat _ na q(isintCast $a (.negOfNat $na) $pa)
| _ => failure
/-! ### Arithmetic -/
library_note2 «norm_num lemma function equality» /--
Note: Many of the lemmas in this file use a function equality hypothesis like `f = HAdd.hAdd`
below. The reason for this is that when this is applied, to prove e.g. `100 + 200 = 300`, the
`+` here is `HAdd.hAdd` with an instance that may not be syntactically equal to the one supplied
by the `AddMonoidWithOne` instance, and rather than attempting to prove the instances equal lean
will sometimes decide to evaluate `100 + 200` directly (into whatever `+` is defined to do in this
ring), which is definitely not what we want; if the subterms are expensive to kernel-reduce then
this could cause a `(kernel) deep recursion detected` error (see https://github.com/leanprover/lean4/issues/2171, https://github.com/leanprover-community/mathlib4/pull/4048).
By using an equality for the unapplied `+` function and proving it by `rfl` we take away the
opportunity for lean to unfold the numerals (and the instance defeq problem is usually comparatively
easy).
-/
-- see note [norm_num lemma function equality]
theorem isNat_add {α} [AddMonoidWithOne α] : ∀ {f : α → α → α} {a b : α} {a' b' c : ℕ},
f = HAdd.hAdd → IsNat a a' → IsNat b b' → Nat.add a' b' = c → IsNat (f a b) c
| _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨(Nat.cast_add _ _).symm⟩
-- see note [norm_num lemma function equality]
theorem isInt_add {α} [Ring α] : ∀ {f : α → α → α} {a b : α} {a' b' c : ℤ},
f = HAdd.hAdd → IsInt a a' → IsInt b b' → Int.add a' b' = c → IsInt (f a b) c
| _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨(Int.cast_add ..).symm⟩
/-- If `b` divides `a` and `a` is invertible, then `b` is invertible. -/
def invertibleOfMul {α} [Semiring α] (k : ℕ) (b : α) :
∀ (a : α) [Invertible a], a = k * b → Invertible b
| _, ⟨c, hc1, hc2⟩, rfl => by
rw [← mul_assoc] at hc1
rw [Nat.cast_commute k, mul_assoc, Nat.cast_commute k] at hc2
exact ⟨_, hc1, hc2⟩
/-- If `b` divides `a` and `a` is invertible, then `b` is invertible. -/
def invertibleOfMul' {α} [Semiring α] {a k b : ℕ} [Invertible (a : α)]
(h : a = k * b) : Invertible (b : α) := invertibleOfMul k (b:α) ↑a (by simp [h])
-- see note [norm_num lemma function equality]
theorem isNNRat_add {α} [Semiring α] {f : α → α → α} {a b : α} {na nb nc : ℕ} {da db dc k : ℕ} :
f = HAdd.hAdd → IsNNRat a na da → IsNNRat b nb db →
Nat.add (Nat.mul na db) (Nat.mul nb da) = Nat.mul k nc →
Nat.mul da db = Nat.mul k dc →
IsNNRat (f a b) nc dc := by
rintro rfl ⟨_, rfl⟩ ⟨_, rfl⟩ (h₁ : na * db + nb * da = k * nc) (h₂ : da * db = k * dc)
have : Invertible (↑(da * db) : α) := by simpa using invertibleMul (da:α) db
have := invertibleOfMul' (α := α) h₂
use this
have H := (Nat.cast_commute (α := α) da db).invOf_left.invOf_right.right_comm
have h₁ := congr_arg (↑· * (⅟↑da * ⅟↑db : α)) h₁
simp only [Nat.cast_add, Nat.cast_mul, ← mul_assoc,
add_mul, mul_invOf_cancel_right] at h₁
have h₂ := congr_arg (↑nc * ↑· * (⅟↑da * ⅟↑db * ⅟↑dc : α)) h₂
simp only [H, mul_invOf_cancel_right', Nat.cast_mul, ← mul_assoc] at h₁ h₂
rw [h₁, h₂, Nat.cast_commute]
simp only [mul_invOf_cancel_right,
(Nat.cast_commute (α := α) da dc).invOf_left.invOf_right.right_comm,
(Nat.cast_commute (α := α) db dc).invOf_left.invOf_right.right_comm]
-- TODO: clean up and move it somewhere in mathlib? It's a bit much for this file
-- see note [norm_num lemma function equality]
theorem isRat_add {α} [Ring α] {f : α → α → α} {a b : α} {na nb nc : ℤ} {da db dc k : ℕ} :
f = HAdd.hAdd → IsRat a na da → IsRat b nb db →
Int.add (Int.mul na db) (Int.mul nb da) = Int.mul k nc →
Nat.mul da db = Nat.mul k dc →
IsRat (f a b) nc dc := by
rintro rfl ⟨_, rfl⟩ ⟨_, rfl⟩ (h₁ : na * db + nb * da = k * nc) (h₂ : da * db = k * dc)
have : Invertible (↑(da * db) : α) := by simpa using invertibleMul (da:α) db
have := invertibleOfMul' (α := α) h₂
use this
have H := (Nat.cast_commute (α := α) da db).invOf_left.invOf_right.right_comm
have h₁ := congr_arg (↑· * (⅟↑da * ⅟↑db : α)) h₁
simp only [Int.cast_add, Int.cast_mul, Int.cast_natCast, ← mul_assoc,
add_mul, mul_invOf_cancel_right] at h₁
have h₂ := congr_arg (↑nc * ↑· * (⅟↑da * ⅟↑db * ⅟↑dc : α)) h₂
simp only [H, mul_invOf_cancel_right', Nat.cast_mul, ← mul_assoc] at h₁ h₂
rw [h₁, h₂, Nat.cast_commute]
simp only [mul_invOf_cancel_right,
(Nat.cast_commute (α := α) da dc).invOf_left.invOf_right.right_comm,
(Nat.cast_commute (α := α) db dc).invOf_left.invOf_right.right_comm]
/-- Consider an `Option` as an object in the `MetaM` monad, by throwing an error on `none`. -/
def _root_.Mathlib.Meta.monadLiftOptionMetaM : MonadLift Option MetaM where
monadLift
| none => failure
| some e => pure e
attribute [local instance] monadLiftOptionMetaM in
/-- The result of adding two norm_num results. -/
def Result.add {u : Level} {α : Q(Type u)} {a b : Q($α)} (ra : Result q($a)) (rb : Result q($b))
(inst : Q(Add $α) := by exact q(delta% inferInstance)) :
MetaM (Result q($a + $b)) := do
let rec intArm (rα : Q(Ring $α)) := do
assumeInstancesCommute
let ⟨za, na, pa⟩ ← ra.toInt _; let ⟨zb, nb, pb⟩ ← rb.toInt _
let zc := za + zb
have c := mkRawIntLit zc
haveI' : Int.add $na $nb =Q $c := ⟨⟩
return .isInt rα c zc q(isInt_add (.refl _) $pa $pb (.refl $c))
let rec nnratArm (dsα : Q(DivisionSemiring $α)) : MetaM (Result _) := do
assumeInstancesCommute
let ⟨qa, na, da, pa⟩ ← ra.toNNRat' dsα; let ⟨qb, nb, db, pb⟩ ← rb.toNNRat' dsα
let qc := qa + qb
let dd := qa.den * qb.den
let k := dd / qc.den
have t1 : Q(ℕ) := mkRawNatLit (k * qc.num.toNat)
have t2 : Q(ℕ) := mkRawNatLit dd
have nc : Q(ℕ) := mkRawNatLit qc.num.toNat
have dc : Q(ℕ) := mkRawNatLit qc.den
have k : Q(ℕ) := mkRawNatLit k
let r1 : Q(Nat.add (Nat.mul $na $db) (Nat.mul $nb $da) = Nat.mul $k $nc) :=
(q(Eq.refl $t1) : Expr)
let r2 : Q(Nat.mul $da $db = Nat.mul $k $dc) := (q(Eq.refl $t2) : Expr)
return .isNNRat' dsα qc nc dc q(isNNRat_add (.refl _) $pa $pb $r1 $r2)
let rec ratArm (dα : Q(DivisionRing $α)) : MetaM (Result _) := do
assumeInstancesCommute
let ⟨qa, na, da, pa⟩ ← ra.toRat' dα; let ⟨qb, nb, db, pb⟩ ← rb.toRat' dα
let qc := qa + qb
let dd := qa.den * qb.den
let k := dd / qc.den
have t1 : Q(ℤ) := mkRawIntLit (k * qc.num)
have t2 : Q(ℕ) := mkRawNatLit dd
have nc : Q(ℤ) := mkRawIntLit qc.num
have dc : Q(ℕ) := mkRawNatLit qc.den
have k : Q(ℕ) := mkRawNatLit k
let r1 : Q(Int.add (Int.mul $na $db) (Int.mul $nb $da) = Int.mul $k $nc) :=
(q(Eq.refl $t1) : Expr)
let r2 : Q(Nat.mul $da $db = Nat.mul $k $dc) := (q(Eq.refl $t2) : Expr)
return .isRat dα qc nc dc q(isRat_add (.refl _) $pa $pb $r1 $r2)
match ra, rb with
| .isBool .., _ | _, .isBool .. => failure
| .isNegNNRat dα .., _ | _, .isNegNNRat dα .. => ratArm dα
-- mixing positive rationals and negative naturals means we need to use the full rat handler
| .isNNRat _dsα .., .isNegNat _rα .. | .isNegNat _rα .., .isNNRat _dsα .. =>
-- could alternatively try to combine `rα` and `dsα` here, but we'd have to do a defeq check
-- so would still need to be in `MetaM`.
let dα ← synthInstanceQ q(DivisionRing $α)
assumeInstancesCommute
ratArm q($dα)
| .isNNRat dsα .., _ | _, .isNNRat dsα .. => nnratArm dsα
| .isNegNat rα .., _ | _, .isNegNat rα .. => intArm rα
| .isNat _ na pa, .isNat sα nb pb =>
assumeInstancesCommute
have c : Q(ℕ) := mkRawNatLit (na.natLit! + nb.natLit!)
haveI' : Nat.add $na $nb =Q $c := ⟨⟩
return .isNat sα c q(isNat_add (.refl _) $pa $pb (.refl $c))
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `a + b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num _ + _] def evalAdd : NormNumExt where eval {u α} e := do
let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← whnfR e | failure
let ra ← derive a; let rb ← derive b
match ra, rb with
| .isBool .., _ | _, .isBool .. => failure
| .isNat _ .., .isNat _ .. | .isNat _ .., .isNegNat _ .. | .isNat _ .., .isNNRat _ ..
| .isNat _ .., .isNegNNRat _ ..
| .isNegNat _ .., .isNat _ .. | .isNegNat _ .., .isNegNat _ .. | .isNegNat _ .., .isNNRat _ ..
| .isNegNat _ .., .isNegNNRat _ ..
| .isNNRat _ .., .isNat _ .. | .isNNRat _ .., .isNegNat _ .. | .isNNRat _ .., .isNNRat _ ..
| .isNNRat _ .., .isNegNNRat _ ..
| .isNegNNRat _ .., .isNat _ .. | .isNegNNRat _ .., .isNegNat _ ..
| .isNegNNRat _ .., .isNNRat _ .. | .isNegNNRat _ .., .isNegNNRat _ .. =>
guard <|← withNewMCtxDepth <| isDefEq f q(HAdd.hAdd (α := $α))
ra.add rb
-- see note [norm_num lemma function equality]
theorem isInt_neg {α} [Ring α] : ∀ {f : α → α} {a : α} {a' b : ℤ},
f = Neg.neg → IsInt a a' → Int.neg a' = b → IsInt (-a) b
| _, _, _, _, rfl, ⟨rfl⟩, rfl => ⟨(Int.cast_neg ..).symm⟩
-- see note [norm_num lemma function equality]
theorem isRat_neg {α} [Ring α] : ∀ {f : α → α} {a : α} {n n' : ℤ} {d : ℕ},
f = Neg.neg → IsRat a n d → Int.neg n = n' → IsRat (-a) n' d
| _, _, _, _, _, rfl, ⟨h, rfl⟩, rfl => ⟨h, by rw [← neg_mul, ← Int.cast_neg]; rfl⟩
attribute [local instance] monadLiftOptionMetaM in
/-- The result of negating a norm_num result. -/
def Result.neg {u : Level} {α : Q(Type u)} {a : Q($α)} (ra : Result q($a))
(rα : Q(Ring $α) := by exact q(delta% inferInstance)) :
MetaM (Result q(-$a)) := do
let intArm (rα : Q(Ring $α)) := do
assumeInstancesCommute
let ⟨za, na, pa⟩ ← ra.toInt rα
let zb := -za
have b := mkRawIntLit zb
haveI' : Int.neg $na =Q $b := ⟨⟩
return .isInt rα b zb q(isInt_neg (.refl _) $pa (.refl $b))
let ratArm (dα : Q(DivisionRing $α)) : Option (Result _) := do
assumeInstancesCommute
let ⟨qa, na, da, pa⟩ ← ra.toRat' dα
let qb := -qa
have nb := mkRawIntLit qb.num
haveI' : Int.neg $na =Q $nb := ⟨⟩
return .isRat dα qb nb da q(isRat_neg (.refl _) $pa (.refl $nb))
match ra with
| .isBool _ .. => failure
| .isNat _ .. => intArm rα
| .isNegNat rα .. => intArm rα
| .isNNRat _dsα .. => ratArm (← synthInstanceQ q(DivisionRing $α))
| .isNegNNRat dα .. => ratArm dα
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `-a`,
such that `norm_num` successfully recognises `a`. -/
@[norm_num -_] def evalNeg : NormNumExt where eval {u α} e := do
let .app (f : Q($α → $α)) (a : Q($α)) ← whnfR e | failure
let ra ← derive a
let rα ← inferRing α
let ⟨(_f_eq : $f =Q Neg.neg)⟩ ← withNewMCtxDepth <| assertDefEqQ _ _
haveI' _e_eq : $e =Q -$a := ⟨⟩
ra.neg
-- see note [norm_num lemma function equality]
theorem isInt_sub {α} [Ring α] : ∀ {f : α → α → α} {a b : α} {a' b' c : ℤ},
f = HSub.hSub → IsInt a a' → IsInt b b' → Int.sub a' b' = c → IsInt (f a b) c
| _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨(Int.cast_sub ..).symm⟩
-- see note [norm_num lemma function equality]
theorem isRat_sub {α} [Ring α] {f : α → α → α} {a b : α} {na nb nc : ℤ} {da db dc k : ℕ}
(hf : f = HSub.hSub) (ra : IsRat a na da) (rb : IsRat b nb db)
(h₁ : Int.sub (Int.mul na db) (Int.mul nb da) = Int.mul k nc)
(h₂ : Nat.mul da db = Nat.mul k dc) :
IsRat (f a b) nc dc := by
rw [hf, sub_eq_add_neg]
refine isRat_add rfl ra (isRat_neg (n' := -nb) rfl rb rfl) (k := k) (nc := nc) ?_ h₂
rw [show Int.mul (-nb) _ = _ from neg_mul ..]; exact h₁
attribute [local instance] monadLiftOptionMetaM in
/-- The result of subtracting two norm_num results. -/
def Result.sub {u : Level} {α : Q(Type u)} {a b : Q($α)} (ra : Result q($a)) (rb : Result q($b))
(inst : Q(Ring $α) := by exact q(delta% inferInstance)) :
MetaM (Result q($a - $b)) := do
let intArm (rα : Q(Ring $α)) := do
assumeInstancesCommute
let ⟨za, na, pa⟩ ← ra.toInt rα; let ⟨zb, nb, pb⟩ ← rb.toInt rα
let zc := za - zb
have c := mkRawIntLit zc
haveI' : Int.sub $na $nb =Q $c := ⟨⟩
return Result.isInt rα c zc q(isInt_sub (.refl _) $pa $pb (.refl $c))
let ratArm (dα : Q(DivisionRing $α)) : MetaM (Result _) := do
assumeInstancesCommute
let ⟨qa, na, da, pa⟩ ← ra.toRat' dα; let ⟨qb, nb, db, pb⟩ ← rb.toRat' dα
let qc := qa - qb
let dd := qa.den * qb.den
let k := dd / qc.den
have t1 : Q(ℤ) := mkRawIntLit (k * qc.num)
have t2 : Q(ℕ) := mkRawNatLit dd
have nc : Q(ℤ) := mkRawIntLit qc.num
have dc : Q(ℕ) := mkRawNatLit qc.den
have k : Q(ℕ) := mkRawNatLit k
let r1 : Q(Int.sub (Int.mul $na $db) (Int.mul $nb $da) = Int.mul $k $nc) :=
(q(Eq.refl $t1) : Expr)
let r2 : Q(Nat.mul $da $db = Nat.mul $k $dc) := (q(Eq.refl $t2) : Expr)
return .isRat dα qc nc dc q(isRat_sub (.refl _) $pa $pb $r1 $r2)
match ra, rb with
| .isBool .., _ | _, .isBool .. => failure
| .isNegNNRat dα .., _ | _, .isNegNNRat dα .. =>
ratArm dα
| _, .isNNRat _dsα .. | .isNNRat _dsα .., _ =>
ratArm (← synthInstanceQ q(DivisionRing $α))
| .isNegNat _rα .., _ | _, .isNegNat _rα ..
| .isNat _ .., .isNat _ .. =>
intArm inst
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `a - b` in a ring,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num _ - _] def evalSub : NormNumExt where eval {u α} e := do
let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← whnfR e | failure
let rα ← inferRing α
let ⟨(_f_eq : $f =Q HSub.hSub)⟩ ← withNewMCtxDepth <| assertDefEqQ _ _
let ra ← derive a; let rb ← derive b
haveI' _e_eq : $e =Q $a - $b := ⟨⟩
ra.sub rb
-- see note [norm_num lemma function equality]
theorem isNat_mul {α} [Semiring α] : ∀ {f : α → α → α} {a b : α} {a' b' c : ℕ},
f = HMul.hMul → IsNat a a' → IsNat b b' → Nat.mul a' b' = c → IsNat (a * b) c
| _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨(Nat.cast_mul ..).symm⟩
-- see note [norm_num lemma function equality]
theorem isInt_mul {α} [Ring α] : ∀ {f : α → α → α} {a b : α} {a' b' c : ℤ},
f = HMul.hMul → IsInt a a' → IsInt b b' → Int.mul a' b' = c → IsInt (a * b) c
| _, _, _, _, _, _, rfl, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨(Int.cast_mul ..).symm⟩
theorem isNNRat_mul {α} [Semiring α] {f : α → α → α} {a b : α} {na nb nc : ℕ} {da db dc k : ℕ} :
f = HMul.hMul → IsNNRat a na da → IsNNRat b nb db →
Nat.mul na nb = Nat.mul k nc →
Nat.mul da db = Nat.mul k dc →
IsNNRat (f a b) nc dc := by
rintro rfl ⟨_, rfl⟩ ⟨_, rfl⟩ (h₁ : na * nb = k * nc) (h₂ : da * db = k * dc)
have : Invertible (↑(da * db) : α) := by simpa using invertibleMul (da:α) db
have := invertibleOfMul' (α := α) h₂
refine ⟨this, ?_⟩
have H := (Nat.cast_commute (α := α) da db).invOf_left.invOf_right.right_comm
have h₁ := congr_arg (Nat.cast (R := α)) h₁
simp only [Nat.cast_mul] at h₁
simp only [← mul_assoc, (Nat.cast_commute (α := α) da nb).invOf_left.right_comm, h₁]
have h₂ := congr_arg (↑nc * ↑· * (⅟↑da * ⅟↑db * ⅟↑dc : α)) h₂
simp only [Nat.cast_mul, ← mul_assoc] at h₂; rw [H] at h₂
simp only [mul_invOf_cancel_right'] at h₂; rw [h₂, Nat.cast_commute]
simp only [mul_invOf_cancel_right',
(Nat.cast_commute (α := α) da dc).invOf_left.invOf_right.right_comm,
(Nat.cast_commute (α := α) db dc).invOf_left.invOf_right.right_comm]
theorem isRat_mul {α} [Ring α] {f : α → α → α} {a b : α} {na nb nc : ℤ} {da db dc k : ℕ} :
f = HMul.hMul → IsRat a na da → IsRat b nb db →
Int.mul na nb = Int.mul k nc →
Nat.mul da db = Nat.mul k dc →
IsRat (f a b) nc dc := by
rintro rfl ⟨_, rfl⟩ ⟨_, rfl⟩ (h₁ : na * nb = k * nc) (h₂ : da * db = k * dc)
have : Invertible (↑(da * db) : α) := by simpa using invertibleMul (da:α) db
have := invertibleOfMul' (α := α) h₂
refine ⟨this, ?_⟩
have H := (Nat.cast_commute (α := α) da db).invOf_left.invOf_right.right_comm
have h₁ := congr_arg (Int.cast (R := α)) h₁
simp only [Int.cast_mul, Int.cast_natCast] at h₁
simp only [← mul_assoc, (Nat.cast_commute (α := α) da nb).invOf_left.right_comm, h₁]
have h₂ := congr_arg (↑nc * ↑· * (⅟↑da * ⅟↑db * ⅟↑dc : α)) h₂
simp only [Nat.cast_mul, ← mul_assoc] at h₂; rw [H] at h₂
simp only [mul_invOf_cancel_right'] at h₂; rw [h₂, Nat.cast_commute]
simp only [mul_invOf_cancel_right,
(Nat.cast_commute (α := α) da dc).invOf_left.invOf_right.right_comm,
(Nat.cast_commute (α := α) db dc).invOf_left.invOf_right.right_comm]
attribute [local instance] monadLiftOptionMetaM in
/-- The result of multiplying two norm_num results. -/
def Result.mul {u : Level} {α : Q(Type u)} {a b : Q($α)} (ra : Result q($a)) (rb : Result q($b))
(inst : Q(Semiring $α) := by exact q(delta% inferInstance)) :
MetaM (Result q($a * $b)) := do
let intArm (rα : Q(Ring $α)) := do
assumeInstancesCommute
let ⟨za, na, pa⟩ ← ra.toInt rα; let ⟨zb, nb, pb⟩ ← rb.toInt rα
let zc := za * zb
have c := mkRawIntLit zc
haveI' : Int.mul $na $nb =Q $c := ⟨⟩
return .isInt rα c zc q(isInt_mul (.refl _) $pa $pb (.refl $c))
let nnratArm (dsα : Q(DivisionSemiring $α)) : Option (Result _) := do
assumeInstancesCommute
let ⟨qa, na, da, pa⟩ ← ra.toNNRat' dsα; let ⟨qb, nb, db, pb⟩ ← rb.toNNRat' dsα
let qc := qa * qb
let dd := qa.den * qb.den
let k := dd / qc.den
have nc : Q(ℕ) := mkRawNatLit qc.num.toNat
have dc : Q(ℕ) := mkRawNatLit qc.den
have k : Q(ℕ) := mkRawNatLit k
let r1 : Q(Nat.mul $na $nb = Nat.mul $k $nc) :=
(q(Eq.refl (Nat.mul $na $nb)) : Expr)
have t2 : Q(ℕ) := mkRawNatLit dd
let r2 : Q(Nat.mul $da $db = Nat.mul $k $dc) := (q(Eq.refl $t2) : Expr)
return .isNNRat' dsα qc nc dc q(isNNRat_mul (.refl _) $pa $pb $r1 $r2)
let rec ratArm (dα : Q(DivisionRing $α)) : Option (Result _) := do
assumeInstancesCommute
let ⟨qa, na, da, pa⟩ ← ra.toRat' dα; let ⟨qb, nb, db, pb⟩ ← rb.toRat' dα
let qc := qa * qb
let dd := qa.den * qb.den
let k := dd / qc.den
have nc : Q(ℤ) := mkRawIntLit qc.num
have dc : Q(ℕ) := mkRawNatLit qc.den
have k : Q(ℕ) := mkRawNatLit k
let r1 : Q(Int.mul $na $nb = Int.mul $k $nc) :=
(q(Eq.refl (Int.mul $na $nb)) : Expr)
have t2 : Q(ℕ) := mkRawNatLit dd
let r2 : Q(Nat.mul $da $db = Nat.mul $k $dc) := (q(Eq.refl $t2) : Expr)
return .isRat dα qc nc dc q(isRat_mul (.refl _) $pa $pb $r1 $r2)
match ra, rb with
| .isBool .., _ | _, .isBool .. => failure
| .isNegNNRat dα .., _ | _, .isNegNNRat dα .. =>
ratArm dα
-- mixing positive rationals and negative naturals means we need to use the full rat handler
| .isNNRat dsα .., .isNegNat rα .. | .isNegNat rα .., .isNNRat dsα .. =>
-- could alternatively try to combine `rα` and `dsα` here, but we'd have to do a defeq check
-- so would still need to be in `MetaM`.
ratArm (←synthInstanceQ q(DivisionRing $α))
| .isNNRat dsα .., _ | _, .isNNRat dsα .. =>
nnratArm dsα
| .isNegNat rα .., _ | _, .isNegNat rα .. => intArm rα
| .isNat mα' na pa, .isNat mα nb pb => do
haveI' : $mα =Q by clear! $mα $mα'; apply AddCommMonoidWithOne.toAddMonoidWithOne := ⟨⟩
assumeInstancesCommute
have c : Q(ℕ) := mkRawNatLit (na.natLit! * nb.natLit!)
haveI' : Nat.mul $na $nb =Q $c := ⟨⟩
return .isNat mα c q(isNat_mul (.refl _) $pa $pb (.refl $c))
/-- The `norm_num` extension which identifies expressions of the form `a * b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num _ * _] def evalMul : NormNumExt where eval {u α} e := do
let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← whnfR e | failure
let sα ← inferSemiring α
let ra ← derive a; let rb ← derive b
guard <|← withNewMCtxDepth <| isDefEq f q(HMul.hMul (α := $α))
haveI' : $f =Q HMul.hMul := ⟨⟩
haveI' : $e =Q $a * $b := ⟨⟩
ra.mul rb
theorem isNNRat_div {α : Type u} [DivisionSemiring α] : {a b : α} → {cn : ℕ} → {cd : ℕ} →
IsNNRat (a * b⁻¹) cn cd → IsNNRat (a / b) cn cd
| _, _, _, _, h => by simpa [div_eq_mul_inv] using h
theorem isRat_div {α : Type u} [DivisionRing α] : {a b : α} → {cn : ℤ} → {cd : ℕ} →
IsRat (a * b⁻¹) cn cd → IsRat (a / b) cn cd
| _, _, _, _, h => by simpa [div_eq_mul_inv] using h
/-- Helper function to synthesize a typed `DivisionSemiring α` expression. -/
def inferDivisionSemiring {u : Level} (α : Q(Type u)) : MetaM Q(DivisionSemiring $α) :=
return ← synthInstanceQ q(DivisionSemiring $α) <|> throwError "not a division semiring"
/-- Helper function to synthesize a typed `DivisionRing α` expression. -/
def inferDivisionRing {u : Level} (α : Q(Type u)) : MetaM Q(DivisionRing $α) :=
return ← synthInstanceQ q(DivisionRing $α) <|> throwError "not a division ring"
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `a / b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num _ / _] def evalDiv : NormNumExt where eval {u α} e := do
let .app (.app f (a : Q($α))) (b : Q($α)) ← whnfR e | failure
let dsα ← inferDivisionSemiring α
haveI' : $e =Q $a / $b := ⟨⟩
guard <| ← withNewMCtxDepth <| isDefEq f q(HDiv.hDiv (α := $α))
let rab ← derive (q($a * $b⁻¹) : Q($α))
if let some ⟨qa, na, da, pa⟩ := rab.toNNRat' dsα then
assumeInstancesCommute
return .isNNRat' dsα qa na da q(isNNRat_div $pa)
else
let dα ← inferDivisionRing α
let ⟨qa, na, da, pa⟩ ← rab.toRat' dα
assumeInstancesCommute
return .isRat dα qa na da q(isRat_div $pa)
/-! ### Logic -/
/-- The `norm_num` extension which identifies `True`. -/
@[norm_num True] def evalTrue : NormNumExt where eval {u α} e :=
return (.isTrue q(True.intro) : Result q(True))
/-- The `norm_num` extension which identifies `False`. -/
@[norm_num False] def evalFalse : NormNumExt where eval {u α} e :=
return (.isFalse q(not_false) : Result q(False))
/-- The `norm_num` extension which identifies expressions of the form `¬a`,
such that `norm_num` successfully recognises `a`. -/
@[norm_num ¬_] def evalNot : NormNumExt where eval {u α} e := do
let .app (.const ``Not _) (a : Q(Prop)) ← whnfR e | failure
guard <|← withNewMCtxDepth <| isDefEq α q(Prop)
let ⟨b, p⟩ ← deriveBool q($a)
match b with
| true => return .isFalse q(not_not_intro $p)
| false => return .isTrue q($p)
/-! ### (In)equalities -/
variable {α : Type u}
theorem isNat_eq_true [AddMonoidWithOne α] : {a b : α} → {c : ℕ} →
IsNat a c → IsNat b c → a = b
| _, _, _, ⟨rfl⟩, ⟨rfl⟩ => rfl
theorem ble_eq_false {x y : ℕ} : x.ble y = false ↔ y < x := by
rw [← Nat.not_le, ← Bool.not_eq_true, Nat.ble_eq]
theorem isInt_eq_true [Ring α] : {a b : α} → {z : ℤ} → IsInt a z → IsInt b z → a = b
| _, _, _, ⟨rfl⟩, ⟨rfl⟩ => rfl
theorem isNNRat_eq_true [Semiring α] : {a b : α} → {n : ℕ} → {d : ℕ} →
IsNNRat a n d → IsNNRat b n d → a = b
| _, _, _, _, ⟨_, rfl⟩, ⟨_, rfl⟩ => by congr; apply Subsingleton.elim
theorem isRat_eq_true [Ring α] : {a b : α} → {n : ℤ} → {d : ℕ} →
IsRat a n d → IsRat b n d → a = b
| _, _, _, _, ⟨_, rfl⟩, ⟨_, rfl⟩ => by congr; apply Subsingleton.elim
theorem eq_of_true {a b : Prop} (ha : a) (hb : b) : a = b := propext (iff_of_true ha hb)
theorem ne_of_false_of_true {a b : Prop} (ha : ¬a) (hb : b) : a ≠ b := mt (· ▸ hb) ha
theorem ne_of_true_of_false {a b : Prop} (ha : a) (hb : ¬b) : a ≠ b := mt (· ▸ ha) hb
theorem eq_of_false {a b : Prop} (ha : ¬a) (hb : ¬b) : a = b := propext (iff_of_false ha hb)
/-! ### Nat operations -/
theorem isNat_natSucc : {a : ℕ} → {a' c : ℕ} →
IsNat a a' → Nat.succ a' = c → IsNat (a.succ) c
| _, _,_, ⟨rfl⟩, rfl => ⟨by simp⟩
/-- The `norm_num` extension which identifies expressions of the form `Nat.succ a`,
such that `norm_num` successfully recognises `a`. -/
@[norm_num Nat.succ _] def evalNatSucc : NormNumExt where eval {u α} e := do
let .app f (a : Q(ℕ)) ← whnfR e | failure
guard <|← withNewMCtxDepth <| isDefEq f q(Nat.succ)
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q Nat.succ $a := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨na, pa⟩ ← deriveNat a sℕ
have nc : Q(ℕ) := mkRawNatLit (na.natLit!.succ)
haveI' : $nc =Q ($na).succ := ⟨⟩
return .isNat sℕ nc q(isNat_natSucc $pa (.refl $nc))
theorem isNat_natSub : {a b : ℕ} → {a' b' c : ℕ} →
IsNat a a' → IsNat b b' → Nat.sub a' b' = c → IsNat (a - b) c
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨by simp⟩
/-- The `norm_num` extension which identifies expressions of the form `Nat.sub a b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num (_ : ℕ) - _] def evalNatSub :
NormNumExt where eval {u α} e := do
let .app (.app f (a : Q(ℕ))) (b : Q(ℕ)) ← whnfR e | failure
-- We assert that the default instance for `HSub` is `Nat.sub` when the first parameter is `ℕ`.
guard <|← withNewMCtxDepth <| isDefEq f q(HSub.hSub (α := ℕ))
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q $a - $b := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨na, pa⟩ ← deriveNat a sℕ; let ⟨nb, pb⟩ ← deriveNat b sℕ
have nc : Q(ℕ) := mkRawNatLit (na.natLit! - nb.natLit!)
haveI' : Nat.sub $na $nb =Q $nc := ⟨⟩
return .isNat sℕ nc q(isNat_natSub $pa $pb (.refl $nc))
theorem isNat_natMod : {a b : ℕ} → {a' b' c : ℕ} →
IsNat a a' → IsNat b b' → Nat.mod a' b' = c → IsNat (a % b) c
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨by aesop⟩
/-- The `norm_num` extension which identifies expressions of the form `Nat.mod a b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num (_ : ℕ) % _] def evalNatMod :
NormNumExt where eval {u α} e := do
let .app (.app f (a : Q(ℕ))) (b : Q(ℕ)) ← whnfR e | failure
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q $a % $b := ⟨⟩
-- We assert that the default instance for `HMod` is `Nat.mod` when the first parameter is `ℕ`.
guard <|← withNewMCtxDepth <| isDefEq f q(HMod.hMod (α := ℕ))
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨na, pa⟩ ← deriveNat a sℕ; let ⟨nb, pb⟩ ← deriveNat b sℕ
have nc : Q(ℕ) := mkRawNatLit (na.natLit! % nb.natLit!)
haveI' : Nat.mod $na $nb =Q $nc := ⟨⟩
return .isNat sℕ nc q(isNat_natMod $pa $pb (.refl $nc))
theorem isNat_natDiv : {a b : ℕ} → {a' b' c : ℕ} →
IsNat a a' → IsNat b b' → Nat.div a' b' = c → IsNat (a / b) c
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨by aesop⟩
/-- The `norm_num` extension which identifies expressions of the form `Nat.div a b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num (_ : ℕ) / _]
def evalNatDiv : NormNumExt where eval {u α} e := do
let .app (.app f (a : Q(ℕ))) (b : Q(ℕ)) ← whnfR e | failure
haveI' : u =QL 0 := ⟨⟩; haveI' : $α =Q ℕ := ⟨⟩
haveI' : $e =Q $a / $b := ⟨⟩
-- We assert that the default instance for `HDiv` is `Nat.div` when the first parameter is `ℕ`.
guard <|← withNewMCtxDepth <| isDefEq f q(HDiv.hDiv (α := ℕ))
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨na, pa⟩ ← deriveNat a sℕ; let ⟨nb, pb⟩ ← deriveNat b sℕ
have nc : Q(ℕ) := mkRawNatLit (na.natLit! / nb.natLit!)
haveI' : Nat.div $na $nb =Q $nc := ⟨⟩
return .isNat sℕ nc q(isNat_natDiv $pa $pb (.refl $nc))
theorem isNat_dvd_true : {a b : ℕ} → {a' b' : ℕ} →
IsNat a a' → IsNat b b' → Nat.mod b' a' = nat_lit 0 → a ∣ b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, e => Nat.dvd_of_mod_eq_zero e
theorem isNat_dvd_false : {a b : ℕ} → {a' b' c : ℕ} →
IsNat a a' → IsNat b b' → Nat.mod b' a' = Nat.succ c → ¬a ∣ b
| _, _, _, _, c, ⟨rfl⟩, ⟨rfl⟩, e => mt Nat.mod_eq_zero_of_dvd (e.symm ▸ Nat.succ_ne_zero c :)
/-- The `norm_num` extension which identifies expressions of the form `(a : ℕ) | b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num (_ : ℕ) ∣ _] def evalNatDvd : NormNumExt where eval {u α} e := do
let .app (.app f (a : Q(ℕ))) (b : Q(ℕ)) ← whnfR e | failure
-- We assert that the default instance for `Dvd` is `Nat.dvd` when the first parameter is `ℕ`.
guard <|← withNewMCtxDepth <| isDefEq f q(Dvd.dvd (α := ℕ))
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨na, pa⟩ ← deriveNat a sℕ; let ⟨nb, pb⟩ ← deriveNat b sℕ
match nb.natLit! % na.natLit! with
| 0 =>
have : Q(Nat.mod $nb $na = nat_lit 0) := (q(Eq.refl (nat_lit 0)) : Expr)
return .isTrue q(isNat_dvd_true $pa $pb $this)
| c+1 =>
have nc : Q(ℕ) := mkRawNatLit c
have : Q(Nat.mod $nb $na = Nat.succ $nc) := (q(Eq.refl (Nat.succ $nc)) : Expr)
return .isFalse q(isNat_dvd_false $pa $pb $this)
end NormNum
end Meta
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/IsCoprime.lean | import Mathlib.RingTheory.Coprime.Lemmas
import Mathlib.Tactic.NormNum.GCD
/-! # `norm_num` extension for `IsCoprime`
This module defines a `norm_num` extension for `IsCoprime` over `ℤ`.
(While `IsCoprime` is defined over `ℕ`, since it uses Bezout's identity with `ℕ` coefficients
it does not correspond to the usual notion of coprime.)
-/
namespace Tactic
namespace NormNum
open Qq Lean Elab.Tactic Mathlib.Meta.NormNum
theorem int_not_isCoprime_helper (x y : ℤ) (d : ℕ) (hd : Int.gcd x y = d)
(h : Nat.beq d 1 = false) : ¬ IsCoprime x y := by
rw [Int.isCoprime_iff_gcd_eq_one, hd]
exact Nat.ne_of_beq_eq_false h
theorem isInt_isCoprime : {x y nx ny : ℤ} →
IsInt x nx → IsInt y ny → IsCoprime nx ny → IsCoprime x y
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => h
theorem isInt_not_isCoprime : {x y nx ny : ℤ} →
IsInt x nx → IsInt y ny → ¬ IsCoprime nx ny → ¬ IsCoprime x y
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => h
/-- Evaluates `IsCoprime` for the given integer number literals.
Panics if `ex` or `ey` aren't integer number literals. -/
def proveIntIsCoprime (ex ey : Q(ℤ)) : Q(IsCoprime $ex $ey) ⊕ Q(¬ IsCoprime $ex $ey) :=
let ⟨ed, pf⟩ := proveIntGCD ex ey
if ed.natLit! = 1 then
have pf' : Q(Int.gcd $ex $ey = 1) := pf
Sum.inl q(Int.isCoprime_iff_gcd_eq_one.mpr $pf')
else
have h : Q(Nat.beq $ed 1 = false) := (q(Eq.refl false) : Expr)
Sum.inr q(int_not_isCoprime_helper $ex $ey $ed $pf $h)
/-- Evaluates the `IsCoprime` predicate over `ℤ`. -/
@[norm_num IsCoprime (_ : ℤ) (_ : ℤ)]
def evalIntIsCoprime : NormNumExt where eval {_ _} e := do
let .app (.app _ (x : Q(ℤ))) (y : Q(ℤ)) ← Meta.whnfR e | failure
let ⟨ex, p⟩ ← deriveInt x _
let ⟨ey, q⟩ ← deriveInt y _
match proveIntIsCoprime ex ey with
| .inl pf =>
have pf' : Q(IsCoprime $x $y) := q(isInt_isCoprime $p $q $pf)
return .isTrue pf'
| .inr pf =>
have pf' : Q(¬ IsCoprime $x $y) := q(isInt_not_isCoprime $p $q $pf)
return .isFalse pf'
end NormNum
end Tactic |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/OfScientific.lean | import Mathlib.Tactic.NormNum.Basic
import Mathlib.Data.Rat.Cast.Lemmas
/-!
## `norm_num` plugin for scientific notation.
-/
namespace Mathlib
open Lean
open Meta
namespace Meta.NormNum
open Qq
variable {α : Type*}
-- see note [norm_num lemma function equality]
theorem isNNRat_ofScientific_of_true [DivisionRing α] :
{m e : ℕ} → {n : ℕ} → {d : ℕ} →
IsNNRat (mkRat m (10 ^ e) : α) n d → IsNNRat (OfScientific.ofScientific m true e : α) n d
| _, _, _, _, ⟨_, eq⟩ => ⟨‹_›, by
rwa [← Rat.cast_ofScientific, ← Rat.ofScientific_eq_ofScientific, Rat.ofScientific_true_def]⟩
-- see note [norm_num lemma function equality]
theorem isNat_ofScientific_of_false [DivisionRing α] : {m e nm ne n : ℕ} →
IsNat m nm → IsNat e ne → n = Nat.mul nm ((10 : ℕ) ^ ne) →
IsNat (OfScientific.ofScientific m false e : α) n
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => ⟨by
rw [← Rat.cast_ofScientific, ← Rat.ofScientific_eq_ofScientific]
simp only [Nat.cast_id, Rat.ofScientific_false_def, Nat.cast_mul, Nat.cast_pow,
Nat.cast_ofNat, h, Nat.mul_eq]
norm_cast⟩
/-- The `norm_num` extension which identifies expressions in scientific notation, normalizing them
to rat casts if the scientific notation is inherited from the one for rationals. -/
@[norm_num OfScientific.ofScientific _ _ _] def evalOfScientific :
NormNumExt where eval {u α} e := do
let .app (.app (.app f (m : Q(ℕ))) (b : Q(Bool))) (exp : Q(ℕ)) ← whnfR e | failure
let dα ← inferDivisionRing α
guard <|← withNewMCtxDepth <| isDefEq f q(OfScientific.ofScientific (α := $α))
assumeInstancesCommute
haveI' : $e =Q OfScientific.ofScientific $m $b $exp := ⟨⟩
match b with
| ~q(true) =>
let rme ← derive (q(mkRat $m (10 ^ $exp)) : Q($α))
let some ⟨q, n, d, p⟩ := rme.toNNRat' q(DivisionRing.toDivisionSemiring) | failure
return .isNNRat q(DivisionRing.toDivisionSemiring) q n d q(isNNRat_ofScientific_of_true $p)
| ~q(false) =>
let ⟨nm, pm⟩ ← deriveNat m q(AddCommMonoidWithOne.toAddMonoidWithOne)
let ⟨ne, pe⟩ ← deriveNat exp q(AddCommMonoidWithOne.toAddMonoidWithOne)
have pm : Q(IsNat $m $nm) := pm
have pe : Q(IsNat $exp $ne) := pe
let m' := nm.natLit!
let exp' := ne.natLit!
let n' := Nat.mul m' (Nat.pow (10 : ℕ) exp')
have n : Q(ℕ) := mkRawNatLit n'
haveI : $n =Q Nat.mul $nm ((10 : ℕ) ^ $ne) := ⟨⟩
return .isNat _ n q(isNat_ofScientific_of_false $pm $pe (.refl $n))
end NormNum
end Meta
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Result.lean | import Mathlib.Algebra.Field.Defs
import Mathlib.Algebra.GroupWithZero.Invertible
import Mathlib.Data.Sigma.Basic
import Mathlib.Algebra.Ring.Nat
import Mathlib.Data.Int.Cast.Basic
import Qq.MetaM
/-!
## The `Result` type for `norm_num`
We set up predicates `IsNat`, `IsInt`, and `IsRat`,
stating that an element of a ring is equal to the "normal form" of a natural number, integer,
or rational number coerced into that ring.
We then define `Result e`, which contains a proof that a typed expression `e : Q($α)`
is equal to the coercion of an explicit natural number, integer, or rational number,
or is either `true` or `false`.
-/
universe u
variable {α : Type u}
open Lean
open Lean.Meta Qq Lean.Elab Term
namespace Mathlib
namespace Meta.NormNum
variable {u : Level}
/-- A shortcut (non)instance for `AddMonoidWithOne ℕ` to shrink generated proofs. -/
def instAddMonoidWithOneNat : AddMonoidWithOne ℕ := inferInstance
/-- A shortcut (non)instance for `AddMonoidWithOne α`
from `Semiring α` to shrink generated proofs. -/
def instAddMonoidWithOne' {α : Type u} [Semiring α] : AddMonoidWithOne α := inferInstance
/-- A shortcut (non)instance for `AddMonoidWithOne α` from `Ring α` to shrink generated proofs. -/
def instAddMonoidWithOne {α : Type u} [Ring α] : AddMonoidWithOne α := inferInstance
/-- A shortcut (non)instance for `Nat.AtLeastTwo (n + 2)` to shrink generated proofs. -/
lemma instAtLeastTwo (n : ℕ) : Nat.AtLeastTwo (n + 2) := inferInstance
/-- Helper function to synthesize a typed `AddMonoidWithOne α` expression. -/
def inferAddMonoidWithOne (α : Q(Type u)) : MetaM Q(AddMonoidWithOne $α) :=
return ← synthInstanceQ q(AddMonoidWithOne $α) <|>
throwError "not an AddMonoidWithOne"
/-- Helper function to synthesize a typed `Semiring α` expression. -/
def inferSemiring (α : Q(Type u)) : MetaM Q(Semiring $α) :=
return ← synthInstanceQ q(Semiring $α) <|> throwError "not a semiring"
/-- Helper function to synthesize a typed `Ring α` expression. -/
def inferRing (α : Q(Type u)) : MetaM Q(Ring $α) :=
return ← synthInstanceQ q(Ring $α) <|> throwError "not a ring"
/--
Represent an integer as a "raw" typed expression.
This uses `.lit (.natVal n)` internally to represent a natural number,
rather than the preferred `OfNat.ofNat` form.
We use this internally to avoid unnecessary typeclass searches.
This function is the inverse of `Expr.intLit!`.
-/
def mkRawIntLit (n : ℤ) : Q(ℤ) :=
let lit : Q(ℕ) := mkRawNatLit n.natAbs
if 0 ≤ n then q(.ofNat $lit) else q(.negOfNat $lit)
/--
Represent an integer as a "raw" typed expression.
This `.lit (.natVal n)` internally to represent a natural number,
rather than the preferred `OfNat.ofNat` form.
We use this internally to avoid unnecessary typeclass searches.
-/
def mkRawRatLit (q : ℚ) : Q(ℚ) :=
let nlit : Q(ℤ) := mkRawIntLit q.num
let dlit : Q(ℕ) := mkRawNatLit q.den
q(mkRat $nlit $dlit)
/-- Extract the raw natlit representing the absolute value of a raw integer literal
(of the type produced by `Mathlib.Meta.NormNum.mkRawIntLit`) along with an equality proof. -/
def rawIntLitNatAbs (n : Q(ℤ)) : (m : Q(ℕ)) × Q(Int.natAbs $n = $m) :=
if n.isAppOfArity ``Int.ofNat 1 then
have m : Q(ℕ) := n.appArg!
⟨m, show Q(Int.natAbs (Int.ofNat $m) = $m) from q(Int.natAbs_natCast $m)⟩
else if n.isAppOfArity ``Int.negOfNat 1 then
have m : Q(ℕ) := n.appArg!
⟨m, show Q(Int.natAbs (Int.negOfNat $m) = $m) from q(Int.natAbs_neg $m)⟩
else
panic! "not a raw integer literal"
/--
Constructs an `ofNat` application `a'` with the canonical instance, together with a proof that
the instance is equal to the result of `Nat.cast` on the given `AddMonoidWithOne` instance.
This function is performance-critical, as many higher level tactics have to construct numerals.
So rather than using typeclass search we hardcode the (relatively small) set of solutions
to the typeclass problem.
-/
def mkOfNat (α : Q(Type u)) (_sα : Q(AddMonoidWithOne $α)) (lit : Q(ℕ)) :
MetaM ((a' : Q($α)) × Q($lit = $a')) := do
if α.isConstOf ``Nat then
let a' : Q(ℕ) := q(OfNat.ofNat $lit : ℕ)
pure ⟨a', (q(Eq.refl $a') : Expr)⟩
else if α.isConstOf ``Int then
let a' : Q(ℤ) := q(OfNat.ofNat $lit : ℤ)
pure ⟨a', (q(Eq.refl $a') : Expr)⟩
else if α.isConstOf ``Rat then
let a' : Q(ℚ) := q(OfNat.ofNat $lit : ℚ)
pure ⟨a', (q(Eq.refl $a') : Expr)⟩
else
let some n := lit.rawNatLit? | failure
match n with
| 0 => pure ⟨q(0 : $α), (q(Nat.cast_zero (R := $α)) : Expr)⟩
| 1 => pure ⟨q(1 : $α), (q(Nat.cast_one (R := $α)) : Expr)⟩
| k+2 =>
let k : Q(ℕ) := mkRawNatLit k
let _x : Q(Nat.AtLeastTwo $lit) :=
(q(instAtLeastTwo $k) : Expr)
let a' : Q($α) := q(OfNat.ofNat $lit)
pure ⟨a', (q(Eq.refl $a') : Expr)⟩
/-- Assert that an element of a semiring is equal to the coercion of some natural number. -/
structure IsNat {α : Type u} [AddMonoidWithOne α] (a : α) (n : ℕ) : Prop where
/-- The element is equal to the coercion of the natural number. -/
out : a = n
theorem IsNat.raw_refl (n : ℕ) : IsNat n n := ⟨rfl⟩
/--
A "raw nat cast" is an expression of the form `(Nat.rawCast lit : α)` where `lit` is a raw
natural number literal. These expressions are used by tactics like `ring` to decrease the number
of typeclass arguments required in each use of a number literal at type `α`.
-/
@[simp] def _root_.Nat.rawCast {α : Type u} [AddMonoidWithOne α] (n : ℕ) : α := n
theorem IsNat.to_eq {α : Type u} [AddMonoidWithOne α] {n} : {a a' : α} → IsNat a n → n = a' → a = a'
| _, _, ⟨rfl⟩, rfl => rfl
theorem IsNat.to_raw_eq {a : α} {n : ℕ} [AddMonoidWithOne α] : IsNat (a : α) n → a = n.rawCast
| ⟨e⟩ => e
theorem IsNat.of_raw (α) [AddMonoidWithOne α] (n : ℕ) : IsNat (n.rawCast : α) n := ⟨rfl⟩
@[elab_as_elim]
theorem isNat.natElim {p : ℕ → Prop} : {n : ℕ} → {n' : ℕ} → IsNat n n' → p n' → p n
| _, _, ⟨rfl⟩, h => h
/-- Assert that an element of a ring is equal to the coercion of some integer. -/
structure IsInt [Ring α] (a : α) (n : ℤ) : Prop where
/-- The element is equal to the coercion of the integer. -/
out : a = n
/--
A "raw int cast" is an expression of the form:
* `(Nat.rawCast lit : α)` where `lit` is a raw natural number literal
* `(Int.rawCast (Int.negOfNat lit) : α)` where `lit` is a nonzero raw natural number literal
(That is, we only actually use this function for negative integers.) This representation is used by
tactics like `ring` to decrease the number of typeclass arguments required in each use of a number
literal at type `α`.
-/
@[simp] def _root_.Int.rawCast [Ring α] (n : ℤ) : α := n
theorem IsInt.to_isNat {α} [Ring α] : ∀ {a : α} {n}, IsInt a (.ofNat n) → IsNat a n
| _, _, ⟨rfl⟩ => ⟨by simp⟩
theorem IsNat.to_isInt {α} [Ring α] : ∀ {a : α} {n}, IsNat a n → IsInt a (.ofNat n)
| _, _, ⟨rfl⟩ => ⟨by simp⟩
theorem IsInt.to_raw_eq {a : α} {n : ℤ} [Ring α] : IsInt (a : α) n → a = n.rawCast
| ⟨e⟩ => e
theorem IsInt.of_raw (α) [Ring α] (n : ℤ) : IsInt (n.rawCast : α) n := ⟨rfl⟩
theorem IsInt.neg_to_eq {α} [Ring α] {n} :
{a a' : α} → IsInt a (.negOfNat n) → n = a' → a = -a'
| _, _, ⟨rfl⟩, rfl => by simp [Int.negOfNat_eq, Int.cast_neg]
theorem IsInt.nonneg_to_eq {α} [Ring α] {n}
{a a' : α} (h : IsInt a (.ofNat n)) (e : n = a') : a = a' := h.to_isNat.to_eq e
/--
Assert that an element of a ring is equal to `num / denom`
(and `denom` is invertible so that this makes sense).
We will usually also have `num` and `denom` coprime,
although this is not part of the definition.
-/
inductive IsRat [Ring α] (a : α) (num : ℤ) (denom : ℕ) : Prop
| mk (inv : Invertible (denom : α)) (eq : a = num * ⅟(denom : α))
/--
Assert that an element of a semiring is equal to `num / denom`
(and `denom` is invertible so that this makes sense).
We will usually also have `num` and `denom` coprime,
although this is not part of the definition.
-/
inductive IsNNRat [Semiring α] (a : α) (num : ℕ) (denom : ℕ) : Prop
| mk (inv : Invertible (denom : α)) (eq : a = num * ⅟(denom : α))
/--
A "raw nnrat cast" is an expression of the form:
* `(Nat.rawCast lit : α)` where `lit` is a raw natural number literal
* `(NNRat.rawCast n d : α)` where `n` is a raw nat literal, `d` is a raw nat literal, and `d` is not
`1` or `0`.
This representation is used by tactics like `ring` to decrease the number of typeclass arguments
required in each use of a number literal at type `α`.
-/
@[simp]
def _root_.NNRat.rawCast [DivisionSemiring α] (n : ℕ) (d : ℕ) : α := n / d
/--
A "raw rat cast" is an expression of the form:
* `(Nat.rawCast lit : α)` where `lit` is a raw natural number literal
* `(Int.rawCast (Int.negOfNat lit) : α)` where `lit` is a nonzero raw natural number literal
* `(NNRat.rawCast n d : α)` where `n` is a raw nat literal, `d` is a raw nat literal, and `d` is not
`1` or `0`.
* `(Rat.rawCast (Int.negOfNat n) d : α)` where `n` is a raw nat literal,
`d` is a raw nat literal, `n` is not `0`, and `d` is not `1` or `0`.
This representation is used by tactics like `ring` to decrease the number of typeclass arguments
required in each use of a number literal at type `α`.
-/
@[simp]
def _root_.Rat.rawCast [DivisionRing α] (n : ℤ) (d : ℕ) : α := n / d
theorem IsNNRat.to_isNat {α} [Semiring α] : ∀ {a : α} {n}, IsNNRat a (n) (nat_lit 1) → IsNat a n
| _, num, ⟨inv, rfl⟩ => have := @invertibleOne α _; ⟨by simp⟩
theorem IsRat.to_isNNRat {α} [Ring α] : ∀ {a : α} {n d}, IsRat a (.ofNat n) (d) → IsNNRat a n d
| _, _, _, ⟨inv, rfl⟩ => ⟨inv, by simp⟩
theorem IsNat.to_isNNRat {α} [Semiring α] : ∀ {a : α} {n}, IsNat a n → IsNNRat a (n) (nat_lit 1)
| _, _, ⟨rfl⟩ => ⟨⟨1, by simp, by simp⟩, by simp⟩
theorem IsNNRat.to_isRat {α} [Ring α] : ∀ {a : α} {n d}, IsNNRat a n d → IsRat a (.ofNat n) d
| _, _, _, ⟨inv, rfl⟩ => ⟨inv, by simp⟩
theorem IsRat.to_isInt {α} [Ring α] : ∀ {a : α} {n}, IsRat a n (nat_lit 1) → IsInt a n
| _, _, ⟨inv, rfl⟩ => have := @invertibleOne α _; ⟨by simp⟩
theorem IsInt.to_isRat {α} [Ring α] : ∀ {a : α} {n}, IsInt a n → IsRat a n (nat_lit 1)
| _, _, ⟨rfl⟩ => ⟨⟨1, by simp, by simp⟩, by simp⟩
theorem IsNNRat.to_raw_eq {n d : ℕ} [DivisionSemiring α] :
∀ {a}, IsNNRat (a : α) n d → a = NNRat.rawCast n d
| _, ⟨inv, rfl⟩ => by simp [div_eq_mul_inv]
theorem IsRat.to_raw_eq {n : ℤ} {d : ℕ} [DivisionRing α] :
∀ {a}, IsRat (a : α) n d → a = Rat.rawCast n d
| _, ⟨inv, rfl⟩ => by simp [div_eq_mul_inv]
theorem IsRat.neg_to_eq {α} [DivisionRing α] {n d} :
{a n' d' : α} → IsRat a (.negOfNat n) d → n = n' → d = d' → a = -(n' / d')
| _, _, _, ⟨_, rfl⟩, rfl, rfl => by simp [div_eq_mul_inv]
theorem IsNNRat.to_eq {α} [DivisionSemiring α] {n d} :
{a n' d' : α} → IsNNRat a n d → n = n' → d = d' → a = n' / d'
| _, _, _, ⟨_, rfl⟩, rfl, rfl => by simp [div_eq_mul_inv]
theorem IsNNRat.of_raw (α) [DivisionSemiring α] (n : ℕ) (d : ℕ)
(h : (d : α) ≠ 0) : IsNNRat (NNRat.rawCast n d : α) n d :=
have := invertibleOfNonzero h
⟨this, by simp [div_eq_mul_inv]⟩
theorem IsRat.of_raw (α) [DivisionRing α] (n : ℤ) (d : ℕ)
(h : (d : α) ≠ 0) : IsRat (Rat.rawCast n d : α) n d :=
have := invertibleOfNonzero h
⟨this, by simp [div_eq_mul_inv]⟩
theorem IsNNRat.den_nz {α} [DivisionSemiring α] {a n d} : IsNNRat (a : α) n d → (d : α) ≠ 0
| ⟨_, _⟩ => Invertible.ne_zero (d : α)
theorem IsRat.den_nz {α} [DivisionRing α] {a n d} : IsRat (a : α) n d → (d : α) ≠ 0
| ⟨_, _⟩ => Invertible.ne_zero (d : α)
/-- The result of `norm_num` running on an expression `x` of type `α`.
Untyped version of `Result`. -/
inductive Result' where
/-- Untyped version of `Result.isBool`. -/
| isBool (val : Bool) (proof : Expr)
/-- Untyped version of `Result.isNat`. -/
| isNat (inst lit proof : Expr)
/-- Untyped version of `Result.isNegNat`. -/
| isNegNat (inst lit proof : Expr)
/-- Untyped version of `Result.isNNRat`. -/
| isNNRat (inst : Expr) (q : Rat) (n d proof : Expr)
/-- Untyped version of `Result.isNegNNRat`. -/
| isNegNNRat (inst : Expr) (q : Rat) (n d proof : Expr)
deriving Inhabited
section
set_option linter.unusedVariables false
/-- The result of `norm_num` running on an expression `x` of type `α`. -/
@[nolint unusedArguments] def Result {α : Q(Type u)} (x : Q($α)) := Result'
instance {α : Q(Type u)} {x : Q($α)} : Inhabited (Result x) := inferInstanceAs (Inhabited Result')
/-- The result is `proof : x`, where `x` is a (true) proposition. -/
@[match_pattern, inline] def Result.isTrue {x : Q(Prop)} :
∀ (proof : Q($x)), Result q($x) := Result'.isBool true
/-- The result is `proof : ¬x`, where `x` is a (false) proposition. -/
@[match_pattern, inline] def Result.isFalse {x : Q(Prop)} :
∀ (proof : Q(¬$x)), Result q($x) := Result'.isBool false
/-- The result is `lit : ℕ` (a raw nat literal) and `proof : isNat x lit`. -/
@[match_pattern, inline] def Result.isNat {α : Q(Type u)} {x : Q($α)} :
∀ (inst : Q(AddMonoidWithOne $α) := by assumption) (lit : Q(ℕ)) (proof : Q(IsNat $x $lit)),
Result x := Result'.isNat
/-- The result is `-lit` where `lit` is a raw nat literal
and `proof : isInt x (.negOfNat lit)`. -/
@[match_pattern, inline] def Result.isNegNat {α : Q(Type u)} {x : Q($α)} :
∀ (inst : Q(Ring $α) := by assumption) (lit : Q(ℕ)) (proof : Q(IsInt $x (.negOfNat $lit))),
Result x := Result'.isNegNat
/-- The result is `proof : IsNNRat x n d`,
where `n` a raw nat literal, `d` is a raw nat literal (not 0 or 1),
`n` and `d` are coprime, and `q` is the value of `n / d`. -/
@[match_pattern, inline] def Result.isNNRat {α : Q(Type u)} {x : Q($α)} :
∀ (inst : Q(DivisionSemiring $α) := by assumption) (q : Rat) (n : Q(ℕ)) (d : Q(ℕ))
(proof : Q(IsNNRat $x $n $d)), Result x := Result'.isNNRat
/-- The result is `proof : IsRat x n d`,
where `n` is `.negOfNat lit` with `lit` a raw nat literal,
`d` is a raw nat literal (not 0 or 1),
`n` and `d` are coprime, and `q` is the value of `n / d`. -/
@[match_pattern, inline] def Result.isNegNNRat {α : Q(Type u)} {x : Q($α)} :
∀ (inst : Q(DivisionRing $α) := by assumption) (q : Rat) (n : Q(ℕ)) (d : Q(ℕ))
(proof : Q(IsRat $x (.negOfNat $n) $d)), Result x := Result'.isNegNNRat
end
/-- The result is `z : ℤ` and `proof : isNat x z`. -/
-- Note the independent arguments `z : Q(ℤ)` and `n : ℤ`.
-- We ensure these are "the same" when calling.
def Result.isInt {α : Q(Type u)} {x : Q($α)} (inst : Q(Ring $α) := by assumption)
(z : Q(ℤ)) (n : ℤ) (proof : Q(IsInt $x $z)) : Result x :=
have lit : Q(ℕ) := z.appArg!
if 0 ≤ n then
let proof : Q(IsInt $x (.ofNat $lit)) := proof
.isNat q(instAddMonoidWithOne) lit q(IsInt.to_isNat $proof)
else
.isNegNat inst lit proof
/-- The result is `q : NNRat` and `proof : isNNRat x q`. -/
-- Note the independent arguments `q : Q(ℚ)` and `n : ℚ`.
-- We ensure these are "the same" when calling.
def Result.isNNRat' {α : Q(Type u)} {x : Q($α)} (inst : Q(DivisionSemiring $α) := by assumption)
(q : Rat) (n : Q(ℕ)) (d : Q(ℕ)) (proof : Q(IsNNRat $x $n $d)) : Result x :=
if q.den = 1 then
haveI : nat_lit 1 =Q $d := ⟨⟩
.isNat q(instAddMonoidWithOne') n q(IsNNRat.to_isNat $proof)
else
.isNNRat inst q n d proof
/-- The result is `q : ℚ` and `proof : isRat x q`. -/
-- Note the independent arguments `q : Q(ℚ)` and `n : ℚ`.
-- We ensure these are "the same" when calling.
def Result.isRat {α : Q(Type u)} {x : Q($α)} (inst : Q(DivisionRing $α) := by assumption)
(q : ℚ) (n : Q(ℤ)) (d : Q(ℕ)) (proof : Q(IsRat $x $n $d)) : Result x :=
have lit : Q(ℕ) := n.appArg!
if q.den = 1 then
have proof : Q(IsRat $x $n (nat_lit 1)) := proof
.isInt q(DivisionRing.toRing) n q.num q(IsRat.to_isInt $proof)
else if 0 ≤ q then
let proof : Q(IsRat $x (.ofNat $lit) $d) := proof
.isNNRat q(DivisionRing.toDivisionSemiring) q lit d q(IsRat.to_isNNRat $proof)
else
.isNegNNRat inst q lit d proof
instance {α : Q(Type u)} {x : Q($α)} : ToMessageData (Result x) where
toMessageData
| .isBool true proof => m!"isTrue ({proof})"
| .isBool false proof => m!"isFalse ({proof})"
| .isNat _ lit proof => m!"isNat {lit} ({proof})"
| .isNegNat _ lit proof => m!"isNegNat {lit} ({proof})"
| .isNNRat _ q _ _ proof => m!"isNNRat {q} ({proof})"
| .isNegNNRat _ q _ _ proof => m!"isNegNNRat {q} ({proof})"
/-- Returns the rational number that is the result of `norm_num` evaluation. -/
def Result.toRat {α : Q(Type u)} {e : Q($α)} : Result e → Option Rat
| .isBool .. => none
| .isNat _ lit _ => some lit.natLit!
| .isNegNat _ lit _ => some (-lit.natLit!)
| .isNNRat _ q .. => some q
| .isNegNNRat _ q .. => some q
/-- Returns the rational number that is the result of `norm_num` evaluation, along with a proof
that the denominator is nonzero in the `isRat` case. -/
def Result.toRatNZ {α : Q(Type u)} {e : Q($α)} : Result e → Option (Rat × Option Expr)
| .isBool .. => none
| .isNat _ lit _ => some (lit.natLit!, none)
| .isNegNat _ lit _ => some (-lit.natLit!, none)
| .isNNRat _ q _ _ p => some (q, q(IsNNRat.den_nz $p))
| .isNegNNRat _ q _ _ p => some (q, q(IsRat.den_nz $p))
/--
Extract from a `Result` the integer value (as both a term and an expression),
and the proof that the original expression is equal to this integer.
-/
def Result.toInt {α : Q(Type u)} {e : Q($α)} (_i : Q(Ring $α) := by with_reducible assumption) :
Result e → Option (ℤ × (lit : Q(ℤ)) × Q(IsInt $e $lit))
| .isNat _ lit proof => do
have proof : Q(@IsNat _ instAddMonoidWithOne $e $lit) := proof
pure ⟨lit.natLit!, q(.ofNat $lit), q(($proof).to_isInt)⟩
| .isNegNat _ lit proof => pure ⟨-lit.natLit!, q(.negOfNat $lit), proof⟩
| _ => failure
/--
Extract from a `Result` the rational value (as both a term and an expression),
and the proof that the original expression is equal to this rational number.
-/
def Result.toNNRat' {α : Q(Type u)} {e : Q($α)}
(_i : Q(DivisionSemiring $α) := by with_reducible assumption) :
Result e → Option (Rat × (n : Q(ℕ)) × (d : Q(ℕ)) × Q(IsNNRat $e $n $d))
| .isNat _ lit proof =>
have proof : Q(@IsNat _ instAddMonoidWithOne' $e $lit) := proof
some ⟨lit.natLit!, q($lit), q(nat_lit 1), q(($proof).to_isNNRat)⟩
| .isNNRat _ q n d proof => some ⟨q, n, d, proof⟩
| _ => none
/--
Extract from a `Result` the rational value (as both a term and an expression),
and the proof that the original expression is equal to this rational number.
-/
def Result.toRat' {α : Q(Type u)} {e : Q($α)}
(_i : Q(DivisionRing $α) := by with_reducible assumption) :
Result e → Option (ℚ × (n : Q(ℤ)) × (d : Q(ℕ)) × Q(IsRat $e $n $d))
| .isBool .. => none
| .isNat _ lit proof =>
have proof : Q(@IsNat _ instAddMonoidWithOne $e $lit) := proof
some ⟨lit.natLit!, q(.ofNat $lit), q(nat_lit 1), q(($proof).to_isNNRat.to_isRat)⟩
| .isNegNat _ lit proof =>
have proof : Q(@IsInt _ DivisionRing.toRing $e (.negOfNat $lit)) := proof
some ⟨-lit.natLit!, q(.negOfNat $lit), q(nat_lit 1),
q(@IsInt.to_isRat _ DivisionRing.toRing _ _ $proof)⟩
| .isNNRat inst q n d proof =>
letI : $inst =Q DivisionRing.toDivisionSemiring := ⟨⟩
some ⟨q, q(.ofNat $n), d, q(IsNNRat.to_isRat $proof)⟩
| .isNegNNRat _ q n d proof => some ⟨q, q(.negOfNat $n), d, proof⟩
/--
Given a `NormNum.Result e` (which uses `IsNat`, `IsInt`, `IsRat` to express equality to a rational
numeral), converts it to an equality `e = Nat.rawCast n`, `e = Int.rawCast n`, or
`e = Rat.rawCast n d` to a raw cast expression, so it can be used for rewriting.
-/
def Result.toRawEq {α : Q(Type u)} {e : Q($α)} : Result e → (e' : Q($α)) × Q($e = $e')
| .isBool false p =>
have e : Q(Prop) := e; have p : Q(¬$e) := p
⟨(q(False) : Expr), (q(eq_false $p) : Expr)⟩
| .isBool true p =>
have e : Q(Prop) := e; have p : Q($e) := p
⟨(q(True) : Expr), (q(eq_true $p) : Expr)⟩
| .isNat _ lit p => ⟨q(Nat.rawCast $lit), q(IsNat.to_raw_eq $p)⟩
| .isNegNat _ lit p => ⟨q(Int.rawCast (.negOfNat $lit)), q(IsInt.to_raw_eq $p)⟩
| .isNNRat _ _ n d p => ⟨q(NNRat.rawCast $n $d), q(IsNNRat.to_raw_eq $p)⟩
| .isNegNNRat _ _ n d p => ⟨q(Rat.rawCast (.negOfNat $n) $d), q(IsRat.to_raw_eq $p)⟩
/--
`Result.toRawEq` but providing an integer. Given a `NormNum.Result e` for something known to be an
integer (which uses `IsNat` or `IsInt` to express equality to an integer numeral), converts it to
an equality `e = Nat.rawCast n` or `e = Int.rawCast n` to a raw cast expression, so it can be used
for rewriting. Gives `none` if not an integer.
-/
def Result.toRawIntEq {α : Q(Type u)} {e : Q($α)} : Result e →
Option (ℤ × (e' : Q($α)) × Q($e = $e'))
| .isNat _ lit p => some ⟨lit.natLit!, q(Nat.rawCast $lit), q(IsNat.to_raw_eq $p)⟩
| .isNegNat _ lit p => some ⟨-lit.natLit!, q(Int.rawCast (.negOfNat $lit)), q(IsInt.to_raw_eq $p)⟩
| .isNNRat _ .. | .isNegNNRat _ .. | .isBool .. => none
/-- Constructs a `Result` out of a raw nat cast. Assumes `e` is a raw nat cast expression. -/
def Result.ofRawNat {α : Q(Type u)} (e : Q($α)) : Result e := Id.run do
let .app (.app _ (sα : Q(AddMonoidWithOne $α))) (lit : Q(ℕ)) := e | panic! "not a raw nat cast"
.isNat sα lit (q(IsNat.of_raw $α $lit) : Expr)
/-- Constructs a `Result` out of a raw int cast.
Assumes `e` is a raw int cast expression denoting `n`. -/
def Result.ofRawInt {α : Q(Type u)} (n : ℤ) (e : Q($α)) : Result e :=
if 0 ≤ n then
Result.ofRawNat e
else Id.run do
let .app (.app _ (rα : Q(Ring $α))) (.app _ (lit : Q(ℕ))) := e | panic! "not a raw int cast"
.isNegNat rα lit (q(IsInt.of_raw $α (.negOfNat $lit)) : Expr)
/-- Constructs a `Result` out of a raw rat cast.
Assumes `e` is a raw rat cast expression denoting `n`. -/
def Result.ofRawNNRat
{α : Q(Type u)} (q : ℚ) (e : Q($α)) (hyp : Option Expr := none) : Result e :=
if q.den = 1 then
Result.ofRawNat e
else Id.run do
let .app (.app (.app _ (dα : Q(DivisionSemiring $α))) (n : Q(ℕ))) (d : Q(ℕ)) := e
| panic! "not a raw nnrat cast"
let hyp : Q(($d : $α) ≠ 0) := hyp.get!
.isNNRat dα q n d (q(IsNNRat.of_raw $α $n $d $hyp) : Expr)
/-- Constructs a `Result` out of a raw rat cast.
Assumes `e` is a raw rat cast expression denoting `n`. -/
def Result.ofRawRat {α : Q(Type u)} (q : ℚ) (e : Q($α)) (hyp : Option Expr := none) : Result e :=
if q.den = 1 then
Result.ofRawInt q.num e
else if 0 ≤ q then
Result.ofRawNNRat q e hyp
else Id.run do
let .app (.app (.app _ (dα : Q(DivisionRing $α))) (.app _ (n : Q(ℕ)))) (d : Q(ℕ)) := e
| panic! "not a raw rat cast"
let hyp : Q(($d : $α) ≠ 0) := hyp.get!
.isNegNNRat dα q n d (q(IsRat.of_raw $α (.negOfNat $n) $d $hyp) : Expr)
/-- Convert a `Result` to a `Simp.Result`. -/
def Result.toSimpResult {α : Q(Type u)} {e : Q($α)} : Result e → MetaM Simp.Result
| r@(.isBool ..) => let ⟨expr, proof?⟩ := r.toRawEq; pure { expr, proof? }
| .isNat sα lit p => do
let ⟨a', pa'⟩ ← mkOfNat α sα lit
return { expr := a', proof? := q(IsNat.to_eq $p $pa') }
| .isNegNat _rα lit p => do
let ⟨a', pa'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) lit
return { expr := q(-$a'), proof? := q(IsInt.neg_to_eq $p $pa') }
| .isNNRat _ _ n d p => do
let ⟨n', pn'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) n
let ⟨d', pd'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) d
return { expr := q($n' / $d'), proof? := q(IsNNRat.to_eq $p $pn' $pd') }
| .isNegNNRat _ _ n d p => do
let ⟨n', pn'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) n
let ⟨d', pd'⟩ ← mkOfNat α q(AddCommMonoidWithOne.toAddMonoidWithOne) d
return { expr := q(-($n' / $d')), proof? := q(IsRat.neg_to_eq $p $pn' $pd') }
/-- Given `Mathlib.Meta.NormNum.Result.isBool p b`, this is the type of `p`.
Note that `BoolResult p b` is definitionally equal to `Expr`, and if you write `match b with ...`,
then in the `true` branch `BoolResult p true` is reducibly equal to `Q($p)` and
in the `false` branch it is reducibly equal to `Q(¬ $p)`. -/
abbrev BoolResult (p : Q(Prop)) (b : Bool) : Type :=
Q(Bool.rec (¬ $p) ($p) $b)
/-- Obtain a `Result` from a `BoolResult`. -/
def Result.ofBoolResult {p : Q(Prop)} {b : Bool} (prf : BoolResult p b) : Result q(Prop) :=
Result'.isBool b prf
/-- If `a = b` and we can evaluate `b`, then we can evaluate `a`. -/
def Result.eqTrans {α : Q(Type u)} {a b : Q($α)} (eq : Q($a = $b)) : Result b → Result a
| .isBool true proof =>
have a : Q(Prop) := a
have b : Q(Prop) := b
have eq : Q($a = $b) := eq
have proof : Q($b) := proof
Result.isTrue (x := a) q($eq ▸ $proof)
| .isBool false proof =>
have a : Q(Prop) := a
have b : Q(Prop) := b
have eq : Q($a = $b) := eq
have proof : Q(¬ $b) := proof
Result.isFalse (x := a) q($eq ▸ $proof)
| .isNat inst lit proof => Result.isNat inst lit q($eq ▸ $proof)
| .isNegNat inst lit proof => Result.isNegNat inst lit q($eq ▸ $proof)
| .isNNRat inst q n d proof => Result.isNNRat inst q n d q($eq ▸ $proof)
| .isNegNNRat inst q n d proof => Result.isNegNNRat inst q n d q($eq ▸ $proof)
end Meta.NormNum
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Ordinal.lean | import Mathlib.SetTheory.Ordinal.Exponential
import Mathlib.Tactic.NormNum.Basic
/-!
# `norm_num` extensions for Ordinals
The default `norm_num` extensions for many operators requires a semiring,
which without a right distributive law, ordinals do not have.
We must therefore define new extensions for them.
-/
namespace Mathlib.Meta.NormNum
open Lean Lean.Meta Qq Ordinal
/- The `guard_msgs` in this file are for checking whether the current default extensions have been
updated and the extensions in this file are no longer needed. -/
/-- info: 12 * 5 -/
#guard_msgs in
#norm_num (12 : Ordinal.{0}) * (5 : Ordinal.{0})
lemma isNat_ordinalMul.{u} : ∀ {a b : Ordinal.{u}} {an bn rn : ℕ},
IsNat a an → IsNat b bn → an * bn = rn → IsNat (a * b) rn
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨Eq.symm <| natCast_mul ..⟩
/-- The `norm_num` extension for multiplication on ordinals. -/
@[norm_num (_ : Ordinal) * (_ : Ordinal)]
def evalOrdinalMul : NormNumExt where
eval {u α} e := do
let some u' := u.dec | throwError "level is not succ"
haveI' : u =QL u' + 1 := ⟨⟩
match α, e with
| ~q(Ordinal.{u'}), ~q(($a : Ordinal) * ($b : Ordinal)) =>
let i : Q(AddMonoidWithOne Ordinal.{u'}) := q(inferInstance)
let ⟨an, pa⟩ ← deriveNat a i
let ⟨bn, pb⟩ ← deriveNat b i
have rn : Q(ℕ) := mkRawNatLit (an.natLit! * bn.natLit!)
have : ($an * $bn) =Q $rn := ⟨⟩
pure (.isNat i rn q(isNat_ordinalMul $pa $pb (.refl $rn)))
| _, _ => throwError "not multiplication on ordinals"
/-- info: 5 ≤ 12 -/
#guard_msgs in
#norm_num (5 : Ordinal.{0}) ≤ 12
/-- info: 5 < 12 -/
#guard_msgs in
#norm_num (5 : Ordinal.{0}) < 12
lemma isNat_ordinalLE_true.{u} : ∀ {a b : Ordinal.{u}} {an bn : ℕ},
IsNat a an → IsNat b bn → decide (an ≤ bn) = true → a ≤ b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Nat.cast_le.mpr <| of_decide_eq_true h
lemma isNat_ordinalLE_false.{u} : ∀ {a b : Ordinal.{u}} {an bn : ℕ},
IsNat a an → IsNat b bn → decide (an ≤ bn) = false → ¬a ≤ b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => not_iff_not.mpr Nat.cast_le |>.mpr <| of_decide_eq_false h
lemma isNat_ordinalLT_true.{u} : ∀ {a b : Ordinal.{u}} {an bn : ℕ},
IsNat a an → IsNat b bn → decide (an < bn) = true → a < b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => Nat.cast_lt.mpr <| of_decide_eq_true h
lemma isNat_ordinalLT_false.{u} : ∀ {a b : Ordinal.{u}} {an bn : ℕ},
IsNat a an → IsNat b bn → decide (an < bn) = false → ¬a < b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => not_iff_not.mpr Nat.cast_lt |>.mpr <| of_decide_eq_false h
/-- The `norm_num` extension for inequality on ordinals. -/
@[norm_num (_ : Ordinal) ≤ (_ : Ordinal)]
def evalOrdinalLE : NormNumExt where
eval {u α} e := do
let ⟨_⟩ ← assertLevelDefEqQ u ql(0)
match α, e with
| ~q(Prop), ~q(($a : Ordinal) ≤ ($b : Ordinal)) =>
let i : Q(AddMonoidWithOne Ordinal.{u_1}) := q(inferInstance)
let ⟨an, pa⟩ ← deriveNat a i
let ⟨bn, pb⟩ ← deriveNat b i
if an.natLit! ≤ bn.natLit! then
have this : decide ($an ≤ $bn) =Q true := ⟨⟩
pure (.isTrue q(isNat_ordinalLE_true $pa $pb $this))
else
have this : decide ($an ≤ $bn) =Q false := ⟨⟩
pure (.isFalse q(isNat_ordinalLE_false $pa $pb $this))
| _, _ => throwError "not inequality on ordinals"
/-- The `norm_num` extension for strict inequality on ordinals. -/
@[norm_num (_ : Ordinal) < (_ : Ordinal)]
def evalOrdinalLT : NormNumExt where
eval {u α} e := do
let ⟨_⟩ ← assertLevelDefEqQ u ql(0)
match α, e with
| ~q(Prop), ~q(($a : Ordinal) < ($b : Ordinal)) =>
let i : Q(AddMonoidWithOne Ordinal.{u_1}) := q(inferInstance)
let ⟨an, pa⟩ ← deriveNat a i
let ⟨bn, pb⟩ ← deriveNat b i
if an.natLit! < bn.natLit! then
have this : decide ($an < $bn) =Q true := ⟨⟩
pure (.isTrue q(isNat_ordinalLT_true $pa $pb $this))
else
have this : decide ($an < $bn) =Q false := ⟨⟩
pure (.isFalse q(isNat_ordinalLT_false $pa $pb $this))
| _, _ => throwError "not strict inequality on ordinals"
/-- info: 12 - 5 -/
#guard_msgs in
#norm_num (12 : Ordinal.{0}) - 5
lemma isNat_ordinalSub.{u} : ∀ {a b : Ordinal.{u}} {an bn rn : ℕ},
IsNat a an → IsNat b bn → an - bn = rn → IsNat (a - b) rn
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨Eq.symm <| natCast_sub ..⟩
/-- The `norm_num` extension for subtraction on ordinals. -/
@[norm_num (_ : Ordinal) - (_ : Ordinal)]
def evalOrdinalSub : NormNumExt where
eval {u α} e := do
let some u' := u.dec | throwError "level is not succ"
haveI' : u =QL u' + 1 := ⟨⟩
match α, e with
| ~q(Ordinal.{u'}), ~q(($a : Ordinal) - ($b : Ordinal)) =>
let i : Q(AddMonoidWithOne Ordinal.{u'}) := q(inferInstance)
let ⟨an, pa⟩ ← deriveNat a i
let ⟨bn, pb⟩ ← deriveNat b i
have rn : Q(ℕ) := mkRawNatLit (an.natLit! - bn.natLit!)
have : ($an - $bn) =Q $rn := ⟨⟩
pure (.isNat i rn q(isNat_ordinalSub $pa $pb (.refl $rn)))
| _, _ => throwError "not subtration on ordinals"
/-- info: 12 / 5 -/
#guard_msgs in
#norm_num (12 : Ordinal.{0}) / 5
lemma isNat_ordinalDiv.{u} : ∀ {a b : Ordinal.{u}} {an bn rn : ℕ},
IsNat a an → IsNat b bn → an / bn = rn → IsNat (a / b) rn
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨Eq.symm <| natCast_div ..⟩
/-- The `norm_num` extension for division on ordinals. -/
@[norm_num (_ : Ordinal) / (_ : Ordinal)]
def evalOrdinalDiv : NormNumExt where
eval {u α} e := do
let some u' := u.dec | throwError "level is not succ"
haveI' : u =QL u' + 1 := ⟨⟩
match α, e with
| ~q(Ordinal.{u'}), ~q(($a : Ordinal) / ($b : Ordinal)) =>
let i : Q(AddMonoidWithOne Ordinal.{u'}) := q(inferInstance)
let ⟨an, pa⟩ ← deriveNat a i
let ⟨bn, pb⟩ ← deriveNat b i
have rn : Q(ℕ) := mkRawNatLit (an.natLit! / bn.natLit!)
have : ($an / $bn) =Q $rn := ⟨⟩
pure (.isNat i rn q(isNat_ordinalDiv $pa $pb (.refl $rn)))
| _, _ => throwError "not division on ordinals"
/-- info: 12 % 5 -/
#guard_msgs in
#norm_num (12 : Ordinal.{0}) % 5
lemma isNat_ordinalMod.{u} : ∀ {a b : Ordinal.{u}} {an bn rn : ℕ},
IsNat a an → IsNat b bn → an % bn = rn → IsNat (a % b) rn
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨Eq.symm <| natCast_mod ..⟩
/-- The `norm_num` extension for modulo on ordinals. -/
@[norm_num (_ : Ordinal) % (_ : Ordinal)]
def evalOrdinalMod : NormNumExt where
eval {u α} e := do
let some u' := u.dec | throwError "level is not succ"
haveI' : u =QL u' + 1 := ⟨⟩
match α, e with
| ~q(Ordinal.{u'}), ~q(($a : Ordinal) % ($b : Ordinal)) =>
let i : Q(AddMonoidWithOne Ordinal.{u'}) := q(inferInstance)
let ⟨an, pa⟩ ← deriveNat a i
let ⟨bn, pb⟩ ← deriveNat b i
have rn : Q(ℕ) := mkRawNatLit (an.natLit! % bn.natLit!)
have : ($an % $bn) =Q $rn := ⟨⟩
pure (.isNat i rn q(isNat_ordinalMod $pa $pb (.refl $rn)))
| _, _ => throwError "not modulo on ordinals"
lemma isNat_ordinalOPow.{u} : ∀ {a b : Ordinal.{u}} {an bn rn : ℕ},
IsNat a an → IsNat b bn → an ^ bn = rn → IsNat (a ^ b) rn
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨Eq.symm <| natCast_opow ..⟩
/-- The `norm_num` extension for homogeneous power on ordinals. -/
@[norm_num (_ : Ordinal) ^ (_ : Ordinal)]
def evalOrdinalOPow : NormNumExt where
eval {u α} e := do
let some u' := u.dec | throwError "level is not succ"
haveI' : u =QL u' + 1 := ⟨⟩
match α, e with
| ~q(Ordinal.{u'}), ~q(($a : Ordinal) ^ ($b : Ordinal)) =>
let i : Q(AddMonoidWithOne Ordinal.{u'}) := q(inferInstance)
let ⟨an, pa⟩ ← deriveNat a i
let ⟨bn, pb⟩ ← deriveNat b i
have rn : Q(ℕ) := mkRawNatLit (an.natLit! ^ bn.natLit!)
have : ($an ^ $bn) =Q $rn := ⟨⟩
pure (.isNat i rn q(isNat_ordinalOPow $pa $pb (.refl $rn)))
| _, _ => throwError "not homogeneous power on ordinals"
/-- info: 12 ^ 2 -/
#guard_msgs in
#norm_num (12 : Ordinal.{0}) ^ (2 : ℕ)
lemma isNat_ordinalNPow.{u} : ∀ {a : Ordinal.{u}} {b an bn rn : ℕ},
IsNat a an → IsNat b bn → an ^ bn = rn → IsNat (a ^ b) rn
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨Eq.symm <| natCast_opow .. |>.trans <| opow_natCast ..⟩
/-- The `norm_num` extension for natural power on ordinals. -/
@[norm_num (_ : Ordinal) ^ (_ : ℕ)]
def evalOrdinalNPow : NormNumExt where
eval {u α} e := do
let some u' := u.dec | throwError "level is not succ"
haveI' : u =QL u' + 1 := ⟨⟩
match α, e with
| ~q(Ordinal.{u'}), ~q(($a : Ordinal) ^ ($b : ℕ)) =>
let i : Q(AddMonoidWithOne Ordinal.{u'}) := q(inferInstance)
let ⟨an, pa⟩ ← deriveNat a i
let ⟨bn, pb⟩ ← deriveNat b q(inferInstance)
have rn : Q(ℕ) := mkRawNatLit (an.natLit! ^ bn.natLit!)
have : ($an ^ $bn) =Q $rn := ⟨⟩
pure (.isNat i rn q(isNat_ordinalNPow $pa $pb (.refl $rn)))
| _, _ => throwError "not natural power on ordinals"
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Eq.lean | import Mathlib.Tactic.NormNum.Inv
/-!
# `norm_num` extension for equalities
-/
variable {α : Type*}
open Lean Meta Qq
namespace Mathlib.Meta.NormNum
theorem isNat_eq_false [AddMonoidWithOne α] [CharZero α] : {a b : α} → {a' b' : ℕ} →
IsNat a a' → IsNat b b' → Nat.beq a' b' = false → ¬a = b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => by simpa using Nat.ne_of_beq_eq_false h
theorem isInt_eq_false [Ring α] [CharZero α] : {a b : α} → {a' b' : ℤ} →
IsInt a a' → IsInt b b' → decide (a' = b') = false → ¬a = b
| _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, h => by simpa using of_decide_eq_false h
theorem NNRat.invOf_denom_swap [Semiring α] (n₁ n₂ : ℕ) (a₁ a₂ : α)
[Invertible a₁] [Invertible a₂] : n₁ * ⅟a₁ = n₂ * ⅟a₂ ↔ n₁ * a₂ = n₂ * a₁ := by
rw [mul_invOf_eq_iff_eq_mul_right, ← Nat.commute_cast, mul_assoc,
← mul_left_eq_iff_eq_invOf_mul, Nat.commute_cast]
theorem isNNRat_eq_false [Semiring α] [CharZero α] : {a b : α} → {na nb : ℕ} → {da db : ℕ} →
IsNNRat a na da → IsNNRat b nb db →
decide (Nat.mul na db = Nat.mul nb da) = false → ¬a = b
| _, _, _, _, _, _, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by
rw [NNRat.invOf_denom_swap]; exact mod_cast of_decide_eq_false h
theorem Rat.invOf_denom_swap [Ring α] (n₁ n₂ : ℤ) (a₁ a₂ : α)
[Invertible a₁] [Invertible a₂] : n₁ * ⅟a₁ = n₂ * ⅟a₂ ↔ n₁ * a₂ = n₂ * a₁ := by
rw [mul_invOf_eq_iff_eq_mul_right, ← Int.commute_cast, mul_assoc,
← mul_left_eq_iff_eq_invOf_mul, Int.commute_cast]
theorem isRat_eq_false [Ring α] [CharZero α] : {a b : α} → {na nb : ℤ} → {da db : ℕ} →
IsRat a na da → IsRat b nb db →
decide (Int.mul na (.ofNat db) = Int.mul nb (.ofNat da)) = false → ¬a = b
| _, _, _, _, _, _, ⟨_, rfl⟩, ⟨_, rfl⟩, h => by
rw [Rat.invOf_denom_swap]; exact mod_cast of_decide_eq_false h
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `a = b`,
such that `norm_num` successfully recognises both `a` and `b`. -/
@[norm_num _ = _] def evalEq : NormNumExt where eval {v β} e := do
haveI' : v =QL 0 := ⟨⟩; haveI' : $β =Q Prop := ⟨⟩
let .app (.app f a) b ← whnfR e | failure
let ⟨u, α, a⟩ ← inferTypeQ' a
have b : Q($α) := b
haveI' : $e =Q ($a = $b) := ⟨⟩
guard <|← withNewMCtxDepth <| isDefEq f q(Eq (α := $α))
let ra ← derive a; let rb ← derive b
let rec intArm (rα : Q(Ring $α)) := do
let ⟨za, na, pa⟩ ← ra.toInt rα; let ⟨zb, nb, pb⟩ ← rb.toInt rα
if za = zb then
haveI' : $na =Q $nb := ⟨⟩
return .isTrue q(isInt_eq_true $pa $pb)
else if let some _i ← inferCharZeroOfRing? rα then
let r : Q(decide ($na = $nb) = false) := (q(Eq.refl false) : Expr)
return .isFalse q(isInt_eq_false $pa $pb $r)
else
failure --TODO: nonzero characteristic ≠
let rec nnratArm (dsα : Q(DivisionSemiring $α)) := do
let ⟨qa, na, da, pa⟩ ← ra.toNNRat' dsα; let ⟨qb, nb, db, pb⟩ ← rb.toNNRat' dsα
if qa = qb then
haveI' : $na =Q $nb := ⟨⟩
haveI' : $da =Q $db := ⟨⟩
return .isTrue q(isNNRat_eq_true $pa $pb)
else if let some _i ← inferCharZeroOfDivisionSemiring? dsα then
let r : Q(decide (Nat.mul $na $db = Nat.mul $nb $da) = false) :=
(q(Eq.refl false) : Expr)
return .isFalse q(isNNRat_eq_false $pa $pb $r)
else
failure --TODO: nonzero characteristic ≠
let rec ratArm (dα : Q(DivisionRing $α)) := do
let ⟨qa, na, da, pa⟩ ← ra.toRat' dα; let ⟨qb, nb, db, pb⟩ ← rb.toRat' dα
if qa = qb then
haveI' : $na =Q $nb := ⟨⟩
haveI' : $da =Q $db := ⟨⟩
return .isTrue q(isRat_eq_true $pa $pb)
else if let some _i ← inferCharZeroOfDivisionRing? dα then
let r : Q(decide (Int.mul $na (.ofNat $db) = Int.mul $nb (.ofNat $da)) = false) :=
(q(Eq.refl false) : Expr)
return .isFalse q(isRat_eq_false $pa $pb $r)
else
failure --TODO: nonzero characteristic ≠
match ra, rb with
| .isBool b₁ p₁, .isBool b₂ p₂ =>
have a : Q(Prop) := a; have b : Q(Prop) := b
match b₁, p₁, b₂, p₂ with
| true, (p₁ : Q($a)), true, (p₂ : Q($b)) =>
return .isTrue q(eq_of_true $p₁ $p₂)
| false, (p₁ : Q(¬$a)), false, (p₂ : Q(¬$b)) =>
return .isTrue q(eq_of_false $p₁ $p₂)
| false, (p₁ : Q(¬$a)), true, (p₂ : Q($b)) =>
return .isFalse q(ne_of_false_of_true $p₁ $p₂)
| true, (p₁ : Q($a)), false, (p₂ : Q(¬$b)) =>
return .isFalse q(ne_of_true_of_false $p₁ $p₂)
| .isBool .., _ | _, .isBool .. => failure
| .isNegNNRat dα .., _ | _, .isNegNNRat dα .. => ratArm dα
-- mixing positive rationals and negative naturals means we need to use the full rat handler
| .isNNRat dsα .., .isNegNat rα .. | .isNegNat rα .., .isNNRat dsα .. =>
-- could alternatively try to combine `rα` and `dsα` here, but we'd have to do a defeq check
-- so would still need to be in `MetaM`.
ratArm (←synthInstanceQ q(DivisionRing $α))
| .isNNRat dsα .., _ | _, .isNNRat dsα .. => nnratArm dsα
| .isNegNat rα .., _ | _, .isNegNat rα .. => intArm rα
| .isNat _ na pa, .isNat mα nb pb =>
assumeInstancesCommute
if na.natLit! = nb.natLit! then
haveI' : $na =Q $nb := ⟨⟩
return .isTrue q(isNat_eq_true $pa $pb)
else if let some _i ← inferCharZeroOfAddMonoidWithOne? mα then
let r : Q(Nat.beq $na $nb = false) := (q(Eq.refl false) : Expr)
return .isFalse q(isNat_eq_false $pa $pb $r)
else
failure --TODO: nonzero characteristic ≠
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/RealSqrt.lean | import Mathlib.Data.Real.Sqrt
/-! # `norm_num` extension for `Real.sqrt`
This module defines a `norm_num` extension for `Real.sqrt` and `NNReal.sqrt`.
-/
namespace Tactic.NormNum
open Qq Lean Lean.Meta Elab.Tactic Mathlib.Meta.NormNum NNReal
lemma isNat_realSqrt {x : ℝ} {nx ny : ℕ} (h : IsNat x nx) (hy : ny * ny = nx) :
IsNat √x ny := ⟨by simp [h.out, ← hy]⟩
lemma isNat_nnrealSqrt {x : ℝ≥0} {nx ny : ℕ} (h : IsNat x nx) (hy : ny * ny = nx) :
IsNat (NNReal.sqrt x) ny := ⟨by simp [h.out, ← hy]⟩
lemma isNNRat_nnrealSqrt_of_isNNRat {x : ℝ≥0} {n sn : ℕ} {d sd : ℕ} (hn : sn * sn = n)
(hd : sd * sd = d) (h : IsNNRat x n d) :
IsNNRat (NNReal.sqrt x) sn sd := by
obtain ⟨_, rfl⟩ := h
refine ⟨?_, ?out⟩
· apply invertibleOfNonzero
rw [← mul_self_ne_zero, ← Nat.cast_mul, hd]
exact Invertible.ne_zero _
· simp [← hn, ← hd, NNReal.sqrt_mul]
lemma isNat_realSqrt_neg {x : ℝ} {nx : ℕ} (h : IsInt x (Int.negOfNat nx)) :
IsNat √x (nat_lit 0) := ⟨by simp [Real.sqrt_eq_zero', h.out]⟩
lemma isNat_realSqrt_of_isRat_negOfNat {x : ℝ} {num : ℕ} {denom : ℕ}
(h : IsRat x (.negOfNat num) denom) : IsNat √x (nat_lit 0) := by
refine ⟨?_⟩
obtain ⟨inv, rfl⟩ := h
have h₁ : 0 ≤ (num : ℚ) * ⅟(denom : ℝ) :=
mul_nonneg (Nat.cast_nonneg' _) (invOf_nonneg.2 <| Nat.cast_nonneg' _)
simpa [Nat.cast_zero, Real.sqrt_eq_zero', Int.cast_negOfNat, neg_mul, neg_nonpos] using h₁
lemma isNNRat_realSqrt_of_isNNRat {x : ℝ} {n sn : ℕ} {d sd : ℕ} (hn : sn * sn = n)
(hd : sd * sd = d) (h : IsNNRat x n d) :
IsNNRat √x sn sd := by
obtain ⟨_, rfl⟩ := h
refine ⟨?_, ?out⟩
· apply invertibleOfNonzero
rw [← mul_self_ne_zero, ← Nat.cast_mul, hd]
exact Invertible.ne_zero _
· simp [← hn, ← hd, Real.sqrt_mul (mul_self_nonneg ↑sn)]
/-- `norm_num` extension that evaluates the function `Real.sqrt`. -/
@[norm_num √_]
def evalRealSqrt : NormNumExt where eval {u α} e := do
match u, α, e with
| 0, ~q(ℝ), ~q(√$x) =>
match ← derive x with
| .isBool _ _ => failure
| .isNat sℝ ex pf =>
let x := ex.natLit!
let y := Nat.sqrt x
unless y * y = x do failure
have ey : Q(ℕ) := mkRawNatLit y
have pf₁ : Q($ey * $ey = $ex) := (q(Eq.refl $ex) : Expr)
assumeInstancesCommute
return .isNat q($sℝ) q($ey) q(isNat_realSqrt $pf $pf₁)
| .isNegNat _ ex pf =>
-- Recall that `Real.sqrt` returns 0 for negative inputs
assumeInstancesCommute
return .isNat q(inferInstance) q(nat_lit 0) q(isNat_realSqrt_neg $pf)
| .isNegNNRat sℝ eq n ed pf =>
assumeInstancesCommute
return .isNat q(inferInstance) q(nat_lit 0) q(isNat_realSqrt_of_isRat_negOfNat $pf)
| .isNNRat sℝ eq n' ed pf =>
let n : ℕ := n'.natLit!
let d : ℕ := ed.natLit!
let sn := Nat.sqrt n
let sd := Nat.sqrt d
unless sn * sn = n ∧ sd * sd = d do failure
have esn : Q(ℕ) := mkRawNatLit sn
have esd : Q(ℕ) := mkRawNatLit sd
have hn : Q($esn * $esn = $n') := (q(Eq.refl $n') : Expr)
have hd : Q($esd * $esd = $ed) := (q(Eq.refl $ed) : Expr)
assumeInstancesCommute
-- will never be an integer
return .isNNRat q($sℝ) (sn / sd) _ q($esd) q(isNNRat_realSqrt_of_isNNRat $hn $hd $pf)
| _ => failure
/-- `norm_num` extension that evaluates the function `NNReal.sqrt`. -/
@[norm_num NNReal.sqrt _]
def evalNNRealSqrt : NormNumExt where eval {u α} e := do
match u, α, e with
| 0, ~q(NNReal), ~q(NNReal.sqrt $x) =>
match ← derive x with
| .isBool _ _ => failure
| .isNat sℝ ex pf =>
let x := ex.natLit!
let y := Nat.sqrt x
unless y * y = x do failure
have ey : Q(ℕ) := mkRawNatLit y
have pf₁ : Q($ey * $ey = $ex) := (q(Eq.refl $ex) : Expr)
assumeInstancesCommute
return .isNat sℝ ey q(isNat_nnrealSqrt $pf $pf₁)
| .isNegNat _ ex pf => failure
| .isNNRat sℝ eq n' ed pf =>
let n : ℕ := n'.natLit!
let d : ℕ := ed.natLit!
let sn := Nat.sqrt n
let sd := Nat.sqrt d
unless sn * sn = n ∧ sd * sd = d do failure
have esn : Q(ℕ) := mkRawNatLit sn
have esd : Q(ℕ) := mkRawNatLit sd
have hn : Q($esn * $esn = $n') := (q(Eq.refl $n') : Expr)
have hd : Q($esd * $esd = $ed) := (q(Eq.refl $ed) : Expr)
assumeInstancesCommute
-- will never be an integer
return .isNNRat q($sℝ) (sn / sd) _ q($esd) q(isNNRat_nnrealSqrt_of_isNNRat $hn $hd $pf)
| .isNegNNRat sℝ eq en ed pf => failure
| _ => failure
end Tactic.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/BigOperators.lean | import Mathlib.Tactic.NormNum.Basic
import Mathlib.Data.List.FinRange
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
/-!
# `norm_num` plugin for big operators
This file adds `norm_num` plugins for `Finset.prod` and `Finset.sum`.
The driving part of this plugin is `Mathlib.Meta.NormNum.evalFinsetBigop`.
We repeatedly use `Finset.proveEmptyOrCons` to try to find a proof that the given set is empty,
or that it consists of one element inserted into a strict subset, and evaluate the big operator
on that subset until the set is completely exhausted.
## See also
* The `fin_cases` tactic has similar scope: splitting out a finite collection into its elements.
## Porting notes
This plugin is noticeably less powerful than the equivalent version in Mathlib 3: the design of
`norm_num` means plugins have to return numerals, rather than a generic expression.
In particular, we can't use the plugin on sums containing variables.
(See also the TODO note "To support variables".)
## TODO
* Support intervals: `Finset.Ico`, `Finset.Icc`, ...
* To support variables, like in Mathlib 3, turn this into a standalone tactic that unfolds
the sum/prod, without computing its numeric value (using the `ring` tactic to do some
normalization?)
-/
namespace Mathlib.Meta
open Lean
open Meta
open Qq
variable {u v : Level}
/-- This represents the result of trying to determine whether the given expression `n : Q(ℕ)`
is either `zero` or `succ`. -/
inductive Nat.UnifyZeroOrSuccResult (n : Q(ℕ))
/-- `n` unifies with `0` -/
| zero (pf : $n =Q 0)
/-- `n` unifies with `succ n'` for this specific `n'` -/
| succ (n' : Q(ℕ)) (pf : $n =Q Nat.succ $n')
/-- Determine whether the expression `n : Q(ℕ)` unifies with `0` or `Nat.succ n'`.
We do not use `norm_num` functionality because we want definitional equality,
not propositional equality, for use in dependent types.
Fails if neither of the options succeed.
-/
def Nat.unifyZeroOrSucc (n : Q(ℕ)) : MetaM (Nat.UnifyZeroOrSuccResult n) := do
match ← isDefEqQ n q(0) with
| .defEq pf => return .zero pf
| .notDefEq => do
let n' : Q(ℕ) ← mkFreshExprMVar q(ℕ)
let ⟨(_pf : $n =Q Nat.succ $n')⟩ ← assertDefEqQ n q(Nat.succ $n')
let (.some (n'_val : Q(ℕ))) ← getExprMVarAssignment? n'.mvarId! |
throwError "could not figure out value of `?n` from `{n} =?= Nat.succ ?n`"
pure (.succ n'_val ⟨⟩)
/-- This represents the result of trying to determine whether the given expression
`s : Q(List $α)` is either empty or consists of an element inserted into a strict subset. -/
inductive List.ProveNilOrConsResult {α : Q(Type u)} (s : Q(List $α))
/-- The set is Nil. -/
| nil (pf : Q($s = []))
/-- The set equals `a` inserted into the strict subset `s'`. -/
| cons (a : Q($α)) (s' : Q(List $α)) (pf : Q($s = List.cons $a $s'))
/-- If `s` unifies with `t`, convert a result for `s` to a result for `t`.
If `s` does not unify with `t`, this results in a type-incorrect proof.
-/
def List.ProveNilOrConsResult.uncheckedCast {α : Q(Type u)} {β : Q(Type v)}
(s : Q(List $α)) (t : Q(List $β)) :
List.ProveNilOrConsResult s → List.ProveNilOrConsResult t
| .nil pf => .nil pf
| .cons a s' pf => .cons a s' pf
/-- If `s = t` and we can get the result for `t`, then we can get the result for `s`.
-/
def List.ProveNilOrConsResult.eq_trans {α : Q(Type u)} {s t : Q(List $α)}
(eq : Q($s = $t)) :
List.ProveNilOrConsResult t → List.ProveNilOrConsResult s
| .nil pf => .nil q(Eq.trans $eq $pf)
| .cons a s' pf => .cons a s' q(Eq.trans $eq $pf)
lemma List.range_zero' {n : ℕ} (pn : NormNum.IsNat n 0) :
List.range n = [] := by rw [pn.out, Nat.cast_zero, List.range_zero]
lemma List.range_succ_eq_map' {n nn n' : ℕ} (pn : NormNum.IsNat n nn) (pn' : nn = Nat.succ n') :
List.range n = 0 :: List.map Nat.succ (List.range n') := by
rw [pn.out, Nat.cast_id, pn', List.range_succ_eq_map]
set_option linter.unusedVariables false in
/-- Either show the expression `s : Q(List α)` is Nil, or remove one element from it.
Fails if we cannot determine which of the alternatives apply to the expression.
-/
partial def List.proveNilOrCons {u : Level} {α : Q(Type u)} (s : Q(List $α)) :
MetaM (List.ProveNilOrConsResult s) :=
s.withApp fun e a =>
match (e, e.constName, a) with
| (_, ``EmptyCollection.emptyCollection, _) => haveI : $s =Q {} := ⟨⟩; pure (.nil q(.refl []))
| (_, ``List.nil, _) => haveI : $s =Q [] := ⟨⟩; pure (.nil q(rfl))
| (_, ``List.cons, #[_, (a : Q($α)), (s' : Q(List $α))]) =>
haveI : $s =Q $a :: $s' := ⟨⟩; pure (.cons a s' q(rfl))
| (_, ``List.range, #[(n : Q(ℕ))]) =>
have s : Q(List ℕ) := s; .uncheckedCast _ _ <$> show MetaM (ProveNilOrConsResult s) from do
let ⟨nn, pn⟩ ← NormNum.deriveNat n _
haveI' : $s =Q .range $n := ⟨⟩
let nnL := nn.natLit!
if nnL = 0 then
haveI' : $nn =Q 0 := ⟨⟩
return .nil q(List.range_zero' $pn)
else
have n' : Q(ℕ) := mkRawNatLit (nnL - 1)
have : $nn =Q .succ $n' := ⟨⟩
return .cons _ _ q(List.range_succ_eq_map' $pn (.refl $nn))
| (_, ``List.finRange, #[(n : Q(ℕ))]) =>
have s : Q(List (Fin $n)) := s
.uncheckedCast _ _ <$> show MetaM (ProveNilOrConsResult s) from do
haveI' : $s =Q .finRange $n := ⟨⟩
return match ← Nat.unifyZeroOrSucc n with -- We want definitional equality on `n`.
| .zero _pf => .nil q(List.finRange_zero)
| .succ n' _pf => .cons _ _ q(List.finRange_succ)
| (.const ``List.map [v, _], _, #[(β : Q(Type v)), _, (f : Q($β → $α)), (xxs : Q(List $β))]) => do
haveI' : $s =Q ($xxs).map $f := ⟨⟩
return match ← List.proveNilOrCons xxs with
| .nil pf => .nil q(($pf ▸ List.map_nil : List.map _ _ = _))
| .cons x xs pf => .cons q($f $x) q(($xs).map $f)
q(($pf ▸ List.map_cons : List.map _ _ = _))
| (_, fn, args) =>
throwError "List.proveNilOrCons: unsupported List expression {s} ({fn}, {args})"
/-- This represents the result of trying to determine whether the given expression
`s : Q(Multiset $α)` is either empty or consists of an element inserted into a strict subset. -/
inductive Multiset.ProveZeroOrConsResult {α : Q(Type u)} (s : Q(Multiset $α))
/-- The set is zero. -/
| zero (pf : Q($s = 0))
/-- The set equals `a` inserted into the strict subset `s'`. -/
| cons (a : Q($α)) (s' : Q(Multiset $α)) (pf : Q($s = Multiset.cons $a $s'))
/-- If `s` unifies with `t`, convert a result for `s` to a result for `t`.
If `s` does not unify with `t`, this results in a type-incorrect proof.
-/
def Multiset.ProveZeroOrConsResult.uncheckedCast {α : Q(Type u)} {β : Q(Type v)}
(s : Q(Multiset $α)) (t : Q(Multiset $β)) :
Multiset.ProveZeroOrConsResult s → Multiset.ProveZeroOrConsResult t
| .zero pf => .zero pf
| .cons a s' pf => .cons a s' pf
/-- If `s = t` and we can get the result for `t`, then we can get the result for `s`.
-/
def Multiset.ProveZeroOrConsResult.eq_trans {α : Q(Type u)} {s t : Q(Multiset $α)}
(eq : Q($s = $t)) :
Multiset.ProveZeroOrConsResult t → Multiset.ProveZeroOrConsResult s
| .zero pf => .zero q(Eq.trans $eq $pf)
| .cons a s' pf => .cons a s' q(Eq.trans $eq $pf)
lemma Multiset.insert_eq_cons {α : Type*} (a : α) (s : Multiset α) :
insert a s = Multiset.cons a s :=
rfl
lemma Multiset.range_zero' {n : ℕ} (pn : NormNum.IsNat n 0) :
Multiset.range n = 0 := by rw [pn.out, Nat.cast_zero, Multiset.range_zero]
lemma Multiset.range_succ' {n nn n' : ℕ} (pn : NormNum.IsNat n nn) (pn' : nn = Nat.succ n') :
Multiset.range n = n' ::ₘ Multiset.range n' := by
rw [pn.out, Nat.cast_id, pn', Multiset.range_succ]
/-- Either show the expression `s : Q(Multiset α)` is Zero, or remove one element from it.
Fails if we cannot determine which of the alternatives apply to the expression.
-/
partial def Multiset.proveZeroOrCons {α : Q(Type u)} (s : Q(Multiset $α)) :
MetaM (Multiset.ProveZeroOrConsResult s) :=
match s.getAppFnArgs with
| (``EmptyCollection.emptyCollection, _) => haveI : $s =Q {} := ⟨⟩; pure (.zero q(rfl))
| (``Zero.zero, _) => haveI : $s =Q 0 := ⟨⟩; pure (.zero q(rfl))
| (``Multiset.cons, #[_, (a : Q($α)), (s' : Q(Multiset $α))]) =>
haveI : $s =Q .cons $a $s' := ⟨⟩
pure (.cons a s' q(rfl))
| (``Multiset.ofList, #[_, (val : Q(List $α))]) => do
haveI : $s =Q .ofList $val := ⟨⟩
return match ← List.proveNilOrCons val with
| .nil pf => .zero q($pf ▸ Multiset.coe_nil : Multiset.ofList _ = _)
| .cons a s' pf => .cons a q($s') q($pf ▸ Multiset.cons_coe $a $s' : Multiset.ofList _ = _)
| (``Multiset.range, #[(n : Q(ℕ))]) => do
have s : Q(Multiset ℕ) := s; .uncheckedCast _ _ <$> show MetaM (ProveZeroOrConsResult s) from do
let ⟨nn, pn⟩ ← NormNum.deriveNat n _
haveI' : $s =Q .range $n := ⟨⟩
let nnL := nn.natLit!
if nnL = 0 then
haveI' : $nn =Q 0 := ⟨⟩
return .zero q(Multiset.range_zero' $pn)
else
have n' : Q(ℕ) := mkRawNatLit (nnL - 1)
haveI' : $nn =Q ($n').succ := ⟨⟩
return .cons _ _ q(Multiset.range_succ' $pn rfl)
| (fn, args) =>
throwError "Multiset.proveZeroOrCons: unsupported multiset expression {s} ({fn}, {args})"
/-- This represents the result of trying to determine whether the given expression
`s : Q(Finset $α)` is either empty or consists of an element inserted into a strict subset. -/
inductive Finset.ProveEmptyOrConsResult {α : Q(Type u)} (s : Q(Finset $α))
/-- The set is empty. -/
| empty (pf : Q($s = ∅))
/-- The set equals `a` inserted into the strict subset `s'`. -/
| cons (a : Q($α)) (s' : Q(Finset $α)) (h : Q($a ∉ $s')) (pf : Q($s = Finset.cons $a $s' $h))
/-- If `s` unifies with `t`, convert a result for `s` to a result for `t`.
If `s` does not unify with `t`, this results in a type-incorrect proof.
-/
def Finset.ProveEmptyOrConsResult.uncheckedCast {α : Q(Type u)} {β : Q(Type v)}
(s : Q(Finset $α)) (t : Q(Finset $β)) :
Finset.ProveEmptyOrConsResult s → Finset.ProveEmptyOrConsResult t
| .empty pf => .empty pf
| .cons a s' h pf => .cons a s' h pf
/-- If `s = t` and we can get the result for `t`, then we can get the result for `s`.
-/
def Finset.ProveEmptyOrConsResult.eq_trans {α : Q(Type u)} {s t : Q(Finset $α)}
(eq : Q($s = $t)) :
Finset.ProveEmptyOrConsResult t → Finset.ProveEmptyOrConsResult s
| .empty pf => .empty q(Eq.trans $eq $pf)
| .cons a s' h pf => .cons a s' h q(Eq.trans $eq $pf)
lemma Finset.insert_eq_cons {α : Type*} [DecidableEq α] (a : α) (s : Finset α) (h : a ∉ s) :
insert a s = Finset.cons a s h := by
simp
lemma Finset.range_zero' {n : ℕ} (pn : NormNum.IsNat n 0) :
Finset.range n = {} := by rw [pn.out, Nat.cast_zero, Finset.range_zero]
lemma Finset.range_succ' {n nn n' : ℕ} (pn : NormNum.IsNat n nn) (pn' : nn = Nat.succ n') :
Finset.range n = Finset.cons n' (Finset.range n') Finset.notMem_range_self := by
rw [pn.out, Nat.cast_id, pn', Finset.range_add_one, Finset.insert_eq_cons]
lemma Finset.univ_eq_elems {α : Type*} [Fintype α] (elems : Finset α)
(complete : ∀ x : α, x ∈ elems) :
Finset.univ = elems := by
ext x; simpa using complete x
/-- Either show the expression `s : Q(Finset α)` is empty, or remove one element from it.
Fails if we cannot determine which of the alternatives apply to the expression.
-/
partial def Finset.proveEmptyOrCons {α : Q(Type u)} (s : Q(Finset $α)) :
MetaM (ProveEmptyOrConsResult s) :=
match s.getAppFnArgs with
| (``EmptyCollection.emptyCollection, _) => haveI : $s =Q {} := ⟨⟩; pure (.empty q(rfl))
| (``Finset.cons, #[_, (a : Q($α)), (s' : Q(Finset $α)), (h : Q($a ∉ $s'))]) =>
haveI : $s =Q .cons $a $s' $h := ⟨⟩
pure (.cons a s' h q(.refl $s))
| (``Finset.mk, #[_, (val : Q(Multiset $α)), (nd : Q(Multiset.Nodup $val))]) => do
match ← Multiset.proveZeroOrCons val with
| .zero pf => pure <| .empty (q($pf ▸ Finset.mk_zero) : Q(Finset.mk $val $nd = ∅))
| .cons a s' pf => do
let h : Q(Multiset.Nodup ($a ::ₘ $s')) := q($pf ▸ $nd)
let nd' : Q(Multiset.Nodup $s') := q((Multiset.nodup_cons.mp $h).2)
let h' : Q($a ∉ $s') := q((Multiset.nodup_cons.mp $h).1)
return (.cons a q(Finset.mk $s' $nd') h'
(q($pf ▸ Finset.mk_cons $h) : Q(Finset.mk $val $nd = Finset.cons $a ⟨$s', $nd'⟩ $h')))
| (``Finset.range, #[(n : Q(ℕ))]) =>
have s : Q(Finset ℕ) := s; .uncheckedCast _ _ <$> show MetaM (ProveEmptyOrConsResult s) from do
let ⟨nn, pn⟩ ← NormNum.deriveNat n _
haveI' : $s =Q .range $n := ⟨⟩
let nnL := nn.natLit!
if nnL = 0 then
haveI : $nn =Q 0 := ⟨⟩
return .empty q(Finset.range_zero' $pn)
else
have n' : Q(ℕ) := mkRawNatLit (nnL - 1)
haveI' : $nn =Q ($n').succ := ⟨⟩
return .cons n' _ _ q(Finset.range_succ' $pn (.refl $nn))
| (``Finset.univ, #[_, (instFT : Q(Fintype $α))]) => do
haveI' : $s =Q .univ := ⟨⟩
match (← whnfI instFT).getAppFnArgs with
| (``Fintype.mk, #[_, (elems : Q(Finset $α)), (complete : Q(∀ x : $α, x ∈ $elems))]) => do
let res ← Finset.proveEmptyOrCons elems
pure <| res.eq_trans q(Finset.univ_eq_elems $elems $complete)
| e =>
throwError "Finset.proveEmptyOrCons: could not determine elements of Fintype instance {e}"
| (fn, args) =>
throwError "Finset.proveEmptyOrCons: unsupported finset expression {s} ({fn}, {args})"
namespace NormNum
/-- If `a = b` and we can evaluate `b`, then we can evaluate `a`. -/
def Result.eq_trans {α : Q(Type u)} {a b : Q($α)} (eq : Q($a = $b)) : Result b → Result a
| .isBool true proof =>
have a : Q(Prop) := a
have b : Q(Prop) := b
have eq : Q($a = $b) := eq
have proof : Q($b) := proof
Result.isTrue (x := a) q($eq ▸ $proof)
| .isBool false proof =>
have a : Q(Prop) := a
have b : Q(Prop) := b
have eq : Q($a = $b) := eq
have proof : Q(¬ $b) := proof
Result.isFalse (x := a) q($eq ▸ $proof)
| .isNat inst lit proof => Result.isNat inst lit q($eq ▸ $proof)
| .isNegNat inst lit proof => Result.isNegNat inst lit q($eq ▸ $proof)
| .isNNRat inst q n d proof => Result.isNNRat inst q n d q($eq ▸ $proof)
| .isNegNNRat inst q n d proof => Result.isNegNNRat inst q n d q($eq ▸ $proof)
protected lemma Finset.sum_empty {β α : Type*} [CommSemiring β] (f : α → β) :
IsNat (Finset.sum ∅ f) 0 :=
⟨by simp⟩
protected lemma Finset.prod_empty {β α : Type*} [CommSemiring β] (f : α → β) :
IsNat (Finset.prod ∅ f) 1 :=
⟨by simp⟩
/-- Evaluate a big operator applied to a finset by repeating `proveEmptyOrCons` until
we exhaust all elements of the set. -/
partial def evalFinsetBigop {α : Q(Type u)} {β : Q(Type v)}
(op : Q(Finset $α → ($α → $β) → $β))
(f : Q($α → $β))
(res_empty : Result q($op Finset.empty $f))
(res_cons : {a : Q($α)} -> {s' : Q(Finset $α)} -> {h : Q($a ∉ $s')} ->
Result (α := β) q($f $a) -> Result (α := β) q($op $s' $f) ->
MetaM (Result (α := β) q($op (Finset.cons $a $s' $h) $f))) :
(s : Q(Finset $α)) → MetaM (Result (α := β) q($op $s $f))
| s => do
match ← Finset.proveEmptyOrCons s with
| .empty pf => pure <| res_empty.eq_trans q(congr_fun (congr_arg _ $pf) _)
| .cons a s' h pf => do
let fa : Q($β) := Expr.betaRev f #[a]
let res_fa ← derive fa
let res_op_s' : Result q($op $s' $f) ← evalFinsetBigop op f res_empty @res_cons s'
let res ← res_cons res_fa res_op_s'
let eq : Q($op $s $f = $op (Finset.cons $a $s' $h) $f) := q(congr_fun (congr_arg _ $pf) _)
pure (res.eq_trans eq)
attribute [local instance] monadLiftOptionMetaM in
/-- `norm_num` plugin for evaluating products of finsets.
If your finset is not supported, you can add it to the match in `Finset.proveEmptyOrCons`.
-/
@[norm_num @Finset.prod _ _ _ _ _]
partial def evalFinsetProd : NormNumExt where eval {u β} e := do
let .app (.app (.app (.app (.app (.const ``Finset.prod [v, _]) α) β') _) s) f ←
whnfR e | failure
guard <| ← withNewMCtxDepth <| isDefEq β β'
have α : Q(Type v) := α
have s : Q(Finset $α) := s
have f : Q($α → $β) := f
let instCS : Q(CommSemiring $β) ← synthInstanceQ q(CommSemiring $β) <|>
throwError "not a commutative semiring: {β}"
let instS : Q(Semiring $β) := q(CommSemiring.toSemiring)
-- Have to construct this expression manually, `q(1)` doesn't parse correctly:
let n : Q(ℕ) := .lit (.natVal 1)
let pf : Q(IsNat (Finset.prod ∅ $f) $n) := q(@Finset.prod_empty $β $α $instCS $f)
let res_empty := Result.isNat _ n pf
evalFinsetBigop q(Finset.prod) f res_empty (fun {a s' h} res_fa res_prod_s' ↦ do
let fa : Q($β) := Expr.app f a
let res ← res_fa.mul res_prod_s'
let eq : Q(Finset.prod (Finset.cons $a $s' $h) $f = $fa * Finset.prod $s' $f) :=
q(Finset.prod_cons $h)
pure <| res.eq_trans eq)
s
attribute [local instance] monadLiftOptionMetaM in
/-- `norm_num` plugin for evaluating sums of finsets.
If your finset is not supported, you can add it to the match in `Finset.proveEmptyOrCons`.
-/
@[norm_num @Finset.sum _ _ _ _ _]
partial def evalFinsetSum : NormNumExt where eval {u β} e := do
let .app (.app (.app (.app (.app (.const ``Finset.sum [v, _]) α) β') _) s) f ←
whnfR e | failure
guard <| ← withNewMCtxDepth <| isDefEq β β'
have α : Q(Type v) := α
have s : Q(Finset $α) := s
have f : Q($α → $β) := f
let instCS : Q(CommSemiring $β) ← synthInstanceQ q(CommSemiring $β) <|>
throwError "not a commutative semiring: {β}"
let pf : Q(IsNat (Finset.sum ∅ $f) (nat_lit 0)) := q(@Finset.sum_empty $β $α $instCS $f)
let res_empty := Result.isNat _ _ q($pf)
evalFinsetBigop q(Finset.sum) f res_empty (fun {a s' h} res_fa res_sum_s' ↦ do
let fa : Q($β) := Expr.app f a
let res ← res_fa.add res_sum_s'
let eq : Q(Finset.sum (Finset.cons $a $s' $h) $f = $fa + Finset.sum $s' $f) :=
q(Finset.sum_cons $h)
pure <| res.eq_trans eq)
s
end NormNum
end Meta
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Irrational.lean | import Mathlib.Analysis.SpecialFunctions.Pow.Real
import Mathlib.NumberTheory.Real.Irrational
import Mathlib.Tactic.NormNum.GCD
import Mathlib.Tactic.Rify
/-! # `norm_num` extension for `Irrational`
This module defines a `norm_num` extension for `Irrational x ^ y` for rational `x` and `y`. It also
supports `Irrational √x` expressions.
## Implementation details
To prove that `(a / b) ^ (p / q)` is irrational, we reduce the problem to showing that `(a / b) ^ p`
is not a `q`-th power of any rational number. This, in turn, reduces to proving that either `a` or
`b` is not a `q`-th power of a natural number, assuming `p` and `q` are coprime.
To show that a given `n : ℕ` is not a `q`-th power, we find a natural number `k`
such that `k ^ q < n < (k + 1) ^ q`, using binary search.
## TODO
Disprove `Irrational x` for rational `x`.
-/
namespace Tactic
namespace NormNum
open Qq Lean Elab.Tactic Mathlib.Meta.NormNum
section lemmas
private theorem irrational_rpow_rat_of_not_power {q : ℚ} {a b : ℕ}
(h : ∀ p : ℚ, q ^ a ≠ p ^ b) (hb : 0 < b) (hq : 0 ≤ q) :
Irrational (Real.rpow q (a / b : ℚ)) := by
simp only [Irrational, Rat.cast_div, Rat.cast_natCast, Real.rpow_eq_pow, Set.mem_range,
not_exists]
intro x hx
absurd h x
rify
rw [hx, ← Real.rpow_mul_natCast, div_mul_cancel₀] <;> simp
· cutsat
· assumption
private theorem not_power_nat_pow {n p q : ℕ}
(h_coprime : p.Coprime q)
(hq : 0 < q)
(h : ∀ m, n ≠ m ^ q) (m : ℕ) :
n ^ p ≠ m ^ q := by
by_cases hn : n = 0
· specialize h 0
simp [hn, zero_pow hq.ne.symm] at h
contrapose! h
apply_fun Nat.factorization at h
simp only [Nat.factorization_pow] at h
suffices ∃ f : ℕ →₀ ℕ, n.factorization = q • f by
obtain ⟨f, hf⟩ := this
have : f = (f.prod fun x1 x2 => x1 ^ x2).factorization := by
rw [Nat.prod_pow_factorization_eq_self]
intro z hz
apply_fun Finsupp.support at hf
rw [Finsupp.support_smul_eq (by cutsat)] at hf
rw [← hf] at hz
exact Nat.prime_of_mem_primeFactors hz
have hf0 : f 0 = 0 := by
apply_fun (· 0) at hf
simp only [Nat.factorization_zero_right, Finsupp.coe_smul, Pi.smul_apply, smul_eq_mul,
zero_eq_mul] at hf
cases hf
· cutsat
· assumption
rw [this, ← Nat.factorization_pow] at hf
apply Nat.factorization_inj at hf
· use f.prod (· ^ ·)
· exact hn
· simp only [ne_eq, Set.mem_setOf_eq, pow_eq_zero_iff', Finsupp.prod_eq_zero_iff,
Finsupp.mem_support_iff, existsAndEq, true_and, and_self, not_and, Decidable.not_not]
tauto
use n.factorization.mapRange (fun e ↦ e / q) (by simp)
ext z
apply_fun (· z) at h
simp only [Finsupp.coe_smul, Pi.smul_apply, smul_eq_mul, Finsupp.mapRange_apply] at h ⊢
rw [Nat.mul_div_cancel']
apply Nat.Coprime.dvd_of_dvd_mul_left _ ⟨_, h⟩
rwa [Nat.coprime_comm]
private theorem not_power_nat_of_bounds {n k d : ℕ}
(h_left : k ^ d < n) (h_right : n < (k + 1) ^ d) {m : ℕ} :
n ≠ m ^ d := by
intro h
rw [h] at h_left h_right
have : k < m := lt_of_pow_lt_pow_left' d h_left
have : m < k + 1 := lt_of_pow_lt_pow_left' d h_right
cutsat
private theorem not_power_nat_pow_of_bounds {n k p q : ℕ}
(hq : 0 < q) (h_coprime : p.Coprime q) (h_left : k ^ q < n) (h_right : n < (k + 1) ^ q)
(m : ℕ) :
n ^ p ≠ m ^ q := by
apply not_power_nat_pow h_coprime hq
intro m
apply not_power_nat_of_bounds h_left h_right
private lemma eq_of_mul_eq_mul_of_coprime_aux {a b x y : ℕ} (hab : a.Coprime b)
(h : a * x = b * y) : a ∣ y := Nat.Coprime.dvd_of_dvd_mul_left hab (Dvd.intro x h)
private lemma eq_of_mul_eq_mul_of_coprime {a b x y : ℕ} (hab : a.Coprime b) (hxy : x.Coprime y)
(h : a * x = b * y) : a = y := by
apply Nat.dvd_antisymm
· exact eq_of_mul_eq_mul_of_coprime_aux hab h
· exact eq_of_mul_eq_mul_of_coprime_aux (x := b) hxy.symm (by rw [mul_comm, ← h, mul_comm])
/-- Weaker version of `not_power_rat_of_num` with extra `q ≥ 0` assumption. -/
private theorem not_power_rat_of_num_aux {a b d : ℕ}
(h_coprime : a.Coprime b) (ha : ∀ x, a ≠ x ^ d) {q : ℚ} (hq : 0 ≤ q) :
(a / b : ℚ) ≠ q ^ d := by
by_cases hb_zero : b = 0
· subst hb_zero
contrapose! ha
simp only [Nat.coprime_zero_right] at h_coprime
subst h_coprime
use 1
simp
by_contra! h
rw [← Rat.num_div_den q] at h
set x' := q.num
set y := q.den
obtain ⟨x, hx'⟩ := Int.eq_ofNat_of_zero_le (show 0 ≤ x' by rwa [Rat.num_nonneg])
rw [hx'] at h
specialize ha x
simp only [Int.cast_natCast, div_pow] at h
rw [div_eq_div_iff] at h
rotate_left
· simpa
· simp [y]
replace h : a * y ^ d = x ^ d * b := by
qify
assumption
apply ha
conv at h => rhs; rw [mul_comm]
apply eq_of_mul_eq_mul_of_coprime h_coprime _ h
apply Nat.Coprime.pow_left
apply Nat.Coprime.pow_right
apply Nat.Coprime.symm
simpa [hx'] using (show x'.natAbs.Coprime y from Rat.reduced q)
private theorem not_power_rat_of_num {a b d : ℕ}
(h_coprime : a.Coprime b) (ha : ∀ x, a ≠ x ^ d) (q : ℚ) :
(a / b : ℚ) ≠ q ^ d := by
by_cases hq : 0 ≤ q
· apply not_power_rat_of_num_aux h_coprime ha hq
rcases d.even_or_odd with (h_even | h_odd)
· have := not_power_rat_of_num_aux h_coprime (q := -q) ha (by linarith)
rwa [h_even.neg_pow] at this
· contrapose! hq
rw [← h_odd.pow_nonneg_iff, ← hq]
positivity
private theorem irrational_rpow_rat_rat_of_num {x y : ℝ} {x_num x_den y_num y_den k_num : ℕ}
(hx_isNNRat : IsNNRat x x_num x_den)
(hy_isNNRat : IsNNRat y y_num y_den)
(hx_coprime : Nat.Coprime x_num x_den)
(hy_coprime : Nat.Coprime y_num y_den)
(hn1 : k_num ^ y_den < x_num)
(hn2 : x_num < (k_num + 1) ^ y_den) :
Irrational (x ^ y) := by
have hy_den_pos : 0 < y_den := by
by_contra! h
simp only [nonpos_iff_eq_zero] at h
simp only [h, pow_zero, Nat.lt_one_iff] at hn1 hn2
omega
rcases hx_isNNRat with ⟨hx_inv, hx_eq⟩
rcases hy_isNNRat with ⟨hy_inv, hy_eq⟩
rw [hy_eq, hx_eq]
have h1 : (y_num * ⅟(y_den : ℝ) : ℝ) = ((y_num / y_den : ℚ) : ℝ) := by
simp
rfl
have h2 : (x_num * ⅟(x_den : ℝ) : ℝ) = ((x_num / x_den : ℚ) : ℝ) := by
simp
rfl
rw [h1, h2]
refine irrational_rpow_rat_of_not_power ?_ hy_den_pos ?_
· simp only [div_pow, ← Nat.cast_pow]
apply not_power_rat_of_num
· apply Nat.Coprime.pow _ _ hx_coprime
· apply not_power_nat_pow_of_bounds hy_den_pos hy_coprime hn1 hn2
· positivity
private theorem irrational_rpow_rat_rat_of_den {x y : ℝ} {x_num x_den y_num y_den k_den : ℕ}
(hx_isNNRat : IsNNRat x x_num x_den)
(hy_isNNRat : IsNNRat y y_num y_den)
(hx_coprime : Nat.Coprime x_num x_den)
(hy_coprime : Nat.Coprime y_num y_den)
(hd1 : k_den ^ y_den < x_den)
(hd2 : x_den < (k_den + 1) ^ y_den) :
Irrational (x ^ y) := by
rcases hx_isNNRat with ⟨hx_inv, hx_eq⟩
apply Irrational.of_inv
rw [← Real.inv_rpow (by simp [hx_eq]; positivity)]
apply irrational_rpow_rat_rat_of_num (x_num := x_den) (x_den := x_num) _ hy_isNNRat
(Nat.coprime_comm.mp hx_coprime) hy_coprime hd1 hd2
refine ⟨invertibleOfNonzero (fun _ ↦ ?_), by simp [hx_eq]⟩
simp_all
private theorem irrational_rpow_nat_rat {x y : ℝ} {x_num y_num y_den k : ℕ}
(hx_isNat : IsNat x x_num)
(hy_isNNRat : IsNNRat y y_num y_den)
(hy_coprime : Nat.Coprime y_num y_den)
(hn1 : k ^ y_den < x_num)
(hn2 : x_num < (k + 1) ^ y_den) :
Irrational (x ^ y) :=
irrational_rpow_rat_rat_of_num hx_isNat.to_isNNRat hy_isNNRat (by simp) hy_coprime hn1 hn2
private theorem irrational_sqrt_rat_of_num {x : ℝ} {num den num_k : ℕ}
(hx_isNNRat : IsNNRat x num den)
(hx_coprime : Nat.Coprime num den)
(hn1 : num_k ^ 2 < num)
(hn2 : num < (num_k + 1) ^ 2) :
Irrational (Real.sqrt x) := by
rw [Real.sqrt_eq_rpow]
apply irrational_rpow_rat_rat_of_num hx_isNNRat (y_num := 1) (y_den := 2) _ hx_coprime (by simp)
hn1 hn2
exact ⟨Invertible.mk (1/2) (by simp) (by simp), by simp⟩
private theorem irrational_sqrt_rat_of_den {x : ℝ} {num den den_k : ℕ}
(hx_isNNRat : IsNNRat x num den)
(hx_coprime : Nat.Coprime num den)
(hd1 : den_k ^ 2 < den)
(hd2 : den < (den_k + 1) ^ 2) :
Irrational (Real.sqrt x) := by
rw [Real.sqrt_eq_rpow]
apply irrational_rpow_rat_rat_of_den hx_isNNRat (y_num := 1) (y_den := 2) _ hx_coprime (by simp)
hd1 hd2
exact ⟨Invertible.mk (1/2) (by simp) (by simp), by simp⟩
private theorem irrational_sqrt_nat {x : ℝ} {n k : ℕ}
(hx_isNat : IsNat x n)
(hn1 : k ^ 2 < n)
(hn2 : n < (k + 1) ^ 2) :
Irrational (Real.sqrt x) :=
irrational_sqrt_rat_of_num hx_isNat.to_isNNRat (by simp) hn1 hn2
end lemmas
/-- To prove that `m` is not `n`-power (and thus `m ^ (1/n)` is irrational), we find `k` such that
`k ^ n < m < (k + 1) ^ n`. -/
structure NotPowerCertificate (m n : Q(ℕ)) where
/-- Natural `k` such that `k ^ n < m < (k + 1) ^ n`. -/
k : Q(ℕ)
/-- Proof of `k ^ n < m`. -/
pf_left : Q($k ^ $n < $m)
/-- Proof of `m < (k + 1) ^ n`. -/
pf_right : Q($m < ($k + 1) ^ $n)
/-- Finds `k` such that `k ^ n < m < (k + 1) ^ n` using bisection method. It assumes `n > 0`. -/
def findNotPowerCertificateCore (m n : ℕ) : Option ℕ := Id.run do
let mut left := 0
let mut right := m + 1
while right - left > 1 do
let middle := (left + right) / 2
if middle ^ n ≤ m then
left := middle
else
right := middle
if left ^ n < m then
return some left
return none
/-- Finds `NotPowerCertificate` showing that `m` is not `n`-power. -/
def findNotPowerCertificate (m n : Q(ℕ)) : MetaM (NotPowerCertificate m n) := do
let .isNat (_ : Q(AddMonoidWithOne ℕ)) m _ := ← derive m | failure
let .isNat (_ : Q(AddMonoidWithOne ℕ)) n _ := ← derive n | failure
let mVal := m.natLit!
let nVal := n.natLit!
let some k := findNotPowerCertificateCore mVal nVal | failure
let .isBool true pf_left ← derive q($k ^ $n < $m) | failure
let .isBool true pf_right ← derive q($m < ($k + 1) ^ $n) | failure
return ⟨q($k), pf_left, pf_right⟩
/-- `norm_num` extension that proves `Irrational x ^ y` for rational `y`. `x` may be
natural or rational. -/
@[norm_num Irrational (_ ^ (_ : ℝ))]
def evalIrrationalRpow : NormNumExt where eval {u α} e := do
let 0 := u | failure
let ~q(Prop) := α | failure
let ~q(Irrational (($x : ℝ) ^ ($y : ℝ))) := e | failure
let .isNNRat sℝ _ y_num y_den y_isNNRat ← derive y | failure
let ⟨gy, hy_coprime⟩ := proveNatGCD y_num y_den
if gy.natLit! != 1 then failure
let _ : $gy =Q 1 := ⟨⟩
match ← derive x with
| .isNat sℝ ex x_isNat =>
let cert ← findNotPowerCertificate q($ex) y_den
assumeInstancesCommute
return .isTrue q(irrational_rpow_nat_rat $x_isNat $y_isNNRat $hy_coprime
$cert.pf_left $cert.pf_right)
| .isNNRat sℝ _ x_num x_den x_isNNRat =>
let ⟨gx, hx_coprime⟩ := proveNatGCD x_num x_den
if gx.natLit! != 1 then failure
let _ : $gx =Q 1 := ⟨⟩
let hx_isNNRat' : Q(IsNNRat $x $x_num $x_den) := x_isNNRat
let hy_isNNRat' : Q(IsNNRat $y $y_num $y_den) := y_isNNRat
try
let numCert ← findNotPowerCertificate q($x_num) y_den
assumeInstancesCommute
return Result.isTrue q(irrational_rpow_rat_rat_of_num $hx_isNNRat' $hy_isNNRat'
$hx_coprime $hy_coprime $numCert.pf_left $numCert.pf_right)
catch _ =>
let denCert ← findNotPowerCertificate q($x_den) y_den
assumeInstancesCommute
return Result.isTrue q(irrational_rpow_rat_rat_of_den $hx_isNNRat' $hy_isNNRat'
$hx_coprime $hy_coprime $denCert.pf_left $denCert.pf_right)
| _ => failure
/-- `norm_num` extension that proves `Irrational √x` for rational `x`. -/
@[norm_num Irrational (Real.sqrt _)]
def evalIrrationalSqrt : NormNumExt where eval {u α} e := do
let 0 := u | failure
let ~q(Prop) := α | failure
let ~q(Irrational (√$x)) := e | failure
match ← derive x with
| .isNat sℝ ex pf =>
let cert ← findNotPowerCertificate ex q(nat_lit 2)
assumeInstancesCommute
return .isTrue q(irrational_sqrt_nat $pf $cert.pf_left $cert.pf_right)
| .isNNRat sℝ eq en ed pf =>
let ⟨g, pf_coprime⟩ := proveNatGCD en ed
if g.natLit! != 1 then failure
let _ : $g =Q 1 := ⟨⟩
try
let numCert ← findNotPowerCertificate en q(nat_lit 2)
assumeInstancesCommute
return Result.isTrue
q(irrational_sqrt_rat_of_num $pf $pf_coprime $numCert.pf_left $numCert.pf_right)
catch _ =>
let denCert ← findNotPowerCertificate ed q(nat_lit 2)
assumeInstancesCommute
return Result.isTrue
q(irrational_sqrt_rat_of_den $pf $pf_coprime $denCert.pf_left $denCert.pf_right)
| _ => failure
end NormNum
end Tactic |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Prime.lean | import Mathlib.Tactic.NormNum.Basic
import Mathlib.Data.Nat.Prime.Basic
/-!
# `norm_num` extensions on natural numbers
This file provides a `norm_num` extension to prove that natural numbers are prime and compute
its minimal factor. Todo: compute the list of all factors.
## Implementation Notes
For numbers larger than 25 bits, the primality proof produced by `norm_num` is an expression
that is thousands of levels deep, and the Lean kernel seems to raise a stack overflow when
type-checking that proof. If we want an implementation that works for larger primes, we should
generate a proof that has a smaller depth.
Note: `evalMinFac.aux` does not raise a stack overflow, which can be checked by replacing the
`prf'` in the recursive call by something like `(.sort .zero)`
-/
open Nat Qq Lean Meta
namespace Mathlib.Meta.NormNum
theorem not_prime_mul_of_ble (a b n : ℕ) (h : a * b = n) (h₁ : a.ble 1 = false)
(h₂ : b.ble 1 = false) : ¬ n.Prime :=
not_prime_of_mul_eq h (ble_eq_false.mp h₁).ne' (ble_eq_false.mp h₂).ne'
/-- Produce a proof that `n` is not prime from a factor `1 < d < n`. `en` should be the expression
that is the natural number literal `n`. -/
def deriveNotPrime (n d : ℕ) (en : Q(ℕ)) : Q(¬ Nat.Prime $en) := Id.run <| do
let d' : ℕ := n / d
let prf : Q($d * $d' = $en) := (q(Eq.refl $en) : Expr)
let r : Q(Nat.ble $d 1 = false) := (q(Eq.refl false) : Expr)
let r' : Q(Nat.ble $d' 1 = false) := (q(Eq.refl false) : Expr)
return q(not_prime_mul_of_ble _ _ _ $prf $r $r')
/-- A predicate representing partial progress in a proof of `minFac`. -/
def MinFacHelper (n k : ℕ) : Prop :=
2 < k ∧ k % 2 = 1 ∧ k ≤ minFac n
theorem MinFacHelper.one_lt {n k : ℕ} (h : MinFacHelper n k) : 1 < n := by
have : 2 < minFac n := h.1.trans_le h.2.2
obtain rfl | h := n.eq_zero_or_pos
· contradiction
rcases (succ_le_of_lt h).eq_or_lt with rfl | h
· simp_all
exact h
theorem minFacHelper_0 (n : ℕ)
(h1 : Nat.ble (nat_lit 2) n = true) (h2 : nat_lit 1 = n % (nat_lit 2)) :
MinFacHelper n (nat_lit 3) := by
refine ⟨by simp, by simp, ?_⟩
refine (le_minFac'.mpr fun p hp hpn ↦ ?_).resolve_left (Nat.ne_of_gt (Nat.le_of_ble_eq_true h1))
rcases hp.eq_or_lt with rfl | h
· simp [(Nat.dvd_iff_mod_eq_zero ..).1 hpn] at h2
· exact h
theorem minFacHelper_1 {n k k' : ℕ} (e : k + 2 = k') (h : MinFacHelper n k)
(np : minFac n ≠ k) : MinFacHelper n k' := by
rw [← e]
refine ⟨Nat.lt_add_right _ h.1, ?_, ?_⟩
· rw [add_mod, mod_self, add_zero, mod_mod]
exact h.2.1
rcases h.2.2.eq_or_lt with rfl | h2
· exact (np rfl).elim
rcases (succ_le_of_lt h2).eq_or_lt with h2|h2
· refine ((h.1.trans_le h.2.2).ne ?_).elim
have h3 : 2 ∣ minFac n := by
rw [Nat.dvd_iff_mod_eq_zero, ← h2, succ_eq_add_one, add_mod, h.2.1]
rw [dvd_prime <| minFac_prime h.one_lt.ne'] at h3
norm_num at h3
exact h3
exact h2
theorem minFacHelper_2 {n k k' : ℕ} (e : k + 2 = k') (nk : ¬ Nat.Prime k)
(h : MinFacHelper n k) : MinFacHelper n k' := by
refine minFacHelper_1 e h fun h2 ↦ ?_
rw [← h2] at nk
exact nk <| minFac_prime h.one_lt.ne'
theorem minFacHelper_3 {n k k' : ℕ} (e : k + 2 = k') (nk : (n % k).beq 0 = false)
(h : MinFacHelper n k) : MinFacHelper n k' := by
refine minFacHelper_1 e h fun h2 ↦ ?_
have nk := Nat.ne_of_beq_eq_false nk
rw [← Nat.dvd_iff_mod_eq_zero, ← h2] at nk
exact nk <| minFac_dvd n
theorem isNat_minFac_1 : {a : ℕ} → IsNat a (nat_lit 1) → IsNat a.minFac 1
| _, ⟨rfl⟩ => ⟨minFac_one⟩
theorem isNat_minFac_2 : {a a' : ℕ} → IsNat a a' → a' % 2 = 0 → IsNat a.minFac 2
| a, _, ⟨rfl⟩, h => ⟨by rw [cast_ofNat, minFac_eq_two_iff, Nat.dvd_iff_mod_eq_zero, h]⟩
theorem isNat_minFac_3 : {n n' : ℕ} → (k : ℕ) →
IsNat n n' → MinFacHelper n' k → nat_lit 0 = n' % k → IsNat (minFac n) k
| n, _, k, ⟨rfl⟩, h1, h2 => by
rw [eq_comm, ← Nat.dvd_iff_mod_eq_zero] at h2
exact ⟨le_antisymm (minFac_le_of_dvd h1.1.le h2) h1.2.2⟩
theorem isNat_minFac_4 : {n n' k : ℕ} →
IsNat n n' → MinFacHelper n' k → (k * k).ble n' = false → IsNat (minFac n) n'
| n, _, k, ⟨rfl⟩, h1, h2 => by
refine ⟨(Nat.prime_def_minFac.mp ?_).2⟩
rw [Nat.prime_def_le_sqrt]
refine ⟨h1.one_lt, fun m hm hmn h2mn ↦ ?_⟩
exact lt_irrefl m <| calc
m ≤ sqrt n := hmn
_ < k := sqrt_lt.mpr (ble_eq_false.mp h2)
_ ≤ n.minFac := h1.2.2
_ ≤ m := Nat.minFac_le_of_dvd hm h2mn
/-- The `norm_num` extension which identifies expressions of the form `minFac n`. -/
@[norm_num Nat.minFac _] partial def evalMinFac : NormNumExt where eval {_ _} e := do
let .app (.const ``Nat.minFac _) (n : Q(ℕ)) ← whnfR e | failure
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨nn, pn⟩ ← deriveNat n sℕ
let n' := nn.natLit!
let rec aux (ek : Q(ℕ)) (prf : Q(MinFacHelper $nn $ek)) :
(c : Q(ℕ)) × Q(IsNat (Nat.minFac $n) $c) :=
let k := ek.natLit!
-- remark: `deriveBool q($nn < $ek * $ek)` is 2x slower than the following test.
if n' < k * k then
let r : Q(Nat.ble ($ek * $ek) $nn = false) := (q(Eq.refl false) : Expr)
⟨nn, q(isNat_minFac_4 $pn $prf $r)⟩
else
let d : ℕ := k.minFac
-- the following branch is not necessary for the correctness,
-- but makes the algorithm 2x faster
if d < k then
have ek' : Q(ℕ) := mkRawNatLit <| k + 2
let pk' : Q($ek + 2 = $ek') := (q(Eq.refl $ek') : Expr)
let pd := deriveNotPrime k d ek
aux ek' q(minFacHelper_2 $pk' $pd $prf)
-- remark: `deriveBool q($nn % $ek = 0)` is 5x slower than the following test
else if n' % k = 0 then
let r : Q(nat_lit 0 = $nn % $ek) := (q(Eq.refl 0) : Expr)
let r' : Q(IsNat (minFac $n) $ek) := q(isNat_minFac_3 _ $pn $prf $r)
⟨ek, r'⟩
else
let r : Q(Nat.beq ($nn % $ek) 0 = false) := (q(Eq.refl false) : Expr)
have ek' : Q(ℕ) := mkRawNatLit <| k + 2
let pk' : Q($ek + 2 = $ek') := (q(Eq.refl $ek') : Expr)
aux ek' q(minFacHelper_3 $pk' $r $prf)
let rec core : MetaM <| Result q(Nat.minFac $n) := do
if n' = 1 then
let pn : Q(IsNat $n (nat_lit 1)) := pn
return .isNat sℕ q(nat_lit 1) q(isNat_minFac_1 $pn)
if n' % 2 = 0 then
let pq : Q($nn % 2 = 0) := (q(Eq.refl 0) : Expr)
return .isNat sℕ q(nat_lit 2) q(isNat_minFac_2 $pn $pq)
let pp : Q(Nat.ble 2 $nn = true) := (q(Eq.refl true) : Expr)
let pq : Q(1 = $nn % 2) := (q(Eq.refl (nat_lit 1)) : Expr)
let ⟨c, pc⟩ := aux q(nat_lit 3) q(minFacHelper_0 $nn $pp $pq)
return .isNat sℕ c pc
core
theorem isNat_prime_0 : {n : ℕ} → IsNat n (nat_lit 0) → ¬ n.Prime
| _, ⟨rfl⟩ => not_prime_zero
theorem isNat_prime_1 : {n : ℕ} → IsNat n (nat_lit 1) → ¬ n.Prime
| _, ⟨rfl⟩ => not_prime_one
theorem isNat_prime_2 : {n n' : ℕ} →
IsNat n n' → Nat.ble 2 n' = true → IsNat (minFac n') n' → n.Prime
| _, _, ⟨rfl⟩, h1, ⟨h2⟩ => prime_def_minFac.mpr ⟨ble_eq.mp h1, h2⟩
theorem isNat_not_prime {n n' : ℕ} (h : IsNat n n') : ¬n'.Prime → ¬n.Prime := isNat.natElim h
/-- The `norm_num` extension which identifies expressions of the form `Nat.Prime n`. -/
@[norm_num Nat.Prime _] def evalNatPrime : NormNumExt where eval {_ _} e := do
let .app (.const `Nat.Prime _) (n : Q(ℕ)) ← whnfR e | failure
let ⟨nn, pn⟩ ← deriveNat n _
let n' := nn.natLit!
-- note: if `n` is not prime, we don't have to verify the calculation of `n.minFac`, we just have
-- to compute it, which is a lot quicker
let rec core : MetaM (Result q(Nat.Prime $n)) := do
match n' with
| 0 => haveI' : $nn =Q 0 := ⟨⟩; return .isFalse q(isNat_prime_0 $pn)
| 1 => haveI' : $nn =Q 1 := ⟨⟩; return .isFalse q(isNat_prime_1 $pn)
| _ =>
let d := n'.minFac
if d < n' then
let prf : Q(¬ Nat.Prime $nn) := deriveNotPrime n' d nn
return .isFalse q(isNat_not_prime $pn $prf)
let r : Q(Nat.ble 2 $nn = true) := (q(Eq.refl true) : Expr)
let .isNat _ _lit (p2n : Q(IsNat (minFac $nn) $nn)) ←
evalMinFac.core nn _ nn q(.raw_refl _) nn.natLit! | failure
return .isTrue q(isNat_prime_2 $pn $r $p2n)
core
end NormNum
end Meta
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Parity.lean | import Mathlib.Algebra.Ring.Int.Parity
import Mathlib.Tactic.NormNum.Core
/-!
# `norm_num` extensions for `Even` and `Odd`
In this file we provide `norm_num` extensions for `Even n` and `Odd n`,
where `n : ℕ` or `n : ℤ`.
-/
namespace Mathlib.Meta.NormNum
open Qq
/-- `norm_num` extension for `Even`.
Works for `ℕ` and `ℤ`. -/
@[norm_num Even _]
def evalEven : NormNumExt where eval {u αP} e := do
match u, αP, e with
| 0, ~q(Prop), ~q(@Even ℕ _ $a) =>
assertInstancesCommute
let ⟨b, r⟩ ← deriveBoolOfIff q($a % 2 = 0) q(Even $a) q((@Nat.even_iff $a).symm)
return .ofBoolResult r
| 0, ~q(Prop), ~q(@Even ℤ _ $a) =>
assertInstancesCommute
let ⟨b, r⟩ ← deriveBoolOfIff q($a % 2 = 0) q(Even $a) q((@Int.even_iff $a).symm)
return .ofBoolResult r
| _, _, _ => failure
/-- `norm_num` extension for `Odd`.
Works for `ℕ` and `ℤ`. -/
@[norm_num Odd _]
def evalOdd : NormNumExt where eval {u αP} e := do
match u, αP, e with
| 0, ~q(Prop), ~q(@Odd ℕ $inst $a) =>
assertInstancesCommute
let ⟨b, r⟩ ← deriveBoolOfIff q($a % 2 = 1) q(Odd $a) q((@Nat.odd_iff $a).symm)
return .ofBoolResult r
| 0, ~q(Prop), ~q(@Odd ℤ $inst $a) =>
assertInstancesCommute
let ⟨b, r⟩ ← deriveBoolOfIff q($a % 2 = 1) q(Odd $a) q((@Int.odd_iff $a).symm)
return .ofBoolResult r
| _ => failure
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/NatLog.lean | import Mathlib.Data.Nat.Log
import Mathlib.Tactic.NormNum
/-! # `norm_num` extensions for `Nat.log` and `Nat.clog`
This module defines `norm_num` extensions for `Nat.log` and `Nat.clog`.
-/
namespace Mathlib.Meta.NormNum
open Qq Lean Elab.Tactic
private lemma nat_log_zero (n : Nat) : Nat.log 0 n = 0 := Nat.log_zero_left n
private lemma nat_log_one (n : Nat) : Nat.log 1 n = 0 := Nat.log_one_left n
private lemma nat_log_helper0 (b n : Nat) (hl : Nat.blt n b = true) :
Nat.log b n = 0 := by
rw [Nat.blt_eq] at hl
simp [hl]
private lemma nat_log_helper (b n k : Nat)
(hl : Nat.ble (b ^ k) n = true) (hh : Nat.blt n (b ^ (k + 1)) = true) :
Nat.log b n = k :=
Nat.log_eq_of_pow_le_of_lt_pow (Nat.le_of_ble_eq_true hl) (Nat.le_of_ble_eq_true hh)
private theorem isNat_log : {b nb n nn k : ℕ} → IsNat b nb → IsNat n nn →
Nat.log nb nn = k → IsNat (Nat.log b n) k
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩
/--
Given the natural number literals `eb` and `en`, returns `Nat.log eb en`
as a natural number literal and an equality proof.
Panics if `ex` or `en` aren't natural number literals.
-/
def proveNatLog (eb en : Q(ℕ)) : (ek : Q(ℕ)) × Q(Nat.log $eb $en = $ek) :=
match eb.natLit!, en.natLit! with
| 0, _ => have : $eb =Q nat_lit 0 := ⟨⟩; ⟨q(nat_lit 0), q(nat_log_zero $en)⟩
| 1, _ => have : $eb =Q nat_lit 1 := ⟨⟩; ⟨q(nat_lit 0), q(nat_log_one $en)⟩
| b, n =>
if n < b then
have hh : Q(Nat.blt $en $eb = true) := (q(Eq.refl true) : Expr)
⟨q(nat_lit 0), q(nat_log_helper0 $eb $en $hh)⟩
else
let k := Nat.log b n
have ek : Q(ℕ) := mkRawNatLit k
have hl : Q(Nat.ble ($eb ^ $ek) $en = true) := (q(Eq.refl true) : Expr)
have hh : Q(Nat.blt $en ($eb ^ ($ek + 1)) = true) := (q(Eq.refl true) : Expr)
⟨ek, q(nat_log_helper $eb $en $ek $hl $hh)⟩
/--
Evaluates the `Nat.log` function.
-/
@[norm_num Nat.log _ _]
def evalNatLog : NormNumExt where eval {u α} e := do
let mkApp2 _ (b : Q(ℕ)) (n : Q(ℕ)) ← Meta.whnfR e | failure
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨eb, pb⟩ ← deriveNat b sℕ
let ⟨en, pn⟩ ← deriveNat n sℕ
let ⟨ek, pf⟩ := proveNatLog eb en
let pf' : Q(IsNat (Nat.log $b $n) $ek) := q(isNat_log $pb $pn $pf)
return .isNat sℕ ek pf'
private lemma nat_clog_zero_left (b n : Nat) (hb : Nat.ble b 1 = true) :
Nat.clog b n = 0 := Nat.clog_of_left_le_one (Nat.le_of_ble_eq_true hb) n
private lemma nat_clog_zero_right (b n : Nat) (hn : Nat.ble n 1 = true) :
Nat.clog b n = 0 := Nat.clog_of_right_le_one (Nat.le_of_ble_eq_true hn) b
theorem nat_clog_helper {b m n : ℕ} (hb : Nat.blt 1 b = true)
(h₁ : Nat.blt (b ^ m) n = true) (h₂ : Nat.ble n (b ^ (m + 1)) = true) :
Nat.clog b n = m + 1 := by
rw [Nat.blt_eq] at hb
rw [Nat.blt_eq, ← Nat.lt_clog_iff_pow_lt hb] at h₁
rw [Nat.ble_eq, ← Nat.clog_le_iff_le_pow hb] at h₂
cutsat
private theorem isNat_clog : {b nb n nn k : ℕ} → IsNat b nb → IsNat n nn →
Nat.clog nb nn = k → IsNat (Nat.clog b n) k
| _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, rfl => ⟨rfl⟩
/--
Given the natural number literals `eb` and `en`, returns `Nat.clog eb en`
as a natural number literal and an equality proof.
Panics if `ex` or `en` aren't natural number literals.
-/
def proveNatClog (eb en : Q(ℕ)) : (ek : Q(ℕ)) × Q(Nat.clog $eb $en = $ek) :=
let b := eb.natLit!
let n := en.natLit!
if _ : b ≤ 1 then
have h : Q(Nat.ble $eb 1 = true) := reflBoolTrue
⟨q(nat_lit 0), q(nat_clog_zero_left $eb $en $h)⟩
else if _ : n ≤ 1 then
have h : Q(Nat.ble $en 1 = true) := reflBoolTrue
⟨q(nat_lit 0), q(nat_clog_zero_right $eb $en $h)⟩
else
match h : Nat.clog b n with
| 0 => False.elim <|
Nat.ne_of_gt (Nat.clog_pos (by cutsat) (by cutsat)) h
| k + 1 =>
have ek : Q(ℕ) := mkRawNatLit k
have ek1 : Q(ℕ) := mkRawNatLit (k + 1)
have _ : $ek1 =Q $ek + 1 := ⟨⟩
have hb : Q(Nat.blt 1 $eb = true) := reflBoolTrue
have hl : Q(Nat.blt ($eb ^ $ek) $en = true) := reflBoolTrue
have hh : Q(Nat.ble $en ($eb ^ ($ek + 1)) = true) := reflBoolTrue
⟨ek1, q(nat_clog_helper $hb $hl $hh)⟩
/--
Evaluates the `Nat.clog` function.
-/
@[norm_num Nat.clog _ _]
def evalNatClog : NormNumExt where eval {u α} e := do
let mkApp2 _ (b : Q(ℕ)) (n : Q(ℕ)) ← Meta.whnfR e | failure
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨eb, pb⟩ ← deriveNat b sℕ
let ⟨en, pn⟩ ← deriveNat n sℕ
let ⟨ek, pf⟩ := proveNatClog eb en
let pf' : Q(IsNat (Nat.clog $b $n) $ek) := q(isNat_clog $pb $pn $pf)
return .isNat sℕ ek pf'
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/NatFactorial.lean | import Mathlib.Data.Nat.Factorial.Basic
import Mathlib.Tactic.NormNum
/-! # `norm_num` extensions for factorials
Extensions for `norm_num` that compute `Nat.factorial`, `Nat.ascFactorial` and `Nat.descFactorial`.
This is done by reducing each of these to `ascFactorial`, which is computed using a divide and
conquer strategy that improves performance and avoids exceeding the recursion depth.
-/
namespace Mathlib.Meta.NormNum
open Nat Qq Lean Elab.Tactic Meta
lemma asc_factorial_aux (n l m a b : ℕ) (h₁ : n.ascFactorial l = a)
(h₂ : (n + l).ascFactorial m = b) : n.ascFactorial (l + m) = a * b := by
rw [← h₁, ← h₂]
symm
apply ascFactorial_mul_ascFactorial
/-- Calculate `n.ascFactorial l` and return this value along with a proof of the result. -/
partial def proveAscFactorial (n l : ℕ) (en el : Q(ℕ)) :
ℕ × (eresult : Q(ℕ)) × Q(($en).ascFactorial $el = $eresult) :=
if l ≤ 50 then
have res : ℕ := n.ascFactorial l
have eres : Q(ℕ) := mkRawNatLit (n.ascFactorial l)
have : ($en).ascFactorial $el =Q $eres := ⟨⟩
⟨res, eres, q(Eq.refl $eres)⟩
else
have m : ℕ := l / 2
have em : Q(ℕ) := mkRawNatLit m
have : $em =Q $el / 2 := ⟨⟩
have r : ℕ := l - m
have er : Q(ℕ) := mkRawNatLit r
have : $er =Q $el - $em := ⟨⟩
have : $el =Q ($em + $er) := ⟨⟩
have nm : ℕ := n + m
have enm : Q(ℕ) := mkRawNatLit nm
have : $enm =Q $en + $em := ⟨⟩
let ⟨a, ea, a_prf⟩ := proveAscFactorial n m en em
let ⟨b, eb, b_prf⟩ := proveAscFactorial (n + m) r enm er
have eab : Q(ℕ) := mkRawNatLit (a * b)
have : $eab =Q $ea * $eb := ⟨⟩
⟨a * b, eab, q(by convert asc_factorial_aux $en $em $er $ea $eb $a_prf $b_prf)⟩
lemma isNat_factorial {n x : ℕ} (h₁ : IsNat n x) (a : ℕ) (h₂ : (1).ascFactorial x = a) :
IsNat (n !) a := by
constructor
simp only [h₁.out, cast_id, ← h₂, one_ascFactorial]
/-- Evaluates the `Nat.factorial` function. -/
@[nolint unusedHavesSuffices, norm_num Nat.factorial _]
def evalNatFactorial : NormNumExt where eval {u α} e := do
let .app _ (x : Q(ℕ)) ← Meta.whnfR e | failure
have : u =QL 0 := ⟨⟩; have : $α =Q ℕ := ⟨⟩; have : $e =Q Nat.factorial $x := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨ex, p⟩ ← deriveNat x sℕ
let ⟨_, val, ascPrf⟩ := proveAscFactorial 1 ex.natLit! q(nat_lit 1) ex
return .isNat sℕ q($val) q(isNat_factorial $p $val $ascPrf)
lemma isNat_ascFactorial {n x l y : ℕ} (h₁ : IsNat n x) (h₂ : IsNat l y) (a : ℕ)
(p : x.ascFactorial y = a) : IsNat (n.ascFactorial l) a := by
constructor
simp [h₁.out, h₂.out, ← p]
/-- Evaluates the Nat.ascFactorial function. -/
@[nolint unusedHavesSuffices, norm_num Nat.ascFactorial _ _]
def evalNatAscFactorial : NormNumExt where eval {u α} e := do
let .app (.app _ (x : Q(ℕ))) (y : Q(ℕ)) ← Meta.whnfR e | failure
have : u =QL 0 := ⟨⟩; have : $α =Q ℕ := ⟨⟩; have : $e =Q Nat.ascFactorial $x $y := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨ex₁, p₁⟩ ← deriveNat x sℕ
let ⟨ex₂, p₂⟩ ← deriveNat y sℕ
let ⟨_, val, ascPrf⟩ := proveAscFactorial ex₁.natLit! ex₂.natLit! ex₁ ex₂
return .isNat sℕ q($val) q(isNat_ascFactorial $p₁ $p₂ $val $ascPrf)
lemma isNat_descFactorial {n x l y : ℕ} (z : ℕ) (h₁ : IsNat n x) (h₂ : IsNat l y)
(h₃ : x = z + y) (a : ℕ) (p : (z + 1).ascFactorial y = a) : IsNat (n.descFactorial l) a := by
constructor
simpa [h₁.out, h₂.out, ← p, h₃] using Nat.add_descFactorial_eq_ascFactorial _ _
lemma isNat_descFactorial_zero {n x l y : ℕ} (z : ℕ) (h₁ : IsNat n x) (h₂ : IsNat l y)
(h₃ : y = z + x + 1) : IsNat (n.descFactorial l) 0 := by
constructor
simp [h₁.out, h₂.out, h₃]
private partial def evalNatDescFactorialNotZero {x' y' : Q(ℕ)} (x y z : Q(ℕ))
(_hx : $x =Q $z + $y)
(px : Q(IsNat $x' $x)) (py : Q(IsNat $y' $y)) :
(n : Q(ℕ)) × Q(IsNat (descFactorial $x' $y') $n) :=
have zp1 :Q(ℕ) := mkRawNatLit (z.natLit! + 1)
have : $zp1 =Q $z + 1 := ⟨⟩
let ⟨_, val, ascPrf⟩ := proveAscFactorial (z.natLit! + 1) y.natLit! zp1 y
⟨val, q(isNat_descFactorial $z $px $py rfl $val $ascPrf)⟩
private partial def evalNatDescFactorialZero {x' y' : Q(ℕ)} (x y z : Q(ℕ))
(_hy : $y =Q $z + $x + 1)
(px : Q(IsNat $x' $x)) (py : Q(IsNat $y' $y)) :
(n : Q(ℕ)) × Q(IsNat (descFactorial $x' $y') $n) :=
⟨q(nat_lit 0), q(isNat_descFactorial_zero $z $px $py rfl)⟩
/-- Evaluates the `Nat.descFactorial` function. -/
@[nolint unusedHavesSuffices, norm_num Nat.descFactorial _ _]
def evalNatDescFactorial : NormNumExt where eval {u α} e := do
let .app (.app _ (x' : Q(ℕ))) (y' : Q(ℕ)) ← Meta.whnfR e | failure
have : u =QL 0 := ⟨⟩
have : $α =Q ℕ := ⟨⟩
have : $e =Q Nat.descFactorial $x' $y' := ⟨⟩
let sℕ : Q(AddMonoidWithOne ℕ) := q(instAddMonoidWithOneNat)
let ⟨x, p₁⟩ ← deriveNat x' sℕ
let ⟨y, p₂⟩ ← deriveNat y' sℕ
if x.natLit! ≥ y.natLit! then
have z : Q(ℕ) := mkRawNatLit (x.natLit! - y.natLit!)
have : $x =Q $z + $y := ⟨⟩
let ⟨val, prf⟩ := evalNatDescFactorialNotZero (x' := x') (y' := y') x y z ‹_› p₁ p₂
return .isNat sℕ val q($prf)
else
have z : Q(ℕ) := mkRawNatLit (y.natLit! - x.natLit! - 1)
have : $y =Q $z + $x + 1 := ⟨⟩
let ⟨val, prf⟩ := evalNatDescFactorialZero (x' := x') (y' := y') x y z ‹_› p₁ p₂
return .isNat sℕ val q($prf)
end NormNum
end Meta
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Abs.lean | import Mathlib.Tactic.NormNum.Basic
import Mathlib.Data.Nat.Cast.Order.Ring
/-!
# `norm_num` plugin for `abs`
TODO: plugins for `mabs`, `norm`, `nnorm`, and `enorm`.
-/
namespace Mathlib.Meta.NormNum
open Lean.Meta Qq
theorem isNat_abs_nonneg {α : Type*} [Ring α] [Lattice α] [IsOrderedRing α]
{a : α} {na : ℕ} (pa : IsNat a na) : IsNat |a| na := by
rw [pa.out, Nat.abs_cast]
constructor
rfl
theorem isNat_abs_neg {α : Type*} [Ring α] [Lattice α] [IsOrderedRing α]
{a : α} {na : ℕ} (pa : IsInt a (.negOfNat na)) : IsNat |a| na := by
rw [pa.out]
constructor
simp
theorem isNNRat_abs_nonneg {α : Type*} [DivisionRing α] [LinearOrder α]
[IsStrictOrderedRing α] {a : α} {num den : ℕ} (ra : IsNNRat a num den) :
IsNNRat |a| num den := by
obtain ⟨ha1, rfl⟩ := ra
refine ⟨ha1, abs_of_nonneg ?_⟩
apply mul_nonneg
· exact Nat.cast_nonneg' num
· simp only [invOf_eq_inv, inv_nonneg, Nat.cast_nonneg]
theorem isNNRat_abs_neg {α : Type*} [DivisionRing α] [LinearOrder α] [IsStrictOrderedRing α]
{a : α} {num den : ℕ} (ra : IsRat a (.negOfNat num) den) : IsNNRat |a| num den := by
obtain ⟨ha1, rfl⟩ := ra
simp only [Int.cast_negOfNat, neg_mul, abs_neg]
refine ⟨ha1, abs_of_nonneg ?_⟩
apply mul_nonneg
· exact Nat.cast_nonneg' num
· simp only [invOf_eq_inv, inv_nonneg, Nat.cast_nonneg]
/-- The `norm_num` extension which identifies expressions of the form `|a|`,
such that `norm_num` successfully recognises `a`. -/
@[norm_num |_|] def evalAbs : NormNumExt where eval {u α}
| ~q(@abs _ $instLattice $instAddGroup $a) => do
match ← derive a with
| .isBool .. => failure
| .isNat sα na pa =>
let rα : Q(Ring $α) ← synthInstanceQ q(Ring $α)
let iorα : Q(IsOrderedRing $α) ← synthInstanceQ q(IsOrderedRing $α)
assumeInstancesCommute
return .isNat sα na q(isNat_abs_nonneg $pa)
| .isNegNat sα na pa =>
let rα : Q(Ring $α) ← synthInstanceQ q(Ring $α)
let iorα : Q(IsOrderedRing $α) ← synthInstanceQ q(IsOrderedRing $α)
assumeInstancesCommute
return .isNat _ _ q(isNat_abs_neg $pa)
| .isNNRat dsα' qe' nume' dene' pe' =>
let rα : Q(DivisionRing $α) ← synthInstanceQ q(DivisionRing $α)
let loα : Q(LinearOrder $α) ← synthInstanceQ q(LinearOrder $α)
let isorα : Q(IsStrictOrderedRing $α) ← synthInstanceQ q(IsStrictOrderedRing $α)
assumeInstancesCommute
return .isNNRat _ qe' _ _ q(isNNRat_abs_nonneg $pe')
| .isNegNNRat dα' qe' nume' dene' pe' =>
let loα : Q(LinearOrder $α) ← synthInstanceQ q(LinearOrder $α)
let isorα : Q(IsStrictOrderedRing $α) ← synthInstanceQ q(IsStrictOrderedRing $α)
assumeInstancesCommute
return .isNNRat _ (-qe') _ _ q(isNNRat_abs_neg $pe')
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/NormNum/Inv.lean | import Mathlib.Tactic.NormNum.Basic
import Mathlib.Data.Rat.Cast.CharZero
import Mathlib.Algebra.Field.Basic
/-!
# `norm_num` plugins for `Rat.cast` and `⁻¹`.
-/
variable {u : Lean.Level}
namespace Mathlib.Meta.NormNum
open Lean.Meta Qq
/-- Helper function to synthesize a typed `CharZero α` expression given `Ring α`. -/
def inferCharZeroOfRing {α : Q(Type u)} (_i : Q(Ring $α) := by with_reducible assumption) :
MetaM Q(CharZero $α) :=
return ← synthInstanceQ q(CharZero $α) <|>
throwError "not a characteristic zero ring"
/-- Helper function to synthesize a typed `CharZero α` expression given `Ring α`, if it exists. -/
def inferCharZeroOfRing? {α : Q(Type u)} (_i : Q(Ring $α) := by with_reducible assumption) :
MetaM (Option Q(CharZero $α)) :=
return (← trySynthInstanceQ q(CharZero $α)).toOption
/-- Helper function to synthesize a typed `CharZero α` expression given `AddMonoidWithOne α`. -/
def inferCharZeroOfAddMonoidWithOne {α : Q(Type u)}
(_i : Q(AddMonoidWithOne $α) := by with_reducible assumption) : MetaM Q(CharZero $α) :=
return ← synthInstanceQ q(CharZero $α) <|>
throwError "not a characteristic zero AddMonoidWithOne"
/-- Helper function to synthesize a typed `CharZero α` expression given `AddMonoidWithOne α`, if it
exists. -/
def inferCharZeroOfAddMonoidWithOne? {α : Q(Type u)}
(_i : Q(AddMonoidWithOne $α) := by with_reducible assumption) :
MetaM (Option Q(CharZero $α)) :=
return (← trySynthInstanceQ q(CharZero $α)).toOption
/-- Helper function to synthesize a typed `CharZero α` expression given `DivisionRing α`. -/
def inferCharZeroOfDivisionRing {α : Q(Type u)}
(_i : Q(DivisionRing $α) := by with_reducible assumption) : MetaM Q(CharZero $α) :=
return ← synthInstanceQ q(CharZero $α) <|>
throwError "not a characteristic zero division ring"
/-- Helper function to synthesize a typed `CharZero α` expression given `Divisionsemiring α`, if it
exists. -/
def inferCharZeroOfDivisionSemiring? {α : Q(Type u)}
(_i : Q(DivisionSemiring $α) := by with_reducible assumption) : MetaM (Option Q(CharZero $α)) :=
return (← trySynthInstanceQ (q(CharZero $α) : Q(Prop))).toOption
/-- Helper function to synthesize a typed `CharZero α` expression given `DivisionRing α`, if it
exists. -/
def inferCharZeroOfDivisionRing? {α : Q(Type u)}
(_i : Q(DivisionRing $α) := by with_reducible assumption) : MetaM (Option Q(CharZero $α)) :=
return (← trySynthInstanceQ q(CharZero $α)).toOption
theorem isRat_mkRat : {a na n : ℤ} → {b nb d : ℕ} → IsInt a na → IsNat b nb →
IsRat (na / nb : ℚ) n d → IsRat (mkRat a b) n d
| _, _, _, _, _, _, ⟨rfl⟩, ⟨rfl⟩, ⟨_, h⟩ => by rw [Rat.mkRat_eq_div]; exact ⟨_, h⟩
attribute [local instance] monadLiftOptionMetaM in
/-- The `norm_num` extension which identifies expressions of the form `mkRat a b`,
such that `norm_num` successfully recognises both `a` and `b`, and returns `a / b`. -/
@[norm_num mkRat _ _]
def evalMkRat : NormNumExt where eval {u α} (e : Q(ℚ)) : MetaM (Result e) := do
let .app (.app (.const ``mkRat _) (a : Q(ℤ))) (b : Q(ℕ)) ← whnfR e | failure
haveI' : $e =Q mkRat $a $b := ⟨⟩
let ra ← derive a
let some ⟨_, na, pa⟩ := ra.toInt (q(Int.instRing) : Q(Ring Int)) | failure
let ⟨nb, pb⟩ ← deriveNat q($b) q(AddCommMonoidWithOne.toAddMonoidWithOne)
let rab ← derive q($na / $nb : Rat)
let ⟨q, n, d, p⟩ ← rab.toRat' q(Rat.instDivisionRing)
return .isRat _ q n d q(isRat_mkRat $pa $pb $p)
theorem isNat_ratCast {R : Type*} [DivisionRing R] : {q : ℚ} → {n : ℕ} →
IsNat q n → IsNat (q : R) n
| _, _, ⟨rfl⟩ => ⟨by simp⟩
theorem isInt_ratCast {R : Type*} [DivisionRing R] : {q : ℚ} → {n : ℤ} →
IsInt q n → IsInt (q : R) n
| _, _, ⟨rfl⟩ => ⟨by simp⟩
theorem isNNRat_ratCast {R : Type*} [DivisionRing R] [CharZero R] : {q : ℚ} → {n : ℕ} → {d : ℕ} →
IsNNRat q n d → IsNNRat (q : R) n d
| _, _, _, ⟨⟨qi,_,_⟩, rfl⟩ => ⟨⟨qi, by norm_cast, by norm_cast⟩, by simp only; norm_cast⟩
theorem isRat_ratCast {R : Type*} [DivisionRing R] [CharZero R] : {q : ℚ} → {n : ℤ} → {d : ℕ} →
IsRat q n d → IsRat (q : R) n d
| _, _, _, ⟨⟨qi,_,_⟩, rfl⟩ => ⟨⟨qi, by norm_cast, by norm_cast⟩, by simp only; norm_cast⟩
/-- The `norm_num` extension which identifies an expression `RatCast.ratCast q` where `norm_num`
recognizes `q`, returning the cast of `q`. -/
@[norm_num Rat.cast _, RatCast.ratCast _] def evalRatCast : NormNumExt where eval {u α} e := do
let dα ← inferDivisionRing α
let .app r (a : Q(ℚ)) ← whnfR e | failure
guard <|← withNewMCtxDepth <| isDefEq r q(Rat.cast (K := $α))
let r ← derive q($a)
haveI' : $e =Q Rat.cast $a := ⟨⟩
match r with
| .isNat _ na pa =>
assumeInstancesCommute
return .isNat _ na q(isNat_ratCast $pa)
| .isNegNat _ na pa =>
assumeInstancesCommute
return .isNegNat _ na q(isInt_ratCast $pa)
| .isNNRat _ qa na da pa =>
assumeInstancesCommute
let i ← inferCharZeroOfDivisionRing dα
return .isNNRat q(inferInstance) qa na da q(isNNRat_ratCast $pa)
| .isNegNNRat _ qa na da pa =>
assumeInstancesCommute
let i ← inferCharZeroOfDivisionRing dα
return .isNegNNRat dα qa na da q(isRat_ratCast $pa)
| _ => failure
theorem isNNRat_inv_pos {α} [DivisionSemiring α] [CharZero α] {a : α} {n d : ℕ} :
IsNNRat a (Nat.succ n) d → IsNNRat a⁻¹ d (Nat.succ n) := by
rintro ⟨_, rfl⟩
have := invertibleOfNonzero (α := α) (Nat.cast_ne_zero.2 (Nat.succ_ne_zero n))
exact ⟨this, by simp⟩
theorem isRat_inv_pos {α} [DivisionRing α] [CharZero α] {a : α} {n d : ℕ} :
IsRat a (.ofNat (Nat.succ n)) d → IsRat a⁻¹ (.ofNat d) (Nat.succ n) := by
rintro ⟨_, rfl⟩
have := invertibleOfNonzero (α := α) (Nat.cast_ne_zero.2 (Nat.succ_ne_zero n))
exact ⟨this, by simp⟩
theorem isNat_inv_one {α} [DivisionSemiring α] : {a : α} →
IsNat a (nat_lit 1) → IsNat a⁻¹ (nat_lit 1)
| _, ⟨rfl⟩ => ⟨by simp⟩
theorem isNat_inv_zero {α} [DivisionSemiring α] : {a : α} →
IsNat a (nat_lit 0) → IsNat a⁻¹ (nat_lit 0)
| _, ⟨rfl⟩ => ⟨by simp⟩
theorem isInt_inv_neg_one {α} [DivisionRing α] : {a : α} →
IsInt a (.negOfNat (nat_lit 1)) → IsInt a⁻¹ (.negOfNat (nat_lit 1))
| _, ⟨rfl⟩ => ⟨by simp⟩
theorem isRat_inv_neg {α} [DivisionRing α] [CharZero α] {a : α} {n d : ℕ} :
IsRat a (.negOfNat (Nat.succ n)) d → IsRat a⁻¹ (.negOfNat d) (Nat.succ n) := by
rintro ⟨_, rfl⟩
simp only [Int.negOfNat_eq]
have := invertibleOfNonzero (α := α) (Nat.cast_ne_zero.2 (Nat.succ_ne_zero n))
generalize Nat.succ n = n at *
use this; simp only [Int.ofNat_eq_coe, Int.cast_neg,
Int.cast_natCast, invOf_eq_inv, inv_neg, neg_mul, mul_inv_rev, inv_inv]
open Lean
attribute [local instance] monadLiftOptionMetaM in
/-- The result of inverting a norm_num result. -/
def Result.inv {u : Level} {α : Q(Type u)} {a : Q($α)} (ra : Result a)
(dsα : Q(DivisionSemiring $α)) (czα? : Option Q(CharZero $α)) :
MetaM (Result q($a⁻¹)) := do
if let .some ⟨qa, na, da, pa⟩ := ra.toNNRat' dsα then
let qb := qa⁻¹
if qa > 0 then
if let some _i := czα? then
have lit2 : Q(ℕ) := mkRawNatLit (na.natLit! - 1)
haveI : $na =Q ($lit2).succ := ⟨⟩
return .isNNRat' dsα qb q($da) q($na) q(isNNRat_inv_pos $pa)
else
guard (qa = 1)
let .isNat inst n pa := ra | failure
haveI' : $n =Q nat_lit 1 := ⟨⟩
assumeInstancesCommute
return .isNat inst n q(isNat_inv_one $pa)
else
let .isNat inst n pa := ra | failure
haveI' : $n =Q nat_lit 0 := ⟨⟩
assumeInstancesCommute
return .isNat inst n q(isNat_inv_zero $pa)
else
let dα ← inferDivisionRing α
assertInstancesCommute
let ⟨qa, na, da, pa⟩ ← ra.toRat' dα
let qb := qa⁻¹
guard <| qa < 0
if let some _i := czα? then
have lit : Q(ℕ) := na.appArg!
haveI : $na =Q Int.negOfNat $lit := ⟨⟩
have lit2 : Q(ℕ) := mkRawNatLit (lit.natLit! - 1)
haveI : $lit =Q ($lit2).succ := ⟨⟩
return .isRat dα qb q(.negOfNat $da) lit q(isRat_inv_neg $pa)
else
guard (qa = -1)
let .isNegNat inst n pa := ra | failure
haveI' : $n =Q nat_lit 1 := ⟨⟩
assumeInstancesCommute
return .isNegNat inst n q(isInt_inv_neg_one $pa)
/-- The `norm_num` extension which identifies expressions of the form `a⁻¹`,
such that `norm_num` successfully recognises `a`. -/
@[norm_num _⁻¹] def evalInv : NormNumExt where eval {u α} e := do
let .app f (a : Q($α)) ← whnfR e | failure
let ra ← derive a
let dsα ← inferDivisionSemiring α
guard <| ← withNewMCtxDepth <| isDefEq f q(Inv.inv (α := $α))
haveI' : $e =Q $a⁻¹ := ⟨⟩
assumeInstancesCommute
ra.inv q($dsα) (← inferCharZeroOfDivisionSemiring? dsα)
end Mathlib.Meta.NormNum |
.lake/packages/mathlib/Mathlib/Tactic/Nontriviality/Core.lean | import Qq.MetaM
import Mathlib.Logic.Nontrivial.Basic
import Mathlib.Tactic.Attr.Core
/-! # The `nontriviality` tactic. -/
universe u
namespace Mathlib.Tactic.Nontriviality
open Lean Elab Meta Tactic Qq
theorem subsingleton_or_nontrivial_elim {p : Prop} {α : Type u}
(h₁ : Subsingleton α → p) (h₂ : Nontrivial α → p) : p :=
(subsingleton_or_nontrivial α).elim @h₁ @h₂
/--
Tries to generate a `Nontrivial α` instance by performing case analysis on
`subsingleton_or_nontrivial α`,
attempting to discharge the subsingleton branch using lemmas with `@[nontriviality]` attribute,
including `Subsingleton.le` and `eq_iff_true_of_subsingleton`.
-/
def nontrivialityByElim {u : Level} (α : Q(Type u)) (g : MVarId) (simpArgs : Array Syntax) :
MetaM MVarId := do
let p : Q(Prop) ← g.getType
guard (← instantiateMVars (← inferType p)).isProp
g.withContext do
let g₁ ← mkFreshExprMVarQ q(Subsingleton $α → $p)
let (_, g₁') ← g₁.mvarId!.intro1
g₁'.withContext try
-- FIXME: restore after https://github.com/leanprover/lean4/issues/2054 is fixed
-- g₁'.inferInstance <|> do
(do g₁'.assign (← synthInstance (← g₁'.getType))) <|> do
let simpArgs := simpArgs.push (Unhygienic.run `(Parser.Tactic.simpLemma| nontriviality))
let stx := open TSyntax.Compat in Unhygienic.run `(tactic| simp [$simpArgs,*])
let ([], _) ← runTactic g₁' stx | failure
catch _ => throwError
"Could not prove goal assuming `{q(Subsingleton $α)}`\n{MessageData.ofGoal g₁'}"
let g₂ : Q(Nontrivial $α → $p) ← mkFreshExprMVarQ q(Nontrivial $α → $p)
g.assign q(subsingleton_or_nontrivial_elim $g₁ $g₂)
pure g₂.mvarId!
open Lean.Elab.Tactic.SolveByElim in
/--
Tries to generate a `Nontrivial α` instance using `nontrivial_of_ne` or `nontrivial_of_lt`
and local hypotheses.
-/
def nontrivialityByAssumption (g : MVarId) : MetaM Unit := do
g.inferInstance <|> do
_ ← processSyntax {maxDepth := 6}
false false [← `(nontrivial_of_ne), ← `(nontrivial_of_lt)] [] #[] [g]
/-- Attempts to generate a `Nontrivial α` hypothesis.
The tactic first checks to see that there is not already a `Nontrivial α` instance
before trying to synthesize one using other techniques.
If the goal is an (in)equality, the type `α` is inferred from the goal.
Otherwise, the type needs to be specified in the tactic invocation, as `nontriviality α`.
The `nontriviality` tactic will first look for strict inequalities amongst the hypotheses,
and use these to derive the `Nontrivial` instance directly.
Otherwise, it will perform a case split on `Subsingleton α ∨ Nontrivial α`, and attempt to discharge
the `Subsingleton` goal using `simp [h₁, h₂, ..., hₙ, nontriviality]`, where `[h₁, h₂, ..., hₙ]` is
a list of additional `simp` lemmas that can be passed to `nontriviality` using the syntax
`nontriviality α using h₁, h₂, ..., hₙ`.
```
example {R : Type} [OrderedRing R] {a : R} (h : 0 < a) : 0 < a := by
nontriviality -- There is now a `Nontrivial R` hypothesis available.
assumption
```
```
example {R : Type} [CommRing R] {r s : R} : r * s = s * r := by
nontriviality -- There is now a `Nontrivial R` hypothesis available.
apply mul_comm
```
```
example {R : Type} [OrderedRing R] {a : R} (h : 0 < a) : (2 : ℕ) ∣ 4 := by
nontriviality R -- there is now a `Nontrivial R` hypothesis available.
dec_trivial
```
```
def myeq {α : Type} (a b : α) : Prop := a = b
example {α : Type} (a b : α) (h : a = b) : myeq a b := by
success_if_fail nontriviality α -- Fails
nontriviality α using myeq -- There is now a `Nontrivial α` hypothesis available
assumption
```
-/
syntax (name := nontriviality) "nontriviality" (ppSpace colGt term)?
(" using " Parser.Tactic.simpArg,+)? : tactic
/-- Elaborator for the `nontriviality` tactic. -/
@[tactic nontriviality] def elabNontriviality : Tactic := fun stx => do
let g ← getMainGoal
let α ← match stx[1].getOptional? with
| some e => Term.elabType e
| none => (do
let mut tgt ← withReducible g.getType'
if let some tgt' := tgt.not? then tgt ← withReducible (whnf tgt')
if let some (α, _) := tgt.eq? then return α
if let some (α, _) := tgt.app4? ``LE.le then return α
if let some (α, _) := tgt.app4? ``LT.lt then return α
throwError "The goal is not an (in)equality, so you'll need to specify the desired \
`Nontrivial α` instance by invoking `nontriviality α`.")
let .sort u ← whnf (← inferType α) | unreachable!
let some v := u.dec | throwError "not a type{indentExpr α}"
let α : Q(Type v) := α
let tac := do
let ty := q(Nontrivial $α)
let m ← mkFreshExprMVar (some ty)
nontrivialityByAssumption m.mvarId!
g.assert `inst ty m
let g ← liftM <| tac <|> nontrivialityByElim α g stx[2][1].getSepArgs
replaceMainGoal [(← g.intro1).2]
end Nontriviality
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/Core.lean | import Mathlib.Tactic.FunProp.Theorems
import Mathlib.Tactic.FunProp.ToBatteries
import Mathlib.Tactic.FunProp.Types
import Mathlib.Lean.Expr.Basic
import Batteries.Tactic.Exact
/-!
# Tactic `fun_prop` for proving function properties like `Continuous f`, `Differentiable ℝ f`, ...
-/
namespace Mathlib
open Lean Meta Qq
namespace Meta.FunProp
/-- Synthesize instance of type `type` and
1. assign it to `x` if `x` is meta variable
2. check it is equal to `x` -/
def synthesizeInstance (thmId : Origin) (x type : Expr) : MetaM Bool := do
match (← trySynthInstance type) with
| .some val =>
if (← withReducibleAndInstances <| isDefEq x val) then
return true
else
trace[Meta.Tactic.fun_prop]
"{← ppOrigin thmId}, failed to assign instance{indentExpr type}
synthesized value{indentExpr val}\nis not definitionally equal to{indentExpr x}"
return false
| _ =>
trace[Meta.Tactic.fun_prop]
"{← ppOrigin thmId}, failed to synthesize instance{indentExpr type}"
return false
/-- Synthesize arguments `xs` either with typeclass synthesis, with `fun_prop` or with
discharger. -/
def synthesizeArgs (thmId : Origin) (xs : Array Expr)
(funProp : Expr → FunPropM (Option Result)) :
FunPropM Bool := do
let mut postponed : Array Expr := #[]
for x in xs do
let type ← inferType x
if (← instantiateMVars x).isMVar then
-- try type class
if (← isClass? type).isSome then
if (← synthesizeInstance thmId x type) then
continue
else if (← isFunPropGoal type) then
-- try function property
if let some ⟨proof⟩ ← funProp type then
if (← isDefEq x proof) then
continue
else do
trace[Meta.Tactic.fun_prop]
"{← ppOrigin thmId}, failed to assign proof{indentExpr type}"
return false
else
-- try user provided discharger
let ctx : Context ← read
if (← isProp type) then
if let some proof ← ctx.disch type then
if (← isDefEq x proof) then
continue
else do
trace[Meta.Tactic.fun_prop]
"{← ppOrigin thmId}, failed to assign proof{indentExpr type}"
return false
else
logError s!"Failed to prove necessary assumption `{← ppExpr type}` \
when applying theorem `{← ppOrigin' thmId}`."
if ¬(← isProp type) then
postponed := postponed.push x
continue
else
trace[Meta.Tactic.fun_prop]
"{← ppOrigin thmId}, failed to discharge hypotheses{indentExpr type}"
return false
for x in postponed do
if (← instantiateMVars x).isMVar then
logError s!"Failed to infer `({← ppExpr x} : {← ppExpr (← inferType x)})` \
when applying theorem `{← ppOrigin' thmId}`."
trace[Meta.Tactic.fun_prop]
"{← ppOrigin thmId}, failed to infer `({← ppExpr x} : {← ppExpr (← inferType x)})`"
return false
return true
/-- Try to apply theorem - core function -/
def tryTheoremCore (xs : Array Expr) (val : Expr) (type : Expr) (e : Expr)
(thmId : Origin) (funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
withTraceNode `Meta.Tactic.fun_prop
(fun r => return s!"[{ExceptToEmoji.toEmoji r}] applying: {← ppOrigin' thmId}") do
if (← isDefEq type e) then
if ¬(← synthesizeArgs thmId xs funProp) then
return none
let proof ← instantiateMVars (mkAppN val xs)
return some { proof := proof }
else
trace[Meta.Tactic.fun_prop] "failed to unify {← ppOrigin thmId}\n{type}\nwith\n{e}"
return none
/-- Try to apply a theorem provided some of the theorem arguments. -/
def tryTheoremWithHint? (e : Expr) (thmOrigin : Origin)
(hint : Array (Nat × Expr))
(funProp : Expr → FunPropM (Option Result)) (newMCtxDepth : Bool := false) :
FunPropM (Option Result) := do
let go : FunPropM (Option Result) := do
let thmProof ← thmOrigin.getValue
let type ← inferType thmProof
let (xs, _, type) ← forallMetaTelescope type
for (i,x) in hint do
try
for (id,v) in hint do
xs[id]!.mvarId!.assignIfDefEq v
catch _ =>
trace[Debug.Meta.Tactic.fun_prop]
"failed to use hint {i} `{← ppExpr x} when applying theorem {← ppOrigin thmOrigin}"
tryTheoremCore xs thmProof type e thmOrigin funProp
-- `simp` introduces new meta variable context depth for some reason
-- This is probably to avoid mvar assignment when trying a theorem fails
--
-- However, in `fun_prop` case this is not completely desirable
-- For example, I want to be able to solve a goal with mvars like `ContDiff ℝ ?n f` using local
-- hypothesis `(h : ContDiff ℝ ∞ f)` and assign `∞` to the mvar `?n`.
--
-- This could be problematic if there are two local hypothesis `(hinf : ContDiff ℝ ∞ f)` and
-- `(h1 : ContDiff ℝ 1 f)` and apart from solving `ContDiff ℝ ?n f` there is also a subgoal
-- `2 ≤ ?n`. If `fun_prop` decides to try `h1` first it would assign `1` to `?n` and then there
-- is no hope solving `2 ≤ 1` and it won't be able to apply `hinf` after trying `h1` as `n?` is
-- assigned already. Ideally `fun_prop` would roll back the `MetaM.State`. This issue did not
-- come up yet so I didn't bother and I'm worried about the performance impact.
if newMCtxDepth then
withNewMCtxDepth go
else
go
/-- Try to apply a theorem `thmOrigin` to the goal `e`. -/
def tryTheorem? (e : Expr) (thmOrigin : Origin) (funProp : Expr → FunPropM (Option Result))
(newMCtxDepth : Bool := false) : FunPropM (Option Result) :=
tryTheoremWithHint? e thmOrigin #[] funProp newMCtxDepth
/--
Try to prove `e` using the *identity lambda theorem*.
For example, `e = q(Continuous fun x => x)` and `funPropDecl` is `FunPropDecl` for `Continuous`.
-/
def applyIdRule (funPropDecl : FunPropDecl) (e : Expr)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
let thms ← getLambdaTheorems funPropDecl.funPropName .id
if thms.size = 0 then
let msg := s!"missing identity rule to prove `{← ppExpr e}`"
logError msg
trace[Meta.Tactic.fun_prop] msg
return none
for thm in thms do
if let some r ← tryTheoremWithHint? e (.decl thm.thmName) #[] funProp then
return r
return none
/--
Try to prove `e` using the *constant lambda theorem*.
For example, `e = q(Continuous fun x => y)` and `funPropDecl` is `FunPropDecl` for `Continuous`.
-/
def applyConstRule (funPropDecl : FunPropDecl) (e : Expr)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
let thms ← getLambdaTheorems funPropDecl.funPropName .const
if thms.size = 0 then
let msg := s!"missing constant rule to prove `{← ppExpr e}`"
logError msg
trace[Meta.Tactic.fun_prop] msg
return none
for thm in thms do
let .const := thm.thmArgs | return none
if let some r ← tryTheorem? e (.decl thm.thmName) funProp then
return r
return none
/--
Try to prove `e` using the *apply lambda theorem*.
For example, `e = q(Continuous fun f => f x)` and `funPropDecl` is `FunPropDecl` for `Continuous`.
-/
def applyApplyRule (funPropDecl : FunPropDecl) (e : Expr)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
let thms := (← getLambdaTheorems funPropDecl.funPropName .apply)
for thm in thms do
if let some r ← tryTheoremWithHint? e (.decl thm.thmName) #[] funProp then
return r
return none
/--
Try to prove `e` using *composition lambda theorem*.
For example, `e = q(Continuous fun x => f (g x))` and `funPropDecl` is `FunPropDecl` for
`Continuous`
You also have to provide the functions `f` and `g`. -/
def applyCompRule (funPropDecl : FunPropDecl) (e f g : Expr)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
let thms ← getLambdaTheorems funPropDecl.funPropName .comp
if thms.size = 0 then
let msg := s!"missing composition rule to prove `{← ppExpr e}`"
logError msg
trace[Meta.Tactic.fun_prop] msg
return none
for thm in thms do
let .comp id_f id_g := thm.thmArgs | return none
if let some r ← tryTheoremWithHint? e (.decl thm.thmName) #[(id_f, f), (id_g, g)] funProp then
return r
return none
/--
Try to prove `e` using *pi lambda theorem*.
For example, `e = q(Continuous fun x y => f x y)` and `funPropDecl` is `FunPropDecl` for
`Continuous`
-/
def applyPiRule (funPropDecl : FunPropDecl) (e : Expr)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
let thms ← getLambdaTheorems funPropDecl.funPropName .pi
if thms.size = 0 then
let msg := s!"missing pi rule to prove `{← ppExpr e}`"
logError msg
trace[Meta.Tactic.fun_prop] msg
return none
for thm in thms do
if let some r ← tryTheoremWithHint? e (.decl thm.thmName) #[] funProp then
return r
return none
/--
Try to prove `e = q(P (fun x => let y := φ x; ψ x y)`.
For example,
- `funPropDecl` is `FunPropDecl` for `Continuous`
- `e = q(Continuous fun x => let y := φ x; ψ x y)`
- `f = q(fun x => let y := φ x; ψ x y)`
-/
def letCase (funPropDecl : FunPropDecl) (e : Expr) (f : Expr)
(funProp : Expr → FunPropM (Option Result)) :
FunPropM (Option Result) := do
match f with
| .lam xName xType (.letE yName yType yValue yBody _) xBi => do
let yType := yType.consumeMData
let yValue := yValue.consumeMData
let yBody := yBody.consumeMData
-- We perform reduction because the type is quite often of the form
-- `(fun x => Y) #0` which is just `Y`
-- Usually this is caused by the usage of `FunLike`
let yType := yType.headBeta
if (yType.hasLooseBVar 0) then
throwError "dependent type encountered {← ppExpr (Expr.forallE xName xType yType default)}"
-- let binding can be pulled out of the lambda function
if ¬(yValue.hasLooseBVar 0) then
let body := yBody.swapBVars 0 1
let e' := mkLet yName yType yValue
(e.setArg (funPropDecl.funArgId) (.lam xName xType body xBi))
return ← funProp e'
match (yBody.hasLooseBVar 0), (yBody.hasLooseBVar 1) with
| true, true =>
let f ← mkUncurryFun 2 (Expr.lam xName xType (.lam yName yType yBody default) xBi)
let g := Expr.lam xName xType (binderInfo := default)
(mkAppN (← mkConstWithFreshMVarLevels ``Prod.mk) #[xType,yType,.bvar 0, yValue])
applyCompRule funPropDecl e f g funProp
| true, false =>
let f := Expr.lam yName yType yBody default
let g := Expr.lam xName xType yValue default
applyCompRule funPropDecl e f g funProp
| false, _ =>
let f := Expr.lam xName xType (yBody.lowerLooseBVars 1 1) xBi
funProp (e.setArg (funPropDecl.funArgId) f)
| _ => throwError "expected expression of the form `fun x => lam y := ..; ..`"
/-- Prove function property of using *morphism theorems*. -/
def applyMorRules (funPropDecl : FunPropDecl) (e : Expr) (fData : FunctionData)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
trace[Debug.Meta.Tactic.fun_prop] "applying morphism theorems to {← ppExpr e}"
match ← fData.isMorApplication with
| .none => throwError "fun_prop bug: invalid use of mor rules on {← ppExpr e}"
| .underApplied =>
applyPiRule funPropDecl e funProp
| .overApplied =>
let some (f, g) ← fData.peeloffArgDecomposition | return none
applyCompRule funPropDecl e f g funProp
| .exact =>
let candidates ← getMorphismTheorems e
trace[Meta.Tactic.fun_prop]
"candidate morphism theorems: {← candidates.mapM fun c => ppOrigin (.decl c.thmName)}"
for c in candidates do
if let some r ← tryTheorem? e (.decl c.thmName) funProp then
return r
trace[Debug.Meta.Tactic.fun_prop] "no theorem matched"
return none
/-- Prove function property of using *transition theorems*. -/
def applyTransitionRules (e : Expr) (funProp : Expr → FunPropM (Option Result)) :
FunPropM (Option Result) := do
withIncreasedTransitionDepth do
let candidates ← getTransitionTheorems e
trace[Meta.Tactic.fun_prop]
"candidate transition theorems: {← candidates.mapM fun c => ppOrigin (.decl c.thmName)}"
for c in candidates do
if let some r ← tryTheorem? e (.decl c.thmName) funProp then
return r
trace[Debug.Meta.Tactic.fun_prop] "no theorem matched"
return none
/-- Try to remove applied argument i.e. prove `P (fun x => f x y)` from `P (fun x => f x)`.
For example
- `funPropDecl` is `FunPropDecl` for `Continuous`
- `e = q(Continuous fun x => foo (bar x) y)`
- `fData` contains info on `fun x => foo (bar x) y`
This tries to prove `Continuous fun x => foo (bar x) y` from `Continuous fun x => foo (bar x)`
-/
def removeArgRule (funPropDecl : FunPropDecl) (e : Expr) (fData : FunctionData)
(funProp : Expr → FunPropM (Option Result)) :
FunPropM (Option Result) := do
match h : fData.args.size with
| 0 => throwError "fun_prop bug: invalid use of remove arg case {←ppExpr e}"
| n + 1 =>
let arg := fData.args[n]
if arg.coe.isSome then
-- if have to apply morphisms rules if we deal with morphisms
return ← applyMorRules funPropDecl e fData funProp
else
let some (f, g) ← fData.peeloffArgDecomposition | return none
applyCompRule funPropDecl e f g funProp
/-- Prove function property of `fun f => f x₁ ... xₙ`. -/
def bvarAppCase (funPropDecl : FunPropDecl) (e : Expr) (fData : FunctionData)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
if (← fData.isMorApplication) != .none then
applyMorRules funPropDecl e fData funProp
else
if let some (f, g) ← fData.nontrivialDecomposition then
applyCompRule funPropDecl e f g funProp
else
applyApplyRule funPropDecl e funProp
/--
Get candidate theorems from the environment for function property `funPropDecl` and
function `funName`. -/
def getDeclTheorems (funPropDecl : FunPropDecl) (funName : Name)
(mainArgs : Array Nat) (appliedArgs : Nat) : MetaM (Array FunctionTheorem) := do
let thms ← getTheoremsForFunction funName funPropDecl.funPropName
let thms := thms
|>.filter (fun thm => (isOrderedSubsetOf mainArgs thm.mainArgs))
|>.qsort (fun t s =>
let dt := (Int.ofNat t.appliedArgs - Int.ofNat appliedArgs).natAbs
let ds := (Int.ofNat s.appliedArgs - Int.ofNat appliedArgs).natAbs
match compare dt ds with
| .lt => true
| .gt => false
| .eq => t.mainArgs.size < s.mainArgs.size)
-- todo: sorting and filtering
return thms
/--
Get candidate theorems from the local context for function property `funPropDecl` and
function `funName`. -/
def getLocalTheorems (funPropDecl : FunPropDecl) (funOrigin : Origin)
(mainArgs : Array Nat) (appliedArgs : Nat) : FunPropM (Array FunctionTheorem) := do
let mut thms : Array FunctionTheorem := #[]
let lctx ← getLCtx
for var in lctx do
if (var.kind = Lean.LocalDeclKind.auxDecl) then
continue
let type ← instantiateMVars var.type
let thm? : Option FunctionTheorem ←
forallTelescope type fun _ b => do
let b ← whnfR b
let some (decl, f) ← getFunProp? b | return none
unless decl.funPropName = funPropDecl.funPropName do return none
let .data fData ← getFunctionData? f (← unfoldNamePred)
| return none
unless (fData.getFnOrigin == funOrigin) do return none
unless isOrderedSubsetOf mainArgs fData.mainArgs do return none
let dec? ← fData.nontrivialDecomposition
let thm : FunctionTheorem := {
funPropName := funPropDecl.funPropName
thmOrigin := .fvar var.fvarId
funOrigin := funOrigin
mainArgs := fData.mainArgs
appliedArgs := fData.args.size
priority := eval_prio default
form := if dec?.isSome then .comp else .uncurried
}
return some thm
if let some thm := thm? then
thms := thms.push thm
thms := thms
|>.qsort (fun t s =>
let dt := (Int.ofNat t.appliedArgs - Int.ofNat appliedArgs).natAbs
let ds := (Int.ofNat s.appliedArgs - Int.ofNat appliedArgs).natAbs
match compare dt ds with
| .lt => true
| .gt => false
| .eq => t.mainArgs.size < s.mainArgs.size)
return thms
/-- Try to apply *function theorems* `thms` to `e`. -/
def tryTheorems (funPropDecl : FunPropDecl) (e : Expr) (fData : FunctionData)
(thms : Array FunctionTheorem) (funProp : Expr → FunPropM (Option Result)) :
FunPropM (Option Result) := do
-- none - decomposition not tried
-- some none - decomposition failed
-- some some (f, g) - successful decomposition
let mut dec? : Option (Option (Expr × Expr)) := none
for thm in thms do
trace[Debug.Meta.Tactic.fun_prop] s!"trying theorem {← ppOrigin' thm.thmOrigin}"
match compare thm.appliedArgs fData.args.size with
| .lt =>
trace[Meta.Tactic.fun_prop] s!"removing argument to later use {← ppOrigin' thm.thmOrigin}"
if let some r ← removeArgRule funPropDecl e fData funProp then
return r
continue
| .gt =>
trace[Meta.Tactic.fun_prop] s!"adding argument to later use {← ppOrigin' thm.thmOrigin}"
if let some r ← applyPiRule funPropDecl e funProp then
return r
continue
| .eq =>
if thm.form == .comp then
if let some r ← tryTheorem? e thm.thmOrigin funProp then
return r
else
if thm.mainArgs.size == fData.mainArgs.size then
if dec?.isNone then
dec? := some (← fData.nontrivialDecomposition)
match dec? with
| some none =>
if let some r ← tryTheorem? e thm.thmOrigin funProp then
return r
| some (some (f, g)) =>
trace[Meta.Tactic.fun_prop]
s!"decomposing to later use {←ppOrigin' thm.thmOrigin} as:
({← ppExpr f}) ∘ ({← ppExpr g})"
if let some r ← applyCompRule funPropDecl e f g funProp then
return r
| _ => continue
else
let some (f, g) ← fData.decompositionOverArgs thm.mainArgs | continue
trace[Meta.Tactic.fun_prop]
s!"decomposing to later use {←ppOrigin' thm.thmOrigin} as:
({← ppExpr f}) ∘ ({← ppExpr g})"
if let some r ← applyCompRule funPropDecl e f g funProp then
return r
-- todo: decompose if uncurried and arguments do not match exactly
return none
/-- Prove function property of `fun x => f x₁ ... xₙ` where `f` is free variable. -/
def fvarAppCase (funPropDecl : FunPropDecl) (e : Expr) (fData : FunctionData)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
-- fvar theorems are almost exclusively in uncurried form so we decompose if we can
if let some (f, g) ← fData.nontrivialDecomposition then
applyCompRule funPropDecl e f g funProp
else
let .fvar id := fData.fn | throwError "fun_prop bug: invalid use of fvar app case"
let thms ← getLocalTheorems funPropDecl (.fvar id) fData.mainArgs fData.args.size
trace[Meta.Tactic.fun_prop]
s!"candidate local theorems for {←ppExpr (.fvar id)} \
{← thms.mapM fun thm => ppOrigin' thm.thmOrigin}"
if let some r ← tryTheorems funPropDecl e fData thms funProp then
return r
if let some f ← fData.unfoldHeadFVar? then
let e' := e.setArg funPropDecl.funArgId f
if let some r ← funProp e' then
return r
if (← fData.isMorApplication) != .none then
if let some r ← applyMorRules funPropDecl e fData funProp then
return r
if (← fData.nontrivialDecomposition).isNone then
if let some r ← applyTransitionRules e funProp then
return r
if thms.size = 0 then
logError s!"No theorems found for `{← ppExpr (.fvar id)}` in order to prove `{← ppExpr e}`"
return none
/-- Prove function property of `fun x => f x₁ ... xₙ` where `f` is declared function. -/
def constAppCase (funPropDecl : FunPropDecl) (e : Expr) (fData : FunctionData)
(funProp : Expr → FunPropM (Option Result)) : FunPropM (Option Result) := do
let some (funName, _) := fData.fn.const?
| throwError "fun_prop bug: invelid use of const app case"
let globalThms ← getDeclTheorems funPropDecl funName fData.mainArgs fData.args.size
trace[Meta.Tactic.fun_prop]
s!"candidate theorems for {funName} {← globalThms.mapM fun thm => ppOrigin' thm.thmOrigin}"
if let some r ← tryTheorems funPropDecl e fData globalThms funProp then
return r
-- Try local theorems - this is useful for recursive functions
let localThms ← getLocalTheorems funPropDecl (.decl funName) fData.mainArgs fData.args.size
if localThms.size ≠ 0 then
trace[Meta.Tactic.fun_prop]
s!"candidate local theorems for {funName} \
{← localThms.mapM fun thm => ppOrigin' thm.thmOrigin}"
if let some r ← tryTheorems funPropDecl e fData localThms funProp then
return r
-- log error if no global or local theorems were found
if globalThms.size = 0 && localThms.size = 0 then
logError s!"No theorems found for `{funName}` in order to prove `{← ppExpr e}`"
if (← fData.isMorApplication) != .none then
if let some r ← applyMorRules funPropDecl e fData funProp then
return r
if let some (f, g) ← fData.nontrivialDecomposition then
trace[Meta.Tactic.fun_prop]
s!"failed applying `{funPropDecl.funPropName}` theorems for `{funName}`
trying again after decomposing function as: `({← ppExpr f}) ∘ ({← ppExpr g})`"
if let some r ← applyCompRule funPropDecl e f g funProp then
return r
else
trace[Meta.Tactic.fun_prop]
s!"failed applying `{funPropDecl.funPropName}` theorems for `{funName}`
now trying to prove `{funPropDecl.funPropName}` from another function property"
if let some r ← applyTransitionRules e funProp then
return r
return none
/-- Cache result if it does not have any subgoals. -/
def cacheResult (e : Expr) (r : Result) : FunPropM Result := do -- return proof?
modify (fun s => { s with cache := s.cache.insert e { expr := q(True), proof? := r.proof} })
return r
/-- Cache for failed goals such that `fun_prop` can fail fast next time. -/
def cacheFailure (e : Expr) : FunPropM Unit := do -- return proof?
modify (fun s => { s with failureCache := s.failureCache.insert e })
mutual
/-- Main `funProp` function. Returns proof of `e`. -/
partial def funProp (e : Expr) : FunPropM (Option Result) := do
let e ← instantiateMVars e
withTraceNode `Meta.Tactic.fun_prop
(fun r => do pure s!"[{ExceptToEmoji.toEmoji r}] {← ppExpr e}") do
-- check cache for successful goals
if let some { expr := _, proof? := some proof } := (← get).cache.find? e then
trace[Meta.Tactic.fun_prop] "reusing previously found proof for {e}"
return some { proof := proof }
else if (← get).failureCache.contains e then
trace[Meta.Tactic.fun_prop] "skipping proof search, proving {e} was tried already and failed"
return none
else
-- take care of forall and let binders and run main
match e with
| .letE .. =>
letTelescope e fun xs b => do
let some r ← funProp b
| return none
cacheResult e {proof := ← mkLambdaFVars (generalizeNondepLet := false) xs r.proof }
| .forallE .. =>
forallTelescope e fun xs b => do
let some r ← funProp b
| return none
cacheResult e {proof := ← mkLambdaFVars xs r.proof }
| .mdata _ e' => funProp e'
| _ =>
if let some r ← main e then
cacheResult e r
else
cacheFailure e
return none
/-- Main `funProp` function. Returns proof of `e`. -/
private partial def main (e : Expr) : FunPropM (Option Result) := do
let some (funPropDecl, f) ← getFunProp? e
| return none
increaseSteps
-- if function starts with let bindings move them the top of `e` and try again
if f.isLet then
return ← funProp (← mapLetTelescope f fun _ b => pure <| e.setArg funPropDecl.funArgId b)
match ← getFunctionData? f (← unfoldNamePred) with
| .letE f =>
trace[Debug.Meta.Tactic.fun_prop] "let case on {← ppExpr f}"
let e := e.setArg funPropDecl.funArgId f -- update e with reduced f
letCase funPropDecl e f funProp
| .lam f =>
trace[Debug.Meta.Tactic.fun_prop] "pi case on {← ppExpr f}"
let e := e.setArg funPropDecl.funArgId f -- update e with reduced f
applyPiRule funPropDecl e funProp
| .data fData =>
let e := e.setArg funPropDecl.funArgId (← fData.toExpr) -- update e with reduced f
if fData.isIdentityFun then
applyIdRule funPropDecl e funProp
else if fData.isConstantFun then
applyConstRule funPropDecl e funProp
else
match fData.fn with
| .fvar id =>
if id == fData.mainVar.fvarId! then
bvarAppCase funPropDecl e fData funProp
else
fvarAppCase funPropDecl e fData funProp
| .const .. | .proj .. => do
constAppCase funPropDecl e fData funProp
| _ =>
trace[Debug.Meta.Tactic.fun_prop] "unknown case, ctor: {f.ctorName}\n{e}"
return none
end
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/Attr.lean | import Mathlib.Tactic.FunProp.Decl
import Mathlib.Tactic.FunProp.Theorems
/-!
## `funProp` attribute
-/
namespace Mathlib
open Lean Meta
namespace Meta.FunProp
private def funPropHelpString : String :=
"`fun_prop` tactic to prove function properties like `Continuous`, `Differentiable`, `IsLinearMap`"
/-- Initialization of `funProp` attribute -/
initialize funPropAttr : Unit ←
registerBuiltinAttribute {
name := `fun_prop
descr := funPropHelpString
applicationTime := AttributeApplicationTime.afterCompilation
add := fun declName _stx attrKind =>
discard <| MetaM.run do
let info ← getConstInfo declName
forallTelescope info.type fun _ b => do
if b.isProp then
addFunPropDecl declName
else
addTheorem declName attrKind
erase := fun _declName =>
throwError "can't remove `funProp` attribute (not implemented yet)"
}
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/FunctionData.lean | import Qq
import Mathlib.Tactic.FunProp.Mor
import Mathlib.Tactic.FunProp.ToBatteries
/-!
## `funProp` data structure holding information about a function
`FunctionData` holds data about function in the form `fun x => f x₁ ... xₙ`.
-/
namespace Mathlib
open Lean Meta
namespace Meta.FunProp
/-- Structure storing parts of a function in funProp-normal form. -/
structure FunctionData where
/-- local context where `mainVar` exists -/
lctx : LocalContext
/-- local instances -/
insts : LocalInstances
/-- main function -/
fn : Expr
/-- applied function arguments -/
args : Array Mor.Arg
/-- main variable -/
mainVar : Expr
/-- indices of `args` that contain `mainVars` -/
mainArgs : Array Nat
/-- Turn function data back to expression. -/
def FunctionData.toExpr (f : FunctionData) : MetaM Expr := do
withLCtx f.lctx f.insts do
let body := Mor.mkAppN f.fn f.args
mkLambdaFVars #[f.mainVar] body
/-- Is `f` an identity function? -/
def FunctionData.isIdentityFun (f : FunctionData) : Bool :=
(f.args.size = 0 && f.fn == f.mainVar)
/-- Is `f` a constant function? -/
def FunctionData.isConstantFun (f : FunctionData) : Bool :=
((f.mainArgs.size = 0) && !(f.fn.containsFVar f.mainVar.fvarId!))
/-- Domain type of `f`. -/
def FunctionData.domainType (f : FunctionData) : MetaM Expr :=
withLCtx f.lctx f.insts do
inferType f.mainVar
/-- Is head function of `f` a constant?
If the head of `f` is a projection return the name of corresponding projection function. -/
def FunctionData.getFnConstName? (f : FunctionData) : MetaM (Option Name) := do
match f.fn with
| .const n _ => return n
| .proj typeName idx _ =>
let some info := getStructureInfo? (← getEnv) typeName | return none
let some projName := info.getProjFn? idx | return none
return projName
| _ => return none
/-- Get `FunctionData` for `f`. Throws if `f` can't be put into funProp-normal form. -/
def getFunctionData (f : Expr) : MetaM FunctionData := do
lambdaTelescope f fun xs b => do
let xId := xs[0]!.fvarId!
Mor.withApp b fun fn args => do
let mut fn := fn
let mut args := args
-- revert projection in fn
if let .proj n i x := fn then
let some info := getStructureInfo? (← getEnv) n | unreachable!
let some projName := info.getProjFn? i | unreachable!
let p ← mkAppM projName #[x]
fn := p.getAppFn
args := p.getAppArgs.map (fun a => {expr:=a}) ++ args
let mainArgs := args
|>.mapIdx (fun i ⟨arg,_⟩ => if arg.containsFVar xId then some i else none)
|>.filterMap id
return {
lctx := ← getLCtx
insts := ← getLocalInstances
fn := fn
args := args
mainVar := xs[0]!
mainArgs := mainArgs
}
/-- Result of `getFunctionData?`. It returns function data if the function is in the form
`fun x => f y₁ ... yₙ`. Two other cases are `fun x => let y := ...` or `fun x y => ...` -/
inductive MaybeFunctionData where
/-- Can't generate function data as function body has let binder. -/
| letE (f : Expr)
/-- Can't generate function data as function body has lambda binder. -/
| lam (f : Expr)
/-- Function data has been successfully generated. -/
| data (fData : FunctionData)
/-- Turn `MaybeFunctionData` to the function. -/
def MaybeFunctionData.get (fData : MaybeFunctionData) : MetaM Expr :=
match fData with
| .letE f | .lam f => pure f
| .data d => d.toExpr
/-- Get `FunctionData` for `f`. -/
def getFunctionData? (f : Expr)
(unfoldPred : Name → Bool := fun _ => false) :
MetaM MaybeFunctionData := do
withConfig (fun cfg => { cfg with zeta := false, zetaDelta := false }) do
let unfold := fun e : Expr => do
if let some n := e.getAppFn'.constName? then
pure ((unfoldPred n) || (← isReducible n))
else
pure false
let .forallE xName xType _ _ ← instantiateMVars (← inferType f)
| throwError m!"fun_prop bug: function expected, got `{f} : {← inferType f}, \
type ctor {(← inferType f).ctorName}"
withLocalDeclD xName xType fun x => do
let fx' := (← Mor.whnfPred (f.beta #[x]).eta unfold) |> headBetaThroughLet
let f' ← mkLambdaFVars #[x] fx'
match fx' with
| .letE .. => return .letE f'
| .lam .. => return .lam f'
| _ => return .data (← getFunctionData f')
/-- If head function is a let-fvar unfold it and return resulting function.
Return `none` otherwise. -/
def FunctionData.unfoldHeadFVar? (fData : FunctionData) : MetaM (Option Expr) := do
let .fvar id := fData.fn | return none
let some val ← id.getValue? | return none
let f ← withLCtx fData.lctx fData.insts do
mkLambdaFVars #[fData.mainVar] (headBetaThroughLet (Mor.mkAppN val fData.args))
return f
/-- Type of morphism application. -/
inductive MorApplication where
/-- Of the form `⇑f` i.e. missing argument. -/
| underApplied
/-- Of the form `⇑f x` i.e. morphism and one argument is provided. -/
| exact
/-- Of the form `⇑f x y ...` i.e. additional applied arguments `y ...`. -/
| overApplied
/-- Not a morphism application. -/
| none
deriving Inhabited, BEq
/-- Is function body of `f` a morphism application? What kind? -/
def FunctionData.isMorApplication (f : FunctionData) : MetaM MorApplication := do
if let some name := f.fn.constName? then
if ← Mor.isCoeFunName name then
let info ← getConstInfo name
let arity := info.type.getNumHeadForalls
match compare arity f.args.size with
| .eq => return .exact
| .lt => return .overApplied
| .gt => return .underApplied
match h : f.args.size with
| 0 => return .none
| n + 1 =>
if f.args[n].coe.isSome then
return .exact
else if f.args.any (fun a => a.coe.isSome) then
return .overApplied
else
return .none
/-- Decomposes `fun x => f y₁ ... yₙ` into `(fun g => g yₙ) ∘ (fun x y => f y₁ ... yₙ₋₁ y)`
Returns none if:
- `n=0`
- `yₙ` contains `x`
- `n=1` and `(fun x y => f y)` is identity function i.e. `x=f` -/
def FunctionData.peeloffArgDecomposition (fData : FunctionData) : MetaM (Option (Expr × Expr)) := do
unless fData.args.size > 0 do return none
withLCtx fData.lctx fData.insts do
let n := fData.args.size
let x := fData.mainVar
let yₙ := fData.args[n-1]!
if yₙ.expr.containsFVar x.fvarId! then
return none
if fData.args.size = 1 &&
fData.mainVar == fData.fn then
return none
let gBody' := Mor.mkAppN fData.fn fData.args[:n-1]
let gBody' := if let some coe := yₙ.coe then coe.app gBody' else gBody'
let g' ← mkLambdaFVars #[x] gBody'
let f' := Expr.lam `f (← inferType gBody') (.app (.bvar 0) (yₙ.expr)) default
return (f',g')
/-- Decompose function `f = (← fData.toExpr)` into composition of two functions.
Returns none if the decomposition would produce composition with identity function. -/
def FunctionData.nontrivialDecomposition (fData : FunctionData) : MetaM (Option (Expr × Expr)) := do
let mut lctx := fData.lctx
let insts := fData.insts
let x := fData.mainVar
let xId := x.fvarId!
let xName ← withLCtx lctx insts xId.getUserName
let fn := fData.fn
let mut args := fData.args
if fn.containsFVar xId then
return ← fData.peeloffArgDecomposition
let mut yVals : Array Expr := #[]
let mut yVars : Array Expr := #[]
for argId in fData.mainArgs do
let yVal := args[argId]!
let yVal' := yVal.expr
let yId ← withLCtx lctx insts mkFreshFVarId
let yType ← withLCtx lctx insts (inferType yVal')
if yType.containsFVar fData.mainVar.fvarId! then
return none
lctx := lctx.mkLocalDecl yId (xName.appendAfter (toString argId)) yType
let yVar := Expr.fvar yId
yVars := yVars.push yVar
yVals := yVals.push yVal'
args := args.set! argId ⟨yVar, yVal.coe⟩
let g ← withLCtx lctx insts do
mkLambdaFVars #[x] (← mkProdElem yVals)
let f ← withLCtx lctx insts do
(mkLambdaFVars yVars (Mor.mkAppN fn args))
>>=
mkUncurryFun yVars.size
-- check if is non-triviality
let f' ← fData.toExpr
if (← withReducibleAndInstances <| isDefEq f' f <||> isDefEq f' g) then
return none
return (f, g)
/-- Decompose function `fun x => f y₁ ... yₙ` over specified argument indices `#[i, j, ...]`.
The result is:
```
(fun (yᵢ',yⱼ',...) => f y₁ .. yᵢ' .. yⱼ' .. yₙ) ∘ (fun x => (yᵢ, yⱼ, ...))
```
This is not possible if `yₗ` for `l ∉ #[i,j,...]` still contains `x`.
In such case `none` is returned.
-/
def FunctionData.decompositionOverArgs (fData : FunctionData) (args : Array Nat) :
MetaM (Option (Expr × Expr)) := do
unless isOrderedSubsetOf fData.mainArgs args do return none
unless ¬(fData.fn.containsFVar fData.mainVar.fvarId!) do return none
withLCtx fData.lctx fData.insts do
let gxs := args.map (fun i => fData.args[i]!.expr)
try
let gx ← mkProdElem gxs -- this can crash if we have dependent types
let g ← withLCtx fData.lctx fData.insts <| mkLambdaFVars #[fData.mainVar] gx
withLocalDeclD `y (← inferType gx) fun y => do
let ys ← mkProdSplitElem y gxs.size
let args' := (args.zip ys).foldl (init := fData.args)
(fun args' (i,y) => args'.set! i { expr := y, coe := args'[i]!.coe })
let f ← mkLambdaFVars #[y] (Mor.mkAppN fData.fn args')
return (f,g)
catch _ =>
return none
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/ToBatteries.lean | import Mathlib.Init
/-!
## `funProp` missing function from standard library
-/
namespace Mathlib
open Lean Meta
namespace Meta.FunProp
/-- Check if `a` can be obtained by removing elements from `b`. -/
def isOrderedSubsetOf {α} [Inhabited α] [DecidableEq α] (a b : Array α) : Bool :=
Id.run do
if a.size > b.size then
return false
let mut i := 0
for h' : j in [0:b.size] do
if i = a.size then
break
if a[i]! = b[j] then
i := i+1
if i = a.size then
return true
else
return false
/--
Swaps bvars indices `i` and `j`
NOTE: the indices `i` and `j` do not correspond to the `n` in `bvar n`. Rather
they behave like indices in `Expr.lowerLooseBVars`, `Expr.liftLooseBVars`, etc.
TODO: This has to have a better implementation, but I'm still beyond confused with how bvar
indices work
-/
def _root_.Lean.Expr.swapBVars (e : Expr) (i j : Nat) : Expr :=
let swapBVarArray : Array Expr := Id.run do
let mut a : Array Expr := .mkEmpty e.looseBVarRange
for k in [0:e.looseBVarRange] do
a := a.push (.bvar (if k = i then j else if k = j then i else k))
a
e.instantiate swapBVarArray
/--
For `#[x₁, .., xₙ]` create `(x₁, .., xₙ)`.
-/
def mkProdElem (xs : Array Expr) : MetaM Expr := do
match h : xs.size with
| 0 => return default
| 1 => return xs[0]
| n + 1 =>
xs[0:n].foldrM (init := xs[n]) fun x p => mkAppM ``Prod.mk #[x,p]
/--
For `(x₀, .., xₙ₋₁)` return `xᵢ` but as a product projection.
We need to know the total size of the product to be considered.
For example for `xyz : X × Y × Z`
- `mkProdProj xyz 1 3` returns `xyz.snd.fst`.
- `mkProdProj xyz 1 2` returns `xyz.snd`.
-/
def mkProdProj (x : Expr) (i : Nat) (n : Nat) : MetaM Expr := do
-- let X ← inferType x
-- if X.isAppOfArity ``Prod 2 then
match i, n with
| _, 0 => pure x
| _, 1 => pure x
| 0, _ => mkAppM ``Prod.fst #[x]
| i'+1, n'+1 => mkProdProj (← withTransparency .all <| mkAppM ``Prod.snd #[x]) i' n'
/-- For an element of a product type(of size`n`) `xs` create an array of all possible projections
i.e. `#[xs.1, xs.2.1, xs.2.2.1, ..., xs.2..2]` -/
def mkProdSplitElem (xs : Expr) (n : Nat) : MetaM (Array Expr) :=
(Array.range n)
|>.mapM (fun i ↦ mkProdProj xs i n)
/-- Uncurry function `f` in `n` arguments. -/
def mkUncurryFun (n : Nat) (f : Expr) : MetaM Expr := do
if n ≤ 1 then
return f
forallBoundedTelescope (← inferType f) n fun xs _ ↦ do
let xProdName : String ← xs.foldlM (init:="") fun n x ↦
do return (n ++ toString (← x.fvarId!.getUserName).eraseMacroScopes)
let xProdType ← inferType (← mkProdElem xs)
withLocalDecl (.mkSimple xProdName) default xProdType fun xProd ↦ do
let xs' ← mkProdSplitElem xProd n
mkLambdaFVars #[xProd] (← mkAppM' f xs').headBeta
/-- Eta expand `f` in only one variable and reduce in others.
Examples:
```
f ==> fun x => f x
fun x y => f x y ==> fun x => f x
HAdd.hAdd y ==> fun x => HAdd.hAdd y x
HAdd.hAdd ==> fun x => HAdd.hAdd x
``` -/
def etaExpand1 (f : Expr) : MetaM Expr := do
let f := f.eta
if f.isLambda then
return f
else
withDefault do forallBoundedTelescope (← inferType f) (.some 1) fun xs _ => do
mkLambdaFVars xs (mkAppN f xs)
/-- Implementation of `betaThroughLet` -/
private def betaThroughLetAux (f : Expr) (args : List Expr) : Expr :=
match f, args with
| f, [] => f
| .lam _ _ b _, a :: as => (betaThroughLetAux (b.instantiate1 a) as)
| .letE n t v b nondep, args => .letE n t v (betaThroughLetAux b args) nondep
| .mdata _ b, args => betaThroughLetAux b args
| f, args => mkAppN f args.toArray
/-- Apply the given arguments to `f`, beta-reducing if `f` is a lambda expression. This variant
does beta-reduction through let bindings without inlining them.
Example
```
beta' (fun x => let y := x * x; fun z => x + y + z) #[a,b]
==>
let y := a * a; a + y + b
```
-/
def betaThroughLet (f : Expr) (args : Array Expr) : Expr :=
betaThroughLetAux f args.toList
/-- Beta reduces head of an expression, `(fun x => e) a` ==> `e[x/a]`. This version applies
arguments through let bindings without inlining them.
Example
```
headBeta' ((fun x => let y := x * x; fun z => x + y + z) a b)
==>
let y := a * a; a + y + b
```
-/
def headBetaThroughLet (e : Expr) : Expr :=
let f := e.getAppFn
if f.isHeadBetaTargetFn true then betaThroughLet f e.getAppArgs else e
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/Mor.lean | import Mathlib.Init
/-!
## `funProp` Meta programming functions like in Lean.Expr.* but for working with bundled morphisms.
Function application in normal lean expression looks like `.app f x` but when we work with bundled
morphism `f` it looks like `.app (.app coe f) x` where `f`. In mathlib `coe` is usually
`DFunLike.coe` but it can be any coercion that is registered with the `coe` attribute.
The main difference when working with expression involving morphisms is that the notion the head of
expression changes. For example in:
```
coe (f a) b
```
the head of expression is considered to be `f` and not `coe`.
-/
namespace Mathlib
open Lean Meta
namespace Meta.FunProp
namespace Mor
/-- Is `name` a coercion from some function space to functions? -/
def isCoeFunName (name : Name) : CoreM Bool := do
let some info ← getCoeFnInfo? name | return false
return info.type == .coeFun
/-- Is `e` a coercion from some function space to functions? -/
def isCoeFun (e : Expr) : MetaM Bool := do
let some (name, _) := e.getAppFn.const? | return false
let some info ← getCoeFnInfo? name | return false
return e.getAppNumArgs' + 1 == info.numArgs
/-- Morphism application -/
structure App where
/-- morphism coercion -/
coe : Expr
/-- bundled morphism -/
fn : Expr
/-- morphism argument -/
arg : Expr
/-- Is `e` morphism application? -/
def isMorApp? (e : Expr) : MetaM (Option App) := do
let .app (.app coe f) x := e | return none
if ← isCoeFun coe then
return some { coe := coe, fn := f, arg := x }
else
return none
/--
Weak normal head form of an expression involving morphism applications. Additionally, `pred`
can specify which when to unfold definitions.
For example calling this on `coe (f a) b` will put `f` in weak normal head form instead of `coe`.
-/
partial def whnfPred (e : Expr) (pred : Expr → MetaM Bool) :
MetaM Expr := do
whnfEasyCases e fun e => do
let e ← whnfCore e
if let some ⟨coe,f,x⟩ ← isMorApp? e then
let f ← whnfPred f pred
if (← getConfig).zeta then
return (coe.app f).app x
else
return ← mapLetTelescope f fun _ f' => pure ((coe.app f').app x)
if (← pred e) then
match (← unfoldDefinition? e) with
| some e => whnfPred e pred
| none => return e
else
return e
/--
Weak normal head form of an expression involving morphism applications.
For example calling this on `coe (f a) b` will put `f` in weak normal head form instead of `coe`.
-/
def whnf (e : Expr) : MetaM Expr :=
whnfPred e (fun _ => return false)
/-- Argument of morphism application that stores corresponding coercion if necessary -/
structure Arg where
/-- argument of type `α` -/
expr : Expr
/-- coercion `F → α → β` -/
coe : Option Expr := none
deriving Inhabited
/-- Morphism application -/
def app (f : Expr) (arg : Arg) : Expr :=
match arg.coe with
| none => f.app arg.expr
| some coe => (coe.app f).app arg.expr
/-- Given `e = f a₁ a₂ ... aₙ`, returns `k f #[a₁, ..., aₙ]` where `f` can be bundled morphism. -/
partial def withApp {α} (e : Expr) (k : Expr → Array Arg → MetaM α) : MetaM α :=
go e #[]
where
/-- -/
go : Expr → Array Arg → MetaM α
| .mdata _ b, as => go b as
| .app (.app c f) x, as => do
if ← isCoeFun c then
go f (as.push { coe := c, expr := x})
else
go (.app c f) (as.push { expr := x})
| .app (.proj n i f) x, as => do
-- convert proj back to function application
let env ← getEnv
let info := getStructureInfo? env n |>.get!
let projFn := getProjFnForField? env n (info.fieldNames[i]!) |>.get!
let .app c f ← mkAppM projFn #[f] | panic! "bug in Mor.withApp"
go (.app (.app c f) x) as
| .app f a, as => go f (as.push { expr := a })
| f, as => k f as.reverse
/--
If the given expression is a sequence of morphism applications `f a₁ .. aₙ`, return `f`.
Otherwise return the input expression.
-/
def getAppFn (e : Expr) : MetaM Expr :=
match e with
| .mdata _ b => getAppFn b
| .app (.app c f) _ => do
if ← isCoeFun c then
getAppFn f
else
getAppFn (.app c f)
| .app f _ =>
getAppFn f
| e => return e
/-- Given `f a₁ a₂ ... aₙ`, returns `#[a₁, ..., aₙ]` where `f` can be bundled morphism. -/
def getAppArgs (e : Expr) : MetaM (Array Arg) := withApp e fun _ xs => return xs
/-- `mkAppN f #[a₀, ..., aₙ]` ==> `f a₀ a₁ .. aₙ` where `f` can be bundled morphism. -/
def mkAppN (f : Expr) (xs : Array Arg) : Expr :=
xs.foldl (init := f) (fun f x =>
match x with
| ⟨x, .none⟩ => (f.app x)
| ⟨x, some coe⟩ => (coe.app f).app x)
end Mor
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/ContDiff.lean | import Mathlib.Analysis.Calculus.IteratedDeriv.Lemmas
import Mathlib.Analysis.SpecialFunctions.ExpDeriv
import Mathlib.Analysis.SpecialFunctions.Log.Deriv
import Mathlib.Tactic.FunProp
import Mathlib.Tactic.FunProp.Differentiable
deprecated_module
"fun_prop knows about ContDiff(At/On) directly; no need to import this file any more"
(since := "2025-05-13") |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/Theorems.lean | import Mathlib.Tactic.FunProp.Decl
import Mathlib.Tactic.FunProp.Types
import Mathlib.Tactic.FunProp.FunctionData
import Mathlib.Lean.Meta.RefinedDiscrTree.Initialize
import Mathlib.Lean.Meta.RefinedDiscrTree.Lookup
/-!
## `fun_prop` environment extensions storing theorems for `fun_prop`
-/
namespace Mathlib
open Lean Meta
open Std (TreeMap)
namespace Meta.FunProp
/-- Tag for one of the 5 basic lambda theorems, that also hold extra data for composition theorem
-/
inductive LambdaTheoremArgs
/-- Identity theorem e.g. `Continuous fun x => x` -/
| id
/-- Constant theorem e.g. `Continuous fun x => y` -/
| const
/-- Apply theorem e.g. `Continuous fun (f : (x : X) → Y x => f x)` -/
| apply
/-- Composition theorem e.g. `Continuous f → Continuous g → Continuous fun x => f (g x)`
The numbers `fArgId` and `gArgId` store the argument index for `f` and `g` in the composition
theorem. -/
| comp (fArgId gArgId : Nat)
/-- Pi theorem e.g. `∀ y, Continuous (f · y) → Continuous fun x y => f x y` -/
| pi
deriving Inhabited, BEq, Repr, Hashable
/-- Tag for one of the 5 basic lambda theorems -/
inductive LambdaTheoremType
/-- Identity theorem e.g. `Continuous fun x => x` -/
| id
/-- Constant theorem e.g. `Continuous fun x => y` -/
| const
/-- Apply theorem e.g. `Continuous fun (f : (x : X) → Y x => f x)` -/
| apply
/-- Composition theorem e.g. `Continuous f → Continuous g → Continuous fun x => f (g x)` -/
| comp
/-- Pi theorem e.g. `∀ y, Continuous (f · y) → Continuous fun x y => f x y` -/
| pi
deriving Inhabited, BEq, Repr, Hashable
/-- Convert `LambdaTheoremArgs` to `LambdaTheoremType`. -/
def LambdaTheoremArgs.type (t : LambdaTheoremArgs) : LambdaTheoremType :=
match t with
| .id => .id
| .const => .const
| .comp .. => .comp
| .apply => .apply
| .pi => .pi
/-- Decides whether `f` is a function corresponding to one of the lambda theorems. -/
def detectLambdaTheoremArgs (f : Expr) (ctxVars : Array Expr) :
MetaM (Option LambdaTheoremArgs) := do
-- eta expand but beta reduce body
let f ← forallTelescope (← inferType f) fun xs _ =>
mkLambdaFVars xs (mkAppN f xs).headBeta
match f with
| .lam _ _ xBody _ =>
unless xBody.hasLooseBVars do return some .const
match xBody with
| .bvar 0 => return some .id
| .app (.bvar 0) (.fvar _) => return some .apply
| .app (.fvar fId) (.app (.fvar gId) (.bvar 0)) =>
-- fun x => f (g x)
let some argId_f := ctxVars.findIdx? (fun x => x == (.fvar fId)) | return none
let some argId_g := ctxVars.findIdx? (fun x => x == (.fvar gId)) | return none
return some <| .comp argId_f argId_g
| .lam _ _ (.app (.app (.fvar _) (.bvar 1)) (.bvar 0)) _ =>
return some .pi
| _ => return none
| _ => return none
/-- Structure holding information about lambda theorem. -/
structure LambdaTheorem where
/-- Name of function property -/
funPropName : Name
/-- Name of lambda theorem -/
thmName : Name
/-- Type and important argument of the theorem. -/
thmArgs : LambdaTheoremArgs
deriving Inhabited, BEq
/-- Collection of lambda theorems -/
structure LambdaTheorems where
/-- map: function property name × theorem type → lambda theorem -/
theorems : Std.HashMap (Name × LambdaTheoremType) (Array LambdaTheorem) := {}
deriving Inhabited
/-- Return proof of lambda theorem -/
def LambdaTheorem.getProof (thm : LambdaTheorem) : MetaM Expr := do
mkConstWithFreshMVarLevels thm.thmName
/-- Environment extension storing lambda theorems. -/
abbrev LambdaTheoremsExt := SimpleScopedEnvExtension LambdaTheorem LambdaTheorems
/-- Environment extension storing all lambda theorems. -/
initialize lambdaTheoremsExt : LambdaTheoremsExt ←
registerSimpleScopedEnvExtension {
name := by exact decl_name%
initial := {}
addEntry := fun d e =>
{d with theorems :=
let es := d.theorems.getD (e.funPropName, e.thmArgs.type) #[]
d.theorems.insert (e.funPropName, e.thmArgs.type) (es.push e)}
}
/-- Get lambda theorems for particular function property `funPropName`. -/
def getLambdaTheorems (funPropName : Name) (type : LambdaTheoremType) :
CoreM (Array LambdaTheorem) := do
return (lambdaTheoremsExt.getState (← getEnv)).theorems.getD (funPropName,type) #[]
--------------------------------------------------------------------------------
/-- Function theorems are stated in uncurried or compositional form.
uncurried
```
theorem Continuous_add : Continuous (fun x => x.1 + x.2)
```
compositional
```
theorem Continuous_add (hf : Continuous f) (hg : Continuous g) : Continuous (fun x => (f x) + (g x))
```
-/
inductive TheoremForm where
| uncurried | comp
deriving Inhabited, BEq, Repr
/-- TheoremForm to string -/
instance : ToString TheoremForm :=
⟨fun x => match x with | .uncurried => "simple" | .comp => "compositional"⟩
/-- theorem about specific function (either declared constant or free variable) -/
structure FunctionTheorem where
/-- function property name -/
funPropName : Name
/-- theorem name -/
thmOrigin : Origin
/-- function name -/
funOrigin : Origin
/-- array of argument indices about which this theorem is about -/
mainArgs : Array Nat
/-- total number of arguments applied to the function -/
appliedArgs : Nat
/-- priority -/
priority : Nat := eval_prio default
/-- form of the theorem, see documentation of TheoremForm -/
form : TheoremForm
deriving Inhabited, BEq
private local instance : Ord Name := ⟨Name.quickCmp⟩
set_option linter.style.docString.empty false in
/-- -/
structure FunctionTheorems where
/-- map: function name → function property → function theorem -/
theorems :
TreeMap Name (TreeMap Name (Array FunctionTheorem) compare) compare := {}
deriving Inhabited
/-- return proof of function theorem -/
def FunctionTheorem.getProof (thm : FunctionTheorem) : MetaM Expr := do
match thm.thmOrigin with
| .decl name => mkConstWithFreshMVarLevels name
| .fvar id => return .fvar id
set_option linter.style.docString.empty false in
/-- -/
abbrev FunctionTheoremsExt := SimpleScopedEnvExtension FunctionTheorem FunctionTheorems
/-- Extension storing all function theorems. -/
initialize functionTheoremsExt : FunctionTheoremsExt ←
registerSimpleScopedEnvExtension {
name := by exact decl_name%
initial := {}
addEntry := fun d e =>
{d with
theorems :=
d.theorems.alter e.funOrigin.name fun funProperties =>
let funProperties := funProperties.getD {}
funProperties.alter e.funPropName fun thms =>
let thms := thms.getD #[]
thms.push e}
}
set_option linter.style.docString.empty false in
/-- -/
def getTheoremsForFunction (funName : Name) (funPropName : Name) :
CoreM (Array FunctionTheorem) := do
return (functionTheoremsExt.getState (← getEnv)).theorems.getD funName {}
|>.getD funPropName #[]
--------------------------------------------------------------------------------
/-- Get proof of a theorem. -/
def GeneralTheorem.getProof (thm : GeneralTheorem) : MetaM Expr := do
mkConstWithFreshMVarLevels thm.thmName
/-- Extensions for transition or morphism theorems -/
abbrev GeneralTheoremsExt := SimpleScopedEnvExtension GeneralTheorem GeneralTheorems
/-- Environment extension for transition theorems. -/
initialize transitionTheoremsExt : GeneralTheoremsExt ←
registerSimpleScopedEnvExtension {
name := by exact decl_name%
initial := {}
addEntry := fun d e =>
{d with theorems := e.keys.foldl (fun thms (key, entry) =>
RefinedDiscrTree.insert thms key (entry, e)) d.theorems}
}
/-- Get transition theorems applicable to `e`.
For example calling on `e` equal to `Continuous f` might return theorems implying continuity
from linearity over finite-dimensional spaces or differentiability. -/
def getTransitionTheorems (e : Expr) : FunPropM (Array GeneralTheorem) := do
let thms := (← get).transitionTheorems.theorems
let (candidates, thms) ← withConfig (fun cfg => { cfg with iota := false, zeta := false }) <|
thms.getMatch e false true
modify ({ · with transitionTheorems := ⟨thms⟩ })
return (← MonadExcept.ofExcept candidates).toArray
/-- Environment extension for morphism theorems. -/
initialize morTheoremsExt : GeneralTheoremsExt ←
registerSimpleScopedEnvExtension {
name := by exact decl_name%
initial := {}
addEntry := fun d e =>
{d with theorems := e.keys.foldl (fun thms (key, entry) =>
RefinedDiscrTree.insert thms key (entry, e)) d.theorems}
}
/-- Get morphism theorems applicable to `e`.
For example calling on `e` equal to `Continuous f` for `f : X→L[ℝ] Y` would return theorem
inferring continuity from the bundled morphism. -/
def getMorphismTheorems (e : Expr) : FunPropM (Array GeneralTheorem) := do
let thms := (← get).morTheorems.theorems
let (candidates, thms) ← withConfig (fun cfg => { cfg with iota := false, zeta := false }) <|
thms.getMatch e false true
modify ({ · with morTheorems := ⟨thms⟩ })
return (← MonadExcept.ofExcept candidates).toArray
--------------------------------------------------------------------------------
/-- There are four types of theorems:
- lam - theorem about basic lambda calculus terms
- function - theorem about a specific function(declared or free variable) in specific arguments
- mor - special theorems talking about bundled morphisms/DFunLike.coe
- transition - theorems inferring one function property from another
Examples:
- lam
```
theorem Continuous_id : Continuous fun x => x
theorem Continuous_comp (hf : Continuous f) (hg : Continuous g) : Continuous fun x => f (g x)
```
- function
```
theorem Continuous_add : Continuous (fun x => x.1 + x.2)
theorem Continuous_add (hf : Continuous f) (hg : Continuous g) :
Continuous (fun x => (f x) + (g x))
```
- mor - the head of function body has to be ``DFunLike.code
```
theorem ContDiff.clm_apply {f : E → F →L[𝕜] G} {g : E → F}
(hf : ContDiff 𝕜 n f) (hg : ContDiff 𝕜 n g) :
ContDiff 𝕜 n fun x => (f x) (g x)
theorem clm_linear {f : E →L[𝕜] F} : IsLinearMap 𝕜 f
```
- transition - the conclusion has to be in the form `P f` where `f` is a free variable
```
theorem linear_is_continuous [FiniteDimensional ℝ E] {f : E → F} (hf : IsLinearMap 𝕜 f) :
Continuous f
```
-/
inductive Theorem where
| lam (thm : LambdaTheorem)
| function (thm : FunctionTheorem)
| mor (thm : GeneralTheorem)
| transition (thm : GeneralTheorem)
/-- For a theorem declaration `declName` return `fun_prop` theorem. It correctly detects which
type of theorem it is. -/
def getTheoremFromConst (declName : Name) (prio : Nat := eval_prio default) : MetaM Theorem := do
let info ← getConstInfo declName
forallTelescope info.type fun xs b => do
let some (decl,f) ← getFunProp? b
| throwError "unrecognized function property `{← ppExpr b}`"
let funPropName := decl.funPropName
let fData? ←
withConfig (fun cfg => { cfg with zeta := false}) <| getFunctionData? f defaultUnfoldPred
if let some thmArgs ← detectLambdaTheoremArgs (← fData?.get) xs then
return .lam {
funPropName := funPropName
thmName := declName
thmArgs := thmArgs
}
let .data fData := fData?
| throwError s!"function in invalid form {← ppExpr f}"
match fData.fn with
| .const funName _ =>
-- todo: more robust detection of compositional and uncurried form!!!
-- I think this detects `Continuous fun x => x + c` as compositional ...
let dec ← fData.nontrivialDecomposition
let form : TheoremForm := if dec.isSome || funName == ``Prod.mk then .comp else .uncurried
return .function {
-- funPropName funName fData.mainArgs fData.args.size thmForm
funPropName := funPropName
thmOrigin := .decl declName
funOrigin := .decl funName
mainArgs := fData.mainArgs
appliedArgs := fData.args.size
priority := prio
form := form
}
| .fvar .. =>
let (_,_,b') ← forallMetaTelescope info.type
let keys ← RefinedDiscrTree.initializeLazyEntryWithEta b'
let thm : GeneralTheorem := {
funPropName := funPropName
thmName := declName
keys := keys
priority := prio
}
-- todo: maybe do a little bit more careful detection of morphism and transition theorems
match (← fData.isMorApplication) with
| .exact => return .mor thm
| .underApplied | .overApplied =>
throwError "fun_prop theorem about morphism coercion has to be in fully applied form"
| .none =>
if fData.fn.isFVar && (fData.args.size == 1) &&
(fData.args[0]!.expr == fData.mainVar) then
return .transition thm
throwError "Not a valid `fun_prop` theorem!"
| _ =>
throwError "unrecognized theoremType `{← ppExpr b}`"
/-- Register theorem `declName` with `fun_prop`. -/
def addTheorem (declName : Name) (attrKind : AttributeKind := .global)
(prio : Nat := eval_prio default) : MetaM Unit := do
match (← getTheoremFromConst declName prio) with
| .lam thm =>
trace[Meta.Tactic.fun_prop.attr] "\
lambda theorem: {thm.thmName}
function property: {thm.funPropName}
type: {repr thm.thmArgs.type}"
lambdaTheoremsExt.add thm attrKind
| .function thm =>
trace[Meta.Tactic.fun_prop.attr] "\
function theorem: {thm.thmOrigin.name}
function property: {thm.funPropName}
function name: {thm.funOrigin.name}
main arguments: {thm.mainArgs}
applied arguments: {thm.appliedArgs}
form: {toString thm.form} form"
functionTheoremsExt.add thm attrKind
| .mor thm =>
trace[Meta.Tactic.fun_prop.attr] "\
morphism theorem: {thm.thmName}
function property: {thm.funPropName}"
morTheoremsExt.add thm attrKind
| .transition thm =>
trace[Meta.Tactic.fun_prop.attr] "\
transition theorem: {thm.thmName}
function property: {thm.funPropName}"
transitionTheoremsExt.add thm attrKind
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/Differentiable.lean | import Mathlib.Analysis.Calculus.FDeriv.Basic
import Mathlib.Analysis.Calculus.FDeriv.Comp
import Mathlib.Analysis.Calculus.FDeriv.Prod
import Mathlib.Analysis.Calculus.FDeriv.Pi
import Mathlib.Analysis.Calculus.FDeriv.Add
import Mathlib.Analysis.Calculus.FDeriv.Mul
import Mathlib.Analysis.Calculus.Deriv.Inv
import Mathlib.Analysis.SpecialFunctions.ExpDeriv
import Mathlib.Analysis.SpecialFunctions.Log.Deriv
import Mathlib.Tactic.FunProp
deprecated_module
"fun_prop knows about Differentiable(At/On) directly; no need to import this file any more"
(since := "2025-06-25") |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/Elab.lean | import Mathlib.Tactic.FunProp.Core
/-!
## `funProp` tactic syntax
-/
namespace Mathlib
open Lean Meta Elab Tactic
namespace Meta.FunProp
open Lean.Parser.Tactic
/-- `fun_prop` config elaborator -/
declare_config_elab elabFunPropConfig FunProp.Config
/-- Tactic to prove function properties -/
syntax (name := funPropTacStx)
"fun_prop" optConfig (discharger)? (" [" withoutPosition(ident,*,?) "]")? : tactic
private def emptyDischarge : Expr → MetaM (Option Expr) :=
fun e =>
withTraceNode `Meta.Tactic.fun_prop
(fun r => do pure s!"[{ExceptToEmoji.toEmoji r}] discharging: {← ppExpr e}") do
pure none
/-- Tactic to prove function properties -/
@[tactic funPropTacStx]
def funPropTac : Tactic
| `(tactic| fun_prop $cfg:optConfig $[$d]? $[[$names,*]]?) => do
let goal ← getMainGoal
goal.withContext do
let goalType ← goal.getType
-- the whnf and telescope is here because the goal can be
-- `∀ y, let f := fun x => x + y; Continuous fun x => x + f x`
-- However it is still not complete solution. How should we deal with mix of let and forall?
withReducible <| forallTelescopeReducing (← whnfR goalType) fun _ type => do
unless (← getFunProp? type).isSome do
let hint :=
if let some n := type.getAppFn.constName?
then s!" Maybe you forgot marking `{n}` with `@[fun_prop]`."
else ""
throwError "`{← ppExpr type}` is not a `fun_prop` goal!{hint}"
let cfg ← elabFunPropConfig cfg
let disch ← show MetaM (Expr → MetaM (Option Expr)) from do
match d with
| none => pure emptyDischarge
| some d =>
match d with
| `(discharger| (discharger:=$tac)) => pure <| tacticToDischarge (← `(tactic| ($tac)))
| _ => pure emptyDischarge
let namesToUnfold : Array Name :=
match names with
| none => #[]
| some ns => ns.getElems.map (fun n => n.getId)
let namesToUnfold := namesToUnfold.append defaultNamesToUnfold
let ctx : Context :=
{ config := cfg,
disch := disch
constToUnfold := .ofArray namesToUnfold _}
let env ← getEnv
let s := {
morTheorems := morTheoremsExt.getState env
transitionTheorems := transitionTheoremsExt.getState env }
let (r?, s) ← funProp goalType ctx |>.run s
if let some r := r? then
goal.assign r.proof
else
let mut msg := s!"`fun_prop` was unable to prove `{← Meta.ppExpr goalType}`\n\n"
msg := msg ++ "Issues:"
msg := s.msgLog.foldl (init := msg) (fun msg m => msg ++ "\n " ++ m)
throwError msg
| _ => throwUnsupportedSyntax
/-- Command that printins all function properties attached to a function.
For example
```
#print_fun_prop_theorems HAdd.hAdd
```
might print out
```
Continuous
continuous_add, args: [4,5], priority: 1000
continuous_add_left, args: [5], priority: 1000
continuous_add_right, args [4], priority: 1000
...
Differentiable
Differentiable.add, args: [4,5], priority: 1000
Differentiable.add_const, args: [4], priority: 1000
Differentiable.const_add, args: [5], priority: 1000
...
```
You can also see only theorems about a concrete function property
```
#print_fun_prop_theorems HAdd.hAdd Continuous
```
-/
elab "#print_fun_prop_theorems " funIdent:ident funProp:(ident)? : command => do
let funName ← ensureNonAmbiguous funIdent (← resolveGlobalConst funIdent)
let funProp? ← funProp.mapM (fun stx => do
ensureNonAmbiguous stx (← resolveGlobalConst stx))
let theorems := (functionTheoremsExt.getState (← getEnv)).theorems.getD funName {}
let logTheorems (funProp : Name) (thms : Array FunctionTheorem) : Command.CommandElabM Unit := do
let mut msg : MessageData := ""
msg := msg ++ m!"{← Meta.ppOrigin (.decl funProp)}"
for thm in thms do
msg := msg ++ m!"\n {← Meta.ppOrigin (.decl thm.thmOrigin.name)}, \
args: {thm.mainArgs}, form: {thm.form}"
pure ()
logInfo msg
match funProp? with
| none =>
for (funProp,thms) in theorems do
logTheorems funProp thms
| some funProp =>
logTheorems funProp (theorems.getD funProp #[])
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/Decl.lean | import Mathlib.Init
/-!
## `funProp` environment extension that stores all registered function properties
-/
namespace Mathlib
open Lean Meta
namespace Meta.FunProp
/-- Basic information about function property
To use `funProp` to prove a function property `P : (α→β)→Prop` one has to provide `FunPropDecl`.
-/
structure FunPropDecl where
/-- function transformation name -/
funPropName : Name
/-- path for discrimination tree -/
path : Array DiscrTree.Key
/-- argument index of a function this function property talks about.
For example, this would be 4 for `@Continuous α β _ _ f` -/
funArgId : Nat
deriving Inhabited, BEq
/-- Discrimination tree for function properties. -/
structure FunPropDecls where
/-- Discrimination tree for function properties. -/
decls : DiscrTree FunPropDecl := {}
deriving Inhabited
set_option linter.style.docString.empty false in
/-- -/
abbrev FunPropDeclsExt := SimpleScopedEnvExtension FunPropDecl FunPropDecls
/-- Extension storing function properties tracked and used by the `fun_prop` attribute and tactic,
including, for example, `Continuous`, `Measurable`, `Differentiable`, etc. -/
initialize funPropDeclsExt : FunPropDeclsExt ←
registerSimpleScopedEnvExtension {
name := by exact decl_name%
initial := {}
addEntry := fun d e =>
{d with decls := d.decls.insertCore e.path e}
}
/-- Register new function property. -/
def addFunPropDecl (declName : Name) : MetaM Unit := do
let info ← getConstInfo declName
let (xs, bi, b) ← forallMetaTelescope info.type
if ¬b.isProp then
throwError "invalid fun_prop declaration, has to be `Prop`-valued function"
let lvls := info.levelParams.map (fun l => Level.param l)
let e := mkAppN (.const declName lvls) xs
let path ← DiscrTree.mkPath e
-- find the argument position of the function `f` in `P f`
let mut some funArgId ← (xs.zip bi).findIdxM? fun (x,bi) => do
if (← inferType x).isForall && bi.isExplicit then
return true
else
return false
| throwError "invalid fun_prop declaration, can't find argument of type `α → β`"
let decl : FunPropDecl := {
funPropName := declName
path := path
funArgId := funArgId
}
modifyEnv fun env => funPropDeclsExt.addEntry env decl
trace[Meta.Tactic.fun_prop.attr]
"added new function property `{declName}`\nlook up pattern is `{path}`"
/-- Is `e` a function property statement? If yes return function property declaration and
the function it talks about. -/
def getFunProp? (e : Expr) : MetaM (Option (FunPropDecl × Expr)) := do
let ext := funPropDeclsExt.getState (← getEnv)
let decls ← ext.decls.getMatch e (← read)
if h : decls.size = 0 then
return none
else
if decls.size > 1 then
throwError "fun_prop bug: expression {← ppExpr e} matches multiple function properties\n\
{decls.map (fun d => d.funPropName)}"
let decl := decls[0]
unless decl.funArgId < e.getAppNumArgs do return none
let f := e.getArg! decl.funArgId
return (decl,f)
/-- Is `e` a function property statement? -/
def isFunProp (e : Expr) : MetaM Bool := do return (← getFunProp? e).isSome
/-- Is `e` a `fun_prop` goal? For example `∀ y z, Continuous fun x => f x y z` -/
def isFunPropGoal (e : Expr) : MetaM Bool := do
forallTelescope e fun _ b =>
return (← getFunProp? b).isSome
/-- Returns function property declaration from `e = P f`. -/
def getFunPropDecl? (e : Expr) : MetaM (Option FunPropDecl) := do
match ← getFunProp? e with
| some (decl, _) => return decl
| none => return none
/-- Returns function `f` from `e = P f` and `P` is function property. -/
def getFunPropFun? (e : Expr) : MetaM (Option Expr) := do
match ← getFunProp? e with
| some (_, f) => return f
| none => return none
open Elab Term in
/-- Turn tactic syntax into a discharger function. -/
def tacticToDischarge (tacticCode : TSyntax `tactic) : Expr → MetaM (Option Expr) := fun e =>
withTraceNode `Meta.Tactic.fun_prop
(fun r => do pure s!"[{ExceptToEmoji.toEmoji r}] discharging: {← ppExpr e}") do
let mvar ← mkFreshExprSyntheticOpaqueMVar e `funProp.discharger
let runTac? : TermElabM (Option Expr) :=
try
withoutModifyingStateWithInfoAndMessages do
instantiateMVarDeclMVars mvar.mvarId!
let _ ←
withSynthesize (postpone := .no) do
Tactic.run mvar.mvarId! (Tactic.evalTactic tacticCode *> Tactic.pruneSolvedGoals)
let result ← instantiateMVars mvar
if result.hasExprMVar then
return none
else
return some result
catch _ =>
return none
let (result?, _) ← runTac?.run {} {}
return result?
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/FunProp/Types.lean | import Mathlib.Tactic.FunProp.FunctionData
import Mathlib.Lean.Meta.RefinedDiscrTree.Basic
/-!
## `funProp`
this file defines environment extension for `funProp`
-/
namespace Mathlib
open Lean Meta
open Std (TreeSet)
namespace Meta.FunProp
initialize registerTraceClass `Meta.Tactic.fun_prop
initialize registerTraceClass `Meta.Tactic.fun_prop.attr
initialize registerTraceClass `Debug.Meta.Tactic.fun_prop
/-- Indicated origin of a function or a statement. -/
inductive Origin where
/-- It is a constant defined in the environment. -/
| decl (name : Name)
/-- It is a free variable in the local context. -/
| fvar (fvarId : FVarId)
deriving Inhabited, BEq
/-- Name of the origin. -/
def Origin.name (origin : Origin) : Name :=
match origin with
| .decl name => name
| .fvar id => id.name
/-- Get the expression specified by `origin`. -/
def Origin.getValue (origin : Origin) : MetaM Expr := do
match origin with
| .decl name => mkConstWithFreshMVarLevels name
| .fvar id => pure (.fvar id)
/-- Pretty print `FunProp.Origin`. -/
def ppOrigin {m} [Monad m] [MonadEnv m] [MonadError m] : Origin → m MessageData
| .decl n => return m!"{← mkConstWithLevelParams n}"
| .fvar n => return mkFVar n
/-- Pretty print `FunProp.Origin`. Returns string unlike `ppOrigin`. -/
def ppOrigin' (origin : Origin) : MetaM String := do
match origin with
| .fvar id => return s!"{← ppExpr (.fvar id)} : {← ppExpr (← inferType (.fvar id))}"
| _ => pure (toString origin.name)
/-- Get origin of the head function. -/
def FunctionData.getFnOrigin (fData : FunctionData) : Origin :=
match fData.fn with
| .fvar id => .fvar id
| .const name _ => .decl name
| _ => .decl Name.anonymous
/-- Default names to be considered reducible by `fun_prop` -/
def defaultNamesToUnfold : Array Name :=
#[`id, `Function.comp, `Function.HasUncurry.uncurry, `Function.uncurry]
/-- `fun_prop` configuration -/
structure Config where
/-- Maximum number of transitions between function properties. For example inferring continuity
from differentiability and then differentiability from smoothness (`ContDiff ℝ ∞`) requires
`maxTransitionDepth = 2`. The default value of one expects that transition theorems are
transitively closed e.g. there is a transition theorem that infers continuity directly from
smoothness.
Setting `maxTransitionDepth` to zero will disable all transition theorems. This can be very
useful when `fun_prop` should fail quickly. For example when using `fun_prop` as discharger in
`simp`.
-/
maxTransitionDepth := 1
/-- Maximum number of steps `fun_prop` can take. -/
maxSteps := 100000
deriving Inhabited, BEq
/-- `fun_prop` context -/
structure Context where
/-- fun_prop config -/
config : Config := {}
/-- Name to unfold -/
constToUnfold : TreeSet Name Name.quickCmp :=
.ofArray defaultNamesToUnfold _
/-- Custom discharger to satisfy theorem hypotheses. -/
disch : Expr → MetaM (Option Expr) := fun _ => pure none
/-- current transition depth -/
transitionDepth := 0
/-- General theorem about a function property used for transition and morphism theorems -/
structure GeneralTheorem where
/-- function property name -/
funPropName : Name
/-- theorem name -/
thmName : Name
/-- discrimination tree keys used to index this theorem -/
keys : List (RefinedDiscrTree.Key × RefinedDiscrTree.LazyEntry)
/-- priority -/
priority : Nat := eval_prio default
deriving Inhabited
/-- Structure holding transition or morphism theorems for `fun_prop` tactic. -/
structure GeneralTheorems where
/-- Discrimination tree indexing theorems. -/
theorems : RefinedDiscrTree GeneralTheorem := {}
deriving Inhabited
/-- `fun_prop` state -/
structure State where
/-- Simp's cache is used as the `fun_prop` tactic is designed to be used inside of simp and
utilize its cache. It holds successful goals. -/
cache : Simp.Cache := {}
/-- Cache storing failed goals such that they are not tried again. -/
failureCache : ExprSet := {}
/-- Count the number of steps and stop when maxSteps is reached. -/
numSteps := 0
/-- Log progress and failures messages that should be displayed to the user at the end. -/
msgLog : List String := []
/-- `RefinedDiscrTree` is lazy, so we store the partially evaluated tree. -/
morTheorems : GeneralTheorems
/-- `RefinedDiscrTree` is lazy, so we store the partially evaluated tree. -/
transitionTheorems : GeneralTheorems
/-- Increase depth -/
def Context.increaseTransitionDepth (ctx : Context) : Context :=
{ctx with transitionDepth := ctx.transitionDepth + 1}
/-- Monad to run `fun_prop` tactic in. -/
abbrev FunPropM := ReaderT FunProp.Context <| StateT FunProp.State MetaM
set_option linter.style.docString.empty false in
/-- Result of `funProp`, it is a proof of function property `P f` -/
structure Result where
/-- -/
proof : Expr
/-- Default names to unfold -/
def defaultUnfoldPred : Name → Bool :=
defaultNamesToUnfold.contains
/-- Get predicate on names indicating whether they should be unfolded. -/
def unfoldNamePred : FunPropM (Name → Bool) := do
let toUnfold := (← read).constToUnfold
return fun n => toUnfold.contains n
/-- Increase heartbeat, throws error when `maxSteps` was reached -/
def increaseSteps : FunPropM Unit := do
let numSteps := (← get).numSteps
let maxSteps := (← read).config.maxSteps
if numSteps > maxSteps then
throwError s!"fun_prop failed, maximum number({maxSteps}) of steps exceeded"
modify (fun s => {s with numSteps := s.numSteps + 1})
/-- Increase transition depth. Return `none` if maximum transition depth has been reached. -/
def withIncreasedTransitionDepth {α} (go : FunPropM (Option α)) : FunPropM (Option α) := do
let maxDepth := (← read).config.maxTransitionDepth
let newDepth := (← read).transitionDepth + 1
if newDepth > maxDepth then
trace[Meta.Tactic.fun_prop]
"maximum transition depth ({maxDepth}) reached
if you want `fun_prop` to continue then increase the maximum depth with \
`fun_prop (maxTransitionDepth := {newDepth})`"
return none
else
withReader (fun s => {s with transitionDepth := newDepth}) go
/-- Log error message that will displayed to the user at the end.
Messages are logged only when `transitionDepth = 0` i.e. when `fun_prop` is **not** trying to infer
function property like continuity from another property like differentiability.
The main reason is that if the user forgets to add a continuity theorem for function `foo` then
`fun_prop` should report that there is a continuity theorem for `foo` missing. If we would log
messages `transitionDepth > 0` then user will see messages saying that there is a missing theorem
for differentiability, smoothness, ... for `foo`. -/
def logError (msg : String) : FunPropM Unit := do
if (← read).transitionDepth = 0 then
modify fun s =>
{s with msgLog :=
if s.msgLog.contains msg then
s.msgLog
else
msg::s.msgLog}
end Meta.FunProp
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Coherence.lean | import Mathlib.CategoryTheory.Monoidal.Free.Coherence
import Mathlib.Lean.Meta
import Mathlib.Tactic.CategoryTheory.BicategoryCoherence
import Mathlib.Tactic.CategoryTheory.MonoidalComp
/-!
# A `coherence` tactic for monoidal categories
We provide a `coherence` tactic,
which proves equations where the two sides differ by replacing
strings of monoidal structural morphisms with other such strings.
(The replacements are always equalities by the monoidal coherence theorem.)
A simpler version of this tactic is `pure_coherence`,
which proves that any two morphisms (with the same source and target)
in a monoidal category which are built out of associators and unitors
are equal.
-/
universe v u
open CategoryTheory FreeMonoidalCategory
-- As the lemmas and typeclasses in this file are not intended for use outside of the tactic,
-- we put everything inside a namespace.
namespace Mathlib.Tactic.Coherence
variable {C : Type u} [Category.{v} C]
open scoped MonoidalCategory
noncomputable section lifting
variable [MonoidalCategory C]
/-- A typeclass carrying a choice of lift of an object from `C` to `FreeMonoidalCategory C`.
It must be the case that `projectObj id (LiftObj.lift x) = x` by defeq. -/
class LiftObj (X : C) where
protected lift : FreeMonoidalCategory C
instance LiftObj_unit : LiftObj (𝟙_ C) := ⟨unit⟩
instance LiftObj_tensor (X Y : C) [LiftObj X] [LiftObj Y] : LiftObj (X ⊗ Y) where
lift := LiftObj.lift X ⊗ LiftObj.lift Y
instance (priority := 100) LiftObj_of (X : C) : LiftObj X := ⟨of X⟩
/-- A typeclass carrying a choice of lift of a morphism from `C` to `FreeMonoidalCategory C`.
It must be the case that `projectMap id _ _ (LiftHom.lift f) = f` by defeq. -/
class LiftHom {X Y : C} [LiftObj X] [LiftObj Y] (f : X ⟶ Y) where
protected lift : LiftObj.lift X ⟶ LiftObj.lift Y
instance LiftHom_id (X : C) [LiftObj X] : LiftHom (𝟙 X) := ⟨𝟙 _⟩
instance LiftHom_left_unitor_hom (X : C) [LiftObj X] : LiftHom (λ_ X).hom where
lift := (λ_ (LiftObj.lift X)).hom
instance LiftHom_left_unitor_inv (X : C) [LiftObj X] : LiftHom (λ_ X).inv where
lift := (λ_ (LiftObj.lift X)).inv
instance LiftHom_right_unitor_hom (X : C) [LiftObj X] : LiftHom (ρ_ X).hom where
lift := (ρ_ (LiftObj.lift X)).hom
instance LiftHom_right_unitor_inv (X : C) [LiftObj X] : LiftHom (ρ_ X).inv where
lift := (ρ_ (LiftObj.lift X)).inv
instance LiftHom_associator_hom (X Y Z : C) [LiftObj X] [LiftObj Y] [LiftObj Z] :
LiftHom (α_ X Y Z).hom where
lift := (α_ (LiftObj.lift X) (LiftObj.lift Y) (LiftObj.lift Z)).hom
instance LiftHom_associator_inv (X Y Z : C) [LiftObj X] [LiftObj Y] [LiftObj Z] :
LiftHom (α_ X Y Z).inv where
lift := (α_ (LiftObj.lift X) (LiftObj.lift Y) (LiftObj.lift Z)).inv
instance LiftHom_comp {X Y Z : C} [LiftObj X] [LiftObj Y] [LiftObj Z] (f : X ⟶ Y) (g : Y ⟶ Z)
[LiftHom f] [LiftHom g] : LiftHom (f ≫ g) where
lift := LiftHom.lift f ≫ LiftHom.lift g
instance liftHom_WhiskerLeft (X : C) [LiftObj X] {Y Z : C} [LiftObj Y] [LiftObj Z]
(f : Y ⟶ Z) [LiftHom f] : LiftHom (X ◁ f) where
lift := LiftObj.lift X ◁ LiftHom.lift f
instance liftHom_WhiskerRight {X Y : C} (f : X ⟶ Y) [LiftObj X] [LiftObj Y] [LiftHom f]
{Z : C} [LiftObj Z] : LiftHom (f ▷ Z) where
lift := LiftHom.lift f ▷ LiftObj.lift Z
instance LiftHom_tensor {W X Y Z : C} [LiftObj W] [LiftObj X] [LiftObj Y] [LiftObj Z]
(f : W ⟶ X) (g : Y ⟶ Z) [LiftHom f] [LiftHom g] : LiftHom (f ⊗ₘ g) where
lift := LiftHom.lift f ⊗ₘ LiftHom.lift g
end lifting
open Lean Meta Elab Tactic
/-- Helper function for throwing exceptions. -/
def exception {α : Type} (g : MVarId) (msg : MessageData) : MetaM α :=
throwTacticEx `monoidal_coherence g msg
/-- Helper function for throwing exceptions with respect to the main goal. -/
def exception' (msg : MessageData) : TacticM Unit := do
try
liftMetaTactic (exception (msg := msg))
catch _ =>
-- There might not be any goals
throwError msg
/-- Auxiliary definition for `monoidal_coherence`. -/
-- We could construct this expression directly without using `elabTerm`,
-- but it would require preparing many implicit arguments by hand.
def mkProjectMapExpr (e : Expr) : TermElabM Expr := do
Term.elabTerm
(← ``(FreeMonoidalCategory.projectMap _root_.id _ _ (LiftHom.lift $(← Term.exprToSyntax e))))
none
/-- Coherence tactic for monoidal categories. -/
def monoidal_coherence (g : MVarId) : TermElabM Unit := g.withContext do
withOptions (fun opts => synthInstance.maxSize.set opts
(max 512 (synthInstance.maxSize.get opts))) do
let thms := [``MonoidalCoherence.iso, ``Iso.trans, ``Iso.symm, ``Iso.refl,
``MonoidalCategory.whiskerRightIso, ``MonoidalCategory.whiskerLeftIso].foldl
(·.addDeclToUnfoldCore ·) {}
let (ty, _) ← dsimp (← g.getType) (← Simp.mkContext (simpTheorems := #[thms]))
let some (_, lhs, rhs) := (← whnfR ty).eq? | exception g "Not an equation of morphisms."
let projectMap_lhs ← mkProjectMapExpr lhs
let projectMap_rhs ← mkProjectMapExpr rhs
-- This new equation is defeq to the original by assumption
-- on the `LiftObj` and `LiftHom` instances.
let g₁ ← g.change (← mkEq projectMap_lhs projectMap_rhs)
let [g₂] ← g₁.applyConst ``congrArg
| exception g "congrArg failed in coherence"
let [] ← g₂.applyConst ``Subsingleton.elim
| exception g "This shouldn't happen; Subsingleton.elim does not create goals."
/-- Coherence tactic for monoidal categories.
Use `pure_coherence` instead, which is a frontend to this one. -/
elab "monoidal_coherence" : tactic => do monoidal_coherence (← getMainGoal)
open Mathlib.Tactic.BicategoryCoherence
/--
`pure_coherence` uses the coherence theorem for monoidal categories to prove the goal.
It can prove any equality made up only of associators, unitors, and identities.
```lean
example {C : Type} [Category C] [MonoidalCategory C] :
(λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom := by
pure_coherence
```
Users will typically just use the `coherence` tactic,
which can also cope with identities of the form
`a ≫ f ≫ b ≫ g ≫ c = a' ≫ f ≫ b' ≫ g ≫ c'`
where `a = a'`, `b = b'`, and `c = c'` can be proved using `pure_coherence`
-/
elab (name := pure_coherence) "pure_coherence" : tactic => do
let g ← getMainGoal
monoidal_coherence g <|> bicategory_coherence g
/--
Auxiliary simp lemma for the `coherence` tactic:
this moves brackets to the left in order to expose a maximal prefix
built out of unitors and associators.
-/
-- We have unused typeclass arguments here.
-- They are intentional, to ensure that `simp only [assoc_LiftHom]` only left associates
-- monoidal structural morphisms.
@[nolint unusedArguments]
lemma assoc_liftHom {W X Y Z : C} [LiftObj W] [LiftObj X] [LiftObj Y]
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) [LiftHom f] [LiftHom g] :
f ≫ (g ≫ h) = (f ≫ g) ≫ h :=
(Category.assoc _ _ _).symm
/--
Internal tactic used in `coherence`.
Rewrites an equation `f = g` as `f₀ ≫ f₁ = g₀ ≫ g₁`,
where `f₀` and `g₀` are maximal prefixes of `f` and `g` (possibly after reassociating)
which are "liftable" (i.e. expressible as compositions of unitors and associators).
-/
elab (name := liftable_prefixes) "liftable_prefixes" : tactic => do
withOptions (fun opts => synthInstance.maxSize.set opts
(max 256 (synthInstance.maxSize.get opts))) do
evalTactic (← `(tactic|
(simp -failIfUnchanged only
[monoidalComp, bicategoricalComp, Category.assoc, BicategoricalCoherence.iso,
MonoidalCoherence.iso, Iso.trans, Iso.symm, Iso.refl,
MonoidalCategory.whiskerRightIso, MonoidalCategory.whiskerLeftIso,
Bicategory.whiskerRightIso, Bicategory.whiskerLeftIso]) <;>
(apply (cancel_epi (𝟙 _)).1 <;> try infer_instance) <;>
(simp -failIfUnchanged only
[assoc_liftHom, Mathlib.Tactic.BicategoryCoherence.assoc_liftHom₂])))
lemma insert_id_lhs {C : Type*} [Category C] {X Y : C} (f g : X ⟶ Y) (w : f ≫ 𝟙 _ = g) :
f = g := by
simpa using w
lemma insert_id_rhs {C : Type*} [Category C] {X Y : C} (f g : X ⟶ Y) (w : f = g ≫ 𝟙 _) :
f = g := by
simpa using w
/-- If either the lhs or rhs is not a composition, compose it on the right with an identity. -/
def insertTrailingIds (g : MVarId) : MetaM MVarId := do
let some (_, lhs, rhs) := (← withReducible g.getType').eq? | exception g "Not an equality."
let mut g := g
if !(lhs.isAppOf ``CategoryStruct.comp) then
let [g'] ← g.applyConst ``insert_id_lhs | exception g "failed to apply insert_id_lhs"
g := g'
if !(rhs.isAppOf ``CategoryStruct.comp) then
let [g'] ← g.applyConst ``insert_id_rhs | exception g "failed to apply insert_id_rhs"
g := g'
return g
/-- The main part of `coherence` tactic. -/
-- Porting note: this is an ugly port, using too many `evalTactic`s.
-- We can refactor later into either a `macro` (but the flow control is awkward)
-- or a `MetaM` tactic.
def coherence_loop (maxSteps := 37) : TacticM Unit :=
match maxSteps with
| 0 => exception' "`coherence` tactic reached iteration limit"
| maxSteps' + 1 => do
-- To prove an equality `f = g` in a monoidal category,
-- first try the `pure_coherence` tactic on the entire equation:
evalTactic (← `(tactic| pure_coherence)) <|> do
-- Otherwise, rearrange so we have a maximal prefix of each side
-- that is built out of unitors and associators:
evalTactic (← `(tactic| liftable_prefixes)) <|>
exception' "Something went wrong in the `coherence` tactic: \
is the target an equation in a monoidal category?"
-- The goal should now look like `f₀ ≫ f₁ = g₀ ≫ g₁`,
liftMetaTactic MVarId.congrCore
-- and now we have two goals `f₀ = g₀` and `f₁ = g₁`.
-- Discharge the first using `coherence`,
evalTactic (← `(tactic| { pure_coherence })) <|>
exception' "`coherence` tactic failed, subgoal not true in the free monoidal category"
-- Then check that either `g₀` is identically `g₁`,
evalTactic (← `(tactic| rfl)) <|> do
-- or that both are compositions,
liftMetaTactic' insertTrailingIds
liftMetaTactic MVarId.congrCore
-- with identical first terms,
evalTactic (← `(tactic| rfl)) <|>
exception' "`coherence` tactic failed, non-structural morphisms don't match"
-- and whose second terms can be identified by recursively called `coherence`.
coherence_loop maxSteps'
open Lean.Parser.Tactic
/--
Simp lemmas for rewriting a hom in monoidal categories into a normal form.
-/
syntax (name := monoidal_simps) "monoidal_simps" optConfig : tactic
@[inherit_doc monoidal_simps]
elab_rules : tactic
| `(tactic| monoidal_simps $cfg:optConfig) => do
evalTactic (← `(tactic|
simp $cfg only [
Category.assoc, MonoidalCategory.tensor_whiskerLeft, MonoidalCategory.id_whiskerLeft,
MonoidalCategory.whiskerRight_tensor, MonoidalCategory.whiskerRight_id,
MonoidalCategory.whiskerLeft_comp, MonoidalCategory.whiskerLeft_id,
MonoidalCategory.comp_whiskerRight, MonoidalCategory.id_whiskerRight,
MonoidalCategory.whisker_assoc,
MonoidalCategory.id_tensorHom, MonoidalCategory.tensorHom_id];
-- I'm not sure if `tensorHom` should be expanded.
try simp only [MonoidalCategory.tensorHom_def]
))
/--
Use the coherence theorem for monoidal categories to solve equations in a monoidal equation,
where the two sides only differ by replacing strings of monoidal structural morphisms
(that is, associators, unitors, and identities)
with different strings of structural morphisms with the same source and target.
That is, `coherence` can handle goals of the form
`a ≫ f ≫ b ≫ g ≫ c = a' ≫ f ≫ b' ≫ g ≫ c'`
where `a = a'`, `b = b'`, and `c = c'` can be proved using `pure_coherence`.
(If you have very large equations on which `coherence` is unexpectedly failing,
you may need to increase the typeclass search depth,
using e.g. `set_option synthInstance.maxSize 500`.)
-/
syntax (name := coherence) "coherence" : tactic
@[inherit_doc coherence]
elab_rules : tactic
| `(tactic| coherence) => do
evalTactic (← `(tactic|
(simp -failIfUnchanged only [bicategoricalComp, monoidalComp]);
whisker_simps -failIfUnchanged;
monoidal_simps -failIfUnchanged))
coherence_loop
end Coherence
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/BicategoricalComp.lean | import Mathlib.CategoryTheory.Bicategory.Basic
/-!
# Bicategorical composition `⊗≫` (composition up to associators)
We provide `f ⊗≫ g`, the `bicategoricalComp` operation,
which automatically inserts associators and unitors as needed
to make the target of `f` match the source of `g`.
-/
universe w v u
open CategoryTheory Bicategory
namespace CategoryTheory
variable {B : Type u} [Bicategory.{w, v} B] {a b c d : B}
/-- A typeclass carrying a choice of bicategorical structural isomorphism between two objects.
Used by the `⊗≫` bicategorical composition operator, and the `coherence` tactic.
-/
class BicategoricalCoherence (f g : a ⟶ b) where
/-- The chosen structural isomorphism between to 1-morphisms. -/
iso : f ≅ g
/-- Notation for identities up to unitors and associators. -/
scoped[CategoryTheory.Bicategory] notation " ⊗𝟙 " =>
BicategoricalCoherence.iso -- type as \ot 𝟙
/-- Construct an isomorphism between two objects in a bicategorical category
out of unitors and associators. -/
abbrev bicategoricalIso (f g : a ⟶ b) [BicategoricalCoherence f g] : f ≅ g :=
⊗𝟙
/-- Compose two morphisms in a bicategorical category,
inserting unitors and associators between as necessary. -/
def bicategoricalComp {f g h i : a ⟶ b} [BicategoricalCoherence g h]
(η : f ⟶ g) (θ : h ⟶ i) : f ⟶ i :=
η ≫ ⊗𝟙.hom ≫ θ
-- type as \ot \gg
@[inherit_doc bicategoricalComp]
scoped[CategoryTheory.Bicategory] infixr:80 " ⊗≫ " => bicategoricalComp
/-- Compose two isomorphisms in a bicategorical category,
inserting unitors and associators between as necessary. -/
def bicategoricalIsoComp {f g h i : a ⟶ b} [BicategoricalCoherence g h]
(η : f ≅ g) (θ : h ≅ i) : f ≅ i :=
η ≪≫ ⊗𝟙 ≪≫ θ
@[inherit_doc bicategoricalIsoComp]
scoped[CategoryTheory.Bicategory] infixr:80 " ≪⊗≫ " =>
bicategoricalIsoComp -- type as \ll \ot \gg
namespace BicategoricalCoherence
@[simps]
instance refl (f : a ⟶ b) : BicategoricalCoherence f f :=
⟨Iso.refl _⟩
@[simps]
instance whiskerLeft (f : a ⟶ b) (g h : b ⟶ c)
[BicategoricalCoherence g h] : BicategoricalCoherence (f ≫ g) (f ≫ h) :=
⟨whiskerLeftIso f ⊗𝟙⟩
@[simps]
instance whiskerRight (f g : a ⟶ b) (h : b ⟶ c)
[BicategoricalCoherence f g] : BicategoricalCoherence (f ≫ h) (g ≫ h) :=
⟨whiskerRightIso ⊗𝟙 h⟩
@[simps]
instance tensorRight (f : a ⟶ b) (g : b ⟶ b)
[BicategoricalCoherence (𝟙 b) g] : BicategoricalCoherence f (f ≫ g) :=
⟨(ρ_ f).symm ≪≫ (whiskerLeftIso f ⊗𝟙)⟩
@[simps]
instance tensorRight' (f : a ⟶ b) (g : b ⟶ b)
[BicategoricalCoherence g (𝟙 b)] : BicategoricalCoherence (f ≫ g) f :=
⟨whiskerLeftIso f ⊗𝟙 ≪≫ (ρ_ f)⟩
@[simps]
instance left (f g : a ⟶ b) [BicategoricalCoherence f g] :
BicategoricalCoherence (𝟙 a ≫ f) g :=
⟨λ_ f ≪≫ ⊗𝟙⟩
@[simps]
instance left' (f g : a ⟶ b) [BicategoricalCoherence f g] :
BicategoricalCoherence f (𝟙 a ≫ g) :=
⟨⊗𝟙 ≪≫ (λ_ g).symm⟩
@[simps]
instance right (f g : a ⟶ b) [BicategoricalCoherence f g] :
BicategoricalCoherence (f ≫ 𝟙 b) g :=
⟨ρ_ f ≪≫ ⊗𝟙⟩
@[simps]
instance right' (f g : a ⟶ b) [BicategoricalCoherence f g] :
BicategoricalCoherence f (g ≫ 𝟙 b) :=
⟨⊗𝟙 ≪≫ (ρ_ g).symm⟩
@[simps]
instance assoc (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : a ⟶ d)
[BicategoricalCoherence (f ≫ g ≫ h) i] :
BicategoricalCoherence ((f ≫ g) ≫ h) i :=
⟨α_ f g h ≪≫ ⊗𝟙⟩
@[simps]
instance assoc' (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : a ⟶ d)
[BicategoricalCoherence i (f ≫ g ≫ h)] :
BicategoricalCoherence i ((f ≫ g) ≫ h) :=
⟨⊗𝟙 ≪≫ (α_ f g h).symm⟩
end BicategoricalCoherence
@[simp]
theorem bicategoricalComp_refl {f g h : a ⟶ b} (η : f ⟶ g) (θ : g ⟶ h) : η ⊗≫ θ = η ≫ θ := by
dsimp [bicategoricalComp]; simp
end CategoryTheory |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Elementwise.lean | import Mathlib.CategoryTheory.ConcreteCategory.Basic
import Mathlib.Util.AddRelatedDecl
import Batteries.Tactic.Lint
/-!
# Tools to reformulate category-theoretic lemmas in concrete categories
## The `elementwise` attribute
The `elementwise` attribute generates lemmas for concrete categories from lemmas
that equate morphisms in a category.
A sort of inverse to this for the `Type*` category is the `@[higher_order]` attribute.
For more details, see the documentation attached to the `syntax` declaration.
## Main definitions
- The `@[elementwise]` attribute.
- The ``elementwise_of% h` term elaborator.
## Implementation
This closely follows the implementation of the `@[reassoc]` attribute, due to Simon Hudon and
reimplemented by Kim Morrison in Lean 4.
-/
open Lean Meta Elab Tactic
open Mathlib.Tactic
namespace Tactic.Elementwise
open CategoryTheory
section theorems
universe u
theorem forall_congr_forget_Type (α : Type u) (p : α → Prop) :
(∀ (x : (forget (Type u)).obj α), p x) ↔ ∀ (x : α), p x := Iff.rfl
attribute [local instance] HasForget.instFunLike HasForget.hasCoeToSort
theorem forget_hom_Type (α β : Type u) (f : α ⟶ β) : DFunLike.coe f = f := rfl
theorem hom_elementwise {C : Type*} [Category C] [HasForget C]
{X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x := by rw [h]
end theorems
/-- List of simp lemmas to apply to the elementwise theorem. -/
def elementwiseThms : List Name :=
[ -- HasForget lemmas
``CategoryTheory.coe_id, ``CategoryTheory.coe_comp, ``CategoryTheory.comp_apply,
``CategoryTheory.id_apply,
-- ConcreteCategory lemmas
``CategoryTheory.hom_id, ``CategoryTheory.hom_comp, ``id_eq, ``Function.comp_apply,
-- further simplifications if the category is `Type`
``forget_hom_Type, ``forall_congr_forget_Type, ``types_comp_apply, ``types_id_apply,
-- further simplifications to turn `HasForget` definitions into `ConcreteCategory` ones
-- (if available)
``forget_obj, ``ConcreteCategory.forget_map_eq_coe, ``coe_toHasForget_instFunLike,
-- simp can itself simplify trivial equalities into `true`. Adding this lemma makes it
-- easier to detect when this has occurred.
``implies_true]
/--
Given an equation `f = g` between morphisms `X ⟶ Y` in a category `C`
(possibly after a `∀` binder), produce the equation `∀ (x : X), f x = g x` or
`∀ [HasForget C] (x : X), f x = g x` as needed (after the `∀` binder), but
with compositions fully right associated and identities removed.
Returns the proof of the new theorem along with (optionally) a new level metavariable
for the first universe parameter to `HasForget`.
The `simpSides` option controls whether to simplify both sides of the equality, for simpNF
purposes.
-/
def elementwiseExpr (src : Name) (pf : Expr) (simpSides := true) :
MetaM (Expr × Option (Level × Level)) := do
let type := (← instantiateMVars (← inferType pf)).cleanupAnnotations
forallTelescope type fun fvars type' => do
mkHomElementwise type' (mkAppN pf fvars) fun eqPf instConcr? => do
-- First simplify using elementwise-specific lemmas
let mut eqPf' ← simpType (simpOnlyNames elementwiseThms (config := { decide := false })) eqPf
if (← inferType eqPf') == .const ``True [] then
throwError "elementwise lemma for {src} is trivial after applying HasForget \
lemmas, which can be caused by how applications are unfolded. \
Using elementwise is unnecessary."
if simpSides then
let ctx ← Simp.Context.mkDefault
let (ty', eqPf'') ← simpEq (fun e => return (← simp e ctx).1) (← inferType eqPf') eqPf'
-- check that it's not a simp-trivial equality:
forallTelescope ty' fun _ ty' => do
if let some (_, lhs, rhs) := ty'.eq? then
if ← Batteries.Tactic.Lint.isSimpEq lhs rhs then
throwError "applying simp to both sides reduces elementwise lemma for {src} \
to the trivial equality {ty'}. \
Either add `nosimp` or remove the `elementwise` attribute."
eqPf' ← mkExpectedTypeHint eqPf'' ty'
if let some (w, uF, insts) := instConcr? then
return (← Meta.mkLambdaFVars (fvars.append insts) eqPf', (w, uF))
else
return (← Meta.mkLambdaFVars fvars eqPf', none)
where
/-- Given an equality, extract a `Category` instance from it or raise an error.
Returns the name of the category and its instance. -/
extractCatInstance (eqTy : Expr) : MetaM (Expr × Expr) := do
let some (α, _, _) := eqTy.cleanupAnnotations.eq? | failure
let (``Quiver.Hom, #[_, instQuiv, _, _]) := α.getAppFnArgs | failure
let (``CategoryTheory.CategoryStruct.toQuiver, #[_, instCS]) := instQuiv.getAppFnArgs | failure
let (``CategoryTheory.Category.toCategoryStruct, #[C, instC]) := instCS.getAppFnArgs | failure
return (C, instC)
mkHomElementwise {α} [Inhabited α] (eqTy eqPf : Expr)
(k : Expr → Option (Level × Level × Array Expr) → MetaM α) :
MetaM α := do
let (C, instC) ← try extractCatInstance eqTy catch _ =>
throwError "elementwise expects equality of morphisms in a category"
-- First try being optimistic that there is already a HasForget instance.
if let some eqPf' ← observing? (mkAppM ``hom_elementwise #[eqPf]) then
k eqPf' none
else
-- That failed, so we need to introduce the instance, which takes creating
-- a fresh universe level for `ConcreteCategory`'s forgetful functor.
let .app (.const ``Category [v, u]) _ ← inferType instC
| throwError "internal error in elementwise: {← inferType instC}"
let w ← mkFreshLevelMVar
let uF ← mkFreshLevelMVar
-- Give a type to the `FunLike` instance on `F`
let fty (F carrier : Expr) : Expr :=
-- I *think* this is right, but it certainly doesn't feel like I'm doing it right.
.forallE `X C (.forallE `Y C (mkApp3
(.const ``FunLike [.succ uF, .succ w, .succ w])
(mkApp2 F (.bvar 1) (.bvar 0))
(mkApp carrier (.bvar 1)) (mkApp carrier (.bvar 0))) default) default
-- Give a type to the `ConcreteCategory` instance on `C`
let cty (F carrier instFunLike : Expr) : Expr :=
mkApp5 (.const ``ConcreteCategory [w, v, u, uF]) C instC F carrier instFunLike
withLocalDecls
#[(`F, .implicit, fun _ => pure <| .forallE `X C (.forallE `Y C
(.sort (.succ uF)) default) default),
(`carrier, .implicit, fun _ => pure <| .forallE `X C (.sort (.succ w)) default),
(`instFunLike, .implicit, fun decls => pure <| fty decls[0]! decls[1]!),
(`inst, .instImplicit, fun decls => pure <| cty decls[0]! decls[1]! decls[2]!)]
fun cfvars => do
let eqPf' ← mkAppM ``hom_elementwise #[eqPf]
k eqPf' (some (w, uF, cfvars))
/-- Gives a name based on `baseName` that's not already in the list. -/
private partial def mkUnusedName (names : List Name) (baseName : Name) : Name :=
if not (names.contains baseName) then
baseName
else
let rec loop (i : Nat := 0) : Name :=
let w := Name.appendIndexAfter baseName i
if names.contains w then
loop (i + 1)
else
w
loop 1
/-- The `elementwise` attribute can be added to a lemma proving an equation of morphisms, and it
creates a new lemma for a `HasForget` giving an equation with those morphisms applied
to some value.
Syntax examples:
- `@[elementwise]`
- `@[elementwise nosimp]` to not use `simp` on both sides of the generated lemma
- `@[elementwise (attr := simp)]` to apply the `simp` attribute to both the generated lemma and
the original lemma.
Example application of `elementwise`:
```lean
@[elementwise]
lemma some_lemma {C : Type*} [Category C]
{X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : X ⟶ Z) (w : ...) : f ≫ g = h := ...
```
produces
```lean
lemma some_lemma_apply {C : Type*} [Category C]
{X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : X ⟶ Z) (w : ...)
[HasForget C] (x : X) : g (f x) = h x := ...
```
Here `X` is being coerced to a type via `CategoryTheory.HasForget.hasCoeToSort` and
`f`, `g`, and `h` are being coerced to functions via `CategoryTheory.HasForget.hasCoeToFun`.
Further, we simplify the type using `CategoryTheory.coe_id : ((𝟙 X) : X → X) x = x` and
`CategoryTheory.coe_comp : (f ≫ g) x = g (f x)`,
replacing morphism composition with function composition.
The `[HasForget C]` argument will be omitted if it is possible to synthesize an instance.
The name of the produced lemma can be specified with `@[elementwise other_lemma_name]`.
If `simp` is added first, the generated lemma will also have the `simp` attribute.
-/
syntax (name := elementwise) "elementwise"
" nosimp"? (" (" &"attr" " := " Parser.Term.attrInstance,* ")")? : attr
initialize registerBuiltinAttribute {
name := `elementwise
descr := ""
applicationTime := .afterCompilation
add := fun src ref kind => match ref with
| `(attr| elementwise $[nosimp%$nosimp?]? $[(attr := $stx?,*)]?) => MetaM.run' do
if (kind != AttributeKind.global) then
throwError "`elementwise` can only be used as a global attribute"
addRelatedDecl src "_apply" ref stx? fun value levels => do
let (newValue, level?) ← elementwiseExpr src value (simpSides := nosimp?.isNone)
let newLevels ← if let some (levelW, levelUF) := level? then do
let w := mkUnusedName levels `w
let uF := mkUnusedName levels `uF
unless ← isLevelDefEq levelW (mkLevelParam w) do
throwError "Could not create level parameter `w` for ConcreteCategory instance"
unless ← isLevelDefEq levelUF (mkLevelParam uF) do
throwError "Could not create level parameter `uF` for ConcreteCategory instance"
pure <| uF :: w :: levels
else
pure levels
pure (newValue, newLevels)
| _ => throwUnsupportedSyntax }
/--
`elementwise_of% h`, where `h` is a proof of an equation `f = g` between
morphisms `X ⟶ Y` in a concrete category (possibly after a `∀` binder),
produces a proof of equation `∀ (x : X), f x = g x`, but with compositions fully
right associated and identities removed.
A typical example is using `elementwise_of%` to dynamically generate rewrite lemmas:
```lean
example (M N K : MonCat) (f : M ⟶ N) (g : N ⟶ K) (h : M ⟶ K) (w : f ≫ g = h) (m : M) :
g (f m) = h m := by rw [elementwise_of% w]
```
In this case, `elementwise_of% w` generates the lemma `∀ (x : M), f (g x) = h x`.
Like the `@[elementwise]` attribute, `elementwise_of%` inserts a `HasForget`
instance argument if it can't synthesize a relevant `HasForget` instance.
(Technical note: The forgetful functor's universe variable is instantiated with a
fresh level metavariable in this case.)
One difference between `elementwise_of%` and `@[elementwise]` is that `@[elementwise]` by
default applies `simp` to both sides of the generated lemma to get something that is in simp
normal form. `elementwise_of%` does not do this.
-/
elab "elementwise_of% " t:term : term => do
let e ← Term.elabTerm t none
let (pf, _) ← elementwiseExpr .anonymous e (simpSides := false)
return pf
-- TODO: elementwise tactic
syntax "elementwise" (ppSpace colGt ident)* : tactic
syntax "elementwise!" (ppSpace colGt ident)* : tactic
end Tactic.Elementwise |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Reassoc.lean | import Mathlib.CategoryTheory.Functor.Basic
import Mathlib.Lean.Meta.Simp
import Mathlib.Tactic.Simps.Basic
import Mathlib.Util.AddRelatedDecl
/-!
# The `reassoc` attribute
Adding `@[reassoc]` to a lemma named `F` of shape `∀ .., f = g`,
where `f g : X ⟶ Y` in some category
will create a new lemma named `F_assoc` of shape
`∀ .. {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h`
but with the conclusions simplified using the axioms for a category
(`Category.comp_id`, `Category.id_comp`, and `Category.assoc`).
This is useful for generating lemmas which the simplifier can use even on expressions
that are already right associated.
There is also a term elaborator `reassoc_of% t` for use within proofs.
The `Mathlib.Tactic.CategoryTheory.IsoReassoc` extends `@[reassoc]` and `reassoc_of%`
to support creating isomorphism reassociation lemmas.
-/
open Lean Meta Elab Tactic
open Mathlib.Tactic
namespace CategoryTheory
/-- A variant of `eq_whisker` with a more convenient argument order for use in tactics. -/
theorem eq_whisker' {C : Type*} [Category C]
{X Y : C} {f g : X ⟶ Y} (w : f = g) {Z : C} (h : Y ⟶ Z) :
f ≫ h = g ≫ h := by rw [w]
/-- Simplify an expression using only the axioms of a category. -/
def categorySimp (e : Expr) : MetaM Simp.Result :=
simpOnlyNames [``Category.comp_id, ``Category.id_comp, ``Category.assoc,
``Functor.id_obj, ``Functor.id_map, ``Functor.comp_obj, ``Functor.comp_map] e
(config := { decide := false })
/--
Given an equation `f = g` between morphisms `X ⟶ Y` in a category,
produce the equation `∀ {Z} (h : Y ⟶ Z), f ≫ h = g ≫ h`,
but with compositions fully right associated and identities removed.
Also returns the category `C` and any instance metavariables that need to be solved for.
-/
def reassocExprHom (e : Expr) : MetaM (Expr × Array MVarId) := do
let lem₀ ← mkConstWithFreshMVarLevels ``eq_whisker'
let (args, _, _) ← forallMetaBoundedTelescope (← inferType lem₀) 7
let inst := args[1]!
inst.mvarId!.setKind .synthetic
let w := args[6]!
w.mvarId!.assignIfDefEq e
withEnsuringLocalInstance inst.mvarId! do
return (← simpType categorySimp (mkAppN lem₀ args), #[inst.mvarId!])
/--
Adding `@[reassoc]` to a lemma named `F` of shape `∀ .., f = g`, where `f g : X ⟶ Y` are
morphisms in some category, will create a new lemma named `F_assoc` of shape
`∀ .. {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h`
but with the conclusions simplified using the axioms for a category
(`Category.comp_id`, `Category.id_comp`, and `Category.assoc`).
So, for example, if the conclusion of `F` is `a ≫ b = g` then
the conclusion of `F_assoc` will be `a ≫ (b ≫ h) = g ≫ h` (note that `≫` reassociates
to the right so the brackets will not appear in the statement).
This attribute is useful for generating lemmas which the simplifier can use even on expressions
that are already right associated.
Note that if you want both the lemma and the reassociated lemma to be
`simp` lemmas, you should tag the lemma `@[reassoc (attr := simp)]`.
The variant `@[simp, reassoc]` on a lemma `F` will tag `F` with `@[simp]`,
but not `F_assoc` (this is sometimes useful).
This attribute also works for lemmas of shape `∀ .., f = g` where `f g : X ≅ Y` are
isomorphisms, provided that `Tactic.CategoryTheory.IsoReassoc` has been imported.
-/
syntax (name := reassoc) "reassoc" (" (" &"attr" " := " Parser.Term.attrInstance,* ")")? : attr
/--
IO ref for reassociation handlers `reassoc` attribute, so that it can be extended
with additional handlers. Handlers take a proof of the equation.
The default handler is `reassocExprHom` for morphism reassociation.
This will be extended in `Tactic.CategoryTheory.IsoReassoc` for isomorphism reassociation.
-/
private initialize reassocImplRef : IO.Ref (Array (Expr → MetaM (Expr × Array MVarId))) ←
IO.mkRef #[reassocExprHom]
/--
Registers a handler for `reassocExpr`. The handler takes a proof of an equation
and returns a proof of the reassociation lemma.
Handlers are considered in order of registration.
They are applied directly to the equation in the body of the forall.
-/
def registerReassocExpr (f : Expr → MetaM (Expr × Array MVarId)) : IO Unit := do
reassocImplRef.modify (·.push f)
/--
Reassociates the morphisms in the type of `pf` using the registered handlers,
using `reassocExprHom` as the default.
Returns the proof of the lemma along with instance metavariables that need synthesis.
-/
def reassocExpr (pf : Expr) : MetaM (Expr × Array MVarId) := do
forallTelescopeReducing (← inferType pf) fun xs _ => do
let pf := mkAppN pf xs
let handlers ← reassocImplRef.get
let (pf, insts) ← handlers.firstM (fun h => h pf) <|> do
throwError "`reassoc` can only be used on terms about equality of (iso)morphisms"
return (← mkLambdaFVars xs pf, insts)
/--
Version of `reassocExpr` for the `TermElabM` monad. Handles instance metavariables automatically.
-/
def reassocExpr' (pf : Expr) : TermElabM Expr := do
let (e, insts) ← reassocExpr pf
for inst in insts do
inst.withContext do
unless ← Term.synthesizeInstMVarCore inst do
Term.registerSyntheticMVarWithCurrRef inst (.typeClass none)
return e
initialize registerBuiltinAttribute {
name := `reassoc
descr := ""
applicationTime := .afterCompilation
add := fun src ref kind => match ref with
| `(attr| reassoc $[(attr := $stx?,*)]?) => MetaM.run' do
if (kind != AttributeKind.global) then
throwError "`reassoc` can only be used as a global attribute"
addRelatedDecl src "_assoc" ref stx? fun value levels => do
Term.TermElabM.run' <| Term.withSynthesize do
let pf ← reassocExpr' value
pure (pf, levels)
| _ => throwUnsupportedSyntax }
/--
`reassoc_of% t`, where `t` is
an equation `f = g` between morphisms `X ⟶ Y` in a category (possibly after a `∀` binder),
produce the equation `∀ {Z} (h : Y ⟶ Z), f ≫ h = g ≫ h`,
but with compositions fully right associated and identities removed.
This also works for equations between isomorphisms, provided that
`Tactic.CategoryTheory.IsoReassoc` has been imported.
-/
elab "reassoc_of% " t:term : term => do
let e ← Term.withSynthesizeLight <| Term.elabTerm t none
reassocExpr' e
end CategoryTheory |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/ToApp.lean | import Mathlib.CategoryTheory.Category.Cat
import Mathlib.Util.AddRelatedDecl
/-!
# The `to_app` attribute
Adding `@[to_app]` to a lemma named `F` of shape `∀ .., η = θ`, where `η θ : f ⟶ g` are 2-morphisms
in some bicategory, create a new lemma named `F_app`. This lemma is obtained by first specializing
the bicategory in which the equality is taking place to `Cat`, then applying `NatTrans.congr_app`
to obtain a proof of `∀ ... (X : Cat), η.app X = θ.app X`, and finally simplifying the conclusion
using some basic lemmas in the bicategory `Cat`:
`Cat.whiskerLeft_app`, `Cat.whiskerRight_app`, `Cat.id_app`, `Cat.comp_app` and `Cat.eqToHom_app`
So, for example, if the conclusion of `F` is `f ◁ η = θ` then the conclusion of `F_app` will be
`η.app (f.obj X) = θ.app X`.
This is useful for automatically generating lemmas that can be applied to expressions of 1-morphisms
in `Cat` which contain components of 2-morphisms.
There is also a term elaborator `to_app_of% t` for use within proofs.
-/
open Lean Meta Elab Tactic
open Mathlib.Tactic
namespace CategoryTheory
/-- Simplify an expression in `Cat` using basic properties of `NatTrans.app`. -/
def catAppSimp (e : Expr) : MetaM Simp.Result :=
simpOnlyNames [
``Cat.comp_obj, ``Cat.whiskerLeft_app, ``Cat.whiskerRight_app, ``Cat.id_app, ``Cat.comp_app,
``Cat.eqToHom_app, ``Cat.leftUnitor_hom_app, ``Cat.leftUnitor_inv_app,
``Cat.rightUnitor_hom_app, ``Cat.rightUnitor_inv_app,
``Cat.associator_hom_app, ``Cat.associator_inv_app, ``eqToHom_refl,
``Category.comp_id, ``Category.id_comp] e
(config := { decide := false })
/--
Given a term of type `∀ ..., η = θ`, where `η θ : f ⟶ g` are 2-morphisms in some bicategory
`B`, which is bound by the `∀` binder, get the corresponding equation in the bicategory `Cat`.
It is important here that the levels in the term are level metavariables, as otherwise these will
not be reassignable to the corresponding levels of `Cat`. -/
def toCatExpr (e : Expr) : MetaM Expr := do
let (args, binderInfos, conclusion) ← forallMetaTelescope (← inferType e)
-- Find the expression corresponding to the bicategory, by analyzing `η = θ` (i.e. conclusion)
let B ←
match conclusion.getAppFnArgs with
| (`Eq, #[_, η, _]) =>
match (← inferType η).getAppFnArgs with
| (`Quiver.Hom, #[_, _, f, _]) =>
match (← inferType f).getAppFnArgs with
| (`Quiver.Hom, #[_, _, a, _]) => inferType a
| _ => throwError "The conclusion {conclusion} is not an equality of 2-morphisms!"
| _ => throwError "The conclusion {conclusion} is not an equality of 2-morphisms!"
| _ => throwError "The conclusion {conclusion} is not an equality!"
-- Create level metavariables to be used for `Cat.{v, u}`
let u ← mkFreshLevelMVar
let v ← mkFreshLevelMVar
-- Assign `B` to `Cat.{v, u}`
let _ ← isDefEq B (.const ``Cat [v, u])
-- Assign the right bicategory instance to `Cat.{v, u}`
let some inst ← args.findM? fun x => do
return (← inferType x).getAppFnArgs == (`CategoryTheory.Bicategory, #[B])
| throwError "Cannot find the argument for the bicategory instance of the bicategory in which \
the equality is taking place."
let _ ← isDefEq inst (.const ``CategoryTheory.Cat.bicategory [v, u])
-- Construct the new expression
let value := mkAppN e args
let rec
/-- Recursive function which applies `mkLambdaFVars` stepwise
(so that each step can have different binderinfos) -/
apprec (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < args.size then
let arg := args[i]
let bi := binderInfos[i]!
let e' ← apprec (i + 1) e
unless arg != B && arg != inst do return e'
mkLambdaFVars #[arg] e' (binderInfoForMVars := bi)
else
return e
let value ← apprec 0 value
return value
/--
Given morphisms `f g : C ⟶ D` in the bicategory `Cat`, and an equation `η = θ` between 2-morphisms
(possibly after a `∀` binder), produce the equation `∀ (X : C), f.app X = g.app X`, and simplify
it using basic lemmas about `NatTrans.app`. -/
def toAppExpr (e : Expr) : MetaM Expr := do
mapForallTelescope (fun e => do simpType catAppSimp (← mkAppM ``NatTrans.congr_app #[e])) e
/--
Adding `@[to_app]` to a lemma named `F` of shape `∀ .., η = θ`, where `η θ : f ⟶ g` are 2-morphisms
in some bicategory, create a new lemma named `F_app`. This lemma is obtained by first specializing
the bicategory in which the equality is taking place to `Cat`, then applying `NatTrans.congr_app`
to obtain a proof of `∀ ... (X : Cat), η.app X = θ.app X`, and finally simplifying the conclusion
using some basic lemmas in the bicategory `Cat`:
`Cat.whiskerLeft_app`, `Cat.whiskerRight_app`, `Cat.id_app`, `Cat.comp_app` and `Cat.eqToHom_app`
So, for example, if the conclusion of `F` is `f ◁ η = θ` then the conclusion of `F_app` will be
`η.app (f.obj X) = θ.app X`.
This is useful for automatically generating lemmas that can be applied to expressions of 1-morphisms
in `Cat` which contain components of 2-morphisms.
Note that if you want both the lemma and the new lemma to be `simp` lemmas, you should tag the lemma
`@[to_app (attr := simp)]`. The variant `@[simp, to_app]` on a lemma `F` will tag `F` with
`@[simp]`, but not `F_app` (this is sometimes useful).
-/
syntax (name := to_app) "to_app" (" (" &"attr" " := " Parser.Term.attrInstance,* ")")? : attr
initialize registerBuiltinAttribute {
name := `to_app
descr := ""
applicationTime := .afterCompilation
add := fun src ref kind => match ref with
| `(attr| to_app $[(attr := $stx?,*)]?) => MetaM.run' do
if (kind != AttributeKind.global) then
throwError "`to_app` can only be used as a global attribute"
addRelatedDecl src "_app" ref stx? fun value levels => do
let levelMVars ← levels.mapM fun _ => mkFreshLevelMVar
let value := value.instantiateLevelParams levels levelMVars
let newValue ← toAppExpr (← toCatExpr value)
let r := (← getMCtx).levelMVarToParam (fun _ => false) (fun _ => false) newValue
let output := (r.expr, r.newParamNames.toList)
pure output
| _ => throwUnsupportedSyntax }
open Term in
/--
Given an equation `t` of the form `η = θ` between 2-morphisms `f ⟶ g` with `f g : C ⟶ D` in the
bicategory `Cat` (possibly after a `∀` binder), `to_app_of% t` produces the equation
`∀ (X : C), η.app X = θ.app X` (where `X` is an object in the domain of `f` and `g`), and simplifies
it suitably using basic lemmas about `NatTrans.app`.
-/
elab "to_app_of% " t:term : term => do
toAppExpr (← elabTerm t none)
end CategoryTheory |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/IsoReassoc.lean | import Mathlib.CategoryTheory.Iso
/-!
# Extension of `reassoc` to isomorphisms.
We extend `reassoc` and `reassoc_of%` for equality of isomorphisms.
Adding `@[reassoc]` to a lemma named `F` of shape `∀ .., f = g`,
where `f g : X ≅ Y` in some category will create a new lemma named `F_assoc` of shape
`∀ .. {Z : C} (h : Y ≅ Z), f ≪≫ h = g ≪≫ h`
but with the conclusions simplified using basic proportions in isomorphisms in a category
(`Iso.trans_refl`, `Iso.refl_trans`, `Iso.trans_assoc`, `Iso.trans_symm`,
`Iso.symm_self_id` and `Iso.self_symm_id`).
This is useful for generating lemmas which the simplifier can use even on expressions
that are already right associated.
-/
open Lean Meta Elab Tactic
open Mathlib.Tactic
namespace CategoryTheory
theorem Iso.eq_whisker {C : Type*} [Category C]
{X Y : C} {f g : X ≅ Y} (w : f = g) {Z : C} (h : Y ≅ Z) :
f ≪≫ h = g ≪≫ h := by rw [w]
/-- Simplify an expression using only the axioms of a groupoid. -/
def categoryIsoSimp (e : Expr) : MetaM Simp.Result :=
simpOnlyNames [``Iso.trans_symm, ``Iso.trans_refl, ``Iso.refl_trans, ``Iso.trans_assoc,
``Iso.symm_self_id, ``Iso.self_symm_id, ``Iso.symm_self_id_assoc, ``Iso.self_symm_id_assoc,
``Functor.mapIso_trans, ``Functor.mapIso_symm, ``Functor.mapIso_refl, ``Functor.id_obj] e
(config := { decide := false })
/--
Given an equation `f = g` between isomorphisms `X ≅ Y` in a category,
produce the equation `∀ {Z} (h : Y ≅ Z), f ≪≫ h = g ≪≫ h`,
but with compositions fully right associated, identities removed, and functors applied.
-/
def reassocExprIso (e : Expr) : MetaM (Expr × Array MVarId) := do
let lem₀ ← mkConstWithFreshMVarLevels ``Iso.eq_whisker
let (args, _, _) ← forallMetaBoundedTelescope (← inferType lem₀) 7
let inst := args[1]!
inst.mvarId!.setKind .synthetic
let w := args[6]!
w.mvarId!.assignIfDefEq e
withEnsuringLocalInstance inst.mvarId! do
return (← simpType categoryIsoSimp (mkAppN lem₀ args), #[inst.mvarId!])
initialize registerReassocExpr reassocExprIso
end CategoryTheory |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/CheckCompositions.lean | import Mathlib.CategoryTheory.Category.Basic
/-!
The `check_compositions` tactic,
which checks the typing of categorical compositions in the goal,
reporting discrepancies at "instances and reducible" transparency.
Reports from this tactic do not necessarily indicate a problem,
although typically `simp` should reduce rather than increase the reported discrepancies.
`check_compositions` may be useful in diagnosing uses of `erw` in the category theory library.
-/
namespace Mathlib.Tactic.CheckCompositions
open CategoryTheory
open Lean Meta Elab Tactic
/-- Find appearances of `CategoryStruct.comp C inst X Y Z f g`, and apply `f` to each. -/
def forEachComposition (e : Expr) (f : Expr → MetaM Unit) : MetaM Unit := do
e.forEach (fun e ↦ if e.isAppOfArity ``CategoryStruct.comp 7 then f e else pure ())
/-- Given a composition `CategoryStruct.comp _ _ X Y Z f g`,
infer the types of `f` and `g` and check whether their sources and targets agree,
at "instances and reducible" transparency, with `X`, `Y`, and `Z`,
reporting any discrepancies. -/
def checkComposition (e : Expr) : MetaM Unit := do
match_expr e with
| CategoryStruct.comp _ _ X Y Z f g =>
match_expr ← inferType f with
| Quiver.Hom _ _ X' Y' =>
withReducibleAndInstances do
if !(← isDefEq X' X) then
logInfo m!"In composition\n {e}\nthe source of\n {f}\nis\n {X'}\nbut should be\n {X}"
if !(← isDefEq Y' Y) then
logInfo m!"In composition\n {e}\nthe target of\n {f}\nis\n {Y'}\nbut should be\n {Y}"
| _ => throwError "In composition\n {e}\nthe type of\n {f}\nis not a morphism."
match_expr ← inferType g with
| Quiver.Hom _ _ Y' Z' =>
withReducibleAndInstances do
if !(← isDefEq Y' Y) then
logInfo m!"In composition\n {e}\nthe source of\n {g}\nis\n {Y'}\nbut should be\n {Y}"
if !(← isDefEq Z' Z) then
logInfo m!"In composition\n {e}\nthe target of\n {g}\nis\n {Z'}\nbut should be\n {Z}"
| _ => throwError "In composition\n {e}\nthe type of\n {g}\nis not a morphism."
| _ => throwError "{e} is not a composition."
/-- Check the typing of categorical compositions in an expression. -/
def checkCompositions (e : Expr) : MetaM Unit := do
forEachComposition e checkComposition
/-- Check the typing of categorical compositions in the goal. -/
def checkCompositionsTac : TacticM Unit := withMainContext do
let e ← getMainTarget
checkCompositions e
/-- For each composition `f ≫ g` in the goal,
which internally is represented as `CategoryStruct.comp C inst X Y Z f g`,
infer the types of `f` and `g` and check whether their sources and targets agree
with `X`, `Y`, and `Z` at "instances and reducible" transparency,
reporting any discrepancies.
An example:
```
example (j : J) :
colimit.ι ((F ⋙ G) ⋙ H) j ≫ (preservesColimitIso (G ⋙ H) F).inv =
H.map (G.map (colimit.ι F j)) := by
-- We know which lemma we want to use, and it's even a simp lemma, but `rw`
-- won't let us apply it
fail_if_success rw [ι_preservesColimitIso_inv]
fail_if_success rw [ι_preservesColimitIso_inv (G ⋙ H)]
fail_if_success simp only [ι_preservesColimitIso_inv]
-- This would work:
-- erw [ι_preservesColimitIso_inv (G ⋙ H)]
-- `check_compositions` checks if the two morphisms we're composing are
-- composed by abusing defeq, and indeed it tells us that we are abusing
-- definitional associativity of composition of functors here: it prints
-- the following.
-- info: In composition
-- colimit.ι ((F ⋙ G) ⋙ H) j ≫ (preservesColimitIso (G ⋙ H) F).inv
-- the source of
-- (preservesColimitIso (G ⋙ H) F).inv
-- is
-- colimit (F ⋙ G ⋙ H)
-- but should be
-- colimit ((F ⋙ G) ⋙ H)
check_compositions
-- In this case, we can "fix" this by reassociating in the goal, but
-- usually at this point the right thing to do is to back off and
-- check how we ended up with a bad goal in the first place.
dsimp only [Functor.assoc]
-- This would work now, but it is not needed, because simp works as well
-- rw [ι_preservesColimitIso_inv]
simp
```
-/
elab "check_compositions" : tactic => checkCompositionsTac
end Mathlib.Tactic.CheckCompositions |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/MonoidalComp.lean | import Mathlib.CategoryTheory.Monoidal.Category
/-!
# Monoidal composition `⊗≫` (composition up to associators)
We provide `f ⊗≫ g`, the `monoidalComp` operation,
which automatically inserts associators and unitors as needed
to make the target of `f` match the source of `g`.
## Example
Suppose we have a braiding morphism `R X Y : X ⊗ Y ⟶ Y ⊗ X` in a monoidal category, and that we
want to define the morphism with the type `V₁ ⊗ V₂ ⊗ V₃ ⊗ V₄ ⊗ V₅ ⟶ V₁ ⊗ V₃ ⊗ V₂ ⊗ V₄ ⊗ V₅` that
transposes the second and third components by `R V₂ V₃`. How to do this? The first guess would be
to use the whiskering operators `◁` and `▷`, and define the morphism as `V₁ ◁ R V₂ V₃ ▷ V₄ ▷ V₅`.
However, this morphism has the type `V₁ ⊗ ((V₂ ⊗ V₃) ⊗ V₄) ⊗ V₅ ⟶ V₁ ⊗ ((V₃ ⊗ V₂) ⊗ V₄) ⊗ V₅`,
which is not what we need. We should insert suitable associators. The desired associators can,
in principle, be defined by using the primitive three-components associator
`α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)` as a building block, but writing down actual definitions
are quite tedious, and we usually don't want to see them.
The monoidal composition `⊗≫` is designed to solve such a problem. In this case, we can define the
desired morphism as `𝟙 _ ⊗≫ V₁ ◁ R V₂ V₃ ▷ V₄ ▷ V₅ ⊗≫ 𝟙 _`, where the first and the second `𝟙 _`
are completed as `𝟙 (V₁ ⊗ V₂ ⊗ V₃ ⊗ V₄ ⊗ V₅)` and `𝟙 (V₁ ⊗ V₃ ⊗ V₂ ⊗ V₄ ⊗ V₅)`, respectively.
-/
universe v u
open CategoryTheory MonoidalCategory
namespace CategoryTheory
variable {C : Type u} [Category.{v} C]
open scoped MonoidalCategory
/--
A typeclass carrying a choice of monoidal structural isomorphism between two objects.
Used by the `⊗≫` monoidal composition operator, and the `coherence` tactic.
-/
-- We could likely turn this into a `Prop`-valued existential if that proves useful.
class MonoidalCoherence (X Y : C) where
/-- A monoidal structural isomorphism between two objects. -/
iso : X ≅ Y
/-- Notation for identities up to unitors and associators. -/
scoped[CategoryTheory.MonoidalCategory] notation " ⊗𝟙 " =>
MonoidalCoherence.iso -- type as \ot 𝟙
/-- Construct an isomorphism between two objects in a monoidal category
out of unitors and associators. -/
abbrev monoidalIso (X Y : C) [MonoidalCoherence X Y] : X ≅ Y := MonoidalCoherence.iso
/-- Compose two morphisms in a monoidal category,
inserting unitors and associators between as necessary. -/
def monoidalComp {W X Y Z : C} [MonoidalCoherence X Y] (f : W ⟶ X) (g : Y ⟶ Z) : W ⟶ Z :=
f ≫ ⊗𝟙.hom ≫ g
@[inherit_doc monoidalComp]
scoped[CategoryTheory.MonoidalCategory] infixr:80 " ⊗≫ " =>
monoidalComp -- type as \ot \gg
/-- Compose two isomorphisms in a monoidal category,
inserting unitors and associators between as necessary. -/
def monoidalIsoComp {W X Y Z : C} [MonoidalCoherence X Y] (f : W ≅ X) (g : Y ≅ Z) : W ≅ Z :=
f ≪≫ ⊗𝟙 ≪≫ g
@[inherit_doc monoidalIsoComp]
scoped[CategoryTheory.MonoidalCategory] infixr:80 " ≪⊗≫ " =>
monoidalIsoComp -- type as \ll \ot \gg
namespace MonoidalCoherence
variable [MonoidalCategory C]
@[simps]
instance refl (X : C) : MonoidalCoherence X X := ⟨Iso.refl _⟩
@[simps]
instance whiskerLeft (X Y Z : C) [MonoidalCoherence Y Z] :
MonoidalCoherence (X ⊗ Y) (X ⊗ Z) :=
⟨whiskerLeftIso X ⊗𝟙⟩
@[simps]
instance whiskerRight (X Y Z : C) [MonoidalCoherence X Y] :
MonoidalCoherence (X ⊗ Z) (Y ⊗ Z) :=
⟨whiskerRightIso ⊗𝟙 Z⟩
@[simps]
instance tensor_right (X Y : C) [MonoidalCoherence (𝟙_ C) Y] :
MonoidalCoherence X (X ⊗ Y) :=
⟨(ρ_ X).symm ≪≫ (whiskerLeftIso X ⊗𝟙)⟩
@[simps]
instance tensor_right' (X Y : C) [MonoidalCoherence Y (𝟙_ C)] :
MonoidalCoherence (X ⊗ Y) X :=
⟨whiskerLeftIso X ⊗𝟙 ≪≫ (ρ_ X)⟩
@[simps]
instance left (X Y : C) [MonoidalCoherence X Y] :
MonoidalCoherence (𝟙_ C ⊗ X) Y :=
⟨λ_ X ≪≫ ⊗𝟙⟩
@[simps]
instance left' (X Y : C) [MonoidalCoherence X Y] :
MonoidalCoherence X (𝟙_ C ⊗ Y) :=
⟨⊗𝟙 ≪≫ (λ_ Y).symm⟩
@[simps]
instance right (X Y : C) [MonoidalCoherence X Y] :
MonoidalCoherence (X ⊗ 𝟙_ C) Y :=
⟨ρ_ X ≪≫ ⊗𝟙⟩
@[simps]
instance right' (X Y : C) [MonoidalCoherence X Y] :
MonoidalCoherence X (Y ⊗ 𝟙_ C) :=
⟨⊗𝟙 ≪≫ (ρ_ Y).symm⟩
@[simps]
instance assoc (X Y Z W : C) [MonoidalCoherence (X ⊗ (Y ⊗ Z)) W] :
MonoidalCoherence ((X ⊗ Y) ⊗ Z) W :=
⟨α_ X Y Z ≪≫ ⊗𝟙⟩
@[simps]
instance assoc' (W X Y Z : C) [MonoidalCoherence W (X ⊗ (Y ⊗ Z))] :
MonoidalCoherence W ((X ⊗ Y) ⊗ Z) :=
⟨⊗𝟙 ≪≫ (α_ X Y Z).symm⟩
end MonoidalCoherence
@[simp] lemma monoidalComp_refl {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) :
f ⊗≫ g = f ≫ g := by
simp [monoidalComp]
end CategoryTheory |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Slice.lean | import Mathlib.CategoryTheory.Category.Basic
import Mathlib.Tactic.Conv
/-!
# The `slice` tactic
Applies a tactic to an interval of terms from a term obtained by repeated application
of `Category.comp`.
-/
open CategoryTheory
open Lean Parser.Tactic Elab Command Elab.Tactic Meta
-- TODO someone might like to generalise this tactic to work with other associative structures.
open Parser.Tactic.Conv
/--
`slice` is a conv tactic; if the current focus is a composition of several morphisms,
`slice a b` reassociates as needed, and zooms in on the `a`-th through `b`-th morphisms.
Thus if the current focus is `(a ≫ b) ≫ ((c ≫ d) ≫ e)`, then `slice 2 3` zooms to `b ≫ c`.
-/
syntax (name := slice) "slice " num ppSpace num : conv
/--
`evalSlice`
- rewrites the target expression using `Category.assoc`.
- uses `congr` to split off the first `a-1` terms and rotates to `a`-th (last) term
- counts the number `k` of rewrites as it uses `←Category.assoc` to bring the target to
left associated form; from the first step this is the total number of remaining terms from `C`
- it now splits off `b-a` terms from target using `congr` leaving the desired subterm
- finally, it rewrites it once more using `Category.assoc` to bring it to right-associated
normal form
-/
def evalSlice (a b : Nat) : TacticM Unit := do
let _ ← iterateUntilFailureWithResults do
evalTactic (← `(conv| rw [Category.assoc]))
iterateRange (a - 1) (a - 1) do
evalTactic (← `(conv| congr))
evalTactic (← `(tactic| rotate_left))
let k ← iterateUntilFailureCount
<| evalTactic (← `(conv| rw [← Category.assoc]))
let c := k+1+a-b
iterateRange c c <| evalTactic (← `(conv| congr))
let _ ← iterateUntilFailureWithResults do
evalTactic (← `(conv| rw [Category.assoc]))
/-- `slice` is implemented by `evalSlice`. -/
elab "slice " a:num ppSpace b:num : conv => evalSlice a.getNat b.getNat
/--
`slice_lhs a b => tac` zooms to the left-hand side, uses associativity for categorical
composition as needed, zooms in on the `a`-th through `b`-th morphisms, and invokes `tac`.
-/
syntax (name := sliceLHS) "slice_lhs " num ppSpace num " => " convSeq : tactic
macro_rules
| `(tactic| slice_lhs $a $b => $seq) =>
`(tactic| conv => lhs; slice $a $b; ($seq:convSeq))
/--
`slice_rhs a b => tac` zooms to the right-hand side, uses associativity for categorical
composition as needed, zooms in on the `a`-th through `b`-th morphisms, and invokes `tac`.
-/
syntax (name := sliceRHS) "slice_rhs " num ppSpace num " => " convSeq : tactic
macro_rules
| `(tactic| slice_rhs $a $b => $seq) =>
`(tactic| conv => rhs; slice $a $b; ($seq:convSeq))
/- Porting note: update when `add_tactic_doc` is supported` -/
-- add_tactic_doc
-- { Name := "slice"
-- category := DocCategory.tactic
-- declNames := [`tactic.interactive.sliceLHS, `tactic.interactive.sliceRHS]
-- tags := ["category theory"] }
-- |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/BicategoryCoherence.lean | import Mathlib.CategoryTheory.Bicategory.Coherence
import Mathlib.Tactic.CategoryTheory.BicategoricalComp
/-!
# A `coherence` tactic for bicategories
We provide a `bicategory_coherence` tactic,
which proves that any two 2-morphisms (with the same source and target)
in a bicategory which are built out of associators and unitors
are equal.
This file mainly deals with the type class setup for the coherence tactic. The actual front end
tactic is given in `Mathlib/Tactic/CategoryTheory/Coherence.lean` at the same time as the coherence
tactic for monoidal categories.
-/
noncomputable section
universe w v u
open CategoryTheory CategoryTheory.FreeBicategory
open scoped Bicategory
variable {B : Type u} [Bicategory.{w, v} B] {a b c d : B}
namespace Mathlib.Tactic.BicategoryCoherence
/-- A typeclass carrying a choice of lift of a 1-morphism from `B` to `FreeBicategory B`. -/
class LiftHom {a b : B} (f : a ⟶ b) where
/-- A lift of a morphism to the free bicategory.
This should only exist for "structural" morphisms. -/
lift : of.obj a ⟶ of.obj b
instance liftHomId : LiftHom (𝟙 a) where lift := 𝟙 (of.obj a)
instance liftHomComp (f : a ⟶ b) (g : b ⟶ c) [LiftHom f] [LiftHom g] : LiftHom (f ≫ g) where
lift := LiftHom.lift f ≫ LiftHom.lift g
instance (priority := 100) liftHomOf (f : a ⟶ b) : LiftHom f where lift := of.map f
/-- A typeclass carrying a choice of lift of a 2-morphism from `B` to `FreeBicategory B`. -/
class LiftHom₂ {f g : a ⟶ b} [LiftHom f] [LiftHom g] (η : f ⟶ g) where
/-- A lift of a 2-morphism to the free bicategory.
This should only exist for "structural" 2-morphisms. -/
lift : LiftHom.lift f ⟶ LiftHom.lift g
instance liftHom₂Id (f : a ⟶ b) [LiftHom f] : LiftHom₂ (𝟙 f) where
lift := 𝟙 _
instance liftHom₂LeftUnitorHom (f : a ⟶ b) [LiftHom f] : LiftHom₂ (λ_ f).hom where
lift := (λ_ (LiftHom.lift f)).hom
instance liftHom₂LeftUnitorInv (f : a ⟶ b) [LiftHom f] : LiftHom₂ (λ_ f).inv where
lift := (λ_ (LiftHom.lift f)).inv
instance liftHom₂RightUnitorHom (f : a ⟶ b) [LiftHom f] : LiftHom₂ (ρ_ f).hom where
lift := (ρ_ (LiftHom.lift f)).hom
instance liftHom₂RightUnitorInv (f : a ⟶ b) [LiftHom f] : LiftHom₂ (ρ_ f).inv where
lift := (ρ_ (LiftHom.lift f)).inv
instance liftHom₂AssociatorHom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) [LiftHom f] [LiftHom g]
[LiftHom h] : LiftHom₂ (α_ f g h).hom where
lift := (α_ (LiftHom.lift f) (LiftHom.lift g) (LiftHom.lift h)).hom
instance liftHom₂AssociatorInv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) [LiftHom f] [LiftHom g]
[LiftHom h] : LiftHom₂ (α_ f g h).inv where
lift := (α_ (LiftHom.lift f) (LiftHom.lift g) (LiftHom.lift h)).inv
instance liftHom₂Comp {f g h : a ⟶ b} [LiftHom f] [LiftHom g] [LiftHom h] (η : f ⟶ g) (θ : g ⟶ h)
[LiftHom₂ η] [LiftHom₂ θ] : LiftHom₂ (η ≫ θ) where
lift := LiftHom₂.lift η ≫ LiftHom₂.lift θ
instance liftHom₂WhiskerLeft (f : a ⟶ b) [LiftHom f] {g h : b ⟶ c} (η : g ⟶ h) [LiftHom g]
[LiftHom h] [LiftHom₂ η] : LiftHom₂ (f ◁ η) where
lift := LiftHom.lift f ◁ LiftHom₂.lift η
instance liftHom₂WhiskerRight {f g : a ⟶ b} (η : f ⟶ g) [LiftHom f] [LiftHom g] [LiftHom₂ η]
{h : b ⟶ c} [LiftHom h] : LiftHom₂ (η ▷ h) where
lift := LiftHom₂.lift η ▷ LiftHom.lift h
open Lean Elab Tactic Meta
/-- Helper function for throwing exceptions. -/
def exception {α : Type} (g : MVarId) (msg : MessageData) : MetaM α :=
throwTacticEx `bicategorical_coherence g msg
/-- Helper function for throwing exceptions with respect to the main goal. -/
def exception' (msg : MessageData) : TacticM Unit := do
try
liftMetaTactic (exception (msg := msg))
catch _ =>
-- There might not be any goals
throwError msg
set_option quotPrecheck false in
/-- Auxiliary definition for `bicategorical_coherence`. -/
-- We could construct this expression directly without using `elabTerm`,
-- but it would require preparing many implicit arguments by hand.
def mkLiftMap₂LiftExpr (e : Expr) : TermElabM Expr := do
Term.elabTerm
(← ``((FreeBicategory.lift (Prefunctor.id _)).map₂ (LiftHom₂.lift $(← Term.exprToSyntax e))))
none
/-- Coherence tactic for bicategories. -/
def bicategory_coherence (g : MVarId) : TermElabM Unit := g.withContext do
withOptions (fun opts => synthInstance.maxSize.set opts
(max 256 (synthInstance.maxSize.get opts))) do
let thms := [``BicategoricalCoherence.iso, ``Iso.trans, ``Iso.symm, ``Iso.refl,
``Bicategory.whiskerRightIso, ``Bicategory.whiskerLeftIso].foldl
(·.addDeclToUnfoldCore ·) {}
let (ty, _) ← dsimp (← g.getType) (← Simp.mkContext (simpTheorems := #[thms]))
let some (_, lhs, rhs) := (← whnfR ty).eq? | exception g "Not an equation of morphisms."
let lift_lhs ← mkLiftMap₂LiftExpr lhs
let lift_rhs ← mkLiftMap₂LiftExpr rhs
-- This new equation is defeq to the original by assumption
-- on the `LiftHom` instances.
let g₁ ← g.change (← mkEq lift_lhs lift_rhs)
let [g₂] ← g₁.applyConst ``congrArg
| exception g "congrArg failed in coherence"
let [] ← g₂.applyConst ``Subsingleton.elim
| exception g "This shouldn't happen; Subsingleton.elim does not create goals."
/-- Coherence tactic for bicategories.
Use `pure_coherence` instead, which is a frontend to this one. -/
elab "bicategory_coherence" : tactic => do bicategory_coherence (← getMainGoal)
open Lean.Parser.Tactic
/--
Simp lemmas for rewriting a 2-morphism into a normal form.
-/
syntax (name := whisker_simps) "whisker_simps" optConfig : tactic
@[inherit_doc whisker_simps]
elab_rules : tactic
| `(tactic| whisker_simps $cfg) => do
evalTactic (← `(tactic|
simp $cfg only [Category.assoc,
Bicategory.comp_whiskerLeft, Bicategory.id_whiskerLeft,
Bicategory.whiskerRight_comp, Bicategory.whiskerRight_id,
Bicategory.whiskerLeft_comp, Bicategory.whiskerLeft_id,
Bicategory.comp_whiskerRight, Bicategory.id_whiskerRight, Bicategory.whisker_assoc]
))
-- We have unused typeclass arguments here.
-- They are intentional, to ensure that `simp only [assoc_liftHom₂]` only left associates
-- bicategorical structural morphisms.
/-- Auxiliary simp lemma for the `coherence` tactic:
this move brackets to the left in order to expose a maximal prefix
built out of unitors and associators.
-/
@[nolint unusedArguments]
theorem assoc_liftHom₂ {f g h i : a ⟶ b} [LiftHom f] [LiftHom g] [LiftHom h]
(η : f ⟶ g) (θ : g ⟶ h) (ι : h ⟶ i) [LiftHom₂ η] [LiftHom₂ θ] : η ≫ θ ≫ ι = (η ≫ θ) ≫ ι :=
(Category.assoc _ _ _).symm
end Mathlib.Tactic.BicategoryCoherence |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Coherence/PureCoherence.lean | import Lean.Meta.Tactic.Apply
import Mathlib.Tactic.CategoryTheory.Coherence.Datatypes
/-!
# Coherence tactic
This file provides a meta framework for the coherence tactic, which solves goals of the form
`η = θ`, where `η` and `θ` are 2-morphism in a bicategory or morphisms in a monoidal category
made up only of associators, unitors, and identities.
The function defined here is a meta reimplementation of the formalized coherence theorems provided
in the following files:
- Mathlib.CategoryTheory.Monoidal.Free.Coherence
- Mathlib.CategoryTheory.Bicategory.Coherence
See these files for a mathematical explanation of the proof of the coherence theorem.
The actual tactics that users will use are given in
- `Mathlib/Tactic/CategoryTheory/Monoidal/PureCoherence.lean`
- `Mathlib/Tactic/CategoryTheory/Bicategory/PureCoherence.lean`
-/
open Lean Meta
namespace Mathlib.Tactic
namespace BicategoryLike
/-- The result of normalizing a 1-morphism. -/
structure Normalize.Result where
/-- The normalized 1-morphism. -/
normalizedHom : NormalizedHom
/-- The 2-morphism from the original 1-morphism to the normalized 1-morphism. -/
toNormalize : Mor₂Iso
deriving Inhabited
open Mor₂Iso MonadMor₂Iso
variable {ρ : Type} [Context ρ] [MonadMor₁ (CoherenceM ρ)] [MonadMor₂Iso (CoherenceM ρ)]
/-- Meta version of `CategoryTheory.FreeBicategory.normalizeIso`. -/
def normalize (p : NormalizedHom) (f : Mor₁) :
CoherenceM ρ Normalize.Result := do
match f with
| .id _ _ =>
return ⟨p, ← rightUnitorM' p.e⟩
| .comp _ f g =>
let ⟨pf, η_f⟩ ← normalize p f
let η_f' ← whiskerRightM η_f g
let ⟨pfg, η_g⟩ ← normalize pf g
let η ← comp₂M η_f' η_g
let α ← symmM (← associatorM' p.e f g)
let η' ← comp₂M α η
return ⟨pfg, η'⟩
| .of f =>
let pf ← NormalizedHom.consM p f
let α ← id₂M' pf.e
return ⟨pf, α⟩
/-- Lemmas to prove the meta version of `CategoryTheory.FreeBicategory.normalize_naturality`. -/
class MonadNormalizeNaturality (m : Type → Type) where
/-- The naturality for the associator. -/
mkNaturalityAssociator (p pf pfg pfgh : NormalizedHom) (f g h : Mor₁)
(η_f η_g η_h : Mor₂Iso) : m Expr
/-- The naturality for the left unitor. -/
mkNaturalityLeftUnitor (p pf : NormalizedHom) (f : Mor₁) (η_f : Mor₂Iso) : m Expr
/-- The naturality for the right unitor. -/
mkNaturalityRightUnitor (p pf : NormalizedHom) (f : Mor₁) (η_f : Mor₂Iso) : m Expr
/-- The naturality for the identity. -/
mkNaturalityId (p pf : NormalizedHom) (f : Mor₁) (η_f : Mor₂Iso) : m Expr
/-- The naturality for the composition. -/
mkNaturalityComp (p pf : NormalizedHom) (f g h : Mor₁) (η θ η_f η_g η_h : Mor₂Iso)
(ih_η ih_θ : Expr) : m Expr
/-- The naturality for the left whiskering. -/
mkNaturalityWhiskerLeft (p pf pfg : NormalizedHom) (f g h : Mor₁)
(η η_f η_fg η_fh : Mor₂Iso) (ih_η : Expr) : m Expr
/-- The naturality for the right whiskering. -/
mkNaturalityWhiskerRight (p pf pfh : NormalizedHom) (f g h : Mor₁) (η η_f η_g η_fh : Mor₂Iso)
(ih_η : Expr) : m Expr
/-- The naturality for the horizontal composition. -/
mkNaturalityHorizontalComp (p pf₁ pf₁f₂ : NormalizedHom) (f₁ g₁ f₂ g₂ : Mor₁)
(η θ η_f₁ η_g₁ η_f₂ η_g₂ : Mor₂Iso) (ih_η ih_θ : Expr) : m Expr
/-- The naturality for the inverse. -/
mkNaturalityInv (p pf : NormalizedHom) (f g : Mor₁) (η η_f η_g : Mor₂Iso) (ih_η : Expr) : m Expr
open MonadNormalizeNaturality
variable [MonadCoherehnceHom (CoherenceM ρ)] [MonadNormalizeNaturality (CoherenceM ρ)]
/-- Meta version of `CategoryTheory.FreeBicategory.normalize_naturality`. -/
partial def naturality (nm : Name) (p : NormalizedHom) (η : Mor₂Iso) : CoherenceM ρ Expr := do
let result ← match η with
| .of _ => throwError m!"could not find a structural isomorphism, but {η.e}"
| .coherenceComp _ _ _ _ _ α η θ => withTraceNode nm (fun _ => return m!"monoidalComp") do
let α ← MonadCoherehnceHom.unfoldM α
let αθ ← comp₂M α θ
let ηαθ ← comp₂M η αθ
naturality nm p ηαθ
| .structuralAtom η => match η with
| .coherenceHom α => withTraceNode nm (fun _ => return m!"coherenceHom") do
let α ← MonadCoherehnceHom.unfoldM α
naturality nm p α
| .associator _ f g h => withTraceNode nm (fun _ => return m!"associator") do
let ⟨pf, η_f⟩ ← normalize p f
let ⟨pfg, η_g⟩ ← normalize pf g
let ⟨pfgh, η_h⟩ ← normalize pfg h
mkNaturalityAssociator p pf pfg pfgh f g h η_f η_g η_h
| .leftUnitor _ f => withTraceNode nm (fun _ => return m!"leftUnitor") do
let ⟨pf, η_f⟩ ← normalize p f
mkNaturalityLeftUnitor p pf f η_f
| .rightUnitor _ f => withTraceNode nm (fun _ => return m!"rightUnitor") do
let ⟨pf, η_f⟩ ← normalize p f
mkNaturalityRightUnitor p pf f η_f
| .id _ f => withTraceNode nm (fun _ => return m!"id") do
let ⟨pf, η_f⟩ ← normalize p f
mkNaturalityId p pf f η_f
| .comp _ f g h η θ => withTraceNode nm (fun _ => return m!"comp") do
let ⟨pf, η_f⟩ ← normalize p f
let ⟨_, η_g⟩ ← normalize p g
let ⟨_, η_h⟩ ← normalize p h
let ih_η ← naturality nm p η
let ih_θ ← naturality nm p θ
mkNaturalityComp p pf f g h η θ η_f η_g η_h ih_η ih_θ
| .whiskerLeft _ f g h η => withTraceNode nm (fun _ => return m!"whiskerLeft") do
let ⟨pf, η_f⟩ ← normalize p f
let ⟨pfg, η_fg⟩ ← normalize pf g
let ⟨_, η_fh⟩ ← normalize pf h
let ih ← naturality nm pf η
mkNaturalityWhiskerLeft p pf pfg f g h η η_f η_fg η_fh ih
| .whiskerRight _ f g η h => withTraceNode nm (fun _ => return m!"whiskerRight") do
let ⟨pf, η_f⟩ ← normalize p f
let ⟨_, η_g⟩ ← normalize p g
let ⟨pfh, η_fh⟩ ← normalize pf h
let ih ← naturality nm p η
mkNaturalityWhiskerRight p pf pfh f g h η η_f η_g η_fh ih
| .horizontalComp _ f₁ g₁ f₂ g₂ η θ => withTraceNode nm (fun _ => return m!"hComp") do
let ⟨pf₁, η_f₁⟩ ← normalize p f₁
let ⟨_, η_g₁⟩ ← normalize p g₁
let ⟨pf₁f₂, η_f₂⟩ ← normalize pf₁ f₂
let ⟨_, η_g₂⟩ ← normalize pf₁ g₂
let ih_η ← naturality nm p η
let ih_θ ← naturality nm pf₁ θ
mkNaturalityHorizontalComp p pf₁ pf₁f₂ f₁ g₁ f₂ g₂ η θ η_f₁ η_g₁ η_f₂ η_g₂ ih_η ih_θ
| .inv _ f g η => withTraceNode nm (fun _ => return m!"inv") do
let ⟨pf, η_f⟩ ← normalize p f
let ⟨_, η_g⟩ ← normalize p g
let ih_η ← naturality nm p η
mkNaturalityInv p pf f g η η_f η_g ih_η
withTraceNode nm (fun _ => return m!"{checkEmoji} {← inferType result}") do
if ← isTracingEnabledFor nm then addTrace nm m!"proof: {result}"
return result
/-- Prove the equality between structural isomorphisms using the naturality of `normalize`. -/
class MkEqOfNaturality (m : Type → Type) where
/-- Auxiliary function for `pureCoherence`. -/
mkEqOfNaturality (η θ : Expr) (η' θ' : IsoLift) (η_f η_g : Mor₂Iso) (Hη Hθ : Expr) : m Expr
export MkEqOfNaturality (mkEqOfNaturality)
/-- Close the goal of the form `η = θ`, where `η` and `θ` are 2-isomorphisms made up only of
associators, unitors, and identities. -/
def pureCoherence (ρ : Type) [Context ρ] [MkMor₂ (CoherenceM ρ)]
[MonadMor₁ (CoherenceM ρ)] [MonadMor₂Iso (CoherenceM ρ)]
[MonadCoherehnceHom (CoherenceM ρ)] [MonadNormalizeNaturality (CoherenceM ρ)]
[MkEqOfNaturality (CoherenceM ρ)]
(nm : Name) (mvarId : MVarId) : MetaM (List MVarId) :=
mvarId.withContext do
withTraceNode nm (fun ex => match ex with
| .ok _ => return m!"{checkEmoji} coherence equality: {← mvarId.getType}"
| .error err => return m!"{crossEmoji} {err.toMessageData}") do
let e ← instantiateMVars <| ← mvarId.getType
let some (_, η, θ) := (← whnfR e).eq?
| throwError "coherence requires an equality goal"
let ctx : ρ ← mkContext η
CoherenceM.run (ctx := ctx) do
let some ηIso := (← MkMor₂.ofExpr η).isoLift? |
throwError "could not find a structural isomorphism, but {η}"
let some θIso := (← MkMor₂.ofExpr θ).isoLift? |
throwError "could not find a structural isomorphism, but {θ}"
let f ← ηIso.e.srcM
let g ← ηIso.e.tgtM
let a := f.src
let nil ← normalizedHom.nilM a
let ⟨_, η_f⟩ ← normalize nil f
let ⟨_, η_g⟩ ← normalize nil g
let Hη ← withTraceNode nm (fun ex => do return m!"{exceptEmoji ex} LHS") do
naturality nm nil ηIso.e
let Hθ ← withTraceNode nm (fun ex => do return m!"{exceptEmoji ex} RHS") do
naturality nm nil θIso.e
let H ← mkEqOfNaturality η θ ηIso θIso η_f η_g Hη Hθ
mvarId.apply H
end Mathlib.Tactic.BicategoryLike |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Coherence/Basic.lean | import Mathlib.Tactic.CategoryTheory.Coherence.Normalize
import Mathlib.Tactic.CategoryTheory.Coherence.PureCoherence
import Mathlib.CategoryTheory.Category.Basic
/-!
# The Core function for `monoidal` and `bicategory` tactics
This file provides the function `BicategoryLike.main` for proving equalities in monoidal categories
and bicategories. Using `main`, we will define the following tactics:
- `monoidal` at `Mathlib/Tactic/CategoryTheory/Monoidal/Basic.lean`
- `bicategory` at `Mathlib/Tactic/CategoryTheory/Bicategory/Basic.lean`
The `main` first normalizes the both sides using `eval`, then compares the corresponding components.
It closes the goal at non-structural parts with `rfl` and the goal at structural parts by
`pureCoherence`.
-/
open Lean Meta Elab
open CategoryTheory Mathlib.Tactic.BicategoryLike
namespace Mathlib.Tactic.BicategoryLike
theorem mk_eq {α : Type _} (a b a' b' : α) (ha : a = a') (hb : b = b') (h : a' = b') : a = b := by
simp [h, ha, hb]
/-- Transform an equality between 2-morphisms into the equality between their normalizations. -/
def normalForm (ρ : Type) [Context ρ]
[MonadMor₁ (CoherenceM ρ)]
[MonadMor₂Iso (CoherenceM ρ)]
[MonadNormalExpr (CoherenceM ρ)] [MkEval (CoherenceM ρ)]
[MkMor₂ (CoherenceM ρ)]
[MonadMor₂ (CoherenceM ρ)]
(nm : Name) (mvarId : MVarId) : MetaM (List MVarId) := do
mvarId.withContext do
let e ← instantiateMVars <| ← mvarId.getType
withTraceNode nm (fun _ => return m!"normalize: {e}") do
let some (_, e₁, e₂) := (← whnfR <| ← instantiateMVars <| e).eq?
| throwError "{nm}_nf requires an equality goal"
let ctx : ρ ← mkContext e₁
CoherenceM.run (ctx := ctx) do
let e₁' ← MkMor₂.ofExpr e₁
let e₂' ← MkMor₂.ofExpr e₂
let e₁'' ← eval nm e₁'
let e₂'' ← eval nm e₂'
let H ← mkAppM ``mk_eq #[e₁, e₂, e₁''.expr.e.e, e₂''.expr.e.e, e₁''.proof, e₂''.proof]
mvarId.apply H
universe v u
theorem mk_eq_of_cons {C : Type u} [CategoryStruct.{v} C]
{f₁ f₂ f₃ f₄ : C}
(α α' : f₁ ⟶ f₂) (η η' : f₂ ⟶ f₃) (ηs ηs' : f₃ ⟶ f₄)
(e_α : α = α') (e_η : η = η') (e_ηs : ηs = ηs') :
α ≫ η ≫ ηs = α' ≫ η' ≫ ηs' := by
simp [e_α, e_η, e_ηs]
/-- Split the goal `α ≫ η ≫ ηs = α' ≫ η' ≫ ηs'` into `α = α'`, `η = η'`, and `ηs = ηs'`. -/
def ofNormalizedEq (mvarId : MVarId) : MetaM (List MVarId) := do
mvarId.withContext do
let e ← instantiateMVars <| ← mvarId.getType
let some (_, e₁, e₂) := (← whnfR e).eq? | throwError "requires an equality goal"
match (← whnfR e₁).getAppFnArgs, (← whnfR e₂).getAppFnArgs with
| (``CategoryStruct.comp, #[_, _, _, _, _, α, η]),
(``CategoryStruct.comp, #[_, _, _, _, _, α', η']) =>
match (← whnfR η).getAppFnArgs, (← whnfR η').getAppFnArgs with
| (``CategoryStruct.comp, #[_, _, _, _, _, η, ηs]),
(``CategoryStruct.comp, #[_, _, _, _, _, η', ηs']) =>
let e_α ← mkFreshExprMVar (← Meta.mkEq α α')
let e_η ← mkFreshExprMVar (← Meta.mkEq η η')
let e_ηs ← mkFreshExprMVar (← Meta.mkEq ηs ηs')
let x ← mvarId.apply (← mkAppM ``mk_eq_of_cons #[α, α', η, η', ηs, ηs', e_α, e_η, e_ηs])
return x
| _, _ => throwError "failed to make a normalized equality for {e}"
| _, _ => throwError "failed to make a normalized equality for {e}"
/-- List.splitEvenOdd [0, 1, 2, 3, 4] = ([0, 2, 4], [1, 3]) -/
def List.splitEvenOdd {α : Type u} : List α → List α × List α
| [] => ([], [])
| [a] => ([a], [])
| a::b::xs =>
let (as, bs) := List.splitEvenOdd xs
(a::as, b::bs)
/-- The core function for `monoidal` and `bicategory` tactics. -/
def main (ρ : Type) [Context ρ] [MonadMor₁ (CoherenceM ρ)] [MonadMor₂Iso (CoherenceM ρ)]
[MonadNormalExpr (CoherenceM ρ)] [MkEval (CoherenceM ρ)] [MkMor₂ (CoherenceM ρ)]
[MonadMor₂ (CoherenceM ρ)] [MonadCoherehnceHom (CoherenceM ρ)]
[MonadNormalizeNaturality (CoherenceM ρ)] [MkEqOfNaturality (CoherenceM ρ)]
(nm : Name) (mvarId : MVarId) : MetaM (List MVarId) :=
mvarId.withContext do
let mvarIds ← normalForm ρ nm mvarId
let (mvarIdsCoherence, mvarIdsRefl) := List.splitEvenOdd (← repeat' ofNormalizedEq mvarIds)
for mvarId in mvarIdsRefl do mvarId.refl
let mvarIds'' ← mvarIdsCoherence.mapM fun mvarId => do
withTraceNode nm (fun _ => do return m!"goal: {← mvarId.getType}") do
try
pureCoherence ρ nm mvarId
catch _ => return [mvarId]
return mvarIds''.flatten
end Mathlib.Tactic.BicategoryLike |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Coherence/Normalize.lean | import Lean.Meta.AppBuilder
import Mathlib.Tactic.CategoryTheory.Coherence.Datatypes
/-!
# Normalization of 2-morphisms in bicategories
This file provides a function that normalizes 2-morphisms in bicategories. The function also
used to normalize morphisms in monoidal categories. This is used in the string diagram widget given
in `Mathlib/Tactic/StringDiagram.lean`, as well as `monoidal` and `bicategory` tactics.
We say that the 2-morphism `η` in a bicategory is in normal form if
1. `η` is of the form `α₀ ≫ η₀ ≫ α₁ ≫ η₁ ≫ ... αₘ ≫ ηₘ ≫ αₘ₊₁` where each `αᵢ` is a
structural 2-morphism (consisting of associators and unitors),
2. each `ηᵢ` is a non-structural 2-morphism of the form `f₁ ◁ ... ◁ fₙ ◁ θ`, and
3. `θ` is of the form `ι₁ ◫ ... ◫ ιₗ`, and
4. each `ιᵢ` is of the form `κ ▷ g₁ ▷ ... ▷ gₖ`.
Note that the horizontal composition `◫` is not currently defined for bicategories. In the monoidal
category setting, the horizontal composition is defined as the `tensorHom`, denoted by `⊗`.
Note that the structural morphisms `αᵢ` are not necessarily normalized, as the main purpose
is to get a list of the non-structural morphisms out.
Currently, the primary application of the normalization tactic in mind is drawing string diagrams,
which are graphical representations of morphisms in monoidal categories, in the infoview. When
drawing string diagrams, we often ignore associators and unitors (i.e., drawing morphisms in
strict monoidal categories). On the other hand, in Lean, it is considered difficult to formalize
the concept of strict monoidal categories due to the feature of dependent type theory. The
normalization tactic can remove associators and unitors from the expression, extracting the
necessary data for drawing string diagrams.
The string diagrams widget is to use Penrose (https://github.com/penrose) via ProofWidget.
However, it should be noted that the normalization procedure in this file does not rely on specific
settings, allowing for broader application. Future plans include the following. At least I (Yuma)
would like to work on these in the future, but it might not be immediate. If anyone is interested,
I would be happy to discuss.
- Currently, the string diagrams widget only do drawing. It would be better they also generate
proofs. That is, by manipulating the string diagrams displayed in the infoview with a mouse to
generate proofs. In https://github.com/leanprover-community/mathlib4/pull/10581,
the string diagram widget only uses the morphisms generated by the
normalization tactic and does not use proof terms ensuring that the original morphism and the
normalized morphism are equal. Proof terms will be necessary for proof generation.
- There is also the possibility of using homotopy.io (https://github.com/homotopy-io), a graphical
proof assistant for category theory, from Lean. At this point, I have very few ideas regarding
this approach.
## Main definitions
- `Tactic.BicategoryLike.eval`: Given a Lean expression `e` that represents a morphism in a monoidal
category, this function returns a pair of `⟨e', pf⟩` where `e'` is the normalized expression of `e`
and `pf` is a proof that `e = e'`.
-/
open Lean Meta
namespace Mathlib.Tactic.BicategoryLike
section
/-- Expressions of the form `η ▷ f₁ ▷ ... ▷ fₙ`. -/
inductive WhiskerRight : Type
/-- Construct the expression for an atomic 2-morphism. -/
| of (η : Atom) : WhiskerRight
/-- Construct the expression for `η ▷ f`. -/
| whisker (e : Mor₂) (η : WhiskerRight) (f : Atom₁) : WhiskerRight
deriving Inhabited
/-- The underlying `Mor₂` term of a `WhiskerRight` term. -/
def WhiskerRight.e : WhiskerRight → Mor₂
| .of η => .of η
| .whisker e .. => e
/-- Expressions of the form `η₁ ⊗ ... ⊗ ηₙ`. -/
inductive HorizontalComp : Type
| of (η : WhiskerRight) : HorizontalComp
| cons (e : Mor₂) (η : WhiskerRight) (ηs : HorizontalComp) :
HorizontalComp
deriving Inhabited
/-- The underlying `Mor₂` term of a `HorizontalComp` term. -/
def HorizontalComp.e : HorizontalComp → Mor₂
| .of η => η.e
| .cons e .. => e
/-- Expressions of the form `f₁ ◁ ... ◁ fₙ ◁ η`. -/
inductive WhiskerLeft : Type
/-- Construct the expression for a right-whiskered 2-morphism. -/
| of (η : HorizontalComp) : WhiskerLeft
/-- Construct the expression for `f ◁ η`. -/
| whisker (e : Mor₂) (f : Atom₁) (η : WhiskerLeft) : WhiskerLeft
deriving Inhabited
/-- The underlying `Mor₂` term of a `WhiskerLeft` term. -/
def WhiskerLeft.e : WhiskerLeft → Mor₂
| .of η => η.e
| .whisker e .. => e
/-- Whether a given 2-isomorphism is structural or not. -/
def Mor₂Iso.isStructural (α : Mor₂Iso) : Bool :=
match α with
| .structuralAtom _ => true
| .comp _ _ _ _ η θ => η.isStructural && θ.isStructural
| .whiskerLeft _ _ _ _ η => η.isStructural
| .whiskerRight _ _ _ η _ => η.isStructural
| .horizontalComp _ _ _ _ _ η θ => η.isStructural && θ.isStructural
| .inv _ _ _ η => η.isStructural
| .coherenceComp _ _ _ _ _ _ η θ => η.isStructural && θ.isStructural
| .of _ => false
/-- Expressions for structural isomorphisms. We do not impose the condition `isStructural` since
it is not needed to write the tactic. -/
abbrev Structural := Mor₂Iso
/-- Normalized expressions for 2-morphisms. -/
inductive NormalExpr : Type
/-- Construct the expression for a structural 2-morphism. -/
| nil (e : Mor₂) (α : Structural) : NormalExpr
/-- Construct the normalized expression of a 2-morphism `α ≫ η ≫ ηs` recursively. -/
| cons (e : Mor₂) (α : Structural) (η : WhiskerLeft) (ηs : NormalExpr) : NormalExpr
deriving Inhabited
/-- The underlying `Mor₂` term of a `NormalExpr` term. -/
def NormalExpr.e : NormalExpr → Mor₂
| .nil e .. => e
| .cons e .. => e
/-- A monad equipped with the ability to construct `WhiskerRight` terms. -/
class MonadWhiskerRight (m : Type → Type) where
/-- The expression for the right whiskering `η ▷ f`. -/
whiskerRightM (η : WhiskerRight) (f : Atom₁) : m WhiskerRight
/-- A monad equipped with the ability to construct `HorizontalComp` terms. -/
class MonadHorizontalComp (m : Type → Type) extends MonadWhiskerRight m where
/-- The expression for the horizontal composition `η ◫ ηs`. -/
hConsM (η : WhiskerRight) (ηs : HorizontalComp) : m HorizontalComp
/-- A monad equipped with the ability to construct `WhiskerLeft` terms. -/
class MonadWhiskerLeft (m : Type → Type) extends MonadHorizontalComp m where
/-- The expression for the left whiskering `f ▷ η`. -/
whiskerLeftM (f : Atom₁) (η : WhiskerLeft) : m WhiskerLeft
/-- A monad equipped with the ability to construct `NormalExpr` terms. -/
class MonadNormalExpr (m : Type → Type) extends MonadWhiskerLeft m where
/-- The expression for the structural 2-morphism `α`. -/
nilM (α : Structural) : m NormalExpr
/-- The expression for the normalized 2-morphism `α ≫ η ≫ ηs`. -/
consM (headStructural : Structural) (η : WhiskerLeft) (ηs : NormalExpr) : m NormalExpr
variable {m : Type → Type} [Monad m]
open MonadMor₁
/-- The domain of a 2-morphism. -/
def WhiskerRight.srcM [MonadMor₁ m] : WhiskerRight → m Mor₁
| WhiskerRight.of η => return η.src
| WhiskerRight.whisker _ η f => do comp₁M (← η.srcM) (.of f)
/-- The codomain of a 2-morphism. -/
def WhiskerRight.tgtM [MonadMor₁ m] : WhiskerRight → m Mor₁
| WhiskerRight.of η => return η.tgt
| WhiskerRight.whisker _ η f => do comp₁M (← η.tgtM) (.of f)
/-- The domain of a 2-morphism. -/
def HorizontalComp.srcM [MonadMor₁ m] : HorizontalComp → m Mor₁
| HorizontalComp.of η => η.srcM
| HorizontalComp.cons _ η ηs => do comp₁M (← η.srcM) (← ηs.srcM)
/-- The codomain of a 2-morphism. -/
def HorizontalComp.tgtM [MonadMor₁ m] : HorizontalComp → m Mor₁
| HorizontalComp.of η => η.tgtM
| HorizontalComp.cons _ η ηs => do comp₁M (← η.tgtM) (← ηs.tgtM)
/-- The domain of a 2-morphism. -/
def WhiskerLeft.srcM [MonadMor₁ m] : WhiskerLeft → m Mor₁
| WhiskerLeft.of η => η.srcM
| WhiskerLeft.whisker _ f η => do comp₁M (.of f) (← η.srcM)
/-- The codomain of a 2-morphism. -/
def WhiskerLeft.tgtM [MonadMor₁ m] : WhiskerLeft → m Mor₁
| WhiskerLeft.of η => η.tgtM
| WhiskerLeft.whisker _ f η => do comp₁M (.of f) (← η.tgtM)
/-- The domain of a 2-morphism. -/
def NormalExpr.srcM [MonadMor₁ m] : NormalExpr → m Mor₁
| NormalExpr.nil _ η => η.srcM
| NormalExpr.cons _ α _ _ => α.srcM
/-- The codomain of a 2-morphism. -/
def NormalExpr.tgtM [MonadMor₁ m] : NormalExpr → m Mor₁
| NormalExpr.nil _ η => η.tgtM
| NormalExpr.cons _ _ _ ηs => ηs.tgtM
namespace NormalExpr
variable [MonadMor₂Iso m] [MonadNormalExpr m]
/-- The identity 2-morphism as a term of `normalExpr`. -/
def idM (f : Mor₁) : m NormalExpr := do
MonadNormalExpr.nilM <| .structuralAtom <| ← MonadMor₂Iso.id₂M f
/-- The associator as a term of `normalExpr`. -/
def associatorM (f g h : Mor₁) : m NormalExpr := do
MonadNormalExpr.nilM <| .structuralAtom <| ← MonadMor₂Iso.associatorM f g h
/-- The inverse of the associator as a term of `normalExpr`. -/
def associatorInvM (f g h : Mor₁) : m NormalExpr := do
MonadNormalExpr.nilM <| ← MonadMor₂Iso.symmM <|
.structuralAtom <| ← MonadMor₂Iso.associatorM f g h
/-- The left unitor as a term of `normalExpr`. -/
def leftUnitorM (f : Mor₁) : m NormalExpr := do
MonadNormalExpr.nilM <| .structuralAtom <| ← MonadMor₂Iso.leftUnitorM f
/-- The inverse of the left unitor as a term of `normalExpr`. -/
def leftUnitorInvM (f : Mor₁) : m NormalExpr := do
MonadNormalExpr.nilM <| ← MonadMor₂Iso.symmM <| .structuralAtom <| ← MonadMor₂Iso.leftUnitorM f
/-- The right unitor as a term of `normalExpr`. -/
def rightUnitorM (f : Mor₁) : m NormalExpr := do
MonadNormalExpr.nilM <| .structuralAtom <| ← MonadMor₂Iso.rightUnitorM f
/-- The inverse of the right unitor as a term of `normalExpr`. -/
def rightUnitorInvM (f : Mor₁) : m NormalExpr := do
MonadNormalExpr.nilM <| ← MonadMor₂Iso.symmM <| .structuralAtom <| ← MonadMor₂Iso.rightUnitorM f
/-- Construct a `NormalExpr` expression from a `WhiskerLeft` expression. -/
def ofM [MonadMor₁ m] (η : WhiskerLeft) : m NormalExpr := do
MonadNormalExpr.consM ((.structuralAtom <| ← MonadMor₂Iso.id₂M (← η.srcM))) η
(← MonadNormalExpr.nilM ((.structuralAtom <| ← MonadMor₂Iso.id₂M (← η.tgtM))))
/-- Construct a `NormalExpr` expression from a Lean expression for an atomic 2-morphism. -/
def ofAtomM [MonadMor₁ m] (η : Atom) : m NormalExpr :=
NormalExpr.ofM <| .of <| .of <| .of η
end NormalExpr
/-- Convert a `NormalExpr` expression into a list of `WhiskerLeft` expressions. -/
def NormalExpr.toList : NormalExpr → List WhiskerLeft
| NormalExpr.nil _ _ => []
| NormalExpr.cons _ _ η ηs => η :: NormalExpr.toList ηs
end
section
/-- The result of evaluating an expression into normal form. -/
structure Eval.Result where
/-- The normalized expression of the 2-morphism. -/
expr : NormalExpr
/-- The proof that the normalized expression is equal to the original expression. -/
proof : Expr
deriving Inhabited
variable {m : Type → Type}
/-- Evaluate the expression `α ≫ β`. -/
class MkEvalComp (m : Type → Type) where
/-- Evaluate `α ≫ β` -/
mkEvalCompNilNil (α β : Structural) : m Expr
/-- Evaluate `α ≫ (β ≫ η ≫ ηs)` -/
mkEvalCompNilCons (α β : Structural) (η : WhiskerLeft) (ηs : NormalExpr) : m Expr
/-- Evaluate `(α ≫ η ≫ ηs) ≫ θ` -/
mkEvalCompCons (α : Structural) (η : WhiskerLeft) (ηs θ ι : NormalExpr) (e_η : Expr) : m Expr
/-- Evaluate the expression `f ◁ η`. -/
class MkEvalWhiskerLeft (m : Type → Type) where
/-- Evaluate `f ◁ α` -/
mkEvalWhiskerLeftNil (f : Mor₁) (α : Structural) : m Expr
/-- Evaluate `f ◁ (α ≫ η ≫ ηs)`. -/
mkEvalWhiskerLeftOfCons (f : Atom₁) (α : Structural) (η : WhiskerLeft) (ηs θ : NormalExpr)
(e_θ : Expr) : m Expr
/-- Evaluate `(f ≫ g) ◁ η` -/
mkEvalWhiskerLeftComp (f g : Mor₁) (η η₁ η₂ η₃ η₄ : NormalExpr)
(e_η₁ e_η₂ e_η₃ e_η₄ : Expr) : m Expr
/-- Evaluate `𝟙 _ ◁ η` -/
mkEvalWhiskerLeftId (η η₁ η₂ : NormalExpr) (e_η₁ e_η₂ : Expr) : m Expr
/-- Evaluate the expression `η ▷ f`. -/
class MkEvalWhiskerRight (m : Type → Type) where
/-- Evaluate `η ▷ f` -/
mkEvalWhiskerRightAuxOf (η : WhiskerRight) (f : Atom₁) : m Expr
/-- Evaluate `(η ◫ ηs) ▷ f` -/
mkEvalWhiskerRightAuxCons (f : Atom₁) (η : WhiskerRight) (ηs : HorizontalComp)
(ηs' η₁ η₂ η₃ : NormalExpr) (e_ηs' e_η₁ e_η₂ e_η₃ : Expr) : m Expr
/-- Evaluate `α ▷ f` -/
mkEvalWhiskerRightNil (α : Structural) (f : Mor₁) : m Expr
/-- Evaluate ` (α ≫ η ≫ ηs) ▷ j` -/
mkEvalWhiskerRightConsOfOf (f : Atom₁) (α : Structural) (η : HorizontalComp)
(ηs ηs₁ η₁ η₂ η₃ : NormalExpr)
(e_ηs₁ e_η₁ e_η₂ e_η₃ : Expr) : m Expr
/-- Evaluate `(α ≫ (f ◁ η) ≫ ηs) ▷ g` -/
mkEvalWhiskerRightConsWhisker (f : Atom₁) (g : Mor₁) (α : Structural) (η : WhiskerLeft)
(ηs η₁ η₂ ηs₁ ηs₂ η₃ η₄ η₅ : NormalExpr) (e_η₁ e_η₂ e_ηs₁ e_ηs₂ e_η₃ e_η₄ e_η₅ : Expr) : m Expr
/-- Evaluate `η ▷ (g ⊗ h)` -/
mkEvalWhiskerRightComp (g h : Mor₁)
(η η₁ η₂ η₃ η₄ : NormalExpr) (e_η₁ e_η₂ e_η₃ e_η₄ : Expr) : m Expr
/-- Evaluate `η ▷ 𝟙 _` -/
mkEvalWhiskerRightId (η η₁ η₂ : NormalExpr) (e_η₁ e_η₂ : Expr) : m Expr
/-- Evaluate the expression `η ◫ θ`. -/
class MkEvalHorizontalComp (m : Type → Type) where
/-- Evaluate `η ◫ θ` -/
mkEvalHorizontalCompAuxOf (η : WhiskerRight) (θ : HorizontalComp) : m Expr
/-- Evaluate `(η ◫ ηs) ◫ θ` -/
mkEvalHorizontalCompAuxCons (η : WhiskerRight) (ηs θ : HorizontalComp)
(ηθ η₁ ηθ₁ ηθ₂ : NormalExpr) (e_ηθ e_η₁ e_ηθ₁ e_ηθ₂ : Expr) : m Expr
/-- Evaluate `(f ◁ η) ◫ θ` -/
mkEvalHorizontalCompAux'Whisker (f : Atom₁) (η θ : WhiskerLeft)
(ηθ ηθ₁ ηθ₂ ηθ₃ : NormalExpr) (e_ηθ e_ηθ₁ e_ηθ₂ e_ηθ₃ : Expr) : m Expr
/-- Evaluate `η ◫ (f ◁ θ)` -/
mkEvalHorizontalCompAux'OfWhisker (f : Atom₁) (η : HorizontalComp) (θ : WhiskerLeft)
(η₁ ηθ ηθ₁ ηθ₂ : NormalExpr) (e_ηθ e_η₁ e_ηθ₁ e_ηθ₂ : Expr) : m Expr
/-- Evaluate `α ◫ β` -/
mkEvalHorizontalCompNilNil (α β : Structural) : m Expr
/-- Evaluate `α ◫ (β ≫ η ≫ ηs)` -/
mkEvalHorizontalCompNilCons (α β : Structural) (η : WhiskerLeft)
(ηs η₁ ηs₁ η₂ η₃ : NormalExpr) (e_η₁ e_ηs₁ e_η₂ e_η₃ : Expr) : m Expr
/-- Evaluate `(α ≫ η ≫ ηs) ◫ β` -/
mkEvalHorizontalCompConsNil (α β : Structural) (η : WhiskerLeft) (ηs : NormalExpr)
(η₁ ηs₁ η₂ η₃ : NormalExpr) (e_η₁ e_ηs₁ e_η₂ e_η₃ : Expr) : m Expr
/-- Evaluate `(α ≫ η ≫ ηs) ◫ (β ≫ θ ≫ θs)` -/
mkEvalHorizontalCompConsCons (α β : Structural) (η θ : WhiskerLeft)
(ηs θs ηθ ηθs ηθ₁ ηθ₂ : NormalExpr) (e_ηθ e_ηθs e_ηθ₁ e_ηθ₂ : Expr) : m Expr
/-- Evaluate the expression of a 2-morphism into a normalized form. -/
class MkEval (m : Type → Type) extends
MkEvalComp m, MkEvalWhiskerLeft m, MkEvalWhiskerRight m, MkEvalHorizontalComp m where
/-- Evaluate the expression `η ≫ θ` into a normalized form. -/
mkEvalComp (η θ : Mor₂) (η' θ' ηθ : NormalExpr) (e_η e_θ e_ηθ : Expr) : m Expr
/-- Evaluate the expression `f ◁ η` into a normalized form. -/
mkEvalWhiskerLeft (f : Mor₁) (η : Mor₂) (η' θ : NormalExpr) (e_η e_θ : Expr) : m Expr
/-- Evaluate the expression `η ▷ f` into a normalized form. -/
mkEvalWhiskerRight (η : Mor₂) (h : Mor₁) (η' θ : NormalExpr) (e_η e_θ : Expr) : m Expr
/-- Evaluate the expression `η ◫ θ` into a normalized form. -/
mkEvalHorizontalComp (η θ : Mor₂) (η' θ' ι : NormalExpr) (e_η e_θ e_ι : Expr) : m Expr
/-- Evaluate the atomic 2-morphism `η` into a normalized form. -/
mkEvalOf (η : Atom) : m Expr
/-- Evaluate the expression `η ⊗≫ θ := η ≫ α ≫ θ` into a normalized form. -/
mkEvalMonoidalComp (η θ : Mor₂) (α : Structural) (η' θ' αθ ηαθ : NormalExpr)
(e_η e_θ e_αθ e_ηαθ : Expr) : m Expr
variable {ρ : Type}
variable [MonadMor₂Iso (CoherenceM ρ)] [MonadNormalExpr (CoherenceM ρ)] [MkEval (CoherenceM ρ)]
open MkEvalComp MonadMor₂Iso MonadNormalExpr
/-- Evaluate the expression `α ≫ η` into a normalized form. -/
def evalCompNil (α : Structural) : NormalExpr → CoherenceM ρ Eval.Result
| .nil _ β => do return ⟨← nilM (← comp₂M α β), ← mkEvalCompNilNil α β⟩
| .cons _ β η ηs => do return ⟨← consM (← comp₂M α β) η ηs, ← mkEvalCompNilCons α β η ηs⟩
/-- Evaluate the expression `η ≫ θ` into a normalized form. -/
def evalComp : NormalExpr → NormalExpr → CoherenceM ρ Eval.Result
| .nil _ α, η => do evalCompNil α η
| .cons _ α η ηs, θ => do
let ⟨ι, e_ι⟩ ← evalComp ηs θ
return ⟨← consM α η ι, ← mkEvalCompCons α η ηs θ ι e_ι⟩
open MkEvalWhiskerLeft
variable [MonadMor₁ (CoherenceM ρ)] [MonadMor₂Iso (CoherenceM ρ)]
/-- Evaluate the expression `f ◁ η` into a normalized form. -/
def evalWhiskerLeft : Mor₁ → NormalExpr → CoherenceM ρ Eval.Result
| f, .nil _ α => do
return ⟨← nilM (← whiskerLeftM f α), ← mkEvalWhiskerLeftNil f α⟩
| .of f, .cons _ α η ηs => do
let η' ← MonadWhiskerLeft.whiskerLeftM f η
let ⟨θ, e_θ⟩ ← evalWhiskerLeft (.of f) ηs
let η'' ← consM (← whiskerLeftM (.of f) α) η' θ
return ⟨η'', ← mkEvalWhiskerLeftOfCons f α η ηs θ e_θ⟩
| .comp _ f g, η => do
let ⟨θ, e_θ⟩ ← evalWhiskerLeft g η
let ⟨ι, e_ι⟩ ← evalWhiskerLeft f θ
let h ← η.srcM
let h' ← η.tgtM
let ⟨ι', e_ι'⟩ ← evalComp ι (← NormalExpr.associatorInvM f g h')
let ⟨ι'', e_ι''⟩ ← evalComp (← NormalExpr.associatorM f g h) ι'
return ⟨ι'', ← mkEvalWhiskerLeftComp f g η θ ι ι' ι'' e_θ e_ι e_ι' e_ι''⟩
| .id _ _, η => do
let f ← η.srcM
let g ← η.tgtM
let ⟨η', e_η'⟩ ← evalComp η (← NormalExpr.leftUnitorInvM g)
let ⟨η'', e_η''⟩ ← evalComp (← NormalExpr.leftUnitorM f) η'
return ⟨η'', ← mkEvalWhiskerLeftId η η' η'' e_η' e_η''⟩
open MkEvalWhiskerRight MkEvalHorizontalComp
mutual
/-- Evaluate the expression `η ▷ f` into a normalized form. -/
partial def evalWhiskerRightAux : HorizontalComp → Atom₁ → CoherenceM ρ Eval.Result
| .of η, f => do
let η' ← NormalExpr.ofM <| .of <| .of <| ← MonadWhiskerRight.whiskerRightM η f
return ⟨η', ← mkEvalWhiskerRightAuxOf η f⟩
| .cons _ η ηs, f => do
let ⟨ηs', e_ηs'⟩ ← evalWhiskerRightAux ηs f
let ⟨η₁, e_η₁⟩ ← evalHorizontalComp (← NormalExpr.ofM <| .of <| .of η) ηs'
let ⟨η₂, e_η₂⟩ ← evalComp η₁ (← NormalExpr.associatorInvM (← η.tgtM) (← ηs.tgtM) (.of f))
let ⟨η₃, e_η₃⟩ ← evalComp (← NormalExpr.associatorM (← η.srcM) (← ηs.srcM) (.of f)) η₂
return ⟨η₃, ← mkEvalWhiskerRightAuxCons f η ηs ηs' η₁ η₂ η₃ e_ηs' e_η₁ e_η₂ e_η₃⟩
/-- Evaluate the expression `η ▷ f` into a normalized form. -/
partial def evalWhiskerRight : NormalExpr → Mor₁ → CoherenceM ρ Eval.Result
| .nil _ α, h => do
return ⟨← nilM (← whiskerRightM α h), ← mkEvalWhiskerRightNil α h⟩
| .cons _ α (.of η) ηs, .of f => do
let ⟨ηs₁, e_ηs₁⟩ ← evalWhiskerRight ηs (.of f)
let ⟨η₁, e_η₁⟩ ← evalWhiskerRightAux η f
let ⟨η₂, e_η₂⟩ ← evalComp η₁ ηs₁
let ⟨η₃, e_η₃⟩ ← evalCompNil (← whiskerRightM α (.of f)) η₂
return ⟨η₃, ← mkEvalWhiskerRightConsOfOf f α η ηs ηs₁ η₁ η₂ η₃ e_ηs₁ e_η₁ e_η₂ e_η₃⟩
| .cons _ α (.whisker _ f η) ηs, h => do
let g ← η.srcM
let g' ← η.tgtM
let ⟨η₁, e_η₁⟩ ← evalWhiskerRight (← consM (← id₂M' g) η (← NormalExpr.idM g')) h
let ⟨η₂, e_η₂⟩ ← evalWhiskerLeft (.of f) η₁
let ⟨ηs₁, e_ηs₁⟩ ← evalWhiskerRight ηs h
let α' ← whiskerRightM α h
let ⟨ηs₂, e_ηs₂⟩ ← evalComp (← NormalExpr.associatorInvM (.of f) g' h) ηs₁
let ⟨η₃, e_η₃⟩ ← evalComp η₂ ηs₂
let ⟨η₄, e_η₄⟩ ← evalComp (← NormalExpr.associatorM (.of f) g h) η₃
let ⟨η₅, e_η₅⟩ ← evalComp (← nilM α') η₄
return ⟨η₅, ← mkEvalWhiskerRightConsWhisker f h α η ηs η₁ η₂ ηs₁ ηs₂ η₃ η₄ η₅
e_η₁ e_η₂ e_ηs₁ e_ηs₂ e_η₃ e_η₄ e_η₅⟩
| η, .comp _ g h => do
let ⟨η₁, e_η₁⟩ ← evalWhiskerRight η g
let ⟨η₂, e_η₂⟩ ← evalWhiskerRight η₁ h
let f ← η.srcM
let f' ← η.tgtM
let ⟨η₃, e_η₃⟩ ← evalComp η₂ (← NormalExpr.associatorM f' g h)
let ⟨η₄, e_η₄⟩ ← evalComp (← NormalExpr.associatorInvM f g h) η₃
return ⟨η₄, ← mkEvalWhiskerRightComp g h η η₁ η₂ η₃ η₄ e_η₁ e_η₂ e_η₃ e_η₄⟩
| η, .id _ _ => do
let f ← η.srcM
let g ← η.tgtM
let ⟨η₁, e_η₁⟩ ← evalComp η (← NormalExpr.rightUnitorInvM g)
let ⟨η₂, e_η₂⟩ ← evalComp (← NormalExpr.rightUnitorM f) η₁
return ⟨η₂, ← mkEvalWhiskerRightId η η₁ η₂ e_η₁ e_η₂⟩
/-- Evaluate the expression `η ⊗ θ` into a normalized form. -/
partial def evalHorizontalCompAux : HorizontalComp → HorizontalComp → CoherenceM ρ Eval.Result
| .of η, θ => do
return ⟨← NormalExpr.ofM <| .of <| ← MonadHorizontalComp.hConsM η θ,
← mkEvalHorizontalCompAuxOf η θ⟩
| .cons _ η ηs, θ => do
let α ← NormalExpr.associatorM (← η.srcM) (← ηs.srcM) (← θ.srcM)
let α' ← NormalExpr.associatorInvM (← η.tgtM) (← ηs.tgtM) (← θ.tgtM)
let ⟨ηθ, e_ηθ⟩ ← evalHorizontalCompAux ηs θ
let ⟨η₁, e_η₁⟩ ← evalHorizontalComp (← NormalExpr.ofM <| .of <| .of η) ηθ
let ⟨ηθ₁, e_ηθ₁⟩ ← evalComp η₁ α'
let ⟨ηθ₂, e_ηθ₂⟩ ← evalComp α ηθ₁
return ⟨ηθ₂, ← mkEvalHorizontalCompAuxCons η ηs θ ηθ η₁ ηθ₁ ηθ₂ e_ηθ e_η₁ e_ηθ₁ e_ηθ₂⟩
/-- Evaluate the expression `η ⊗ θ` into a normalized form. -/
partial def evalHorizontalCompAux' : WhiskerLeft → WhiskerLeft → CoherenceM ρ Eval.Result
| .of η, .of θ => evalHorizontalCompAux η θ
| .whisker _ f η, θ => do
let ⟨ηθ, e_ηθ⟩ ← evalHorizontalCompAux' η θ
let ⟨ηθ₁, e_ηθ₁⟩ ← evalWhiskerLeft (.of f) ηθ
let ⟨ηθ₂, e_ηθ₂⟩ ← evalComp ηθ₁ (← NormalExpr.associatorInvM (.of f) (← η.tgtM) (← θ.tgtM))
let ⟨ηθ₃, e_ηθ₃⟩ ← evalComp (← NormalExpr.associatorM (.of f) (← η.srcM) (← θ.srcM)) ηθ₂
return ⟨ηθ₃, ← mkEvalHorizontalCompAux'Whisker f η θ ηθ ηθ₁ ηθ₂ ηθ₃ e_ηθ e_ηθ₁ e_ηθ₂ e_ηθ₃⟩
| .of η, .whisker _ f θ => do
let ⟨η₁, e_η₁⟩ ← evalWhiskerRightAux η f
let ⟨ηθ, e_ηθ⟩ ← evalHorizontalComp η₁ (← NormalExpr.ofM θ)
let ⟨ηθ₁, e_ηθ₁⟩ ← evalComp ηθ (← NormalExpr.associatorM (← η.tgtM) (.of f) (← θ.tgtM))
let ⟨ηθ₂, e_ηθ₂⟩ ← evalComp (← NormalExpr.associatorInvM (← η.srcM) (.of f) (← θ.srcM)) ηθ₁
return ⟨ηθ₂, ← mkEvalHorizontalCompAux'OfWhisker f η θ ηθ η₁ ηθ₁ ηθ₂ e_η₁ e_ηθ e_ηθ₁ e_ηθ₂⟩
/-- Evaluate the expression `η ⊗ θ` into a normalized form. -/
partial def evalHorizontalComp : NormalExpr → NormalExpr → CoherenceM ρ Eval.Result
| .nil _ α, .nil _ β => do
return ⟨← nilM <| ← horizontalCompM α β, ← mkEvalHorizontalCompNilNil α β⟩
| .nil _ α, .cons _ β η ηs => do
let ⟨η₁, e_η₁⟩ ← evalWhiskerLeft (← α.tgtM) (← NormalExpr.ofM η)
let ⟨ηs₁, e_ηs₁⟩ ← evalWhiskerLeft (← α.tgtM) ηs
let ⟨η₂, e_η₂⟩ ← evalComp η₁ ηs₁
let ⟨η₃, e_η₃⟩ ← evalCompNil (← horizontalCompM α β) η₂
return ⟨η₃, ← mkEvalHorizontalCompNilCons α β η ηs η₁ ηs₁ η₂ η₃ e_η₁ e_ηs₁ e_η₂ e_η₃⟩
| .cons _ α η ηs, .nil _ β => do
let ⟨η₁, e_η₁⟩ ← evalWhiskerRight (← NormalExpr.ofM η) (← β.tgtM)
let ⟨ηs₁, e_ηs₁⟩ ← evalWhiskerRight ηs (← β.tgtM)
let ⟨η₂, e_η₂⟩ ← evalComp η₁ ηs₁
let ⟨η₃, e_η₃⟩ ← evalCompNil (← horizontalCompM α β) η₂
return ⟨η₃, ← mkEvalHorizontalCompConsNil α β η ηs η₁ ηs₁ η₂ η₃ e_η₁ e_ηs₁ e_η₂ e_η₃⟩
| .cons _ α η ηs, .cons _ β θ θs => do
let ⟨ηθ, e_ηθ⟩ ← evalHorizontalCompAux' η θ
let ⟨ηθs, e_ηθs⟩ ← evalHorizontalComp ηs θs
let ⟨ηθ₁, e_ηθ₁⟩ ← evalComp ηθ ηθs
let ⟨ηθ₂, e_ηθ₂⟩ ← evalCompNil (← horizontalCompM α β) ηθ₁
return ⟨ηθ₂,
← mkEvalHorizontalCompConsCons α β η θ ηs θs ηθ ηθs ηθ₁ ηθ₂ e_ηθ e_ηθs e_ηθ₁ e_ηθ₂⟩
end
open MkEval
variable {ρ : Type}
[MonadMor₁ (CoherenceM ρ)]
[MonadMor₂Iso (CoherenceM ρ)]
[MonadNormalExpr (CoherenceM ρ)] [MkEval (CoherenceM ρ)]
[MonadMor₂ (CoherenceM ρ)]
/-- Trace the proof of the normalization. -/
def traceProof (nm : Name) (result : Expr) : CoherenceM ρ Unit := do
withTraceNode nm (fun _ => return m!"{checkEmoji} {← inferType result}") do
if ← isTracingEnabledFor nm then addTrace nm m!"proof: {result}"
-- TODO: It takes a while to compile. Find out why.
/-- Evaluate the expression of a 2-morphism into a normalized form. -/
def eval (nm : Name) (e : Mor₂) : CoherenceM ρ Eval.Result := do
withTraceNode nm (fun _ => return m!"eval: {e.e}") do
match e with
| .isoHom _ _ α => withTraceNode nm (fun _ => return m!"Iso.hom") do match α with
| .structuralAtom α => return ⟨← nilM <| .structuralAtom α, ← mkEqRefl e.e⟩
| .of η =>
let η ← MonadMor₂.atomHomM η
let result ← mkEvalOf η
traceProof nm result
return ⟨← NormalExpr.ofAtomM η, result⟩
| _ => throwError "not implemented. try dsimp first."
| .isoInv _ _ α => withTraceNode nm (fun _ => return m!"Iso.inv") do match α with
| .structuralAtom α => return ⟨← nilM <| (← symmM (.structuralAtom α)), ← mkEqRefl e.e⟩
| .of η =>
let η ← MonadMor₂.atomInvM η
let result ← mkEvalOf η
traceProof nm result
return ⟨← NormalExpr.ofAtomM η, result⟩
| _ => throwError "not implemented. try dsimp first."
| .id _ _ f =>
let α ← MonadMor₂Iso.id₂M f
return ⟨← nilM <| .structuralAtom α, ← mkEqRefl e.e⟩
| .comp _ _ _ _ _ η θ => withTraceNode nm (fun _ => return m!"comp") do
let ⟨η', e_η⟩ ← eval nm η
let ⟨θ', e_θ⟩ ← eval nm θ
let ⟨ηθ, pf⟩ ← evalComp η' θ'
let result ← mkEvalComp η θ η' θ' ηθ e_η e_θ pf
traceProof nm result
return ⟨ηθ, result⟩
| .whiskerLeft _ _ f _ _ η => withTraceNode nm (fun _ => return m!"whiskerLeft") do
let ⟨η', e_η⟩ ← eval nm η
let ⟨θ, e_θ⟩ ← evalWhiskerLeft f η'
let result ← mkEvalWhiskerLeft f η η' θ e_η e_θ
traceProof nm result
return ⟨θ, result⟩
| .whiskerRight _ _ _ _ η h =>
withTraceNode nm (fun _ => return m!"whiskerRight") do
let ⟨η', e_η⟩ ← eval nm η
let ⟨θ, e_θ⟩ ← evalWhiskerRight η' h
let result ← mkEvalWhiskerRight η h η' θ e_η e_θ
traceProof nm result
return ⟨θ, result⟩
| .coherenceComp _ _ _ _ _ _ α₀ η θ =>
withTraceNode nm (fun _ => return m!"monoidalComp") do
let ⟨η', e_η⟩ ← eval nm η
let α₀ := .structuralAtom <| .coherenceHom α₀
let α ← nilM α₀
let ⟨θ', e_θ⟩ ← eval nm θ
let ⟨αθ, e_αθ⟩ ← evalComp α θ'
let ⟨ηαθ, e_ηαθ⟩ ← evalComp η' αθ
let result ← mkEvalMonoidalComp η θ α₀ η' θ' αθ ηαθ e_η e_θ e_αθ e_ηαθ
traceProof nm result
return ⟨ηαθ, result⟩
| .horizontalComp _ _ _ _ _ _ η θ =>
withTraceNode nm (fun _ => return m!"horizontalComp") do
let ⟨η', e_η⟩ ← eval nm η
let ⟨θ', e_θ⟩ ← eval nm θ
let ⟨ηθ, e_ηθ⟩ ← evalHorizontalComp η' θ'
let result ← mkEvalHorizontalComp η θ η' θ' ηθ e_η e_θ e_ηθ
traceProof nm result
return ⟨ηθ, result⟩
| .of η =>
let result ← mkEvalOf η
traceProof nm result
return ⟨← NormalExpr.ofAtomM η, result⟩
end
end Mathlib.Tactic.BicategoryLike |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Coherence/Datatypes.lean | import Lean.Meta.Basic
import Mathlib.Init
/-!
# Datatypes for bicategory like structures
This file defines the basic datatypes for bicategory like structures. We will use these datatypes
to write tactics that can be applied to both monoidal categories and bicategories:
- `Obj`: objects type
- `Atom₁`: atomic 1-morphisms type
- `Mor₁`: 1-morphisms type
- `Atom`: atomic non-structural 2-morphisms type
- `Mor₂`: 2-morphisms type
- `AtomIso`: atomic non-structural 2-isomorphisms type
- `Mor₂Iso`: 2-isomorphisms type
- `NormalizedHom`: normalized 1-morphisms type
A term of these datatypes wraps the corresponding `Expr` term, which can be extracted by
e.g. `η.e` for `η : Mor₂`.
The operations of these datatypes are defined in a monad `m` with the corresponding typeclasses:
- `MonadMor₁`: operations on `Mor₁`
- `MonadMor₂Iso`: operations on `Mor₂Iso`
- `MonadMor₂`: operations on `Mor₂`
For example, a monad `m` with `[MonadMor₂ m]` provides the operation
`MonadMor₂.comp₂M : Mor₂Iso → Mor₂Iso → m Mor₂Iso`, which constructs the expression for the
composition `η ≫ θ` of 2-morphisms `η` and `θ` in the monad `m`.
-/
open Lean Meta
namespace Mathlib.Tactic
namespace BicategoryLike
/-- Expressions for objects. -/
structure Obj where
/-- Extracts a lean expression from an `Obj` term. Return `none` in the monoidal
category context. -/
e? : Option Expr
deriving Inhabited
/-- Extract a lean expression from an `Obj` term. -/
def Obj.e (a : Obj) : Expr :=
a.e?.get!
/-- Expressions for atomic 1-morphisms. -/
structure Atom₁ : Type where
/-- Extract a lean expression from an `Atom₁` term. -/
e : Expr
/-- The domain of the 1-morphism. -/
src : Obj
/-- The codomain of the 1-morphism. -/
tgt : Obj
deriving Inhabited
/-- A monad equipped with the ability to construct `Atom₁` terms. -/
class MkAtom₁ (m : Type → Type) where
/-- Construct a `Atom₁` term from a lean expression. -/
ofExpr (e : Expr) : m Atom₁
/-- Expressions for 1-morphisms. -/
inductive Mor₁ : Type
/-- `id e a` is the expression for `𝟙 a`, where `e` is the underlying lean expression. -/
| id (e : Expr) (a : Obj) : Mor₁
/-- `comp e f g` is the expression for `f ≫ g`, where `e` is the underlying lean expression. -/
| comp (e : Expr) : Mor₁ → Mor₁ → Mor₁
/-- The expression for an atomic 1-morphism. -/
| of : Atom₁ → Mor₁
deriving Inhabited
/-- A monad equipped with the ability to construct `Mor₁` terms. -/
class MkMor₁ (m : Type → Type) where
/-- Construct a `Mor₁` term from a lean expression. -/
ofExpr (e : Expr) : m Mor₁
/-- The underlying lean expression of a 1-morphism. -/
def Mor₁.e : Mor₁ → Expr
| .id e _ => e
| .comp e _ _ => e
| .of a => a.e
/-- The domain of a 1-morphism. -/
def Mor₁.src : Mor₁ → Obj
| .id _ a => a
| .comp _ f _ => f.src
| .of f => f.src
/-- The codomain of a 1-morphism. -/
def Mor₁.tgt : Mor₁ → Obj
| .id _ a => a
| .comp _ _ g => g.tgt
| .of f => f.tgt
/-- Converts a 1-morphism into a list of its components. -/
def Mor₁.toList : Mor₁ → List Atom₁
| .id _ _ => []
| .comp _ f g => f.toList ++ g.toList
| .of f => [f]
/-- A monad equipped with the ability to manipulate 1-morphisms. -/
class MonadMor₁ (m : Type → Type) where
/-- The expression for `𝟙 a`. -/
id₁M (a : Obj) : m Mor₁
/-- The expression for `f ≫ g`. -/
comp₁M (f g : Mor₁) : m Mor₁
/-- Expressions for coherence isomorphisms (i.e., structural 2-morphisms
given by `BicategoricalCoherence.iso`). -/
structure CoherenceHom where
/-- The underlying lean expression of a coherence isomorphism. -/
e : Expr
/-- The domain of a coherence isomorphism. -/
src : Mor₁
/-- The codomain of a coherence isomorphism. -/
tgt : Mor₁
/-- The `BicategoricalCoherence` instance. -/
inst : Expr
/-- Extract the structural 2-isomorphism. -/
unfold : Expr
deriving Inhabited
/-- Expressions for atomic non-structural 2-isomorphisms. -/
structure AtomIso where
/-- The underlying lean expression of an `AtomIso` term. -/
e : Expr
/-- The domain of a 2-isomorphism. -/
src : Mor₁
/-- The codomain of a 2-isomorphism. -/
tgt : Mor₁
deriving Inhabited
/-- Expressions for atomic structural 2-morphisms. -/
inductive StructuralAtom : Type
/-- The expression for the associator `α_ f g h`. -/
| associator (e : Expr) (f g h : Mor₁) : StructuralAtom
/-- The expression for the left unitor `λ_ f`. -/
| leftUnitor (e : Expr) (f : Mor₁) : StructuralAtom
/-- The expression for the right unitor `ρ_ f`. -/
| rightUnitor (e : Expr) (f : Mor₁) : StructuralAtom
| id (e : Expr) (f : Mor₁) : StructuralAtom
| coherenceHom (α : CoherenceHom) : StructuralAtom
deriving Inhabited
/-- Expressions for 2-isomorphisms. -/
inductive Mor₂Iso : Type where
| structuralAtom (α : StructuralAtom) : Mor₂Iso
| comp (e : Expr) (f g h : Mor₁) (η θ : Mor₂Iso) : Mor₂Iso
| whiskerLeft (e : Expr) (f g h : Mor₁) (η : Mor₂Iso) : Mor₂Iso
| whiskerRight (e : Expr) (f g : Mor₁) (η : Mor₂Iso) (h : Mor₁) : Mor₂Iso
| horizontalComp (e : Expr) (f₁ g₁ f₂ g₂ : Mor₁) (η θ : Mor₂Iso) : Mor₂Iso
| inv (e : Expr) (f g : Mor₁) (η : Mor₂Iso) : Mor₂Iso
| coherenceComp (e : Expr) (f g h i : Mor₁) (α : CoherenceHom) (η θ : Mor₂Iso) : Mor₂Iso
| of (η : AtomIso) : Mor₂Iso
deriving Inhabited
/-- A monad equipped with the ability to unfold `BicategoricalCoherence.iso`. -/
class MonadCoherehnceHom (m : Type → Type) where
/-- Unfold a coherence isomorphism. -/
unfoldM (α : CoherenceHom) : m Mor₂Iso
/-- The underlying lean expression of a 2-isomorphism. -/
def StructuralAtom.e : StructuralAtom → Expr
| .associator e .. => e
| .leftUnitor e .. => e
| .rightUnitor e .. => e
| .id e .. => e
| .coherenceHom α => α.e
open MonadMor₁
variable {m : Type → Type} [Monad m]
/-- The domain of a 2-isomorphism. -/
def StructuralAtom.srcM [MonadMor₁ m] : StructuralAtom → m Mor₁
| .associator _ f g h => do comp₁M (← comp₁M f g) h
| .leftUnitor _ f => do comp₁M (← id₁M f.src) f
| .rightUnitor _ f => do comp₁M f (← id₁M f.tgt)
| .id _ f => return f
| .coherenceHom α => return α.src
/-- The codomain of a 2-isomorphism. -/
def StructuralAtom.tgtM [MonadMor₁ m] : StructuralAtom → m Mor₁
| .associator _ f g h => do comp₁M f (← comp₁M g h)
| .leftUnitor _ f => return f
| .rightUnitor _ f => return f
| .id _ f => return f
| .coherenceHom α => return α.tgt
/-- The underlying lean expression of a 2-isomorphism. -/
def Mor₂Iso.e : Mor₂Iso → Expr
| .structuralAtom α => α.e
| .comp e .. => e
| .whiskerLeft e .. => e
| .whiskerRight e .. => e
| .horizontalComp e .. => e
| .inv e .. => e
| .coherenceComp e .. => e
| .of η => η.e
/-- The domain of a 2-isomorphism. -/
def Mor₂Iso.srcM {m : Type → Type} [Monad m] [MonadMor₁ m] : Mor₂Iso → m Mor₁
| .structuralAtom α => α.srcM
| .comp _ f .. => return f
| .whiskerLeft _ f g .. => do comp₁M f g
| .whiskerRight _ f _ _ h => do comp₁M f h
| .horizontalComp _ f₁ _ f₂ .. => do comp₁M f₁ f₂
| .inv _ _ g _ => return g
| .coherenceComp _ f .. => return f
| .of η => return η.src
/-- The codomain of a 2-isomorphism. -/
def Mor₂Iso.tgtM {m : Type → Type} [Monad m] [MonadMor₁ m] : Mor₂Iso → m Mor₁
| .structuralAtom α => α.tgtM
| .comp _ _ _ h .. => return h
| .whiskerLeft _ f _ h _ => do comp₁M f h
| .whiskerRight _ _ g _ h => do comp₁M g h
| .horizontalComp _ _ g₁ _ g₂ _ _ => do comp₁M g₁ g₂
| .inv _ f _ _ => return f
| .coherenceComp _ _ _ _ i .. => return i
| .of η => return η.tgt
/-- A monad equipped with the ability to construct `Mor₂Iso` terms. -/
class MonadMor₂Iso (m : Type → Type) where
/-- The expression for the associator `α_ f g h`. -/
associatorM (f g h : Mor₁) : m StructuralAtom
/-- The expression for the left unitor `λ_ f`. -/
leftUnitorM (f : Mor₁) : m StructuralAtom
/-- The expression for the right unitor `ρ_ f`. -/
rightUnitorM (f : Mor₁) : m StructuralAtom
/-- The expression for the identity `Iso.refl f`. -/
id₂M (f : Mor₁) : m StructuralAtom
/-- The expression for the coherence isomorphism `⊗𝟙 : f ⟶ g`. -/
coherenceHomM (f g : Mor₁) (inst : Expr) : m CoherenceHom
/-- The expression for the composition `η ≪≫ θ`. -/
comp₂M (η θ : Mor₂Iso) : m Mor₂Iso
/-- The expression for the left whiskering `whiskerLeftIso f η`. -/
whiskerLeftM (f : Mor₁) (η : Mor₂Iso) : m Mor₂Iso
/-- The expression for the right whiskering `whiskerRightIso η h`. -/
whiskerRightM (η : Mor₂Iso) (h : Mor₁) : m Mor₂Iso
/-- The expression for the horizontal composition `η ◫ θ`. -/
horizontalCompM (η θ : Mor₂Iso) : m Mor₂Iso
/-- The expression for the inverse `Iso.symm η`. -/
symmM (η : Mor₂Iso) : m Mor₂Iso
/-- The expression for the coherence composition `η ≪⊗≫ θ := η ≪≫ α ≪≫ θ`. -/
coherenceCompM (α : CoherenceHom) (η θ : Mor₂Iso) : m Mor₂Iso
namespace MonadMor₂Iso
variable {m : Type → Type} [Monad m] [MonadMor₂Iso m]
/-- The expression for the associator `α_ f g h`. -/
def associatorM' (f g h : Mor₁) : m Mor₂Iso := do
return .structuralAtom <| ← MonadMor₂Iso.associatorM f g h
/-- The expression for the left unitor `λ_ f`. -/
def leftUnitorM' (f : Mor₁) : m Mor₂Iso := do
return .structuralAtom <| ← MonadMor₂Iso.leftUnitorM f
/-- The expression for the right unitor `ρ_ f`. -/
def rightUnitorM' (f : Mor₁) : m Mor₂Iso := do
return .structuralAtom <| ← MonadMor₂Iso.rightUnitorM f
/-- The expression for the identity `Iso.refl f`. -/
def id₂M' (f : Mor₁) : m Mor₂Iso := do
return .structuralAtom <| ← MonadMor₂Iso.id₂M f
/-- The expression for the coherence isomorphism `⊗𝟙 : f ⟶ g`. -/
def coherenceHomM' (f g : Mor₁) (inst : Expr) : m Mor₂Iso := do
return .structuralAtom <| .coherenceHom <| ← MonadMor₂Iso.coherenceHomM f g inst
end MonadMor₂Iso
/-- Expressions for atomic non-structural 2-morphisms. -/
structure Atom where
/-- Extract a lean expression from an `Atom` expression. -/
e : Expr
/-- The domain of a 2-morphism. -/
src : Mor₁
/-- The codomain of a 2-morphism. -/
tgt : Mor₁
deriving Inhabited
/-- `Mor₂` expressions defined below will have the `isoLift? : Option IsoLift` field.
For `η : Mor₂` such that `η.isoLift? = some isoLift`, we have the following data:
- `isoLift.e`: an expression for a 2-isomorphism `η'`, given as a `Mor₂Iso` term,
- `isoLift.eq`: a lean expression for the proof that `η'.hom = η`.
-/
structure IsoLift where
/-- The expression for the 2-isomorphism. -/
e : Mor₂Iso
/-- The expression for the proof that the forward direction of the 2-isomorphism is equal to
the original 2-morphism. -/
eq : Expr
/-- Expressions for 2-morphisms. -/
inductive Mor₂ : Type where
/-- The expression for `Iso.hom`. -/
| isoHom (e : Expr) (isoLift : IsoLift) (iso : Mor₂Iso) : Mor₂
/-- The expression for `Iso.inv`. -/
| isoInv (e : Expr) (isoLift : IsoLift) (iso : Mor₂Iso) : Mor₂
/-- The expression for the identity `𝟙 f`. -/
| id (e : Expr) (isoLift : IsoLift) (f : Mor₁) : Mor₂
/-- The expression for the composition `η ≫ θ`. -/
| comp (e : Expr) (isoLift? : Option IsoLift) (f g h : Mor₁) (η θ : Mor₂) : Mor₂
/-- The expression for the left whiskering `f ◁ η` with `η : g ⟶ h`. -/
| whiskerLeft (e : Expr) (isoLift? : Option IsoLift) (f g h : Mor₁) (η : Mor₂) : Mor₂
/-- The expression for the right whiskering `η ▷ h` with `η : f ⟶ g`. -/
| whiskerRight (e : Expr) (isoLift? : Option IsoLift) (f g : Mor₁) (η : Mor₂) (h : Mor₁) : Mor₂
/-- The expression for the horizontal composition `η ◫ θ` with `η : f₁ ⟶ g₁` and `θ : f₂ ⟶ g₂`. -/
| horizontalComp (e : Expr) (isoLift? : Option IsoLift) (f₁ g₁ f₂ g₂ : Mor₁) (η θ : Mor₂) : Mor₂
/-- The expression for the coherence composition `η ⊗≫ θ := η ≫ α ≫ θ` with `η : f ⟶ g`
and `θ : h ⟶ i`. -/
| coherenceComp (e : Expr) (isoLift? : Option IsoLift) (f g h i : Mor₁)
(α : CoherenceHom) (η θ : Mor₂) : Mor₂
/-- The expression for an atomic non-structural 2-morphism. -/
| of (η : Atom) : Mor₂
deriving Inhabited
/-- A monad equipped with the ability to construct `Mor₂` terms. -/
class MkMor₂ (m : Type → Type) where
/-- Construct a `Mor₂` term from a lean expression. -/
ofExpr (e : Expr) : m Mor₂
/-- The underlying lean expression of a 2-morphism. -/
def Mor₂.e : Mor₂ → Expr
| .isoHom e .. => e
| .isoInv e .. => e
| .id e .. => e
| .comp e .. => e
| .whiskerLeft e .. => e
| .whiskerRight e .. => e
| .horizontalComp e .. => e
| .coherenceComp e .. => e
| .of η => η.e
/-- `η.isoLift?` is a pair of a 2-isomorphism `η'` and a proof that `η'.hom = η`. If no such `η'`
is found, returns `none`. This function does not seek `IsIso` instance. -/
def Mor₂.isoLift? : Mor₂ → Option IsoLift
| .isoHom _ isoLift .. => some isoLift
| .isoInv _ isoLift .. => some isoLift
| .id _ isoLift .. => some isoLift
| .comp _ isoLift? .. => isoLift?
| .whiskerLeft _ isoLift? .. => isoLift?
| .whiskerRight _ isoLift? .. => isoLift?
| .horizontalComp _ isoLift? .. => isoLift?
| .coherenceComp _ isoLift? .. => isoLift?
| .of _ => none
/-- The domain of a 2-morphism. -/
def Mor₂.srcM {m : Type → Type} [Monad m] [MonadMor₁ m] : Mor₂ → m Mor₁
| .isoHom _ _ iso => iso.srcM
| .isoInv _ _ iso => iso.tgtM
| .id _ _ f => return f
| .comp _ _ f .. => return f
| .whiskerLeft _ _ f g .. => do comp₁M f g
| .whiskerRight _ _ f _ _ h => do comp₁M f h
| .horizontalComp _ _ f₁ _ f₂ .. => do comp₁M f₁ f₂
| .coherenceComp _ _ f .. => return f
| .of η => return η.src
/-- The codomain of a 2-morphism. -/
def Mor₂.tgtM {m : Type → Type} [Monad m] [MonadMor₁ m] : Mor₂ → m Mor₁
| .isoHom _ _ iso => iso.tgtM
| .isoInv _ _ iso => iso.srcM
| .id _ _ f => return f
| .comp _ _ _ _ h .. => return h
| .whiskerLeft _ _ f _ h _ => do comp₁M f h
| .whiskerRight _ _ _ g _ h => do comp₁M g h
| .horizontalComp _ _ _ g₁ _ g₂ _ _ => do comp₁M g₁ g₂
| .coherenceComp _ _ _ _ _ i .. => return i
| .of η => return η.tgt
/-- A monad equipped with the ability to manipulate 2-morphisms. -/
class MonadMor₂ (m : Type → Type) where
/-- The expression for `Iso.hom η`. -/
homM (η : Mor₂Iso) : m Mor₂
/-- The expression for `Iso.hom η`. -/
atomHomM (η : AtomIso) : m Atom
/-- The expression for `Iso.inv η`. -/
invM (η : Mor₂Iso) : m Mor₂
/-- The expression for `Iso.inv η`. -/
atomInvM (η : AtomIso) : m Atom
/-- The expression for the identity `𝟙 f`. -/
id₂M (f : Mor₁) : m Mor₂
/-- The expression for the composition `η ≫ θ`. -/
comp₂M (η θ : Mor₂) : m Mor₂
/-- The expression for the left whiskering `f ◁ η`. -/
whiskerLeftM (f : Mor₁) (η : Mor₂) : m Mor₂
/-- The expression for the right whiskering `η ▷ h`. -/
whiskerRightM (η : Mor₂) (h : Mor₁) : m Mor₂
/-- The expression for the horizontal composition `η ◫ θ`. -/
horizontalCompM (η θ : Mor₂) : m Mor₂
/-- The expression for the coherence composition `η ⊗≫ θ := η ≫ α ≫ θ`. -/
coherenceCompM (α : CoherenceHom) (η θ : Mor₂) : m Mor₂
/-- Type of normalized 1-morphisms `((... ≫ h) ≫ g) ≫ f`. -/
inductive NormalizedHom : Type
/-- The identity 1-morphism `𝟙 a`. -/
| nil (e : Mor₁) (a : Obj) : NormalizedHom
/-- The `cons` composes an atomic 1-morphism at the end of a normalized 1-morphism. -/
| cons (e : Mor₁) : NormalizedHom → Atom₁ → NormalizedHom
deriving Inhabited
/-- The underlying expression of a normalized 1-morphism. -/
def NormalizedHom.e : NormalizedHom → Mor₁
| NormalizedHom.nil e _ => e
| NormalizedHom.cons e _ _ => e
/-- The domain of a normalized 1-morphism. -/
def NormalizedHom.src : NormalizedHom → Obj
| NormalizedHom.nil _ a => a
| NormalizedHom.cons _ p _ => p.src
/-- The codomain of a normalized 1-morphism. -/
def NormalizedHom.tgt : NormalizedHom → Obj
| NormalizedHom.nil _ a => a
| NormalizedHom.cons _ _ f => f.tgt
/-- Construct the `NormalizedHom.nil` term in `m`. -/
def normalizedHom.nilM [MonadMor₁ m] (a : Obj) : m NormalizedHom := do
return NormalizedHom.nil (← id₁M a) a
/-- Construct a `NormalizedHom.cons` term in `m`. -/
def NormalizedHom.consM [MonadMor₁ m] (p : NormalizedHom) (f : Atom₁) :
m NormalizedHom := do
return NormalizedHom.cons (← comp₁M p.e (.of f)) p f
/-- `Context ρ` provides the context for manipulating 2-morphisms in a monoidal category or
bicategory. In particular, we will store `MonoidalCategory` or `Bicategory` instance in a context,
and use this through a reader monad when we construct the lean expressions for 2-morphisms. -/
class Context (ρ : Type) where
/-- Construct a context from a lean expression for a 2-morphism. -/
mkContext? : Expr → MetaM (Option ρ)
export Context (mkContext?)
/-- Construct a context from a lean expression for a 2-morphism. -/
def mkContext {ρ : Type} [Context ρ] (e : Expr) : MetaM ρ := do
match ← mkContext? e with
| some c => return c
| none => throwError "failed to construct a monoidal category or bicategory context from {e}"
/-- The state for the `CoherenceM ρ` monad. -/
structure State where
/-- The cache for evaluating lean expressions of 1-morphisms into `Mor₁` terms. -/
cache : PersistentExprMap Mor₁ := {}
/-- The monad for manipulating 2-morphisms in a monoidal category or bicategory. -/
abbrev CoherenceM (ρ : Type) := ReaderT ρ <| StateT State MetaM
/-- Run the `CoherenceM ρ` monad. -/
def CoherenceM.run {α ρ : Type} (x : CoherenceM ρ α) (ctx : ρ) (s : State := {}) :
MetaM α := do
Prod.fst <$> ReaderT.run x ctx s
end BicategoryLike
end Tactic
end Mathlib |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Monoidal/PureCoherence.lean | import Mathlib.Tactic.CategoryTheory.Coherence.PureCoherence
import Mathlib.Tactic.CategoryTheory.Monoidal.Datatypes
/-!
# Coherence tactic for monoidal categories
We provide a `monoidal_coherence` tactic,
which proves that any two morphisms (with the same source and target)
in a monoidal category which are built out of associators and unitors
are equal.
-/
open Lean Meta Elab Qq
open CategoryTheory Mathlib.Tactic.BicategoryLike MonoidalCategory
namespace Mathlib.Tactic.Monoidal
section
universe v u
variable {C : Type u} [Category.{v} C] [MonoidalCategory C]
local infixr:81 " ◁ " => MonoidalCategory.whiskerLeftIso
local infixl:81 " ▷ " => MonoidalCategory.whiskerRightIso
/-- The composition of the normalizing isomorphisms `η_f : p ⊗ f ≅ pf` and `η_g : pf ⊗ g ≅ pfg`. -/
abbrev normalizeIsoComp {p f g pf pfg : C} (η_f : p ⊗ f ≅ pf) (η_g : pf ⊗ g ≅ pfg) :=
(α_ _ _ _).symm ≪≫ whiskerRightIso η_f g ≪≫ η_g
theorem naturality_associator {p f g h pf pfg pfgh : C}
(η_f : p ⊗ f ≅ pf) (η_g : pf ⊗ g ≅ pfg) (η_h : pfg ⊗ h ≅ pfgh) :
p ◁ (α_ f g h) ≪≫ normalizeIsoComp η_f (normalizeIsoComp η_g η_h) =
normalizeIsoComp (normalizeIsoComp η_f η_g) η_h :=
Iso.ext (by simp)
theorem naturality_leftUnitor {p f pf : C} (η_f : p ⊗ f ≅ pf) :
p ◁ (λ_ f) ≪≫ η_f = normalizeIsoComp (ρ_ p) η_f :=
Iso.ext (by simp)
theorem naturality_rightUnitor {p f pf : C} (η_f : p ⊗ f ≅ pf) :
p ◁ (ρ_ f) ≪≫ η_f = normalizeIsoComp η_f (ρ_ pf) :=
Iso.ext (by simp)
theorem naturality_id {p f pf : C} (η_f : p ⊗ f ≅ pf) :
p ◁ Iso.refl f ≪≫ η_f = η_f := by
simp
theorem naturality_comp {p f g h pf : C} {η : f ≅ g} {θ : g ≅ h}
(η_f : p ⊗ f ≅ pf) (η_g : p ⊗ g ≅ pf) (η_h : p ⊗ h ≅ pf)
(ih_η : p ◁ η ≪≫ η_g = η_f) (ih_θ : p ◁ θ ≪≫ η_h = η_g) :
p ◁ (η ≪≫ θ) ≪≫ η_h = η_f := by
simp_all
theorem naturality_whiskerLeft {p f g h pf pfg : C} {η : g ≅ h}
(η_f : p ⊗ f ≅ pf) (η_fg : pf ⊗ g ≅ pfg) (η_fh : (pf ⊗ h) ≅ pfg)
(ih_η : pf ◁ η ≪≫ η_fh = η_fg) :
p ◁ (f ◁ η) ≪≫ normalizeIsoComp η_f η_fh = normalizeIsoComp η_f η_fg := by
rw [← ih_η]
apply Iso.ext
simp [← whisker_exchange_assoc]
theorem naturality_whiskerRight {p f g h pf pfh : C} {η : f ≅ g}
(η_f : p ⊗ f ≅ pf) (η_g : p ⊗ g ≅ pf) (η_fh : (pf ⊗ h) ≅ pfh)
(ih_η : p ◁ η ≪≫ η_g = η_f) :
p ◁ (η ▷ h) ≪≫ normalizeIsoComp η_g η_fh = normalizeIsoComp η_f η_fh := by
rw [← ih_η]
apply Iso.ext
simp
theorem naturality_tensorHom {p f₁ g₁ f₂ g₂ pf₁ pf₁f₂ : C} {η : f₁ ≅ g₁} {θ : f₂ ≅ g₂}
(η_f₁ : p ⊗ f₁ ≅ pf₁) (η_g₁ : p ⊗ g₁ ≅ pf₁) (η_f₂ : pf₁ ⊗ f₂ ≅ pf₁f₂) (η_g₂ : pf₁ ⊗ g₂ ≅ pf₁f₂)
(ih_η : p ◁ η ≪≫ η_g₁ = η_f₁)
(ih_θ : pf₁ ◁ θ ≪≫ η_g₂ = η_f₂) :
p ◁ (η ⊗ᵢ θ) ≪≫ normalizeIsoComp η_g₁ η_g₂ = normalizeIsoComp η_f₁ η_f₂ := by
rw [tensorIso_def]
apply naturality_comp
· apply naturality_whiskerRight _ _ _ ih_η
· apply naturality_whiskerLeft _ _ _ ih_θ
theorem naturality_inv {p f g pf : C} {η : f ≅ g}
(η_f : p ⊗ f ≅ pf) (η_g : p ⊗ g ≅ pf) (ih : p ◁ η ≪≫ η_g = η_f) :
p ◁ η.symm ≪≫ η_f = η_g := by
rw [← ih]
apply Iso.ext
simp
instance : MonadNormalizeNaturality MonoidalM where
mkNaturalityAssociator p pf pfg pfgh f g h η_f η_g η_h := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have pf : Q($ctx.C) := pf.e.e
have pfg : Q($ctx.C) := pfg.e.e
have pfgh : Q($ctx.C) := pfgh.e.e
have η_f : Q($p ⊗ $f ≅ $pf) := η_f.e
have η_g : Q($pf ⊗ $g ≅ $pfg) := η_g.e
have η_h : Q($pfg ⊗ $h ≅ $pfgh) := η_h.e
return q(naturality_associator $η_f $η_g $η_h)
mkNaturalityLeftUnitor p pf f η_f := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f : Q($ctx.C) := f.e
have pf : Q($ctx.C) := pf.e.e
have η_f : Q($p ⊗ $f ≅ $pf) := η_f.e
return q(naturality_leftUnitor $η_f)
mkNaturalityRightUnitor p pf f η_f := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f : Q($ctx.C) := f.e
have pf : Q($ctx.C) := pf.e.e
have η_f : Q($p ⊗ $f ≅ $pf) := η_f.e
return q(naturality_rightUnitor $η_f)
mkNaturalityId p pf f η_f := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f : Q($ctx.C) := f.e
have pf : Q($ctx.C) := pf.e.e
have η_f : Q($p ⊗ $f ≅ $pf) := η_f.e
return q(naturality_id $η_f)
mkNaturalityComp p pf f g h η θ η_f η_g η_h ih_η ih_θ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have pf : Q($ctx.C) := pf.e.e
have η : Q($f ≅ $g) := η.e
have θ : Q($g ≅ $h) := θ.e
have η_f : Q($p ⊗ $f ≅ $pf) := η_f.e
have η_g : Q($p ⊗ $g ≅ $pf) := η_g.e
have η_h : Q($p ⊗ $h ≅ $pf) := η_h.e
have ih_η : Q($p ◁ $η ≪≫ $η_g = $η_f) := ih_η
have ih_θ : Q($p ◁ $θ ≪≫ $η_h = $η_g) := ih_θ
return q(naturality_comp $η_f $η_g $η_h $ih_η $ih_θ)
mkNaturalityWhiskerLeft p pf pfg f g h η η_f η_fg η_fh ih_η := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have pf : Q($ctx.C) := pf.e.e
have pfg : Q($ctx.C) := pfg.e.e
have η : Q($g ≅ $h) := η.e
have η_f : Q($p ⊗ $f ≅ $pf) := η_f.e
have η_fg : Q($pf ⊗ $g ≅ $pfg) := η_fg.e
have η_fh : Q($pf ⊗ $h ≅ $pfg) := η_fh.e
have ih_η : Q($pf ◁ $η ≪≫ $η_fh = $η_fg) := ih_η
return q(naturality_whiskerLeft $η_f $η_fg $η_fh $ih_η)
mkNaturalityWhiskerRight p pf pfh f g h η η_f η_g η_fh ih_η := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have pf : Q($ctx.C) := pf.e.e
have pfh : Q($ctx.C) := pfh.e.e
have η : Q($f ≅ $g) := η.e
have η_f : Q($p ⊗ $f ≅ $pf) := η_f.e
have η_g : Q($p ⊗ $g ≅ $pf) := η_g.e
have η_fh : Q($pf ⊗ $h ≅ $pfh) := η_fh.e
have ih_η : Q($p ◁ $η ≪≫ $η_g = $η_f) := ih_η
return q(naturality_whiskerRight $η_f $η_g $η_fh $ih_η)
mkNaturalityHorizontalComp p pf₁ pf₁f₂ f₁ g₁ f₂ g₂ η θ η_f₁ η_g₁ η_f₂ η_g₂ ih_η ih_θ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f₁ : Q($ctx.C) := f₁.e
have g₁ : Q($ctx.C) := g₁.e
have f₂ : Q($ctx.C) := f₂.e
have g₂ : Q($ctx.C) := g₂.e
have pf₁ : Q($ctx.C) := pf₁.e.e
have pf₁f₂ : Q($ctx.C) := pf₁f₂.e.e
have η : Q($f₁ ≅ $g₁) := η.e
have θ : Q($f₂ ≅ $g₂) := θ.e
have η_f₁ : Q($p ⊗ $f₁ ≅ $pf₁) := η_f₁.e
have η_g₁ : Q($p ⊗ $g₁ ≅ $pf₁) := η_g₁.e
have η_f₂ : Q($pf₁ ⊗ $f₂ ≅ $pf₁f₂) := η_f₂.e
have η_g₂ : Q($pf₁ ⊗ $g₂ ≅ $pf₁f₂) := η_g₂.e
have ih_η : Q($p ◁ $η ≪≫ $η_g₁ = $η_f₁) := ih_η
have ih_θ : Q($pf₁ ◁ $θ ≪≫ $η_g₂ = $η_f₂) := ih_θ
return q(naturality_tensorHom $η_f₁ $η_g₁ $η_f₂ $η_g₂ $ih_η $ih_θ)
mkNaturalityInv p pf f g η η_f η_g ih := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have p : Q($ctx.C) := p.e.e
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have pf : Q($ctx.C) := pf.e.e
have η : Q($f ≅ $g) := η.e
have η_f : Q($p ⊗ $f ≅ $pf) := η_f.e
have η_g : Q($p ⊗ $g ≅ $pf) := η_g.e
have ih : Q($p ◁ $η ≪≫ $η_g = $η_f) := ih
return q(naturality_inv $η_f $η_g $ih)
theorem of_normalize_eq {f g f' : C} {η θ : f ≅ g} (η_f : 𝟙_ C ⊗ f ≅ f') (η_g : 𝟙_ C ⊗ g ≅ f')
(h_η : 𝟙_ C ◁ η ≪≫ η_g = η_f)
(h_θ : 𝟙_ C ◁ θ ≪≫ η_g = η_f) : η = θ := by
apply Iso.ext
calc
η.hom = (λ_ f).inv ≫ η_f.hom ≫ η_g.inv ≫ (λ_ g).hom := by
simp [← reassoc_of% (congrArg Iso.hom h_η)]
_ = θ.hom := by
simp [← reassoc_of% (congrArg Iso.hom h_θ)]
theorem mk_eq_of_naturality {f g f' : C} {η θ : f ⟶ g} {η' θ' : f ≅ g}
(η_f : 𝟙_ C ⊗ f ≅ f') (η_g : 𝟙_ C ⊗ g ≅ f')
(η_hom : η'.hom = η) (Θ_hom : θ'.hom = θ)
(Hη : whiskerLeftIso (𝟙_ C) η' ≪≫ η_g = η_f)
(Hθ : whiskerLeftIso (𝟙_ C) θ' ≪≫ η_g = η_f) : η = θ :=
calc
η = η'.hom := η_hom.symm
_ = (λ_ f).inv ≫ η_f.hom ≫ η_g.inv ≫ (λ_ g).hom := by
simp [← reassoc_of% (congrArg Iso.hom Hη)]
_ = θ'.hom := by
simp [← reassoc_of% (congrArg Iso.hom Hθ)]
_ = θ := Θ_hom
end
instance : MkEqOfNaturality MonoidalM where
mkEqOfNaturality η θ ηIso θIso η_f η_g Hη Hθ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let η' := ηIso.e
let θ' := θIso.e
let f ← η'.srcM
let g ← η'.tgtM
let f' ← η_f.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have f' : Q($ctx.C) := f'.e
have η : Q($f ⟶ $g) := η
have θ : Q($f ⟶ $g) := θ
have η'_e : Q($f ≅ $g) := η'.e
have θ'_e : Q($f ≅ $g) := θ'.e
have η_f : Q(𝟙_ _ ⊗ $f ≅ $f') := η_f.e
have η_g : Q(𝟙_ _ ⊗ $g ≅ $f') := η_g.e
have η_hom : Q(Iso.hom $η'_e = $η) := ηIso.eq
have Θ_hom : Q(Iso.hom $θ'_e = $θ) := θIso.eq
have Hη : Q(whiskerLeftIso (𝟙_ _) $η'_e ≪≫ $η_g = $η_f) := Hη
have Hθ : Q(whiskerLeftIso (𝟙_ _) $θ'_e ≪≫ $η_g = $η_f) := Hθ
return q(mk_eq_of_naturality $η_f $η_g $η_hom $Θ_hom $Hη $Hθ)
open Elab.Tactic
/-- Close the goal of the form `η = θ`, where `η` and `θ` are 2-isomorphisms made up only of
associators, unitors, and identities.
```lean
example {C : Type} [Category C] [MonoidalCategory C] :
(λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom := by
monoidal_coherence
```
-/
def pureCoherence (mvarId : MVarId) : MetaM (List MVarId) :=
BicategoryLike.pureCoherence Monoidal.Context `monoidal mvarId
@[inherit_doc pureCoherence]
elab "monoidal_coherence" : tactic => withMainContext do
replaceMainGoal <| ← Monoidal.pureCoherence <| ← getMainGoal
end Mathlib.Tactic.Monoidal |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Monoidal/Basic.lean | import Mathlib.Tactic.CategoryTheory.Coherence.Basic
import Mathlib.Tactic.CategoryTheory.Monoidal.Normalize
import Mathlib.Tactic.CategoryTheory.Monoidal.PureCoherence
/-!
# `monoidal` tactic
This file provides `monoidal` tactic, which solves equations in a monoidal category, where
the two sides only differ by replacing strings of monoidal structural morphisms (that is,
associators, unitors, and identities) with different strings of structural morphisms with the same
source and target. In other words, `monoidal` solves equalities where both sides have the same
string diagrams.
The core function for the `monoidal` tactic is provided in
`Mathlib/Tactic/CategoryTheory/Coherence/Basic.lean`. See this file for more details about the
implementation.
-/
open Lean Meta Elab Tactic
open CategoryTheory Mathlib.Tactic.BicategoryLike
namespace Mathlib.Tactic.Monoidal
/-- Normalize the both sides of an equality. -/
def monoidalNf (mvarId : MVarId) : MetaM (List MVarId) := do
BicategoryLike.normalForm Monoidal.Context `monoidal mvarId
@[inherit_doc monoidalNf]
elab "monoidal_nf" : tactic => withMainContext do
replaceMainGoal (← monoidalNf (← getMainGoal))
/--
Use the coherence theorem for monoidal categories to solve equations in a monoidal category,
where the two sides only differ by replacing strings of monoidal structural morphisms
(that is, associators, unitors, and identities)
with different strings of structural morphisms with the same source and target.
That is, `monoidal` can handle goals of the form
`a ≫ f ≫ b ≫ g ≫ c = a' ≫ f ≫ b' ≫ g ≫ c'`
where `a = a'`, `b = b'`, and `c = c'` can be proved using `monoidal_coherence`.
-/
def monoidal (mvarId : MVarId) : MetaM (List MVarId) :=
BicategoryLike.main Monoidal.Context `monoidal mvarId
@[inherit_doc monoidal]
elab "monoidal" : tactic => withMainContext do
replaceMainGoal <| ← monoidal <| ← getMainGoal
end Mathlib.Tactic.Monoidal |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Monoidal/Normalize.lean | import Mathlib.Tactic.CategoryTheory.Coherence.Normalize
import Mathlib.Tactic.CategoryTheory.Monoidal.Datatypes
/-!
# Normalization of morphisms in monoidal categories
This file provides the implementation of the normalization given in
`Mathlib/Tactic/CategoryTheory/Coherence/Normalize.lean`. See this file for more details.
-/
open Lean Meta Elab Qq
open CategoryTheory Mathlib.Tactic.BicategoryLike MonoidalCategory
namespace Mathlib.Tactic.Monoidal
section
universe v u
variable {C : Type u} [Category.{v} C]
variable {f f' g g' h h' i i' j : C}
@[nolint synTaut]
theorem evalComp_nil_nil {f g h : C} (α : f ≅ g) (β : g ≅ h) :
(α ≪≫ β).hom = (α ≪≫ β).hom := by
simp
theorem evalComp_nil_cons {f g h i j : C} (α : f ≅ g) (β : g ≅ h) (η : h ⟶ i) (ηs : i ⟶ j) :
α.hom ≫ (β.hom ≫ η ≫ ηs) = (α ≪≫ β).hom ≫ η ≫ ηs := by
simp
theorem evalComp_cons {f g h i j : C} (α : f ≅ g) (η : g ⟶ h) {ηs : h ⟶ i} {θ : i ⟶ j} {ι : h ⟶ j}
(e_ι : ηs ≫ θ = ι) :
(α.hom ≫ η ≫ ηs) ≫ θ = α.hom ≫ η ≫ ι := by
simp [e_ι]
theorem eval_comp
{η η' : f ⟶ g} {θ θ' : g ⟶ h} {ι : f ⟶ h}
(e_η : η = η') (e_θ : θ = θ') (e_ηθ : η' ≫ θ' = ι) :
η ≫ θ = ι := by
simp [e_η, e_θ, e_ηθ]
theorem eval_of (η : f ⟶ g) :
η = (Iso.refl _).hom ≫ η ≫ (Iso.refl _).hom := by
simp
theorem eval_monoidalComp
{η η' : f ⟶ g} {α : g ≅ h} {θ θ' : h ⟶ i} {αθ : g ⟶ i} {ηαθ : f ⟶ i}
(e_η : η = η') (e_θ : θ = θ') (e_αθ : α.hom ≫ θ' = αθ) (e_ηαθ : η' ≫ αθ = ηαθ) :
η ≫ α.hom ≫ θ = ηαθ := by
simp [e_η, e_θ, e_αθ, e_ηαθ]
variable [MonoidalCategory C]
@[nolint synTaut]
theorem evalWhiskerLeft_nil (f : C) {g h : C} (α : g ≅ h) :
(whiskerLeftIso f α).hom = (whiskerLeftIso f α).hom := by
simp
theorem evalWhiskerLeft_of_cons {f g h i j : C}
(α : g ≅ h) (η : h ⟶ i) {ηs : i ⟶ j} {θ : f ⊗ i ⟶ f ⊗ j} (e_θ : f ◁ ηs = θ) :
f ◁ (α.hom ≫ η ≫ ηs) = (whiskerLeftIso f α).hom ≫ f ◁ η ≫ θ := by
simp [e_θ]
theorem evalWhiskerLeft_comp {f g h i : C}
{η : h ⟶ i} {η₁ : g ⊗ h ⟶ g ⊗ i} {η₂ : f ⊗ g ⊗ h ⟶ f ⊗ g ⊗ i}
{η₃ : f ⊗ g ⊗ h ⟶ (f ⊗ g) ⊗ i} {η₄ : (f ⊗ g) ⊗ h ⟶ (f ⊗ g) ⊗ i}
(e_η₁ : g ◁ η = η₁) (e_η₂ : f ◁ η₁ = η₂)
(e_η₃ : η₂ ≫ (α_ _ _ _).inv = η₃) (e_η₄ : (α_ _ _ _).hom ≫ η₃ = η₄) :
(f ⊗ g) ◁ η = η₄ := by
simp [e_η₁, e_η₂, e_η₃, e_η₄]
theorem evalWhiskerLeft_id {f g : C} {η : f ⟶ g}
{η₁ : f ⟶ 𝟙_ C ⊗ g} {η₂ : 𝟙_ C ⊗ f ⟶ 𝟙_ C ⊗ g}
(e_η₁ : η ≫ (λ_ _).inv = η₁) (e_η₂ : (λ_ _).hom ≫ η₁ = η₂) :
𝟙_ C ◁ η = η₂ := by
simp [e_η₁, e_η₂]
theorem eval_whiskerLeft {f g h : C}
{η η' : g ⟶ h} {θ : f ⊗ g ⟶ f ⊗ h}
(e_η : η = η') (e_θ : f ◁ η' = θ) :
f ◁ η = θ := by
simp [e_η, e_θ]
theorem eval_whiskerRight {f g h : C}
{η η' : f ⟶ g} {θ : f ⊗ h ⟶ g ⊗ h}
(e_η : η = η') (e_θ : η' ▷ h = θ) :
η ▷ h = θ := by
simp [e_η, e_θ]
theorem eval_tensorHom {f g h i : C}
{η η' : f ⟶ g} {θ θ' : h ⟶ i} {ι : f ⊗ h ⟶ g ⊗ i}
(e_η : η = η') (e_θ : θ = θ') (e_ι : η' ⊗ₘ θ' = ι) :
η ⊗ₘ θ = ι := by
simp [e_η, e_θ, e_ι]
@[nolint synTaut]
theorem evalWhiskerRight_nil {f g : C} (α : f ≅ g) (h : C) :
(whiskerRightIso α h).hom = (whiskerRightIso α h).hom := by
simp
theorem evalWhiskerRight_cons_of_of {f g h i j : C}
{α : f ≅ g} {η : g ⟶ h} {ηs : h ⟶ i} {ηs₁ : h ⊗ j ⟶ i ⊗ j}
{η₁ : g ⊗ j ⟶ h ⊗ j} {η₂ : g ⊗ j ⟶ i ⊗ j} {η₃ : f ⊗ j ⟶ i ⊗ j}
(e_ηs₁ : ηs ▷ j = ηs₁) (e_η₁ : η ▷ j = η₁)
(e_η₂ : η₁ ≫ ηs₁ = η₂) (e_η₃ : (whiskerRightIso α j).hom ≫ η₂ = η₃) :
(α.hom ≫ η ≫ ηs) ▷ j = η₃ := by
simp_all
theorem evalWhiskerRight_cons_whisker {f g h i j k : C}
{α : g ≅ f ⊗ h} {η : h ⟶ i} {ηs : f ⊗ i ⟶ j}
{η₁ : h ⊗ k ⟶ i ⊗ k} {η₂ : f ⊗ (h ⊗ k) ⟶ f ⊗ (i ⊗ k)} {ηs₁ : (f ⊗ i) ⊗ k ⟶ j ⊗ k}
{ηs₂ : f ⊗ (i ⊗ k) ⟶ j ⊗ k} {η₃ : f ⊗ (h ⊗ k) ⟶ j ⊗ k} {η₄ : (f ⊗ h) ⊗ k ⟶ j ⊗ k}
{η₅ : g ⊗ k ⟶ j ⊗ k}
(e_η₁ : ((Iso.refl _).hom ≫ η ≫ (Iso.refl _).hom) ▷ k = η₁) (e_η₂ : f ◁ η₁ = η₂)
(e_ηs₁ : ηs ▷ k = ηs₁) (e_ηs₂ : (α_ _ _ _).inv ≫ ηs₁ = ηs₂)
(e_η₃ : η₂ ≫ ηs₂ = η₃) (e_η₄ : (α_ _ _ _).hom ≫ η₃ = η₄)
(e_η₅ : (whiskerRightIso α k).hom ≫ η₄ = η₅) :
(α.hom ≫ (f ◁ η) ≫ ηs) ▷ k = η₅ := by
simp at e_η₁ e_η₅
simp [e_η₁, e_η₂, e_ηs₁, e_ηs₂, e_η₃, e_η₄, e_η₅]
theorem evalWhiskerRight_comp {f f' g h : C}
{η : f ⟶ f'} {η₁ : f ⊗ g ⟶ f' ⊗ g} {η₂ : (f ⊗ g) ⊗ h ⟶ (f' ⊗ g) ⊗ h}
{η₃ : (f ⊗ g) ⊗ h ⟶ f' ⊗ (g ⊗ h)} {η₄ : f ⊗ (g ⊗ h) ⟶ f' ⊗ (g ⊗ h)}
(e_η₁ : η ▷ g = η₁) (e_η₂ : η₁ ▷ h = η₂)
(e_η₃ : η₂ ≫ (α_ _ _ _).hom = η₃) (e_η₄ : (α_ _ _ _).inv ≫ η₃ = η₄) :
η ▷ (g ⊗ h) = η₄ := by
simp [e_η₁, e_η₂, e_η₃, e_η₄]
theorem evalWhiskerRight_id {f g : C}
{η : f ⟶ g} {η₁ : f ⟶ g ⊗ 𝟙_ C} {η₂ : f ⊗ 𝟙_ C ⟶ g ⊗ 𝟙_ C}
(e_η₁ : η ≫ (ρ_ _).inv = η₁) (e_η₂ : (ρ_ _).hom ≫ η₁ = η₂) :
η ▷ 𝟙_ C = η₂ := by
simp [e_η₁, e_η₂]
theorem evalWhiskerRightAux_of {f g : C} (η : f ⟶ g) (h : C) :
η ▷ h = (Iso.refl _).hom ≫ η ▷ h ≫ (Iso.refl _).hom := by
simp
theorem evalWhiskerRightAux_cons {f g h i j : C} {η : g ⟶ h} {ηs : i ⟶ j}
{ηs' : i ⊗ f ⟶ j ⊗ f} {η₁ : g ⊗ (i ⊗ f) ⟶ h ⊗ (j ⊗ f)}
{η₂ : g ⊗ (i ⊗ f) ⟶ (h ⊗ j) ⊗ f} {η₃ : (g ⊗ i) ⊗ f ⟶ (h ⊗ j) ⊗ f}
(e_ηs' : ηs ▷ f = ηs') (e_η₁ : ((Iso.refl _).hom ≫ η ≫ (Iso.refl _).hom) ⊗ₘ ηs' = η₁)
(e_η₂ : η₁ ≫ (α_ _ _ _).inv = η₂) (e_η₃ : (α_ _ _ _).hom ≫ η₂ = η₃) :
(η ⊗ₘ ηs) ▷ f = η₃ := by
simp [← e_ηs', ← e_η₁, ← e_η₂, ← e_η₃, MonoidalCategory.tensorHom_def]
theorem evalWhiskerRight_cons_of {f f' g h i : C} {α : f' ≅ g} {η : g ⟶ h} {ηs : h ⟶ i}
{ηs₁ : h ⊗ f ⟶ i ⊗ f} {η₁ : g ⊗ f ⟶ h ⊗ f} {η₂ : g ⊗ f ⟶ i ⊗ f}
{η₃ : f' ⊗ f ⟶ i ⊗ f}
(e_ηs₁ : ηs ▷ f = ηs₁) (e_η₁ : η ▷ f = η₁)
(e_η₂ : η₁ ≫ ηs₁ = η₂) (e_η₃ : (whiskerRightIso α f).hom ≫ η₂ = η₃) :
(α.hom ≫ η ≫ ηs) ▷ f = η₃ := by
simp_all
theorem evalHorizontalCompAux_of {f g h i : C} (η : f ⟶ g) (θ : h ⟶ i) :
η ⊗ₘ θ = (Iso.refl _).hom ≫ (η ⊗ₘ θ) ≫ (Iso.refl _).hom := by
simp
theorem evalHorizontalCompAux_cons {f f' g g' h i : C} {η : f ⟶ g} {ηs : f' ⟶ g'} {θ : h ⟶ i}
{ηθ : f' ⊗ h ⟶ g' ⊗ i} {η₁ : f ⊗ (f' ⊗ h) ⟶ g ⊗ (g' ⊗ i)}
{ηθ₁ : f ⊗ (f' ⊗ h) ⟶ (g ⊗ g') ⊗ i} {ηθ₂ : (f ⊗ f') ⊗ h ⟶ (g ⊗ g') ⊗ i}
(e_ηθ : ηs ⊗ₘ θ = ηθ) (e_η₁ : ((Iso.refl _).hom ≫ η ≫ (Iso.refl _).hom) ⊗ₘ ηθ = η₁)
(e_ηθ₁ : η₁ ≫ (α_ _ _ _).inv = ηθ₁) (e_ηθ₂ : (α_ _ _ _).hom ≫ ηθ₁ = ηθ₂) :
(η ⊗ₘ ηs) ⊗ₘ θ = ηθ₂ := by
simp_all
theorem evalHorizontalCompAux'_whisker {f f' g g' h : C} {η : g ⟶ h} {θ : f' ⟶ g'}
{ηθ : g ⊗ f' ⟶ h ⊗ g'} {η₁ : f ⊗ (g ⊗ f') ⟶ f ⊗ (h ⊗ g')}
{η₂ : f ⊗ (g ⊗ f') ⟶ (f ⊗ h) ⊗ g'} {η₃ : (f ⊗ g) ⊗ f' ⟶ (f ⊗ h) ⊗ g'}
(e_ηθ : η ⊗ₘ θ = ηθ) (e_η₁ : f ◁ ηθ = η₁)
(e_η₂ : η₁ ≫ (α_ _ _ _).inv = η₂) (e_η₃ : (α_ _ _ _).hom ≫ η₂ = η₃) :
(f ◁ η) ⊗ₘ θ = η₃ := by
simp only [← e_ηθ, ← e_η₁, ← e_η₂, ← e_η₃]
simp [MonoidalCategory.tensorHom_def]
theorem evalHorizontalCompAux'_of_whisker {f f' g g' h : C} {η : g ⟶ h} {θ : f' ⟶ g'}
{η₁ : g ⊗ f ⟶ h ⊗ f} {ηθ : (g ⊗ f) ⊗ f' ⟶ (h ⊗ f) ⊗ g'}
{ηθ₁ : (g ⊗ f) ⊗ f' ⟶ h ⊗ (f ⊗ g')}
{ηθ₂ : g ⊗ (f ⊗ f') ⟶ h ⊗ (f ⊗ g')}
(e_η₁ : η ▷ f = η₁) (e_ηθ : η₁ ⊗ₘ ((Iso.refl _).hom ≫ θ ≫ (Iso.refl _).hom) = ηθ)
(e_ηθ₁ : ηθ ≫ (α_ _ _ _).hom = ηθ₁) (e_ηθ₂ : (α_ _ _ _).inv ≫ ηθ₁ = ηθ₂) :
η ⊗ₘ (f ◁ θ) = ηθ₂ := by
simp only [← e_η₁, ← e_ηθ, ← e_ηθ₁, ← e_ηθ₂]
simp [MonoidalCategory.tensorHom_def]
@[nolint synTaut]
theorem evalHorizontalComp_nil_nil {f g h i : C} (α : f ≅ g) (β : h ≅ i) :
(α ⊗ᵢ β).hom = (α ⊗ᵢ β).hom := by
simp
theorem evalHorizontalComp_nil_cons {f f' g g' h i : C}
{α : f ≅ g} {β : f' ≅ g'} {η : g' ⟶ h} {ηs : h ⟶ i}
{η₁ : g ⊗ g' ⟶ g ⊗ h} {ηs₁ : g ⊗ h ⟶ g ⊗ i}
{η₂ : g ⊗ g' ⟶ g ⊗ i} {η₃ : f ⊗ f' ⟶ g ⊗ i}
(e_η₁ : g ◁ ((Iso.refl _).hom ≫ η ≫ (Iso.refl _).hom) = η₁)
(e_ηs₁ : g ◁ ηs = ηs₁) (e_η₂ : η₁ ≫ ηs₁ = η₂)
(e_η₃ : (α ⊗ᵢ β).hom ≫ η₂ = η₃) :
α.hom ⊗ₘ (β.hom ≫ η ≫ ηs) = η₃ := by
simp_all [MonoidalCategory.tensorHom_def]
theorem evalHorizontalComp_cons_nil {f f' g g' h i : C}
{α : f ≅ g} {η : g ⟶ h} {ηs : h ⟶ i} {β : f' ≅ g'}
{η₁ : g ⊗ g' ⟶ h ⊗ g'} {ηs₁ : h ⊗ g' ⟶ i ⊗ g'} {η₂ : g ⊗ g' ⟶ i ⊗ g'} {η₃ : f ⊗ f' ⟶ i ⊗ g'}
(e_η₁ : ((Iso.refl _).hom ≫ η ≫ (Iso.refl _).hom) ▷ g' = η₁) (e_ηs₁ : ηs ▷ g' = ηs₁)
(e_η₂ : η₁ ≫ ηs₁ = η₂) (e_η₃ : (α ⊗ᵢ β).hom ≫ η₂ = η₃) :
(α.hom ≫ η ≫ ηs) ⊗ₘ β.hom = η₃ := by
simp_all [MonoidalCategory.tensorHom_def']
theorem evalHorizontalComp_cons_cons {f f' g g' h h' i i' : C}
{α : f ≅ g} {η : g ⟶ h} {ηs : h ⟶ i}
{β : f' ≅ g'} {θ : g' ⟶ h'} {θs : h' ⟶ i'}
{ηθ : g ⊗ g' ⟶ h ⊗ h'} {ηθs : h ⊗ h' ⟶ i ⊗ i'}
{ηθ₁ : g ⊗ g' ⟶ i ⊗ i'} {ηθ₂ : f ⊗ f' ⟶ i ⊗ i'}
(e_ηθ : η ⊗ₘ θ = ηθ) (e_ηθs : ηs ⊗ₘ θs = ηθs)
(e_ηθ₁ : ηθ ≫ ηθs = ηθ₁) (e_ηθ₂ : (α ⊗ᵢ β).hom ≫ ηθ₁ = ηθ₂) :
(α.hom ≫ η ≫ ηs) ⊗ₘ (β.hom ≫ θ ≫ θs) = ηθ₂ := by
simp [← e_ηθ, ← e_ηθs, ← e_ηθ₁, ← e_ηθ₂]
end
open Mor₂Iso
instance : MkEvalComp MonoidalM where
mkEvalCompNilNil α β := do
let ctx ← read
let _cat := ctx.instCat
let f ← α.srcM
let g ← α.tgtM
let h ← β.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have α : Q($f ≅ $g) := α.e
have β : Q($g ≅ $h) := β.e
return q(evalComp_nil_nil $α $β)
mkEvalCompNilCons α β η ηs := do
let ctx ← read
let _cat := ctx.instCat
let f ← α.srcM
let g ← α.tgtM
let h ← β.tgtM
let i ← η.tgtM
let j ← ηs.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have j : Q($ctx.C) := j.e
have α : Q($f ≅ $g) := α.e
have β : Q($g ≅ $h) := β.e
have η : Q($h ⟶ $i) := η.e.e
have ηs : Q($i ⟶ $j) := ηs.e.e
return q(evalComp_nil_cons $α $β $η $ηs)
mkEvalCompCons α η ηs θ ι e_ι := do
let ctx ← read
let _cat := ctx.instCat
let f ← α.srcM
let g ← α.tgtM
let h ← η.tgtM
let i ← ηs.tgtM
let j ← θ.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have j : Q($ctx.C) := j.e
have α : Q($f ≅ $g) := α.e
have η : Q($g ⟶ $h) := η.e.e
have ηs : Q($h ⟶ $i) := ηs.e.e
have θ : Q($i ⟶ $j) := θ.e.e
have ι : Q($h ⟶ $j) := ι.e.e
have e_ι : Q($ηs ≫ $θ = $ι) := e_ι
return q(evalComp_cons $α $η $e_ι)
instance : MkEvalWhiskerLeft MonoidalM where
mkEvalWhiskerLeftNil f α := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← α.srcM
let h ← α.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have α_e : Q($g_e ≅ $h_e) := α.e
return q(evalWhiskerLeft_nil $f_e $α_e)
mkEvalWhiskerLeftOfCons f α η ηs θ e_θ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← α.srcM
let h ← α.tgtM
let i ← η.tgtM
let j ← ηs.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have j : Q($ctx.C) := j.e
have α : Q($g ≅ $h) := α.e
have η : Q($h ⟶ $i) := η.e.e
have ηs : Q($i ⟶ $j) := ηs.e.e
have θ : Q($f ⊗ $i ⟶ $f ⊗ $j) := θ.e.e
have e_θ : Q($f ◁ $ηs = $θ) := e_θ
return q(evalWhiskerLeft_of_cons $α $η $e_θ)
mkEvalWhiskerLeftComp f g η η₁ η₂ η₃ η₄ e_η₁ e_η₂ e_η₃ e_η₄ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let h ← η.srcM
let i ← η.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have η : Q($h ⟶ $i) := η.e.e
have η₁ : Q($g ⊗ $h ⟶ $g ⊗ $i) := η₁.e.e
have η₂ : Q($f ⊗ $g ⊗ $h ⟶ $f ⊗ $g ⊗ $i) := η₂.e.e
have η₃ : Q($f ⊗ $g ⊗ $h ⟶ ($f ⊗ $g) ⊗ $i) := η₃.e.e
have η₄ : Q(($f ⊗ $g) ⊗ $h ⟶ ($f ⊗ $g) ⊗ $i) := η₄.e.e
have e_η₁ : Q($g ◁ $η = $η₁) := e_η₁
have e_η₂ : Q($f ◁ $η₁ = $η₂) := e_η₂
have e_η₃ : Q($η₂ ≫ (α_ _ _ _).inv = $η₃) := e_η₃
have e_η₄ : Q((α_ _ _ _).hom ≫ $η₃ = $η₄) := e_η₄
return q(evalWhiskerLeft_comp $e_η₁ $e_η₂ $e_η₃ $e_η₄)
mkEvalWhiskerLeftId η η₁ η₂ e_η₁ e_η₂ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η.srcM
let g ← η.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have η : Q($f ⟶ $g) := η.e.e
have η₁ : Q($f ⟶ 𝟙_ _ ⊗ $g) := η₁.e.e
have η₂ : Q(𝟙_ _ ⊗ $f ⟶ 𝟙_ _ ⊗ $g) := η₂.e.e
have e_η₁ : Q($η ≫ (λ_ _).inv = $η₁) := e_η₁
have e_η₂ : Q((λ_ _).hom ≫ $η₁ = $η₂) := e_η₂
return q(evalWhiskerLeft_id $e_η₁ $e_η₂)
instance : MkEvalWhiskerRight MonoidalM where
mkEvalWhiskerRightAuxOf η h := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η.srcM
let g ← η.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have η : Q($f ⟶ $g) := η.e.e
have h : Q($ctx.C) := h.e
return q(evalWhiskerRightAux_of $η $h)
mkEvalWhiskerRightAuxCons f η ηs ηs' η₁ η₂ η₃ e_ηs' e_η₁ e_η₂ e_η₃ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← η.srcM
let h ← η.tgtM
let i ← ηs.srcM
let j ← ηs.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have j : Q($ctx.C) := j.e
have η : Q($g ⟶ $h) := η.e.e
have ηs : Q($i ⟶ $j) := ηs.e.e
have ηs' : Q($i ⊗ $f ⟶ $j ⊗ $f) := ηs'.e.e
have η₁ : Q($g ⊗ ($i ⊗ $f) ⟶ $h ⊗ ($j ⊗ $f)) := η₁.e.e
have η₂ : Q($g ⊗ ($i ⊗ $f) ⟶ ($h ⊗ $j) ⊗ $f) := η₂.e.e
have η₃ : Q(($g ⊗ $i) ⊗ $f ⟶ ($h ⊗ $j) ⊗ $f) := η₃.e.e
have e_ηs' : Q($ηs ▷ $f = $ηs') := e_ηs'
have e_η₁ : Q(((Iso.refl _).hom ≫ $η ≫ (Iso.refl _).hom) ⊗ₘ $ηs' = $η₁) := e_η₁
have e_η₂ : Q($η₁ ≫ (α_ _ _ _).inv = $η₂) := e_η₂
have e_η₃ : Q((α_ _ _ _).hom ≫ $η₂ = $η₃) := e_η₃
return q(evalWhiskerRightAux_cons $e_ηs' $e_η₁ $e_η₂ $e_η₃)
mkEvalWhiskerRightNil α h := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← α.srcM
let g ← α.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have α : Q($f ≅ $g) := α.e
return q(evalWhiskerRight_nil $α $h)
mkEvalWhiskerRightConsOfOf j α η ηs ηs₁ η₁ η₂ η₃ e_ηs₁ e_η₁ e_η₂ e_η₃ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← α.srcM
let g ← α.tgtM
let h ← η.tgtM
let i ← ηs.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have j : Q($ctx.C) := j.e
have α : Q($f ≅ $g) := α.e
have η : Q($g ⟶ $h) := η.e.e
have ηs : Q($h ⟶ $i) := ηs.e.e
have ηs₁ : Q($h ⊗ $j ⟶ $i ⊗ $j) := ηs₁.e.e
have η₁ : Q($g ⊗ $j ⟶ $h ⊗ $j) := η₁.e.e
have η₂ : Q($g ⊗ $j ⟶ $i ⊗ $j) := η₂.e.e
have η₃ : Q($f ⊗ $j ⟶ $i ⊗ $j) := η₃.e.e
have e_ηs₁ : Q($ηs ▷ $j = $ηs₁) := e_ηs₁
have e_η₁ : Q($η ▷ $j = $η₁) := e_η₁
have e_η₂ : Q($η₁ ≫ $ηs₁ = $η₂) := e_η₂
have e_η₃ : Q((whiskerRightIso $α $j).hom ≫ $η₂ = $η₃) := e_η₃
return q(evalWhiskerRight_cons_of_of $e_ηs₁ $e_η₁ $e_η₂ $e_η₃)
mkEvalWhiskerRightConsWhisker f k α η ηs η₁ η₂ ηs₁ ηs₂ η₃ η₄ η₅
e_η₁ e_η₂ e_ηs₁ e_ηs₂ e_η₃ e_η₄ e_η₅ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← α.srcM
let h ← η.srcM
let i ← η.tgtM
let j ← ηs.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have j : Q($ctx.C) := j.e
have k : Q($ctx.C) := k.e
have α : Q($g ≅ $f ⊗ $h) := α.e
have η : Q($h ⟶ $i) := η.e.e
have ηs : Q($f ⊗ $i ⟶ $j) := ηs.e.e
have η₁ : Q($h ⊗ $k ⟶ $i ⊗ $k) := η₁.e.e
have η₂ : Q($f ⊗ ($h ⊗ $k) ⟶ $f ⊗ ($i ⊗ $k)) := η₂.e.e
have ηs₁ : Q(($f ⊗ $i) ⊗ $k ⟶ $j ⊗ $k) := ηs₁.e.e
have ηs₂ : Q($f ⊗ ($i ⊗ $k) ⟶ $j ⊗ $k) := ηs₂.e.e
have η₃ : Q($f ⊗ ($h ⊗ $k) ⟶ $j ⊗ $k) := η₃.e.e
have η₄ : Q(($f ⊗ $h) ⊗ $k ⟶ $j ⊗ $k) := η₄.e.e
have η₅ : Q($g ⊗ $k ⟶ $j ⊗ $k) := η₅.e.e
have e_η₁ : Q(((Iso.refl _).hom ≫ $η ≫ (Iso.refl _).hom) ▷ $k = $η₁) := e_η₁
have e_η₂ : Q($f ◁ $η₁ = $η₂) := e_η₂
have e_ηs₁ : Q($ηs ▷ $k = $ηs₁) := e_ηs₁
have e_ηs₂ : Q((α_ _ _ _).inv ≫ $ηs₁ = $ηs₂) := e_ηs₂
have e_η₃ : Q($η₂ ≫ $ηs₂ = $η₃) := e_η₃
have e_η₄ : Q((α_ _ _ _).hom ≫ $η₃ = $η₄) := e_η₄
have e_η₅ : Q((whiskerRightIso $α $k).hom ≫ $η₄ = $η₅) := e_η₅
return q(evalWhiskerRight_cons_whisker $e_η₁ $e_η₂ $e_ηs₁ $e_ηs₂ $e_η₃ $e_η₄ $e_η₅)
mkEvalWhiskerRightComp g h η η₁ η₂ η₃ η₄ e_η₁ e_η₂ e_η₃ e_η₄ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η.srcM
let f' ← η.tgtM
have f : Q($ctx.C) := f.e
have f' : Q($ctx.C) := f'.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have η : Q($f ⟶ $f') := η.e.e
have η₁ : Q($f ⊗ $g ⟶ $f' ⊗ $g) := η₁.e.e
have η₂ : Q(($f ⊗ $g) ⊗ $h ⟶ ($f' ⊗ $g) ⊗ $h) := η₂.e.e
have η₃ : Q(($f ⊗ $g) ⊗ $h ⟶ $f' ⊗ ($g ⊗ $h)) := η₃.e.e
have η₄ : Q($f ⊗ ($g ⊗ $h) ⟶ $f' ⊗ ($g ⊗ $h)) := η₄.e.e
have e_η₁ : Q($η ▷ $g = $η₁) := e_η₁
have e_η₂ : Q($η₁ ▷ $h = $η₂) := e_η₂
have e_η₃ : Q($η₂ ≫ (α_ _ _ _).hom = $η₃) := e_η₃
have e_η₄ : Q((α_ _ _ _).inv ≫ $η₃ = $η₄) := e_η₄
return q(evalWhiskerRight_comp $e_η₁ $e_η₂ $e_η₃ $e_η₄)
mkEvalWhiskerRightId η η₁ η₂ e_η₁ e_η₂ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η.srcM
let g ← η.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have η : Q($f ⟶ $g) := η.e.e
have η₁ : Q($f ⟶ $g ⊗ 𝟙_ _) := η₁.e.e
have η₂ : Q($f ⊗ 𝟙_ _ ⟶ $g ⊗ 𝟙_ _) := η₂.e.e
have e_η₁ : Q($η ≫ (ρ_ _).inv = $η₁) := e_η₁
have e_η₂ : Q((ρ_ _).hom ≫ $η₁ = $η₂) := e_η₂
return q(evalWhiskerRight_id $e_η₁ $e_η₂)
instance : MkEvalHorizontalComp MonoidalM where
mkEvalHorizontalCompAuxOf η θ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η.srcM
let g ← η.tgtM
let h ← θ.srcM
let i ← θ.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have η : Q($f ⟶ $g) := η.e.e
have θ : Q($h ⟶ $i) := θ.e.e
return q(evalHorizontalCompAux_of $η $θ)
mkEvalHorizontalCompAuxCons η ηs θ ηθ η₁ ηθ₁ ηθ₂ e_ηθ e_η₁ e_ηθ₁ e_ηθ₂ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η.srcM
let g ← η.tgtM
let f' ← ηs.srcM
let g' ← ηs.tgtM
let h ← θ.srcM
let i ← θ.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have f' : Q($ctx.C) := f'.e
have g' : Q($ctx.C) := g'.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have η : Q($f ⟶ $g) := η.e.e
have ηs : Q($f' ⟶ $g') := ηs.e.e
have θ : Q($h ⟶ $i) := θ.e.e
have ηθ : Q($f' ⊗ $h ⟶ $g' ⊗ $i) := ηθ.e.e
have η₁ : Q($f ⊗ ($f' ⊗ $h) ⟶ $g ⊗ ($g' ⊗ $i)) := η₁.e.e
have ηθ₁ : Q($f ⊗ ($f' ⊗ $h) ⟶ ($g ⊗ $g') ⊗ $i) := ηθ₁.e.e
have ηθ₂ : Q(($f ⊗ $f') ⊗ $h ⟶ ($g ⊗ $g') ⊗ $i) := ηθ₂.e.e
have e_ηθ : Q($ηs ⊗ₘ $θ = $ηθ) := e_ηθ
have e_η₁ : Q(((Iso.refl _).hom ≫ $η ≫ (Iso.refl _).hom) ⊗ₘ $ηθ = $η₁) := e_η₁
have e_ηθ₁ : Q($η₁ ≫ (α_ _ _ _).inv = $ηθ₁) := e_ηθ₁
have e_ηθ₂ : Q((α_ _ _ _).hom ≫ $ηθ₁ = $ηθ₂) := e_ηθ₂
return q(evalHorizontalCompAux_cons $e_ηθ $e_η₁ $e_ηθ₁ $e_ηθ₂)
mkEvalHorizontalCompAux'Whisker f η θ ηθ η₁ η₂ η₃ e_ηθ e_η₁ e_η₂ e_η₃ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← η.srcM
let h ← η.tgtM
let f' ← θ.srcM
let g' ← θ.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have f' : Q($ctx.C) := f'.e
have g' : Q($ctx.C) := g'.e
have η : Q($g ⟶ $h) := η.e.e
have θ : Q($f' ⟶ $g') := θ.e.e
have ηθ : Q($g ⊗ $f' ⟶ $h ⊗ $g') := ηθ.e.e
have η₁ : Q($f ⊗ ($g ⊗ $f') ⟶ $f ⊗ ($h ⊗ $g')) := η₁.e.e
have η₂ : Q($f ⊗ ($g ⊗ $f') ⟶ ($f ⊗ $h) ⊗ $g') := η₂.e.e
have η₃ : Q(($f ⊗ $g) ⊗ $f' ⟶ ($f ⊗ $h) ⊗ $g') := η₃.e.e
have e_ηθ : Q($η ⊗ₘ $θ = $ηθ) := e_ηθ
have e_η₁ : Q($f ◁ $ηθ = $η₁) := e_η₁
have e_η₂ : Q($η₁ ≫ (α_ _ _ _).inv = $η₂) := e_η₂
have e_η₃ : Q((α_ _ _ _).hom ≫ $η₂ = $η₃) := e_η₃
return q(evalHorizontalCompAux'_whisker $e_ηθ $e_η₁ $e_η₂ $e_η₃)
mkEvalHorizontalCompAux'OfWhisker f η θ η₁ ηθ ηθ₁ ηθ₂ e_η₁ e_ηθ e_ηθ₁ e_ηθ₂ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← η.srcM
let h ← η.tgtM
let f' ← θ.srcM
let g' ← θ.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have f' : Q($ctx.C) := f'.e
have g' : Q($ctx.C) := g'.e
have η : Q($g ⟶ $h) := η.e.e
have θ : Q($f' ⟶ $g') := θ.e.e
have η₁ : Q($g ⊗ $f ⟶ $h ⊗ $f) := η₁.e.e
have ηθ : Q(($g ⊗ $f) ⊗ $f' ⟶ ($h ⊗ $f) ⊗ $g') := ηθ.e.e
have ηθ₁ : Q(($g ⊗ $f) ⊗ $f' ⟶ $h ⊗ ($f ⊗ $g')) := ηθ₁.e.e
have ηθ₂ : Q($g ⊗ ($f ⊗ $f') ⟶ $h ⊗ ($f ⊗ $g')) := ηθ₂.e.e
have e_η₁ : Q($η ▷ $f = $η₁) := e_η₁
have e_ηθ : Q($η₁ ⊗ₘ ((Iso.refl _).hom ≫ $θ ≫ (Iso.refl _).hom) = $ηθ) := e_ηθ
have e_ηθ₁ : Q($ηθ ≫ (α_ _ _ _).hom = $ηθ₁) := e_ηθ₁
have e_ηθ₂ : Q((α_ _ _ _).inv ≫ $ηθ₁ = $ηθ₂) := e_ηθ₂
return q(evalHorizontalCompAux'_of_whisker $e_η₁ $e_ηθ $e_ηθ₁ $e_ηθ₂)
mkEvalHorizontalCompNilNil α β := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← α.srcM
let g ← α.tgtM
let h ← β.srcM
let i ← β.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have α : Q($f ≅ $g) := α.e
have β : Q($h ≅ $i) := β.e
return q(evalHorizontalComp_nil_nil $α $β)
mkEvalHorizontalCompNilCons α β η ηs η₁ ηs₁ η₂ η₃ e_η₁ e_ηs₁ e_η₂ e_η₃ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← α.srcM
let g ← α.tgtM
let f' ← β.srcM
let g' ← β.tgtM
let h ← η.tgtM
let i ← ηs.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have f' : Q($ctx.C) := f'.e
have g' : Q($ctx.C) := g'.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have α : Q($f ≅ $g) := α.e
have β : Q($f' ≅ $g') := β.e
have η : Q($g' ⟶ $h) := η.e.e
have ηs : Q($h ⟶ $i) := ηs.e.e
have η₁ : Q($g ⊗ $g' ⟶ $g ⊗ $h) := η₁.e.e
have ηs₁ : Q($g ⊗ $h ⟶ $g ⊗ $i) := ηs₁.e.e
have η₂ : Q($g ⊗ $g' ⟶ $g ⊗ $i) := η₂.e.e
have η₃ : Q($f ⊗ $f' ⟶ $g ⊗ $i) := η₃.e.e
have e_η₁ : Q($g ◁ ((Iso.refl _).hom ≫ $η ≫ (Iso.refl _).hom) = $η₁) := e_η₁
have e_ηs₁ : Q($g ◁ $ηs = $ηs₁) := e_ηs₁
have e_η₂ : Q($η₁ ≫ $ηs₁ = $η₂) := e_η₂
have e_η₃ : Q(($α ⊗ᵢ $β).hom ≫ $η₂ = $η₃) := e_η₃
return q(evalHorizontalComp_nil_cons $e_η₁ $e_ηs₁ $e_η₂ $e_η₃)
mkEvalHorizontalCompConsNil α β η ηs η₁ ηs₁ η₂ η₃ e_η₁ e_ηs₁ e_η₂ e_η₃ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← α.srcM
let g ← α.tgtM
let h ← η.tgtM
let i ← ηs.tgtM
let f' ← β.srcM
let g' ← β.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have f' : Q($ctx.C) := f'.e
have g' : Q($ctx.C) := g'.e
have α : Q($f ≅ $g) := α.e
have η : Q($g ⟶ $h) := η.e.e
have ηs : Q($h ⟶ $i) := ηs.e.e
have β : Q($f' ≅ $g') := β.e
have η₁ : Q($g ⊗ $g' ⟶ $h ⊗ $g') := η₁.e.e
have ηs₁ : Q($h ⊗ $g' ⟶ $i ⊗ $g') := ηs₁.e.e
have η₂ : Q($g ⊗ $g' ⟶ $i ⊗ $g') := η₂.e.e
have η₃ : Q($f ⊗ $f' ⟶ $i ⊗ $g') := η₃.e.e
have e_η₁ : Q(((Iso.refl _).hom ≫ $η ≫ (Iso.refl _).hom) ▷ $g' = $η₁) := e_η₁
have e_ηs₁ : Q($ηs ▷ $g' = $ηs₁) := e_ηs₁
have e_η₂ : Q($η₁ ≫ $ηs₁ = $η₂) := e_η₂
have e_η₃ : Q(($α ⊗ᵢ $β).hom ≫ $η₂ = $η₃) := e_η₃
return q(evalHorizontalComp_cons_nil $e_η₁ $e_ηs₁ $e_η₂ $e_η₃)
mkEvalHorizontalCompConsCons α β η θ ηs θs ηθ ηθs ηθ₁ ηθ₂ e_ηθ e_ηθs e_ηθ₁ e_ηθ₂ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← α.srcM
let g ← α.tgtM
let h ← η.tgtM
let i ← ηs.tgtM
let f' ← β.srcM
let g' ← β.tgtM
let h' ← θ.tgtM
let i' ← θs.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have f' : Q($ctx.C) := f'.e
have g' : Q($ctx.C) := g'.e
have h' : Q($ctx.C) := h'.e
have i' : Q($ctx.C) := i'.e
have α : Q($f ≅ $g) := α.e
have η : Q($g ⟶ $h) := η.e.e
have ηs : Q($h ⟶ $i) := ηs.e.e
have β : Q($f' ≅ $g') := β.e
have θ : Q($g' ⟶ $h') := θ.e.e
have θs : Q($h' ⟶ $i') := θs.e.e
have ηθ : Q($g ⊗ $g' ⟶ $h ⊗ $h') := ηθ.e.e
have ηθs : Q($h ⊗ $h' ⟶ $i ⊗ $i') := ηθs.e.e
have ηθ₁ : Q($g ⊗ $g' ⟶ $i ⊗ $i') := ηθ₁.e.e
have ηθ₂ : Q($f ⊗ $f' ⟶ $i ⊗ $i') := ηθ₂.e.e
have e_ηθ : Q($η ⊗ₘ $θ = $ηθ) := e_ηθ
have e_ηθs : Q($ηs ⊗ₘ $θs = $ηθs) := e_ηθs
have e_ηθ₁ : Q($ηθ ≫ $ηθs = $ηθ₁) := e_ηθ₁
have e_ηθ₂ : Q(($α ⊗ᵢ $β).hom ≫ $ηθ₁ = $ηθ₂) := e_ηθ₂
return q(evalHorizontalComp_cons_cons $e_ηθ $e_ηθs $e_ηθ₁ $e_ηθ₂)
instance : MkEval MonoidalM where
mkEvalComp η θ η' θ' ι e_η e_θ e_ηθ := do
let ctx ← read
let _cat := ctx.instCat
let f ← η'.srcM
let g ← η'.tgtM
let h ← θ'.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have η : Q($f ⟶ $g) := η.e
have η' : Q($f ⟶ $g) := η'.e.e
have θ : Q($g ⟶ $h) := θ.e
have θ' : Q($g ⟶ $h) := θ'.e.e
have ι : Q($f ⟶ $h) := ι.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($θ = $θ') := e_θ
have e_ηθ : Q($η' ≫ $θ' = $ι) := e_ηθ
return q(eval_comp $e_η $e_θ $e_ηθ)
mkEvalWhiskerLeft f η η' θ e_η e_θ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← η'.srcM
let h ← η'.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have η : Q($g ⟶ $h) := η.e
have η' : Q($g ⟶ $h) := η'.e.e
have θ : Q($f ⊗ $g ⟶ $f ⊗ $h) := θ.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($f ◁ $η' = $θ) := e_θ
return q(eval_whiskerLeft $e_η $e_θ)
mkEvalWhiskerRight η h η' θ e_η e_θ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η'.srcM
let g ← η'.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have η : Q($f ⟶ $g) := η.e
have η' : Q($f ⟶ $g) := η'.e.e
have θ : Q($f ⊗ $h ⟶ $g ⊗ $h) := θ.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($η' ▷ $h = $θ) := e_θ
return q(eval_whiskerRight $e_η $e_θ)
mkEvalHorizontalComp η θ η' θ' ι e_η e_θ e_ι := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η'.srcM
let g ← η'.tgtM
let h ← θ'.srcM
let i ← θ'.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have η : Q($f ⟶ $g) := η.e
have η' : Q($f ⟶ $g) := η'.e.e
have θ : Q($h ⟶ $i) := θ.e
have θ' : Q($h ⟶ $i) := θ'.e.e
have ι : Q($f ⊗ $h ⟶ $g ⊗ $i) := ι.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($θ = $θ') := e_θ
have e_ι : Q($η' ⊗ₘ $θ' = $ι) := e_ι
return q(eval_tensorHom $e_η $e_θ $e_ι)
mkEvalOf η := do
let ctx ← read
let _cat := ctx.instCat
let f := η.src
let g := η.tgt
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have η : Q($f ⟶ $g) := η.e
return q(eval_of $η)
mkEvalMonoidalComp η θ α η' θ' αθ ηαθ e_η e_θ e_αθ e_ηαθ := do
let ctx ← read
let _cat := ctx.instCat
let f ← η'.srcM
let g ← η'.tgtM
let h ← α.tgtM
let i ← θ'.tgtM
have f : Q($ctx.C) := f.e
have g : Q($ctx.C) := g.e
have h : Q($ctx.C) := h.e
have i : Q($ctx.C) := i.e
have η : Q($f ⟶ $g) := η.e
have η' : Q($f ⟶ $g) := η'.e.e
have α : Q($g ≅ $h) := α.e
have θ : Q($h ⟶ $i) := θ.e
have θ' : Q($h ⟶ $i) := θ'.e.e
have αθ : Q($g ⟶ $i) := αθ.e.e
have ηαθ : Q($f ⟶ $i) := ηαθ.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($θ = $θ') := e_θ
have e_αθ : Q(Iso.hom $α ≫ $θ' = $αθ) := e_αθ
have e_ηαθ : Q($η' ≫ $αθ = $ηαθ) := e_ηαθ
return q(eval_monoidalComp $e_η $e_θ $e_αθ $e_ηαθ)
instance : MonadNormalExpr MonoidalM where
whiskerRightM η h := do
return .whisker (← MonadMor₂.whiskerRightM η.e (.of h)) η h
hConsM η θ := do
return .cons (← MonadMor₂.horizontalCompM η.e θ.e) η θ
whiskerLeftM f η := do
return .whisker (← MonadMor₂.whiskerLeftM (.of f) η.e) f η
nilM α := do
return .nil (← MonadMor₂.homM α) α
consM α η ηs := do
return .cons (← MonadMor₂.comp₂M (← MonadMor₂.homM α) (← MonadMor₂.comp₂M η.e ηs.e)) α η ηs
instance : MkMor₂ MonoidalM where
ofExpr := Mor₂OfExpr
end Mathlib.Tactic.Monoidal |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Monoidal/Datatypes.lean | import Mathlib.Tactic.CategoryTheory.Coherence.Datatypes
import Mathlib.Tactic.CategoryTheory.MonoidalComp
/-!
# Expressions for monoidal categories
This file converts lean expressions representing morphisms in monoidal categories into `Mor₂Iso`
or `Mor` terms. The converted expressions are used in the coherence tactics and the string diagram
widgets.
-/
open Lean Meta Elab Qq
open CategoryTheory Mathlib.Tactic.BicategoryLike MonoidalCategory
namespace Mathlib.Tactic.Monoidal
/-- The domain of a morphism. -/
def srcExpr (η : Expr) : MetaM Expr := do
match (← whnfR (← inferType η)).getAppFnArgs with
| (``Quiver.Hom, #[_, _, f, _]) => return f
| _ => throwError m!"{η} is not a morphism"
/-- The codomain of a morphism. -/
def tgtExpr (η : Expr) : MetaM Expr := do
match (← whnfR (← inferType η)).getAppFnArgs with
| (``Quiver.Hom, #[_, _, _, g]) => return g
| _ => throwError m!"{η} is not a morphism"
/-- The domain of an isomorphism. -/
def srcExprOfIso (η : Expr) : MetaM Expr := do
match (← whnfR (← inferType η)).getAppFnArgs with
| (``Iso, #[_, _, f, _]) => return f
| _ => throwError m!"{η} is not a morphism"
/-- The codomain of an isomorphism. -/
def tgtExprOfIso (η : Expr) : MetaM Expr := do
match (← whnfR (← inferType η)).getAppFnArgs with
| (``Iso, #[_, _, _, g]) => return g
| _ => throwError m!"{η} is not a morphism"
initialize registerTraceClass `monoidal
/-- The context for evaluating expressions. -/
structure Context where
/-- The level for morphisms. -/
level₂ : Level
/-- The level for objects. -/
level₁ : Level
/-- The expression for the underlying category. -/
C : Q(Type level₁)
/-- The category instance. -/
instCat : Q(Category.{level₂, level₁} $C)
/-- The monoidal category instance. -/
instMonoidal? : Option Q(MonoidalCategory.{level₂, level₁} $C)
/-- Populate a `context` object for evaluating `e`. -/
def mkContext? (e : Expr) : MetaM (Option Context) := do
let e ← instantiateMVars e
let type ← instantiateMVars <| ← inferType e
match (← whnfR type).getAppFnArgs with
| (``Quiver.Hom, #[_, _, f, _]) =>
let C ← instantiateMVars <| ← inferType f
let .succ level₁ ← getLevel C | return none
let .succ level₂ ← getLevel type | return none
let some instCat ← synthInstance?
(mkAppN (.const ``Category [level₂, level₁]) #[C]) | return none
let instMonoidal? ← synthInstance?
(mkAppN (.const ``MonoidalCategory [level₂, level₁]) #[C, instCat])
return some ⟨level₂, level₁, C, instCat, instMonoidal?⟩
| _ => return none
instance : BicategoryLike.Context Monoidal.Context where
mkContext? := Monoidal.mkContext?
/-- The monad for the normalization of 2-morphisms. -/
abbrev MonoidalM := CoherenceM Context
/-- Throw an error if the monoidal category instance is not found. -/
def synthMonoidalError {α : Type} : MetaM α := do
throwError "failed to find monoidal category instance"
instance : MonadMor₁ MonoidalM where
id₁M a := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
return .id (q(𝟙_ _) : Q($ctx.C)) a
comp₁M f g := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f_e : Q($ctx.C) := f.e
let g_e : Q($ctx.C) := g.e
return .comp (q($f_e ⊗ $g_e)) f g
section
universe v u
variable {C : Type u} [Category.{v} C]
theorem structuralIsoOfExpr_comp {f g h : C}
(η : f ⟶ g) (η' : f ≅ g) (ih_η : η'.hom = η)
(θ : g ⟶ h) (θ' : g ≅ h) (ih_θ : θ'.hom = θ) :
(η' ≪≫ θ').hom = η ≫ θ := by
simp [ih_η, ih_θ]
theorem StructuralOfExpr_monoidalComp {f g h i : C} [MonoidalCoherence g h]
(η : f ⟶ g) (η' : f ≅ g) (ih_η : η'.hom = η) (θ : h ⟶ i) (θ' : h ≅ i) (ih_θ : θ'.hom = θ) :
(η' ≪⊗≫ θ').hom = η ⊗≫ θ := by
simp [ih_η, ih_θ, monoidalIsoComp, monoidalComp]
variable [MonoidalCategory C]
theorem structuralIsoOfExpr_whiskerLeft (f : C) {g h : C}
(η : g ⟶ h) (η' : g ≅ h) (ih_η : η'.hom = η) :
(whiskerLeftIso f η').hom = f ◁ η := by
simp [ih_η]
theorem structuralIsoOfExpr_whiskerRight {f g : C} (h : C)
(η : f ⟶ g) (η' : f ≅ g) (ih_η : η'.hom = η) :
(whiskerRightIso η' h).hom = η ▷ h := by
simp [ih_η]
theorem structuralIsoOfExpr_horizontalComp {f₁ g₁ f₂ g₂ : C}
(η : f₁ ⟶ g₁) (η' : f₁ ≅ g₁) (ih_η : η'.hom = η)
(θ : f₂ ⟶ g₂) (θ' : f₂ ≅ g₂) (ih_θ : θ'.hom = θ) :
(η' ⊗ᵢ θ').hom = η ⊗ₘ θ := by
simp [ih_η, ih_θ]
end
open MonadMor₁
instance : MonadMor₂Iso MonoidalM where
associatorM f g h := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f_e : Q($ctx.C) := f.e
let g_e : Q($ctx.C) := g.e
let h_e : Q($ctx.C) := h.e
return .associator q(α_ $f_e $g_e $h_e) f g h
leftUnitorM f := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f_e : Q($ctx.C) := f.e
return .leftUnitor q(λ_ $f_e) f
rightUnitorM f := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f_e : Q($ctx.C) := f.e
return .rightUnitor q(ρ_ $f_e) f
id₂M f := do
let ctx ← read
let _cat := ctx.instCat
have f_e : Q($ctx.C) := f.e
return .id q(Iso.refl $f_e) f
coherenceHomM f g inst := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have inst : Q(MonoidalCoherence $f_e $g_e) := inst
match (← whnfI inst).getAppFnArgs with
| (``MonoidalCoherence.mk, #[_, _, _, _, α]) =>
let e : Q($f_e ≅ $g_e) := q(MonoidalCoherence.iso)
return ⟨e, f, g, inst, α⟩
| _ => throwError m!"failed to unfold {inst}"
comp₂M η θ := do
let ctx ← read
let _cat := ctx.instCat
let f ← η.srcM
let g ← η.tgtM
let h ← θ.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have η_e : Q($f_e ≅ $g_e) := η.e
have θ_e : Q($g_e ≅ $h_e) := θ.e
return .comp q($η_e ≪≫ $θ_e) f g h η θ
whiskerLeftM f η := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← η.srcM
let h ← η.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have η_e : Q($g_e ≅ $h_e) := η.e
return .whiskerLeft q(whiskerLeftIso $f_e $η_e) f g h η
whiskerRightM η h := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η.srcM
let g ← η.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have η_e : Q($f_e ≅ $g_e) := η.e
return .whiskerRight q(whiskerRightIso $η_e $h_e) f g η h
horizontalCompM η θ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f₁ ← η.srcM
let g₁ ← η.tgtM
let f₂ ← θ.srcM
let g₂ ← θ.tgtM
have f₁_e : Q($ctx.C) := f₁.e
have g₁_e : Q($ctx.C) := g₁.e
have f₂_e : Q($ctx.C) := f₂.e
have g₂_e : Q($ctx.C) := g₂.e
have η_e : Q($f₁_e ≅ $g₁_e) := η.e
have θ_e : Q($f₂_e ≅ $g₂_e) := θ.e
return .horizontalComp q(tensorIso $η_e $θ_e) f₁ g₁ f₂ g₂ η θ
symmM η := do
let ctx ← read
let _cat := ctx.instCat
let f ← η.srcM
let g ← η.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
return .inv q(Iso.symm $η_e) f g η
coherenceCompM α η θ := do
let ctx ← read
let _cat := ctx.instCat
let f ← η.srcM
let g ← η.tgtM
let h ← θ.srcM
let i ← θ.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have i_e : Q($ctx.C) := i.e
have _inst : Q(MonoidalCoherence $g_e $h_e) := α.inst
have η_e : Q($f_e ≅ $g_e) := η.e
have θ_e : Q($h_e ≅ $i_e) := θ.e
return .coherenceComp q($η_e ≪⊗≫ $θ_e) f g h i α η θ
open MonadMor₂Iso
instance : MonadMor₂ MonoidalM where
homM η := do
let ctx ← read
let _cat := ctx.instCat
let f ← η.srcM
let g ← η.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
let e : Q($f_e ⟶ $g_e) := q(Iso.hom $η_e)
have eq : Q(Iso.hom $η_e = $e) := q(rfl)
return .isoHom e ⟨η, eq⟩ η
atomHomM η := do
let ctx ← read
let _cat := ctx.instCat
let f := η.src
let g := η.tgt
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
return .mk q(Iso.hom $η_e) f g
invM η := do
let ctx ← read
let _cat := ctx.instCat
let f ← η.srcM
let g ← η.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
let e : Q($g_e ⟶ $f_e) := q(Iso.inv $η_e)
let η_inv ← symmM η
let eq : Q(Iso.inv $η_e = $e) := q(Iso.symm_hom $η_e)
return .isoInv e ⟨η_inv, eq⟩ η
atomInvM η := do
let ctx ← read
let _cat := ctx.instCat
let f := η.src
let g := η.tgt
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
return .mk q(Iso.inv $η_e) g f
id₂M f := do
let ctx ← read
let _cat := ctx.instCat
have f_e : Q($ctx.C) := f.e
let e : Q($f_e ⟶ $f_e) := q(𝟙 $f_e)
let eq : Q(𝟙 $f_e = $e) := q(Iso.refl_hom $f_e)
return .id e ⟨.structuralAtom <| ← id₂M f, eq⟩ f
comp₂M η θ := do
let ctx ← read
let _cat := ctx.instCat
let f ← η.srcM
let g ← η.tgtM
let h ← θ.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have η_e : Q($f_e ⟶ $g_e) := η.e
have θ_e : Q($g_e ⟶ $h_e) := θ.e
let iso_lift? ← (match (η.isoLift?, θ.isoLift?) with
| (some η_iso, some θ_iso) =>
have η_iso_e : Q($f_e ≅ $g_e) := η_iso.e.e
have θ_iso_e : Q($g_e ≅ $h_e) := θ_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
have θ_iso_eq : Q(Iso.hom $θ_iso_e = $θ_e) := θ_iso.eq
let eq := q(structuralIsoOfExpr_comp _ _ $η_iso_eq _ _ $θ_iso_eq)
return some ⟨← comp₂M η_iso.e θ_iso.e, eq⟩
| _ => return none)
let e : Q($f_e ⟶ $h_e) := q($η_e ≫ $θ_e)
return .comp e iso_lift? f g h η θ
whiskerLeftM f η := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let g ← η.srcM
let h ← η.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have η_e : Q($g_e ⟶ $h_e) := η.e
let iso_lift? ← (match η.isoLift? with
| some η_iso => do
have η_iso_e : Q($g_e ≅ $h_e) := η_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
let eq := q(structuralIsoOfExpr_whiskerLeft $f_e _ _ $η_iso_eq)
return some ⟨← whiskerLeftM f η_iso.e, eq⟩
| _ => return none)
let e : Q($f_e ⊗ $g_e ⟶ $f_e ⊗ $h_e) := q($f_e ◁ $η_e)
return .whiskerLeft e iso_lift? f g h η
whiskerRightM η h := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f ← η.srcM
let g ← η.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have η_e : Q($f_e ⟶ $g_e) := η.e
let iso_lift? ← (match η.isoLift? with
| some η_iso => do
have η_iso_e : Q($f_e ≅ $g_e) := η_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
let eq := q(structuralIsoOfExpr_whiskerRight $h_e _ _ $η_iso_eq)
return some ⟨← whiskerRightM η_iso.e h, eq⟩
| _ => return none)
let e : Q($f_e ⊗ $h_e ⟶ $g_e ⊗ $h_e) := q($η_e ▷ $h_e)
return .whiskerRight e iso_lift? f g η h
horizontalCompM η θ := do
let ctx ← read
let some _monoidal := ctx.instMonoidal? | synthMonoidalError
let f₁ ← η.srcM
let g₁ ← η.tgtM
let f₂ ← θ.srcM
let g₂ ← θ.tgtM
have f₁_e : Q($ctx.C) := f₁.e
have g₁_e : Q($ctx.C) := g₁.e
have f₂_e : Q($ctx.C) := f₂.e
have g₂_e : Q($ctx.C) := g₂.e
have η_e : Q($f₁_e ⟶ $g₁_e) := η.e
have θ_e : Q($f₂_e ⟶ $g₂_e) := θ.e
let iso_lift? ← (match (η.isoLift?, θ.isoLift?) with
| (some η_iso, some θ_iso) => do
have η_iso_e : Q($f₁_e ≅ $g₁_e) := η_iso.e.e
have θ_iso_e : Q($f₂_e ≅ $g₂_e) := θ_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
have θ_iso_eq : Q(Iso.hom $θ_iso_e = $θ_e) := θ_iso.eq
let eq := q(structuralIsoOfExpr_horizontalComp _ _ $η_iso_eq _ _ $θ_iso_eq)
return some ⟨← horizontalCompM η_iso.e θ_iso.e, eq⟩
| _ => return none)
let e : Q($f₁_e ⊗ $f₂_e ⟶ $g₁_e ⊗ $g₂_e) := q($η_e ⊗ₘ $θ_e)
return .horizontalComp e iso_lift? f₁ g₁ f₂ g₂ η θ
coherenceCompM α η θ := do
let ctx ← read
let _cat := ctx.instCat
let f ← η.srcM
let g ← η.tgtM
let h ← θ.srcM
let i ← θ.tgtM
have f_e : Q($ctx.C) := f.e
have g_e : Q($ctx.C) := g.e
have h_e : Q($ctx.C) := h.e
have i_e : Q($ctx.C) := i.e
have _inst : Q(MonoidalCoherence $g_e $h_e) := α.inst
have η_e : Q($f_e ⟶ $g_e) := η.e
have θ_e : Q($h_e ⟶ $i_e) := θ.e
let iso_lift? ← (match (η.isoLift?, θ.isoLift?) with
| (some η_iso, some θ_iso) => do
have η_iso_e : Q($f_e ≅ $g_e) := η_iso.e.e
have θ_iso_e : Q($h_e ≅ $i_e) := θ_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
have θ_iso_eq : Q(Iso.hom $θ_iso_e = $θ_e) := θ_iso.eq
let eq := q(StructuralOfExpr_monoidalComp _ _ $η_iso_eq _ _ $θ_iso_eq)
return some ⟨← coherenceCompM α η_iso.e θ_iso.e, eq⟩
| _ => return none)
let e : Q($f_e ⟶ $i_e) := q($η_e ⊗≫ $θ_e)
return .coherenceComp e iso_lift? f g h i α η θ
/-- Check that `e` is definitionally equal to `𝟙_ C`. -/
def id₁? (e : Expr) : MonoidalM (Option Obj) := do
let ctx ← read
match ctx.instMonoidal? with
| some _monoidal => do
if ← withDefault <| isDefEq e (q(𝟙_ _) : Q($ctx.C)) then
return some ⟨none⟩
else
return none
| _ => return none
/-- Return `(f, g)` if `e` is definitionally equal to `f ⊗ g`. -/
def comp? (e : Expr) : MonoidalM (Option (Mor₁ × Mor₁)) := do
let ctx ← read
let f ← mkFreshExprMVarQ ctx.C
let g ← mkFreshExprMVarQ ctx.C
match ctx.instMonoidal? with
| some _monoidal => do
if ← withDefault <| isDefEq e q($f ⊗ $g) then
let f ← instantiateMVars f
let g ← instantiateMVars g
return some ((.of ⟨f, ⟨none⟩, ⟨none⟩⟩ : Mor₁), (.of ⟨g, ⟨none⟩, ⟨none⟩⟩ : Mor₁))
else
return none
| _ => return none
/-- Construct a `Mor₁` expression from a Lean expression. -/
partial def mor₁OfExpr (e : Expr) : MonoidalM Mor₁ := do
if let some f := (← get).cache.find? e then
return f
let f ←
if let some a ← id₁? e then
MonadMor₁.id₁M a
else if let some (f, g) ← comp? e then
MonadMor₁.comp₁M (← mor₁OfExpr f.e) (← mor₁OfExpr g.e)
else
return Mor₁.of ⟨e, ⟨none⟩, ⟨none⟩⟩
modify fun s => { s with cache := s.cache.insert e f }
return f
instance : MkMor₁ MonoidalM where
ofExpr := mor₁OfExpr
/-- Construct a `Mor₂Iso` term from a Lean expression. -/
partial def Mor₂IsoOfExpr (e : Expr) : MonoidalM Mor₂Iso := do
match (← whnfR e).getAppFnArgs with
| (``MonoidalCategoryStruct.associator, #[_, _, _, f, g, h]) =>
associatorM' (← MkMor₁.ofExpr f) (← MkMor₁.ofExpr g) (← MkMor₁.ofExpr h)
| (``MonoidalCategoryStruct.leftUnitor, #[_, _, _, f]) =>
leftUnitorM' (← MkMor₁.ofExpr f)
| (``MonoidalCategoryStruct.rightUnitor, #[_, _, _, f]) =>
rightUnitorM' (← MkMor₁.ofExpr f)
| (``Iso.refl, #[_, _, f]) =>
id₂M' (← MkMor₁.ofExpr f)
| (``Iso.symm, #[_, _, _, _, η]) =>
symmM (← Mor₂IsoOfExpr η)
| (``Iso.trans, #[_, _, _, _, _, η, θ]) =>
comp₂M (← Mor₂IsoOfExpr η) (← Mor₂IsoOfExpr θ)
| (``MonoidalCategory.whiskerLeftIso, #[_, _, _, f, _, _, η]) =>
whiskerLeftM (← MkMor₁.ofExpr f) (← Mor₂IsoOfExpr η)
| (``MonoidalCategory.whiskerRightIso, #[_, _, _, _, _, η, h]) =>
whiskerRightM (← Mor₂IsoOfExpr η) (← MkMor₁.ofExpr h)
| (``tensorIso, #[_, _, _, _, _, _, _, η, θ]) =>
horizontalCompM (← Mor₂IsoOfExpr η) (← Mor₂IsoOfExpr θ)
| (``monoidalIsoComp, #[_, _, _, g, h, _, inst, η, θ]) =>
let α ← coherenceHomM (← MkMor₁.ofExpr g) (← MkMor₁.ofExpr h) inst
coherenceCompM α (← Mor₂IsoOfExpr η) (← Mor₂IsoOfExpr θ)
| (``MonoidalCoherence.iso, #[_, _, f, g, inst]) =>
coherenceHomM' (← MkMor₁.ofExpr f) (← MkMor₁.ofExpr g) inst
| _ =>
return .of ⟨e, ← MkMor₁.ofExpr (← srcExprOfIso e), ← MkMor₁.ofExpr (← tgtExprOfIso e)⟩
open MonadMor₂ in
/-- Construct a `Mor₂` term from a Lean expression. -/
partial def Mor₂OfExpr (e : Expr) : MonoidalM Mor₂ := do
match ← whnfR e with
-- whnfR version of `Iso.hom η`
| .proj ``Iso 0 η => homM (← Mor₂IsoOfExpr η)
-- whnfR version of `Iso.inv η`
| .proj ``Iso 1 η => invM (← Mor₂IsoOfExpr η)
| .app .. => match (← whnfR e).getAppFnArgs with
| (``CategoryStruct.id, #[_, _, f]) => id₂M (← MkMor₁.ofExpr f)
| (``CategoryStruct.comp, #[_, _, _, _, _, η, θ]) =>
comp₂M (← Mor₂OfExpr η) (← Mor₂OfExpr θ)
| (``MonoidalCategoryStruct.whiskerLeft, #[_, _, _, f, _, _, η]) =>
whiskerLeftM (← MkMor₁.ofExpr f) (← Mor₂OfExpr η)
| (``MonoidalCategoryStruct.whiskerRight, #[_, _, _, _, _, η, h]) =>
whiskerRightM (← Mor₂OfExpr η) (← MkMor₁.ofExpr h)
| (``MonoidalCategoryStruct.tensorHom, #[_, _, _, _, _, _, _, η, θ]) =>
horizontalCompM (← Mor₂OfExpr η) (← Mor₂OfExpr θ)
| (``monoidalComp, #[_, _, _, g, h, _, inst, η, θ]) =>
let α ← coherenceHomM (← MkMor₁.ofExpr g) (← MkMor₁.ofExpr h) inst
coherenceCompM α (← Mor₂OfExpr η) (← Mor₂OfExpr θ)
| _ => return .of ⟨e, ← MkMor₁.ofExpr (← srcExpr e), ← MkMor₁.ofExpr (← tgtExpr e)⟩
| _ =>
return .of ⟨e, ← MkMor₁.ofExpr (← srcExpr e), ← MkMor₁.ofExpr (← tgtExpr e)⟩
instance : BicategoryLike.MkMor₂ MonoidalM where
ofExpr := Mor₂OfExpr
instance : MonadCoherehnceHom MonoidalM where
unfoldM α := Mor₂IsoOfExpr α.unfold
end Mathlib.Tactic.Monoidal |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Bicategory/PureCoherence.lean | import Mathlib.Tactic.CategoryTheory.Coherence.PureCoherence
import Mathlib.Tactic.CategoryTheory.Bicategory.Datatypes
/-!
# Coherence tactic for bicategories
We provide a `bicategory_coherence` tactic,
which proves that any two morphisms (with the same source and target)
in a bicategory which are built out of associators and unitors
are equal.
-/
open Lean Meta Elab Qq
open CategoryTheory Mathlib.Tactic.BicategoryLike Bicategory
namespace Mathlib.Tactic.Bicategory
section
universe w v u
variable {B : Type u} [Bicategory.{w, v} B] {a b c d e : B}
local infixr:81 " ◁ " => Bicategory.whiskerLeftIso
local infixl:81 " ▷ " => Bicategory.whiskerRightIso
/-- The composition of the normalizing isomorphisms `η_f : p ≫ f ≅ pf` and `η_g : pf ≫ g ≅ pfg`. -/
abbrev normalizeIsoComp {p : a ⟶ b} {f : b ⟶ c} {g : c ⟶ d} {pf : a ⟶ c} {pfg : a ⟶ d}
(η_f : p ≫ f ≅ pf) (η_g : pf ≫ g ≅ pfg) :=
(α_ _ _ _).symm ≪≫ whiskerRightIso η_f g ≪≫ η_g
theorem naturality_associator
{p : a ⟶ b} {f : b ⟶ c} {g : c ⟶ d} {h : d ⟶ e} {pf : a ⟶ c} {pfg : a ⟶ d} {pfgh : a ⟶ e}
(η_f : p ≫ f ≅ pf) (η_g : pf ≫ g ≅ pfg) (η_h : pfg ≫ h ≅ pfgh) :
p ◁ (α_ f g h) ≪≫ (normalizeIsoComp η_f (normalizeIsoComp η_g η_h)) =
(normalizeIsoComp (normalizeIsoComp η_f η_g) η_h) :=
Iso.ext (by simp)
theorem naturality_leftUnitor {p : a ⟶ b} {f : b ⟶ c} {pf : a ⟶ c} (η_f : p ≫ f ≅ pf) :
p ◁ (λ_ f) ≪≫ η_f = normalizeIsoComp (ρ_ p) η_f :=
Iso.ext (by simp)
theorem naturality_rightUnitor {p : a ⟶ b} {f : b ⟶ c} {pf : a ⟶ c} (η_f : p ≫ f ≅ pf) :
p ◁ (ρ_ f) ≪≫ η_f = normalizeIsoComp η_f (ρ_ pf) :=
Iso.ext (by simp)
theorem naturality_id {p : a ⟶ b} {f : b ⟶ c} {pf : a ⟶ c} (η_f : p ≫ f ≅ pf) :
p ◁ Iso.refl f ≪≫ η_f = η_f :=
Iso.ext (by simp)
theorem naturality_comp {p : a ⟶ b} {f g h : b ⟶ c} {pf : a ⟶ c} {η : f ≅ g} {θ : g ≅ h}
(η_f : p ≫ f ≅ pf) (η_g : p ≫ g ≅ pf) (η_h : p ≫ h ≅ pf)
(ih_η : p ◁ η ≪≫ η_g = η_f) (ih_θ : p ◁ θ ≪≫ η_h = η_g) :
p ◁ (η ≪≫ θ) ≪≫ η_h = η_f := by
rw [← ih_η, ← ih_θ]
apply Iso.ext (by simp)
theorem naturality_whiskerLeft {p : a ⟶ b} {f : b ⟶ c} {g h : c ⟶ d} {pf : a ⟶ c} {pfg : a ⟶ d}
{η : g ≅ h} (η_f : p ≫ f ≅ pf) (η_fg : pf ≫ g ≅ pfg) (η_fh : pf ≫ h ≅ pfg)
(ih_η : pf ◁ η ≪≫ η_fh = η_fg) :
p ◁ (f ◁ η) ≪≫ normalizeIsoComp η_f η_fh = normalizeIsoComp η_f η_fg := by
rw [← ih_η]
apply Iso.ext (by simp [← whisker_exchange_assoc])
theorem naturality_whiskerRight {p : a ⟶ b} {f g : b ⟶ c} {h : c ⟶ d} {pf : a ⟶ c} {pfh : a ⟶ d}
{η : f ≅ g} (η_f : p ≫ f ≅ pf) (η_g : p ≫ g ≅ pf) (η_fh : pf ≫ h ≅ pfh)
(ih_η : p ◁ η ≪≫ η_g = η_f) :
p ◁ (η ▷ h) ≪≫ normalizeIsoComp η_g η_fh = normalizeIsoComp η_f η_fh := by
rw [← ih_η]
apply Iso.ext (by simp)
theorem naturality_inv {p : a ⟶ b} {f g : b ⟶ c} {pf : a ⟶ c}
{η : f ≅ g} (η_f : p ≫ f ≅ pf) (η_g : p ≫ g ≅ pf) (ih : p ◁ η ≪≫ η_g = η_f) :
p ◁ η.symm ≪≫ η_f = η_g := by
rw [← ih]
apply Iso.ext (by simp)
instance : MonadNormalizeNaturality BicategoryM where
mkNaturalityAssociator p pf pfg pfgh f g h η_f η_g η_h := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := p.src.e
have b : Q($ctx.B) := p.tgt.e
have c : Q($ctx.B) := f.tgt.e
have d : Q($ctx.B) := g.tgt.e
have e : Q($ctx.B) := h.tgt.e
have p : Q($a ⟶ $b) := p.e.e
have f : Q($b ⟶ $c) := f.e
have g : Q($c ⟶ $d) := g.e
have h : Q($d ⟶ $e) := h.e
have pf : Q($a ⟶ $c) := pf.e.e
have pfg : Q($a ⟶ $d) := pfg.e.e
have pfgh : Q($a ⟶ $e) := pfgh.e.e
have η_f : Q($p ≫ $f ≅ $pf) := η_f.e
have η_g : Q($pf ≫ $g ≅ $pfg) := η_g.e
have η_h : Q($pfg ≫ $h ≅ $pfgh) := η_h.e
return q(naturality_associator $η_f $η_g $η_h)
mkNaturalityLeftUnitor p pf f η_f := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := p.src.e
have b : Q($ctx.B) := p.tgt.e
have c : Q($ctx.B) := f.tgt.e
have p : Q($a ⟶ $b) := p.e.e
have f : Q($b ⟶ $c) := f.e
have pf : Q($a ⟶ $c) := pf.e.e
have η_f : Q($p ≫ $f ≅ $pf) := η_f.e
return q(naturality_leftUnitor $η_f)
mkNaturalityRightUnitor p pf f η_f := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := p.src.e
have b : Q($ctx.B) := p.tgt.e
have c : Q($ctx.B) := f.tgt.e
have p : Q($a ⟶ $b) := p.e.e
have f : Q($b ⟶ $c) := f.e
have pf : Q($a ⟶ $c) := pf.e.e
have η_f : Q($p ≫ $f ≅ $pf) := η_f.e
return q(naturality_rightUnitor $η_f)
mkNaturalityId p pf f η_f := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := p.src.e
have b : Q($ctx.B) := p.tgt.e
have c : Q($ctx.B) := f.tgt.e
have p : Q($a ⟶ $b) := p.e.e
have f : Q($b ⟶ $c) := f.e
have pf : Q($a ⟶ $c) := pf.e.e
have η_f : Q($p ≫ $f ≅ $pf) := η_f.e
return q(naturality_id $η_f)
mkNaturalityComp p pf f g h η θ η_f η_g η_h ih_η ih_θ := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := p.src.e
have b : Q($ctx.B) := p.tgt.e
have c : Q($ctx.B) := f.tgt.e
have p : Q($a ⟶ $b) := p.e.e
have f : Q($b ⟶ $c) := f.e
have g : Q($b ⟶ $c) := g.e
have h : Q($b ⟶ $c) := h.e
have pf : Q($a ⟶ $c) := pf.e.e
have η : Q($f ≅ $g) := η.e
have θ : Q($g ≅ $h) := θ.e
have η_f : Q($p ≫ $f ≅ $pf) := η_f.e
have η_g : Q($p ≫ $g ≅ $pf) := η_g.e
have η_h : Q($p ≫ $h ≅ $pf) := η_h.e
have ih_η : Q($p ◁ $η ≪≫ $η_g = $η_f) := ih_η
have ih_θ : Q($p ◁ $θ ≪≫ $η_h = $η_g) := ih_θ
return q(naturality_comp $η_f $η_g $η_h $ih_η $ih_θ)
mkNaturalityWhiskerLeft p pf pfg f g h η η_f η_fg η_fh ih_η := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := p.src.e
have b : Q($ctx.B) := p.tgt.e
have c : Q($ctx.B) := f.tgt.e
have d : Q($ctx.B) := g.tgt.e
have p : Q($a ⟶ $b) := p.e.e
have f : Q($b ⟶ $c) := f.e
have g : Q($c ⟶ $d) := g.e
have h : Q($c ⟶ $d) := h.e
have pf : Q($a ⟶ $c) := pf.e.e
have pfg : Q($a ⟶ $d) := pfg.e.e
have η : Q($g ≅ $h) := η.e
have η_f : Q($p ≫ $f ≅ $pf) := η_f.e
have η_fg : Q($pf ≫ $g ≅ $pfg) := η_fg.e
have η_fh : Q($pf ≫ $h ≅ $pfg) := η_fh.e
have ih_η : Q($pf ◁ $η ≪≫ $η_fh = $η_fg) := ih_η
return q(naturality_whiskerLeft $η_f $η_fg $η_fh $ih_η)
mkNaturalityWhiskerRight p pf pfh f g h η η_f η_g η_fh ih_η := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := p.src.e
have b : Q($ctx.B) := p.tgt.e
have c : Q($ctx.B) := f.tgt.e
have d : Q($ctx.B) := h.tgt.e
have p : Q($a ⟶ $b) := p.e.e
have f : Q($b ⟶ $c) := f.e
have g : Q($b ⟶ $c) := g.e
have h : Q($c ⟶ $d) := h.e
have pf : Q($a ⟶ $c) := pf.e.e
have pfh : Q($a ⟶ $d) := pfh.e.e
have η : Q($f ≅ $g) := η.e
have η_f : Q($p ≫ $f ≅ $pf) := η_f.e
have η_g : Q($p ≫ $g ≅ $pf) := η_g.e
have η_fh : Q($pf ≫ $h ≅ $pfh) := η_fh.e
have ih_η : Q($p ◁ $η ≪≫ $η_g = $η_f) := ih_η
return q(naturality_whiskerRight $η_f $η_g $η_fh $ih_η)
mkNaturalityHorizontalComp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ := do
throwError "horizontal composition is not implemented"
mkNaturalityInv p pf f g η η_f η_g ih := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := p.src.e
have b : Q($ctx.B) := p.tgt.e
have c : Q($ctx.B) := f.tgt.e
have p : Q($a ⟶ $b) := p.e.e
have f : Q($b ⟶ $c) := f.e
have g : Q($b ⟶ $c) := g.e
have pf : Q($a ⟶ $c) := pf.e.e
have η : Q($f ≅ $g) := η.e
have η_f : Q($p ≫ $f ≅ $pf) := η_f.e
have η_g : Q($p ≫ $g ≅ $pf) := η_g.e
have ih : Q($p ◁ $η ≪≫ $η_g = $η_f) := ih
return q(naturality_inv $η_f $η_g $ih)
theorem of_normalize_eq {f g f' : a ⟶ b} {η θ : f ≅ g} (η_f : 𝟙 a ≫ f ≅ f') (η_g : 𝟙 a ≫ g ≅ f')
(h_η : 𝟙 a ◁ η ≪≫ η_g = η_f)
(h_θ : 𝟙 a ◁ θ ≪≫ η_g = η_f) : η = θ := by
apply Iso.ext
calc
η.hom = (λ_ f).inv ≫ η_f.hom ≫ η_g.inv ≫ (λ_ g).hom := by
simp [← reassoc_of% (congrArg Iso.hom h_η)]
_ = θ.hom := by
simp [← reassoc_of% (congrArg Iso.hom h_θ)]
theorem mk_eq_of_naturality {f g f' : a ⟶ b} {η θ : f ⟶ g} {η' θ' : f ≅ g}
(η_f : 𝟙 a ≫ f ≅ f') (η_g : 𝟙 a ≫ g ≅ f')
(Hη : η'.hom = η) (Hθ : θ'.hom = θ)
(Hη' : whiskerLeftIso (𝟙 a) η' ≪≫ η_g = η_f)
(Hθ' : whiskerLeftIso (𝟙 a) θ' ≪≫ η_g = η_f) : η = θ :=
calc
η = η'.hom := Hη.symm
_ = (λ_ f).inv ≫ η_f.hom ≫ η_g.inv ≫ (λ_ g).hom := by
simp [← reassoc_of% (congrArg Iso.hom Hη')]
_ = θ'.hom := by
simp [← reassoc_of% (congrArg Iso.hom Hθ')]
_ = θ := Hθ
end
instance : MkEqOfNaturality BicategoryM where
mkEqOfNaturality η θ ηIso θIso η_f η_g Hη Hθ := do
let ctx ← read
let _bicat := ctx.instBicategory
let η' := ηIso.e
let θ' := θIso.e
let f ← η'.srcM
let g ← η'.tgtM
let f' ← η_f.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have f' : Q($a ⟶ $b) := f'.e
have η : Q($f ⟶ $g) := η
have θ : Q($f ⟶ $g) := θ
have η'_e : Q($f ≅ $g) := η'.e
have θ'_e : Q($f ≅ $g) := θ'.e
have η_f : Q(𝟙 $a ≫ $f ≅ $f') := η_f.e
have η_g : Q(𝟙 $a ≫ $g ≅ $f') := η_g.e
have η_hom : Q(Iso.hom $η'_e = $η) := ηIso.eq
have Θ_hom : Q(Iso.hom $θ'_e = $θ) := θIso.eq
have Hη : Q(whiskerLeftIso (𝟙 $a) $η'_e ≪≫ $η_g = $η_f) := Hη
have Hθ : Q(whiskerLeftIso (𝟙 $a) $θ'_e ≪≫ $η_g = $η_f) := Hθ
return q(mk_eq_of_naturality $η_f $η_g $η_hom $Θ_hom $Hη $Hθ)
open Elab.Tactic
/-- Close the goal of the form `η.hom = θ.hom`, where `η` and `θ` are 2-isomorphisms made up only of
associators, unitors, and identities.
```lean
example {B : Type} [Bicategory B] {a : B} :
(λ_ (𝟙 a)).hom = (ρ_ (𝟙 a)).hom := by
bicategory_coherence
```
-/
def pureCoherence (mvarId : MVarId) : MetaM (List MVarId) :=
BicategoryLike.pureCoherence Bicategory.Context `bicategory mvarId
@[inherit_doc pureCoherence]
elab "bicategory_coherence" : tactic => withMainContext do
replaceMainGoal <| ← Bicategory.pureCoherence <| ← getMainGoal
end Mathlib.Tactic.Bicategory |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Bicategory/Basic.lean | import Mathlib.Tactic.CategoryTheory.Coherence.Basic
import Mathlib.Tactic.CategoryTheory.Bicategory.Normalize
import Mathlib.Tactic.CategoryTheory.Bicategory.PureCoherence
/-!
# `bicategory` tactic
This file provides `bicategory` tactic, which solves equations in a bicategory, where
the two sides only differ by replacing strings of bicategory structural morphisms (that is,
associators, unitors, and identities) with different strings of structural morphisms with the same
source and target. In other words, `bicategory` solves equalities where both sides have the same
string diagrams.
The core function for the `bicategory` tactic is provided in
`Mathlib/Tactic/CategoryTheory/Coherence/Basic.lean`. See this file for more details about the
implementation.
-/
open Lean Meta Elab Tactic
open CategoryTheory Mathlib.Tactic.BicategoryLike
namespace Mathlib.Tactic.Bicategory
/-- Normalize the both sides of an equality. -/
def bicategoryNf (mvarId : MVarId) : MetaM (List MVarId) := do
BicategoryLike.normalForm Bicategory.Context `bicategory mvarId
@[inherit_doc bicategoryNf]
elab "bicategory_nf" : tactic => withMainContext do
replaceMainGoal (← bicategoryNf (← getMainGoal))
/--
Use the coherence theorem for bicategories to solve equations in a bicategory,
where the two sides only differ by replacing strings of bicategory structural morphisms
(that is, associators, unitors, and identities)
with different strings of structural morphisms with the same source and target.
That is, `bicategory` can handle goals of the form
`a ≫ f ≫ b ≫ g ≫ c = a' ≫ f ≫ b' ≫ g ≫ c'`
where `a = a'`, `b = b'`, and `c = c'` can be proved using `bicategory_coherence`.
-/
def bicategory (mvarId : MVarId) : MetaM (List MVarId) :=
BicategoryLike.main Bicategory.Context `bicategory mvarId
@[inherit_doc bicategory]
elab "bicategory" : tactic => withMainContext do
replaceMainGoal <| ← bicategory <| ← getMainGoal
end Mathlib.Tactic.Bicategory |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Bicategory/Normalize.lean | import Mathlib.Tactic.CategoryTheory.Coherence.Normalize
import Mathlib.Tactic.CategoryTheory.Bicategory.Datatypes
/-!
# Normalization of 2-morphisms in bicategories
This file provides the implementation of the normalization given in
`Mathlib/Tactic/CategoryTheory/Coherence/Normalize.lean`. See this file for more details.
-/
open Lean Meta Elab Qq
open CategoryTheory Mathlib.Tactic.BicategoryLike Bicategory
namespace Mathlib.Tactic.Bicategory
section
universe w v u
variable {B : Type u} [Bicategory.{w, v} B]
variable {a b c d : B}
variable {f f' g g' h i j : a ⟶ b}
@[nolint synTaut]
theorem evalComp_nil_nil (α : f ≅ g) (β : g ≅ h) :
(α ≪≫ β).hom = (α ≪≫ β).hom := by
simp
theorem evalComp_nil_cons (α : f ≅ g) (β : g ≅ h) (η : h ⟶ i) (ηs : i ⟶ j) :
α.hom ≫ (β.hom ≫ η ≫ ηs) = (α ≪≫ β).hom ≫ η ≫ ηs := by
simp
theorem evalComp_cons (α : f ≅ g) (η : g ⟶ h) {ηs : h ⟶ i} {θ : i ⟶ j} {ι : h ⟶ j}
(e_ι : ηs ≫ θ = ι) :
(α.hom ≫ η ≫ ηs) ≫ θ = α.hom ≫ η ≫ ι := by
simp [e_ι]
theorem eval_comp
{η η' : f ⟶ g} {θ θ' : g ⟶ h} {ι : f ⟶ h}
(e_η : η = η') (e_θ : θ = θ') (e_ηθ : η' ≫ θ' = ι) :
η ≫ θ = ι := by
simp [e_η, e_θ, e_ηθ]
theorem eval_of (η : f ⟶ g) :
η = (Iso.refl _).hom ≫ η ≫ (Iso.refl _).hom := by
simp
theorem eval_monoidalComp
{η η' : f ⟶ g} {α : g ≅ h} {θ θ' : h ⟶ i} {αθ : g ⟶ i} {ηαθ : f ⟶ i}
(e_η : η = η') (e_θ : θ = θ') (e_αθ : α.hom ≫ θ' = αθ) (e_ηαθ : η' ≫ αθ = ηαθ) :
η ≫ α.hom ≫ θ = ηαθ := by
simp [e_η, e_θ, e_αθ, e_ηαθ]
@[nolint synTaut]
theorem evalWhiskerLeft_nil (f : a ⟶ b) {g h : b ⟶ c} (α : g ≅ h) :
(whiskerLeftIso f α).hom = (whiskerLeftIso f α).hom := by
simp
theorem evalWhiskerLeft_of_cons
{f : a ⟶ b} {g h i j : b ⟶ c}
(α : g ≅ h) (η : h ⟶ i) {ηs : i ⟶ j} {θ : f ≫ i ⟶ f ≫ j} (e_θ : f ◁ ηs = θ) :
f ◁ (α.hom ≫ η ≫ ηs) = (whiskerLeftIso f α).hom ≫ f ◁ η ≫ θ := by
simp [e_θ]
theorem evalWhiskerLeft_comp
{f : a ⟶ b} {g : b ⟶ c} {h i : c ⟶ d}
{η : h ⟶ i} {η₁ : g ≫ h ⟶ g ≫ i} {η₂ : f ≫ g ≫ h ⟶ f ≫ g ≫ i}
{η₃ : f ≫ g ≫ h ⟶ (f ≫ g) ≫ i} {η₄ : (f ≫ g) ≫ h ⟶ (f ≫ g) ≫ i}
(e_η₁ : g ◁ η = η₁) (e_η₂ : f ◁ η₁ = η₂)
(e_η₃ : η₂ ≫ (α_ _ _ _).inv = η₃) (e_η₄ : (α_ _ _ _).hom ≫ η₃ = η₄) :
(f ≫ g) ◁ η = η₄ := by
simp [e_η₁, e_η₂, e_η₃, e_η₄]
theorem evalWhiskerLeft_id {η : f ⟶ g}
{η₁ : f ⟶ 𝟙 a ≫ g} {η₂ : 𝟙 a ≫ f ⟶ 𝟙 a ≫ g}
(e_η₁ : η ≫ (λ_ _).inv = η₁) (e_η₂ : (λ_ _).hom ≫ η₁ = η₂) :
𝟙 a ◁ η = η₂ := by
simp [e_η₁, e_η₂]
theorem eval_whiskerLeft
{f : a ⟶ b} {g h : b ⟶ c}
{η η' : g ⟶ h} {θ : f ≫ g ⟶ f ≫ h}
(e_η : η = η') (e_θ : f ◁ η' = θ) :
f ◁ η = θ := by
simp [e_η, e_θ]
theorem eval_whiskerRight
{f g : a ⟶ b} {h : b ⟶ c}
{η η' : f ⟶ g} {θ : f ≫ h ⟶ g ≫ h}
(e_η : η = η') (e_θ : η' ▷ h = θ) :
η ▷ h = θ := by
simp [e_η, e_θ]
@[nolint synTaut]
theorem evalWhiskerRight_nil (α : f ≅ g) (h : b ⟶ c) :
α.hom ▷ h = α.hom ▷ h := by
simp
theorem evalWhiskerRightAux_of {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c) :
η ▷ h = (Iso.refl _).hom ≫ η ▷ h ≫ (Iso.refl _).hom := by
simp
theorem evalWhiskerRight_cons_of_of
{f g h i : a ⟶ b} {j : b ⟶ c}
{α : f ≅ g} {η : g ⟶ h} {ηs : h ⟶ i} {ηs₁ : h ≫ j ⟶ i ≫ j}
{η₁ : g ≫ j ⟶ h ≫ j} {η₂ : g ≫ j ⟶ i ≫ j} {η₃ : f ≫ j ⟶ i ≫ j}
(e_ηs₁ : ηs ▷ j = ηs₁) (e_η₁ : η ▷ j = η₁)
(e_η₂ : η₁ ≫ ηs₁ = η₂) (e_η₃ : (whiskerRightIso α j).hom ≫ η₂ = η₃) :
(α.hom ≫ η ≫ ηs) ▷ j = η₃ := by
simp_all
theorem evalWhiskerRight_cons_whisker
{f : a ⟶ b} {g : a ⟶ c} {h i : b ⟶ c} {j : a ⟶ c} {k : c ⟶ d}
{α : g ≅ f ≫ h} {η : h ⟶ i} {ηs : f ≫ i ⟶ j}
{η₁ : h ≫ k ⟶ i ≫ k} {η₂ : f ≫ (h ≫ k) ⟶ f ≫ (i ≫ k)} {ηs₁ : (f ≫ i) ≫ k ⟶ j ≫ k}
{ηs₂ : f ≫ (i ≫ k) ⟶ j ≫ k} {η₃ : f ≫ (h ≫ k) ⟶ j ≫ k} {η₄ : (f ≫ h) ≫ k ⟶ j ≫ k}
{η₅ : g ≫ k ⟶ j ≫ k}
(e_η₁ : ((Iso.refl _).hom ≫ η ≫ (Iso.refl _).hom) ▷ k = η₁) (e_η₂ : f ◁ η₁ = η₂)
(e_ηs₁ : ηs ▷ k = ηs₁) (e_ηs₂ : (α_ _ _ _).inv ≫ ηs₁ = ηs₂)
(e_η₃ : η₂ ≫ ηs₂ = η₃) (e_η₄ : (α_ _ _ _).hom ≫ η₃ = η₄)
(e_η₅ : (whiskerRightIso α k).hom ≫ η₄ = η₅) :
(α.hom ≫ (f ◁ η) ≫ ηs) ▷ k = η₅ := by
simp at e_η₁ e_η₅
simp [e_η₁, e_η₂, e_ηs₁, e_ηs₂, e_η₃, e_η₄, e_η₅]
theorem evalWhiskerRight_comp
{f f' : a ⟶ b} {g : b ⟶ c} {h : c ⟶ d}
{η : f ⟶ f'} {η₁ : f ≫ g ⟶ f' ≫ g} {η₂ : (f ≫ g) ≫ h ⟶ (f' ≫ g) ≫ h}
{η₃ : (f ≫ g) ≫ h ⟶ f' ≫ (g ≫ h)} {η₄ : f ≫ (g ≫ h) ⟶ f' ≫ (g ≫ h)}
(e_η₁ : η ▷ g = η₁) (e_η₂ : η₁ ▷ h = η₂)
(e_η₃ : η₂ ≫ (α_ _ _ _).hom = η₃) (e_η₄ : (α_ _ _ _).inv ≫ η₃ = η₄) :
η ▷ (g ≫ h) = η₄ := by
simp [e_η₁, e_η₂, e_η₃, e_η₄]
theorem evalWhiskerRight_id
{η : f ⟶ g} {η₁ : f ⟶ g ≫ 𝟙 b} {η₂ : f ≫ 𝟙 b ⟶ g ≫ 𝟙 b}
(e_η₁ : η ≫ (ρ_ _).inv = η₁) (e_η₂ : (ρ_ _).hom ≫ η₁ = η₂) :
η ▷ 𝟙 b = η₂ := by
simp [e_η₁, e_η₂]
theorem eval_bicategoricalComp
{η η' : f ⟶ g} {α : g ≅ h} {θ θ' : h ⟶ i} {αθ : g ⟶ i} {ηαθ : f ⟶ i}
(e_η : η = η') (e_θ : θ = θ') (e_αθ : α.hom ≫ θ' = αθ) (e_ηαθ : η' ≫ αθ = ηαθ) :
η ≫ α.hom ≫ θ = ηαθ := by
simp [e_η, e_θ, e_αθ, e_ηαθ]
end
open Mor₂Iso
instance : MkEvalComp BicategoryM where
mkEvalCompNilNil α β := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← α.srcM
let g ← α.tgtM
let h ← β.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($a ⟶ $b) := h.e
have α : Q($f ≅ $g) := α.e
have β : Q($g ≅ $h) := β.e
return q(evalComp_nil_nil $α $β)
mkEvalCompNilCons α β η ηs := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← α.srcM
let g ← α.tgtM
let h ← β.tgtM
let i ← η.tgtM
let j ← ηs.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($a ⟶ $b) := h.e
have i : Q($a ⟶ $b) := i.e
have j : Q($a ⟶ $b) := j.e
have α : Q($f ≅ $g) := α.e
have β : Q($g ≅ $h) := β.e
have η : Q($h ⟶ $i) := η.e.e
have ηs : Q($i ⟶ $j) := ηs.e.e
return q(evalComp_nil_cons $α $β $η $ηs)
mkEvalCompCons α η ηs θ ι e_ι := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← α.srcM
let g ← α.tgtM
let h ← η.tgtM
let i ← ηs.tgtM
let j ← θ.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($a ⟶ $b) := h.e
have i : Q($a ⟶ $b) := i.e
have j : Q($a ⟶ $b) := j.e
have α : Q($f ≅ $g) := α.e
have η : Q($g ⟶ $h) := η.e.e
have ηs : Q($h ⟶ $i) := ηs.e.e
have θ : Q($i ⟶ $j) := θ.e.e
have ι : Q($h ⟶ $j) := ι.e.e
have e_ι : Q($ηs ≫ $θ = $ι) := e_ι
return q(evalComp_cons $α $η $e_ι)
instance : MkEvalWhiskerLeft BicategoryM where
mkEvalWhiskerLeftNil f α := do
let ctx ← read
let _bicat := ctx.instBicategory
let g ← α.srcM
let h ← α.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($b ⟶ $c) := g.e
have h : Q($b ⟶ $c) := h.e
have α : Q($g ≅ $h) := α.e
return q(evalWhiskerLeft_nil $f $α)
mkEvalWhiskerLeftOfCons f α η ηs θ e_θ := do
let ctx ← read
let _bicat := ctx.instBicategory
let g ← α.srcM
let h ← α.tgtM
let i ← η.tgtM
let j ← ηs.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($b ⟶ $c) := g.e
have h : Q($b ⟶ $c) := h.e
have i : Q($b ⟶ $c) := i.e
have j : Q($b ⟶ $c) := j.e
have α : Q($g ≅ $h) := α.e
have η : Q($h ⟶ $i) := η.e.e
have ηs : Q($i ⟶ $j) := ηs.e.e
have θ : Q($f ≫ $i ⟶ $f ≫ $j) := θ.e.e
have e_θ : Q($f ◁ $ηs = $θ) := e_θ
return q(evalWhiskerLeft_of_cons $α $η $e_θ)
mkEvalWhiskerLeftComp f g η η₁ η₂ η₃ η₄ e_η₁ e_η₂ e_η₃ e_η₄ := do
let ctx ← read
let _bicat := ctx.instBicategory
let h ← η.srcM
let i ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have d : Q($ctx.B) := h.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($b ⟶ $c) := g.e
have h : Q($c ⟶ $d) := h.e
have i : Q($c ⟶ $d) := i.e
have η : Q($h ⟶ $i) := η.e.e
have η₁ : Q($g ≫ $h ⟶ $g ≫ $i) := η₁.e.e
have η₂ : Q($f ≫ $g ≫ $h ⟶ $f ≫ $g ≫ $i) := η₂.e.e
have η₃ : Q($f ≫ $g ≫ $h ⟶ ($f ≫ $g) ≫ $i) := η₃.e.e
have η₄ : Q(($f ≫ $g) ≫ $h ⟶ ($f ≫ $g) ≫ $i) := η₄.e.e
have e_η₁ : Q($g ◁ $η = $η₁) := e_η₁
have e_η₂ : Q($f ◁ $η₁ = $η₂) := e_η₂
have e_η₃ : Q($η₂ ≫ (α_ _ _ _).inv = $η₃) := e_η₃
have e_η₄ : Q((α_ _ _ _).hom ≫ $η₃ = $η₄) := e_η₄
return q(evalWhiskerLeft_comp $e_η₁ $e_η₂ $e_η₃ $e_η₄)
mkEvalWhiskerLeftId η η₁ η₂ e_η₁ e_η₂ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have η : Q($f ⟶ $g) := η.e.e
have η₁ : Q($f ⟶ 𝟙 $a ≫ $g) := η₁.e.e
have η₂ : Q(𝟙 $a ≫ $f ⟶ 𝟙 $a ≫ $g) := η₂.e.e
have e_η₁ : Q($η ≫ (λ_ _).inv = $η₁) := e_η₁
have e_η₂ : Q((λ_ _).hom ≫ $η₁ = $η₂) := e_η₂
return q(evalWhiskerLeft_id $e_η₁ $e_η₂)
instance : MkEvalWhiskerRight BicategoryM where
mkEvalWhiskerRightAuxOf η h := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := h.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($b ⟶ $c) := h.e
have η : Q($f ⟶ $g) := η.e.e
return q(evalWhiskerRightAux_of $η $h)
mkEvalWhiskerRightAuxCons _ _ _ _ _ _ _ _ _ _ _ := do
throwError "not implemented"
mkEvalWhiskerRightNil α h := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← α.srcM
let g ← α.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := h.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($b ⟶ $c) := h.e
have α : Q($f ≅ $g) := α.e
return q(evalWhiskerRight_nil $α $h)
mkEvalWhiskerRightConsOfOf j α η ηs ηs₁ η₁ η₂ η₃ e_ηs₁ e_η₁ e_η₂ e_η₃ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← α.srcM
let g ← α.tgtM
let h ← η.tgtM
let i ← ηs.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := j.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($a ⟶ $b) := h.e
have i : Q($a ⟶ $b) := i.e
have j : Q($b ⟶ $c) := j.e
have α : Q($f ≅ $g) := α.e
have η : Q($g ⟶ $h) := η.e.e
have ηs : Q($h ⟶ $i) := ηs.e.e
have ηs₁ : Q($h ≫ $j ⟶ $i ≫ $j) := ηs₁.e.e
have η₁ : Q($g ≫ $j ⟶ $h ≫ $j) := η₁.e.e
have η₂ : Q($g ≫ $j ⟶ $i ≫ $j) := η₂.e.e
have η₃ : Q($f ≫ $j ⟶ $i ≫ $j) := η₃.e.e
have e_ηs₁ : Q($ηs ▷ $j = $ηs₁) := e_ηs₁
have e_η₁ : Q($η ▷ $j = $η₁) := e_η₁
have e_η₂ : Q($η₁ ≫ $ηs₁ = $η₂) := e_η₂
have e_η₃ : Q((whiskerRightIso $α $j).hom ≫ $η₂ = $η₃) := e_η₃
return q(evalWhiskerRight_cons_of_of $e_ηs₁ $e_η₁ $e_η₂ $e_η₃)
mkEvalWhiskerRightConsWhisker f k α η ηs η₁ η₂ ηs₁ ηs₂ η₃ η₄ η₅
e_η₁ e_η₂ e_ηs₁ e_ηs₂ e_η₃ e_η₄ e_η₅ := do
let ctx ← read
let _bicat := ctx.instBicategory
let g ← α.srcM
let h ← η.srcM
let i ← η.tgtM
let j ← ηs.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := h.tgt.e
have d : Q($ctx.B) := k.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $c) := g.e
have h : Q($b ⟶ $c) := h.e
have i : Q($b ⟶ $c) := i.e
have j : Q($a ⟶ $c) := j.e
have k : Q($c ⟶ $d) := k.e
have α : Q($g ≅ $f ≫ $h) := α.e
have η : Q($h ⟶ $i) := η.e.e
have ηs : Q($f ≫ $i ⟶ $j) := ηs.e.e
have η₁ : Q($h ≫ $k ⟶ $i ≫ $k) := η₁.e.e
have η₂ : Q($f ≫ ($h ≫ $k) ⟶ $f ≫ ($i ≫ $k)) := η₂.e.e
have ηs₁ : Q(($f ≫ $i) ≫ $k ⟶ $j ≫ $k) := ηs₁.e.e
have ηs₂ : Q($f ≫ ($i ≫ $k) ⟶ $j ≫ $k) := ηs₂.e.e
have η₃ : Q($f ≫ ($h ≫ $k) ⟶ $j ≫ $k) := η₃.e.e
have η₄ : Q(($f ≫ $h) ≫ $k ⟶ $j ≫ $k) := η₄.e.e
have η₅ : Q($g ≫ $k ⟶ $j ≫ $k) := η₅.e.e
have e_η₁ : Q(((Iso.refl _).hom ≫ $η ≫ (Iso.refl _).hom) ▷ $k = $η₁) := e_η₁
have e_η₂ : Q($f ◁ $η₁ = $η₂) := e_η₂
have e_ηs₁ : Q($ηs ▷ $k = $ηs₁) := e_ηs₁
have e_ηs₂ : Q((α_ _ _ _).inv ≫ $ηs₁ = $ηs₂) := e_ηs₂
have e_η₃ : Q($η₂ ≫ $ηs₂ = $η₃) := e_η₃
have e_η₄ : Q((α_ _ _ _).hom ≫ $η₃ = $η₄) := e_η₄
have e_η₅ : Q((whiskerRightIso $α $k).hom ≫ $η₄ = $η₅) := e_η₅
return q(evalWhiskerRight_cons_whisker $e_η₁ $e_η₂ $e_ηs₁ $e_ηs₂ $e_η₃ $e_η₄ $e_η₅)
mkEvalWhiskerRightComp g h η η₁ η₂ η₃ η₄ e_η₁ e_η₂ e_η₃ e_η₄ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let f' ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have d : Q($ctx.B) := h.tgt.e
have f : Q($a ⟶ $b) := f.e
have f' : Q($a ⟶ $b) := f'.e
have g : Q($b ⟶ $c) := g.e
have h : Q($c ⟶ $d) := h.e
have η : Q($f ⟶ $f') := η.e.e
have η₁ : Q($f ≫ $g ⟶ $f' ≫ $g) := η₁.e.e
have η₂ : Q(($f ≫ $g) ≫ $h ⟶ ($f' ≫ $g) ≫ $h) := η₂.e.e
have η₃ : Q(($f ≫ $g) ≫ $h ⟶ $f' ≫ ($g ≫ $h)) := η₃.e.e
have η₄ : Q($f ≫ ($g ≫ $h) ⟶ $f' ≫ ($g ≫ $h)) := η₄.e.e
have e_η₁ : Q($η ▷ $g = $η₁) := e_η₁
have e_η₂ : Q($η₁ ▷ $h = $η₂) := e_η₂
have e_η₃ : Q($η₂ ≫ (α_ _ _ _).hom = $η₃) := e_η₃
have e_η₄ : Q((α_ _ _ _).inv ≫ $η₃ = $η₄) := e_η₄
return q(evalWhiskerRight_comp $e_η₁ $e_η₂ $e_η₃ $e_η₄)
mkEvalWhiskerRightId η η₁ η₂ e_η₁ e_η₂ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have η : Q($f ⟶ $g) := η.e.e
have η₁ : Q($f ⟶ $g ≫ 𝟙 $b) := η₁.e.e
have η₂ : Q($f ≫ 𝟙 $b ⟶ $g ≫ 𝟙 $b) := η₂.e.e
have e_η₁ : Q($η ≫ (ρ_ _).inv = $η₁) := e_η₁
have e_η₂ : Q((ρ_ _).hom ≫ $η₁ = $η₂) := e_η₂
return q(evalWhiskerRight_id $e_η₁ $e_η₂)
instance : MkEvalHorizontalComp BicategoryM where
mkEvalHorizontalCompAuxOf _ _ := do
throwError "not implemented"
mkEvalHorizontalCompAuxCons _ _ _ _ _ _ _ _ _ _ _ := do
throwError "not implemented"
mkEvalHorizontalCompAux'Whisker _ _ _ _ _ _ _ _ _ _ _ := do
throwError "not implemented"
mkEvalHorizontalCompAux'OfWhisker _ _ _ _ _ _ _ _ _ _ _ := do
throwError "not implemented"
mkEvalHorizontalCompNilNil _ _ := do
throwError "not implemented"
mkEvalHorizontalCompNilCons _ _ _ _ _ _ _ _ _ _ _ _ := do
throwError "not implemented"
mkEvalHorizontalCompConsNil _ _ _ _ _ _ _ _ _ _ _ _ := do
throwError "not implemented"
mkEvalHorizontalCompConsCons _ _ _ _ _ _ _ _ _ _ _ _ _ _ := do
throwError "not implemented"
instance : MkEval BicategoryM where
mkEvalComp η θ η' θ' ι e_η e_θ e_ηθ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η'.srcM
let g ← η'.tgtM
let h ← θ'.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($a ⟶ $b) := h.e
have η : Q($f ⟶ $g) := η.e
have η' : Q($f ⟶ $g) := η'.e.e
have θ : Q($g ⟶ $h) := θ.e
have θ' : Q($g ⟶ $h) := θ'.e.e
have ι : Q($f ⟶ $h) := ι.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($θ = $θ') := e_θ
have e_ηθ : Q($η' ≫ $θ' = $ι) := e_ηθ
return q(eval_comp $e_η $e_θ $e_ηθ)
mkEvalWhiskerLeft f η η' θ e_η e_θ := do
let ctx ← read
let _bicat := ctx.instBicategory
let g ← η'.srcM
let h ← η'.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($b ⟶ $c) := g.e
have h : Q($b ⟶ $c) := h.e
have η : Q($g ⟶ $h) := η.e
have η' : Q($g ⟶ $h) := η'.e.e
have θ : Q($f ≫ $g ⟶ $f ≫ $h) := θ.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($f ◁ $η' = $θ) := e_θ
return q(eval_whiskerLeft $e_η $e_θ)
mkEvalWhiskerRight η h η' θ e_η e_θ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η'.srcM
let g ← η'.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := h.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($b ⟶ $c) := h.e
have η : Q($f ⟶ $g) := η.e
have η' : Q($f ⟶ $g) := η'.e.e
have θ : Q($f ≫ $h ⟶ $g ≫ $h) := θ.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($η' ▷ $h = $θ) := e_θ
return q(eval_whiskerRight $e_η $e_θ)
mkEvalHorizontalComp _ _ _ _ _ _ _ _ := do
throwError "not implemented"
mkEvalOf η := do
let ctx ← read
let _bicat := ctx.instBicategory
let f := η.src
let g := η.tgt
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have η : Q($f ⟶ $g) := η.e
return q(eval_of $η)
mkEvalMonoidalComp η θ α η' θ' αθ ηαθ e_η e_θ e_αθ e_ηαθ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η'.srcM
let g ← η'.tgtM
let h ← α.tgtM
let i ← θ'.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f : Q($a ⟶ $b) := f.e
have g : Q($a ⟶ $b) := g.e
have h : Q($a ⟶ $b) := h.e
have i : Q($a ⟶ $b) := i.e
have η : Q($f ⟶ $g) := η.e
have η' : Q($f ⟶ $g) := η'.e.e
have α : Q($g ≅ $h) := α.e
have θ : Q($h ⟶ $i) := θ.e
have θ' : Q($h ⟶ $i) := θ'.e.e
have αθ : Q($g ⟶ $i) := αθ.e.e
have ηαθ : Q($f ⟶ $i) := ηαθ.e.e
have e_η : Q($η = $η') := e_η
have e_θ : Q($θ = $θ') := e_θ
have e_αθ : Q(Iso.hom $α ≫ $θ' = $αθ) := e_αθ
have e_ηαθ : Q($η' ≫ $αθ = $ηαθ) := e_ηαθ
return q(eval_bicategoricalComp $e_η $e_θ $e_αθ $e_ηαθ)
instance : MonadNormalExpr BicategoryM where
whiskerRightM η h := do
return .whisker (← MonadMor₂.whiskerRightM η.e (.of h)) η h
hConsM _ _ := do
throwError "not implemented"
whiskerLeftM f η := do
return .whisker (← MonadMor₂.whiskerLeftM (.of f) η.e) f η
nilM α := do
return .nil (← MonadMor₂.homM α) α
consM α η ηs := do
return .cons (← MonadMor₂.comp₂M (← MonadMor₂.homM α) (← MonadMor₂.comp₂M η.e ηs.e)) α η ηs
instance : MkMor₂ BicategoryM where
ofExpr := Mor₂OfExpr
end Mathlib.Tactic.Bicategory |
.lake/packages/mathlib/Mathlib/Tactic/CategoryTheory/Bicategory/Datatypes.lean | import Mathlib.Tactic.CategoryTheory.Coherence.Datatypes
import Mathlib.Tactic.CategoryTheory.BicategoricalComp
/-!
# Expressions for bicategories
This file converts lean expressions representing 2-morphisms in bicategories into `Mor₂Iso`
or `Mor` terms. The converted expressions are used in the coherence tactics and the string diagram
widgets.
-/
open Lean Meta Elab Qq
open CategoryTheory Mathlib.Tactic.BicategoryLike Bicategory
namespace Mathlib.Tactic.Bicategory
/-- The domain of a morphism. -/
def srcExpr (η : Expr) : MetaM Expr := do
match (← whnfR (← inferType η)).getAppFnArgs with
| (``Quiver.Hom, #[_, _, f, _]) => return f
| _ => throwError m!"{η} is not a morphism"
/-- The codomain of a morphism. -/
def tgtExpr (η : Expr) : MetaM Expr := do
match (← whnfR (← inferType η)).getAppFnArgs with
| (``Quiver.Hom, #[_, _, _, g]) => return g
| _ => throwError m!"{η} is not a morphism"
/-- The domain of an isomorphism. -/
def srcExprOfIso (η : Expr) : MetaM Expr := do
match (← whnfR (← inferType η)).getAppFnArgs with
| (``Iso, #[_, _, f, _]) => return f
| _ => throwError m!"{η} is not a morphism"
/-- The codomain of an isomorphism. -/
def tgtExprOfIso (η : Expr) : MetaM Expr := do
match (← whnfR (← inferType η)).getAppFnArgs with
| (``Iso, #[_, _, _, g]) => return g
| _ => throwError m!"{η} is not a morphism"
initialize registerTraceClass `bicategory
/-- The context for evaluating expressions. -/
structure Context where
/-- The level for 2-morphisms. -/
level₂ : Level
/-- The level for 1-morphisms. -/
level₁ : Level
/-- The level for objects. -/
level₀ : Level
/-- The expression for the underlying category. -/
B : Q(Type level₀)
/-- The bicategory instance. -/
instBicategory : Q(Bicategory.{level₂, level₁} $B)
/-- Populate a `context` object for evaluating `e`. -/
def mkContext? (e : Expr) : MetaM (Option Context) := do
let e ← instantiateMVars e
let type ← instantiateMVars <| ← inferType e
match (← whnfR (← inferType e)).getAppFnArgs with
| (``Quiver.Hom, #[_, _, f, _]) =>
let fType ← instantiateMVars <| ← inferType f
match (← whnfR fType).getAppFnArgs with
| (``Quiver.Hom, #[_, _, a, _]) =>
let B ← inferType a
let .succ level₀ ← getLevel B | return none
let .succ level₁ ← getLevel fType | return none
let .succ level₂ ← getLevel type | return none
let some instBicategory ← synthInstance?
(mkAppN (.const ``Bicategory [level₂, level₁, level₀]) #[B]) | return none
return some ⟨level₂, level₁, level₀, B, instBicategory⟩
| _ => return none
| _ => return none
instance : BicategoryLike.Context Bicategory.Context where
mkContext? := Bicategory.mkContext?
/-- The monad for the normalization of 2-morphisms. -/
abbrev BicategoryM := CoherenceM Context
instance : MonadMor₁ BicategoryM where
id₁M a := do
let ctx ← read
let _bicat := ctx.instBicategory
have a_e : Q($ctx.B) := a.e
return .id q(𝟙 $a_e) a
comp₁M f g := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($b ⟶ $c) := g.e
return .comp q($f_e ≫ $g_e) f g
section
universe w v u
variable {B : Type u} [Bicategory.{w, v} B] {a b c : B}
theorem structuralIso_inv {f g : a ⟶ b} (η : f ≅ g) :
η.symm.hom = η.inv := by
simp only [Iso.symm_hom]
theorem structuralIsoOfExpr_comp {f g h : a ⟶ b}
(η : f ⟶ g) (η' : f ≅ g) (ih_η : η'.hom = η)
(θ : g ⟶ h) (θ' : g ≅ h) (ih_θ : θ'.hom = θ) :
(η' ≪≫ θ').hom = η ≫ θ := by
simp [ih_η, ih_θ]
theorem structuralIsoOfExpr_whiskerLeft (f : a ⟶ b) {g h : b ⟶ c}
(η : g ⟶ h) (η' : g ≅ h) (ih_η : η'.hom = η) :
(whiskerLeftIso f η').hom = f ◁ η := by
simp [ih_η]
theorem structuralIsoOfExpr_whiskerRight {f g : a ⟶ b} (h : b ⟶ c)
(η : f ⟶ g) (η' : f ≅ g) (ih_η : η'.hom = η) :
(whiskerRightIso η' h).hom = η ▷ h := by
simp [ih_η]
theorem StructuralOfExpr_bicategoricalComp {f g h i : a ⟶ b} [BicategoricalCoherence g h]
(η : f ⟶ g) (η' : f ≅ g) (ih_η : η'.hom = η) (θ : h ⟶ i) (θ' : h ≅ i) (ih_θ : θ'.hom = θ) :
(bicategoricalIsoComp η' θ').hom = η ⊗≫ θ := by
simp [ih_η, ih_θ, bicategoricalIsoComp, bicategoricalComp]
end
open MonadMor₁
instance : MonadMor₂Iso BicategoryM where
associatorM f g h := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have d : Q($ctx.B) := h.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($b ⟶ $c) := g.e
have h_e : Q($c ⟶ $d) := h.e
return .associator q(α_ $f_e $g_e $h_e) f g h
leftUnitorM f := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
return .leftUnitor q(λ_ $f_e) f
rightUnitorM f := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
return .rightUnitor q(ρ_ $f_e) f
id₂M f := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
return .id q(Iso.refl $f_e) f
coherenceHomM f g inst := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have inst : Q(BicategoricalCoherence $f_e $g_e) := inst
match (← whnfI inst).getAppFnArgs with
| (``BicategoricalCoherence.mk, #[_, _, _, _, _, _, α]) =>
let e : Q($f_e ≅ $g_e) := q(BicategoricalCoherence.iso)
return ⟨e, f, g, inst, α⟩
| _ => throwError m!"failed to unfold {inst}"
comp₂M η θ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
let h ← θ.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have h_e : Q($a ⟶ $b) := h.e
have η_e : Q($f_e ≅ $g_e) := η.e
have θ_e : Q($g_e ≅ $h_e) := θ.e
return .comp q($η_e ≪≫ $θ_e) f g h η θ
whiskerLeftM f η := do
let ctx ← read
let _bicat := ctx.instBicategory
let g ← η.srcM
let h ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($b ⟶ $c) := g.e
have h_e : Q($b ⟶ $c) := h.e
have η_e : Q($g_e ≅ $h_e) := η.e
return .whiskerLeft q(whiskerLeftIso $f_e $η_e) f g h η
whiskerRightM η h := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := h.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have h_e : Q($b ⟶ $c) := h.e
have η_e : Q($f_e ≅ $g_e) := η.e
return .whiskerRight q(whiskerRightIso $η_e $h_e) f g η h
horizontalCompM _ _ := throwError "horizontal composition is not implemented"
symmM η := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
return .inv q(Iso.symm $η_e) f g η
coherenceCompM α η θ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
let h ← θ.srcM
let i ← θ.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have h_e : Q($a ⟶ $b) := h.e
have i_e : Q($a ⟶ $b) := i.e
have _inst : Q(BicategoricalCoherence $g_e $h_e) := α.inst
have η_e : Q($f_e ≅ $g_e) := η.e
have θ_e : Q($h_e ≅ $i_e) := θ.e
return .coherenceComp q($η_e ≪⊗≫ $θ_e) f g h i α η θ
open MonadMor₂Iso
instance : MonadMor₂ BicategoryM where
homM η := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
let e : Q($f_e ⟶ $g_e) := q(Iso.hom $η_e)
have eq : Q(Iso.hom $η_e = $e) := q(rfl)
return .isoHom q(Iso.hom $η_e) ⟨η, eq⟩ η
atomHomM η := do
let ctx ← read
let _bicat := ctx.instBicategory
let f := η.src
let g := η.tgt
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
return .mk q(Iso.hom $η_e) f g
invM η := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
let e : Q($g_e ⟶ $f_e) := q(Iso.inv $η_e)
let η_inv ← symmM η
let eq : Q(Iso.inv $η_e = $e) := q(Iso.symm_hom $η_e)
return .isoInv e ⟨η_inv, eq⟩ η
atomInvM η := do
let ctx ← read
let _bicat := ctx.instBicategory
let f := η.src
let g := η.tgt
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have η_e : Q($f_e ≅ $g_e) := η.e
return .mk q(Iso.inv $η_e) g f
id₂M f := do
let ctx ← read
let _bicat := ctx.instBicategory
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
let e : Q($f_e ⟶ $f_e) := q(𝟙 $f_e)
let eq : Q(𝟙 $f_e = $e) := q(Iso.refl_hom $f_e)
return .id e ⟨.structuralAtom <| ← id₂M f, eq⟩ f
comp₂M η θ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
let h ← θ.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have h_e : Q($a ⟶ $b) := h.e
have η_e : Q($f_e ⟶ $g_e) := η.e
have θ_e : Q($g_e ⟶ $h_e) := θ.e
let iso_lift? ← (match (η.isoLift?, θ.isoLift?) with
| (some η_iso, some θ_iso) =>
have η_iso_e : Q($f_e ≅ $g_e) := η_iso.e.e
have θ_iso_e : Q($g_e ≅ $h_e) := θ_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
have θ_iso_eq : Q(Iso.hom $θ_iso_e = $θ_e) := θ_iso.eq
let eq := q(structuralIsoOfExpr_comp _ _ $η_iso_eq _ _ $θ_iso_eq)
return some ⟨← comp₂M η_iso.e θ_iso.e, eq⟩
| _ => return none)
let e : Q($f_e ⟶ $h_e) := q($η_e ≫ $θ_e)
return .comp e iso_lift? f g h η θ
whiskerLeftM f η := do
let ctx ← read
let _bicat := ctx.instBicategory
let g ← η.srcM
let h ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have c : Q($ctx.B) := g.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($b ⟶ $c) := g.e
have h_e : Q($b ⟶ $c) := h.e
have η_e : Q($g_e ⟶ $h_e) := η.e
let iso_lift? ← (match η.isoLift? with
| some η_iso => do
have η_iso_e : Q($g_e ≅ $h_e) := η_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
let eq := q(structuralIsoOfExpr_whiskerLeft $f_e _ _ $η_iso_eq)
return some ⟨← whiskerLeftM f η_iso.e, eq⟩
| _ => return none)
let e : Q($f_e ≫ $g_e ⟶ $f_e ≫ $h_e) := q($f_e ◁ $η_e)
return .whiskerLeft e iso_lift? f g h η
whiskerRightM η h := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := h.src.e
have c : Q($ctx.B) := h.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have h_e : Q($b ⟶ $c) := h.e
have η_e : Q($f_e ⟶ $g_e) := η.e
let iso_lift? ← (match η.isoLift? with
| some η_iso => do
have η_iso_e : Q($f_e ≅ $g_e) := η_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
let eq := q(structuralIsoOfExpr_whiskerRight $h_e _ _ $η_iso_eq)
return some ⟨← whiskerRightM η_iso.e h, eq⟩
| _ => return none)
let e : Q($f_e ≫ $h_e ⟶ $g_e ≫ $h_e) := q($η_e ▷ $h_e)
return .whiskerRight e iso_lift? f g η h
horizontalCompM _ _ := throwError "horizontal composition is not implemented"
coherenceCompM α η θ := do
let ctx ← read
let _bicat := ctx.instBicategory
let f ← η.srcM
let g ← η.tgtM
let h ← θ.srcM
let i ← θ.tgtM
have a : Q($ctx.B) := f.src.e
have b : Q($ctx.B) := f.tgt.e
have f_e : Q($a ⟶ $b) := f.e
have g_e : Q($a ⟶ $b) := g.e
have h_e : Q($a ⟶ $b) := h.e
have i_e : Q($a ⟶ $b) := i.e
have _inst : Q(BicategoricalCoherence $g_e $h_e) := α.inst
have η_e : Q($f_e ⟶ $g_e) := η.e
have θ_e : Q($h_e ⟶ $i_e) := θ.e
let iso_lift? ← (match (η.isoLift?, θ.isoLift?) with
| (some η_iso, some θ_iso) => do
have η_iso_e : Q($f_e ≅ $g_e) := η_iso.e.e
have θ_iso_e : Q($h_e ≅ $i_e) := θ_iso.e.e
have η_iso_eq : Q(Iso.hom $η_iso_e = $η_e) := η_iso.eq
have θ_iso_eq : Q(Iso.hom $θ_iso_e = $θ_e) := θ_iso.eq
let eq := q(StructuralOfExpr_bicategoricalComp _ _ $η_iso_eq _ _ $θ_iso_eq)
return some ⟨← coherenceCompM α η_iso.e θ_iso.e, eq⟩
| _ => return none)
let e : Q($f_e ⟶ $i_e) := q($η_e ⊗≫ $θ_e)
return .coherenceComp e iso_lift? f g h i α η θ
/-- Check that `e` is definitionally equal to `𝟙 a`. -/
def id₁? (e : Expr) : BicategoryM (Option Obj) := do
let ctx ← read
let _bicat := ctx.instBicategory
let a : Q($ctx.B) ← mkFreshExprMVar ctx.B
if ← withDefault <| isDefEq e q(𝟙 $a) then
return some ⟨← instantiateMVars a⟩
else
return none
/-- Return `(f, g)` if `e` is definitionally equal to `f ≫ g`. -/
def comp? (e : Expr) : BicategoryM (Option (Mor₁ × Mor₁)) := do
let ctx ← read
let _bicat := ctx.instBicategory
let a ← mkFreshExprMVarQ ctx.B
let b ← mkFreshExprMVarQ ctx.B
let c ← mkFreshExprMVarQ ctx.B
let f ← mkFreshExprMVarQ q($a ⟶ $b)
let g ← mkFreshExprMVarQ q($b ⟶ $c)
if ← withDefault <| isDefEq e q($f ≫ $g) then
let a ← instantiateMVars a
let b ← instantiateMVars b
let c ← instantiateMVars c
let f ← instantiateMVars f
let g ← instantiateMVars g
return some ((.of ⟨f, ⟨a⟩, ⟨b⟩⟩), .of ⟨g, ⟨b⟩, ⟨c⟩⟩)
else
return none
/-- Construct a `Mor₁` expression from a Lean expression. -/
partial def mor₁OfExpr (e : Expr) : BicategoryM Mor₁ := do
if let some f := (← get).cache.find? e then
return f
let f ←
if let some a ← id₁? e then
MonadMor₁.id₁M a
else if let some (f, g) ← comp? e then
MonadMor₁.comp₁M (← mor₁OfExpr f.e) (← mor₁OfExpr g.e)
else
return Mor₁.of ⟨e, ⟨← srcExpr e⟩, ⟨ ← tgtExpr e⟩⟩
modify fun s => { s with cache := s.cache.insert e f }
return f
instance : MkMor₁ BicategoryM where
ofExpr := mor₁OfExpr
/-- Construct a `Mor₂Iso` term from a Lean expression. -/
partial def Mor₂IsoOfExpr (e : Expr) : BicategoryM Mor₂Iso := do
match (← whnfR e).getAppFnArgs with
| (``Bicategory.associator, #[_, _, _, _, _, _, f, g, h]) =>
associatorM' (← MkMor₁.ofExpr f) (← MkMor₁.ofExpr g) (← MkMor₁.ofExpr h)
| (``Bicategory.leftUnitor, #[_, _, _, _, f]) =>
leftUnitorM' (← MkMor₁.ofExpr f)
| (``Bicategory.rightUnitor, #[_, _, _, _, f]) =>
rightUnitorM' (← MkMor₁.ofExpr f)
| (``Iso.refl, #[_, _, f]) =>
id₂M' (← MkMor₁.ofExpr f)
| (``Iso.symm, #[_, _, _, _, η]) =>
symmM (← Mor₂IsoOfExpr η)
| (``Iso.trans, #[_, _, _, _, _, η, θ]) =>
comp₂M (← Mor₂IsoOfExpr η) (← Mor₂IsoOfExpr θ)
| (``Bicategory.whiskerLeftIso, #[_, _, _, _, _, f, _, _, η]) =>
whiskerLeftM (← MkMor₁.ofExpr f) (← Mor₂IsoOfExpr η)
| (``Bicategory.whiskerRightIso, #[_, _, _, _, _, _, _, η, h]) =>
whiskerRightM (← Mor₂IsoOfExpr η) (← MkMor₁.ofExpr h)
| (``bicategoricalIsoComp, #[_, _, _, _, _, g, h, _, inst, η, θ]) =>
let α ← coherenceHomM (← MkMor₁.ofExpr g) (← MkMor₁.ofExpr h) inst
coherenceCompM α (← Mor₂IsoOfExpr η) (← Mor₂IsoOfExpr θ)
| (``BicategoricalCoherence.iso, #[_, _, _, _, f, g, inst]) =>
coherenceHomM' (← MkMor₁.ofExpr f) (← MkMor₁.ofExpr g) inst
| _ =>
return .of ⟨e, ← MkMor₁.ofExpr (← srcExprOfIso e), ← MkMor₁.ofExpr (← tgtExprOfIso e)⟩
open MonadMor₂ in
/-- Construct a `Mor₂` term from a Lean expression. -/
partial def Mor₂OfExpr (e : Expr) : BicategoryM Mor₂ := do
match ← whnfR e with
-- whnfR version of `Iso.hom η`
| .proj ``Iso 0 η => homM (← Mor₂IsoOfExpr η)
-- whnfR version of `Iso.inv η`
| .proj ``Iso 1 η => invM (← Mor₂IsoOfExpr η)
| .app .. => match (← whnfR e).getAppFnArgs with
| (``CategoryStruct.id, #[_, _, f]) => id₂M (← MkMor₁.ofExpr f)
| (``CategoryStruct.comp, #[_, _, _, _, _, η, θ]) =>
comp₂M (← Mor₂OfExpr η) (← Mor₂OfExpr θ)
| (``Bicategory.whiskerLeft, #[_, _, _, _, _, f, _, _, η]) =>
whiskerLeftM (← MkMor₁.ofExpr f) (← Mor₂OfExpr η)
| (``Bicategory.whiskerRight, #[_, _, _, _, _, _, _, η, h]) =>
whiskerRightM (← Mor₂OfExpr η) (← MkMor₁.ofExpr h)
| (``bicategoricalComp, #[_, _, _, _, _, g, h, _, inst, η, θ]) =>
let α ← coherenceHomM (← MkMor₁.ofExpr g) (← MkMor₁.ofExpr h) inst
coherenceCompM α (← Mor₂OfExpr η) (← Mor₂OfExpr θ)
| _ => return .of ⟨e, ← MkMor₁.ofExpr (← srcExpr e), ← MkMor₁.ofExpr (← tgtExpr e)⟩
| _ =>
return .of ⟨e, ← MkMor₁.ofExpr (← srcExpr e), ← MkMor₁.ofExpr (← tgtExpr e)⟩
instance : BicategoryLike.MkMor₂ BicategoryM where
ofExpr := Mor₂OfExpr
instance : MonadCoherehnceHom BicategoryM where
unfoldM α := Mor₂IsoOfExpr α.unfold
end Mathlib.Tactic.Bicategory |
.lake/packages/mathlib/Mathlib/Tactic/TacticAnalysis/Declarations.lean | import Mathlib.Tactic.TacticAnalysis
import Mathlib.Tactic.ExtractGoal
import Mathlib.Tactic.MinImports
import Lean.Elab.Command
/-!
# Tactic linters
This file defines passes to run from the tactic analysis framework.
-/
open Lean Meta
namespace Mathlib.TacticAnalysis
/-- Helper structure for the return type of the `test` function in `terminalReplacement`. -/
private inductive TerminalReplacementOutcome where
| success (stx : TSyntax `tactic)
| remainingGoals (stx : TSyntax `tactic) (goals : List MessageData)
| error (stx : TSyntax `tactic) (msg : MessageData)
open Elab Command
/--
Define a pass that tries replacing one terminal tactic with another.
`newTacticName` is a human-readable name for the tactic, for example "linarith".
This can be used to group messages together, so that `ring`, `ring_nf`, `ring1`, ...
all produce the same message.
`oldTacticKind` is the `SyntaxNodeKind` for the tactic's main parser,
for example `Mathlib.Tactic.linarith`.
`newTactic stx goal` selects the new tactic to try, which may depend on the old tactic invocation
in `stx` and the current `goal`.
-/
def terminalReplacement (oldTacticName newTacticName : String) (oldTacticKind : SyntaxNodeKind)
(newTactic : ContextInfo → TacticInfo → Syntax → CommandElabM (TSyntax `tactic))
(reportFailure : Bool := true) (reportSuccess : Bool := false)
(reportSlowdown : Bool := false) (maxSlowdown : Float := 1) :
TacticAnalysis.Config := .ofComplex {
out := TerminalReplacementOutcome
ctx := Syntax
trigger _ stx := if stx.getKind == oldTacticKind
then .accept stx else .skip
test ctxI i stx goal := do
let tac ← newTactic ctxI i stx
try
let goalTypes ← ctxI.runTacticCode i goal tac ⟨Expr, MVarId.getType'⟩
match goalTypes with
| [] => return .success tac
| _ => do
let goalsMessages := goalTypes.map fun e => m!"⊢ {MessageData.ofExpr e}\n"
return .remainingGoals tac goalsMessages
catch _e =>
let name ← mkAuxDeclName `extracted
-- Rerun in the original tactic context, since `omega` changes the state.
let ((sig, _, modules), _) ← ctxI.runTactic i goal (fun goal =>
(Mathlib.Tactic.ExtractGoal.goalSignature name goal).run)
let imports := modules.toList.map (s!"import {·}")
return .error tac m!"{"\n".intercalate imports}\n\ntheorem {sig} := by\n fail_if_success {tac}\n {stx}"
tell stx old oldHeartbeats new newHeartbeats :=
-- If the original tactic failed, then we do not need to check the replacement.
if !old.isEmpty then
return none
else match new with
| .error _ msg =>
if reportFailure then
let msg :=
m!"`{newTacticName}` failed where `{oldTacticName}` succeeded.\n" ++
m!"Original tactic:{indentD stx}\n" ++
m!"Counterexample:{indentD msg}"
return msg
else
return none
| .remainingGoals newStx goals =>
if reportFailure then
let msg :=
m!"`{newTacticName}` left unsolved goals where `{oldTacticName}` succeeded.\n" ++
m!"Original tactic:{indentD stx}\n" ++
m!"Replacement tactic:{indentD newStx}\n" ++
m!"Unsolved goals:{indentD goals}"
return msg
else
return none
| .success newStx => do
-- TODO: we should add a "Try this:" suggestion with code action.
let msg := if (← liftCoreM <| PrettyPrinter.ppTactic newStx).pretty = newTacticName then
m!"`{newTacticName}` can replace `{stx}`"
else
m!"`{newTacticName}` can replace `{stx}` using `{newStx}`"
if reportSlowdown ∧ maxSlowdown * oldHeartbeats.toFloat < newHeartbeats.toFloat then
return some m!"{msg}, but is slower: {newHeartbeats / 1000} versus {oldHeartbeats / 1000} heartbeats"
else if reportSuccess then
return some msg
else
return none
}
/--
Define a pass that tries replacing a specific tactic with `grind`.
`tacticName` is a human-readable name for the tactic, for example "linarith".
This can be used to group messages together, so that `ring`, `ring_nf`, `ring1`, ...
all produce the same message.
`tacticKind` is the `SyntaxNodeKind` for the tactic's main parser,
for example `Mathlib.Tactic.linarith`.
-/
def grindReplacementWith (tacticName : String) (tacticKind : SyntaxNodeKind)
(reportFailure : Bool := true) (reportSuccess : Bool := false)
(reportSlowdown : Bool := false) (maxSlowdown : Float := 1) :
TacticAnalysis.Config :=
terminalReplacement tacticName "grind" tacticKind (fun _ _ _ => `(tactic| grind))
reportFailure reportSuccess reportSlowdown maxSlowdown
end Mathlib.TacticAnalysis
open Mathlib TacticAnalysis
/-- Debug `grind` by identifying places where it does not yet supersede `linarith`. -/
register_option linter.tacticAnalysis.regressions.linarithToGrind : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.regressions.linarithToGrind,
inherit_doc linter.tacticAnalysis.regressions.linarithToGrind]
def linarithToGrindRegressions := grindReplacementWith "linarith" `Mathlib.Tactic.linarith
/-- Debug `grind` by identifying places where it does not yet supersede `ring`. -/
register_option linter.tacticAnalysis.regressions.ringToGrind : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.regressions.ringToGrind,
inherit_doc linter.tacticAnalysis.regressions.ringToGrind]
def ringToGrindRegressions := grindReplacementWith "ring" `Mathlib.Tactic.RingNF.ring
/-- Debug `cutsat` by identifying places where it does not yet supersede `omega`. -/
register_option linter.tacticAnalysis.regressions.omegaToCutsat : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.regressions.omegaToCutsat,
inherit_doc linter.tacticAnalysis.regressions.omegaToCutsat]
def omegaToCutsatRegressions :=
terminalReplacement "omega" "cutsat" ``Lean.Parser.Tactic.omega (fun _ _ _ => `(tactic| cutsat))
(reportSuccess := false) (reportFailure := true)
/-- Report places where `omega` can be replaced by `cutsat`. -/
register_option linter.tacticAnalysis.omegaToCutsat : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.omegaToCutsat,
inherit_doc linter.tacticAnalysis.omegaToCutsat]
def omegaToCutsat :=
terminalReplacement "omega" "cutsat" ``Lean.Parser.Tactic.omega (fun _ _ _ => `(tactic| cutsat))
(reportSuccess := true) (reportFailure := false)
/-- Suggest merging two adjacent `rw` tactics if that also solves the goal. -/
register_option linter.tacticAnalysis.rwMerge : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.rwMerge, inherit_doc linter.tacticAnalysis.rwMerge]
def Mathlib.TacticAnalysis.rwMerge : TacticAnalysis.Config := .ofComplex {
out := (List MVarId × Array Syntax)
ctx := (Array (Array Syntax))
trigger ctx stx :=
match stx with
| `(tactic| rw [$args,*]) => .continue ((ctx.getD #[]).push args)
| _ => if let some args := ctx then if args.size > 1 then .accept args else .skip else .skip
test ctxI i ctx goal := do
let ctxT : Array (TSyntax `Lean.Parser.Tactic.rwRule) := ctx.flatten.map (⟨·⟩)
let tac ← `(tactic| rw [$ctxT,*])
let oldMessages := (← get).messages
try
let goals ← ctxI.runTacticCode i goal tac
return (goals, ctxT.map (↑·))
catch _e => -- rw throws an error if it fails to pattern-match.
return ([goal], ctxT.map (↑·))
finally
-- Drop any messages, since they will appear as if they are genuine errors.
modify fun s => { s with messages := oldMessages }
tell _stx _old _oldHeartbeats new _newHeartbeats := pure <|
if new.1.isEmpty then
m!"Try this: rw {new.2}"
else none }
/-- Suggest merging `tac; grind` into just `grind` if that also solves the goal. -/
register_option linter.tacticAnalysis.mergeWithGrind : Bool := {
defValue := false
}
private abbrev mergeWithGrindAllowed : Std.HashSet Name := { `«tactic#adaptation_note_» }
@[tacticAnalysis linter.tacticAnalysis.mergeWithGrind,
inherit_doc linter.tacticAnalysis.mergeWithGrind]
def Mathlib.TacticAnalysis.mergeWithGrind : TacticAnalysis.Config where
run seq := do
if let #[preI, postI] := seq[seq.size - 2:].toArray then
if postI.tacI.stx.getKind == ``Lean.Parser.Tactic.grind &&
preI.tacI.stx.getKind ∉ mergeWithGrindAllowed then
if let [goal] := preI.tacI.goalsBefore then
let goals ← try
preI.runTacticCode goal postI.tacI.stx
catch _e =>
pure [goal]
if goals.isEmpty then
logWarningAt preI.tacI.stx m!"'{preI.tacI.stx}; grind' can be replaced with 'grind'"
/-- Suggest replacing a sequence of tactics with `grind` if that also solves the goal. -/
register_option linter.tacticAnalysis.terminalToGrind : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.terminalToGrind,
inherit_doc linter.tacticAnalysis.terminalToGrind]
def Mathlib.TacticAnalysis.terminalToGrind : TacticAnalysis.Config where
run seq := do
let threshold := 3
-- `replaced` will hold the terminal tactic sequence that can be replaced with `grind`.
-- We prepend each tactic in turn, starting with the last.
let mut replaced : List (TSyntax `tactic) := []
let mut success := false
let mut oldHeartbeats := 0
let mut newHeartbeats := 0
-- We iterate through the tactic sequence in reverse, checking at each tactic if the goal is
-- already solved by `grind` and if so pushing that tactic onto `replaced`.
-- By repeating this until `grind` fails for the first time, we get a terminal sequence
-- of replaceable tactics.
for i in seq.reverse do
if replaced.length >= threshold - 1 && i.tacI.stx.getKind != ``Lean.Parser.Tactic.grind then
if let [goal] := i.tacI.goalsBefore then
-- Count the heartbeats of the original tactic sequence, verifying that this indeed
-- closes the goal like it does in userspace.
let suffix := ⟨i.tacI.stx⟩ :: replaced
let seq ← `(tactic| $suffix.toArray;*)
let (oldGoals, heartbeats) ← withHeartbeats <|
try
i.runTacticCode goal seq
catch _e =>
pure [goal]
if !oldGoals.isEmpty then
logWarningAt i.tacI.stx m!"Original tactics failed to solve the goal: {seq}"
oldHeartbeats := heartbeats
-- To check if `grind` can close the goal, run `grind` on the current goal
-- and verify that no goals remain afterwards.
let tac ← `(tactic| grind)
let (newGoals, heartbeats) ← withHeartbeats <|
try
i.runTacticCode goal tac
catch _e =>
pure [goal]
newHeartbeats := heartbeats
if newGoals.isEmpty then
success := true
else
break
else
break
replaced := ⟨i.tacI.stx⟩ :: replaced
if h : replaced.length >= threshold ∧ success then
let stx := replaced[0]
let seq ← `(tactic| $replaced.toArray;*)
logWarningAt stx m!"replace the proof with 'grind': {seq}"
if oldHeartbeats * 2 < newHeartbeats then
logWarningAt stx m!"'grind' is slower than the original: {oldHeartbeats} -> {newHeartbeats}"
open Elab.Command
/--
When running the "tryAtEachStep" tactic analysis linters,
only run on a fraction `1/n` of the goals found in the library.
This is useful for running quick benchmarks.
-/
register_option linter.tacticAnalysis.tryAtEachStep.fraction : Nat := {
defValue := 1
}
/-- Run a tactic at each proof step. -/
def Mathlib.TacticAnalysis.tryAtEachStep (tac : Syntax → MVarId → CommandElabM (TSyntax `tactic)) : TacticAnalysis.Config where
run seq := do
let fraction := linter.tacticAnalysis.tryAtEachStep.fraction.get (← getOptions)
for i in seq do
if let [goal] := i.tacI.goalsBefore then
if (hash goal) % fraction = 0 then
let tac ← tac i.tacI.stx goal
let goalsAfter ← try
i.runTacticCode goal tac
catch _e =>
pure [goal]
if goalsAfter.isEmpty then
logInfoAt i.tacI.stx m!"`{i.tacI.stx}` can be replaced with `{tac}`"
/-- Run `grind` at every step in proofs, reporting where it succeeds. -/
register_option linter.tacticAnalysis.tryAtEachStepGrind : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.tryAtEachStepGrind,
inherit_doc linter.tacticAnalysis.tryAtEachStepGrind]
def tryAtEachStepGrind := tryAtEachStep fun _ _ => `(tactic| grind)
/-- Run `simp_all` at every step in proofs, reporting where it succeeds. -/
register_option linter.tacticAnalysis.tryAtEachStepSimpAll : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.tryAtEachStepSimpAll,
inherit_doc linter.tacticAnalysis.tryAtEachStepSimpAll]
def tryAtEachStepSimpAll := tryAtEachStep fun _ _ => `(tactic| simp_all)
/-- Run `aesop` at every step in proofs, reporting where it succeeds. -/
register_option linter.tacticAnalysis.tryAtEachStepAesop : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.tryAtEachStepAesop,
inherit_doc linter.tacticAnalysis.tryAtEachStepAesop]
def tryAtEachStepAesop := tryAtEachStep
-- As `aesop` isn't imported here, we construct the tactic syntax manually.
fun _ _ => return ⟨TSyntax.raw <|
mkNode `Aesop.Frontend.Parser.aesopTactic #[mkAtom "aesop", mkNullNode]⟩
/-- Run `grind +premises` at every step in proofs, reporting where it succeeds. -/
register_option linter.tacticAnalysis.tryAtEachStepGrindPremises : Bool := {
defValue := false
}
@[tacticAnalysis linter.tacticAnalysis.tryAtEachStepGrindPremises,
inherit_doc linter.tacticAnalysis.tryAtEachStepGrindPremises]
def tryAtEachStepGrindPremises := tryAtEachStep fun _ _ => `(tactic| grind +premises)
-- TODO: add compatibility with `rintro` and `intros`
/-- Suggest merging two adjacent `intro` tactics which don't pattern match. -/
register_option linter.tacticAnalysis.introMerge : Bool := {
defValue := true
}
@[tacticAnalysis linter.tacticAnalysis.introMerge, inherit_doc linter.tacticAnalysis.introMerge]
def Mathlib.TacticAnalysis.introMerge : TacticAnalysis.Config := .ofComplex {
out := Option (TSyntax `tactic)
ctx := Array (Array Term)
trigger ctx stx :=
match stx with
| `(tactic| intro%$x $args*) => .continue ((ctx.getD #[]).push
-- if `intro` is used without arguments, treat it as `intro _`
<| if args.size = 0 then #[⟨mkHole x⟩] else args)
| _ => if let some args := ctx then if args.size > 1 then .accept args else .skip else .skip
test ctxI i ctx goal := do
let ctxT := ctx.flatten
let tac ← `(tactic| intro $ctxT*)
try
let _ ← ctxI.runTacticCode i goal tac
return some tac
catch _e => -- if for whatever reason we can't run `intro` here.
return none
tell _stx _old _oldHeartbeats new _newHeartbeats := pure <|
if let some tac := new then m!"Try this: {tac}" else none} |
.lake/packages/mathlib/Mathlib/Tactic/Push/Attr.lean | import Mathlib.Lean.Expr.Basic
/-!
# The `@[push]` attribute for the `push`, `push_neg` and `pull` tactics
This file defines the `@[push]` attribute, so that it can be used without importing
the tactic itself.
-/
namespace Mathlib.Tactic.Push
open Lean Meta
/-- The type for a constant to be pushed by `push`. -/
inductive Head where
| const (c : Name)
| lambda
| forall
deriving Inhabited, BEq
/-- Converts a `Head` to a string. -/
def Head.toString : Head → String
| .const c => c.toString
| .lambda => "fun"
| .forall => "Forall"
instance : ToString Head := ⟨Head.toString⟩
/-- Returns the head of an expression. -/
def Head.ofExpr? : Expr → Option Head
| .app f _ => f.getAppFn.constName?.map .const
| .lam .. => some .lambda
| .forallE .. => some .forall
| _ => none
/-- The `push` environment extension -/
initialize pushExt : SimpleScopedEnvExtension SimpTheorem (DiscrTree SimpTheorem) ←
registerSimpleScopedEnvExtension {
initial := {}
addEntry := fun d e => d.insertCore e.keys e
}
/--
Checks if the theorem is suitable for the `pull` tactic. That is,
check if it is of the form `x = f ...` where `x` contains the head `f`,
but `f` is not the head of `x`.
-/
def isPullThm (declName : Name) (inv : Bool) : MetaM (Option Head) := do
let cinfo ← getConstInfo declName
forallTelescope cinfo.type fun _ type => do
let some (lhs, rhs) := type.eqOrIff? | return none
let (lhs, rhs) := if inv then (rhs, lhs) else (lhs, rhs)
let some head := Head.ofExpr? rhs | return none
if Head.ofExpr? lhs != some head && containsHead lhs head then
return head
return none
where
/-- Checks if the expression has the head in any subexpression.
We don't need to check this for `.lambda`, because the term being a function
is sufficient for `pull fun _ ↦ _` to be applicable. -/
containsHead (e : Expr) : Head → Bool
| .const c => e.containsConst (· == c)
| .lambda => true
| .forall => (e.find? (· matches .forallE ..)).isSome
/-- A theorem for the `pull` tactic -/
abbrev PullTheorem := SimpTheorem × Head
/-- The `pull` environment extension -/
initialize pullExt : SimpleScopedEnvExtension PullTheorem (DiscrTree PullTheorem) ←
registerSimpleScopedEnvExtension {
initial := {}
addEntry := fun d e => d.insertCore e.1.keys e
}
/--
The `push` attribute is used to tag lemmas that "push" a constant into an expression.
For example:
```lean
@[push] theorem log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y
@[push] theorem log_abs : log |x| = log x
@[push] theorem not_imp (p q : Prop) : ¬(p → q) ↔ p ∧ ¬q
@[push] theorem not_iff (p q : Prop) : ¬(p ↔ q) ↔ (p ∧ ¬q) ∨ (¬p ∧ q)
@[push] theorem not_not (p : Prop) : ¬ ¬p ↔ p
@[push] theorem not_le : ¬a ≤ b ↔ b < a
```
Note that some `push` lemmas don't push the constant away from the head (`log_abs`) and
some `push` lemmas cancel the constant out (`not_not` and `not_le`).
For the other lemmas that are "genuine" `push` lemmas, a `pull` attribute is automatically added
in the reverse direction. To not add a `pull` tag, use `@[push only]`.
To tag the reverse direction of the lemma, use `@[push ←]`.
-/
syntax (name := pushAttr) "push" (" ←" <|> " <-")? (&" only")? (ppSpace prio)? : attr
@[inherit_doc pushAttr]
initialize registerBuiltinAttribute {
name := `pushAttr
descr := "attribute for push"
add := fun declName stx kind => MetaM.run' do
let inv := !stx[1].isNone
let isOnly := !stx[2].isNone
let prio ← getAttrParamOptPrio stx[3]
let #[thm] ← mkSimpTheoremFromConst declName (inv := inv) (prio := prio) |
throwError "couldn't generate a simp theorem for `push`"
pushExt.add thm
unless isOnly do
let inv := !inv -- the `pull` lemma is added in the reverse direction
if let some head ← isPullThm declName inv then
let #[thm] ← mkSimpTheoremFromConst declName (inv := inv) (prio := prio) |
throwError "couldn't generate a simp theorem for `pull`"
pullExt.add (thm, head)
}
end Mathlib.Tactic.Push |
.lake/packages/mathlib/Mathlib/Tactic/GRewrite/Core.lean | import Mathlib.Tactic.GCongr.Core
/-!
# The generalized rewriting tactic
This module defines the core of the `grw`/`grewrite` tactic.
TODO:
The algorithm used to implement `grw` uses the same method as `rw` to determine where to rewrite.
This means that we can get ill-typed results. Moreover, it doesn't detect which occurrences
can be rewritten by `gcongr` and which can't. It also means we cannot rewrite bound variables.
A better algorithm would be similar to `simp only`, where we recursively enter the subexpression
using `gcongr` lemmas. This is tricky due to the many different `gcongr` for each pattern.
With the current implementation, we can instead use `nth_grw`.
-/
open Lean Meta
namespace Mathlib.Tactic
/-- Given a proof of `a ~ b`, close a goal of the form `a ~' b` or `b ~' a`
for some possibly different relation `~'`. -/
def GRewrite.dischargeMain (hrel : Expr) (goal : MVarId) : MetaM Bool := do
if ← goal.gcongrForward #[hrel] then
return true
else
throwTacticEx `grewrite goal m!"could not discharge {← goal.getType} using {← inferType hrel}"
/-- The result returned by `Lean.MVarId.grewrite`. -/
structure GRewriteResult where
/-- The rewritten expression -/
eNew : Expr
/-- The proof of the implication. The direction depends on the argument `forwardImp`. -/
impProof : Expr
/-- The new side goals -/
mvarIds : List MVarId -- new goals
/-- Configures the behavior of the `rewrite` and `rw` tactics. -/
structure GRewrite.Config extends Rewrite.Config where
/-- When `useRewrite = true`, switch to using the default `rewrite` tactic when the goal is
and equality or iff. -/
useRewrite : Bool := true
/-- When `implicationHyp = true`, interpret the rewrite rule as an implication. -/
implicationHyp : Bool := false
/--
Rewrite `e` using the relation `hrel : x ~ y`, and construct an implication proof
using the `gcongr` tactic to discharge this goal.
if `forwardImp = true`, we prove that `e → eNew`; otherwise `eNew → e`.
If `symm = false`, we rewrite `e` to `eNew := e[x/y]`; otherwise `eNew := e[y/x]`.
The code aligns with `Lean.MVarId.rewrite` as much as possible.
-/
def _root_.Lean.MVarId.grewrite (goal : MVarId) (e : Expr) (hrel : Expr)
(forwardImp symm : Bool) (config : GRewrite.Config) : MetaM GRewriteResult :=
goal.withContext do
goal.checkNotAssigned `grewrite
let hrelType ← instantiateMVars (← inferType hrel)
let maxMVars? ←
if config.implicationHyp then
if let arity + 1 := hrelType.getForallArity then
pure (some arity)
else
throwTacticEx `apply_rw goal m!"invalid implication {hrelType}"
else
pure none
let (newMVars, binderInfos, hrelType) ←
withReducible <| forallMetaTelescopeReducing hrelType maxMVars?
/- We don't reduce `hrelType` because if it is `a > b`, turning it into `b < a` would
reverse the direction of the rewrite. However, we do need to clear metadata annotations. -/
let hrelType := hrelType.cleanupAnnotations
-- If we can use the normal `rewrite` tactic, we default to using that.
if (hrelType.isAppOfArity ``Iff 2 || hrelType.isAppOfArity ``Eq 3) && config.useRewrite then
let { eNew, eqProof, mvarIds } ← goal.rewrite e hrel symm config.toConfig
let mp := if forwardImp then ``Eq.mp else ``Eq.mpr
let impProof ← mkAppOptM mp #[e, eNew, eqProof]
return { eNew, impProof, mvarIds }
let hrelIn := hrel
-- check that `hrel` proves a relation
let hrel := mkAppN hrel newMVars
let some (_, lhs, rhs) := GCongr.getRel hrelType |
throwTacticEx `grewrite goal m!"{hrelType} is not a relation"
let (lhs, rhs) := if symm then (rhs, lhs) else (lhs, rhs)
if lhs.getAppFn.isMVar then
throwTacticEx `grewrite goal
m!"pattern is a metavariable{indentExpr lhs}\nfrom relation{indentExpr hrelType}"
-- abstract the occurrences of `lhs` from `e` to get `eAbst`
let e ← instantiateMVars e
let eAbst ←
withConfig (fun oldConfig => { config, oldConfig with }) <| kabstract e lhs config.occs
unless eAbst.hasLooseBVars do
throwTacticEx `grewrite goal
m!"did not find instance of the pattern in the target expression{indentExpr lhs}"
-- construct `eNew` by instantiating `eAbst` with `rhs`.
let eNew := eAbst.instantiate1 rhs
let eNew ← instantiateMVars eNew
-- check that `eNew` is well typed
try
check eNew
catch ex =>
throwTacticEx `grewrite goal m!"\
rewritten expression is not type correct:{indentD eNew}\nError: {ex.toMessageData}\
\n\n\
Possible solutions: use grewrite's 'occs' configuration option to limit which occurrences \
are rewritten, or specify what the rewritten expression should be and use 'gcongr'."
let eNew ← if rhs.hasBinderNameHint then eNew.resolveBinderNameHint else pure eNew
-- construct the implication proof using `gcongr`
let mkImp (e₁ e₂ : Expr) : Expr := .forallE `_a e₁ e₂ .default
let eNew' := eAbst.instantiate1 (GCongr.mkHoleAnnotation rhs)
let imp := if forwardImp then mkImp e eNew' else mkImp eNew' e
let gcongrGoal ← mkFreshExprMVar imp
let (_, _, sideGoals) ← gcongrGoal.mvarId!.gcongr (!forwardImp) []
(mainGoalDischarger := GRewrite.dischargeMain hrel)
-- post-process the metavariables
postprocessAppMVars `grewrite goal newMVars binderInfos
(synthAssignedInstances := !tactic.skipAssignedInstances.get (← getOptions))
let newMVarIds ← (sideGoals ++ newMVars.map Expr.mvarId!).filterM (not <$> ·.isAssigned)
let otherMVarIds ← getMVarsNoDelayed hrelIn
let otherMVarIds := otherMVarIds.filter (!newMVarIds.contains ·)
let newMVarIds := newMVarIds ++ otherMVarIds
pure { eNew, impProof := ← instantiateMVars gcongrGoal, mvarIds := newMVarIds.toList }
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/GRewrite/Elab.lean | import Mathlib.Tactic.GRewrite.Core
/-!
# The generalized rewriting tactic
This file defines the tactics that use the backend defined in `Mathlib.Tactic.GRewrite.Core`:
- `grewrite`
- `grw`
- `apply_rw`
- `nth_grewrite`
- `nth_grw`
-/
namespace Mathlib.Tactic
open Lean Meta Elab Parser Tactic
/-- Apply the `grewrite` tactic to the current goal. -/
def grewriteTarget (stx : Syntax) (symm : Bool) (config : GRewrite.Config) : TacticM Unit := do
let goal ← getMainGoal
Term.withSynthesize <| goal.withContext do
let e ← elabTerm stx none true
if e.hasSyntheticSorry then
throwAbortTactic
let goal ← getMainGoal
let target ← goal.getType
let r ← goal.grewrite target e (forwardImp := false) (symm := symm) (config := config)
let mvarNew ← mkFreshExprSyntheticOpaqueMVar r.eNew (← goal.getTag)
goal.assign (mkApp r.impProof mvarNew)
replaceMainGoal (mvarNew.mvarId! :: r.mvarIds)
/-- Apply the `grewrite` tactic to a local hypothesis. -/
def grewriteLocalDecl (stx : Syntax) (symm : Bool) (fvarId : FVarId) (config : GRewrite.Config) :
TacticM Unit := withMainContext do
-- Note: we cannot execute `replace` inside `Term.withSynthesize`.
-- See issues https://github.com/leanprover-community/mathlib4/issues/2711 and https://github.com/leanprover-community/mathlib4/issues/2727.
let goal ← getMainGoal
let r ← Term.withSynthesize <| withMainContext do
let e ← elabTerm stx none true
if e.hasSyntheticSorry then
throwAbortTactic
let localDecl ← fvarId.getDecl
goal.grewrite localDecl.type e (forwardImp := true) (symm := symm) (config := config)
let proof := .app (r.impProof) (.fvar fvarId)
let { mvarId, .. } ← goal.replace fvarId proof r.eNew
replaceMainGoal (mvarId :: r.mvarIds)
/-- Function elaborating `GRewrite.Config`. -/
declare_config_elab elabGRewriteConfig GRewrite.Config
/--
`grewrite [e]` is like `grw [e]`, but it doesn't try to close the goal with `rfl`.
This is analogous to `rw` and `rewrite`, where `rewrite` doesn't try to close the goal with `rfl`.
-/
syntax (name := grewriteSeq) "grewrite" optConfig rwRuleSeq (location)? : tactic
@[tactic grewriteSeq, inherit_doc grewriteSeq] def evalGRewriteSeq : Tactic := fun stx => do
let cfg ← elabGRewriteConfig stx[1]
let loc := expandOptLocation stx[3]
withRWRulesSeq stx[0] stx[2] fun symm term => do
withLocation loc
(grewriteLocalDecl term symm · cfg)
(grewriteTarget term symm cfg)
(throwTacticEx `grewrite · "did not find instance of the pattern in the current goal")
/--
`grw [e]` works just like `rw [e]`, but `e` can be a relation other than `=` or `↔`.
For example,
```lean
variable {a b c d n : ℤ}
example (h₁ : a < b) (h₂ : b ≤ c) : a + d ≤ c + d := by
grw [h₁, h₂]
example (h : a ≡ b [ZMOD n]) : a ^ 2 ≡ b ^ 2 [ZMOD n] := by
grw [h]
example (h₁ : a ∣ b) (h₂ : b ∣ a ^ 2 * c) : a ∣ b ^ 2 * c := by
grw [h₁] at *
exact h₂
```
To rewrite only in the `n`-th position, use `nth_grw n`.
This is useful when `grw` tries to rewrite in a position that is not valid for the given relation.
To be able to use `grw`, the relevant lemmas need to be tagged with `@[gcongr]`.
To rewrite inside a transitive relation, you can also give it an `IsTrans` instance.
-/
macro (name := grwSeq) "grw " c:optConfig s:rwRuleSeq l:(location)? : tactic =>
match s with
| `(rwRuleSeq| [$rs,*]%$rbrak) =>
-- We show the `rfl` state on `]`
`(tactic| (grewrite $c [$rs,*] $(l)?; with_annotate_state $rbrak (try (with_reducible rfl))))
| _ => Macro.throwUnsupported
/-- `apply_rewrite [rules]` is a shorthand for `grewrite +implicationHyp [rules]`. -/
macro "apply_rewrite" c:optConfig s:rwRuleSeq loc:(location)? : tactic => do
`(tactic| grewrite $[$(getConfigItems c)]* +implicationHyp $s:rwRuleSeq $(loc)?)
/-- `apply_rw [rules]` is a shorthand for `grw +implicationHyp [rules]`. -/
macro (name := applyRwSeq) "apply_rw " c:optConfig s:rwRuleSeq loc:(location)? : tactic => do
`(tactic| grw $[$(getConfigItems c)]* +implicationHyp $s:rwRuleSeq $(loc)?)
/-- `nth_grewrite` is just like `nth_rewrite`, but for `grewrite`. -/
macro "nth_grewrite" c:optConfig ppSpace nums:(num)+ s:rwRuleSeq loc:(location)? : tactic => do
`(tactic| grewrite $[$(getConfigItems c)]* (occs := .pos [$[$nums],*]) $s:rwRuleSeq $(loc)?)
/-- `nth_grw` is just like `nth_rw`, but for `grw`. -/
macro "nth_grw" c:optConfig ppSpace nums:(num)+ s:rwRuleSeq loc:(location)? : tactic => do
`(tactic| grw $[$(getConfigItems c)]* (occs := .pos [$[$nums],*]) $s:rwRuleSeq $(loc)?)
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/Attr/Register.lean | import Mathlib.Init
import Lean.Meta.Tactic.Simp.SimpTheorems
import Lean.Meta.Tactic.Simp.RegisterCommand
import Lean.LabelAttribute
/-!
# Attributes used in `Mathlib`
In this file we define all `simp`-like and `label`-like attributes used in `Mathlib`. We declare all
of them in one file for two reasons:
- in Lean 4, one cannot use an attribute in the same file where it was declared;
- this way it is easy to see which simp sets contain a given lemma.
-/
/-- Simp set for `functor_norm` -/
register_simp_attr functor_norm
-- Porting note:
-- in mathlib3 we declared `monad_norm` using:
-- mk_simp_attribute monad_norm none with functor_norm
-- This syntax is not supported by mathlib4's `register_simp_attr`.
-- See https://github.com/leanprover-community/mathlib4/issues/802
-- TODO: add `@[monad_norm]` to all `@[functor_norm] lemmas
/-- Simp set for `functor_norm` -/
register_simp_attr monad_norm
/-- Simp attribute for lemmas about `Even` -/
register_simp_attr parity_simps
/-- "Simp attribute for lemmas about `RCLike`" -/
register_simp_attr rclike_simps
/-- The simpset `rify_simps` is used by the tactic `rify` to move expressions from `ℕ`, `ℤ`, or
`ℚ` to `ℝ`. -/
register_simp_attr rify_simps
/-- The simpset `qify_simps` is used by the tactic `qify` to move expressions from `ℕ` or `ℤ` to `ℚ`
which gives a well-behaved division. -/
register_simp_attr qify_simps
/-- The simpset `zify_simps` is used by the tactic `zify` to move expressions from `ℕ` to `ℤ`
which gives a well-behaved subtraction. -/
register_simp_attr zify_simps
/--
The simpset `mfld_simps` records several simp lemmas that are
especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it
possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining
readability.
The typical use case is the following, in a file on manifolds:
If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar, mfld_simps]` and paste
its output. The list of lemmas should be reasonable (contrary to the output of
`squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick
enough.
-/
register_simp_attr mfld_simps
/-- Simp set for integral rules. -/
register_simp_attr integral_simps
/-- simp set for the manipulation of typevec and arrow expressions -/
register_simp_attr typevec
/-- Simplification rules for ghost equations. -/
register_simp_attr ghost_simps
/-- The `@[nontriviality]` simp set is used by the `nontriviality` tactic to automatically
discharge theorems about the trivial case (where we know `Subsingleton α` and many theorems
in e.g. groups are trivially true). -/
register_simp_attr nontriviality
/-- A stub attribute for `is_poly`. -/
register_label_attr is_poly
/-- A simp set for the `fin_omega` wrapper around `omega`. -/
register_simp_attr fin_omega
/-- A simp set for simplifying expressions involving `⊤` in `enat_to_nat`. -/
register_simp_attr enat_to_nat_top
/-- A simp set for pushing coercions from `ℕ` to `ℕ∞` in `enat_to_nat`. -/
register_simp_attr enat_to_nat_coe
/-- A simp set for the `pnat_to_nat` tactic. -/
register_simp_attr pnat_to_nat_coe
/-- `mon_tauto` is a simp set to prove tautologies about morphisms from some (tensor) power of `M`
to `M`, where `M` is a (commutative) monoid object in a (braided) monoidal category.
**This `simp` set is incompatible with the standard simp set.**
If you want to use it, make sure to add the following to your simp call to disable the problematic
default simp lemmas:
```
-MonoidalCategory.whiskerLeft_id, -MonoidalCategory.id_whiskerRight,
-MonoidalCategory.tensor_comp, -MonoidalCategory.tensor_comp_assoc,
-MonObj.mul_assoc, -MonObj.mul_assoc_assoc
```
The general algorithm it follows is to push the associators `α_` and commutators `β_` inwards until
they cancel against the right sequence of multiplications.
This approach is justified by the fact that a tautology in the language of (commutative) monoid
objects "remembers" how it was proved: Every use of a (commutative) monoid object axiom inserts a
unitor, associator or commutator, and proving a tautology simply amounts to undoing those moves as
prescribed by the presence of unitors, associators and commutators in its expression.
This simp set is opiniated about its normal form, which is why it cannot be used concurrently with
some of the simp lemmas in the standard simp set:
* It eliminates all mentions of whiskers by rewriting them to tensored homs,
which goes against `whiskerLeft_id` and `id_whiskerRight`:
`X ◁ f = 𝟙 X ⊗ₘ f`, `f ▷ X = 𝟙 X ⊗ₘ f`.
This goes against `whiskerLeft_id` and `id_whiskerRight` in the standard simp set.
* It collapses compositions of tensored homs to the tensored hom of the compositions,
which goes against `tensor_comp`:
`(f₁ ⊗ₘ g₁) ≫ (f₂ ⊗ₘ g₂) = (f₁ ≫ f₂) ⊗ₘ (g₁ ≫ g₂)`. TODO: Isn't this direction Just Better?
* It cancels the associators against multiplications,
which goes against `mul_assoc`:
`(α_ M M M).hom ≫ (𝟙 M ⊗ₘ μ) ≫ μ = (μ ⊗ₘ 𝟙 M) ≫ μ`,
`(α_ M M M).inv ≫ (μ ⊗ₘ 𝟙 M) ≫ μ = (𝟙 M ⊗ₘ μ) ≫ μ`
* It unfolds non-primitive coherence isomorphisms, like the tensor strengths `tensorμ`, `tensorδ`.
-/
register_simp_attr mon_tauto |
.lake/packages/mathlib/Mathlib/Tactic/Attr/Core.lean | import Mathlib.Tactic.Attr.Register
/-!
# Simp tags for core lemmas
In Lean 4, an attribute declared with `register_simp_attr` cannot be used in the same file. So, we
declare all `simp` attributes used in `Mathlib` in `Mathlib/Tactic/Attr/Register` and tag lemmas
from the core library and the `Batteries` library with these attributes in this file.
-/
attribute [simp] id_map'
attribute [functor_norm, monad_norm] seq_assoc pure_seq pure_bind bind_assoc bind_pure map_pure
attribute [monad_norm] seq_eq_bind_map
attribute [mfld_simps] id and_true true_and Function.comp_apply and_self eq_self not_false
true_or or_true heq_eq_eq forall_const and_imp
attribute [nontriviality] eq_iff_true_of_subsingleton |
.lake/packages/mathlib/Mathlib/Tactic/Finiteness/Attr.lean | import Aesop
import Mathlib.Init
/-! # Finiteness tactic attribute -/
declare_aesop_rule_sets [finiteness] |
.lake/packages/mathlib/Mathlib/Tactic/GCongr/Core.lean | import Lean
import Batteries.Lean.Except
import Batteries.Tactic.Exact
import Mathlib.Tactic.GCongr.ForwardAttr
import Mathlib.Order.Defs.Unbundled
/-!
# The `gcongr` ("generalized congruence") tactic
The `gcongr` tactic applies "generalized congruence" rules, reducing a relational goal
between a LHS and RHS matching the same pattern to relational subgoals between the differing
inputs to the pattern. For example,
```
example {a b x c d : ℝ} (h1 : a + 1 ≤ b + 1) (h2 : c + 2 ≤ d + 2) :
x ^ 2 * a + c ≤ x ^ 2 * b + d := by
gcongr
· linarith
· linarith
```
This example has the goal of proving the relation `≤` between a LHS and RHS both of the pattern
```
x ^ 2 * ?_ + ?_
```
(with inputs `a`, `c` on the left and `b`, `d` on the right); after the use of
`gcongr`, we have the simpler goals `a ≤ b` and `c ≤ d`.
A depth limit, or a pattern can be provided explicitly;
this is useful if a non-maximal match is desired:
```
example {a b c d x : ℝ} (h : a + c + 1 ≤ b + d + 1) :
x ^ 2 * (a + c) + 5 ≤ x ^ 2 * (b + d) + 5 := by
gcongr x ^ 2 * ?_ + 5 -- or `gcongr 2`
linarith
```
## Sourcing the generalized congruence lemmas
Relevant "generalized congruence" lemmas are declared using the attribute `@[gcongr]`. For
example, the first example constructs the proof term
```
add_le_add (mul_le_mul_of_nonneg_left _ (pow_bit0_nonneg x 1)) _
```
using the generalized congruence lemmas `add_le_add` and `mul_le_mul_of_nonneg_left`. The term
`pow_bit0_nonneg x 1` is automatically generated by a discharger (see below).
When a lemma is tagged `@[gcongr]`, it is verified that the lemma is of "generalized congruence"
form, `f x₁ y z₁ ∼ f x₂ y z₂`, that is, a relation between the application of a function to two
argument lists, in which the "varying argument" pairs (here `x₁`/`x₂` and `z₁`/`z₂`) are all free
variables. The `gcongr` tactic will try a lemma only if it matches the goal in relation `∼`,
head function `f` and the arity of `f`. It prioritizes lemmas with fewer "varying arguments". Thus,
for example, all three of the following lemmas are tagged `@[gcongr]` and are used in different
situations according to whether the goal compares constant-left-multiplications,
constant-right-multiplications, or fully varying multiplications:
```
theorem mul_le_mul_of_nonneg_left [Mul α] [Zero α] [Preorder α] [PosMulMono α]
{a b c : α} (h : b ≤ c) (a0 : 0 ≤ a) :
a * b ≤ a * c
theorem mul_le_mul_of_nonneg_right [Mul α] [Zero α] [Preorder α] [MulPosMono α]
{a b c : α} (h : b ≤ c) (a0 : 0 ≤ a) :
b * a ≤ c * a
theorem mul_le_mul [MulZeroClass α] [Preorder α] [PosMulMono α] [MulPosMono α]
{a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) (c0 : 0 ≤ c) (b0 : 0 ≤ b) :
a * c ≤ b * d
```
The advantage of this approach is that the lemmas with fewer "varying" input pairs typically require
fewer side conditions, so the tactic becomes more useful by special-casing them.
There can also be more than one generalized congruence lemma dealing with the same relation
and head function, for example with purely notational head
functions which have different theories when different typeclass assumptions apply. For example,
the following lemma is stored with the same `@[gcongr]` data as `mul_le_mul` above, and the two
lemmas are simply tried in succession to determine which has the typeclasses relevant to the goal:
```
theorem mul_le_mul' [Mul α] [Preorder α] [MulLeftMono α]
[MulRightMono α] {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
a * c ≤ b * d
```
## Resolving goals
The tactic attempts to discharge side goals to the "generalized congruence" lemmas (such as the
side goal `0 ≤ x ^ 2` in the above application of `mul_le_mul_of_nonneg_left`) using the tactic
`gcongr_discharger`, which wraps `positivity` but can also be extended. Side goals not discharged
in this way are left for the user.
The tactic also attempts to discharge "main" goals using the available hypotheses, as well as a
limited amount of forward reasoning. Such attempts are made *before* descending further into
matching by congruence. The built-in forward-reasoning includes reasoning by symmetry and
reflexivity, and this can be extended by writing tactic extensions tagged with the
`@[gcongr_forward]` attribute.
## Introducing variables and hypotheses
Some natural generalized congruence lemmas have "main" hypotheses which are universally quantified
or have the structure of an implication, for example
```
theorem GCongr.Finset.sum_le_sum [OrderedAddCommMonoid N] {f g : ι → N} {s : Finset ι}
(h : ∀ (i : ι), i ∈ s → f i ≤ g i) :
s.sum f ≤ s.sum g
```
The tactic automatically introduces the variable `i✝ : ι` and hypothesis `hi✝ : i✝ ∈ s` in the
subgoal `∀ (i : ι), i ∈ s → f i ≤ g i` generated by applying this lemma. By default this is done
anonymously, so they are inaccessible in the goal state which results. The user can name them if
needed using the syntax `gcongr with i hi`.
## Variants
The tactic `rel` is a variant of `gcongr`, intended for teaching. Local hypotheses are not
used automatically to resolve main goals, but must be invoked by name:
```
example {a b x c d : ℝ} (h1 : a ≤ b) (h2 : c ≤ d) :
x ^ 2 * a + c ≤ x ^ 2 * b + d := by
rel [h1, h2]
```
The `rel` tactic is finishing-only: it fails if any main or side goals are not resolved.
## Implementation notes
### Patterns
When you provide a pattern, such as in `gcongr x ^ 2 * ?_ + 5`, this is elaborated with a metadata
annotation at each `?_` hole. This is then unified with the LHS of the relation in the goal.
As a result, the pattern becomes the same as the LHS, but with mdata annotations that
indicate where the original `?_` holes were. The LHS is then replaced with this expression so that
`gcongr` can tell based on the LHS how far to continue recursively. We also keep track of when
then LHS and RHS swap around, so that we know where to look for the metadata annotation.
-/
namespace Mathlib.Tactic.GCongr
open Lean Meta
/-- `GCongrKey` is the key used in the hashmap for looking up `gcongr` lemmas. -/
structure GCongrKey where
/-- The name of the relation. For example, `a + b ≤ a + c` has ``relName := `LE.le``. -/
relName : Name
/-- The name of the head function. For example, `a + b ≤ a + c` has ``head := `HAdd.hAdd``. -/
head : Name
/-- The number of arguments that `head` is applied to.
For example, `a + b ≤ a + c` has `arity := 6`, because `HAdd.hAdd` has 6 arguments. -/
arity : Nat
deriving Inhabited, BEq, Hashable
/-- Structure recording the data for a "generalized congruence" (`gcongr`) lemma. -/
structure GCongrLemma where
/-- The key under which the lemma is stored. -/
key : GCongrKey
/-- The name of the lemma. -/
declName : Name
/-- `mainSubgoals` are the subgoals on which `gcongr` will be recursively called. They store
- the index of the hypothesis
- the number of parameters in the hypothesis
- whether it is contravariant (i.e. switches the order of the two arguments) -/
mainSubgoals : Array (Nat × Nat × Bool)
/-- The number of arguments that `declName` takes when applying it. -/
numHyps : Nat
/-- The given priority of the lemma, for example as `@[gcongr high]`. -/
prio : Nat
/-- The number of arguments in the application of `head` that are different.
This is used for sorting the lemmas.
For example, `a + b ≤ a + c` has `numVarying := 1`. -/
numVarying : Nat
deriving Inhabited
/-- A collection of `GCongrLemma`, to be stored in the environment extension. -/
abbrev GCongrLemmas := Std.HashMap GCongrKey (List GCongrLemma)
/-- Return `true` if the priority of `a` is less than or equal to the priority of `b`. -/
def GCongrLemma.prioLE (a b : GCongrLemma) : Bool :=
(compare a.prio b.prio).then (compare b.numVarying a.numVarying) |>.isLE
/-- Insert a `GCongrLemma` in a collection of lemmas, making sure that the lemmas are sorted. -/
def addGCongrLemmaEntry (m : GCongrLemmas) (l : GCongrLemma) : GCongrLemmas :=
match m[l.key]? with
| none => m.insert l.key [l]
| some es => m.insert l.key <| insert l es
where
/--- Insert a `GCongrLemma` in the correct place in a list of lemmas. -/
insert (l : GCongrLemma) : List GCongrLemma → List GCongrLemma
| [] => [l]
| l'::ls => if l'.prioLE l then l::l'::ls else l' :: insert l ls
/-- Environment extension for "generalized congruence" (`gcongr`) lemmas. -/
initialize gcongrExt : SimpleScopedEnvExtension GCongrLemma
(Std.HashMap GCongrKey (List GCongrLemma)) ←
registerSimpleScopedEnvExtension {
addEntry := addGCongrLemmaEntry
initial := {}
}
/-- Given an application `f a₁ .. aₙ`, return the name of `f`, and the array of arguments `aᵢ`. -/
def getCongrAppFnArgs (e : Expr) : Option (Name × Array Expr) :=
match e.cleanupAnnotations with
| .forallE n d b bi =>
-- We determine here whether an arrow is an implication or a forall
-- this approach only works if LHS and RHS are both dependent or both non-dependent
if b.hasLooseBVars then
some (`_Forall, #[.lam n d b bi])
else
some (`_Implies, #[d, b])
| e => e.withApp fun f args => f.constName?.map (·, args)
/-- If `e` is of the form `r a b`, return `(r, a, b)`.
Note: we assume that `e` does not have an `Expr.mdata` annotation. -/
def getRel (e : Expr) : Option (Name × Expr × Expr) :=
match e with
| .app (.app rel lhs) rhs => rel.getAppFn.constName?.map (·, lhs, rhs)
| .forallE _ lhs rhs _ =>
if !rhs.hasLooseBVars then
some (`_Implies, lhs, rhs)
else
none
| _ => none
/-- If `e` is of the form `r a b`, replace either `a` or `b` with `e`. -/
def updateRel (r e : Expr) (isLhs : Bool) : Expr :=
match r with
| .forallE _ d b _ => if isLhs then r.updateForallE! e b else r.updateForallE! d e
| .app (.app rel lhs) rhs => if isLhs then mkApp2 rel e rhs else mkApp2 rel lhs e
| _ => r
/-- Construct the `GCongrLemma` data from a given lemma. -/
def makeGCongrLemma (declName : Name) (declTy : Expr) (numHyps prio : Nat) : MetaM GCongrLemma := do
withDefault <| forallBoundedTelescope declTy numHyps fun xs targetTy => withReducible do
let fail {α} (m : MessageData) : MetaM α := throwError "\
@[gcongr] attribute only applies to lemmas proving f x₁ ... xₙ ∼ f x₁' ... xₙ'.\n \
{m} in {targetTy}"
-- verify that conclusion of the lemma is of the form `f x₁ ... xₙ ∼ f x₁' ... xₙ'`
let some (relName, lhs, rhs) := getRel (← whnf targetTy) | fail "No relation found"
let lhs := lhs.headBeta; let rhs := rhs.headBeta -- this is required for `Monotone fun x => ⋯`
let some (head, lhsArgs) := getCongrAppFnArgs lhs | fail "LHS is not suitable for congruence"
let some (head', rhsArgs) := getCongrAppFnArgs rhs | fail "RHS is not suitable for congruence"
unless head == head' && lhsArgs.size == rhsArgs.size do
fail "LHS and RHS do not have the same head function and arity"
let mut pairs := #[]
-- iterate through each pair of corresponding (LHS/RHS) inputs to the head function `head` in
-- the conclusion of the lemma
for e1 in lhsArgs, e2 in rhsArgs do
-- we call such a pair a "varying argument" pair if the LHS/RHS inputs are not defeq
-- (and not proofs)
let isEq ← isDefEq e1 e2 <||> (isProof e1 <&&> isProof e2)
if !isEq then
-- verify that the "varying argument" pairs are free variables (after eta-reduction)
let .fvar e1 := e1.eta | fail "Not all varying arguments are free variables"
let .fvar e2 := e2.eta | fail "Not all varying arguments are free variables"
-- add such a pair to the `pairs` array
pairs := pairs.push (e1, e2)
let numVarying := pairs.size
if numVarying = 0 then
fail "LHS and RHS are the same"
let mut mainSubgoals := #[]
let mut i := 0
-- iterate over antecedents `hyp` to the lemma
for hyp in xs do
mainSubgoals ← forallTelescopeReducing (← inferType hyp) fun args hypTy => do
-- pull out the conclusion `hypTy` of the antecedent, and check whether it is of the form
-- `lhs₁ _ ... _ ≈ rhs₁ _ ... _` (for a possibly different relation `≈` than the relation
-- `rel` above)
let hypTy ← whnf hypTy
let findPair (lhs rhs : FVarId) : Option Bool :=
pairs.findSome? fun pair =>
if (lhs, rhs) == pair then false else if (rhs, lhs) == pair then true else none
if let some (_, lhs₁, rhs₁) := getRel hypTy then
if let .fvar lhs₁ := lhs₁.getAppFn then
if let .fvar rhs₁ := rhs₁.getAppFn then
-- check whether `(lhs₁, rhs₁)` is in some order one of the "varying argument" pairs from
-- the conclusion to the lemma
if let some isContra := findPair lhs₁ rhs₁ then
-- if yes, record the index of this antecedent as a "main subgoal", together with the
-- index of the "varying argument" pair it corresponds to
return mainSubgoals.push (i, args.size, isContra)
else
-- now check whether `hypTy` is of the form `rhs₁ _ ... _`,
-- and whether the last hypothesis is of the form `lhs₁ _ ... _`.
if let .fvar rhs₁ := hypTy.getAppFn then
if let some lastFVar := args.back? then
if let .fvar lhs₁ := (← inferType lastFVar).getAppFn then
if let some isContra := findPair lhs₁ rhs₁ then
return mainSubgoals.push (i, args.size - 1, isContra)
return mainSubgoals
i := i + 1
-- store all the information from this parse of the lemma's structure in a `GCongrLemma`
let key := { relName, head, arity := lhsArgs.size }
return { key, declName, mainSubgoals, numHyps, prio, numVarying }
/-- Attribute marking "generalized congruence" (`gcongr`) lemmas. Such lemmas must have a
conclusion of a form such as `f x₁ y z₁ ∼ f x₂ y z₂`; that is, a relation between the application of
a function to two argument lists, in which the "varying argument" pairs (here `x₁`/`x₂` and
`z₁`/`z₂`) are all free variables.
The antecedents of such a lemma are classified as generating "main goals" if they are of the form
`x₁ ≈ x₂` for some "varying argument" pair `x₁`/`x₂` (and a possibly different relation `≈` to `∼`),
or more generally of the form `∀ i h h' j h'', f₁ i j ≈ f₂ i j` (say) for some "varying argument"
pair `f₁`/`f₂`. (Other antecedents are considered to generate "side goals".) The index of the
"varying argument" pair corresponding to each "main" antecedent is recorded.
If a lemma such as `add_le_add : a ≤ b → c ≤ d → a + c ≤ b + d` has been tagged with `gcongr`,
then a direct consequence like `a ≤ b → a + c ≤ b + c` does *not* need to be tagged.
However, if a more specific lemma has fewer side conditions, it should also be tagged with `gcongr`.
For example, `mul_le_mul_of_nonneg_right` and `mul_le_mul_of_nonneg_left` are both tagged.
Lemmas involving `<` or `≤` can also be marked `@[bound]` for use in the related `bound` tactic. -/
initialize registerBuiltinAttribute {
name := `gcongr
descr := "generalized congruence"
add := fun decl stx kind ↦ MetaM.run' do
let prio ← getAttrParamOptPrio stx[1]
let declTy := (← getConstInfo decl).type
let arity := declTy.getForallArity
-- We have to determine how many of the hypotheses should be introduced for
-- processing the `gcongr` lemma. This is because of implication lemmas like `Or.imp`,
-- which we treat as having conclusion `a ∨ b → c ∨ d` instead of just `c ∨ d`.
-- Since there is only one possible arity at which the `gcongr` lemma will be accepted,
-- we simply attempt to process the lemmas at the different possible arities.
try
-- If the head constant is a monotonicity constant, we want it to be unfolded.
-- We achieve this by increasing the arity
let arity' := match declTy.getForallBody.getAppFn.constName? with
| `Monotone | `Antitone | `StrictMono | `StrictAnti => arity + 3
| `MonotoneOn | `AntitoneOn | `StrictMonoOn | `StrictAntiOn => arity + 5
| _ => arity
gcongrExt.add (← makeGCongrLemma decl declTy arity' prio) kind
catch e => try
guard (1 ≤ arity)
gcongrExt.add (← makeGCongrLemma decl declTy (arity - 1) prio) kind
catch _ => try
-- We need to use `arity - 2` for lemmas such as `imp_imp_imp` and `forall_imp`.
guard (2 ≤ arity)
gcongrExt.add (← makeGCongrLemma decl declTy (arity - 2) prio) kind
catch _ =>
-- If none of the arities work, we throw the error of the first attempt.
throw e
}
initialize registerTraceClass `Meta.gcongr
syntax "gcongr_discharger" : tactic
/--
This is used as the default side-goal discharger,
it calls the `gcongr_discharger` extensible tactic.
-/
def gcongrDischarger (goal : MVarId) : MetaM Unit := Elab.Term.TermElabM.run' do
trace[Meta.gcongr] "Attempting to discharge side goal {goal}"
let [] ← Elab.Tactic.run goal <|
Elab.Tactic.evalTactic (Unhygienic.run `(tactic| gcongr_discharger))
| failure
open Elab Tactic
/-- See if the term is `a = b` and the goal is `a ∼ b` or `b ∼ a`, with `∼` reflexive. -/
@[gcongr_forward] def exactRefl : ForwardExt where
eval h goal := do
let m ← mkFreshExprMVar none
goal.assignIfDefEq (← mkAppOptM ``Eq.subst #[h, m])
goal.applyRfl
/-- See if the term is `a ∼ b` with `∼` symmetric and the goal is `b ∼ a`. -/
@[gcongr_forward] def symmExact : ForwardExt where
eval h goal := do (← goal.applySymm).assignIfDefEq h
@[gcongr_forward] def exact : ForwardExt where
eval e m := m.assignIfDefEq e
/-- Attempt to resolve an (implicitly) relational goal by one of a provided list of hypotheses,
either with such a hypothesis directly or by a limited palette of relational forward-reasoning from
these hypotheses. -/
def _root_.Lean.MVarId.gcongrForward (hs : Array Expr) (g : MVarId) : MetaM Bool :=
withReducible do
let s ← saveState
withTraceNode `Meta.gcongr (fun _ => return m!"gcongr_forward: ⊢ {← g.getType}") do
-- Iterate over a list of terms
let tacs := (forwardExt.getState (← getEnv)).2
for h in hs do
try
tacs.firstM fun (n, tac) =>
withTraceNode `Meta.gcongr (return m!"{·.emoji} trying {n} on {h} : {← inferType h}") do
tac.eval h g
return true
catch _ => s.restore
return false
/--
This is used as the default main-goal discharger,
consisting of running `Lean.MVarId.gcongrForward` (trying a term together with limited
forward-reasoning on that term) on each nontrivial hypothesis.
-/
def gcongrForwardDischarger (goal : MVarId) : MetaM Bool := Elab.Term.TermElabM.run' do
let mut hs := #[]
-- collect the nontrivial hypotheses
for h in ← getLCtx do
if !h.isImplementationDetail then
hs := hs.push (.fvar h.fvarId)
-- run `Lean.MVarId.gcongrForward` on each one
goal.gcongrForward hs
/-- Annotate `e` with a `gcongrHole` mdata annotation. -/
def mkHoleAnnotation (e : Expr) : Expr :=
mkAnnotation `gcongrHole e
/-- Check whether `e` has a `gcongrHole` mdata annotation. -/
def hasHoleAnnotation (e : Expr) : Bool :=
annotation? `gcongrHole e |>.isSome
/-- Determine whether `e` contains a `gcongrHole` mdata annotation in any subexpression.
This tells `gcongr` whether to continue applying `gcongr` lemmas. -/
def containsHoleAnnotation (e : Expr) : Bool :=
(e.find? hasHoleAnnotation).isSome
/-- (Internal for `gcongr`)
Elaborates to an expression satisfying `hasHoleAnnotation`. -/
scoped syntax (name := gcongrHoleExpand) "gcongrHole%" term : term
@[term_elab gcongrHoleExpand, inherit_doc gcongrHoleExpand]
def elabCHoleExpand : Term.TermElab := fun stx expectedType? => do
match stx with
| `(gcongrHole% $e) => return mkHoleAnnotation (← Term.elabTerm e expectedType?)
| _ => throwUnsupportedSyntax
section Trans
/-!
The lemmas `rel_imp_rel`, `rel_trans` and `rel_trans'` are too general to be tagged with
`@[gcongr]`, so instead we use `getTransLemma?` to look up these lemmas.
-/
variable {α : Sort*} {r : α → α → Prop} [IsTrans α r] {a b c d : α}
lemma rel_imp_rel (h₁ : r c a) (h₂ : r b d) : r a b → r c d :=
fun h => IsTrans.trans c b d (IsTrans.trans c a b h₁ h) h₂
/--
Construct a `GCongrLemma` for `gcongr` goals of the form `a ≺ b → c ≺ d`.
This will be tried if there is no other available `@[gcongr]` lemma.
For example, the relation `a ≡ b [ZMOD n]` has an instance of `IsTrans`, so a congruence of the form
`a ≡ b [ZMOD n] → c ≡ d [ZMOD n]` can be solved with `rel_imp_rel`, `rel_trans` or `rel_trans'`.
-/
def relImpRelLemma (arity : Nat) : List GCongrLemma :=
if arity < 2 then [] else [{
declName := ``rel_imp_rel
mainSubgoals := #[(7, 0, true), (8, 0, false)]
numHyps := 9
key := default, prio := default, numVarying := default
}]
end Trans
open private isDefEqApply throwApplyError reorderGoals from Lean.Meta.Tactic.Apply in
/--
`Lean.MVarId.applyWithArity` is a copy of `Lean.MVarId.apply`, where the arity of the
applied function is given explicitly instead of being inferred.
TODO: make `Lean.MVarId.apply` take a configuration argument to do this itself
-/
def _root_.Lean.MVarId.applyWithArity (mvarId : MVarId) (e : Expr) (arity : Nat)
(cfg : ApplyConfig := {}) (term? : Option MessageData := none) : MetaM (List MVarId) :=
mvarId.withContext do
mvarId.checkNotAssigned `apply
let targetType ← mvarId.getType
let eType ← inferType e
let (newMVars, binderInfos) ← do
-- we use `withDefault` so that we can unfold `Monotone`
let (newMVars, binderInfos, eType) ← withDefault <| forallMetaTelescopeReducing eType arity
if (← isDefEqApply cfg.approx eType targetType) then
pure (newMVars, binderInfos)
else
let conclusionType? ← if arity = 0 then
pure none
else
let (_, _, r) ← withDefault <| forallMetaTelescopeReducing eType arity
pure (some r)
throwApplyError mvarId eType conclusionType? targetType term?
postprocessAppMVars `apply mvarId newMVars binderInfos
cfg.synthAssignedInstances cfg.allowSynthFailures
let e ← instantiateMVars e
mvarId.assign (mkAppN e newMVars)
let newMVars ← newMVars.filterM fun mvar => not <$> mvar.mvarId!.isAssigned
let otherMVarIds ← getMVarsNoDelayed e
let newMVarIds ← reorderGoals newMVars cfg.newGoals
let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId
let result := newMVarIds ++ otherMVarIds.toList
result.forM (·.headBetaType)
return result
/-- The core of the `gcongr` tactic. Parse a goal into the form `(f _ ... _) ∼ (f _ ... _)`,
look up any relevant `@[gcongr]` lemmas, try to apply them, recursively run the tactic itself on
"main" goals which are generated, and run the discharger on side goals which are generated. If there
is a user-provided template, first check that the template asks us to descend this far into the
match. -/
partial def _root_.Lean.MVarId.gcongr
(g : MVarId) (mdataLhs? : Option Bool) (names : List (TSyntax ``binderIdent))
(depth : Nat := 1000000)
(mainGoalDischarger : MVarId → MetaM Bool := gcongrForwardDischarger)
(sideGoalDischarger : MVarId → MetaM Unit := gcongrDischarger) :
MetaM (Bool × List (TSyntax ``binderIdent) × Array MVarId) := g.withContext do
withTraceNode `Meta.gcongr (fun _ => return m!"gcongr: ⊢ {← g.getType}") do
if mdataLhs?.isNone then
-- A. If there is no pattern annotation, try to resolve the goal by reflexivity, or
-- by the provided tactic `mainGoalDischarger`, and continue on if this fails.
let success ← try withReducible g.applyRfl; pure true catch _ => mainGoalDischarger g
if success then
return (true, names, #[])
-- If we have reached the depth limit, return the unsolved goal
let depth + 1 := depth | return (false, names, #[g]) -- we know that there is no mdata to remove
-- Check that the goal is of the form `rel (lhsHead _ ... _) (rhsHead _ ... _)`
let rel ← withReducible g.getType'
let some (relName, lhs, rhs) := getRel rel | throwTacticEx `gcongr g m!"{rel} is not a relation"
-- If there is a pattern annotation
if let some mdataLhs := mdataLhs? then
let mdataExpr := if mdataLhs then lhs else rhs
-- if the annotation is at the head of the annotated expression,
-- then try to resolve the goal by the provided tactic `mainGoalDischarger`;
-- if this fails, stop and report the existing goal.
if hasHoleAnnotation mdataExpr then
if ← mainGoalDischarger g then
return (true, names, #[])
else
-- clear the mdata from the goal
let g ← g.replaceTargetDefEq (updateRel rel mdataExpr.mdataExpr! mdataLhs)
return (false, names, #[g])
-- If there are no annotations at all, we close the goal with `rfl`. Otherwise,
-- we report that the provided pattern doesn't apply.
unless containsHoleAnnotation mdataExpr do
try withDefault g.applyRfl; return (true, names, #[])
catch _ => throwTacticEx `gcongr g m!"\
subgoal {← withReducible g.getType'} is not allowed by the provided pattern \
and is not closed by `rfl`"
-- If there are more annotations, then continue on.
let lhs ← if relName == `_Implies then whnfR lhs else pure lhs
let rhs ← if relName == `_Implies then whnfR rhs else pure rhs
let some (lhsHead, lhsArgs) := getCongrAppFnArgs lhs |
if mdataLhs?.isNone then return (false, names, #[g])
throwTacticEx `gcongr g m!"the head of {lhs} is not a constant"
let some (rhsHead, rhsArgs) := getCongrAppFnArgs rhs |
if mdataLhs?.isNone then return (false, names, #[g])
throwTacticEx `gcongr g m!"the head of {rhs} is not a constant"
unless lhsHead == rhsHead && lhsArgs.size == rhsArgs.size do
if mdataLhs?.isNone then return (false, names, #[g])
throwTacticEx `gcongr g m!"{lhs} and {rhs} are not of the same shape"
let s ← saveState
-- Look up the `@[gcongr]` lemmas whose conclusion has the same relation and head function as
-- the goal
let key := { relName, head := lhsHead, arity := lhsArgs.size }
let mut lemmas := (gcongrExt.getState (← getEnv)).getD key []
if relName == `_Implies then
lemmas := lemmas ++ relImpRelLemma lhsArgs.size
for lem in lemmas do
let gs ← try
-- Try `apply`-ing such a lemma to the goal.
let const ← mkConstWithFreshMVarLevels lem.declName
withReducible (g.applyWithArity const lem.numHyps { synthAssignedInstances := false })
catch _ =>
s.restore
continue
let some e ← getExprMVarAssignment? g | panic! "unassigned?"
let args := e.getAppArgs
let mut subgoals := #[]
let mut names := names
-- If the `apply` succeeds, iterate over the lemma's `mainSubgoals` list.
for (i, numHyps, isContra) in lem.mainSubgoals do
-- We anticipate that such a "main" subgoal should not have been solved by the `apply` by
-- unification ...
let some (.mvar mvarId) := args[i]? | panic! "what kind of lemma is this?"
-- Introduce all variables and hypotheses in this subgoal.
let (names2, _vs, mvarId) ← mvarId.introsWithBinderIdents names (maxIntros? := numHyps)
-- Recurse: call ourself (`Lean.MVarId.gcongr`) on the subgoal with (if available) the
-- appropriate template
let mdataLhs?' := mdataLhs?.map (· != isContra)
let (_, names2, subgoals2) ← mvarId.gcongr mdataLhs?' names2 depth mainGoalDischarger
sideGoalDischarger
(names, subgoals) := (names2, subgoals ++ subgoals2)
let mut out := #[]
-- Also try the discharger on any "side" (i.e., non-"main") goals which were not resolved
-- by the `apply`.
for g in gs do
if !(← g.isAssigned) && !subgoals.contains g then
let s ← saveState
try
sideGoalDischarger (← g.intros).2
catch _ =>
s.restore
out := out.push g
-- Return all unresolved subgoals, "main" or "side"
return (true, names, out ++ subgoals)
-- A. If there is no template, and there was no `@[gcongr]` lemma which matched the goal,
-- report this goal back.
if mdataLhs?.isNone then
return (false, names, #[g])
-- B. If there is a template, and there was no `@[gcongr]` lemma which matched the template,
-- fail.
if lemmas.isEmpty then
throwTacticEx `gcongr g m!"there is no `@[gcongr]` lemma \
for relation '{relName}' and constant '{lhsHead}'."
else
throwTacticEx `gcongr g m!"none of the `@[gcongr]` lemmas were applicable to the goal {rel}.\
\n attempted lemmas: {lemmas.map (·.declName)}"
/-- The `gcongr` tactic applies "generalized congruence" rules, reducing a relational goal
between a LHS and RHS. For example,
```
example {a b x c d : ℝ} (h1 : a + 1 ≤ b + 1) (h2 : c + 2 ≤ d + 2) :
x ^ 2 * a + c ≤ x ^ 2 * b + d := by
gcongr
· linarith
· linarith
```
This example has the goal of proving the relation `≤` between a LHS and RHS both of the pattern
```
x ^ 2 * ?_ + ?_
```
(with inputs `a`, `c` on the left and `b`, `d` on the right); after the use of
`gcongr`, we have the simpler goals `a ≤ b` and `c ≤ d`.
A depth limit or a pattern can be provided explicitly;
this is useful if a non-maximal match is desired:
```
example {a b c d x : ℝ} (h : a + c + 1 ≤ b + d + 1) :
x ^ 2 * (a + c) + 5 ≤ x ^ 2 * (b + d) + 5 := by
gcongr x ^ 2 * ?_ + 5 -- or `gcongr 2`
linarith
```
The "generalized congruence" rules are the library lemmas which have been tagged with the
attribute `@[gcongr]`. For example, the first example constructs the proof term
```
add_le_add (mul_le_mul_of_nonneg_left ?_ (Even.pow_nonneg (even_two_mul 1) x)) ?_
```
using the generalized congruence lemmas `add_le_add` and `mul_le_mul_of_nonneg_left`.
The tactic attempts to discharge side goals to these "generalized congruence" lemmas (such as the
side goal `0 ≤ x ^ 2` in the above application of `mul_le_mul_of_nonneg_left`) using the tactic
`gcongr_discharger`, which wraps `positivity` but can also be extended. Side goals not discharged
in this way are left for the user.
`gcongr` will descend into binders (for example sums or suprema). To name the bound variables,
use `with`:
```
example {f g : ℕ → ℝ≥0∞} (h : ∀ n, f n ≤ g n) : ⨆ n, f n ≤ ⨆ n, g n := by
gcongr with i
exact h i
```
-/
elab "gcongr" template:(ppSpace colGt term)?
withArg:((" with" (ppSpace colGt binderIdent)+)?) : tactic => do
let g ← getMainGoal
g.withContext do
let type ← withReducible g.getType'
let some (_rel, lhs, _rhs) := getRel type
| throwError "gcongr failed, not a relation"
-- Get the names from the `with x y z` list
let names := (withArg.raw[1].getArgs.map TSyntax.mk).toList
-- Time to actually run the core tactic `Lean.MVarId.gcongr`!
let (progress, _, unsolvedGoalStates) ← do
let some e := template | g.gcongr none names
if let some depth := e.raw.isNatLit? then
g.gcongr none names (depth := depth)
else
-- Elaborate the template (e.g. `x * ?_ + _`)
-- First, we replace occurrences of `?_` with `gcongrHole% ?_`
let e ← e.raw.replaceM fun stx =>
if stx.isOfKind ``Parser.Term.syntheticHole then `(gcongrHole% _%$stx) else pure none
let patt ← withTheReader Term.Context ({ · with
ignoreTCFailures := true, errToSorry := false }) <| Term.elabTerm e (← inferType lhs)
unless containsHoleAnnotation patt do
throwError "invalid pattern {patt}, it doesn't contain any `?_`"
unless ← withReducible <| isDefEq patt lhs do
throwError "invalid pattern {patt}, it does not match with {lhs}"
let patt ← instantiateMVars patt
let g ← g.replaceTargetDefEq (updateRel type patt true)
g.gcongr true names
if progress then
replaceMainGoal unsolvedGoalStates.toList
else
throwError "gcongr did not make progress"
/-- The `rel` tactic applies "generalized congruence" rules to solve a relational goal by
"substitution". For example,
```
example {a b x c d : ℝ} (h1 : a ≤ b) (h2 : c ≤ d) :
x ^ 2 * a + c ≤ x ^ 2 * b + d := by
rel [h1, h2]
```
In this example we "substitute" the hypotheses `a ≤ b` and `c ≤ d` into the LHS `x ^ 2 * a + c` of
the goal and obtain the RHS `x ^ 2 * b + d`, thus proving the goal.
The "generalized congruence" rules used are the library lemmas which have been tagged with the
attribute `@[gcongr]`. For example, the first example constructs the proof term
```
add_le_add (mul_le_mul_of_nonneg_left h1 (pow_bit0_nonneg x 1)) h2
```
using the generalized congruence lemmas `add_le_add` and `mul_le_mul_of_nonneg_left`. If there are
no applicable generalized congruence lemmas, the tactic fails.
The tactic attempts to discharge side goals to these "generalized congruence" lemmas (such as the
side goal `0 ≤ x ^ 2` in the above application of `mul_le_mul_of_nonneg_left`) using the tactic
`gcongr_discharger`, which wraps `positivity` but can also be extended. If the side goals cannot
be discharged in this way, the tactic fails. -/
syntax "rel" " [" term,* "]" : tactic
elab_rules : tactic
| `(tactic| rel [$hyps,*]) => do
let g ← getMainGoal
g.withContext do
let hyps ← hyps.getElems.mapM (elabTerm · none)
let some (_rel, lhs, rhs) := getRel (← withReducible g.getType')
| throwError "rel failed, goal not a relation"
unless ← isDefEq (← inferType lhs) (← inferType rhs) do
throwError "rel failed, goal not a relation"
-- The core tactic `Lean.MVarId.gcongr` will be run with main-goal discharger being the tactic
-- consisting of running `Lean.MVarId.gcongrForward` (trying a term together with limited
-- forward-reasoning on that term) on each of the listed terms.
let assum g := g.gcongrForward hyps
-- Time to actually run the core tactic `Lean.MVarId.gcongr`!
let (_, _, unsolvedGoalStates) ← g.gcongr none [] (mainGoalDischarger := assum)
match unsolvedGoalStates.toList with
-- if all goals are solved, succeed!
| [] => pure ()
-- if not, fail and report the unsolved goals
| unsolvedGoalStates => do
let unsolvedGoals ← liftMetaM <| List.mapM MVarId.getType unsolvedGoalStates
let g := Lean.MessageData.joinSep (unsolvedGoals.map Lean.MessageData.ofExpr) Format.line
throwError "rel failed, cannot prove goal by 'substituting' the listed relationships. \
The steps which could not be automatically justified were:\n{g}"
end GCongr
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/GCongr/CoreAttrs.lean | import Mathlib.Tactic.GCongr.Core
/-!
# gcongr attributes for lemmas up in the import chain
In this file we add `gcongr` attribute to lemmas in `Lean.Init`.
We may add lemmas from other files imported by `Mathlib/Tactic/GCongr/Core` later.
-/
namespace Mathlib.Tactic.GCongr
variable {a b c : Prop}
lemma imp_trans (h : a → b) : (b → c) → a → c := fun g ha => g (h ha)
lemma imp_right_mono (h : a → b → c) : (a → b) → a → c :=
fun h' ha => h ha (h' ha)
lemma and_right_mono (h : a → b → c) : (a ∧ b) → a ∧ c :=
fun ⟨ha, hb⟩ => ⟨ha, h ha hb⟩
attribute [gcongr] mt
Or.imp Or.imp_left Or.imp_right
And.imp And.imp_left GCongr.and_right_mono
imp_imp_imp GCongr.imp_trans GCongr.imp_right_mono
forall_imp Exists.imp
List.Sublist.append List.Sublist.append_left List.Sublist.append_right
List.Sublist.reverse List.drop_sublist_drop_left List.Sublist.drop
List.Perm.append_left List.Perm.append_right List.Perm.append List.Perm.map
Nat.sub_le_sub_left Nat.sub_le_sub_right Nat.sub_lt_sub_left Nat.sub_lt_sub_right
end Mathlib.Tactic.GCongr |
.lake/packages/mathlib/Mathlib/Tactic/GCongr/ForwardAttr.lean | import Mathlib.Init
import Batteries.Tactic.Basic
/-!
# Environment extension for the forward-reasoning part of the `gcongr` tactic
-/
open Lean Meta Elab Tactic
namespace Mathlib.Tactic.GCongr
/-- An extension for `gcongr_forward`. -/
structure ForwardExt where
eval (h : Expr) (goal : MVarId) : MetaM Unit
/-- Read a `gcongr_forward` extension from a declaration of the right type. -/
def mkForwardExt (n : Name) : ImportM ForwardExt := do
let { env, opts, .. } ← read
IO.ofExcept <| unsafe env.evalConstCheck ForwardExt opts ``ForwardExt n
/-- Environment extensions for `gcongrForward` declarations -/
initialize forwardExt : PersistentEnvExtension Name (Name × ForwardExt)
(List Name × List (Name × ForwardExt)) ←
registerPersistentEnvExtension {
mkInitial := pure ([], {})
addImportedFn := fun s => do
let dt ← s.foldlM (init := {}) fun dt s => s.foldlM (init := dt) fun dt n => do
return (n, ← mkForwardExt n) :: dt
pure ([], dt)
addEntryFn := fun (entries, s) (n, ext) => (n :: entries, (n, ext) :: s)
exportEntriesFn := fun s => s.1.reverse.toArray
}
initialize registerBuiltinAttribute {
name := `gcongr_forward
descr := "adds a gcongr_forward extension"
applicationTime := .afterCompilation
add := fun declName stx kind => match stx with
| `(attr| gcongr_forward) => do
unless kind == AttributeKind.global do
throwError "invalid attribute 'gcongr_forward', must be global"
let env ← getEnv
unless (env.getModuleIdxFor? declName).isNone do
throwError "invalid attribute 'gcongr_forward', declaration is in an imported module"
if (IR.getSorryDep env declName).isSome then return -- ignore in progress definitions
let ext ← mkForwardExt declName
setEnv <| forwardExt.addEntry env (declName, ext)
| _ => throwUnsupportedSyntax
}
end GCongr
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/Sat/FromLRAT.lean | import Mathlib.Algebra.Group.Nat.Defs
import Mathlib.Tactic.ByContra
/-!
# `lrat_proof` command
Defines a macro for producing SAT proofs from CNF / LRAT files.
These files are commonly used in the SAT community for writing proofs.
Most SAT solvers support export to [DRAT](https://arxiv.org/abs/1610.06229) format,
but this format can be expensive to reconstruct because it requires recomputing all
unit propagation steps. The [LRAT](https://arxiv.org/abs/1612.02353) format solves this
issue by attaching a proof to the deduction of each new clause.
(The L in LRAT stands for Linear time verification.)
There are several verified checkers for the LRAT format, and the program implemented here
makes it possible to use the lean kernel as an LRAT checker as well and expose the results
as a standard propositional theorem.
The input to the `lrat_proof` command is the name of the theorem to define,
and the statement (written in CNF format) and the proof (in LRAT format).
For example:
```
lrat_proof foo
"p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0"
"5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
```
produces a theorem:
```
foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1
```
* You can see the theorem statement by hovering over the word `foo`.
* You can use the `example` keyword in place of `foo` to avoid generating a theorem.
* You can use the `include_str` macro in place of the two strings
to load CNF / LRAT files from disk.
-/
open Lean hiding Literal
open Std (HashMap)
namespace Sat
/-- A literal is a positive or negative occurrence of an atomic propositional variable.
Note that unlike DIMACS, 0 is a valid variable index. -/
inductive Literal
| pos : Nat → Literal
| neg : Nat → Literal
/-- Construct a literal. Positive numbers are translated to positive literals,
and negative numbers become negative literals. The input is assumed to be nonzero. -/
def Literal.ofInt (i : Int) : Literal :=
if i < 0 then Literal.neg (-i-1).toNat else Literal.pos (i-1).toNat
/-- Swap the polarity of a literal. -/
def Literal.negate : Literal → Literal
| pos i => neg i
| neg i => pos i
instance : ToExpr Literal where
toTypeExpr := mkConst ``Literal
toExpr
| Literal.pos i => mkApp (mkConst ``Literal.pos) (mkRawNatLit i)
| Literal.neg i => mkApp (mkConst ``Literal.neg) (mkRawNatLit i)
/-- A clause is a list of literals, thought of as a disjunction like `a ∨ b ∨ ¬c`. -/
def Clause := List Literal
/-- The empty clause -/
def Clause.nil : Clause := []
/-- Append a literal to a clause. -/
def Clause.cons : Literal → Clause → Clause := List.cons
/-- A formula is a list of clauses, thought of as a conjunction like `(a ∨ b) ∧ c ∧ (¬c ∨ ¬d)`. -/
abbrev Fmla := List Clause
/-- A single clause as a formula. -/
def Fmla.one (c : Clause) : Fmla := [c]
/-- A conjunction of formulas. -/
def Fmla.and (a b : Fmla) : Fmla := a ++ b
/-- Formula `f` subsumes `f'` if all the clauses in `f'` are in `f`.
We use this to prove that all clauses in the formula are subsumed by it. -/
structure Fmla.subsumes (f f' : Fmla) : Prop where
prop : ∀ x, x ∈ f' → x ∈ f
theorem Fmla.subsumes_self (f : Fmla) : f.subsumes f := ⟨fun _ h ↦ h⟩
theorem Fmla.subsumes_left (f f₁ f₂ : Fmla) (H : f.subsumes (f₁.and f₂)) : f.subsumes f₁ :=
⟨fun _ h ↦ H.1 _ <| List.mem_append.2 <| Or.inl h⟩
theorem Fmla.subsumes_right (f f₁ f₂ : Fmla) (H : f.subsumes (f₁.and f₂)) : f.subsumes f₂ :=
⟨fun _ h ↦ H.1 _ <| List.mem_append.2 <| Or.inr h⟩
/-- A valuation is an assignment of values to all the propositional variables. -/
def Valuation := Nat → Prop
/-- `v.neg lit` asserts that literal `lit` is falsified in the valuation. -/
def Valuation.neg (v : Valuation) : Literal → Prop
| Literal.pos i => ¬ v i
| Literal.neg i => v i
/-- `v.satisfies c` asserts that clause `c` satisfied by the valuation.
It is written in a negative way: A clause like `a ∨ ¬b ∨ c` is rewritten as
`¬a → b → ¬c → False`, so we are asserting that it is not the case that
all literals in the clause are falsified. -/
def Valuation.satisfies (v : Valuation) : Clause → Prop
| [] => False
| l::c => v.neg l → v.satisfies c
/-- `v.satisfies_fmla f` asserts that formula `f` is satisfied by the valuation.
A formula is satisfied if all clauses in it are satisfied. -/
structure Valuation.satisfies_fmla (v : Valuation) (f : Fmla) : Prop where
prop : ∀ c, c ∈ f → v.satisfies c
/-- `f.proof c` asserts that `c` is derivable from `f`. -/
def Fmla.proof (f : Fmla) (c : Clause) : Prop :=
∀ v : Valuation, v.satisfies_fmla f → v.satisfies c
/-- If `f` subsumes `c` (i.e. `c ∈ f`), then `f.proof c`. -/
theorem Fmla.proof_of_subsumes {f : Fmla} {c : Clause}
(H : Fmla.subsumes f (Fmla.one c)) : f.proof c :=
fun _ h ↦ h.1 _ <| H.1 _ <| List.Mem.head ..
/-- The core unit-propagation step.
We have a local context of assumptions `¬l'` (sometimes called an assignment)
and we wish to add `¬l` to the context, that is, we want to prove `l` is also falsified.
This is because there is a clause `a ∨ b ∨ ¬l` in the global context
such that all literals in the clause are falsified except for `¬l`;
so in the context `h₁` where we suppose that `¬l` is falsified,
the clause itself is falsified so we can prove `False`.
We continue the proof in `h₂`, with the assumption that `l` is falsified. -/
theorem Valuation.by_cases {v : Valuation} {l}
(h₁ : v.neg l.negate → False) (h₂ : v.neg l → False) : False :=
match l with
| Literal.pos _ => h₂ h₁
| Literal.neg _ => h₁ h₂
/-- `v.implies p [a, b, c] 0` definitionally unfolds to `(v 0 ↔ a) → (v 1 ↔ b) → (v 2 ↔ c) → p`.
This is used to introduce assumptions about the first `n` values of `v` during reification. -/
def Valuation.implies (v : Valuation) (p : Prop) : List Prop → Nat → Prop
| [], _ => p
| a::as, n => (v n ↔ a) → v.implies p as (n + 1)
/-- `Valuation.mk [a, b, c]` is a valuation which is `a` at 0, `b` at 1 and `c` at 2, and false
everywhere else. -/
def Valuation.mk : List Prop → Valuation
| [], _ => False
| a::_, 0 => a
| _::as, n + 1 => mk as n
/-- The fundamental relationship between `mk` and `implies`:
`(mk ps).implies p ps 0` is equivalent to `p`. -/
theorem Valuation.mk_implies {p} {as ps} (as₁) : as = List.reverseAux as₁ ps →
(Valuation.mk as).implies p ps as₁.length → p := by
induction ps generalizing as₁ with
| nil => exact fun _ ↦ id
| cons a as ih =>
refine fun e H ↦ @ih (a::as₁) e (H ?_)
subst e; clear ih H
suffices ∀ n n', n' = List.length as₁ + n →
∀ bs, mk (as₁.reverseAux bs) n' ↔ mk bs n from this 0 _ rfl (a::as)
induction as₁ with
| nil => simp
| cons b as₁ ih => simpa using fun n bs ↦ ih (n + 1) _ (Nat.succ_add ..) _
/-- Asserts that `¬⟦f⟧_v` implies `p`. -/
structure Fmla.reify (v : Valuation) (f : Fmla) (p : Prop) : Prop where
prop : ¬ v.satisfies_fmla f → p
variable {v : Valuation}
/-- If `f` is unsatisfiable, and every `v` which agrees with `ps` implies `¬⟦f⟧_v → p`, then `p`.
Equivalently, there exists a valuation `v` which agrees with `ps`,
and every such valuation yields `¬⟦f⟧_v` because `f` is unsatisfiable. -/
theorem Fmla.refute {p : Prop} {ps} (f : Fmla) (hf : f.proof [])
(hv : ∀ v, Valuation.implies v (Fmla.reify v f p) ps 0) : p :=
(Valuation.mk_implies [] rfl (hv _)).1 (hf _)
/-- Negation turns AND into OR, so `¬⟦f₁ ∧ f₂⟧_v ≡ ¬⟦f₁⟧_v ∨ ¬⟦f₂⟧_v`. -/
theorem Fmla.reify_or {f₁ : Fmla} {a : Prop} {f₂ : Fmla} {b : Prop}
(h₁ : Fmla.reify v f₁ a) (h₂ : Fmla.reify v f₂ b) : Fmla.reify v (f₁.and f₂) (a ∨ b) := by
refine ⟨fun H ↦ by_contra fun hn ↦ H ⟨fun c h ↦ by_contra fun hn' ↦ ?_⟩⟩
rcases List.mem_append.1 h with h | h
· exact hn <| Or.inl <| h₁.1 fun Hc ↦ hn' <| Hc.1 _ h
· exact hn <| Or.inr <| h₂.1 fun Hc ↦ hn' <| Hc.1 _ h
/-- Asserts that `¬⟦c⟧_v` implies `p`. -/
structure Clause.reify (v : Valuation) (c : Clause) (p : Prop) : Prop where
prop : ¬ v.satisfies c → p
/-- Reification of a single clause formula. -/
theorem Fmla.reify_one {c : Clause} {a : Prop} (h : Clause.reify v c a) :
Fmla.reify v (Fmla.one c) a :=
⟨fun H ↦ h.1 fun h ↦ H ⟨fun | _, List.Mem.head .. => h⟩⟩
/-- Asserts that `¬⟦l⟧_v` implies `p`. -/
structure Literal.reify (v : Valuation) (l : Literal) (p : Prop) : Prop where
prop : v.neg l → p
/-- Negation turns OR into AND, so `¬⟦l ∨ c⟧_v ≡ ¬⟦l⟧_v ∧ ¬⟦c⟧_v`. -/
theorem Clause.reify_and {l : Literal} {a : Prop} {c : Clause} {b : Prop}
(h₁ : Literal.reify v l a) (h₂ : Clause.reify v c b) :
Clause.reify v (Clause.cons l c) (a ∧ b) :=
⟨fun H ↦ ⟨h₁.1 (by_contra fun hn ↦ H hn.elim), h₂.1 fun h ↦ H fun _ ↦ h⟩⟩
/-- The reification of the empty clause is `True`: `¬⟦⊥⟧_v ≡ True`. -/
theorem Clause.reify_zero : Clause.reify v Clause.nil True := ⟨fun _ ↦ trivial⟩
/-- The reification of a singleton clause `¬⟦l⟧_v ≡ ¬⟦l⟧_v`. -/
theorem Clause.reify_one {l : Literal} {a : Prop}
(h₁ : Literal.reify v l a) : Clause.reify v (Clause.nil.cons l) a :=
⟨fun H ↦ ((Clause.reify_and h₁ Clause.reify_zero).1 H).1⟩
/-- The reification of a positive literal `¬⟦a⟧_v ≡ ¬a`. -/
theorem Literal.reify_pos {a : Prop} {n : ℕ} (h : v n ↔ a) : (Literal.pos n).reify v ¬a := ⟨mt h.2⟩
/-- The reification of a negative literal `¬⟦¬a⟧_v ≡ a`. -/
theorem Literal.reify_neg {a : Prop} {n : ℕ} (h : v n ↔ a) : (Literal.neg n).reify v a := ⟨h.1⟩
end Sat
namespace Mathlib.Tactic.Sat
/-- The representation of a global clause. -/
structure Clause where
/-- The list of literals as read from the input file -/
lits : Array Int
/-- The clause expression of type `Clause` -/
expr : Expr
/-- A proof of `⊢ ctx.proof c`.
Note that we do not use `have` statements to cache these proofs:
this is literally the proof expression itself. As a result, the proof terms
rely heavily on dag-like sharing of the expression, and printing these proof terms
directly is likely to crash lean for larger examples. -/
proof : Expr
/-- Construct the clause expression from the input list. For example `[1, -2]` is translated to
`Clause.cons (Literal.pos 1) (Clause.cons (Literal.neg 2) Clause.nil)`. -/
def buildClause (arr : Array Int) : Expr :=
let nil := mkConst ``Sat.Clause.nil
let cons := mkConst ``Sat.Clause.cons
arr.foldr (fun i e ↦ mkApp2 cons (toExpr <| Sat.Literal.ofInt i) e) nil
/-- Constructs the formula expression from the input CNF, as a balanced tree of `Fmla.and` nodes. -/
partial def buildConj (arr : Array (Array Int)) (start stop : Nat) : Expr :=
match stop - start with
| 0 => panic! "empty"
| 1 => mkApp (mkConst ``Sat.Fmla.one) (buildClause arr[start]!)
| len =>
let mid := start + len / 2
mkApp2 (mkConst ``Sat.Fmla.and) (buildConj arr start mid) (buildConj arr mid stop)
/-- Constructs the proofs of `⊢ ctx.proof c` for each clause `c` in `ctx`.
The proofs are stashed in a `HashMap` keyed on the clause ID. -/
partial def buildClauses (arr : Array (Array Int)) (ctx : Expr) (start stop : Nat)
(f p : Expr) (accum : Nat × HashMap Nat Clause) : Nat × HashMap Nat Clause :=
match stop - start with
| 0 => panic! "empty"
| 1 =>
let c := f.appArg!
let proof := mkApp3 (mkConst ``Sat.Fmla.proof_of_subsumes) ctx c p
let n := accum.1 + 1
(n, accum.2.insert n { lits := arr[start]!, expr := c, proof })
| len =>
let mid := start + len / 2
let f₁ := f.appFn!.appArg!
let f₂ := f.appArg!
let p₁ := mkApp4 (mkConst ``Sat.Fmla.subsumes_left) ctx f₁ f₂ p
let p₂ := mkApp4 (mkConst ``Sat.Fmla.subsumes_right) ctx f₁ f₂ p
let accum := buildClauses arr ctx start mid f₁ p₁ accum
buildClauses arr ctx mid stop f₂ p₂ accum
/-- A localized clause reference.
It is the same as `Clause` except that the proof is now a local variable. -/
structure LClause where
/-- The list of literals as read from the input file -/
lits : Array Int
/-- The clause expression of type `Clause` -/
expr : Expr
/-- The bound variable index of the hypothesis asserting `⊢ ctx.proof c`,
_counting from the outside and 1-based_. (We use this numbering because we will need to
reference the variable from multiple binder depths.) -/
depth : Nat
/-- Construct an individual proof step `⊢ ctx.proof c`.
* `db`: the current global context
* `ns`, `clause`: the new clause
* `pf`: the LRAT proof trace
* `ctx`: the main formula
The proof has three steps:
1. Introduce local assumptions `have h1 : ctx.proof c1 := p1` for each clause `c1`
referenced in the proof. We actually do all the introductions at once,
as in `(fun h1 h2 h3 ↦ ...) p1 p2 p3`, because we want `p_i` to not be under any binders
to avoid the cost of `instantiate` during typechecking and get the benefits of dag-like
sharing in the `pi` (which are themselves previous proof steps which may be large terms).
The hypotheses are in `gctx`, keyed on the clause ID.
2. Unfold `⊢ ctx.proof [a, b, c]` to
`∀ v, v.satisfies_fmla ctx → v.neg a → v.neg b → v.neg c → False` and `intro v hv ha hb hc`,
storing each `ha : v.neg a` in `lctx`, keyed on the literal `a`.
3. For each LRAT step `hc : ctx.proof [x, y]`, `hc v hv : v.neg x → v.neg y → False`.
We look for a literal that is not falsified in the clause. Since it is a unit propagation
step, there can be at most one such literal.
* If `x` is the non-falsified clause, let `x'` denote the negated literal of `x`.
Then `x'.negate` reduces to `x`, so `hnx : v.neg x'.negate |- hc v hv hnx hy : False`,
so we construct the term
`by_cases (fun hnx : v.neg x'.negate ↦ hc v hv hnx hy) (fun hx : v.neg x ↦ ...)`
and `hx` is added to the local context.
* If all clauses are falsified, then we are done: `hc v hv hx hy : False`.
-/
partial def buildProofStep (db : HashMap Nat Clause)
(ns pf : Array Int) (ctx clause : Expr) : Except String Expr := Id.run do
let mut lams := #[]
let mut args := #[]
let mut gctx : HashMap Nat LClause := {}
-- step 1
for i in pf do
let i := i.natAbs
let some cl := db[i]? | return Except.error "missing clause"
if !gctx.contains i then
lams := lams.push (mkApp2 (mkConst ``Sat.Fmla.proof) ctx cl.expr)
args := args.push cl.proof
gctx := gctx.insert i {
lits := cl.lits
expr := cl.expr
depth := args.size
}
let n := args.size
-- step 2
let mut f :=
(mkAppN · args) ∘
lams.foldr (mkLambda `c default) ∘
mkLambda `v default (mkConst ``Sat.Valuation) ∘
mkLambda `hv default (mkApp2 (mkConst ``Sat.Valuation.satisfies_fmla) (mkBVar 0) ctx)
let v depth := mkBVar (depth + 1)
let hv depth := mkBVar depth
lams := #[]
let mut clause := clause
let mut depth := 0
let mut lctx : HashMap Int Nat := {}
for i in ns do
let l := clause.appFn!.appArg!
clause := clause.appArg!
lams := lams.push (mkApp2 (mkConst ``Sat.Valuation.neg) (v depth) l)
depth := depth.succ
lctx := lctx.insert i depth
f := f ∘ lams.foldr (mkLambda `h default)
-- step 3
for (step : Int) in pf do
if step < 0 then return Except.error "unimplemented: RAT step"
let some cl := gctx[step.toNat]? | return Except.error "missing clause"
let mut unit := none
for i in cl.lits do
unless lctx.contains i do
if unit.isSome then return Except.error s!"not unit: {cl.lits}"
depth := depth.succ
unit := some i
let mut pr := mkApp2 (mkBVar (depth + n + 2 - cl.depth)) (v depth) (hv depth)
for i in cl.lits do
pr := mkApp pr <| mkBVar (match lctx[i]? with | some k => depth - k | _ => 0)
let some u := unit | return Except.ok <| f pr
let lit := toExpr <| Sat.Literal.ofInt u
let nlit := toExpr <| Sat.Literal.ofInt (-u)
let d1 := depth-1
let app := mkApp3 (mkConst ``Sat.Valuation.by_cases) (v d1) nlit <|
mkLambda `h default (mkApp2 (mkConst ``Sat.Valuation.neg) (v d1) lit) pr
let dom := mkApp2 (mkConst ``Sat.Valuation.neg) (v d1) nlit
f := fun e ↦ f <| mkApp app <| mkLambda `h default dom e
lctx := lctx.insert (-u) depth
return Except.error s!"no refutation: {ns}, {pf}, {lctx.toList}"
/-- An LRAT step is either an addition or a deletion step. -/
inductive LRATStep
| /-- An addition step, with the clause ID, the clause literal list, and the proof trace -/
add (id : Nat) (lits : Array Int) (proof : Array Int) : LRATStep
| /-- A (multiple) deletion step, which deletes all the listed clause IDs from the context -/
del (ids : Array Nat) : LRATStep
/-- Build the main proof of `⊢ ctx.proof []` using the LRAT proof trace.
* `arr`: The input CNF
* `ctx`: The abbreviated formula, a constant like `foo.ctx_1`
* `ctx'`: The definitional expansion of the formula, a tree of `Fmla.and` nodes
* `steps`: The input LRAT proof trace
-/
partial def buildProof (arr : Array (Array Int)) (ctx ctx' : Expr)
(steps : Array LRATStep) : MetaM Expr := do
let p := mkApp (mkConst ``Sat.Fmla.subsumes_self) ctx
let mut db := (buildClauses arr ctx 0 arr.size ctx' p default).2
for step in steps do
match step with
| LRATStep.del ds => db := ds.foldl (·.erase ·) db
| LRATStep.add i ns pf =>
let e := buildClause ns
match buildProofStep db ns pf ctx e with
| Except.ok proof =>
if ns.isEmpty then return proof
db := db.insert i { lits := ns, expr := e, proof }
| Except.error msg => throwError msg
throwError "failed to prove empty clause"
/-- Build the type and value of the reified theorem. This rewrites all the SAT definitions
into standard operators on `Prop`, for example if the formula is `[[1, 2], [-1, 2], [-2]]` then
this produces a proof of `⊢ ∀ a b : Prop, (a ∧ b) ∨ (¬a ∧ b) ∨ ¬b`. We use the input `nvars` to
decide how many quantifiers to use.
Most of the proof is under `2 * nvars + 1` quantifiers
`a1 .. an : Prop, v : Valuation, h1 : v 0 ↔ a1, ... hn : v (n-1) ↔ an ⊢ ...`, and we do the index
arithmetic by hand.
1. First, we call `reifyFormula ctx'` which returns `a` and `pr : reify v ctx' a`
2. Then we build `fun (v : Valuation) (h1 : v 0 ↔ a1) ... (hn : v (n-1) ↔ an) ↦ pr`
3. We have to lower expression `a` from step 1 out of the quantifiers by lowering all variable
indices by `nvars+1`. This is okay because `v` and `h1..hn` do not appear in `a`.
4. We construct the expression `ps`, which is `a1 .. an : Prop ⊢ [a1, ..., an] : List Prop`
5. `refute ctx (hf : ctx.proof []) (fun v h1 .. hn ↦ pr) : a` forces some definitional unfolding
since `fun h1 .. hn ↦ pr` should have type `implies v (reify v ctx a) [a1, ..., an] a`,
which involves unfolding `implies` n times as well as `ctx ↦ ctx'`.
6. Finally, we `intro a1 ... an` so that we have a proof of `∀ a1 ... an, a`.
-/
partial def buildReify (ctx ctx' proof : Expr) (nvars : Nat) : Expr × Expr := Id.run do
let (e, pr) := reifyFmla ctx'
let mut pr := pr
for i in [0:nvars] do
let j := nvars-i-1
let ty := mkApp2 (mkConst ``Iff) (mkApp (mkBVar j) (mkRawNatLit j)) (mkBVar nvars)
pr := mkLambda `h default ty pr
pr := mkLambda `v default (mkConst ``Sat.Valuation) pr
let mut e := e.lowerLooseBVars (nvars+1) (nvars+1)
let cons := mkApp (mkConst ``List.cons [levelZero]) (mkSort levelZero)
let nil := mkApp (mkConst ``List.nil [levelZero]) (mkSort levelZero)
let rec mkPS depth e
| 0 => e
| n + 1 => mkPS (depth+1) (mkApp2 cons (mkBVar depth) e) n
pr := mkApp5 (mkConst ``Sat.Fmla.refute) e (mkPS 0 nil nvars) ctx proof pr
for _ in [0:nvars] do
e := mkForall `a default (mkSort levelZero) e
pr := mkLambda `a default (mkSort levelZero) pr
pure (e, pr)
where
/-- The `v` variable under the `a1 ... an, v, h1 ... hn` context -/
v := mkBVar nvars
/-- Returns `a` and `pr : reify v f a` given a formula `f` -/
reifyFmla f :=
match f.getAppFn.constName! with
| ``Sat.Fmla.and =>
let f₁ := f.appFn!.appArg!
let f₂ := f.appArg!
let (e₁, h₁) := reifyFmla f₁
let (e₂, h₂) := reifyFmla f₂
(mkApp2 (mkConst ``Or) e₁ e₂, mkApp7 (mkConst ``Sat.Fmla.reify_or) v f₁ e₁ f₂ e₂ h₁ h₂)
| ``Sat.Fmla.one =>
let c := f.appArg!
let (e, h) := reifyClause c
(e, mkApp4 (mkConst ``Sat.Fmla.reify_one) v c e h)
| _ => panic! "not a valid formula"
/-- Returns `a` and `pr : reify v c a` given a clause `c` -/
reifyClause c :=
if c.appFn!.isConst then
(mkConst ``True, mkApp (mkConst ``Sat.Clause.reify_zero) v)
else reifyClause1 c
/-- Returns `a` and `pr : reify v c a` given a nonempty clause `c` -/
reifyClause1 c :=
let l := c.appFn!.appArg!
let c := c.appArg!
let (e₁, h₁) := reifyLiteral l
if c.isConst then
(e₁, mkApp4 (mkConst ``Sat.Clause.reify_one) v l e₁ h₁)
else
let (e₂, h₂) := reifyClause1 c
(mkApp2 (mkConst ``And) e₁ e₂, mkApp7 (mkConst ``Sat.Clause.reify_and) v l e₁ c e₂ h₁ h₂)
/-- Returns `a` and `pr : reify v l a` given a literal `c` -/
reifyLiteral l :=
let n := l.appArg!
let (e, h) := reifyVar n
match l.appFn!.constName! with
| ``Sat.Literal.pos =>
(mkApp (mkConst ``Not) e, mkApp4 (mkConst ``Sat.Literal.reify_pos) v e n h)
| ``Sat.Literal.neg =>
(e, mkApp4 (mkConst ``Sat.Literal.reify_neg) v e n h)
| _ => panic! "not a valid literal"
/-- Returns `a` and `pr : v n ↔ a` given a variable index `n`.
These are both lookups into the context
`(a0 .. a(n-1) : Prop) (v) (h1 : v 0 ↔ a0) ... (hn : v (n-1) ↔ a(n-1))`. -/
reifyVar v :=
let n := v.rawNatLit?.get!
(mkBVar (2 * nvars - n), mkBVar (nvars - n - 1))
open Lean
namespace Parser
open Lean Std.Internal.Parsec String
/-- Parse a natural number -/
def parseNat : String.Parser Nat := Json.Parser.natMaybeZero
/-- Parse an integer -/
def parseInt : String.Parser Int := do
if (← peek!) = '-' then skip; pure <| -(← parseNat) else parseNat
/-- Parse a list of integers terminated by 0 -/
partial def parseInts (arr : Array Int := #[]) : String.Parser (Array Int) := do
match ← parseInt <* ws with
| 0 => pure arr
| n => parseInts (arr.push n)
/-- Parse a list of natural numbers terminated by 0 -/
partial def parseNats (arr : Array Nat := #[]) : String.Parser (Array Nat) := do
match ← parseNat <* ws with
| 0 => pure arr
| n => parseNats (arr.push n)
/-- Parse a DIMACS format `.cnf` file.
This is not very robust; we assume the file has had comments stripped. -/
def parseDimacs : String.Parser (Nat × Array (Array Int)) := do
pstring "p cnf" *> ws
let nvars ← parseNat <* ws
let nclauses ← parseNat <* ws
let mut clauses := Array.mkEmpty nclauses
for _ in [:nclauses] do
clauses := clauses.push (← parseInts)
pure (nvars, clauses)
/-- Parse an LRAT file into a list of steps. -/
def parseLRAT : String.Parser (Array LRATStep) := many do
let step ← parseNat <* ws
if (← peek!) = 'd' then skip <* ws; pure <| LRATStep.del (← parseNats)
else ws; pure <| LRATStep.add step (← parseInts) (← parseInts)
end Parser
open Std.Internal
/-- Core of `fromLRAT`. Constructs the context and main proof definitions,
but not the reification theorem. Returns:
* `nvars`: the number of variables specified in the CNF file
* `ctx`: The abbreviated formula, a constant like `foo.ctx_1`
* `ctx'`: The definitional expansion of the formula, a tree of `Fmla.and` nodes
* `proof`: A proof of `ctx.proof []`
-/
def fromLRATAux (cnf lrat : String) (name : Name) : MetaM (Nat × Expr × Expr × Expr) := do
let Parsec.ParseResult.success _ (nvars, arr) := Parser.parseDimacs cnf.mkIterator
| throwError "parse CNF failed"
if arr.isEmpty then throwError "empty CNF"
let ctx' := buildConj arr 0 arr.size
let ctxName ← mkAuxDeclName (name ++ `ctx)
addDecl <| Declaration.defnDecl {
name := ctxName
levelParams := []
type := mkConst ``Sat.Fmla
value := ctx'
hints := ReducibilityHints.regular 0
safety := DefinitionSafety.safe
}
let ctx := mkConst ctxName
let Parsec.ParseResult.success _ steps := Parser.parseLRAT lrat.mkIterator
| throwError "parse LRAT failed"
let proof ← buildProof arr ctx ctx' steps
let declName ← mkAuxDeclName (name ++ `proof)
addDecl <| Declaration.thmDecl {
name := declName
levelParams := []
type := mkApp2 (mkConst ``Sat.Fmla.proof) ctx (buildClause #[])
value := proof
}
return (nvars, ctx, ctx', mkConst declName)
/-- Main entry point. Given strings `cnf` and `lrat` with unparsed file data, and a name `name`,
adds `theorem name : type := proof` where `type` is a propositional theorem like
`∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1`.
Also creates auxiliaries named `name.ctx_1` (for the CNF formula)
and `name.proof_1` (for the LRAT proof), with `name` itself containing the reification proof. -/
def fromLRAT (cnf lrat : String) (name : Name) : MetaM Unit := do
let (nvars, ctx, ctx', proof) ← fromLRATAux cnf lrat name
let (type, value) := buildReify ctx ctx' proof nvars
addDecl <| Declaration.thmDecl { name, levelParams := [], type, value }
open Elab Term
/--
A macro for producing SAT proofs from CNF / LRAT files.
These files are commonly used in the SAT community for writing proofs.
The input to the `lrat_proof` command is the name of the theorem to define,
and the statement (written in CNF format) and the proof (in LRAT format).
For example:
```
lrat_proof foo
"p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0"
"5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
```
produces a theorem:
```
foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1
```
* You can see the theorem statement by hovering over the word `foo`.
* You can use the `example` keyword in place of `foo` to avoid generating a theorem.
* You can use the `include_str` macro in place of the two strings
to load CNF / LRAT files from disk.
-/
elab "lrat_proof " n:(ident <|> "example")
ppSpace cnf:term:max ppSpace lrat:term:max : command => do
let name := (← getCurrNamespace) ++ if n.1.isIdent then n.1.getId else `_example
Command.liftTermElabM do
let cnf ← unsafe evalTerm String (mkConst ``String) cnf
let lrat ← unsafe evalTerm String (mkConst ``String) lrat
let go := do
fromLRAT cnf lrat name
withSaveInfoContext do
Term.addTermInfo' n (mkConst name) (isBinder := true)
if n.1.isIdent then go else withoutModifyingEnv go
lrat_proof example
-- The CNF file
"p cnf 2 4
1 2 0
-1 2 0
1 -2 0
-1 -2 0"
-- The LRAT file
"5 -2 0 4 3 0
5 d 3 4 0
6 1 0 5 1 0
6 d 1 0
7 0 5 2 6 0"
-- lrat_proof full2
-- (include_str "full2.cnf")
-- (include_str "full2.lrat")
/--
A macro for producing SAT proofs from CNF / LRAT files.
These files are commonly used in the SAT community for writing proofs.
The input to the `from_lrat` term syntax is two string expressions with
the statement (written in CNF format) and the proof (in LRAT format).
For example:
```
def foo := from_lrat
"p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0"
"5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
```
produces a theorem:
```
foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1
```
* You can use this term after `have :=` or in `def foo :=` to produce the term
without constraining the type.
* You can use it when a specific type is expected, but it currently does not
pay any attention to the shape of the goal and always produces the same theorem,
so you can only use this to do alpha renaming.
* You can use the `include_str` macro in place of the two strings
to load CNF / LRAT files from disk.
-/
elab "from_lrat " cnf:term:max ppSpace lrat:term:max : term => do
let cnf ← unsafe evalTerm String (mkConst ``String) cnf
let lrat ← unsafe evalTerm String (mkConst ``String) lrat
let name ← mkAuxName `lrat
fromLRAT cnf lrat name
return mkConst name
example : ∀ (a b : Prop), (¬a ∧ ¬b ∨ a ∧ ¬b) ∨ ¬a ∧ b ∨ a ∧ b := from_lrat
"p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0"
"5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
end Sat
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/Monotonicity/Lemmas.lean | import Mathlib.Algebra.Order.Group.Abs
import Mathlib.Algebra.Order.Ring.Defs
import Mathlib.Algebra.Order.Sub.Unbundled.Basic
import Mathlib.Data.Set.Lattice
import Mathlib.Tactic.Monotonicity.Attr
/-! # Lemmas for the `mono` tactic
The `mono` tactic works by throwing all lemmas tagged with the attribute `@[mono]` at the goal. In
this file we tag a few foundational lemmas with the mono attribute. Lemmas in more advanced files
are tagged in place.
-/
open Set
attribute [mono] le_refl -- added for Lean 4 version
attribute [mono] subset_refl inter_subset_inter union_subset_union
sUnion_mono iUnion₂_mono sInter_subset_sInter iInter₂_mono
image_mono preimage_mono prod_mono Monotone.set_prod
image2_subset OrderEmbedding.monotone
attribute [mono] upperBounds_mono_set lowerBounds_mono_set
upperBounds_mono_mem lowerBounds_mono_mem
upperBounds_mono lowerBounds_mono
BddAbove.mono BddBelow.mono
attribute [mono] add_le_add mul_le_mul neg_le_neg
mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right
mul_le_mul_of_nonneg_left mul_le_mul_of_nonneg_right
mul_le_mul_of_nonpos_left mul_le_mul_of_nonpos_right
-- imp_imp_imp
-- le_imp_le_of_le_of_le
tsub_lt_tsub_left_of_le tsub_lt_tsub_right_of_le
tsub_le_tsub abs_le_abs sup_le_sup
inf_le_inf
-- attribute [mono left] add_lt_add_of_le_of_lt mul_lt_mul'
-- attribute [mono right] add_lt_add_of_lt_of_le mul_lt_mul |
.lake/packages/mathlib/Mathlib/Tactic/Monotonicity/Attr.lean | import Mathlib.Init
import Lean.LabelAttribute
/-! # The @[mono] attribute -/
namespace Mathlib.Tactic.Monotonicity
syntax mono.side := &"left" <|> &"right" <|> &"both"
namespace Attr
/-- A lemma stating the monotonicity of some function, with respect to appropriate relations on its
domain and range, and possibly with side conditions. -/
syntax (name := mono) "mono" (ppSpace mono.side)? : attr
-- The following is inlined from `register_label_attr`.
/- TODO: currently `left`/`right`/`both` is ignored, and e.g. `@[mono left]` means the same as
`@[mono]`. No error is thrown by e.g. `@[mono left]`. -/
-- TODO: possibly extend `register_label_attr` to handle trailing syntax
open Lean in
@[inherit_doc mono]
initialize ext : LabelExtension ← (
let descr := "A lemma stating the monotonicity of some function, with respect to appropriate
relations on its domain and range, and possibly with side conditions."
let mono := `mono
registerLabelAttr mono descr mono)
end Attr
end Monotonicity
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/Monotonicity/Basic.lean | import Lean.Elab.Tactic.SolveByElim
import Mathlib.Tactic.Monotonicity.Attr
/-! # Monotonicity tactic
The tactic `mono` applies monotonicity rules (collected through the library by being tagged
`@[mono]`).
The version of the tactic here is a cheap partial port of the `mono` tactic from Lean 3, which had
many more options and features. It is implemented as a wrapper on top of `solve_by_elim`.
Temporary syntax change: Lean 3 `mono` applied a single monotonicity rule, then applied local
hypotheses and the `rfl` tactic as many times as it could. This is hard to implement on top of
`solve_by_elim` because the counting system used in the `maxDepth` field of its configuration would
count these as separate steps, throwing off the count in the desired configuration
`maxDepth := 1`. So instead we just implement a version of `mono` in which monotonicity rules,
local hypotheses and `rfl` are all applied repeatedly until nothing more is applicable. The syntax
for this in Lean 3 was `mono*`. Both `mono` and `mono*` implement this behavior for now.
-/
open Lean Elab Tactic Parser Tactic
open Tactic SolveByElim
namespace Mathlib.Tactic.Monotonicity
/--
`mono` applies monotonicity rules and local hypotheses repetitively. For example,
```lean
example (x y z k : ℤ)
(h : 3 ≤ (4 : ℤ))
(h' : z ≤ y) :
(k + 3 + x) - y ≤ (k + 4 + x) - z := by
mono
```
-/
syntax (name := mono) "mono" "*"? (ppSpace mono.side)?
(" with " (colGt term),+)? (" using " (colGt simpArg),+)? : tactic
elab_rules : tactic
| `(tactic| mono $[*]? $[$h:mono.side]? $[ with%$w $a:term,*]? $[ using%$u $s,*]? ) => do
let msg (s : String) := s ++ " syntax is not yet supported in 'mono'"
if let some h := h then throwErrorAt h (msg "'left'/'right'/'both'")
if let some w := w then throwErrorAt w (msg "'with'")
if let some u := u then throwErrorAt u (msg "'using'")
let cfg := { { : Meta.SolveByElim.ApplyRulesConfig } with
backtracking := false
transparency := .reducible
exfalso := false }
liftMetaTactic fun g => do processSyntax cfg false false [] [] #[mkIdent `mono] [g]
end Monotonicity
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Parsing.lean | import Mathlib.Tactic.Linarith.Datatypes
/-!
# Parsing input expressions into linear form
`linarith` computes the linear form of its input expressions,
assuming (without justification) that the type of these expressions
is a commutative semiring.
It identifies atoms up to ring-equivalence: that is, `(y*3)*x` will be identified `3*(x*y)`,
where the monomial `x*y` is the linear atom.
* Variables are represented by natural numbers.
* Monomials are represented by `Monom := TreeMap ℕ ℕ`.
The monomial `1` is represented by the empty map.
* Linear combinations of monomials are represented by `Sum := TreeMap Monom ℤ`.
All input expressions are converted to `Sum`s, preserving the map from expressions to variables.
We then discard the monomial information, mapping each distinct monomial to a natural number.
The resulting `TreeMap ℕ ℤ` represents the ring-normalized linear form of the expression.
This is ultimately converted into a `Linexp` in the obvious way.
`linearFormsAndMaxVar` is the main entry point into this file. Everything else is contained.
-/
open Std (TreeMap)
namespace Std.TreeMap
-- This will be replaced by a `BEq` instance implemented in the standard library,
-- likely in Q4 2025.
/-- Returns true if the two maps have the same size and the same keys and values
(with keys compared using the ordering, and values compared using `BEq`). -/
def beq {α β : Type*} [BEq β] {c : α → α → Ordering} (m₁ m₂ : TreeMap α β c) : Bool :=
m₁.size == m₂.size && Id.run do
-- This could be made more efficient by simultaneously traversing both maps.
for (k, v) in m₁ do
if let some v' := m₂[k]? then
if v != v' then
return false
else
return false
return true
instance {α β : Type*} [BEq β] {c : α → α → Ordering} : BEq (TreeMap α β c) := ⟨beq⟩
end Std.TreeMap
section
open Lean Elab Tactic Meta
/--
`findDefeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),
and returns the value associated with this key if it exists.
Otherwise, it fails.
-/
def List.findDefeq {v : Type} (red : TransparencyMode) (m : List (Expr × v)) (e : Expr) :
MetaM v := do
if let some (_, n) ← m.findM? fun ⟨e', _⟩ => withTransparency red (isDefEq e e') then
return n
else
failure
end
/--
We introduce a local instance allowing addition of `TreeMap`s,
removing any keys with value zero.
We don't need to prove anything about this addition, as it is only used in meta code.
-/
local instance {α β : Type*} {c : α → α → Ordering} [Add β] [Zero β] [DecidableEq β] :
Add (TreeMap α β c) where
add := fun f g => (f.mergeWith (fun _ b b' => b + b') g).filter (fun _ b => b ≠ 0)
namespace Mathlib.Tactic.Linarith
/-- A local abbreviation for `TreeMap` so we don't need to write `Ord.compare` each time. -/
abbrev Map (α β) [Ord α] := TreeMap α β Ord.compare
/-! ### Parsing datatypes -/
/-- Variables (represented by natural numbers) map to their power. -/
abbrev Monom : Type := Map ℕ ℕ
/-- `1` is represented by the empty monomial, the product of no variables. -/
def Monom.one : Monom := TreeMap.empty
/-- Compare monomials by first comparing their keys and then their powers. -/
def Monom.lt : Monom → Monom → Bool :=
fun a b =>
((a.keys : List ℕ) < b.keys) ||
(((a.keys : List ℕ) = b.keys) && ((a.values : List ℕ) < b.values))
instance : Ord Monom where
compare x y := if x.lt y then .lt else if x == y then .eq else .gt
/-- Linear combinations of monomials are represented by mapping monomials to coefficients. -/
abbrev Sum : Type := Map Monom ℤ
/-- `1` is represented as the singleton sum of the monomial `Monom.one` with coefficient 1. -/
def Sum.one : Sum := TreeMap.empty.insert Monom.one 1
/-- `Sum.scaleByMonom s m` multiplies every monomial in `s` by `m`. -/
def Sum.scaleByMonom (s : Sum) (m : Monom) : Sum :=
s.foldr (fun m' coeff sm => sm.insert (m + m') coeff) TreeMap.empty
/-- `sum.mul s1 s2` distributes the multiplication of two sums. -/
def Sum.mul (s1 s2 : Sum) : Sum :=
s1.foldr (fun mn coeff sm => sm + ((s2.scaleByMonom mn).map (fun _ v => v * coeff)))
TreeMap.empty
/-- The `n`th power of `s : Sum` is the `n`-fold product of `s`, with `s.pow 0 = Sum.one`. -/
partial def Sum.pow (s : Sum) : ℕ → Sum
| 0 => Sum.one
| 1 => s
| n =>
let m := n >>> 1
let a := s.pow m
if n &&& 1 = 0 then
a.mul a
else
a.mul a |>.mul s
/-- `SumOfMonom m` lifts `m` to a sum with coefficient `1`. -/
def SumOfMonom (m : Monom) : Sum :=
TreeMap.empty.insert m 1
/-- The unit monomial `one` is represented by the empty TreeMap. -/
def one : Monom := TreeMap.empty
/-- A scalar `z` is represented by a `Sum` with coefficient `z` and monomial `one` -/
def scalar (z : ℤ) : Sum :=
TreeMap.empty.insert one z
/-- A single variable `n` is represented by a sum with coefficient `1` and monomial `n`. -/
def var (n : ℕ) : Sum :=
TreeMap.empty.insert (TreeMap.empty.insert n 1) 1
/-! ### Parsing algorithms -/
open Lean Elab Tactic Meta
/--
`ExprMap` is used to record atomic expressions which have been seen while processing inequality
expressions.
-/
-- The natural number is just the index in the list,
-- and we could reimplement to just use `List Expr` if desired.
abbrev ExprMap := List (Expr × ℕ)
/--
`linearFormOfAtom red map e` is the atomic case for `linear_form_of_expr`.
If `e` appears with index `k` in `map`, it returns the singleton sum `var k`.
Otherwise it updates `map`, adding `e` with index `n`, and returns the singleton sum `var n`.
-/
def linearFormOfAtom (red : TransparencyMode) (m : ExprMap) (e : Expr) : MetaM (ExprMap × Sum) := do
try
let k ← m.findDefeq red e
return (m, var k)
catch _ =>
let n := m.length + 1
return ((e, n)::m, var n)
/--
`linearFormOfExpr red map e` computes the linear form of `e`.
`map` is a lookup map from atomic expressions to variable numbers.
If a new atomic expression is encountered, it is added to the map with a new number.
It matches atomic expressions up to reducibility given by `red`.
Because it matches up to definitional equality, this function must be in the `MetaM` monad,
and forces some functions that call it into `MetaM` as well.
-/
partial def linearFormOfExpr (red : TransparencyMode) (m : ExprMap) (e : Expr) :
MetaM (ExprMap × Sum) := do
let e ← whnfR e
match e.numeral? with
| some 0 => return ⟨m, TreeMap.empty⟩
| some (n + 1) => return ⟨m, scalar (n + 1)⟩
| none =>
match e.getAppFnArgs with
| (``HMul.hMul, #[_, _, _, _, e1, e2]) => do
let (m1, comp1) ← linearFormOfExpr red m e1
let (m2, comp2) ← linearFormOfExpr red m1 e2
return (m2, comp1.mul comp2)
| (``HAdd.hAdd, #[_, _, _, _, e1, e2]) => do
let (m1, comp1) ← linearFormOfExpr red m e1
let (m2, comp2) ← linearFormOfExpr red m1 e2
return (m2, comp1 + comp2)
| (``HSub.hSub, #[_, _, _, _, e1, e2]) => do
let (m1, comp1) ← linearFormOfExpr red m e1
let (m2, comp2) ← linearFormOfExpr red m1 e2
return (m2, comp1 + comp2.map (fun _ v => -v))
| (``Neg.neg, #[_, _, e]) => do
let (m1, comp) ← linearFormOfExpr red m e
return (m1, comp.map (fun _ v => -v))
| (``HPow.hPow, #[_, _, _, _, a, n]) => do
match n.numeral? with
| some n => do
let (m1, comp) ← linearFormOfExpr red m a
return (m1, comp.pow n)
| none => linearFormOfAtom red m e
| _ => linearFormOfAtom red m e
/--
`elimMonom s map` eliminates the monomial level of the `Sum` `s`.
`map` is a lookup map from monomials to variable numbers.
The output `TreeMap ℕ ℤ` has the same structure as `s : Sum`,
but each monomial key is replaced with its index according to `map`.
If any new monomials are encountered, they are assigned variable numbers and `map` is updated.
-/
def elimMonom (s : Sum) (m : Map Monom ℕ) : Map Monom ℕ × Map ℕ ℤ :=
s.foldr (fun mn coeff ⟨map, out⟩ ↦
match map[mn]? with
| some n => ⟨map, out.insert n coeff⟩
| none =>
let n := map.size
⟨map.insert mn n, out.insert n coeff⟩)
(m, TreeMap.empty)
/--
`toComp red e e_map monom_map` converts an expression of the form `t < 0`, `t ≤ 0`, or `t = 0`
into a `comp` object.
`e_map` maps atomic expressions to indices; `monom_map` maps monomials to indices.
Both of these are updated during processing and returned.
-/
def toComp (red : TransparencyMode) (e : Expr) (e_map : ExprMap) (monom_map : Map Monom ℕ) :
MetaM (Comp × ExprMap × Map Monom ℕ) := do
let (iq, e) ← parseCompAndExpr e
let (m', comp') ← linearFormOfExpr red e_map e
let ⟨nm, mm'⟩ := elimMonom comp' monom_map
-- Note: we use `.reverse` as `Linexp.get` assumes the monomial are in descending order
return ⟨⟨iq, mm'.toList.reverse⟩, m', nm⟩
/--
`toCompFold red e_map exprs monom_map` folds `toComp` over `exprs`,
updating `e_map` and `monom_map` as it goes.
-/
def toCompFold (red : TransparencyMode) : ExprMap → List Expr → Map Monom ℕ →
MetaM (List Comp × ExprMap × Map Monom ℕ)
| m, [], mm => return ([], m, mm)
| m, (h::t), mm => do
let (c, m', mm') ← toComp red h m mm
let (l, mp, mm') ← toCompFold red m' t mm'
return (c::l, mp, mm')
/--
`linearFormsAndMaxVar red pfs` is the main interface for computing the linear forms of a list
of expressions. Given a list `pfs` of proofs of comparisons, it produces a list `c` of `Comp`s of
the same length, such that `c[i]` represents the linear form of the type of `pfs[i]`.
It also returns the largest variable index that appears in comparisons in `c`.
-/
def linearFormsAndMaxVar (red : TransparencyMode) (pfs : List Expr) :
MetaM (List Comp × ℕ) := do
let pftps ← (pfs.mapM inferType)
let (l, _, map) ← toCompFold red [] pftps TreeMap.empty
trace[linarith.detail] "monomial map: {map.toList.map fun ⟨k,v⟩ => (k.toList, v)}"
return (l, map.size - 1)
end Mathlib.Tactic.Linarith |
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Lemmas.lean | import Batteries.Tactic.Lint.Basic
import Mathlib.Algebra.Order.Monoid.Unbundled.Basic
import Mathlib.Algebra.Order.Ring.Defs
import Mathlib.Algebra.Order.ZeroLEOne
import Mathlib.Data.Nat.Cast.Order.Ring
import Mathlib.Data.Int.Order.Basic
import Mathlib.Data.Ineq
/-!
# Lemmas for `linarith`.
Those in the `Linarith` namespace should stay here.
Those outside the `Linarith` namespace may be deleted as they are ported to mathlib4.
-/
namespace Mathlib.Tactic.Linarith
universe u
theorem lt_irrefl {α : Type u} [Preorder α] {a : α} : ¬a < a := _root_.lt_irrefl a
theorem eq_of_eq_of_eq {α} [Semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 := by
simp [*]
section Semiring
variable {α : Type u} [Semiring α] [PartialOrder α]
theorem zero_lt_one [IsStrictOrderedRing α] : (0:α) < 1 :=
_root_.zero_lt_one
theorem le_of_eq_of_le {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 := by
simp [*]
theorem lt_of_eq_of_lt {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 := by
simp [*]
theorem le_of_le_of_eq {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 := by
simp [*]
theorem lt_of_lt_of_eq {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 := by
simp [*]
theorem add_nonpos [IsOrderedRing α] {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) :
a + b ≤ 0 :=
_root_.add_nonpos ha hb
theorem add_lt_of_le_of_neg [IsStrictOrderedRing α] {a b c : α} (hbc : b ≤ c)
(ha : a < 0) : b + a < c :=
_root_.add_lt_of_le_of_neg hbc ha
theorem add_lt_of_neg_of_le [IsStrictOrderedRing α] {a b c : α} (ha : a < 0)
(hbc : b ≤ c) : a + b < c :=
_root_.add_lt_of_neg_of_le ha hbc
theorem add_neg [IsStrictOrderedRing α] {a b : α} (ha : a < 0)
(hb : b < 0) : a + b < 0 :=
_root_.add_neg ha hb
variable (α) in
lemma natCast_nonneg [IsOrderedRing α] (n : ℕ) : (0 : α) ≤ n := Nat.cast_nonneg n
-- used alongside `mul_neg` and `mul_nonpos`, so has the same argument pattern for uniformity
@[nolint unusedArguments]
theorem mul_eq [IsOrderedRing α] {a b : α} (ha : a = 0) (_ : 0 < b) : b * a = 0 := by
simp [*]
end Semiring
section Ring
variable {α : Type u} [Ring α] [PartialOrder α]
theorem mul_neg [IsStrictOrderedRing α] {a b : α} (ha : a < 0) (hb : 0 < b) : b * a < 0 :=
have : (-b)*a > 0 := mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha
neg_of_neg_pos (by simpa)
theorem mul_nonpos [IsOrderedRing α] {a b : α} (ha : a ≤ 0) (hb : 0 < b) : b * a ≤ 0 :=
have : (-b)*a ≥ 0 := mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha
by simpa
theorem sub_nonpos_of_le [IsOrderedRing α] {a b : α} : a ≤ b → a - b ≤ 0 :=
_root_.sub_nonpos_of_le
theorem sub_neg_of_lt [IsOrderedRing α] {a b : α} : a < b → a - b < 0 :=
_root_.sub_neg_of_lt
end Ring
/-- Finds the name of a multiplicative lemma corresponding to an inequality strength. -/
def _root_.Mathlib.Ineq.toConstMulName : Ineq → Lean.Name
| .lt => ``mul_neg
| .le => ``mul_nonpos
| .eq => ``mul_eq
lemma eq_of_not_lt_of_not_gt {α} [LinearOrder α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b :=
le_antisymm (le_of_not_gt h2) (le_of_not_gt h1)
-- used in the `nlinarith` normalization steps. The `_` argument is for uniformity.
@[nolint unusedArguments]
lemma mul_zero_eq {α} {R : α → α → Prop} [Semiring α] {a b : α} (_ : R a 0) (h : b = 0) :
a * b = 0 := by
simp [h]
-- used in the `nlinarith` normalization steps. The `_` argument is for uniformity.
@[nolint unusedArguments]
lemma zero_mul_eq {α} {R : α → α → Prop} [Semiring α] {a b : α} (h : a = 0) (_ : R b 0) :
a * b = 0 := by
simp [h]
end Mathlib.Tactic.Linarith
section
@[deprecated GT.gt.lt (since := "2025-06-16")]
theorem lt_zero_of_zero_gt {α : Type*} [Zero α] [LT α] {a : α} (h : 0 > a) : a < 0 := h
@[deprecated GE.ge.le (since := "2025-06-16")]
theorem le_zero_of_zero_ge {α : Type*} [Zero α] [LE α] {a : α} (h : 0 ≥ a) : a ≤ 0 := h
end |
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Verification.lean | import Mathlib.Tactic.Linarith.Parsing
import Mathlib.Util.Qq
/-!
# Deriving a proof of false
`linarith` uses an untrusted oracle to produce a certificate of unsatisfiability.
It needs to do some proof reconstruction work to turn this into a proof term.
This file implements the reconstruction.
## Main declarations
The public facing declaration in this file is `proveFalseByLinarith`.
-/
open Lean Elab Tactic Meta
namespace Qq
variable {u : Level}
/-- Typesafe conversion of `n : ℕ` to `Q($α)`. -/
def ofNatQ (α : Q(Type $u)) (_ : Q(Semiring $α)) (n : ℕ) : Q($α) :=
match n with
| 0 => q(0 : $α)
| 1 => q(1 : $α)
| k+2 =>
have lit : Q(ℕ) := mkRawNatLit n
have k : Q(ℕ) := mkRawNatLit k
haveI : $lit =Q $k + 2 := ⟨⟩
q(OfNat.ofNat $lit)
end Qq
namespace Mathlib.Tactic.Linarith
open Ineq
open Qq
/-! ### Auxiliary functions for assembling proofs -/
/-- A typesafe version of `mulExpr`. -/
def mulExpr' {u : Level} (n : ℕ) {α : Q(Type $u)} (inst : Q(Semiring $α)) (e : Q($α)) : Q($α) :=
if n = 1 then e else
let n := ofNatQ α inst n
q($n * $e)
/--
`mulExpr n e` creates an `Expr` representing `n*e`.
When elaborated, the coefficient will be a native numeral of the same type as `e`.
-/
def mulExpr (n : ℕ) (e : Expr) : MetaM Expr := do
let ⟨_, α, e⟩ ← inferTypeQ' e
let inst : Q(Semiring $α) ← synthInstanceQ q(Semiring $α)
return mulExpr' n inst e
/-- A type-safe analogue of `addExprs`. -/
def addExprs' {u : Level} {α : Q(Type $u)} (_inst : Q(AddMonoid $α)) : List Q($α) → Q($α)
| [] => q(0)
| h::t => go h t
where
/-- Inner loop for `addExprs'`. -/
go (p : Q($α)) : List Q($α) → Q($α)
| [] => p
| [q] => q($p + $q)
| q::t => go q($p + $q) t
/-- `addExprs L` creates an `Expr` representing the sum of the elements of `L`, associated left. -/
def addExprs : List Expr → MetaM Expr
| [] => return q(0) -- This may not be of the intended type; use with caution.
| L@(h::_) => do
let ⟨_, α, _⟩ ← inferTypeQ' h
let inst : Q(AddMonoid $α) ← synthInstanceQ q(AddMonoid $α)
-- This is not type safe; we just assume all the `Expr`s in the tail have the same type:
return addExprs' inst L
/--
If our goal is to add together two inequalities `t1 R1 0` and `t2 R2 0`,
`addIneq R1 R2` produces the strength of the inequality in the sum `R`,
along with the name of a lemma to apply in order to conclude `t1 + t2 R 0`.
-/
def addIneq : Ineq → Ineq → (Name × Ineq)
| eq, eq => (``Linarith.eq_of_eq_of_eq, eq)
| eq, le => (``Linarith.le_of_eq_of_le, le)
| eq, lt => (``Linarith.lt_of_eq_of_lt, lt)
| le, eq => (``Linarith.le_of_le_of_eq, le)
| le, le => (``Linarith.add_nonpos, le)
| le, lt => (``Linarith.add_lt_of_le_of_neg, lt)
| lt, eq => (``Linarith.lt_of_lt_of_eq, lt)
| lt, le => (``Linarith.add_lt_of_neg_of_le, lt)
| lt, lt => (``Linarith.add_neg, lt)
/--
`mkLTZeroProof coeffs pfs` takes a list of proofs of the form `tᵢ Rᵢ 0`,
paired with coefficients `cᵢ`.
It produces a proof that `∑cᵢ * tᵢ R 0`, where `R` is as strong as possible.
-/
def mkLTZeroProof : List (Expr × ℕ) → MetaM Expr
| [] => throwError "no linear hypotheses found"
| [(h, c)] => do
let (_, t) ← mkSingleCompZeroOf c h
return t
| ((h, c)::t) => do
let (iq, h') ← mkSingleCompZeroOf c h
let (_, t) ← t.foldlM (fun pr ce ↦ step pr.1 pr.2 ce.1 ce.2) (iq, h')
return t
where
/--
`step c pf npf coeff` assumes that `pf` is a proof of `t1 R1 0` and `npf` is a proof
of `t2 R2 0`. It uses `mkSingleCompZeroOf` to prove `t1 + coeff*t2 R 0`, and returns `R`
along with this proof.
-/
step (c : Ineq) (pf npf : Expr) (coeff : ℕ) : MetaM (Ineq × Expr) := do
let (iq, h') ← mkSingleCompZeroOf coeff npf
let (nm, niq) := addIneq c iq
return (niq, ← mkAppM nm #[pf, h'])
/-- If `prf` is a proof of `t R s`, `leftOfIneqProof prf` returns `t`. -/
def leftOfIneqProof (prf : Expr) : MetaM Expr := do
let (_, _, t, _) ← (← inferType prf).ineq?
return t
/-- If `prf` is a proof of `t R s`, `typeOfIneqProof prf` returns the type of `t`. -/
def typeOfIneqProof (prf : Expr) : MetaM Expr := do
let (_, ty, _) ← (← inferType prf).ineq?
return ty
/--
`mkNegOneLtZeroProof tp` returns a proof of `-1 < 0`,
where the numerals are natively of type `tp`.
-/
def mkNegOneLtZeroProof (tp : Expr) : MetaM Expr := do
let zero_lt_one ← mkAppOptM ``Linarith.zero_lt_one #[tp, none, none, none]
mkAppM `neg_neg_of_pos #[zero_lt_one]
/--
`addNegEqProofsIdx l` inspects a list `l` of pairs `(h, i)` where `h` proves
`tᵢ Rᵢ 0` and `i` records the original index of the hypothesis. For each
equality proof `t = 0` in the list, it appends a proof of `-t = 0` with the
same index `i`. All other entries are preserved.
-/
def addNegEqProofsIdx : List (Expr × Nat) → MetaM (List (Expr × Nat))
| [] => return []
| (⟨h, i⟩::tl) => do
let (iq, t) ← parseCompAndExpr (← inferType h)
match iq with
| Ineq.eq => do
let nep :=
mkAppN (← mkAppM `Iff.mpr #[← mkAppOptM ``neg_eq_zero #[none, none, t]]) #[h]
let tl ← addNegEqProofsIdx tl
return (h, i)::(nep, i)::tl
| _ => return (h, i) :: (← addNegEqProofsIdx tl)
/--
`proveEqZeroUsing tac e` tries to use `tac` to construct a proof of `e = 0`.
-/
def proveEqZeroUsing (tac : TacticM Unit) (e : Expr) : MetaM Expr := do
let ⟨u, α, e⟩ ← inferTypeQ' e
let _h : Q(Zero $α) ← synthInstanceQ q(Zero $α)
synthesizeUsing' q($e = 0) tac
/-! #### The main method -/
/--
`proveFalseByLinarith` is the main workhorse of `linarith`.
Given a list `l` of proofs of `tᵢ Rᵢ 0`,
it tries to derive a contradiction from `l` and use this to produce a proof of `False`.
`oracle : CertificateOracle` is used to search for a certificate of unsatisfiability.
The returned certificate is a map `m` from hypothesis indices to natural number coefficients.
If our set of hypotheses has the form `{tᵢ Rᵢ 0}`,
then the elimination process should have guaranteed that
1.\ `∑ (m i)*tᵢ = 0`,
with at least one `i` such that `m i > 0` and `Rᵢ` is `<`.
We have also that
2.\ `∑ (m i)*tᵢ < 0`,
since for each `i`, `(m i)*tᵢ ≤ 0` and at least one is strictly negative.
So we conclude a contradiction `0 < 0`.
It remains to produce proofs of (1) and (2). (1) is verified by calling the provided `discharger`
tactic, which is typically `ring`. We prove (2) by folding over the set of hypotheses.
`transparency : TransparencyMode` controls the transparency level with which atoms are identified.
-/
def proveFalseByLinarith (transparency : TransparencyMode) (oracle : CertificateOracle)
(discharger : TacticM Unit) : MVarId → List Expr → MetaM (Expr × List Nat)
| _, [] => throwError "no args to linarith"
| g, l@(h::_) => do
Lean.Core.checkSystem decl_name%.toString
-- for the elimination to work properly, we must add a proof of `-1 < 0` to the list,
-- along with negated equality proofs.
let lidx := l.zipIdx
let l' ← detailTrace "addNegEqProofs" <| addNegEqProofsIdx lidx
let inputsTagged : List (Expr × Option Nat) ←
detailTrace "mkNegOneLtZeroProof" <|
return ((← mkNegOneLtZeroProof (← typeOfIneqProof h)), none) ::
(l'.reverse.map fun ⟨e, i⟩ => (e, some i))
let inputs := inputsTagged.map Prod.fst
trace[linarith.detail] "inputs:{indentD <| toMessageData (← inputs.mapM inferType)}"
let (comps, max_var) ← detailTrace "linearFormsAndMaxVar" <|
linearFormsAndMaxVar transparency inputs
trace[linarith.detail] "comps:{indentD <| toMessageData comps}"
-- perform the elimination and fail if no contradiction is found.
let certificate : Std.HashMap Nat Nat ←
withTraceNode `linarith (return m!"{exceptEmoji ·} Invoking oracle") do
let certificate ←
try
oracle.produceCertificate comps max_var
catch e =>
trace[linarith] e.toMessageData
throwError "linarith failed to find a contradiction"
trace[linarith] "found a contradiction: {certificate.toList}"
return certificate
let (sm, zip, idxs) ←
withTraceNode `linarith (return m!"{exceptEmoji ·} Building final expression") do
let enum_inputs := inputsTagged.zipIdx
-- construct a list pairing nonzero coeffs with the proof of their corresponding
-- comparison and track the original index
let used := enum_inputs.filterMap fun ⟨⟨e, orig?⟩, n⟩ =>
(certificate[n]?).map fun c => (e, c, orig?)
let zip := used.map fun ⟨e, c, _⟩ => (e, c)
let mls ← used.mapM fun ⟨e, c, _⟩ => do mulExpr c (← leftOfIneqProof e)
-- `sm` is the sum of input terms, scaled to cancel out all variables.
let sm ← addExprs mls
-- let sm ← instantiateMVars sm
trace[linarith] "{indentD sm}\nshould be both 0 and negative"
let idxs :=
(used.foldl (fun acc (_, _, orig?) =>
match orig? with
| some i => i :: acc
| none => acc) []).eraseDups
return (sm, zip, idxs)
-- we prove that `sm = 0`, typically with `ring`.
let sm_eq_zero ← detailTrace "proveEqZeroUsing" <| proveEqZeroUsing discharger sm
-- we also prove that `sm < 0`
let sm_lt_zero ← detailTrace "mkLTZeroProof" <| mkLTZeroProof zip
let pf ← detailTrace "Linarith.lt_irrefl" do
-- this is a contradiction.
let pftp ← inferType sm_lt_zero
let ⟨_, nep, _⟩ ← g.rewrite pftp sm_eq_zero
let pf' ← mkAppM ``Eq.mp #[nep, sm_lt_zero]
mkAppM ``Linarith.lt_irrefl #[pf']
return (pf, idxs)
where
/-- Log `f` under `linarith.detail`, with exception emojis and the provided name. -/
detailTrace {α} (s : String) (f : MetaM α) : MetaM α :=
withTraceNode `linarith.detail (return m!"{exceptEmoji ·} {s}") f
end Mathlib.Tactic.Linarith |
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Preprocessing.lean | import Mathlib.Control.Basic
import Mathlib.Lean.Meta.Tactic.Rewrite
import Mathlib.Tactic.CancelDenoms.Core
import Mathlib.Tactic.Linarith.Datatypes
import Mathlib.Tactic.Zify
import Mathlib.Util.AtomM
/-!
# Linarith preprocessing
This file contains methods used to preprocess inputs to `linarith`.
In particular, `linarith` works over comparisons of the form `t R 0`, where `R ∈ {<,≤,=}`.
It assumes that expressions in `t` have integer coefficients and that the type of `t` has
well-behaved subtraction.
## Implementation details
A `GlobalPreprocessor` is a function `List Expr → TacticM (List Expr)`. Users can add custom
preprocessing steps by adding them to the `LinarithConfig` object. `Linarith.defaultPreprocessors`
is the main list, and generally none of these should be skipped unless you know what you're doing.
-/
namespace Mathlib.Tactic.Linarith
/-! ### Preprocessing -/
open Lean
open Elab Tactic Meta
open Qq
open Std (TreeSet)
/-- Processor that recursively replaces `P ∧ Q` hypotheses with the pair `P` and `Q`. -/
partial def splitConjunctions : Preprocessor where
description := "split conjunctions"
transform := aux
where
/-- Implementation of the `splitConjunctions` preprocessor. -/
aux (proof : Expr) : MetaM (List Expr) := do
match (← instantiateMVars (← inferType proof)).getAppFnArgs with
| (``And, #[_, _]) =>
pure ((← aux (← mkAppM ``And.left #[proof])) ++
(← aux (← mkAppM ``And.right #[proof])))
| _ => pure [proof]
/--
Removes any expressions that are not proofs of inequalities, equalities, or negations thereof.
-/
partial def filterComparisons : Preprocessor where
description := "filter terms that are not proofs of comparisons"
transform h := do
let tp ← instantiateMVars (← inferType h)
try
let (b, rel, _) ← tp.ineqOrNotIneq?
if b || rel != Ineq.eq then pure [h] else pure []
catch _ => pure []
section removeNegations
/--
If `prf` is a proof of `¬ e`, where `e` is a comparison,
`flipNegatedComparison prf e` flips the comparison in `e` and returns a proof.
For example, if `prf : ¬ a < b`, ``flipNegatedComparison prf q(a < b)`` returns a proof of `a ≥ b`.
-/
def flipNegatedComparison (prf : Expr) (e : Expr) : MetaM (Option Expr) :=
match e.getAppFnArgs with
| (``LE.le, #[_, _, _, _]) => try? <| mkAppM ``lt_of_not_ge #[prf]
| (``LT.lt, #[_, _, _, _]) => try? <| mkAppM ``le_of_not_gt #[prf]
| _ => throwError "Not a comparison (flipNegatedComparison): {e}"
/--
Replaces proofs of negations of comparisons with proofs of the reversed comparisons.
For example, a proof of `¬ a < b` will become a proof of `a ≥ b`.
-/
def removeNegations : Preprocessor where
description := "replace negations of comparisons"
transform h := do
let t : Q(Prop) ← whnfR (← inferType h)
match t with
| ~q(¬ $p) =>
match ← flipNegatedComparison h (← whnfR p) with
| some h' =>
trace[linarith] "removing negation in {h}"
return [h']
| _ => return [h]
| _ => return [h]
end removeNegations
section natToInt
open Zify
/--
`isNatProp tp` is true iff `tp` is an inequality or equality between natural numbers
or the negation thereof.
-/
partial def isNatProp (e : Expr) : MetaM Bool := succeeds <| do
let (_, _, .const ``Nat [], _, _) ← e.ineqOrNotIneq? | failure
/-- If `e` is of the form `((n : ℕ) : C)`, `isNatCoe e` returns `⟨n, C⟩`. -/
def isNatCoe (e : Expr) : Option (Expr × Expr) :=
match e.getAppFnArgs with
| (``Nat.cast, #[target, _, n]) => some ⟨n, target⟩
| _ => none
/--
`getNatComparisons e` returns a list of all subexpressions of `e` of the form `((t : ℕ) : C)`.
-/
partial def getNatComparisons (e : Expr) : List (Expr × Expr) :=
match isNatCoe e with
| some x => [x]
| none => match e.getAppFnArgs with
| (``HAdd.hAdd, #[_, _, _, _, a, b]) => getNatComparisons a ++ getNatComparisons b
| (``HMul.hMul, #[_, _, _, _, a, b]) => getNatComparisons a ++ getNatComparisons b
| (``HSub.hSub, #[_, _, _, _, a, b]) => getNatComparisons a ++ getNatComparisons b
| (``Neg.neg, #[_, _, a]) => getNatComparisons a
| _ => []
/-- If `e : ℕ`, returns a proof of `0 ≤ (e : C)`. -/
def mk_natCast_nonneg_prf (p : Expr × Expr) : MetaM (Option Expr) :=
match p with
| ⟨e, target⟩ => try commitIfNoEx (mkAppM ``natCast_nonneg #[target, e])
catch e => do
trace[linarith] "Got exception when using cast {e.toMessageData}"
return none
/-- Ordering on `Expr`. -/
@[deprecated
"Use `Expr.lt` and `Expr.equal` or `Expr.eqv` directly. \
If you need to order expressions, consider ordering them by order seen, with AtomM."
(since := "2025-08-31")]
def Expr.Ord : Ord Expr :=
⟨fun a b => if Expr.lt a b then .lt else if a.equal b then .eq else .gt⟩
/--
If `h` is an equality or inequality between natural numbers,
`natToInt` lifts this inequality to the integers.
It also adds the facts that the integers involved are nonnegative.
To avoid adding the same nonnegativity facts many times, it is a global preprocessor.
-/
def natToInt : GlobalBranchingPreprocessor where
description := "move nats to ints"
transform g l := do
let l ← l.mapM fun h => do
let t ← whnfR (← instantiateMVars (← inferType h))
if ← isNatProp t then
let (some (h', t'), _) ← Term.TermElabM.run' (run_for g (zifyProof none h t))
| throwError "zifyProof failed on {h}"
if ← succeeds t'.ineqOrNotIneq? then
pure h'
else
-- `zifyProof` turned our comparison into something that wasn't a comparison
-- probably replacing `n = n` with `True`, because of
-- https://github.com/leanprover-community/mathlib4/issues/741
-- so we just keep the original hypothesis.
pure h
else
pure h
withNewMCtxDepth <| AtomM.run .reducible <| do
let nonnegs ← l.foldlM (init := ∅) fun (es : TreeSet (Nat × Nat) lexOrd.compare) h => do
try
let (_, _, a, b) ← (← inferType h).ineq?
let getIndices (p : Expr × Expr) : AtomM (ℕ × ℕ) := do
return ((← AtomM.addAtom p.1).1, (← AtomM.addAtom p.2).1)
let indices_a ← (getNatComparisons a).mapM getIndices
let indices_b ← (getNatComparisons b).mapM getIndices
pure <| (es.insertMany indices_a).insertMany indices_b
catch _ => pure es
let atoms : Array Expr := (← get).atoms
let nonneg_pfs : List Expr ← nonnegs.toList.filterMapM fun p => do
mk_natCast_nonneg_prf (atoms[p.1]!, atoms[p.2]!)
pure [(g, nonneg_pfs ++ l)]
end natToInt
section strengthenStrictInt
/--
If `pf` is a proof of a strict inequality `(a : ℤ) < b`,
`mkNonstrictIntProof pf` returns a proof of `a + 1 ≤ b`,
and similarly if `pf` proves a negated weak inequality.
-/
def mkNonstrictIntProof (pf : Expr) : MetaM (Option Expr) := do
match ← (← inferType pf).ineqOrNotIneq? with
| (true, Ineq.lt, .const ``Int [], a, b) =>
return mkApp (← mkAppM ``Iff.mpr #[← mkAppOptM ``Int.add_one_le_iff #[a, b]]) pf
| (false, Ineq.le, .const ``Int [], a, b) =>
return mkApp (← mkAppM ``Iff.mpr #[← mkAppOptM ``Int.add_one_le_iff #[b, a]])
(← mkAppM ``lt_of_not_ge #[pf])
| _ => return none
/-- `strengthenStrictInt h` turns a proof `h` of a strict integer inequality `t1 < t2`
into a proof of `t1 ≤ t2 + 1`. -/
def strengthenStrictInt : Preprocessor where
description := "strengthen strict inequalities over int"
transform h := return [(← mkNonstrictIntProof h).getD h]
end strengthenStrictInt
section compWithZero
/--
`rearrangeComparison e` takes a proof `e` of an equality, inequality, or negation thereof,
and turns it into a proof of a comparison `_ R 0`, where `R ∈ {=, ≤, <}`.
-/
partial def rearrangeComparison (e : Expr) : MetaM (Option Expr) := do
match ← (← inferType e).ineq? with
| (Ineq.le, _) => try? <| mkAppM ``Linarith.sub_nonpos_of_le #[e]
| (Ineq.lt, _) => try? <| mkAppM ``Linarith.sub_neg_of_lt #[e]
| (Ineq.eq, _) => try? <| mkAppM ``sub_eq_zero_of_eq #[e]
/--
`compWithZero h` takes a proof `h` of an equality, inequality, or negation thereof,
and turns it into a proof of a comparison `_ R 0`, where `R ∈ {=, ≤, <}`.
-/
def compWithZero : Preprocessor where
description := "make comparisons with zero"
transform e := return (← rearrangeComparison e).toList
end compWithZero
section cancelDenoms
theorem without_one_mul {M : Type*} [MulOneClass M] {a b : M} (h : 1 * a = b) : a = b := by
rwa [one_mul] at h
/--
`normalizeDenominatorsLHS h lhs` assumes that `h` is a proof of `lhs R 0`.
It creates a proof of `lhs' R 0`, where all numeric division in `lhs` has been cancelled.
-/
def normalizeDenominatorsLHS (h lhs : Expr) : MetaM Expr := do
let mut (v, lhs') ← CancelDenoms.derive lhs
if v = 1 then
-- `lhs'` has a `1 *` out front, but `mkSingleCompZeroOf` has a special case
-- where it does not produce `1 *`. We strip it off here:
lhs' ← mkAppM ``without_one_mul #[lhs']
let (_, h'') ← mkSingleCompZeroOf v h
try
h''.rewriteType lhs'
catch e =>
dbg_trace
s!"Error in Linarith.normalizeDenominatorsLHS: {← e.toMessageData.toString}"
throw e
/--
`cancelDenoms pf` assumes `pf` is a proof of `t R 0`. If `t` contains the division symbol `/`,
it tries to scale `t` to cancel out division by numerals.
-/
def cancelDenoms : Preprocessor where
description := "cancel denominators"
transform := fun pf => (do
let (_, lhs) ← parseCompAndExpr (← inferType pf)
guard <| lhs.containsConst <| fun n =>
n = ``HDiv.hDiv || n = ``Div.div || n = ``Inv.inv || n == ``OfScientific.ofScientific
pure [← normalizeDenominatorsLHS pf lhs])
<|> return [pf]
end cancelDenoms
section nlinarith
/--
`findSquares s e` collects all terms of the form `a ^ 2` and `a * a` that appear in `e`
and adds them to the set `s`.
A pair `(i, true)` is added to `s` when `atoms[i]^2` appears in `e`,
and `(i, false)` is added to `s` when `atoms[i]*atoms[i]` appears in `e`. -/
partial def findSquares (s : TreeSet (Nat × Bool) lexOrd.compare) (e : Expr) :
AtomM (TreeSet (Nat × Bool) lexOrd.compare) :=
-- Completely traversing the expression is non-ideal,
-- as we can descend into expressions that could not possibly be seen by `linarith`.
-- As a result we visit expressions with bvars, which then cause panics.
-- Ideally this preprocessor would be reimplemented so it only visits things that could be atoms.
-- In the meantime we just bail out if we ever encounter loose bvars.
if e.hasLooseBVars then return s else
match e.getAppFnArgs with
| (``HPow.hPow, #[_, _, _, _, a, b]) => match b.numeral? with
| some 2 => do
let s ← findSquares s a
let (ai, _) ← AtomM.addAtom a
return (s.insert (ai, true))
| _ => e.foldlM findSquares s
| (``HMul.hMul, #[_, _, _, _, a, b]) => do
let (ai, _) ← AtomM.addAtom a
let (bi, _) ← AtomM.addAtom b
if ai = bi then do
let s ← findSquares s a
return (s.insert (ai, false))
else
e.foldlM findSquares s
| _ => e.foldlM findSquares s
/-- Get proofs of `-x^2 ≤ 0` and `-(x*x) ≤ 0`, when those terms appear in `ls` -/
private def nlinarithGetSquareProofs (ls : List Expr) : MetaM (List Expr) :=
withTraceNode `linarith (return m!"{exceptEmoji ·} finding squares") do
-- find the squares in `AtomM` to ensure deterministic behavior
let s ← AtomM.run .reducible do
let si ← ls.foldrM (fun h s' => do findSquares s' (← instantiateMVars (← inferType h))) ∅
si.toList.mapM fun (i, is_sq) => return ((← get).atoms[i]!, is_sq)
let new_es ← s.filterMapM fun (e, is_sq) =>
observing? <| mkAppM (if is_sq then ``sq_nonneg else ``mul_self_nonneg) #[e]
let new_es ← compWithZero.globalize.transform new_es
trace[linarith] "found:{indentD <| toMessageData s}"
linarithTraceProofs "so we added proofs" new_es
return new_es
/--
Get proofs for products of inequalities from `ls`.
Note that the length of the resulting list is proportional to `ls.length^2`, which can make a large
amount of work for the linarith oracle.
-/
private def nlinarithGetProductsProofs (ls : List Expr) : MetaM (List Expr) :=
withTraceNode `linarith (return m!"{exceptEmoji ·} adding product terms") do
let with_comps ← ls.mapM (fun e => do
let tp ← inferType e
try
let ⟨ine, _⟩ ← parseCompAndExpr tp
pure (ine, e)
catch _ => pure (Ineq.lt, e))
let products ← with_comps.mapDiagM fun (⟨posa, a⟩ : Ineq × Expr) ⟨posb, b⟩ =>
try
(some <$> match posa, posb with
| Ineq.eq, _ => mkAppM ``zero_mul_eq #[a, b]
| _, Ineq.eq => mkAppM ``mul_zero_eq #[a, b]
| Ineq.lt, Ineq.lt => mkAppM ``mul_pos_of_neg_of_neg #[a, b]
| Ineq.lt, Ineq.le => do
let a ← mkAppM ``le_of_lt #[a]
mkAppM ``mul_nonneg_of_nonpos_of_nonpos #[a, b]
| Ineq.le, Ineq.lt => do
let b ← mkAppM ``le_of_lt #[b]
mkAppM ``mul_nonneg_of_nonpos_of_nonpos #[a, b]
| Ineq.le, Ineq.le => mkAppM ``mul_nonneg_of_nonpos_of_nonpos #[a, b])
catch _ => pure none
compWithZero.globalize.transform products.reduceOption
/--
`nlinarithExtras` is the preprocessor corresponding to the `nlinarith` tactic.
* For every term `t` such that `t^2` or `t*t` appears in the input, adds a proof of `t^2 ≥ 0`
or `t*t ≥ 0`.
* For every pair of comparisons `t1 R1 0` and `t2 R2 0`, adds a proof of `t1*t2 R 0`.
This preprocessor is typically run last, after all inputs have been canonized.
-/
def nlinarithExtras : GlobalPreprocessor where
description := "nonlinear arithmetic extras"
transform ls := do
let new_es ← nlinarithGetSquareProofs ls
let products ← nlinarithGetProductsProofs (new_es ++ ls)
return (new_es ++ ls ++ products)
end nlinarith
section removeNe
/--
`removeNe_aux` case splits on any proof `h : a ≠ b` in the input,
turning it into `a < b ∨ a > b`.
This produces `2^n` branches when there are `n` such hypotheses in the input.
-/
partial def removeNe_aux : MVarId → List Expr → MetaM (List Branch) := fun g hs => do
let some (e, α, a, b) ← hs.findSomeM? (fun e : Expr => do
let some (α, a, b) := (← instantiateMVars (← inferType e)).ne?' | return none
return some (e, α, a, b)) | return [(g, hs)]
let [ng1, ng2] ← g.apply (← mkAppOptM ``Or.elim #[none, none, ← g.getType,
← mkAppOptM ``lt_or_gt_of_ne #[α, none, a, b, e]]) | failure
let do_goal : MVarId → MetaM (List Branch) := fun g => do
let (f, h) ← g.intro1
h.withContext do
let ls ← removeNe_aux h <| hs.removeAll [e]
return ls.map (fun b : Branch => (b.1, (.fvar f)::b.2))
return ((← do_goal ng1) ++ (← do_goal ng2))
/--
`removeNe` case splits on any proof `h : a ≠ b` in the input, turning it into `a < b ∨ a > b`,
by calling `linarith.removeNe_aux`.
This produces `2^n` branches when there are `n` such hypotheses in the input.
-/
def removeNe : GlobalBranchingPreprocessor where
description := "case split on ≠"
transform := removeNe_aux
end removeNe
/--
The default list of preprocessors, in the order they should typically run.
-/
def defaultPreprocessors : List GlobalBranchingPreprocessor :=
[filterComparisons, removeNegations, natToInt, strengthenStrictInt,
compWithZero, cancelDenoms]
/--
`preprocess pps l` takes a list `l` of proofs of propositions.
It maps each preprocessor `pp ∈ pps` over this list.
The preprocessors are run sequentially: each receives the output of the previous one.
Note that a preprocessor may produce multiple or no expressions from each input expression,
so the size of the list may change.
-/
def preprocess (pps : List GlobalBranchingPreprocessor) (g : MVarId) (l : List Expr) :
MetaM (List Branch) := do
withTraceNode `linarith (fun e => return m!"{exceptEmoji e} Running preprocessors") <|
g.withContext <|
pps.foldlM (init := [(g, l)]) fun ls pp => do
return (← ls.mapM fun (g, l) => do pp.process g l).flatten
end Mathlib.Tactic.Linarith |
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Datatypes.lean | import Mathlib.Tactic.Linarith.Lemmas
import Mathlib.Tactic.NormNum.Basic
import Mathlib.Util.SynthesizeUsing
/-!
# Datatypes for `linarith`
Some of the data structures here are used in multiple parts of the tactic.
We split them into their own file.
This file also contains a few convenient auxiliary functions.
-/
open Lean Elab Tactic Meta Qq
initialize registerTraceClass `linarith
initialize registerTraceClass `linarith.detail
namespace Mathlib.Tactic.Linarith
/-- A shorthand for getting the types of a list of proofs terms, to trace. -/
def linarithGetProofsMessage (l : List Expr) : MetaM MessageData := do
return m!"{← l.mapM fun e => do instantiateMVars (← inferType e)}"
/--
A shorthand for tracing the types of a list of proof terms
when the `trace.linarith` option is set to true.
-/
def linarithTraceProofs {α} [ToMessageData α] (s : α) (l : List Expr) : MetaM Unit := do
if ← isTracingEnabledFor `linarith then
addRawTrace <| .trace { cls := `linarith } (toMessageData s) #[← linarithGetProofsMessage l]
/-! ### Linear expressions -/
/--
A linear expression is a list of pairs of variable indices and coefficients,
representing the sum of the products of each coefficient with its corresponding variable.
Some functions on `Linexp` assume that `n : Nat` occurs at most once as the first element of a pair,
and that the list is sorted in decreasing order of the first argument.
This is not enforced by the type but the operations here preserve it.
-/
abbrev Linexp : Type := List (Nat × Int)
namespace Linexp
/--
Add two `Linexp`s together componentwise.
Preserves sorting and uniqueness of the first argument.
-/
partial def add : Linexp → Linexp → Linexp
| [], a => a
| a, [] => a
| (a@(n1,z1)::t1), (b@(n2,z2)::t2) =>
if n1 < n2 then b::add (a::t1) t2
else if n2 < n1 then a::add t1 (b::t2)
else
let sum := z1 + z2
if sum = 0 then add t1 t2 else (n1, sum)::add t1 t2
/-- `l.scale c` scales the values in `l` by `c` without modifying the order or keys. -/
def scale (c : Int) (l : Linexp) : Linexp :=
if c = 0 then []
else if c = 1 then l
else l.map fun ⟨n, z⟩ => (n, z*c)
/--
`l.get n` returns the value in `l` associated with key `n`, if it exists, and `none` otherwise.
This function assumes that `l` is sorted in decreasing order of the first argument,
that is, it will return `none` as soon as it finds a key smaller than `n`.
-/
def get (n : Nat) : Linexp → Option Int
| [] => none
| ((a, b)::t) =>
if a < n then none
else if a = n then some b
else get n t
/--
`l.contains n` is true iff `n` is the first element of a pair in `l`.
-/
def contains (n : Nat) : Linexp → Bool := Option.isSome ∘ get n
/--
`l.zfind n` returns the value associated with key `n` if there is one, and 0 otherwise.
-/
def zfind (n : Nat) (l : Linexp) : Int :=
match l.get n with
| none => 0
| some v => v
/-- `l.vars` returns the list of variables that occur in `l`. -/
def vars (l : Linexp) : List Nat :=
l.map Prod.fst
/--
Defines a lex ordering on `Linexp`. This function is performance critical.
-/
def cmp : Linexp → Linexp → Ordering
| [], [] => Ordering.eq
| [], _ => Ordering.lt
| _, [] => Ordering.gt
| ((n1,z1)::t1), ((n2,z2)::t2) =>
if n1 < n2 then Ordering.lt
else if n2 < n1 then Ordering.gt
else if z1 < z2 then Ordering.lt
else if z2 < z1 then Ordering.gt
else cmp t1 t2
end Linexp
/-! ### Comparisons with 0 -/
/--
The main datatype for FM elimination.
Variables are represented by natural numbers, each of which has an integer coefficient.
Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1.
The represented term is `coeffs.sum (fun ⟨k, v⟩ ↦ v * Var[k])`.
str determines the strength of the comparison -- is it < 0, ≤ 0, or = 0?
-/
structure Comp : Type where
/-- The strength of the comparison, `<`, `≤`, or `=`. -/
str : Ineq
/-- The coefficients of the comparison, stored as list of pairs `(i, a)`,
where `i` is the index of a recorded atom, and `a` is the coefficient. -/
coeffs : Linexp
deriving Inhabited, Repr
-- See https://github.com/leanprover/lean4/issues/10295
attribute [nolint unusedArguments] Mathlib.Tactic.Linarith.instReprComp.repr
/-- `c.vars` returns the list of variables that appear in the linear expression contained in `c`. -/
def Comp.vars : Comp → List Nat := Linexp.vars ∘ Comp.coeffs
/-- `c.coeffOf a` projects the coefficient of variable `a` out of `c`. -/
def Comp.coeffOf (c : Comp) (a : Nat) : Int :=
c.coeffs.zfind a
/-- `c.scale n` scales the coefficients of `c` by `n`. -/
def Comp.scale (c : Comp) (n : Nat) : Comp :=
{ c with coeffs := c.coeffs.scale n }
/--
`Comp.add c1 c2` adds the expressions represented by `c1` and `c2`.
The coefficient of variable `a` in `c1.add c2`
is the sum of the coefficients of `a` in `c1` and `c2`.
-/
def Comp.add (c1 c2 : Comp) : Comp :=
⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩
/-- `Comp` has a lex order. First the `ineq`s are compared, then the `coeff`s. -/
def Comp.cmp : Comp → Comp → Ordering
| ⟨str1, coeffs1⟩, ⟨str2, coeffs2⟩ =>
match str1.cmp str2 with
| Ordering.lt => Ordering.lt
| Ordering.gt => Ordering.gt
| Ordering.eq => coeffs1.cmp coeffs2
/--
A `Comp` represents a contradiction if its expression has no coefficients and its strength is <,
that is, it represents the fact `0 < 0`.
-/
def Comp.isContr (c : Comp) : Bool := c.coeffs.isEmpty && c.str = Ineq.lt
instance Comp.ToFormat : ToFormat Comp :=
⟨fun p => format p.coeffs ++ toString p.str ++ "0"⟩
/-! ### Parsing into linear form -/
/-! ### Control -/
/-- Metadata about preprocessors, for trace output. -/
structure PreprocessorBase : Type where
/-- The name of the preprocessor, populated automatically, to create linkable trace messages. -/
name : Name := by exact decl_name%
/-- The description of the preprocessor. -/
description : String
/--
A preprocessor transforms a proof of a proposition into a proof of a different proposition.
The return type is `List Expr`, since some preprocessing steps may create multiple new hypotheses,
and some may remove a hypothesis from the list.
A "no-op" preprocessor should return its input as a singleton list.
-/
structure Preprocessor : Type extends PreprocessorBase where
/-- Replace a hypothesis by a list of hypotheses. These expressions are the proof terms. -/
transform : Expr → MetaM (List Expr)
/--
Some preprocessors need to examine the full list of hypotheses instead of working item by item.
As with `Preprocessor`, the input to a `GlobalPreprocessor` is replaced by, not added to, its
output.
-/
structure GlobalPreprocessor : Type extends PreprocessorBase where
/-- Replace the collection of all hypotheses with new hypotheses.
These expressions are proof terms. -/
transform : List Expr → MetaM (List Expr)
/--
Some preprocessors perform branching case splits. A `Branch` is used to track one of these case
splits. The first component, an `MVarId`, is the goal corresponding to this branch of the split,
given as a metavariable. The `List Expr` component is the list of hypotheses for `linarith`
in this branch.
-/
def Branch : Type := MVarId × List Expr
/--
Some preprocessors perform branching case splits.
A `GlobalBranchingPreprocessor` produces a list of branches to run.
Each branch is independent, so hypotheses that appear in multiple branches should be duplicated.
The preprocessor is responsible for making sure that each branch contains the correct goal
metavariable.
-/
structure GlobalBranchingPreprocessor : Type extends PreprocessorBase where
/-- Given a goal, and a list of hypotheses,
produce a list of pairs (consisting of a goal and list of hypotheses). -/
transform : MVarId → List Expr → MetaM (List Branch)
/--
A `Preprocessor` lifts to a `GlobalPreprocessor` by folding it over the input list.
-/
def Preprocessor.globalize (pp : Preprocessor) : GlobalPreprocessor where
__ := pp
transform := List.foldrM (fun e ret => do return (← pp.transform e) ++ ret) []
/--
A `GlobalPreprocessor` lifts to a `GlobalBranchingPreprocessor` by producing only one branch.
-/
def GlobalPreprocessor.branching (pp : GlobalPreprocessor) : GlobalBranchingPreprocessor where
__ := pp
transform := fun g l => do return [⟨g, ← pp.transform l⟩]
/--
`process pp l` runs `pp.transform` on `l` and returns the result,
tracing the result if `trace.linarith` is on.
-/
def GlobalBranchingPreprocessor.process (pp : GlobalBranchingPreprocessor)
(g : MVarId) (l : List Expr) : MetaM (List Branch) := g.withContext do
withTraceNode `linarith (fun e =>
return m!"{exceptEmoji e} {.ofConstName pp.name}: {pp.description}") do
let branches ← pp.transform g l
if branches.length > 1 then
trace[linarith] "Preprocessing: {pp.name} has branched, with branches:"
for ⟨goal, hyps⟩ in branches do
trace[linarith] (← goal.withContext <| linarithGetProofsMessage hyps)
return branches
instance PreprocessorToGlobalBranchingPreprocessor :
Coe Preprocessor GlobalBranchingPreprocessor :=
⟨GlobalPreprocessor.branching ∘ Preprocessor.globalize⟩
instance GlobalPreprocessorToGlobalBranchingPreprocessor :
Coe GlobalPreprocessor GlobalBranchingPreprocessor :=
⟨GlobalPreprocessor.branching⟩
/--
A `CertificateOracle` provides a function
`produceCertificate : List Comp → Nat → MetaM (HashMap Nat Nat)`.
The default `CertificateOracle` used by `linarith` is
`Linarith.CertificateOracle.simplexAlgorithmSparse`.
`Linarith.CertificateOracle.simplexAlgorithmDense` and `Linarith.CertificateOracle.fourierMotzkin`
are also available (though the Fourier-Motzkin oracle has some bugs).
-/
structure CertificateOracle : Type where
/-- `produceCertificate hyps max_var` tries to derive a contradiction from the comparisons in
`hyps` by eliminating all variables ≤ `max_var`.
If successful, it returns a map `coeff : Nat → Nat` as a certificate.
This map represents that we can find a contradiction by taking the sum `∑ (coeff i) * hyps[i]`. -/
produceCertificate (hyps : List Comp) (max_var : Nat) : MetaM (Std.HashMap Nat Nat)
/-!
### Auxiliary functions
These functions are used by multiple modules, so we put them here for accessibility.
-/
/--
`parseCompAndExpr e` checks if `e` is of the form `t < 0`, `t ≤ 0`, or `t = 0`.
If it is, it returns the comparison along with `t`.
-/
def parseCompAndExpr (e : Expr) : MetaM (Ineq × Expr) := do
let (rel, _, e, z) ← e.ineq?
if z.zero? then return (rel, e) else throwError "invalid comparison, rhs not zero: {z}"
/--
`mkSingleCompZeroOf c h` assumes that `h` is a proof of `t R 0`.
It produces a pair `(R', h')`, where `h'` is a proof of `c*t R' 0`.
Typically `R` and `R'` will be the same, except when `c = 0`, in which case `R'` is `=`.
If `c = 1`, `h'` is the same as `h` -- specifically, it does *not* change the type to `1*t R 0`.
-/
def mkSingleCompZeroOf (c : Nat) (h : Expr) : MetaM (Ineq × Expr) := do
let tp ← inferType h
let (iq, e) ← parseCompAndExpr tp
if c = 0 then do
let e' ← mkAppM ``zero_mul #[e]
return (Ineq.eq, e')
else if c = 1 then return (iq, h)
else do
let (_, tp, _) ← tp.ineq?
let cpos : Q(Prop) ← mkAppM ``GT.gt #[(← tp.ofNat c), (← tp.ofNat 0)]
let ex ← synthesizeUsingTactic' cpos (← `(tactic| norm_num))
let e' ← mkAppM iq.toConstMulName #[h, ex]
return (iq, e')
end Mathlib.Tactic.Linarith |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.