Skip to content

feat(Tactic/Linter): add superfluousExpose linter - #39387

Open
marcelolynch wants to merge 22 commits into
leanprover-community:masterfrom
marcelolynch:experiment/superfluous-expose-linter
Open

marcelolynch wants to merge 22 commits into
leanprover-community:masterfrom
marcelolynch:experiment/superfluous-expose-linter

Conversation

@marcelolynch

@marcelolynch marcelolynch commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds the linter.superfluousExpose linter, the dual of privateModule. The linter warns on an @[expose] public section where no declaration benefits from the @[expose] modifier, and suggests that you remove the modifier. Downstream code typechecks the same after the removal.

Which declarations benefit from @[expose]

A section-level @[expose] exposes the bodies of the def declarations in the section. A declaration benefits from the modifier when it is a def with an exposed body (Environment.hasExposedBody) and Lean does not expose that body without the modifier. The linter skips generated declarations (isAutoDecl).

These declarations do not benefit from the modifier:

  • Declarations without an exposed body: theorems, opaque and partial defs, private declarations, propositional instances, @[no_expose] and meta defs, and the parser descriptors of notation and syntax.
  • Declarations from an abbrev command. Lean exposes the body of an abbrev by its keyword, not by its reducibility, so a @[reducible] def benefits.
  • Instances (isInstanceCore) from an instance, deriving instance, inductive, class inductive, or structure command. An @[instance] def follows the rules of a def.
  • Structure projections.

Lean exposes the bodies in the last three cases in every public section. The linter reads the command kind through set_option … in and open … in wrappers. A mutual block or a macro gets no exemption.

Every other exposed def benefits from the modifier. Thus the linter is silent when in doubt, and a change to a reported section is safe.

Implementation

The linter is a stateful linter (leanprover/lean4#14357). It tracks the regions where the scope is public and has expose. It classifies the constants of each command while the scopes of that command are active. As a result:

  • Each expose section gets its own verdict.
  • scoped and local instances get the correct classification.
  • The warning points at the section header.

The known limitations cause false negatives only, and the module docstring lists them. The main case is a hand-written meta-code def, such as a def of type Simproc. The linter counts it as an ordinary def.

The test files cover positive and negative cases, with one file per case. The first cleanup sweep, #39388, applied an earlier version of these suggestions to 136 files.

Zulip thread: https://leanprover.zulipchat.com/#narrow/channel/287929-mathlib4/topic/Removing.20unnecessary.20.60.40.5Bexpose.5D.60/with/595180230

@github-actions github-actions Bot added the t-linter Linter label May 14, 2026
@github-actions

github-actions Bot commented May 14, 2026 •

Copy link
Copy Markdown

PR summary 3ffbc00d26

Import changes for modified files

Dependency changes

File Base Count Head Count Change
Mathlib.Tactic 3116 3118 +2 (+0.06%)
Import changes for all files
Files Import difference
Mathlib.Tactic 2
Mathlib.Tactic.Linter.SuperfluousExpose (new file) 99

Declarations diff (regex)

+ ExposeRegion
+ ExposeRegion.classifyNew
+ ExposeRegion.open
+ ExposeRegion.report
+ Foo
+ MyNat
+ Tagged
+ Tree
+ addOne
+ addOne_zero
+ benefitsFromExposure
+ first_section
+ hiddenValue
+ hiddenValue_eq
+ instFooNat
+ instanceCommandKinds
+ keeper
+ leaf_eq
+ myProduct
+ myProduct_one_one
+ opBool
+ opNat
+ op_eq
+ op_three
+ op_true
+ opaqueId
+ opaqueZero
+ opaqueZero_unfolded
+ point_eq
+ point_zero_zero
+ projection.
+ third_section
+ three_pos
+ triple
+ two_plus_two
+ use_foo
++ Op
++ Point
++ double
++ double_zero
++ in
++ one_eq_one
++++++ trivial_proof

You can run this locally as follows
## from your `mathlib4` directory:
git clone https://github.com/leanprover-community/mathlib-ci.git ../mathlib-ci

## summary with just the declaration names:
../mathlib-ci/scripts/pr_summary/declarations_diff.sh <optional_commit>

## more verbose report:
../mathlib-ci/scripts/pr_summary/declarations_diff.sh long <optional_commit>

The doc-module for scripts/pr_summary/declarations_diff.sh in the mathlib-ci repository contains some details about this script.

Declarations diff (Lean -- stale, waiting for the new build)

✅ Lean-aware diff — post-build, computed from the Lean environment (commit 0b1d0ed).

  • +17 new declarations
  • −0 removed declarations
+Mathlib.Linter.ExposeRegion
+Mathlib.Linter.ExposeRegion.casesOn
+Mathlib.Linter.ExposeRegion.ctorIdx
+Mathlib.Linter.ExposeRegion.mk
+Mathlib.Linter.ExposeRegion.mk.inj
+Mathlib.Linter.ExposeRegion.mk.injEq
+Mathlib.Linter.ExposeRegion.mk.noConfusion
+Mathlib.Linter.ExposeRegion.mk.sizeOf_spec
+Mathlib.Linter.ExposeRegion.noConfusion
+Mathlib.Linter.ExposeRegion.noConfusionType
+Mathlib.Linter.ExposeRegion.rec
+Mathlib.Linter.ExposeRegion.recOn
+Mathlib.Linter.ExposeRegion.ref
+Mathlib.Linter.ExposeRegion.seen
+Mathlib.Linter.ExposeRegion.someDeclBenefits
+Mathlib.Linter.linter.superfluousExpose
+Mathlib.Linter.superfluousExpose

No changes to strong technical debt.

Increase in weak tech debt: (relative, absolute) = (21.00, 0.00)
Current number Change Type (weak)
5172 21 exposed public sections

Current commit 3ffbc00d26
Reference commit af6dcfbf23

This script lives in the mathlib-ci repository. To run it locally, from your mathlib4 directory:

git clone https://github.com/leanprover-community/mathlib-ci.git ../mathlib-ci
../mathlib-ci/scripts/reporting/technical-debt-metrics.py pr_summary
  • The relative value is the weighted sum of the differences with weight given by the inverse of the current value of the statistic.
  • The absolute value is the relative value divided by the total sum of the inverses of the current values (i.e. the weighted average of the differences).

@marcelolynch marcelolynch added the LLM-generated PRs with substantial input from LLMs - review accordingly label May 14, 2026
@marcelolynch
marcelolynch force-pushed the experiment/superfluous-expose-linter branch from 4813c2c to 8ff8310 Compare May 14, 2026 19:02
@eric-wieser

Copy link
Copy Markdown
Member

I think we have a choice to make here in Mathlib, between:

  1. files should prefer to use public section and @[expose]. In this case, this linter is a good thing.
  2. files should prefer to use @[expose] public section, and @[no_expose]. In this case, this linter is just encouraging users to create footguns.

I don't think were ready to declare 1 as the strategy yet, and so I would be opposed to this linter (and changes like #39388) landing in mathlib. @jcommelin may have opinions too.

Perhaps a good approach for now is to contribute this linter to batteries, so that downstream projects at least have the option of turning it on if they decide to go with 1?

@marcelolynch
marcelolynch force-pushed the experiment/superfluous-expose-linter branch 3 times, most recently from 8962f34 to 99bff15 Compare May 14, 2026 21:32
Dual of `privateModule`: lints against modules with `@[expose] public
section` where no declaration needs its body visible downstream. Suggests
removing the `@[expose]` modifier.

A declaration 'benefits from exposure' iff its body matters to downstream
typechecking: plain `def`, plain `inductive`, `@[match_pattern]` def,
`@[irreducible] def` / `irreducible_def`, or a `@[to_additive]`-decorated
def. Theorems, abbrevs, classes, structures, instances, `unsafe`/`partial`
defs, compiler-generated auxiliaries, projections, matchers, and notation-
generated parser entries do not.

The linter is conservative: every known limitation produces a false negative
(scoped/local instances and tactic-implementation defs may stay silent),
never a false positive that would break downstream builds.

Includes 18 test files covering positive and negative cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
marcelolynch and others added 7 commits May 14, 2026 15:27
…ame check

The original `s.startsWith "term_"` (and the corresponding checks for
`binder_`/`stx_`/`tactic_`) only matched leaf names with a trailing
underscore separator. Infix notations such as `notation:65 a " ⋄ " b`
generate names like `«term_⋄_»` and do match, but function-like notations
such as `notation "F(" a ")"` generate `«termF(_)»` (no separator
between the prefix and the first literal), which the strict check missed.

Loosen the prefix check to match any leaf name starting with
`term`/`binder`/`stx`/`tactic`. The return-type gate
(`ParserDescr`/`TrailingParserDescr`/`Macro`) is doing the real
classification work; the prefix is just a cheap pre-filter, and broadening
it does not introduce false positives.

Extend `Negative_TermPrefixedDef.lean` to cover both `term_<snake>` (the
original case) and `term<Camel>` (the new path), verifying that the type
gate still rescues non-notation defs that happen to share the broader prefix.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rd_msgs

The seven `Positive_*.lean` tests previously relied on the linter firing
naturally at end-of-file. CI's warnings-as-errors check rejected the
resulting unguarded `warning:` diagnostics, blocking the build.

Refactor each positive test to follow the
`PrivateModuleLinter/hasOnlyPrivate.lean` pattern: import `all` of the
linter module, manufacture an `eoi` syntax via
`mkNode ``Command.eoi #[mkAtom .none ""]`, and feed it to
`superfluousExpose.run` inside a `#guard_msgs in run_cmd` block. This
captures the expected warning text byte-for-byte, removes the unguarded
warning, and makes the test's success condition self-documenting.

Drive-by fixes to two test-source bugs uncovered by the refactor:
* `Positive_ClassOnly.lean` — replace `Foo a.succ.succ` (passes `Nat`
  where `Type` is expected) with `[Foo Nat]`.
* `Positive_Notation.lean` — replace `⊕` (which collides with Lean's
  built-in `Sum` notation, making the test ambiguous) with a function-
  call-style notation `OP[a, b]` that has no possible collision.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…check

The mathlib import-linter requires modules not in `Mathlib.Init`'s transitive
closure to route their copyright-header dependency through `Mathlib.Init`
rather than importing `Mathlib.Tactic.Linter.Header` directly. This module
is not pulled in by `Mathlib.Init` (only by `Mathlib` proper, via the
`mk_all` generated import), so swap `Mathlib.Tactic.Linter.Header` for
`Mathlib.Init`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Port the linter to the stateful-linter API (lean4#14357). The linter
threads a flag across commands: after each command it checks whether the
current scope is public and carries the `expose` attribute (both are
inherited by nested scopes), and at the terminal command it reads the
flag and runs the environment walk. This replaces the block-comment-aware
text scan of the module source, and detects nested forms
(`@[expose] section` inside `public section`) the scan could not see.

Positive tests guard the lint via `#guard_msgs in #exit`: `#exit` is a
terminal command for the stateful linter, so the lint fires where
`#guard_msgs` can capture it. Negative tests keep the option on for the
whole file and assert silence at the real end of input.

The stateful-linter API first appears in nightly-2026-07-21, so this
does not build on v4.33.0-rc1; CI is expected to fail until the
v4.34.0-rc1 toolchain bump. Validated on nightly-testing
(nightly-2026-07-27): the linter and all test modules build green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Rewrite the comments in the linter and its test files. Use short
sentences, active voice, and articles. Remove bold text, arrow chains,
capitalized emphasis, and aligned list columns. Keep the guard
docstrings unchanged: they must match the emitted messages exactly.

Validated on nightly-testing (nightly-2026-07-27): the linter and all
test modules build green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Track exposed regions instead of one flag for the whole file. A region
is a maximal run of commands whose scope is public and carries the
`expose` attribute. The linter classifies the declarations of each
command inside a region at that command, folds the verdicts into one
flag per region, and reports each region when it closes: at its `end`
command, or at the terminal command for a section that the end of the
file closes. The warning points at the section header.

This removes two limitations of the whole-file design:

- File-level granularity: a file with several expose sections now gets
  one verdict per section. One good declaration no longer masks the
  superfluous `@[expose]` on the other sections.
- Scoped and local instances: classification runs while the scopes of
  the declaring command are active, so `Lean.Meta.isInstanceCore` also
  identifies `scoped instance` and `local instance` declarations.
  These test files flip from negative to positive.

Add `Positive_MultiSection.lean`: three sections in one file, with a
`#guard_msgs` around each `end` to capture the verdict of the section
that the `end` closes, and an empty expectation to assert silence for
the section that contains a def.

Validated on nightly-testing (nightly-2026-07-27): the linter and all
test modules build green, with warning positions checked on a
multi-section file.

Co-Authored-By: Claude Fable 5 <[email protected]>
@marcelolynch marcelolynch added the blocked-by-core-release Not relevant for the current Lean release candidate, but will be needed for the next. label Jul 28, 2026
marcelolynch and others added 2 commits July 28, 2026 10:17
Combine the two nested `unless` guards of the classification loop into
one condition. The do-notation hoists the `isAutoDecl` call out of the
`||`, so the call runs for each new constant even after the verdict is
settled; it runs at most once per constant, the same cost profile as
the previous end-of-file walk.

Co-Authored-By: Claude Fable 5 <[email protected]>
…e decision points

Shorten the header-import comment and the `@[irreducible]` branch
comment: both restated facts that the module docstring already covers.
Add one-line comments on the non-module guard and on the two remaining
region-transition arms, so every arm of the match names its event.

Co-Authored-By: Claude Fable 5 <[email protected]>
@marcelolynch

Copy link
Copy Markdown
Contributor Author
image

…osure

A `@[reducible] def` does not carry its own exposure: with the section's
`@[expose]` removed, even a same-file public `rfl` proof about it fails
(`Not a definitional equality`), and its compilation type can change.
Only `abbrev` is exposed independent of the section. Classify a reducible
constant as exposed only when the command that creates it is visibly an
`abbrev`; the creating command's syntax is available because
classification runs per command.

Found by a full-Mathlib sweep: stripping `@[expose]` from sections
containing `Set.Elem` (`@[reducible] def`) and `commutatorElement`
(`@[to_additive (attr := reducible)]`) broke both files.

Add `Negative_ReducibleDef.lean` as a regression test.

Co-Authored-By: Claude Fable 5 <[email protected]>
marcelolynch added a commit to marcelolynch/mathlib4 that referenced this pull request Jul 28, 2026
Strip `@[expose]` from 136 public section headers where no declaration
needs its body visible downstream. Regenerated on current master with
the per-section linter from leanprover-community#39387: the linter now classifies each
declaration at the command that creates it and gives one verdict per
section, which also catches sections in files whose defs sit outside
the section, and sections that contain scoped or local instances.

Each edited module builds on the master toolchain. Files whose content
differs between the linting tree and master were skipped.

Co-Authored-By: Claude Fable 5 <[email protected]>
@marcelolynch
marcelolynch marked this pull request as ready for review July 28, 2026 20:56
@marcelolynch marcelolynch removed the blocked-by-core-release Not relevant for the current Lean release candidate, but will be needed for the next. label Aug 11, 2026
mathlib-bors Bot pushed a commit that referenced this pull request Aug 12, 2026
Strip `@[expose]` from `public section` headers in 136 modules where no declaration needs its body visible downstream. A new sweep in the style of #38480

Found using the linter-in-progress: #39387

Relevant Zulip thread: https://leanprover.zulipchat.com/#narrow/channel/287929-mathlib4/topic/Removing.20unnecessary.20.60.40.5Bexpose.5D.60/with/595180230
attilavjda pushed a commit to attilavjda/mathlib4 that referenced this pull request Sep 5, 2026
@joneugster

Copy link
Copy Markdown
Member

It seems currently unlikely, that such a linter will be enabled in mathlib any time soon. It seems like first there needs to be some agreement that it is worthwhile to address the careless exposing (and also careless public imports) that mathlib currently does.

I personally agree with your view that it would be nice to go into that direction (no wildcard expose/public imports; more deliberate design), and think the status quo is more due to historic reasons. But, so far, I didn't get the impression that there is a clear majority behind the idea of investing time into this.

Therefore, I'll mark this as awaiting-zulip and would suggest to consider Eric's suggestion:

Perhaps a good approach for now is to contribute this linter to batteries, so that downstream projects at least have the option of turning it on if they decide to go with 1?

@joneugster joneugster added the awaiting-zulip There is a Zulip discussion; the author should await and report/implement the decision reached there label Sep 13, 2026
@ocfnash ocfnash removed the awaiting-zulip There is a Zulip discussion; the author should await and report/implement the decision reached there label Sep 14, 2026
@ocfnash

ocfnash commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Regarding this comment I think we should just for for option 1.

marcelolynch and others added 5 commits September 14, 2026 09:25
…e module system

A section-level `@[expose]` reaches the bodies of `def` declarations only.
Align the classification with that rule.

* An `unsafe def` is a `def` for exposure. Downstream `unsafe` code can prove
  `rfl` facts about it, and a hidden body breaks those proofs, so an
  `unsafe def` benefits from exposure.
* A `def` that carries `@[instance]` keeps the exposure rules of a `def`. The
  instance exemption applies only when the command is not a plain `def`.
* An inductive type, its constructors and its recursors follow the visibility
  of the declaration. The section modifier does not reach them, so an
  inductive does not count as a declaration that benefits from exposure.

Stop the per-command scan of the local constants once one declaration of the
region benefits: the verdict cannot change after that. Classify auto
declarations with the pure `Lean.Environment.isAutoDecl`.

Flip `Positive_UnsafeDef` and `Negative_Inductive` to match, and add
`Negative_InstanceAttrDef`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ove repeated test comments

Organize the module docstring around the rule the linter follows: a
section-level `@[expose]` reaches the bodies of `def` declarations only, and
Lean settles every other declaration on its own. Use one term, "benefits
from exposure", in the module docstring, the option, the warning and the
tests.

Move the `#guard_msgs` and `#exit` mechanics into the test suite index and
delete the nine copies. Drop the twelve `-- Expected: no linter warning`
trailers, which repeated the docstring above them, and fold the two that
carried a fact into that docstring first.

Correct `Negative_NoExposeSection`, which named an inductive as a
declaration that benefits from exposure.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Replace the notation, match-pattern, reducibility, matcher and private-name
checks with one `Environment.hasExposedBody` test: a body that Lean hides
with the modifier stays hidden without it. The remaining exemptions name
the bodies Lean exposes in every public section: `abbrev`, `instance`, and
structure projections. The `instance` exemption requires a command that
declares instances through the `instance` elaborator, seen through `… in`
wrappers, so an `@[instance] def` never qualifies. `@[no_expose]` defs and
`meta` defs stop being false negatives.

Store the section header syntax as the warning ref, keep the region in an
`Option`, and reuse core's `attrInstance| expose` match for the scope test.

Tests: one import shape and a top-level option in every file; positives
close with `#guard_msgs in end`; new cases for `@[no_expose]`/`meta` defs,
a nested `@[expose] section`, the file-end close, `deriving DecidableEq`,
and an `in`-wrapped `@[instance] def`; drop the tests of removed heuristics.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ach fact once

The module docstring names the bodies Lean hides and exposes on its own,
lists `class inductive` among the instance-declaring commands, and folds
the nested-section note into the definition of a region. It also notes that
Lean reports an `@[no_expose]` attribute as redundant after the section
modifier is removed. The `initialize` docstring points at the module
docstring rather than repeating it. The test docstrings for the reducible,
irreducible, and `@[instance] def` cases use the vocabulary of the linter.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@marcelolynch

Copy link
Copy Markdown
Contributor Author

Thanks for the review @joneugster, this had fallen a bit off my radar. To be honest I struggle to see the controversy here as this linter should be very benign and move us towards better hygiene with the module system. In any case I think we can still use it to perform 'sweeps' every once in a while even if we don't enable it for every user (I am doing this right now locally...). Maybe this is the case for getting it to batteries instead of mathlib.

In any case, because this is vibe coded I don't want to push too hard on it or burden reviewers (even though the code here is small enough to not be too embarrassed about asking for reviews). I care about people using the module system as much as possible, so I'd like for this linter to exist, but it does need some expert in metaprogramming to weigh in.

My verification of this code is mostly 'behavioral': I iterate by sweeping mathlib (and models have also gotten better in the past few months...) and verifying the result makes sense (oleans don't change).

@joneugster joneugster removed their assignment Sep 19, 2026
@mathlib-merge-conflicts mathlib-merge-conflicts Bot added the merge-conflict The PR has a merge conflict with master, and needs manual merging. (this label is managed by a bot) label Nov 7, 2026
@mathlib-merge-conflicts

Copy link
Copy Markdown

This pull request has conflicts, please merge master and resolve them.

…luous-expose-linter

# Conflicts:
#	Mathlib.lean
#	Mathlib/Tactic.lean
@github-actions github-actions Bot removed the merge-conflict The PR has a merge conflict with master, and needs manual merging. (this label is managed by a bot) label Nov 12, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

LLM-generated PRs with substantial input from LLMs - review accordingly t-linter Linter

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants