fact stringlengths 6 3.84k | type stringclasses 11 values | library stringclasses 32 values | imports listlengths 1 14 | filename stringlengths 20 95 | symbolic_name stringlengths 1 90 | docstring stringlengths 7 20k ⌀ |
|---|---|---|---|---|---|---|
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 | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | mk_natCast_nonneg_prf | If `e : ℕ`, returns a proof of `0 ≤ (e : C)`. |
@[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")]
Expr.Ord : Ord Expr :=
⟨fun a b => if Expr.lt a b then .lt else if a.equal b then .eq else .gt⟩ | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | Expr.Ord | Ordering on `Expr`. |
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
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)] | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | natToInt | 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. |
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 | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | mkNonstrictIntProof | 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. |
strengthenStrictInt : Preprocessor where
description := "strengthen strict inequalities over int"
transform h := return [(← mkNonstrictIntProof h).getD h] | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | strengthenStrictInt | `strengthenStrictInt h` turns a proof `h` of a strict integer inequality `t1 < t2`
into a proof of `t1 ≤ t2 + 1`. |
partial 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] | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | rearrangeComparison | `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 ∈ {=, ≤, <}`. |
compWithZero : Preprocessor where
description := "make comparisons with zero"
transform e := return (← rearrangeComparison e).toList | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | compWithZero | `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 ∈ {=, ≤, <}`. |
without_one_mul {M : Type*} [MulOneClass M] {a b : M} (h : 1 * a = b) : a = b := by
rwa [one_mul] at h | theorem | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | without_one_mul | null |
normalizeDenominatorsLHS (h lhs : Expr) : MetaM Expr := do
let mut (v, lhs') ← CancelDenoms.derive lhs
if v = 1 then
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 | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | normalizeDenominatorsLHS | `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. |
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] | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | cancelDenoms | `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. |
partial findSquares (s : TreeSet (Nat × Bool) lexOrd.compare) (e : Expr) :
AtomM (TreeSet (Nat × Bool) lexOrd.compare) :=
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 | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | findSquares | `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`. |
private nlinarithGetSquareProofs (ls : List Expr) : MetaM (List Expr) :=
withTraceNode `linarith (return m!"{exceptEmoji ·} finding squares") do
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 | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | nlinarithGetSquareProofs | Get proofs of `-x^2 ≤ 0` and `-(x*x) ≤ 0`, when those terms appear in `ls` |
private 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 | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | nlinarithGetProductsProofs | 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. |
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) | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | nlinarithExtras | `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. |
partial 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)) | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | removeNe_aux | `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. |
removeNe : GlobalBranchingPreprocessor where
description := "case split on ≠"
transform := removeNe_aux | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | removeNe | `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. |
defaultPreprocessors : List GlobalBranchingPreprocessor :=
[filterComparisons, removeNegations, natToInt, strengthenStrictInt,
compWithZero, cancelDenoms] | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | defaultPreprocessors | The default list of preprocessors, in the order they should typically run. |
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 | def | Tactic | [
"Mathlib.Control.Basic",
"Mathlib.Lean.Meta.Tactic.Rewrite",
"Mathlib.Tactic.CancelDenoms.Core",
"Mathlib.Tactic.Linarith.Datatypes",
"Mathlib.Tactic.Zify",
"Mathlib.Util.AtomM"
] | Mathlib/Tactic/Linarith/Preprocessing.lean | preprocess | `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. |
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) | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | ofNatQ | Typesafe conversion of `n : ℕ` to `Q($α)`. |
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) | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | mulExpr' | A typesafe version of `mulExpr`. |
mulExpr (n : ℕ) (e : Expr) : MetaM Expr := do
let ⟨_, α, e⟩ ← inferTypeQ' e
let inst : Q(Semiring $α) ← synthInstanceQ q(Semiring $α)
return mulExpr' n inst e | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | mulExpr | `mulExpr n e` creates an `Expr` representing `n*e`.
When elaborated, the coefficient will be a native numeral of the same type as `e`. |
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 | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | addExprs' | A type-safe analogue of `addExprs`. |
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 $α)
return addExprs' inst L | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | addExprs | `addExprs L` creates an `Expr` representing the sum of the elements of `L`, associated left. |
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) | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | addIneq | 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`. |
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']) | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | mkLTZeroProof | `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. |
leftOfIneqProof (prf : Expr) : MetaM Expr := do
let (_, _, t, _) ← (← inferType prf).ineq?
return t | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | leftOfIneqProof | If `prf` is a proof of `t R s`, `leftOfIneqProof prf` returns `t`. |
typeOfIneqProof (prf : Expr) : MetaM Expr := do
let (_, ty, _) ← (← inferType prf).ineq?
return ty | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | typeOfIneqProof | If `prf` is a proof of `t R s`, `typeOfIneqProof prf` returns the type of `t`. |
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] | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | mkNegOneLtZeroProof | `mkNegOneLtZeroProof tp` returns a proof of `-1 < 0`,
where the numerals are natively of type `tp`. |
addNegEqProofs : List Expr → MetaM (List Expr)
| [] => return []
| (h::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 ← addNegEqProofs tl
return h::nep::tl
| _ => return h :: (← addNegEqProofs tl) | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | addNegEqProofs | `addNegEqProofs l` inspects the list of proofs `l` for proofs of the form `t = 0`. For each such
proof, it adds a proof of `-t = 0` to the list. |
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 -/ | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | proveEqZeroUsing | `proveEqZeroUsing tac e` tries to use `tac` to construct a proof of `e = 0`. |
proveFalseByLinarith (transparency : TransparencyMode) (oracle : CertificateOracle)
(discharger : TacticM Unit) : MVarId → List Expr → MetaM Expr
| _, [] => throwError "no args to linarith"
| g, l@(h::_) => do
Lean.Core.checkSystem decl_name%.toString
let l' ← detailTrace "addNegEqProofs" <| addNegEqProofs l
let inputs ← detailTrace "mkNegOneLtZeroProof" <|
return (← mkNegOneLtZeroProof (← typeOfIneqProof h))::l'.reverse
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}"
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) ←
withTraceNode `linarith (return m!"{exceptEmoji ·} Building final expression") do
let enum_inputs := inputs.zipIdx
let zip := enum_inputs.filterMap fun ⟨e, n⟩ => (certificate[n]?).map (e, ·)
let mls ← zip.mapM fun ⟨e, n⟩ => do mulExpr n (← leftOfIneqProof e)
let sm ← addExprs mls
trace[linarith] "{indentD sm}\nshould be both 0 and negative"
return (sm, zip)
let sm_eq_zero ← detailTrace "proveEqZeroUsing" <| proveEqZeroUsing discharger sm
let sm_lt_zero ← detailTrace "mkLTZeroProof" <| mkLTZeroProof zip
detailTrace "Linarith.lt_irrefl" do
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']
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 | def | Tactic | [
"Mathlib.Tactic.Linarith.Parsing",
"Mathlib.Util.Qq"
] | Mathlib/Tactic/Linarith/Verification.lean | proveFalseByLinarith | `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. |
add_eq_eq [Add α] (p₁ : (a₁ : α) = b₁) (p₂ : a₂ = b₂) : a₁ + a₂ = b₁ + b₂ := p₁ ▸ p₂ ▸ rfl | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | add_eq_eq | null |
add_le_eq [AddCommMonoid α] [PartialOrder α] [IsOrderedAddMonoid α]
(p₁ : (a₁ : α) ≤ b₁) (p₂ : a₂ = b₂) : a₁ + a₂ ≤ b₁ + b₂ :=
p₂ ▸ add_le_add_right p₁ b₂ | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | add_le_eq | null |
add_eq_le [AddCommMonoid α] [PartialOrder α] [IsOrderedAddMonoid α]
(p₁ : (a₁ : α) = b₁) (p₂ : a₂ ≤ b₂) : a₁ + a₂ ≤ b₁ + b₂ :=
p₁ ▸ add_le_add_left p₂ b₁ | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | add_eq_le | null |
add_lt_eq [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α]
(p₁ : (a₁ : α) < b₁) (p₂ : a₂ = b₂) : a₁ + a₂ < b₁ + b₂ :=
p₂ ▸ add_lt_add_right p₁ b₂ | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | add_lt_eq | null |
add_eq_lt [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α] {a₁ b₁ a₂ b₂ : α}
(p₁ : a₁ = b₁) (p₂ : a₂ < b₂) : a₁ + a₂ < b₁ + b₂ :=
p₁ ▸ add_lt_add_left p₂ b₁
/-! ### Multiplication -/ | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | add_eq_lt | null |
mul_eq_const [Mul α] (p : a = b) (c : α) : a * c = b * c := p ▸ rfl | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mul_eq_const | null |
mul_le_const [Semiring α] [PartialOrder α] [IsOrderedRing α]
(p : b ≤ c) {a : α} (ha : 0 ≤ a) :
b * a ≤ c * a :=
mul_le_mul_of_nonneg_right p ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mul_le_const | null |
mul_lt_const [Semiring α] [PartialOrder α] [IsStrictOrderedRing α]
(p : b < c) {a : α} (ha : 0 < a) :
b * a < c * a :=
mul_lt_mul_of_pos_right p ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mul_lt_const | null |
mul_lt_const_weak [Semiring α] [PartialOrder α] [IsOrderedRing α]
(p : b < c) {a : α} (ha : 0 ≤ a) :
b * a ≤ c * a :=
mul_le_mul_of_nonneg_right p.le ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mul_lt_const_weak | null |
mul_const_eq [Mul α] (p : b = c) (a : α) : a * b = a * c := p ▸ rfl | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mul_const_eq | null |
mul_const_le [Semiring α] [PartialOrder α] [IsOrderedRing α]
(p : b ≤ c) {a : α} (ha : 0 ≤ a) :
a * b ≤ a * c :=
mul_le_mul_of_nonneg_left p ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mul_const_le | null |
mul_const_lt [Semiring α] [PartialOrder α] [IsStrictOrderedRing α]
(p : b < c) {a : α} (ha : 0 < a) :
a * b < a * c :=
mul_lt_mul_of_pos_left p ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mul_const_lt | null |
mul_const_lt_weak [Semiring α] [PartialOrder α] [IsOrderedRing α]
(p : b < c) {a : α} (ha : 0 ≤ a) :
a * b ≤ a * c :=
mul_le_mul_of_nonneg_left p.le ha
/-! ### Scalar multiplication -/ | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mul_const_lt_weak | null |
smul_eq_const [SMul K α] (p : t = s) (c : α) : t • c = s • c := p ▸ rfl | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smul_eq_const | null |
smul_le_const [Ring K] [PartialOrder K] [IsOrderedRing K]
[AddCommGroup α] [PartialOrder α] [IsOrderedAddMonoid α] [Module K α]
[IsOrderedModule K α] (p : t ≤ s) {a : α} (ha : 0 ≤ a) :
t • a ≤ s • a :=
smul_le_smul_of_nonneg_right p ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smul_le_const | null |
smul_lt_const [Ring K] [PartialOrder K] [IsOrderedRing K]
[AddCommGroup α] [PartialOrder α] [IsOrderedAddMonoid α] [Module K α]
[IsStrictOrderedModule K α] (p : t < s) {a : α} (ha : 0 < a) :
t • a < s • a :=
smul_lt_smul_of_pos_right p ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smul_lt_const | null |
smul_lt_const_weak [Ring K] [PartialOrder K] [IsOrderedRing K]
[AddCommGroup α] [PartialOrder α] [IsOrderedAddMonoid α] [Module K α]
[IsStrictOrderedModule K α] (p : t < s) {a : α} (ha : 0 ≤ a) :
t • a ≤ s • a :=
smul_le_smul_of_nonneg_right p.le ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smul_lt_const_weak | null |
smul_const_eq [SMul K α] (p : b = c) (s : K) : s • b = s • c := p ▸ rfl | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smul_const_eq | null |
smul_const_le [Semiring K] [PartialOrder K]
[AddCommMonoid α] [PartialOrder α] [Module K α]
[PosSMulMono K α] (p : b ≤ c) {s : K} (hs : 0 ≤ s) :
s • b ≤ s • c :=
smul_le_smul_of_nonneg_left p hs | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smul_const_le | null |
smul_const_lt [Semiring K] [PartialOrder K]
[AddCommMonoid α] [PartialOrder α] [Module K α]
[PosSMulStrictMono K α] (p : b < c) {s : K} (hs : 0 < s) :
s • b < s • c :=
smul_lt_smul_of_pos_left p hs | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smul_const_lt | null |
smul_const_lt_weak [Semiring K] [PartialOrder K]
[AddCommMonoid α] [PartialOrder α] [Module K α]
[PosSMulMono K α] (p : b < c) {s : K} (hs : 0 ≤ s) :
s • b ≤ s • c :=
smul_le_smul_of_nonneg_left p.le hs
/-! ### Division -/ | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smul_const_lt_weak | null |
div_eq_const [Div α] (p : a = b) (c : α) : a / c = b / c := p ▸ rfl | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | div_eq_const | null |
div_le_const [Semifield α] [LinearOrder α] [IsStrictOrderedRing α]
(p : b ≤ c) {a : α} (ha : 0 ≤ a) : b / a ≤ c / a :=
div_le_div_of_nonneg_right p ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | div_le_const | null |
div_lt_const [Semifield α] [LinearOrder α] [IsStrictOrderedRing α]
(p : b < c) {a : α} (ha : 0 < a) : b / a < c / a :=
div_lt_div_of_pos_right p ha | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | div_lt_const | null |
div_lt_const_weak [Semifield α] [LinearOrder α] [IsStrictOrderedRing α]
(p : b < c) {a : α} (ha : 0 ≤ a) :
b / a ≤ c / a :=
div_le_div_of_nonneg_right p.le ha
/-! ### Lemmas constructing the reduction of a goal to a specified built-up hypothesis -/ | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | div_lt_const_weak | null |
eq_of_eq [Add α] [IsRightCancelAdd α] (p : (a : α) = b) (H : a' + b = b' + a) :
a' = b' := by
rw [p] at H
exact add_right_cancel H | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | eq_of_eq | null |
le_of_le [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α]
(p : (a : α) ≤ b) (H : a' + b ≤ b' + a) :
a' ≤ b' := by
rw [← add_le_add_iff_right b]
apply H.trans
apply add_le_add_left p | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | le_of_le | null |
le_of_eq [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α]
(p : (a : α) = b) (H : a' + b ≤ b' + a) :
a' ≤ b' := by
rwa [p, add_le_add_iff_right] at H | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | le_of_eq | null |
le_of_lt [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α]
(p : (a : α) < b) (H : a' + b ≤ b' + a) :
a' ≤ b' :=
le_of_le p.le H | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | le_of_lt | null |
lt_of_le [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α]
(p : (a : α) ≤ b) (H : a' + b < b' + a) :
a' < b' := by
rw [← add_lt_add_iff_right b]
apply H.trans_le
apply add_le_add_left p | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | lt_of_le | null |
lt_of_eq [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α]
(p : (a : α) = b) (H : a' + b < b' + a) :
a' < b' := by
rwa [p, add_lt_add_iff_right] at H | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | lt_of_eq | null |
lt_of_lt [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α]
(p : (a : α) < b) (H : a' + b ≤ b' + a) :
a' < b' := by
rw [← add_lt_add_iff_right b]
apply H.trans_lt
apply add_lt_add_left p
alias ⟨eq_rearrange, _⟩ := sub_eq_zero | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | lt_of_lt | null |
le_rearrange {α : Type*} [AddCommGroup α] [PartialOrder α] [IsOrderedAddMonoid α]
{a b : α} (h : a - b ≤ 0) : a ≤ b :=
sub_nonpos.mp h | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | le_rearrange | null |
lt_rearrange {α : Type*} [AddCommGroup α] [PartialOrder α] [IsOrderedAddMonoid α]
{a b : α} (h : a - b < 0) : a < b :=
sub_neg.mp h | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | lt_rearrange | null |
eq_of_add_pow [Ring α] [NoZeroDivisors α] (n : ℕ) (p : (a : α) = b)
(H : (a' - b') ^ n - (a - b) = 0) : a' = b' := by
rw [← sub_eq_zero] at p ⊢; apply pow_eq_zero (n := n); rwa [sub_eq_zero, p] at H | theorem | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | eq_of_add_pow | null |
addRelRelData : Ineq → Ineq → Name
| eq, eq => ``add_eq_eq
| eq, le => ``add_eq_le
| eq, lt => ``add_eq_lt
| le, eq => ``add_le_eq
| le, le => ``add_le_add
| le, lt => ``add_lt_add_of_le_of_lt
| lt, eq => ``add_lt_eq
| lt, le => ``add_lt_add_of_lt_of_le
| lt, lt => ``add_lt_add | def | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | addRelRelData | Given two (in)equalities, look up the lemma to add them. |
protected WithStrictness : Type
| eq : Ineq.WithStrictness
| le : Ineq.WithStrictness
| lt (strict : Bool) : Ineq.WithStrictness | inductive | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | WithStrictness | Finite inductive type extending `Mathlib.Ineq`: a type of inequality (`eq`, `le` or `lt`),
together with, in the case of `lt`, a Boolean, typically representing the strictness (< or ≤) of
some other inequality. |
mulRelConstData : Ineq.WithStrictness → Name
| .eq => ``mul_eq_const
| .le => ``mul_le_const
| .lt true => ``mul_lt_const
| .lt false => ``mul_lt_const_weak | def | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mulRelConstData | Given an (in)equality, look up the lemma to left-multiply it by a constant. If relevant, also
take into account the degree of positivity which can be proved of the constant: strict or
non-strict. |
mulConstRelData : Ineq.WithStrictness → Name
| .eq => ``mul_const_eq
| .le => ``mul_const_le
| .lt true => ``mul_const_lt
| .lt false => ``mul_const_lt_weak | def | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | mulConstRelData | Given an (in)equality, look up the lemma to right-multiply it by a constant. If relevant, also
take into account the degree of positivity which can be proved of the constant: strict or
non-strict. |
smulRelConstData : Ineq.WithStrictness → Name
| .eq => ``smul_eq_const
| .le => ``smul_le_const
| .lt true => ``smul_lt_const
| .lt false => ``smul_lt_const_weak | def | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smulRelConstData | Given an (in)equality, look up the lemma to left-scalar-multiply it by a constant (scalar).
If relevant, also take into account the degree of positivity which can be proved of the constant:
strict or non-strict. |
smulConstRelData : Ineq.WithStrictness → Name
| .eq => ``smul_const_eq
| .le => ``smul_const_le
| .lt true => ``smul_const_lt
| .lt false => ``smul_const_lt_weak | def | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | smulConstRelData | Given an (in)equality, look up the lemma to right-scalar-multiply it by a constant (vector).
If relevant, also take into account the degree of positivity which can be proved of the constant:
strict or non-strict. |
divRelConstData : Ineq.WithStrictness → Name
| .eq => ``div_eq_const
| .le => ``div_le_const
| .lt true => ``div_lt_const
| .lt false => ``div_lt_const_weak | def | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | divRelConstData | Given an (in)equality, look up the lemma to divide it by a constant. If relevant, also take
into account the degree of positivity which can be proved of the constant: strict or non-strict. |
relImpRelData : Ineq → Ineq → Option (Name × Ineq)
| eq, eq => some (``eq_of_eq, eq)
| eq, le => some (``Tactic.LinearCombination.le_of_eq, le)
| eq, lt => some (``lt_of_eq, lt)
| le, eq => none
| le, le => some (``le_of_le, le)
| le, lt => some (``lt_of_le, lt)
| lt, eq => none
| lt, le => some (``Tactic.LinearCombination.le_of_lt, le)
| lt, lt => some (``lt_of_lt, le) | def | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | relImpRelData | Given two (in)equalities `P` and `Q`, look up the lemma to deduce `Q` from `P`, and the relation
appearing in the side condition produced by this lemma. |
rearrangeData : Ineq → Name
| eq => ``eq_rearrange
| le => ``le_rearrange
| lt => ``lt_rearrange | def | Tactic | [
"Mathlib.Algebra.Field.Defs",
"Mathlib.Algebra.Order.Module.Defs",
"Mathlib.Data.Ineq"
] | Mathlib/Tactic/LinearCombination/Lemmas.lean | rearrangeData | Given an (in)equality, look up the lemma to move everything to the LHS. |
CommandStart.endPos (stx : Syntax) : Option String.Pos :=
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 | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | CommandStart.endPos | 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. |
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 | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | mkFormatError | 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
/-- 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
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`. |
pushFormatError (fs : Array FormatError) (f : FormatError) : Array FormatError :=
if fs.isEmpty then fs.push f else
let back := fs.back!
if back.msg != f.msg || back.srcNat - back.length != f.srcNat then fs.push f else
fs.pop.push {back with length := back.length + f.length, srcStartPos := f.srcEndPos} | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | pushFormatError | 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`. |
partial
parallelScanAux (as : Array FormatError) (L M : String) : Array FormatError :=
if M.trim.isEmpty then as else
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
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.get 0, M.get 0 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
pushFormatError as (mkFormatError ls ms "Oh no! (Unreachable?)")
@[inherit_doc parallelScanAux] | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | parallelScanAux | 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.) |
parallelScan (src fmt : String) : Array FormatError :=
parallelScanAux ∅ src fmt | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | parallelScan | null |
unlintedNodes := #[
``«term{_:_//_}»,
`«term{_}»,
``«term{}»,
`Mathlib.Meta.setBuilder,
`str,
``«term_::_»,
``«term¬_»,
``Parser.Command.declId,
`Mathlib.Tactic.superscriptTerm, `Mathlib.Tactic.subscript,
`Bundle.termπ__,
`Finset.«term_#_»,
``Parser.Command.docComment,
``Parser.Term.doubleQuotedName,
] | abbrev | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | unlintedNodes | `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. |
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
| curr, .atom info "where" =>
if let some trail := info.getRangeWithTrailing? then
curr.insert trail
else
curr
| curr, _ => curr | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | getUnlintedRanges | 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`. |
isOutside (rgs : Std.HashSet String.Range) (rg : String.Range) : Bool :=
rgs.all fun {start := a, stop := b} ↦ !(a ≤ rg.start && rg.stop ≤ b) | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | isOutside | 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. |
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 | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | mkWindow | `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! |
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 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."
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 - s.srcEndPos
let rg : String.Range := ⟨center, center + s.srcEndPos - s.srcStartPos + ⟨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\
... | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/CommandStart.lean | commandStartLinter | null |
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?)) | def | Tactic | [
"Std.Time.Format",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/DeprecatedModule.lean | addModuleDeprecation | 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. |
@[inherit_doc Mathlib.Linter.linter.deprecated.module]
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 || (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 | def | Tactic | [
"Std.Time.Format",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/DeprecatedModule.lean | deprecated.moduleLinter | null |
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
some default
| _ => none | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/DeprecatedSyntaxLinter.lean | getSetOptionMaxHeartbeatsComment | 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`. |
isDecideNative (stx : Syntax ) : Bool :=
match stx with
| .node _ ``Lean.Parser.Tactic.decide args =>
let config := args[1]![0]
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/DeprecatedSyntaxLinter.lean | isDecideNative | 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). |
partial
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) =>
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/DeprecatedSyntaxLinter.lean | getDeprecatedSyntax | `getDeprecatedSyntax t` returns all usages of deprecated syntax in the input syntax `t`. |
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
(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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/DeprecatedSyntaxLinter.lean | deprecatedSyntaxLinter | 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`) |
findImports (path : System.FilePath) : IO (Array Lean.Name) := do
return (← Lean.parseImports' (← IO.FS.readFile path) path.toString).imports
|>.map (fun imp ↦ imp.module) |>.erase `Init | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | findImports | Parse all imports in a text file at `path` and return just their names:
this is just a thin wrapper around `Lean.parseImports'`.
Omit `Init` (which is part of the prelude). |
Lean.Name.findPrefix {α} (f : Name → Option α) (n : Name) : Option α := do
f n <|> match n with
| anonymous => none
| str n' _ => n'.findPrefix f
| num n' _ => n'.findPrefix f | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | Lean.Name.findPrefix | Find the longest prefix of `n` such that `f` returns `some` (or return `none` otherwise). |
Lean.Name.prefixes (n : Name) : NameSet :=
NameSet.insert (n := n) <| match n with
| anonymous => ∅
| str n' _ => n'.prefixes
| num n' _ => n'.prefixes | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | Lean.Name.prefixes | Make a `NameSet` containing all prefixes of `n`. |
Lean.Name.prefix? (n : Name) : Option Name :=
match n with
| anonymous => none
| str n' _ => some n'
| num n' _ => some n' | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | Lean.Name.prefix | Return the immediate prefix of `n` (if any). |
Lean.Name.collectPrefixes (ns : Array Name) : NameSet :=
ns.foldl (fun ns n => ns.append n.prefixes) ∅ | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | Lean.Name.collectPrefixes | Collect all prefixes of names in `ns` into a single `NameSet`. |
Lean.Name.prefixToName (p : Name) (ns : Array Name) : Option Name :=
ns.find? p.isPrefixOf | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | Lean.Name.prefixToName | Find a name in `ns` that starts with prefix `p`. |
Lean.Environment.importPath (env : Environment) (imported : Name) : Array Name := Id.run do
let mut result := #[]
let modData := env.header.moduleData
let modNames := env.header.moduleNames
if let some idx := env.getModuleIdx? imported then
let mut target := imported
for i in [idx.toNat + 1 : modData.size] do
if modData[i]!.imports.any (·.module == target) then
target := modNames[i]!
result := result.push modNames[i]!
return result | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | Lean.Environment.importPath | Find the dependency chain, starting at a module that imports `imported`, and ends with the
current module.
The path only contains the intermediate steps: it excludes `imported` and the current module. |
NamePrefixRel := NameMap NameSet | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | NamePrefixRel | The `directoryDependency` linter detects detects imports between directories that are supposed to be
independent. If this is the case, it emits a warning.
-/
register_option linter.directoryDependency : Bool := {
defValue := true
descr := "enable the directoryDependency linter"
}
namespace DirectoryDependency
/-- `NamePrefixRel` is a datatype for storing relations between name prefixes.
That is, `R : NamePrefixRel` is supposed to answer given names `(n₁, n₂)` whether there are any
prefixes `n₁'` of `n₁` and `n₂'` of `n₂` such that `n₁' R n₂'`.
The current implementation is a `NameMap` of `NameSet`s, testing each prefix of `n₁` and `n₂` in
turn. This can probably be optimized. |
insert (r : NamePrefixRel) (n₁ n₂ : Name) : NamePrefixRel :=
match r.find? n₁ with
| some ns => NameMap.insert r n₁ (ns.insert n₂)
| none => NameMap.insert r n₁ (.insert ∅ n₂) | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | insert | Make all names with prefix `n₁` related to names with prefix `n₂`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.