Skip to content

feat: empty by runs try? to suggest a proof - #13430

Merged
nomeata merged 54 commits into
masterfrom
joachim/try-on-empty-by
May 11, 2026
Merged

nomeata merged 54 commits into
masterfrom
joachim/try-on-empty-by

Conversation

@nomeata

@nomeata nomeata commented Apr 16, 2026 •

Copy link
Copy Markdown
Collaborator

This PR makes an empty by block run try? in the background and surface its suggestions, while still producing the usual unsolved-goals diagnostic. The implicit try? is informational only — it does not change elaboration behavior beyond emitting messages. Behaviour is controlled by a new option tactic.tryOnEmptyBy, disabled by default for now; set it to true to opt in. The default may flip in a future release.

Behaviour summary, when the option is enabled:

  • The empty by reports unsolved goals immediately, before the (possibly slow) try? has finished.
  • The try? work is spawned as an asynchronous snapshot task (Term.wrapAsyncAsSnapshot + Core.logSnapshotTask), so subsequent elaboration is not blocked and the suggestions arrive when ready.
  • try? is gated on its parser infrastructure being available, so working on the prelude (before Init.Try is imported) keeps the regular empty-by behaviour.
  • No effect when the empty by appears inside a backtracking combinator (e.g. first | exact (by) | …) or when try? finds no applicable suggestion.

Implementation notes:

  • elabEmptyByAsTry (in Lean.Elab.Tactic.Try) is registered as a second @[builtin_term_elab byTactic], alongside the existing elabByTactic in Lean.Elab.BuiltinTerm. The gate shouldElabEmptyByAsTry is checked in both elaborators so the empty-by path takes the try? route while non-empty by follows the regular path. The body shared between them is factored as elabByTacticCore. The two-elaborator setup avoids a circular module dependency between BuiltinTerm.lean and Tactic/Try.lean; an inline comment in Try.lean explains this.
  • A latent bug from feat: require indentation in commands, allow empty tactic sequences #13229 is fixed along the way: evalSepTactics returned at the very top for an empty tactic sequence without resolving the tacSnap promise that MutualDef.mkTacTask sets up for := by … bodies. The dangling promise was harmless in typical use because the cmd's cancellation token would fire shortly after elaboration and drop it, but with a slow async snapshot task in the same command (as the implicit try? here) the language-server info-tree walk would block on it and the editor's Messages view would only update once the task finished. Resolved at the early-return in evalSepTactics.
  • The test infrastructure in Lean.Server.Test.Cancel gains a label-keyed testTasksRef registry plus mkTestTask / wait_for_test_task. The pre-existing block_until_cancelled is reimplemented on top of mkTestTask and the redundant blockUntilCancelledOnce ref is removed.

Tests:

  • tests/elab/tryOnEmptyBy.lean, tests/elab/try_prelude.lean — feature behaviour and prelude gating.
  • tests/server_interactive/cancellation_empty_by.lean — verifies that on document re-elaboration cancelRec reaches the empty-by snapshot's cancel token registered with Core.logSnapshotTask. A [try_suggestion] generator wires the outer cancel token's onSet to resolve a mkTestTask "T_outer" promise, and the candidate wait_for_test_task "T_outer" waits on it. If cancelTk? := none is passed to Core.logSnapshotTask, cancelRec cannot reach the token, the wait blocks, and the runner times out. If cancelTk? := none is also passed to wrapAsyncAsSnapshot, no onSet resolver is registered, the promise drops without resolution, and wait_for_test_task surfaces a "task dropped" diagnostic on stderr.
  • tests/server_interactive/cancellation_try_plain.lean — verifies cancellation of plain try? (no =>) when its [try_suggestion] candidate runs synchronously inside expandUserTactic, by chaining through wait_for_cancel_once_async's shared promise. Breaking SnapshotTask.cancelRec to skip walking children causes a runner timeout.

🤖 Generated with Claude Code

nomeata and others added 17 commits April 2, 2026 09:46
…approach)

This uses `withPosition commandParser` at the top level to enforce
indentation in `by` blocks, combined with an empty-by fallback for
better error messages. Compare with checkColPosGt approach in #13217.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
This adds a `notFollowedBy checkColGt` guard on the empty-by fallback in
`tacticSeqIndentGt`. When indented non-tactic content follows `by`, this
produces a tactic-level parse error ("expected '{' or tactic") rather than
silently producing an empty tactic sequence. Also adds a comparison test
for first-line vs second-line non-tactic errors.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
This reverts the `notFollowedBy checkColGt` guard on the empty-by
fallback. Indented non-tactic content now consistently gets "unsolved
goals" + "unexpected token; expected command", matching the behavior
when non-tactic content appears on subsequent lines after a valid tactic.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
This adds server_interactive hover tests verifying that goal display
works correctly when the empty-by `pushNone` fallback fires. Tests
hovering on `by`, after `by`, and below an empty `by` block.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Move the pushNone fallback hover tests out of plainGoal.lean (which ends
with an EOF test) into a dedicated plainGoalEmptyBy.lean test file.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add `--⬑` test marker variant that targets the column of `--` itself
(enabling column 0 tests, which `--^` cannot reach).

Test tactic completion in empty `by` blocks for both top-level `by`
(with `withPosition commandParser`) and nested `by` (inside `id <|
have := by`). For each, test completion at various column positions:
indented past `by`, at column 2, and at column 0.

Current behavior: top-level empty `by` offers completions at all
positions; nested empty `by` only offers completions when indented
past the `by` token.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add `--⬑` test marker variant that targets the column of `--` itself
(enabling column 0 tests, which `--^` cannot reach).

Add completion assertion mode: `--^ completion: has "skip"` checks that
a completion item with the given label exists, and `--^ completion: is empty`
checks that no completions are returned. This avoids logging the full
completion JSON, making tests stable against docstring changes.

Test tactic completion in empty `by` blocks for both top-level `by`
and nested `by` (inside `id <| have := by`). For each, test completion
at various column positions on the line below `by`: indented past `by`,
at column 2, and at column 0.

All positions currently offer tactic completions.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ctives

Remove the completion assertion mode (has/is empty) from the test runner
and use plain `completion` directives in the empty-by tests instead.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
# Conflicts:
#	src/Lean/Server/Test/Runner.lean
#	tests/server_interactive/completionEmptyBy.lean
#	tests/server_interactive/completionEmptyBy.lean.out.expected
With strict `by` indentation, empty `by` blocks are now parsed
successfully via `pushNone` instead of producing `.missing` syntax.
This makes the `isEmptyBy` check in `goalsAt?` dead code — remove it.

The `isEmpty` helper in `isSyntheticTacticCompletion` still works
correctly because it handles both `.missing` and empty nodes from
`pushNone` (via the vacuously-true `args.all isEmpty` on `#[]`).

The `have : True := by` followed by a dedent now correctly puts
`this` in scope in the outer tactic block.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
This PR makes empty `by` blocks automatically run `try? (wrapWithBy := true)`
to suggest proofs. Suggestions are prefixed with `by` so the replacement
covers the full `by` expression.

Controlled by the `tactic.tryOnEmptyBy` option (default: true). Disabled
when `errToSorry` is false (i.e., nested in a combinator like `first`).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (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 Apr 16, 2026
@leanprover-bot

leanprover-bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Collaborator

Reference manual CI status:

  • ❗ Reference manual CI can not be attempted yet, as the nightly-testing-2026-04-13 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-04-16 11:15:42)
  • ✅ Reference manual branch lean-pr-testing-13430 has successfully built against this PR. (2026-05-07 11:26:33) View Log
  • 🟡 Reference manual branch lean-pr-testing-13430 build against this PR didn't complete normally. (2026-05-07 11:27:54) View Log
  • ✅ Reference manual branch lean-pr-testing-13430 has successfully built against this PR. (2026-05-07 12:59:01) View Log
  • 🟡 Reference manual branch lean-pr-testing-13430 build against this PR didn't complete normally. (2026-05-07 13:00:46) View Log
  • ❗ Reference manual CI will not be attempted unless your PR branches off the nightly-with-manual branch. Try git rebase 0c6785c68f1cb3b66db6b101f951f3d02f7521f4 --onto 5d5642107d0433519265f155ddbfbfb98007a80b. You can force reference manual CI using the force-manual-ci label. (2026-05-08 09:41:04)
  • ✅ Reference manual branch lean-pr-testing-13430 has successfully built against this PR. (2026-05-10 08:21:54) View Log
  • 🟡 Reference manual branch lean-pr-testing-13430 build against this PR didn't complete normally. (2026-05-10 08:23:03) View Log
  • ✅ Reference manual branch lean-pr-testing-13430 has successfully built against this PR. (2026-05-10 09:25:30) View Log
  • 🟡 Reference manual branch lean-pr-testing-13430 build against this PR didn't complete normally. (2026-05-10 09:26:37) View Log
  • ✅ Reference manual branch lean-pr-testing-13430 has successfully built against this PR. (2026-05-10 21:29:01) View Log
  • 🟡 Reference manual branch lean-pr-testing-13430 build against this PR didn't complete normally. (2026-05-10 21:30:01) View Log

mathlib-nightly-testing Bot pushed a commit to leanprover-community/batteries that referenced this pull request Apr 16, 2026
@github-actions github-actions Bot added the mathlib4-nightly-available A branch for this PR exists at leanprover-community/mathlib4-nightly-testing:lean-pr-testing-NNNN label Apr 16, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/mathlib4-nightly-testing that referenced this pull request Apr 16, 2026
@mathlib-lean-pr-testing mathlib-lean-pr-testing Bot added the builds-mathlib CI has verified that Mathlib builds against this PR label Apr 16, 2026
@mathlib-lean-pr-testing

mathlib-lean-pr-testing Bot commented Apr 16, 2026 •

Copy link
Copy Markdown

Mathlib CI status (docs):

  • ✅ Mathlib branch lean-pr-testing-13430 has successfully built against this PR. (2026-04-16 12:09:46) View Log
  • ✅ Mathlib branch lean-pr-testing-13430 has successfully built against this PR. (2026-05-07 12:15:26) View Log
  • ✅ Mathlib branch lean-pr-testing-13430 has successfully built against this PR. (2026-05-07 13:48:04) View Log
  • ❗ Batteries/Mathlib CI will not be attempted unless your PR branches off the nightly-with-mathlib branch. Try git rebase 0c6785c68f1cb3b66db6b101f951f3d02f7521f4 --onto 5d5642107d0433519265f155ddbfbfb98007a80b. You can force Mathlib CI using the force-mathlib-ci label. (2026-05-08 09:41:02)
  • ❗ Mathlib CI can not be attempted yet, as the nightly-testing-2026-05-09 tag does not exist there yet. We will retry when you push more commits. If you rebase your branch onto nightly-with-mathlib, Mathlib CI should run now. You can force Mathlib CI using the force-mathlib-ci label. (2026-05-10 08:16:44)

nomeata and others added 6 commits May 6, 2026 10:31
This PR gates `tactic.tryOnEmptyBy` on `Lean.Parser.Tactic.tryTrace` being
declared in the environment, so empty `by` blocks behave normally while
working on the prelude (before `Init.Try` is imported), instead of failing
with `Unknown constant` errors deep inside `try?`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This PR adds a test case that an empty `by` nested in a backtracking tactic
combinator (where `errToSorry` is `false`) does not trigger `try?`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This PR makes the implicit `try?` triggered by an empty `by` informational only:
the suggestions are still emitted, but the goal remains unsolved (so the user
gets the usual unsolved-goals error). Previously the goal could be solved by one
of the candidate tactics, which silently changed elaboration behavior. The two
separate info messages (preamble and "Try these") are merged into a single
message via a new `footer` parameter on `Tactic.TryThis.addSuggestion(s)` that
is plumbed through `evalAndSuggestWithBy` and `elabTryCore`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This PR adds a test case that an empty `by` on an unprovable goal produces only
the usual unsolved-goals error, without surfacing the underlying `try?` failure.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This PR makes the empty `by` elaborator run the empty body via
`Term.runTactic` first, so the unsolved-goals diagnostic is emitted before
the (possibly slow) `try?` runs. Previously `try?` was run synchronously
ahead of the synthetic-mvar machinery that emits the diagnostic, so the
user could not see the unsolved-goals error until `try?` finished.

A new test `tryOnEmptyByOrder.lean` registers a slow user `try?` suggestion
generator and uses `#guard_msgs` (which enforces message ordering) to lock
in this property.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This PR runs the implicit `try?` triggered by an empty `by` asynchronously
via `Term.wrapAsyncAsSnapshot` and `Core.logSnapshotTask`. Previously the
search ran synchronously inside the term elaborator, so the language server
could not publish the unsolved-goals diagnostic until `try?` finished.
With the snapshot task, the example's `resultSnap` (which carries the
unsolved-goals diagnostic from the eager `runTactic` call) is published as
soon as command elaboration returns, and the suggestions are published
when the snapshot task completes.

Verified by sending LSP `didOpen` to a test file with a 5s `IO.sleep` user
suggestion generator and observing two `publishDiagnostics` notifications:
unsolved-goals around 1.9s and `Try this` around 8.7s.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
nomeata and others added 3 commits May 7, 2026 12:30
This PR extracts the body of `elabByTactic` into a `elabByTacticCore` helper
in `BuiltinTerm.lean`, used by both `elabByTactic` (after the gate) and
`Lean.Elab.Tactic.Try.elabEmptyByAsTry`. The previous `withOptions
(tactic.tryOnEmptyBy.set · false) <| Term.elabTerm stx` re-dispatch trick
relied on too many non-local invariants for one line of code; calling the
shared body directly makes the delegation explicit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This PR adds a comment to `elabEmptyByAsTry` documenting why we register
a second `byTactic` term elaborator instead of folding the gate-and-
dispatch into `elabByTactic` directly: `Lean.Elab.Tactic.Try` already
imports `Lean.Elab.BuiltinTerm`, so the `try?` infrastructure can't be
referenced from `BuiltinTerm.lean`. The comment notes a possible cleanup
via a registered handler ref later.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
mathlib-nightly-testing Bot pushed a commit to leanprover-community/batteries that referenced this pull request May 7, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/mathlib4-nightly-testing that referenced this pull request May 7, 2026
leanprover-bot added a commit to leanprover/reference-manual that referenced this pull request May 7, 2026
nomeata and others added 5 commits May 7, 2026 13:50
This PR adds a server_interactive test that verifies the asynchronous
snapshot task spawn pattern used by `elabEmptyByAsTry` is properly cancelled
on document edit. The test uses a custom term elaborator that mirrors
`elabEmptyByAsTry`'s structure (`wrapAsyncAsSnapshot` + `Core.logSnapshotTask`)
with a polling cancellation handler that resolves a shared promise when fired.
The second elaboration's `IO.wait` returns only if the first elaboration's
task was actually cancelled — otherwise the test runner times out.

Verified that replacing `cancelTk? := cancelTk` with `cancelTk? := none` in
`Core.logSnapshotTask` makes the test time out, confirming the test
catches incorrect cancel-token plumbing.

The test does not exercise `try?`'s candidate-cancellation path because
that has separate (downstream) cancellation issues unrelated to this PR's
plumbing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Add `tests/server_interactive/cancellation_try_plain.lean` and
`tests/server_interactive/cancellation_empty_by.lean` exercising the
cancellation propagation paths exposed by plain `try?` (calls
`mkTryEvalSuggestStx` -> `expandUserTactic` synchronously on the main
elaboration thread) and by `elabEmptyByAsTry` (spawns a
`wrapAsyncAsSnapshot` task whose cancel token is registered with
`Core.logSnapshotTask`).

