Skip to content

feat: automatic try? suggestions for empty by, unsolved goals, and sorry - #13830

Merged
nomeata merged 52 commits into
masterfrom
joachim/auto-try
Jul 1, 2026
Merged

nomeata merged 52 commits into
masterfrom
joachim/auto-try

Conversation

@nomeata

@nomeata nomeata commented May 25, 2026 •

Copy link
Copy Markdown
Collaborator

This PR adds automatic try? suggestions at common proof sites, gated by three options
that default to off:

  • autoTry.onEmptyProof — suggests on empty proofs and empty subproofs: empty by,
    empty · , empty case h => , and so on.
  • autoTry.onUnsolvedGoal — like autoTry.onEmptyProof, but also fires on proofs and
    subproofs that already contain some tactics and left a goal unsolved. The suggestion
    is appended to the existing sequence (e.g. by skip → by skip; <found>).
  • autoTry.onSorry — suggests on sorry tactics; the suggestion replaces the sorry.

Suggestions are silenced on commands that logged any error other than "unsolved goals",
and on tactic positions elaborated against multiple proof states (rhs of <;>, body of
repeat/iterate, …) where a single replacement can't be replayed.

This iterates on #13430, with a different implementation, and removes the
tactic.tryOnEmptyBy option added there.

nomeata and others added 10 commits May 20, 2026 09:56
…vedGoal,onSorry}` options

This PR replaces the in-elaborator `tactic.tryOnEmptyBy` mechanism with a
post-elaboration hook that walks each command's info trees and runs `try?`
at positions of interest, offering three independently-gated triggers:

* `autoTry.onEmptyBy` -- on empty `by` blocks (replaces the old
  `tactic.tryOnEmptyBy`)
* `autoTry.onUnsolvedGoal` -- on every tactic that left goals unsolved
  (in practice the suggestion at the terminal tactic of a `by` block is
  the relevant one)
* `autoTry.onSorry` -- on each `sorry` (term or tactic), de-duplicated by
  source position so `by sorry` reports once

The walk lives in the new `Lean.Elab.Tactic.AutoTry` module. It hooks
into `addLinter` because that is a convenient post-command-elab entry
point with infotree access, but the feature is not a linter in the
user-facing sense: it does not bail on `messages.hasErrors`, the
triggers are not bundled with `linter.all`, and the options are *not*
under the `linter.` namespace -- using the hook borrows infrastructure
rather than identity.

The `by` term elaborator returns to its pre-`tryOnEmptyBy` form: no
second registered `@[builtin_term_elab byTactic]`, no `errToSorry`
gate, no `elabByTacticCore` split. `elabTryCore` in `Lean.Elab.Tactic.Try`
becomes public so `AutoTry` can drive it. A new `trace.autoTry` trace
class is available for diagnostics.

Behavior changes from the old `tactic.tryOnEmptyBy`:
* the option is renamed (`tactic.tryOnEmptyBy` -> `autoTry.onEmptyBy`)
* nested-in-backtracking empty `by` (e.g. `first | exact (by) | trivial`)
  also triggers a suggestion now; the linter does not have access to the
  `errToSorry` flag the elaborator used. The outer proof still succeeds.
* the disable-footer is dropped (the option name is in the option's
  description, which suffices for `set_option ... false` discoverability)

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

This PR refines the auto-`try?` hook in two ways:

* Drop the `sorry` *term* trigger path. Only `sorry` *tactic* fires now. The
  term-level case was redundant -- `by sorry` already gets covered via the
  tactic trigger -- and a bare term `:= sorry` is a different ergonomic case
  that arguably shouldn't be a `try?` site.
* Skip triggers nested inside multi-elaboration combinators. Tactics like
  `first | a | b`, `<;>` (which expands to `focus / all_goals`), `try ...`,
  `attempt_all`/`attempt_all_par`, `first_par`, `repeat`/`repeat'`, `iterate`,
  `any_goals` all elaborate their arguments multiple times or in a
  backtracking context. Running `try?` on each speculative branch produces
  noisy suggestions for code that did not in fact fail. The infotree walk now
  tracks a combinator depth (`isMultiElabCombinator`) and only emits triggers
  at depth zero.

In practice this restores the pre-linter behavior for `by first | exact (by) | trivial`
(no suggestion for the failed inner branch) and `_ <;> _` (no per-goal suggestion
spam), while still firing on the outer terminal tactic if the proof as a whole
left goals unsolved.

Renames `tests/elab/tryOnEmptyBy.lean` to `tests/elab/autoTry.lean` and expands
it to cover all three triggers, including the nested-in-combinator suppression
and the explicit "no term-`sorry`" case.

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

This PR drops the hand-maintained `isMultiElabCombinator` list in favor of two
data-driven heuristics, both motivated by the observation that a single
"Try this" suggestion cannot replay against multiple proof states:

1. *Per-syntax multi-elaboration*: count `TacticInfo` nodes grouped by
   `(kind, sourcePos)`. Tactics whose count exceeds one were elaborated
   against multiple goals (rhs of `<;>` -> `all_goals`, body of `repeat`,
   `repeat'`, `iterate`, etc.) and we skip them. Keying by `(kind, pos)`
   rather than just `pos` distinguishes the user-typed tactic from its
   macro-expanded form (e.g. `sorry` -> `exact sorry`), which would
   otherwise spuriously inflate the count.

2. *Same-goal dedup*: when collecting triggers, group by the `MVarId` of
   the relevant goal so that `by first | skip | trivial` (where both
   `skip` and the outer `first` carry the same unsolved-goal mvar) only
   produces one suggestion -- at the first (outer) site visited by the
   depth-first traversal.

A new `hasNonUnsolvedGoalError` check additionally suppresses the entire
hook on commands that logged any error besides "unsolved goals". The
intuition: if the user is in the middle of fixing a broken proof, a
suggestion at the unsolved-goal site is noise.

Behavioral consequence: `by first | exact (by) | trivial` and similar do
trigger a suggestion now (one branch is elaborated against one goal, so
the uniqueness heuristic doesn't catch it). The `<;>`, `repeat`, etc.
cases that motivated the suppression originally are still handled.

Tests updated and expanded to cover all three triggers, the `<;>`
suppression case, and the error-gate case.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ductive; drop redundant `private`s

`TriggerKind` was a `Nat` abbreviation with hand-maintained doc comments
mapping `0`/`1`/`2` to the three triggers. Replace with a proper inductive
(`emptyBy`/`sorryTactic`/`unsolvedGoal`), now that the `meta` section
allows declaring one once `Init.Prelude` is imported as a non-`meta` public
import. All trigger-kind sites at the construction and dispatch points get
their named constructors back.

Also drop the `private` markers on declarations inside the module body --
the new module system makes everything private to the module by default,
so the `private` keyword was redundant noise.

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

The file is internal (consumed only by `Lean.Elab.Tactic`'s umbrella module to
trigger `builtin_initialize addLinter`), so the imports don't need to be
re-exported -- plain `import` suffices. And the linter machinery runs at
ordinary `CommandElabM` time, not at elaborator-construction time, so the
`meta` qualifier was unnecessary too. Matches the import style of other core
linters like `Lean.Linter.Extra.UnreachableTactic`.

Also drops `public section`, which had the same overreach.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address a code review of the auto-`try?` feature with a
batch of small, independent improvements:

* Drop the synthetic-stx case at candidate-collection time so the
  code action always has a real document range to apply.
* Fix the option-merge direction in `runMetaMWithMessages` so the
  saved infotree options win over surrounding `CommandElabM` options.
* Re-raise interrupt / max-recursion exceptions from `try?` instead
  of swallowing them.
* Use `Lean.Syntax.Range.contains` against the raw position from
  `stx.getRange?` in `hasNonUnsolvedGoalError`, replacing the lossy
  line-only comparison.
* Replace the hand-rolled `InfoTree` recursion with `InfoTree.foldInfo`
  and `InfoTree.foldInfoM`.
* Replace the two-pass `(kind, pos)` multiplicity scheme with a single
  collection pass plus a `pos`-only drop-on-duplicates filter.
* Key `seenGoal` on `MVarId` directly instead of `MVarId.name`.
* Add a comment explaining `setExporting false` in `runMetaMWithMessages`.
* Restrict the unsolved-goal trigger to exactly one remaining goal, so
  e.g. \`constructor\` (two open goals) stays silent.
* Add a \`#guard_msgs (positions := true)\` regression test verifying
  the unsolved-goal suggestion anchors at the failing tactic, distinct
  from the error's wider range.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Expose `evalAndCollectSuggestions` and `collectTryCoreSuggestions`
returning the raw suggestion array, so callers outside `try?`'s normal
syntax-driven flow can format and emit the suggestions themselves.
Used by the upcoming append-mode rendering in the `autoTry` linter.
No behavioural change in `try?` itself.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Reshape `autoTry.onUnsolvedGoal` to suggest *appending* a tactic to the
existing `by` block rather than replacing the failing tactic. Concretely:

* Drop `autoTry.onEmptyBy` -- the empty-`by` case is subsumed by the
  reshaped `onUnsolvedGoal` (an empty `by` has exactly one unsolved goal
  by definition).
* Trigger on the `byTactic` node, not on inner tactics; fires when the
  byTactic left exactly one unsolved goal.
* For `by skip`, the suggestion now reads as `by skip; <found>` (with
  a `"; "` separator). For empty `by`, it reads as `by <found>`. For
  multi-line `by`, it reads as a newline + indent-aligned append.
* The [apply] widget continues to display the bare tactic; the actual
  edit text (separator + tactic) is computed once and stored in
  `Suggestion.suggestion`, with `messageData?` overriding the rendering.

To make the edit verifiable in tests, add `autoTry.debug.showEdits`
which logs an info message per suggestion describing the replacement
text and the (zero-width) insertion position. Positions are emitted
relative to the enclosing command's first line, matching the format of
`#guard_msgs (positions := true)` so tests can be moved around the file
without breakage.

Internals:

* `Lean.Elab.Tactic.Try` gains a public `collectTryCoreSuggestions`
  returning the raw suggestion array; the existing `evalAndSuggest`
  flow is unchanged.
* The autoTry hook wraps its full body in a final `try ... catch` that
  re-raises only control-flow exceptions; everything else (including
  `try?` failing in restricted contexts like a prelude file) is logged
  at trace level and swallowed so the linter never produces a
  user-visible error.

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

* Restore the `autoTry.onEmptyBy` option as a strict subset of
  `autoTry.onUnsolvedGoal`. It fires only when the `by` block has no
  tactics yet -- useful when the user wants suggestions only for
  "start-of-proof" sites and not on every in-progress proof.
* Drop the broad `try ... catch` that previously swallowed any
  exception escaping `try?`'s internals. Such errors now propagate as
  linter failures so they remain visible.
* Update `tests/elab/try_prelude.lean` to expect the surfaced linter
  error in restricted (prelude) environments; the comment notes this
  as a documented limitation for now.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Apply the simplifications identified by the post-review pass:

* Drop `dropMultiElabCandidates` helper. Its position-multiplicity check
  was followed by another `seenPos` dedupe in the hook body; after the
  multiplicity filter, no two surviving candidates share a position, so
  the second pass was redundant. The hook now builds the counts map
  inline and skips both passes' work in one loop.
* Drop the `seenGoal` MVarId dedupe. Distinct trigger positions have
  distinct mvars by construction (nested by-blocks operate on fresh
  goals), so the filter never actually rejected anything.
* Collapse the double `match k` in the hook body (one to compute
  `goal?`, one to dispatch the action) into a single match per kind.
* Inline the `push` closure in `collectTriggerPoints`: its `anchor`
  argument was always `tacInfo.stx`, and the `getPos?` guard is a
  one-line pre-check at the top of the case.
* Factor `evalAndSuggestWithBy` in `Try.lean` through
  `evalAndCollectSuggestions` (the missing call-site from the earlier
  factoring commit).

Net effect: 62 lines of `AutoTry.lean` reduced to 36; identical
behaviour, identical test output.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@nomeata
nomeata requested a review from kim-em as a code owner May 25, 2026 08:59
@nomeata nomeata added the changelog-tactics User facing tactics label May 25, 2026
@nomeata
nomeata marked this pull request as draft May 25, 2026 08:59
nomeata and others added 12 commits May 25, 2026 09:48
# Conflicts:
#	tests/elab/tryOnEmptyBy.lean
The "after a command is elaborated" wording was implementation
context (when the hook runs), not user-facing behaviour. The short
descrs now read as plain "what this option does" statements.

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

Debug options conventionally live under the `debug.` prefix; the
previous name was inconsistent with `debug.tactic.try.*` and similar.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`ctx.options` is the options snapshot at the saved infotree point and
already inherits file-/command-scope settings, so the previous merge
against the surrounding `CommandElabM` options was redundant. Drop
the merge and pass `ctx.options` straight through.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`collectSuggestionsForGoal` used an `IO.Ref` only because `Tactic.run`
returns the post-run goals, not the action's value. Make `runCore'`
non-private and use it to thread the suggestion array out of TacticM
through TermElabM into MetaM and finally CommandElabM as a normal
return value.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The body of emitAppendSuggestions only uses operations that are
available in `CoreM` (pretty-printing tactic syntax, reading options,
logging info messages, calling `Tactic.TryThis.addSuggestion`), so
there is no reason to enter `MetaM`. Factor out `runCoreMWithMessages`
from the existing `runMetaMWithMessages`; the MetaM variant now just
wraps the CoreM one. The unused `mctx` parameter on
`emitAppendSuggestions` is also dropped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* Reword the docstring on `runReplaceTryOnGoal` to drop the misleading
  "legacy syntax-driven path" framing.
* Note in `computeAppendSep` that this is a heuristic to be replaced
  by a proper formatter when available.
* Reformat multiline docstrings so that `/--` and `-/` are on their
  own lines with the content unindented, matching the convention in
  the rest of `src/Lean`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`autoTry.onUnsolvedGoal` previously fired only on `by` blocks. It now
fires on any tactic-sequence container -- `by`, `· …`, `case h => …`,
`focus …`, and `(…)` -- whose body left exactly one unsolved goal. The
suggestion is rendered as an append at the appropriate position for
the host.

`autoTry.onEmptyBy` remains a strictly narrower variant that fires
only on empty `by` blocks.

* New tests cover `case h => skip` and `· skip` inside a `by` block;
  both produce per-scope suggestions in addition to the outer-`by`
  suggestion for the sibling goal.
* `computeAppendSep` now looks up the body via a generic `findBodySeq`
  helper that searches for the first `tacticSeq` child, replacing the
  byTactic-specific `byStx[1]` access.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Drop the hardcoded `isTacticSeqContainer` kind list; instead trigger
`onUnsolvedGoal` on any `TacticInfo` whose syntax has a `tacticSeq`
child, found via the existing `findBodySeq` helper. This naturally
covers `by`, `· …`, `case … => …`, `focus …`, `(…)`, `try …`, and
any future tactic of the same shape without needing to extend the
list.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`emitAppendSuggestions` was routing through `runCoreMWithMessages` to
get a CoreM context, but every operation it performs (`getOptions`,
`getFileMap`, `PrettyPrinter.ppTactic`, `logInfoAt`,
`Tactic.TryThis.addSuggestion`) is available in CommandElabM either
natively or via `liftCoreM`. Drop the wrapping; the function no longer
needs the saved `ContextInfo`.

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

The new `case` and `·` tests produce two "Try these" messages, one per
scope. Enabling positions in `#guard_msgs` makes them distinguishable
at a glance: each suggestion's anchor span tells you which scope it
belongs to.

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

The `runCoreMWithMessages` split was introduced when
`emitAppendSuggestions` still wrapped its body in one of them. That
wrapping is gone, so the only remaining caller (both
`collectSuggestionsForGoal` and `runReplaceTryOnGoal`) needs the
MetaM variant. Drop the CoreM helper and inline its body in
`runMetaMWithMessages`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@github-actions github-actions Bot added the toolchain-available A toolchain is available for this PR, at leanprover/lean4-pr-releases:pr-release-NNNN label May 25, 2026
@mathlib-lean-pr-testing

mathlib-lean-pr-testing Bot commented May 25, 2026 •

Copy link
Copy Markdown

Mathlib CI status (docs):

@leanprover-bot

leanprover-bot commented May 25, 2026 •

Copy link
Copy Markdown
Collaborator

Reference manual CI status:

  • ❗ Reference manual CI can not be attempted yet, as the nightly-testing-2026-05-25 tag does not exist there yet. We will retry when you push more commits. If you rebase your branch onto nightly-with-manual, reference manual CI should run now. You can force reference manual CI using the force-manual-ci label. (2026-05-25 10:32:54)
  • ✅ Reference manual branch lean-pr-testing-13830 has successfully built against this PR. (2026-06-29 13:42:46) View Log
  • 🟡 Reference manual branch lean-pr-testing-13830 build against this PR didn't complete normally. (2026-06-29 13:44:43) View Log
  • ✅ Reference manual branch lean-pr-testing-13830 has successfully built against this PR. (2026-06-29 18:42:52) View Log
  • 🟡 Reference manual branch lean-pr-testing-13830 build against this PR didn't complete normally. (2026-06-29 18:45:11) View Log
  • ✅ Reference manual branch lean-pr-testing-13830 has successfully built against this PR. (2026-06-30 11:11:32) View Log
  • 🟡 Reference manual branch lean-pr-testing-13830 build against this PR didn't complete normally. (2026-06-30 11:12:57) View Log
  • ✅ Reference manual branch lean-pr-testing-13830 has successfully built against this PR. (2026-06-30 11:28:46) View Log
  • 🟡 Reference manual branch lean-pr-testing-13830 build against this PR didn't complete normally. (2026-06-30 11:30:56) View Log
  • ✅ Reference manual branch lean-pr-testing-13830 has successfully built against this PR. (2026-07-01 11:10:08) View Log
  • 🟡 Reference manual branch lean-pr-testing-13830 build against this PR didn't complete normally. (2026-07-01 11:11:09) View Log

nomeata and others added 2 commits May 25, 2026 10:35
Reverts the change that made `TacticM.runCore'` non-private. Inline
the same effect in `collectSuggestionsForGoal` using `ReaderT.run`
and `StateRefT.run'`, both of which are already public.

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

Switch the trigger criterion for `autoTry.onUnsolvedGoal` from
"`goalsAfter.length == 1`" to "there's an unsolved-goals error in the
scope's range". This:

* Picks up scopes that admitted with sorry but emitted an error
  first (`·` with a body that doesn't close, `case h => …` likewise).
* Skips combinators that silently admit without erroring -- notably
  `case'`, which docs explicitly as "does not ensure the goal has
  been solved nor admits the goal if `tac` failed".

Rename `autoTry.onEmptyBy` to `autoTry.onEmptyProof`. The option now
fires on *any* tactic-sequence container whose body has no tactics
yet -- empty `by`, empty `·`, empty `case h => `, etc. -- as long as
the scope emitted an unsolved-goals error.

Internals:

* `hasUnsolvedGoalErrorInRange` walks `reportedPlusUnreported` (not
  just `unreported`), so the linter sees errors that the surrounding
  framework has already marked reported by the time it runs.
* `hasNonUnsolvedGoalError` switched to the same accessor.
* The candidate tuple now carries `(mctx, goal)` directly so the hook
  doesn't have to re-derive them from the `TacticInfo`; in particular
  scopes that admitted with sorry fall back to `goalsBefore.head`.

Tests cover empty `· `, empty `case` (fires), and `case' … => skip`
(doesn't fire); the latter is the regression test for the error-gated
behaviour.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
nomeata added 8 commits June 29, 2026 14:58
…pairs

`collectGoalsFromMessage` silently drops any `MessageData.ofGoal` not enclosed
in a `withContext`. That contract holds for `Term.reportUnsolvedGoals` today
but is invisible to anyone wrapping the message differently. Emit a
`trace.autoTry` line when a tagged message yields zero `(mctx, goal)` pairs
so future regressions are observable instead of silently disabling the trigger.
…`by { }`

`findTacticSeqBody` falls back to the `Tactic.unsolvedGoals` message's `endPos`
for empty `tacticSeq1Indented` bodies, which is "just past the opener" only
because `Term.reportUnsolvedGoals` happens to log at the surrounding
`byTactic` / `cdot` / `case` syntax. Add `debug.autoTry.showEdits` tests that
pin those positions so any future widening of the producer's `ref` shows up
as a test failure instead of as silently misplaced insertions.
The body-finder hard-codes the two real seq kinds `tacticSeq1Indented` and
`tacticSeqBracketed`; the other names in the parser (`tacticSeq`,
`tacticSeqIndentGt`, `nestedTactic`) are wrappers and aliases pierced by the
DFS walk. A future seq variant would silently disable the trigger; emit a
`trace.autoTry` line at the call site so the silent skip is observable, and
document the universe of variants at the function's docstring.
… filter

The collector dedups incoming messages by `(start, stop)`, but the runner's
`counts > 1` filter previously keyed on `start` only. Two distinct messages
sharing a start position but differing in stop would survive the collector and
then be collapsed by the runner, silently suppressing both legitimate
triggers. No producer triggers this divergence today, but unifying the keys
makes the multi-state filter robust against future shapes. Dropping the
redundant `msgPos` field from `TriggerKind.unsolvedGoal` (the same value lives
on the candidate's `ref` syntax range).
`Candidate` was a 5-tuple destructured at every call site. Convert it to a
structure with named fields so call sites are explicit about what's used,
and use the field docstrings to document the `ctx`-vs-`mctx` source split,
the dual role of `ref` (diagnostic anchor + dedup key), and so on.
…oContaining?`

The per-message "deepest enclosing `ContextInfo`" lookup in `collectTriggerPoints`
was 17 lines: a `foldInfo` to collect `(range, ctx)` pairs, an `Id.run` loop to
pick the smallest containing range, and a defensive fallback to the first
encountered ctx. The same query -- "smallest InfoTree node whose syntax range
contains R" -- is generally useful for post-elab analyses (linters, code
actions), so add `InfoTree.smallestInfoContaining?` to `Lean.Server.InfoUtils`
as a range-based companion to the existing position-based `hoverableInfoAtM?`,
and rewrite `collectTriggerPoints` against it.

The helper filters on `Info.range?` (canonical positions) to match
`smallestInfo?`'s internal size computation -- using `i.stx.getRange?` directly
silently dropped non-canonical nodes from the size step but not from the
predicate, breaking the lookup for nested `by` blocks.

The defensive fallback turns into a `trace.autoTry` skip: when no info node
covers the message range, the candidate is dropped with a trace instead of
silently inheriting some unrelated outer ctx (which was the bug this whole
walk was meant to fix).
The log machinery (`Lean.Log.logAt` → `addMessageContextFull`, then `CoreM.addMessage`
adding `withNamingContext`) unconditionally wraps every logged `MessageData` with the
elaboration scope active at log time -- env, mctx, lctx, opts, currNamespace,
openDecls -- all read straight from `Core.Context`. That includes every
`withTheReader Core.Context` override that's active, e.g. term-level
`open … in <term>`.

Extend the goal walker to extract both wrappers alongside the `(mctx, mvarId)`
pairs, and run the suggester against those. Drops the InfoTree round-trip for
unsolved-goal triggers (no more `smallestInfoContaining?` and no more
"deepest enclosing ContextInfo" dance), and fixes the term-level
`open … in <term>` case as a side effect since the message wrappers see scope
shifts that `InfoTree.foldInfo` misses.

`runMetaMWithMessages` now takes a `MessageDataContext` and `NamingContext`
directly instead of a `ContextInfo`; the `Candidate` structure follows. The
sorry path derives both from the `TacticInfo`'s `ContextInfo` so the runner has
a uniform shape. `InfoTree.smallestInfoContaining?` is removed -- its only
caller is gone, and the helper wasn't worth keeping speculatively.
Fix three stale docstrings that the recent refactor left out of date:
`collectTriggerPoints` no longer hunts for the deepest `TacticInfo` containing
the goal; `collectSuggestionsForGoal` no longer wraps a saved infotree state;
the `set_option … in <example>` test no longer relies on a deepest-enclosing-
ctx walk.

Drop type-signature restating from `runMetaMWithMessages`'s docstring and
from the `Candidate` field docstrings (the field types already document
themselves; collapse the per-field comments into a single structure-level
note covering the non-obvious sourcing of `msgCtx` / `namingCtx` / `ref`).
mathlib-nightly-testing Bot pushed a commit to leanprover-community/batteries that referenced this pull request Jun 29, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/mathlib4-nightly-testing that referenced this pull request Jun 29, 2026
leanprover-bot added a commit to leanprover/reference-manual that referenced this pull request Jun 29, 2026
@nomeata
nomeata marked this pull request as ready for review June 30, 2026 08:55
Comment on lines +65 to +70
/--
Run `try?` on each proof or subproof that left a goal unsolved -- empty `by`, `by skip`,
empty or unfinished `· `, empty or unfinished `case h => `, and so on -- and report any
suggestions to insert. The suggestion is appended to the existing sequence
(e.g. `by skip` → `by skip; <found>`).
-/

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/--
Run `try?` on each proof or subproof that left a goal unsolved -- empty `by`, `by skip`,
empty or unfinished `· `, empty or unfinished `case h => `, and so on -- and report any
suggestions to insert. The suggestion is appended to the existing sequence
(e.g. `by skip` → `by skip; <found>`).
-/
/--
Run `try?` whenever there are unsolved goals (and not other errors).
-/

Comment on lines +42 to +45
/--
Run `try?` on empty proofs and empty subproofs — empty `by`, empty `· `, empty
`case h => `, and so on — and report any suggestions to insert.
-/

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/--
Run `try?` on empty proofs and empty subproofs — empty `by`, empty `· `, empty
`case h => `, and so on — and report any suggestions to insert.
-/
/--
Run `try?` on empty proofs (e.g. empty `by`, empty `· `, empty `case h => `).
-/

Comment on lines +77 to +80
/--
Run `try?` on each `sorry` tactic and report any suggestions; the suggestion replaces
the `sorry`.
-/

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/--
Run `try?` on each `sorry` tactic and report any suggestions; the suggestion replaces
the `sorry`.
-/
/--
Run `try?` on each `sorry` tactic.
-/

Comment thread src/Lean/Elab/Tactic/AutoTry.lean Outdated
Comment on lines +194 to +195
msgCtx : MessageDataContext
namingCtx : NamingContext

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It’s an abstraction violation to use MessageData concepts here: The sorry collection doesn't rely on messages, and below you are constructing a MessageDataContext even though there is no message around. Flatten the fields here, and only touch MessageDataContext when actually dealing with messages. Also runMetaMWithMessages needs to have its arguments flattend and get a more suitable name.

Comment thread src/Lean/Elab/Tactic/AutoTry.lean Outdated
Comment on lines +202 to +211
`currNamespace`, `openDecls`).

These wrappers are unconditionally attached by the standard logging machinery
(`Lean.Log.logAt` → `addMessageContextFull` for the data wrapper, `CoreM`'s
`addMessage` for the naming wrapper), and the values they carry are read from the
active `Core.Context` at log time -- including every `withTheReader Core.Context`
override (e.g. from term-level `open … in <term>`). Recovering them from the message
gives the suggester the exact elaboration scope the error was reported under, without
any InfoTree round-trip. -/
partial def collectGoalsAndCtxFromMessage (msg : MessageData) :

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`currNamespace`, `openDecls`).
These wrappers are unconditionally attached by the standard logging machinery
(`Lean.Log.logAt` → `addMessageContextFull` for the data wrapper, `CoreM`'s
`addMessage` for the naming wrapper), and the values they carry are read from the
active `Core.Context` at log time -- including every `withTheReader Core.Context`
override (e.g. from term-level `open … in <term>`). Recovering them from the message
gives the suggester the exact elaboration scope the error was reported under, without
any InfoTree round-trip. -/
partial def collectGoalsAndCtxFromMessage (msg : MessageData) :
`currNamespace`, `openDecls`). -/
partial def collectGoalsAndCtxFromMessage (msg : MessageData) :

Comment thread src/Lean/Elab/Tactic/AutoTry.lean Outdated
Comment on lines +256 to +262
/- Returns the tactics-container null-node together with its parent seq-variant,
if `stx` is a seq-variant we recognise. -/
bodyAndKind (stx : Syntax) : Option (Syntax × SyntaxNodeKind) :=
match stx.getKind with
| ``Lean.Parser.Tactic.tacticSeq1Indented => some (stx[0], stx.getKind)
| k@``Lean.Parser.Tactic.tacticSeqBracketed => some (stx[1], k)
| _ => none

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Weirdly inconsistent. Why not body returning Option Syntax and use stx.getKind at the caller?

And how about you return the insertPos from this as well, so that we don't need insertPosOf and have only one pattern match on kind?

Comment thread src/Lean/Elab/Tactic/AutoTry.lean Outdated
Comment on lines +316 to +317
-- Unsolved-goal triggers come from the message log.
unless onUnsolved || onEmpty do return acc

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use if and indentation for symmetry with if onSorry

Comment thread src/Lean/Elab/Tactic/AutoTry.lean Outdated
-- error commonly appears twice in `msgs`. Dedup by source range before processing
-- so the later `counts > 1` filter doesn't suppress a single legitimate trigger.
let some cmdRange := cmd.getRange? (canonicalOnly := true) | return acc
let mut seen : Std.HashMap (String.Pos.Raw × String.Pos.Raw) Unit := {}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why store tuples of start and stop, and not just the Lean.Syntax.Range?

Comment thread src/Lean/Elab/Tactic/AutoTry.lean Outdated
if goals.isEmpty then
trace[autoTry] "Tactic.unsolvedGoals message yielded no (msgCtx, namingCtx, goal) \
tuples; producer not following the `withContext`/`withNamingContext` contract?"
for (msgCtx, namingCtx, mvarId) in goals do

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume it’s important to continue even if we have multiple goals, because we can have tac1 <;> (tac2 ; (by)) where the empty by block is producing two “unsolved goals” errors, and if one has one goal and one has two goals, then we don’t want to discard the one with two goals here, so that the “no try when there are multiple tactic invocations” heuristics later still can kick in. Is there a test for this?

Leave a concise comment here (one to three lines).

Comment thread src/Lean/Elab/Tactic/Basic.lean Outdated
pure a

/-- Close the main goal using the given tactic. If it fails, log the error and `admit` -/
/-- Close the main goal using the given tactic. If it fails, log the error and `admit`. -/

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No unrelated changes please.

Suggested change
/-- Close the main goal using the given tactic. If it fails, log the error and `admit`. -/
/-- Close the main goal using the given tactic. If it fails, log the error and `admit` -/

nomeata and others added 2 commits June 30, 2026 10:13
This PR applies review polish to the auto-`try?` module: shorter option docstrings; flatten the `Candidate` struct so the elaboration scope (`env`, `mctx`, `opts`, plus a `NamingContext`) lives as plain fields instead of a borrowed `MessageDataContext`; rename `runMetaMWithMessages` to `runMetaMInScope` to match; collapse the two `findTacticSeqBody` helpers (`bodyAndKind` + `insertPosOf`) into a single `seqBodyAndInsertPos?`; use `Lean.Syntax.Range` directly as the multi-state dedup key; restructure the unsolved-goal pass to mirror the `if onSorry then …` shape; trim a stale paragraph from `collectGoalsAndCtxFromMessage`'s docstring.

Also reverts an unrelated docstring tweak in `Lean.Elab.Tactic.Basic`.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
This PR fixes the auto-`try?` multi-state filter so that an empty `· ` on the rhs of `<;>` no longer fires a misplaced "Try this": each subgoal that re-enters the same `·` raises its own `Tactic.unsolvedGoals` message at the same source range; the old per-message dedup keyed on range collapsed them into one candidate, which then survived the downstream `counts > 1` suppression and triggered the suggester.

Switch the dedup key from `range` to `(range, goal mvarid)`. Same range + same mvarid is a true duplicate (`runLintersAsync` merges the snapshot tree's diagnostics into the command state's message log, so the same `Tactic.unsolvedGoals` error appears twice in `msgs`); same range + different mvarids is the genuinely distinct case the downstream `<;>` filter needs to see. Same change also unhangs `server_interactive/cancellation_empty_by.lean`, which fired the autoTry hook in server mode but had its sole candidate suppressed because the runLintersAsync-induced duplicate inflated `counts` to 2. Add a `refine ⟨?_, ?_⟩ <;> ·` test that exercises the multi-state-with-empty-body case the old dedup was masking.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@nomeata
nomeata force-pushed the joachim/auto-try branch from 4fb3582 to 8bfa82f Compare June 30, 2026 11:00
mathlib-nightly-testing Bot pushed a commit to leanprover-community/batteries that referenced this pull request Jun 30, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/mathlib4-nightly-testing that referenced this pull request Jun 30, 2026
leanprover-bot added a commit to leanprover/reference-manual that referenced this pull request Jun 30, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/batteries that referenced this pull request Jun 30, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/mathlib4-nightly-testing that referenced this pull request Jun 30, 2026
leanprover-bot added a commit to leanprover/reference-manual that referenced this pull request Jun 30, 2026
…on point

This PR replaces the `counts > 1` multi-state filter with a check that asks the same question the LSP `getInteractiveGoals` handler asks: at the insertion point, what runtime tactic state would a newly-typed tactic run against? A suggestion fires only when `InfoTree.goalsAt?` returns exactly one `TacticInfo` runtime instance, and reading off that instance the state the inserted tactic would encounter yields exactly one goal. The state to read depends on where the suggestion goes: `goalsBefore` for a `sorry` replacement (the suggestion takes the sorry's place) and for empty bodies (the suggestion is the first tactic to run there); `goalsAfter` for non-empty bodies (the suggestion runs after the existing tactics). The check makes no assumptions about which tactics are "multi-invoke": it reads the actual runtime traversal off the info tree, so user-defined combinators are handled uniformly with core ones.

Multiple `goalsAt?` results at the same position means the syntactic scope was runtime-entered against multiple goal states -- a single "Try this" cannot safely be replayed there.

The `(range, mvarid)` candidate-collection dedup stays: it handles the `runLintersAsync` duplication (same message reaches `msgs` twice, once via `st.messages` and once via the snapshot-tree merge), which would otherwise fire two identical suggestions.

Add a test for `constructor <;> (· try Qintro; skip)`, where the cdot is `<;>`'s rhs and reaches the insertion point with 0 goals in one branch and 1 in the other -- the previous heuristic saw a single unsolved-goals message and fired, breaking the already-solved branch (`exact` throws on 0 goals). The new filter reports two runtime instances at that position and suppresses.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@nomeata
nomeata enabled auto-merge July 1, 2026 10:39
@nomeata
nomeata added this pull request to the merge queue Jul 1, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/batteries that referenced this pull request Jul 1, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/mathlib4-nightly-testing that referenced this pull request Jul 1, 2026
leanprover-bot added a commit to leanprover/reference-manual that referenced this pull request Jul 1, 2026
Merged via the queue into master with commit 4907d41 Jul 1, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

builds-manual CI has verified that the Lean Language Reference builds against this PR builds-mathlib CI has verified that Mathlib builds against this PR changelog-tactics User facing tactics mathlib4-nightly-available A branch for this PR exists at leanprover-community/mathlib4-nightly-testing:lean-pr-testing-NNNN toolchain-available A toolchain is available for this PR, at leanprover/lean4-pr-releases:pr-release-NNNN

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants