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 ⌀ |
|---|---|---|---|---|---|---|
ofArray (xs : Array (Name × Name)) : NamePrefixRel :=
xs.foldl (init := ∅)
fun r (n₁, n₂) => r.insert n₁ n₂ | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | ofArray | Convert an array of prefix pairs to a `NamePrefixRel`. |
find (r : NamePrefixRel) (n₁ n₂ : Name) : Option (Name × Name) :=
n₁.findPrefix fun n₁' => do
let ns ← r.find? n₁'
n₂.findPrefix fun n₂' =>
if ns.contains n₂' then
(n₁', n₂')
else
none | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | find | Get a prefix of `n₁` that is related to a prefix of `n₂`. |
findAny (r : NamePrefixRel) (n₁ : Name) (ns : Array Name) : Option (Name × Name) :=
let prefixes := Lean.Name.collectPrefixes ns
n₁.findPrefix fun n₁' => do
let ns ← r.find? n₁'
for n₂' in prefixes do
if ns.contains n₂' then
return (n₁', n₂')
else
pure ()
none | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | findAny | Get a prefix of `n₁` that is related to any prefix of the names in `ns`; return the prefixes.
This should be more efficient than iterating over all names in `ns` and calling `find`,
since it doesn't need to worry about overlapping prefixes. |
containsKey (r : NamePrefixRel) (n : Name) : Bool := NameMap.contains r n | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | containsKey | Does `r` contain any entries with key `n`? |
contains (r : NamePrefixRel) (n₁ n₂ : Name) : Bool := (r.find n₁ n₂).isSome | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | contains | Is a prefix of `n₁` related to a prefix of `n₂`? |
getAllLeft (r : NamePrefixRel) (n : Name) : NameSet := Id.run do
let matchingPrefixes := n.prefixes.filter (fun prf ↦ r.containsKey prf)
let mut allRules := NameSet.empty
for prefix_ in matchingPrefixes do
let some rules := r.find? prefix_ | unreachable!
allRules := allRules.append rules
allRules | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | getAllLeft | Look up all names `m` which are values of some prefix of `n` under this relation. |
allowedImportDirs : NamePrefixRel := .ofArray #[
(`MathlibTest.DirectoryDependencyLinter, `Mathlib.Lean),
(`MathlibTest.Header, `Mathlib),
(`MathlibTest.Header, `Aesop),
(`MathlibTest.Header, `ImportGraph),
(`MathlibTest.Header, `LeanSearchClient),
(`MathlibTest.Header, `Plausible),
(`MathlibTest.Header, `ProofWidgets),
(`MathlibTest.Header, `Qq),
(`MathlibTest.Header, `Batteries),
(`MathlibTest.Header, `Lake),
(`Mathlib.Util, `Batteries),
(`Mathlib.Util, `Mathlib.Lean),
(`Mathlib.Util, `Mathlib.Tactic),
(`Mathlib.Util.FormatTable, `Mathlib.Data.String.Defs),
(`Mathlib.Lean, `Batteries.CodeAction),
(`Mathlib.Lean, `Batteries.Tactic.Lint),
(`Mathlib.Lean, `Batteries),
(`Mathlib.Lean.Expr, `Mathlib.Util),
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Util),
(`Mathlib.Lean.CoreM, `Mathlib.Tactic.ToExpr),
(`Mathlib.Lean.CoreM, `Mathlib.Util.WhatsNew),
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Tactic.Lemma),
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Tactic.TypeStar),
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Tactic.ToAdditive),
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Tactic), -- split this up further?
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Data), -- split this up further?
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Algebra.Notation),
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Data.Notation),
(`Mathlib.Lean.Meta.RefinedDiscrTree, `Mathlib.Data.Array),
(`Mathlib.Lean.Meta.CongrTheorems, `Mathlib.Data),
(`Mathlib.Lean.Meta.CongrTheorems, `Mathlib.Logic),
(`Mathlib.Lean.Meta.CongrTheorems, `Mathlib.Order.Defs),
(`Mathlib.Lean.Meta.CongrTheorems, `Mathlib.Tactic),
(`Mathlib.Lean.Expr.ExtraRecognizers, `Mathlib.Data),
(`Mathlib.Lean.Expr.ExtraRecognizers, `Mathlib.Order),
(`Mathlib.Lean.Expr.ExtraRecognizers, `Mathlib.Logic),
(`Mathlib.Lean.Expr.ExtraRecognizers, `Mathlib.Tactic),
(`Mathlib.Tactic.Linter, `Batteries),
(`Mathlib.Tactic.Linter, `ImportGraph),
(`Mathlib.Tactic.Linter, `Mathlib.Tactic.MinImports),
(`Mathlib.Tactic.Linter.TextBased, `Mathlib.Data.Nat.Notation),
(`Mathlib.Logic, `Batteries),
(`Mathlib.Logic, `Mathlib.Control),
(`Mathlib.Logic, `Mathlib.Lean),
(`Mathlib.Logic, `Mathlib.Util),
(`Mathlib.Logic, `Mathlib.Tactic),
(`Mathlib.Logic.Fin.Rotate, `Mathlib.Algebra.Group.Fin.Basic),
(`Mathlib.Logic, `Mathlib.Algebra.Notation),
(`Mathlib.Logic, `Mathlib.Algebra.NeZero),
(`Mathlib.Logic, `Mathlib.Data),
... | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | allowedImportDirs | `allowedImportDirs` relates module prefixes, specifying that modules with the first prefix
are only allowed to import modules in the second directory.
For directories which are low in the import hierarchy, this opt-out approach is both more ergonomic
(fewer updates needed) and needs less configuration.
We always allow imports of `Init`, `Lean`, `Std`, `Qq` and
`Mathlib.Init` (as well as their transitive dependencies.) |
forbiddenImportDirs : NamePrefixRel := .ofArray #[
(`Mathlib.Algebra.Notation, `Mathlib.Algebra),
(`Mathlib, `Mathlib.Deprecated),
(`MathlibTest.Header, `Mathlib.Deprecated),
(`Mathlib.Algebra, `Mathlib.AlgebraicGeometry),
(`Mathlib.Algebra, `Mathlib.Analysis),
(`Mathlib.Algebra, `Mathlib.Computability),
(`Mathlib.Algebra, `Mathlib.Condensed),
(`Mathlib.Algebra, `Mathlib.Geometry),
(`Mathlib.Algebra, `Mathlib.InformationTheory),
(`Mathlib.Algebra, `Mathlib.ModelTheory),
(`Mathlib.Algebra, `Mathlib.RepresentationTheory),
(`Mathlib.Algebra, `Mathlib.Testing),
(`Mathlib.AlgebraicGeometry, `Mathlib.AlgebraicTopology),
(`Mathlib.AlgebraicGeometry, `Mathlib.Analysis),
(`Mathlib.AlgebraicGeometry, `Mathlib.Computability),
(`Mathlib.AlgebraicGeometry, `Mathlib.Condensed),
(`Mathlib.AlgebraicGeometry, `Mathlib.InformationTheory),
(`Mathlib.AlgebraicGeometry, `Mathlib.MeasureTheory),
(`Mathlib.AlgebraicGeometry, `Mathlib.ModelTheory),
(`Mathlib.AlgebraicGeometry, `Mathlib.Probability),
(`Mathlib.AlgebraicGeometry, `Mathlib.RepresentationTheory),
(`Mathlib.AlgebraicGeometry, `Mathlib.Testing),
(`Mathlib.AlgebraicTopology, `Mathlib.AlgebraicGeometry),
(`Mathlib.AlgebraicTopology, `Mathlib.Computability),
(`Mathlib.AlgebraicTopology, `Mathlib.Condensed),
(`Mathlib.AlgebraicTopology, `Mathlib.FieldTheory),
(`Mathlib.AlgebraicTopology, `Mathlib.Geometry),
(`Mathlib.AlgebraicTopology, `Mathlib.InformationTheory),
(`Mathlib.AlgebraicTopology, `Mathlib.MeasureTheory),
(`Mathlib.AlgebraicTopology, `Mathlib.ModelTheory),
(`Mathlib.AlgebraicTopology, `Mathlib.NumberTheory),
(`Mathlib.AlgebraicTopology, `Mathlib.Probability),
(`Mathlib.AlgebraicTopology, `Mathlib.RepresentationTheory),
(`Mathlib.AlgebraicTopology, `Mathlib.SetTheory),
(`Mathlib.AlgebraicTopology, `Mathlib.Testing),
(`Mathlib.Analysis, `Mathlib.AlgebraicGeometry),
(`Mathlib.Analysis, `Mathlib.AlgebraicTopology),
(`Mathlib.Analysis, `Mathlib.Computability),
(`Mathlib.Analysis, `Mathlib.Condensed),
(`Mathlib.Analysis, `Mathlib.InformationTheory),
(`Mathlib.Analysis, `Mathlib.ModelTheory),
(`Mathlib.Analysis, `Mathlib.RepresentationTheory),
(`Mathlib.Analysis, `Mathlib.Testing),
(`Mathlib.CategoryTheory, `Mathlib.AlgebraicGeometry),
(`Mathlib.CategoryTheory, `Mathlib.Analysis),
(`Mathlib.CategoryTheory, `Mathlib.Computability),
(`Mathlib.CategoryTheory, `Mathlib.Condensed),
(`Mathlib.CategoryTheory, `Mathlib.Geometry),
(`Mathlib.CategoryTheory, `Mathlib.InformationTheory),
(`Mathlib.CategoryTheory, `Mathlib.MeasureTheory),
... | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | forbiddenImportDirs | `forbiddenImportDirs` relates module prefixes, specifying that modules with the first prefix
should not import modules with the second prefix (except if specifically allowed in
`overrideAllowedImportDirs`).
For example, ``(`Mathlib.Algebra.Notation, `Mathlib.Algebra)`` is in `forbiddenImportDirs` and
``(`Mathlib.Algebra.Notation, `Mathlib.Algebra.Notation)`` is in `overrideAllowedImportDirs`
because modules in `Mathlib/Algebra/Notation.lean` cannot import modules in `Mathlib.Algebra` that are
outside `Mathlib/Algebra/Notation.lean`. |
overrideAllowedImportDirs : NamePrefixRel := .ofArray #[
(`Mathlib.Algebra.Lie, `Mathlib.RepresentationTheory),
(`Mathlib.Algebra.Module.ZLattice, `Mathlib.Analysis),
(`Mathlib.Algebra.Notation, `Mathlib.Algebra.Notation),
(`Mathlib.Deprecated, `Mathlib.Deprecated),
(`Mathlib.LinearAlgebra.Complex, `Mathlib.Topology), -- Complex numbers are analysis/topology.
(`Mathlib.LinearAlgebra.Matrix, `Mathlib.Topology), -- For e.g. spectra.
(`Mathlib.LinearAlgebra.QuadraticForm, `Mathlib.Topology), -- For real/complex quadratic forms.
(`Mathlib.Topology.Algebra, `Mathlib.Algebra),
(`Mathlib.Topology.Compactification, `Mathlib.Geometry.Manifold)
] | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | overrideAllowedImportDirs | `overrideAllowedImportDirs` relates module prefixes, specifying that modules with the first
prefix are allowed to import modules with the second prefix, even if disallowed in
`forbiddenImportDirs`.
For example, ``(`Mathlib.Algebra.Notation, `Mathlib.Algebra)`` is in `forbiddenImportDirs` and
``(`Mathlib.Algebra.Notation, `Mathlib.Algebra.Notation)`` is in `overrideAllowedImportDirs`
because modules in `Mathlib/Algebra/Notation.lean` cannot import modules in `Mathlib.Algebra` that are
outside `Mathlib/Algebra/Notation.lean`. |
private checkBlocklist (env : Environment) (mainModule : Name) (imports : Array Name) : Option MessageData := Id.run do
match forbiddenImportDirs.findAny mainModule imports with
| some (n₁, n₂) => do
if let some imported := n₂.prefixToName imports then
if !overrideAllowedImportDirs.contains mainModule imported then
let mut msg := m!"Modules starting with {n₁} are not allowed to import modules starting with {n₂}. \
This module depends on {imported}\n"
for dep in env.importPath imported do
msg := msg ++ m!"which is imported by {dep},\n"
return some (msg ++ m!"which is imported by this module. \
(Exceptions can be added to `overrideAllowedImportDirs`.)")
else none
else
return some m!"Internal error in `directoryDependency` linter: this module claims to depend \
on a module starting with {n₂} but a module with that prefix was not found in the import graph."
| none => none
@[inherit_doc Mathlib.Linter.linter.directoryDependency] | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | checkBlocklist | Check if one of the imports `imports` to `mainModule` is forbidden by `forbiddenImportDirs`;
if so, return an error describing how the import transitively arises. |
directoryDependencyCheck (mainModule : Name) : CommandElabM (Array MessageData) := do
unless Linter.getLinterValue linter.directoryDependency (← getLinterOptions) do
return #[]
let env ← getEnv
let imports := env.allImportedModuleNames
let matchingPrefixes := mainModule.prefixes.filter (fun prf ↦ allowedImportDirs.containsKey prf)
if matchingPrefixes.isEmpty then
if let some msg := checkBlocklist env mainModule imports then return #[msg] else return #[]
else
let initImports := (← findImports ("Mathlib" / "Init.lean")).append
#[`Mathlib.Init, `Mathlib.Tactic.DeclarationNames]
let exclude := [
`Init, `Std, `Lean,
`Aesop, `Qq, `Plausible, `ImportGraph, `ProofWidgets, `LeanSearchClient
]
let importsToCheck := imports.filter (fun imp ↦ !exclude.any (·.isPrefixOf imp))
|>.filter (fun imp ↦ !matchingPrefixes.any (·.isPrefixOf imp))
|>.filter (!initImports.contains ·)
let allRules := allowedImportDirs.getAllLeft mainModule
let mut messages := #[]
for imported in importsToCheck do
if !allowedImportDirs.contains mainModule imported then
let importPath := env.importPath imported
let mut msg := m!"Module {mainModule} depends on {imported},\n\
but is only allowed to import modules starting with one of \
{allRules.toArray.qsort (·.toString < ·.toString)}.\n\
Note: module {imported}"
let mut superseded := false
match importPath.toList with
| [] => msg := msg ++ " is directly imported by this module"
| a :: rest =>
if !allowedImportDirs.contains mainModule a then
superseded := true
else
msg := msg ++ s!" is imported by {a},\n"
for dep in rest do
if !allowedImportDirs.contains mainModule dep then
superseded := true
break
msg := msg ++ m!"which is imported by {dep},\n"
msg := msg ++ m!"which is imported by this module."
msg := msg ++ "(Exceptions can be added to `allowedImportDirs`.)"
if !superseded then
messages := messages.push msg
return messages | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast"
] | Mathlib/Tactic/Linter/DirectoryDependency.lean | directoryDependencyCheck | null |
@[inherit_doc Mathlib.Linter.linter.docPrime]
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
if (stx.find? (·.isOfKind ``Lean.Parser.Command.private)).isSome then return
if (stx.find? (·.isOfKind ``Lean.Parser.Command.example)).isSome then return
let docstring := stx[0][0]
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
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/DocPrime.lean | docPrimeLinter | null |
getDeclModifiers : Syntax → Array Syntax
| s@(.node _ kind args) =>
(if kind == ``Parser.Command.declModifiers then #[s] else #[]) ++ args.flatMap getDeclModifiers
| _ => #[] | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/DocString.lean | getDeclModifiers | 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. |
deindentString (currIndent : Nat) (docString : String) : String :=
let indent : String := ⟨'\n' :: List.replicate currIndent ' '⟩
docString.replace indent " " | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/DocString.lean | deindentString | 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. |
@[inherit_doc Mathlib.Linter.linter.style.docString]
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
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.
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
let startSubstring := match docStx with
| .node _ _ #[(.atom si ..), _] => si.getTrailing?.getD default
| _ => default
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
let endRange (n : Nat) : Syntax := .ofRange
{start := docStx.getTailPos?.get! - ⟨n⟩, stop := docStx.getTailPos?.get! - ⟨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 | def | Tactic | [
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/DocString.lean | docStringLinter | null |
goalsTargetedBy (t : TacticInfo) : List MVarId :=
t.goalsBefore.filter (·.name ∉ t.goalsAfter.map (·.name)) | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | goalsTargetedBy | 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 goals that a tactic modifies 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. |
goalsCreatedBy (t : TacticInfo) : List MVarId :=
t.goalsAfter.filter (·.name ∉ t.goalsBefore.map (·.name)) | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | goalsCreatedBy | `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`. |
partial
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | extractCtxAndGoals | `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. |
Stained
| name : Name → Stained
| goal : Stained
| wildcard : Stained
deriving Repr, Inhabited, DecidableEq, Hashable | inductive | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | Stained | `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 (`*`). |
partial
toStained : Syntax → Std.HashSet Stained
| .node _ _ arg => (arg.map toStained).foldl (.union) {}
| .ident _ _ val _ => {.name val}
| .atom _ val => match val with
| "*" => {.wildcard}
| "⊢" => {.goal}
| "|" => {.goal}
| _ => {}
| _ => {} | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | toStained | 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
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | getStained | `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. |
getStained! (stx : Syntax) (all? : Syntax → Bool := fun _ ↦ false) : Std.HashSet Stained :=
let out := getStained stx all?
if out.size == 0 then {.goal} else out | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | getStained | `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. |
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) | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | Stained.toFMVarId | `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`). |
stoppers : Std.HashSet Name :=
{ -- "properly stopper tactics": the effect of these tactics is to return a normal form
``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,
`finiteness_nonterminal,
``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 } | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | stoppers | `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. |
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.Module.tacticModule,
`Mathlib.Tactic.FieldSimp.fieldSimp,
``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,
`cfcTac,
`cfcZeroTac,
`cfcContTac,
`tacticContinuity,
`tacticMeasurability,
`finiteness,
`finiteness?,
`Mathlib.Tactic.Tauto.tauto,
`Lean.Parser.Tactic.split,
`Mathlib.Tactic.splitIfs } | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | flexible | `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`, `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`. |
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | usesGoal | 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. |
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.
-/ | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | getFVarIdCandidates | `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)`. |
persistFVars (fv : FVarId) (before after : LocalContext) : FVarId :=
let ldecl := (before.find? fv).getD default
(getFVarIdCandidates fv ldecl.userName after).getD 0 default | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | persistFVars | `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"). |
reallyPersist
(fmvars : Array (FVarId × MVarId)) (mvs0 mvs1 : List MVarId) (ctx0 ctx1 : MetavarContext) :
Array (FVarId × MVarId) := Id.run do
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | reallyPersist | `reallyPersist` converts an array of pairs `(fvar, mvar)` to another array of the same type. |
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))
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)
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/FlexibleLinter.lean | flexibleLinter | The main implementation of the flexible linter. |
what : False := sorry
attribute [simp] what in | theorem | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/GlobalAttributeIn.lean | what | null |
who {x y : Nat} : x = y := sorry
attribute [ext] who in | theorem | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/GlobalAttributeIn.lean | who | null |
getLinterGlobalAttributeIn (o : LinterOptions) : Bool :=
getLinterValue linter.globalAttributeIn o | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/GlobalAttributeIn.lean | getLinterGlobalAttributeIn | 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. |
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/GlobalAttributeIn.lean | getGlobalAttributesIn | `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`. |
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/GlobalAttributeIn.lean | globalAttributeIn | 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`. |
private partial 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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/HashCommandLinter.lean | withSetOptionIn' | 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 allowed_commands : Std.HashSet String := { "#adaptation_note" } | abbrev | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/HashCommandLinter.lean | allowed_commands | `allowed_commands` is the `HashSet` of `#`-commands that are allowed in 'Mathlib'. |
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.get ⟨0⟩ == '#' && ! 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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/HashCommandLinter.lean | hashCommandLinter | 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. |
isHave? : Syntax → Bool
| .node _ ``Lean.Parser.Tactic.tacticHave__ _ => true
| _ => false | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/HaveLetLinter.lean | isHave | 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. |
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) | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/HaveLetLinter.lean | InfoTree.foldInfoM | a monadic version of `Lean.Elab.InfoTree.foldInfo`.
Used to infer types inside a `CommandElabM`. |
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) | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/HaveLetLinter.lean | toFormat_propTypes | 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. |
partial
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? ·)
let lc := mvdecls.toArray.getMax? (·.index < ·.index) |>.getD default |>.lctx
let oldMvdecls := i.goalsBefore.filterMap (mctx.decls.find? ·)
let oldFVars := (oldMvdecls.map (·.lctx.decls.toList.reduceOption)).flatten.map (·.fvarId)
let newDecls := lc.decls.toList.reduceOption.filter (! oldFVars.contains ·.fvarId)
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}")) | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/HaveLetLinter.lean | nonPropHaves | returns the `have` syntax whose corresponding hypothesis does not have Type `Prop` and
also a `Format`ted version of the corresponding Type. |
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 | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/HaveLetLinter.lean | haveLetLinter | The main implementation of the `have` vs `let` linter. |
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` | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | firstNonImport | `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?`. |
parseUpToHere (pos : String.Pos) (post : String := "") : CommandElabM Syntax := do
let upToHere : Substring := { str := (← getFileMap).source, startPos := ⟨0⟩, stopPos := pos }
Parser.testParseModule (← getEnv) "linter.style.header" (upToHere.toString ++ post) | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | parseUpToHere | `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! |
toSyntax (s pattern : String) (offset : String.Pos := 0) : Syntax :=
let beg := ((s.splitOn pattern).getD 0 "").endPos + offset
let fin := (((s.splitOn pattern).getD 0 "") ++ pattern).endPos + offset
mkAtomFrom (.ofRange ⟨beg, fin⟩) pattern | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | toSyntax | `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`. |
authorsLineChecks (line : String) (offset : String.Pos) : Array (Syntax × String) :=
Id.run do
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.")
return stxs | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | authorsLineChecks | 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. |
copyrightHeaderChecks (copyright : String) : Array (Syntax × String) := Id.run do
let preprocessCopyright := (copyright.replace ",\n " ", ").replace ",\n" ","
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 =>
match openComment, closeComment with
| "/-", "-/" => output := output
| "/-", _ =>
output := output.push (toSyntax copyright closeComment, s!"{stdText "-/"}")
| _, _ =>
output := output.push (toSyntax copyright openComment, s!"{stdText ("/".push '-')}")
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'")
if !copyrightAuthor.endsWith copStop then
output := output.push
(toSyntax copyright (copyrightAuthor.takeRight copStop.length),
s!"Copyright line should end with '. All rights reserved.'")
let authorsLines := authorsLines.dropLast
if authorsLines.length == 0 then
output := output.push (toSyntax copyright "-/", s!"Copyright too short!")
else
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 | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | copyrightHeaderChecks | 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. |
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 | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | isInMathlib | `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. |
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." | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | broadImportsCheck | `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
```
/-
Copyright ...
Apache ...
Authors ...
-/
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}`. |
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 | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | duplicateImportsCheck | 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. |
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
inMathlibRef.set (some val)
return val
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
if mainModule == `Mathlib then return
let fm ← getFileMap
let md := (getMainModuleDoc (← getEnv)).toArray
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
let upToStx ← parseUpToHere firstDocModPos <|> (do
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
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
| _ => ""
if mainModule != `Mathlib.Init then
for (stx, m) in copyrightHeaderChecks copyright do
Linter.logLint linter.style.header stx m!"* '{stx.getAtomVal}':\n{m}\n"
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
... | def | Tactic | [
"Lean.Elab.Command",
"Lean.Elab.ParseImportsFast",
"Mathlib.Tactic.Linter.DirectoryDependency",
"statements*",
"statements*"
] | Mathlib/Tactic/Linter/Header.lean | headerLinter | null |
@[env_linter] structureInType : Linter where
noErrorsFound := "no structures that should be in Prop found."
errorsFound := "FOUND STRUCTURES THAT SHOULD BE IN PROP."
test declName := do
unless isStructure (← getEnv) declName do return none
let isProp ← forallTelescopeReducing (← inferType (← mkConstWithLevelParams declName))
fun _ ty ↦ return ty == .sort .zero
if isProp then return none
let projs := (getStructureInfo? (← getEnv) declName).get!.fieldNames
if projs.isEmpty then return none -- don't flag empty structures
let allProofs ← projs.allM (do isProof <| ← mkConstWithLevelParams <| declName ++ ·)
unless allProofs do return none
return m!"all fields are propositional but the structure isn't." | def | Tactic | [
"Batteries.Tactic.Lint",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Lint.lean | structureInType | Linter that checks whether a structure should be in Prop. |
@[env_linter] deprecatedNoSince : Linter where
noErrorsFound := "no `deprecated` tags without `since` dates."
errorsFound := "FOUND `deprecated` tags without `since` dates."
test declName := do
let some info := Lean.Linter.deprecatedAttr.getParam? (← getEnv) declName | return none
match info.since? with
| some _ => return none -- TODO: enforce `YYYY-MM-DD` format
| none => return m!"`deprecated` attribute without `since` date" | def | Tactic | [
"Batteries.Tactic.Lint",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Lint.lean | deprecatedNoSince | Linter that check that all `deprecated` tags come with `since` dates. |
@[inherit_doc linter.dupNamespace]
dupNamespace : Linter where run := withSetOptionIn fun stx ↦ do
if getLinterValue linter.dupNamespace (← getLinterOptions) then
let mut aliases := #[]
if let some exp := stx.find? (·.isOfKind `Lean.Parser.Command.export) then
aliases ← getAliasSyntax exp
for id in (← getNamesFrom (stx.getPos?.getD default)) ++ aliases do
let declName := id.getId
if declName.hasMacroScopes || isPrivateName declName then continue
let nm := declName.components
let some (dup, _) := nm.zip (nm.tailD []) |>.find? fun (x, y) ↦ x == y
| continue
Linter.logLint linter.dupNamespace id
m!"The namespace '{dup}' is duplicated in the declaration '{declName}'"
initialize addLinter dupNamespace | def | Tactic | [
"Batteries.Tactic.Lint",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Lint.lean | dupNamespace | null |
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 | structure | Tactic | [
"ImportGraph.Imports",
"Mathlib.Tactic.MinImports"
] | Mathlib/Tactic/Linter/MinImports.lean | ImportState | `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. |
importsBelow (tc : NameMap NameSet) (ms : NameSet) : NameSet :=
ms.foldl (·.append <| tc.getD · default) ms
@[inherit_doc Mathlib.Linter.linter.minImports]
macro "#import_bumps" : command => `(
run_cmd logInfo "Counting imports from here."
set_option Elab.async false
set_option linter.minImports true)
@[inherit_doc Mathlib.Linter.linter.minImports] | def | Tactic | [
"ImportGraph.Imports",
"Mathlib.Tactic.MinImports"
] | Mathlib/Tactic/Linter/MinImports.lean | importsBelow | `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`. |
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
if (← minImportsRef.get).transClosure.isNone then
minImportsRef.modify ({· with transClosure := env.importGraph.transitiveClosure})
let impState ← minImportsRef.get
let (importsSoFar, oldCumulImps) := (impState.minImports, impState.importSize)
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
let fname ← getFileName
let contents ← IO.FS.readFile fname
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 !newImps.isEmpty then
let withImport := (newImps.toArray.qsort Name.lt).map (s!"import {·}")
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 ·)
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\
... | def | Tactic | [
"ImportGraph.Imports",
"Mathlib.Tactic.MinImports"
] | Mathlib/Tactic/Linter/MinImports.lean | minImportsLinter | null |
exclusions : Std.HashSet SyntaxNodeKind := .ofArray #[
``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,
`Batteries.Tactic.tacticSwap,
``Lean.Parser.Tactic.rotateLeft,
``Lean.Parser.Tactic.rotateRight,
``Lean.Parser.Tactic.skip,
`Batteries.Tactic.«tacticOn_goal-_=>_»,
`Mathlib.Tactic.«tacticSwap_var__,,»,
``Lean.Parser.Tactic.tacticRepeat_,
``Lean.Parser.Tactic.tacticTry_,
``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_
] | abbrev | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/Multigoal.lean | exclusions | 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. |
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.focus,
``Lean.Parser.Tactic.failIfSuccess,
`Mathlib.Tactic.successIfFailWithMsg
] | abbrev | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/Multigoal.lean | ignoreBranch | 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`. |
partial
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 #[]
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 | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/Multigoal.lean | getManyGoals | `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. |
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/Multigoal.lean | multiGoalLinter | null |
foo : True := by
obtain := trivial
obtain h := trivial
obtain : True := trivial
obtain h : True := trivial
obtain : True
· trivial
obtain h : True
· trivial
```
We allow the first four (since an explicit proof is provided), but lint against the last two. | theorem | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/OldObtain.lean | foo | null |
isObtainWithoutProof : Syntax → Bool
| `(tactic|obtain : $_type) | `(tactic|obtain $_pat : $_type) => true
| _ => false | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/OldObtain.lean | isObtainWithoutProof | Whether a syntax element is an `obtain` tactic call without a provided proof. |
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 | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Tactic.Linter.Header"
] | Mathlib/Tactic/Linter/OldObtain.lean | oldObtainLinter | 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 |
polishPP (s : String) : String :=
let s := s.split (·.isWhitespace)
(" ".intercalate (s.filter (!·.isEmpty)))
|>.replace "/-!" "/-! "
|>.replace "``` " "``` " -- avoid losing an existing space after the triple back-ticks
|>.replace "`` " "``" -- weird pp ```#eval ``«Nat»``` pretty-prints as ```#eval `` «Nat»```
|>.replace "notation3(" "notation3 ("
|>.replace "notation3\"" "notation3 \"" | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/PPRoundtrip.lean | polishPP | The "ppRoundtrip" linter emits a warning when the syntax of a command differs substantially
from the pretty-printed version of itself.
The linter makes an effort to start the highlighting at the first difference.
However, it may not always be successful.
It also prints both the source code and the "expected code" in a 5-character radius from
the first difference.
-/
register_option linter.ppRoundtrip : Bool := {
defValue := false
descr := "enable the ppRoundtrip linter"
}
/-- `polishPP s` takes as input a `String` `s`, assuming that it is the output of
pretty-printing a lean command.
The main intent is to convert `s` to a reasonable candidate for a desirable source code format.
The function first replaces consecutive whitespace sequences into a single space (` `), in an
attempt to side-step line-break differences.
After that, it applies some pre-emptive changes:
* doc-module beginnings tend to have some whitespace following them, so we add a space back in;
* name quotations such as ``` ``Nat``` get pretty-printed as ``` `` Nat```, so we remove a space
after double back-ticks, but take care of adding one more for triple (or more) back-ticks;
* `notation3` is not followed by a pretty-printer space, so we add it here (https://github.com/leanprover-community/mathlib4/pull/15515). |
polishSource (s : String) : String × Array Nat :=
let split := s.split (· == '\n')
let preWS := split.foldl (init := #[]) fun p q =>
let txt := q.trimLeft.length
(p.push (q.length - txt)).push txt
let preWS := preWS.eraseIdxIfInBounds 0
let s := (split.map .trimLeft).filter (· != "")
(" ".intercalate (s.filter (!·.isEmpty)), preWS) | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/PPRoundtrip.lean | polishSource | `polishSource s` is similar to `polishPP s`, but expects the input to be actual source code.
For this reason, `polishSource s` performs more conservative changes:
it only replace all whitespace starting from a linebreak (`\n`) with a single whitespace. |
posToShiftedPos (lths : Array Nat) (diff : Nat) : Nat := Id.run do
let mut (ws, noWS) := (diff, 0)
for con in [:lths.size / 2] do
let curr := lths[2 * con]!
if noWS + curr < diff then
noWS := noWS + curr
ws := ws + lths[2 * con + 1]!
else
break
return ws | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/PPRoundtrip.lean | posToShiftedPos | `posToShiftedPos lths diff` takes as input an array `lths` of natural numbers,
and one further natural number `diff`.
It adds up the elements of `lths` occupying the odd positions, as long as the sum of the
elements in the even positions does not exceed `diff`.
It returns the sum of the accumulated odds and `diff`.
This is useful to figure out the difference between the output of `polishSource s` and `s` itself.
It plays a role similar to the `fileMap`. |
zoomString (str : String) (centre offset : Nat) : Substring :=
{ str := str, startPos := ⟨centre - offset⟩, stopPos := ⟨centre + offset⟩ } | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/PPRoundtrip.lean | zoomString | `zoomString str centre offset` returns the substring of `str` consisting of the `offset`
characters around the `centre`th character. |
capSourceInfo (s : SourceInfo) (p : Nat) : SourceInfo :=
match s with
| .original leading pos trailing endPos =>
.original leading pos {trailing with stopPos := ⟨min endPos.1 p⟩} ⟨min endPos.1 p⟩
| .synthetic pos endPos canonical =>
.synthetic pos ⟨min endPos.1 p⟩ canonical
| .none => s | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/PPRoundtrip.lean | capSourceInfo | `capSourceInfo s p` "shortens" all end-position information in the `SourceInfo` `s` to be
at most `p`, trimming down also the relevant substrings. |
partial
capSyntax (stx : Syntax) (p : Nat) : Syntax :=
match stx with
| .node si k args => .node (capSourceInfo si p) k (args.map (capSyntax · p))
| .atom si val => .atom (capSourceInfo si p) (val.take p)
| .ident si r v pr => .ident (capSourceInfo si p) { r with stopPos := ⟨min r.stopPos.1 p⟩ } v pr
| s => s | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/PPRoundtrip.lean | capSyntax | `capSyntax stx p` applies `capSourceInfo · s` to all `SourceInfo`s in all
`node`s, `atom`s and `ident`s contained in `stx`.
This is used to trim away all "fluff" that follows a command: comments and whitespace after
a command get removed with `capSyntax stx stx.getTailPos?.get!`. |
@[inherit_doc Mathlib.Linter.linter.ppRoundtrip]
ppRoundtrip : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.ppRoundtrip (← getLinterOptions) do
return
if (← MonadState.get).messages.hasErrors then
return
let stx := capSyntax stx (stx.getTailPos?.getD default).1
let origSubstring := stx.getSubstring?.getD default
let (real, lths) := polishSource origSubstring.toString
let fmt ← (liftCoreM do PrettyPrinter.ppCategory `command stx <|> (do
Linter.logLint linter.ppRoundtrip stx
m!"The ppRoundtrip linter had some parsing issues: \
feel free to silence it with `set_option linter.ppRoundtrip false in` \
and report this error!"
return real))
let st := polishPP fmt.pretty
if st != real then
let diff := real.firstDiffPos st
let pos := posToShiftedPos lths diff.1 + origSubstring.startPos.1
let f := origSubstring.str.drop (pos)
let extraLth := (f.takeWhile (· != st.get diff)).length
let srcCtxt := zoomString real diff.1 5
let ppCtxt := zoomString st diff.1 5
Linter.logLint linter.ppRoundtrip (.ofRange ⟨⟨pos⟩, ⟨pos + extraLth + 1⟩⟩)
m!"source context\n'{srcCtxt}'\n'{ppCtxt}'\npretty-printed context"
initialize addLinter ppRoundtrip | def | Tactic | [
"Lean.Elab.Command",
"Mathlib.Init"
] | Mathlib/Tactic/Linter/PPRoundtrip.lean | ppRoundtrip | null |
parseSetOption : Syntax → Option Name
| `(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 | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | parseSetOption | 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. |
isSetOption : Syntax → Bool :=
fun stx ↦ parseSetOption stx matches some _name | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | isSetOption | Whether a given piece of syntax is a `set_option` command, tactic or term. |
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\
example : ... := ...\n```"
initialize addLinter setOptionLinter | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | setOptionLinter | 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.) |
isCDot? : Syntax → Bool
| .node _ ``cdotTk #[.node _ `patternIgnore #[.node _ _ #[.atom _ v]]] => v == "·"
| .node _ ``Lean.Parser.Term.cdot #[.atom _ v, _] => v == "·"
| _ => false | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | isCDot | 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 `·`. |
partial
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
|_ => #[] | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | findCDot | `findCDot stx` extracts from `stx` the syntax nodes of `kind` `Lean.Parser.Term.cdot` or `cdotTk`. |
unwanted_cdot (stx : Syntax) : Array Syntax :=
(findCDot stx).filter (!isCDot? ·) | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | unwanted_cdot | `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. |
@[inherit_doc linter.style.cdot]
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'."
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 | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | cdotLinter | null |
partial
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 | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | findDollarSyntax | 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` `$`. |
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 | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | dollarSyntaxLinter | null |
partial
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 | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | findLambdaSyntax | 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`. |
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 | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | lambdaSyntaxLinter | null |
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 | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | extractOpenNames | 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. |
openClassicalLinter : Linter where run stx := do
unless getLinterValue linter.style.openClassical (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
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 | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | openClassicalLinter | null |
@[inherit_doc Mathlib.Linter.linter.style.show]
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 | def | Tactic | [
"Lean.Elab.Command",
"Lean.Server.InfoUtils",
"Mathlib.Tactic.Linter.Header",
"Mathlib.Tactic.DeclarationNames"
] | Mathlib/Tactic/Linter/Style.lean | showLinter | null |
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 | inductive | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | BroadImports | Different kinds of "broad imports" that are linted against. |
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 | inductive | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | ErrorFormat | 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 |
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" | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | StyleError.errorMessage | Create the underlying error message for a given `StyleError`. |
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 | structure | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | ErrorContext | 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. |
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 | inductive | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | ComparisonResult | 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. |
compare (existing new : ErrorContext) : ComparisonResult :=
if existing.path.components != new.path.components then ComparisonResult.Different
else
if existing.error == new.error then ComparisonResult.Comparable else ComparisonResult.Different | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | compare | 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. |
ErrorContext.find?_comparable (e : ErrorContext) (exceptions : Array ErrorContext) :
Option ErrorContext :=
(exceptions).find? (fun new ↦ compare e new == ComparisonResult.Comparable) | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | ErrorContext.find | Find the first style exception in `exceptions` (if any) which covers a style exception `e`. |
outputMessage (errctx : ErrorContext) (style : ErrorFormat) : String :=
let errorMessage := errctx.error.errorMessage
match style with
| ErrorFormat.github =>
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 =>
s!"{errctx.path} : line {errctx.lineNumber} : {errctx.error.errorCode} : {errorMessage}"
| ErrorFormat.humanReadable =>
s!"error: {errctx.path}:{errctx.lineNumber}: {errorMessage}" | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | outputMessage | 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. |
parse?_errorContext (line : String) : Option ErrorContext := Id.run do
let parts := line.split (· == ' ')
match parts with
| filename :: ":" :: "line" :: lineNumber :: ":" :: errorCode :: ":" :: _errorMessage =>
let path := mkFilePath (filename.split (FilePath.pathSeparators.contains ·))
let err : Option StyleError := match errorCode with
| "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
| _ => none | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | parse | Try parsing an `ErrorContext` from a string: return `some` if successful, `none` otherwise. |
parseStyleExceptions (lines : Array String) : Array ErrorContext := Id.run do
Array.filterMap (parse?_errorContext ·) (lines.filter (fun line ↦ !line.startsWith "--")) | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | parseStyleExceptions | Parse all style exceptions for a line of input.
Return an array of all exceptions which could be parsed: invalid input is ignored. |
formatErrors (errors : Array ErrorContext) (style : ErrorFormat) : IO Unit := do
for e in errors do
IO.println (outputMessage e style) | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | formatErrors | 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. |
TextbasedLinter := LinterOptions → Array String →
Array (StyleError × ℕ) × (Option (Array String))
/-! Definitions of the actual text-based linters. -/ | abbrev | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | TextbasedLinter | 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.) |
isImportsOnlyFile (lines : Array String) : Bool :=
lines.all (fun line ↦ line.startsWith "import " || line == "" || line.startsWith "-- ") | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | isImportsOnlyFile | 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 && line.get (line.prev pos) == ' ' 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 (⟨[' ', ';']⟩ : String) ";")
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. |
allLinters : Array TextbasedLinter := #[
adaptationNoteLinter, semicolonLinter, trailingWhitespaceLinter
] | def | Tactic | [
"Batteries.Data.String.Matcher",
"Mathlib.Data.Nat.Notation",
"Lake.Util.Casing"
] | Mathlib/Tactic/Linter/TextBased.lean | allLinters | All text-based linters registered in this file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.