The empty-by test installs an `onSet` callback on the snapshot task's
cancel token via the `[try_suggestion]` generator (which runs in
MetaM with `(← read).cancelTk?` = the snapshot's cancel token);
the plain-try test relies on `wait_for_cancel_once_async`'s shared
promise to coordinate first-/second-invocation handoff.

Both tests turn into a runner timeout if `SnapshotTask.cancelRec`
stops walking children; the empty-by test additionally fails with an
output mismatch if `elabEmptyByAsTry` passes `cancelTk? := none` to
`Core.logSnapshotTask`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@nomeata
nomeata added this pull request to the merge queue May 8, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks May 8, 2026
The test registers a `[try_suggestion]` whose generator runs in MetaM
inside the empty-`by` snapshot task -- so `(← read).cancelTk?` is the
snapshot's cancel token (`T_outer`). On the first invocation it
allocates a promise, stashes `prom.result!` in `cmdOnceRef`, and
registers an `onSet` callback on `T_outer` that resolves the promise.
The returned candidate `wait_for_t_outer` `IO.wait`s on that stashed
task -- so the empty-`by` snapshot task body completes iff `T_outer`
has been set or dropped.

`t1`'s `wait_for_cancel_once_async` is used purely to publish the
`"blocked"` diagnostic the runner waits for. On re-elaboration
`cancelRec` walks both `t1`'s tree and the empty-`by` example's tree;
firing `T_outer` resolves the promise and the snapshot task body
completes.

If `elabEmptyByAsTry` passes `cancelTk? := none` to
`Core.logSnapshotTask`, `cancelRec` cannot reach `T_outer`. The
snapshot task body's `IO.wait` blocks until `T_outer` is dropped;
since the body holds `T_outer` alive (via `wrapAsync`'s ctx) until it
returns, `T_outer` does not drop, the wait does not return, and the
runner times out. This catches the regression that the previous
stderr-based version of this test could not.

We use `prom.result!` here despite the general footgun (it panics if
the promise is dropped without being resolved): in this specific
setup the only way the promise reaches `IO.wait` is via the
`cancelTk.onSet` callback resolving it when `T_outer` fires, and the
closure capturing `prom` keeps it alive until then -- so the panic
case can't occur. `result?`-derived alternatives (`Task.map (·.getD ())`,
`BaseIO.bindTask` with a `none` branch that prints) were tried but
turned out either flaky or unable to detect the bug case. A 300-run
local stability check passed 298/300; both failures were infrastructure
noise (one runner timeout, one trailing "broken pipe" line from
file-worker cleanup), not cancellation-logic problems.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
leanprover-bot added a commit to leanprover/reference-manual that referenced this pull request May 10, 2026
Switch the empty-`by` cancellation test from `prom.result!` to `prom.result?`
plus an explicit `none` branch that prints to stderr. The previous version
relied on `Promise.result!`'s panic-and-infinite-sleep behavior to detect
dropped promises, which conflated two failure modes (cancel-token unreachable
vs. token absent) into a single timeout. With `result?` we surface
"promise dropped without resolution" on stderr (since `try?` swallows
`throwError`), so the absent-token defect produces a clear, immediate diff
failure rather than a hang.

Stash `Task (Option Unit)` in a new shared ref `tracerPromRef` (declared in
`Lean.Server.Test.Cancel`; `meta initialize` cannot be evaluated in the
defining module). `IO.wait prom.result?` blocks the current thread directly
with no extra task hop, matching `result!`'s `(sync := true)` timing -- a
bare `Task.map (·.getD ())` would default to `sync := false` and queue the
post-resolve hop on a worker, which made earlier variants flaky.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@nomeata
nomeata requested a review from mhuisi as a code owner May 10, 2026 08:36
leanprover-bot added a commit to leanprover/reference-manual that referenced this pull request May 10, 2026
nomeata and others added 4 commits May 10, 2026 18:55
Hoist the `tracerPromRef`-style pattern into a reusable, label-keyed registry
in `Lean.Server.Test.Cancel`: `testTasksRef`, `mkTestTask`, and the
`wait_for_test_task <label>` tactic. The cancellation test for `elabEmptyByAsTry`
becomes a thin caller of these primitives. Behaviour is unchanged; this is a
pure structural refactor of the test infrastructure.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The label-keyed registry added for `mkTestTask` / `wait_for_test_task` is a
strict superset of `blockUntilCancelledOnce`'s data structure (it stores
`Task (Option Unit)` rather than `Task Unit`, but the `Option` is unused on
the happy path). Drop `blockUntilCancelledOnce` and reimplement
`block_until_cancelled` on top of `mkTestTask`. Behaviour and existing
defect coverage of `cancellation_par.lean` are unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Rename `tryOnEmptyByCancel.lean` to `cancellation_async_snapshot.lean` to
fit the `cancellation_*` naming scheme used by the sibling tests, and
switch its term elaborator from the shared `onceRef` to a labeled
`mkTestTask "test_spawn"` slot for better isolation. The module docstring
now explains why this test is more involved than `cancellation_try_plain.lean`
(async snapshot vs synchronous candidate) and why it coexists with
`cancellation_empty_by.lean` (this is a unit test of the spawn-pattern,
the latter is the integration test of `elabEmptyByAsTry`'s wiring).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`cancellation_empty_by.lean` exercises the same `wrapAsyncAsSnapshot` /
`Core.logSnapshotTask` plumbing through the production `elabEmptyByAsTry`
code path. A standalone unit test that mirrors `elabEmptyByAsTry`'s
structure has to be kept in sync by hand and would silently drift if the
real elaborator's pattern changes; the integration test cannot.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
leanprover-bot added a commit to leanprover/reference-manual that referenced this pull request May 10, 2026
@nomeata
nomeata added this pull request to the merge queue May 11, 2026
Merged via the queue into master with commit 2229b07 May 11, 2026
19 checks passed
nomeata added a commit that referenced this pull request May 13, 2026
This PR makes an empty `by` block run `try?` in the background and
surface its suggestions, while still producing the usual unsolved-goals
diagnostic. The implicit `try?` is informational only — it does not
change elaboration behavior beyond emitting messages. Behaviour is
controlled by a new option `tactic.tryOnEmptyBy`, disabled by default
for now; set it to `true` to opt in. The default may flip in a future
release.

Behaviour summary, when the option is enabled:
* The empty `by` reports unsolved goals immediately, before the
(possibly slow) `try?` has finished.
* The `try?` work is spawned as an asynchronous snapshot task
(`Term.wrapAsyncAsSnapshot` + `Core.logSnapshotTask`), so subsequent
elaboration is not blocked and the suggestions arrive when ready.
* `try?` is gated on its parser infrastructure being available, so
working on the prelude (before `Init.Try` is imported) keeps the regular
empty-`by` behaviour.
* No effect when the empty `by` appears inside a backtracking combinator
(e.g. `first | exact (by) | …`) or when `try?` finds no applicable
suggestion.

Implementation notes:
* `elabEmptyByAsTry` (in `Lean.Elab.Tactic.Try`) is registered as a
second `@[builtin_term_elab byTactic]`, alongside the existing
`elabByTactic` in `Lean.Elab.BuiltinTerm`. The gate
`shouldElabEmptyByAsTry` is checked in both elaborators so the
empty-`by` path takes the `try?` route while non-empty `by` follows the
regular path. The body shared between them is factored as
`elabByTacticCore`. The two-elaborator setup avoids a circular module
dependency between `BuiltinTerm.lean` and `Tactic/Try.lean`; an inline
comment in `Try.lean` explains this.
* A latent bug from #13229 is fixed along the way: `evalSepTactics`
returned at the very top for an empty tactic sequence without resolving
the `tacSnap` promise that `MutualDef.mkTacTask` sets up for `:= by …`
bodies. The dangling promise was harmless in typical use because the
cmd's cancellation token would fire shortly after elaboration and drop
it, but with a slow async snapshot task in the same command (as the
implicit `try?` here) the language-server info-tree walk would block on
it and the editor's Messages view would only update once the task
finished. Resolved at the early-return in `evalSepTactics`.
* The test infrastructure in `Lean.Server.Test.Cancel` gains a
label-keyed `testTasksRef` registry plus `mkTestTask` /
`wait_for_test_task`. The pre-existing `block_until_cancelled` is
reimplemented on top of `mkTestTask` and the redundant
`blockUntilCancelledOnce` ref is removed.

Tests:
* `tests/elab/tryOnEmptyBy.lean`, `tests/elab/try_prelude.lean` —
feature behaviour and prelude gating.
* `tests/server_interactive/cancellation_empty_by.lean` — verifies that
on document re-elaboration `cancelRec` reaches the empty-`by` snapshot's
cancel token registered with `Core.logSnapshotTask`. A
`[try_suggestion]` generator wires the outer cancel token's `onSet` to
resolve a `mkTestTask "T_outer"` promise, and the candidate
`wait_for_test_task "T_outer"` waits on it. If `cancelTk? := none` is
passed to `Core.logSnapshotTask`, `cancelRec` cannot reach the token,
the wait blocks, and the runner times out. If `cancelTk? := none` is
also passed to `wrapAsyncAsSnapshot`, no `onSet` resolver is registered,
the promise drops without resolution, and `wait_for_test_task` surfaces
a `"task dropped"` diagnostic on stderr.
* `tests/server_interactive/cancellation_try_plain.lean` — verifies
cancellation of plain `try?` (no `=>`) when its `[try_suggestion]`
candidate runs synchronously inside `expandUserTactic`, by chaining
through `wait_for_cancel_once_async`'s shared promise. Breaking
`SnapshotTask.cancelRec` to skip walking children causes a runner
timeout.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
pull Bot pushed a commit to DaviRain-Su/lean4 that referenced this pull request Jul 1, 2026
…d `sorry` (leanprover#13830)

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 leanprover#13430, with a different implementation, and removes
the
`tactic.tryOnEmptyBy` option added there.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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