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, ... | 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... |
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),
... | 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.Algeb... |
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.T... | 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.Notati... |
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 imp... | 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 ↦ allowedImp... | 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
... | 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 :=... |
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
ret... | 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 pos... |
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,... | 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 metavaria... |
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` e... |
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) {}
... | 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!` neve... |
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` ... |
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!__,
`Ma... | 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.Tacti... | 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!`, `no... |
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 => fa... | 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 `reallyPers... | 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`... |
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, mv... | 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... | 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 : Fals... |
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| s... | 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 non... | 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
withS... | 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 := "enab... |
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⟩... | 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 l... |
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
desc... |
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_prop... |
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 mct... | 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 ← non... | 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 no... |
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 " ... | 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... |
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 c... | 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 ... |
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 != `Mat... | 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.... |
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.Li... | 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 =... | 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 (← mkConstWithLe... | 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
... | 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 ... | 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 t... | 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... |
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... | 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 `minImpo... |
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.minImp... | 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_=>_»,
``L... | 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 thoug... |
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.Par... | 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 g... |
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 ... | 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... |
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
le... | 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!"Ple... | 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 ``... | 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... |
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 ... | 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`.
Thi... |
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
... | 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
... | 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
... |
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
... | 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`, `profile... |
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.mis... |
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
... | 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
... |
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!"P... | 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 Sty... |
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 ... | 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]
| `(openDe... | 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.... |
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 "\
... | 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... | 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 ... | 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 w... |
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"
... | 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... |
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}:{... | 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 : O... | 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 retur... |
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.