Repository navigation
feat: empty by runs try? to suggest a proof - #13430
Merged
Merged
Conversation
…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]>
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]>
Collaborator
|
Reference manual CI status:
|
mathlib-nightly-testing Bot
pushed a commit
to leanprover-community/batteries
that referenced
this pull request
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 CI status (docs):
|
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]>
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
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]>
…ease 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]>
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]>
leanprover-bot
added a commit
to leanprover/reference-manual
that referenced
this pull request
May 10, 2026
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR makes an empty
byblock runtry?in the background and surface its suggestions, while still producing the usual unsolved-goals diagnostic. The implicittry?is informational only — it does not change elaboration behavior beyond emitting messages. Behaviour is controlled by a new optiontactic.tryOnEmptyBy, disabled by default for now; set it totrueto opt in. The default may flip in a future release.Behaviour summary, when the option is enabled:
byreports unsolved goals immediately, before the (possibly slow)try?has finished.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 (beforeInit.Tryis imported) keeps the regular empty-bybehaviour.byappears inside a backtracking combinator (e.g.first | exact (by) | …) or whentry?finds no applicable suggestion.Implementation notes:
elabEmptyByAsTry(inLean.Elab.Tactic.Try) is registered as a second@[builtin_term_elab byTactic], alongside the existingelabByTacticinLean.Elab.BuiltinTerm. The gateshouldElabEmptyByAsTryis checked in both elaborators so the empty-bypath takes thetry?route while non-emptybyfollows the regular path. The body shared between them is factored aselabByTacticCore. The two-elaborator setup avoids a circular module dependency betweenBuiltinTerm.leanandTactic/Try.lean; an inline comment inTry.leanexplains this.evalSepTacticsreturned at the very top for an empty tactic sequence without resolving thetacSnappromise thatMutualDef.mkTacTasksets 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 implicittry?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 inevalSepTactics.Lean.Server.Test.Cancelgains a label-keyedtestTasksRefregistry plusmkTestTask/wait_for_test_task. The pre-existingblock_until_cancelledis reimplemented on top ofmkTestTaskand the redundantblockUntilCancelledOnceref 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-elaborationcancelRecreaches the empty-bysnapshot's cancel token registered withCore.logSnapshotTask. A[try_suggestion]generator wires the outer cancel token'sonSetto resolve amkTestTask "T_outer"promise, and the candidatewait_for_test_task "T_outer"waits on it. IfcancelTk? := noneis passed toCore.logSnapshotTask,cancelReccannot reach the token, the wait blocks, and the runner times out. IfcancelTk? := noneis also passed towrapAsyncAsSnapshot, noonSetresolver is registered, the promise drops without resolution, andwait_for_test_tasksurfaces a"task dropped"diagnostic on stderr.tests/server_interactive/cancellation_try_plain.lean— verifies cancellation of plaintry?(no=>) when its[try_suggestion]candidate runs synchronously insideexpandUserTactic, by chaining throughwait_for_cancel_once_async's shared promise. BreakingSnapshotTask.cancelRecto skip walking children causes a runner timeout.🤖 Generated with Claude Code