source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
reference-manual/Manual/Releases/v4_23_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.23.0 (2025-09-15)" =>
%%%
tag := "release-v4.23.0"
file := "v4.23.0"
%%%
````markdown
For this release, 610 changes landed. In addition to the 95 feature additions and 139 fixes listed below there were 61 refactoring changes, 12 documentation improvements, 71 performance improvements, and 232 other changes.
## Highlights
Lean v4.23.0 release brings significant performance improvements, better error messages,
and a plethora of bug fixes, refinements, and consolidations in `grind`, the compiler, and other components of Lean.
In terms of user experience, noteworthy new features are:
- Improved 'Go to Definition' navigation ([#9040](https://github.com/leanprover/lean4/pull/9040))
- Using 'Go to Definition' on a type class projection now extracts
the specific instances that were involved and provides them as locations
to jump to. For example, using 'Go to Definition' on the `toString` of
`toString 0` yields results for `ToString.toString` and `ToString Nat`.
- Using 'Go to Definition' on a macro that produces syntax with type
class projections now also extracts the specific instances that were
involved and provides them as locations to jump to. For example, using
'Go to Definition' on the `+` of `1 + 1` yields results for
`HAdd.hAdd`, `HAdd α α α` and `Add Nat`.
- Using 'Go to Declaration' now provides all the results of 'Go to
Definition' in addition to the elaborator and the parser that were
involved. For example, using 'Go to Declaration' on the `+` of `1 + 1`
yields results for `HAdd.hAdd`, `HAdd α α α`, `Add Nat`,
`` macro_rules | `($x + $y) => ... `` and `infixl:65 " + " => HAdd.hAdd`.
- Using 'Go to Type Definition' on a value with a type that contains
multiple constants now provides 'Go to Definition' results for each
constant. For example, using 'Go to Type Definition' on `x` for `x : Array Nat`
yields results for `Array` and `Nat`.
- Interactive code-action hints for errors:
- for "invalid named argument" error, suggest valid argument names ([#9315](https://github.com/leanprover/lean4/pull/9315))
- for "invalid case name" error, suggest valid case names ([#9316](https://github.com/leanprover/lean4/pull/9316))
- for "fields missing" error in structure instances, suggest to insert all the missing fields ([#9317](https://github.com/leanprover/lean4/pull/9317))
You can try all of these in the [Lean playground](https://live.lean-lang.org/#codez=PQWghAUAxABAEgSwHYBcDOMBmB7ATjZANwEMAbBAExiWIFsBTK43AcwFcHUNkYAHYlCnq4kaCCGAQIyCmwDGKBIXowAKjADuAC2H0IMGAB8YtANYBGGAAoAHjACeMAF4wAXDABC2bKQCUU+hs6XlIVKxQ3NV83AF59EwE5LRgIjQQULXjjADozSytHVxiU3DZ6aKsNWJKyipcirDI0cpgYgD5rfylQSFhELiw8GDliZuo6ejEJAKDaELCAI0ivH2j3ADkBaoX7eJHmjAW90ZUkbCRAhDQhVFa2+IM0UwRebvBoeGR0QfxaK7RkCwYNdSgo2LgVMhrsQkHIVJgEPRSBQppIICD5ChwSoAMqaHQQ+IIpEUSwbARExHIgBMkQAavQFENNhFicjzDNgqFIniivEAN4AXwgQA).
### Breaking Changes
- [#9800](https://github.com/leanprover/lean4/pull/9800) improves the delta deriving handler, giving it the ability to
process definitions with binders, as well as the ability to recursively
unfold definitions. **Breaking change**: the
derived instance's name uses the `instance` command's name generator,
and the new instance is added to the current namespace.
- [#9040](https://github.com/leanprover/lean4/pull/9040) improves the 'Go to Definition' UX.
**Breaking change**: `InfoTree.hoverableInfoAt?` has been generalized to
`InfoTree.hoverableInfoAtM?` and now takes a general `filter` argument
instead of several boolean flags, as was the case before.
- [#9594](https://github.com/leanprover/lean4/pull/9594) optimizes `Lean.Name.toString`, giving a 10% instruction
benefit.
Crucially this is a **breaking change** as the old `Lean.Name.toString`
method used to support a method for identifying tokens. This method is
now available as `Lean.Name.toStringWithToken` in order to allow for
specialization of the (highly common) `toString` code path which sets
this function to just return `false`.
- [#9729](https://github.com/leanprover/lean4/pull/9729) introduces a canonical way to endow a type with an order
structure. **Breaking changes:**
- The requirements of the `lt_of_le_of_lt`/`le_trans` lemmas for
`Vector`, `List` and `Array` are simplified. They now require an
`IsLinearOrder` instance. The new requirements are logically equivalent
to the old ones, but the `IsLinearOrder` instance is not automatically
inferred from the smaller type classes.
- Hypotheses of type `Std.Total (¬ · < · : α → α → Prop)` are replaced
with the equivalent class `Std.Asymm (· < · : α → α → Prop)`. Breakage
should be limited because there is now an instance that derives the
latter from the former.
- In `Init.Data.List.MinMax`, multiple theorem signatures are modified,
replacing explicit parameters for antisymmetry, totality, `min_ex_or`
etc. with corresponding instance parameters.
## Language
* [#6732](https://github.com/leanprover/lean4/pull/6732) adds support for the `clear` tactic in conversion mode.
* [#8666](https://github.com/leanprover/lean4/pull/8666) adjusts the experimental module system to not import the IR of
non-`meta` declarations. It does this by replacing such IR with opaque
foreign declarations on export and adjusting the new compiler
accordingly.
* [#8842](https://github.com/leanprover/lean4/pull/8842) fixes the bug that `collectAxioms` didn't collect axioms
referenced by other axioms. One of the results of this bug is that
axioms collected from a theorem proved by `native_decide` may not
include `Lean.trustCompiler`.
* [#9015](https://github.com/leanprover/lean4/pull/9015) makes `isDefEq` detect more stuck definitional equalities
involving smart unfoldings. Specifically, if `t =?= defn ?m` and `defn`
matches on its argument, then this equality is stuck on `?m`. Prior to
this change, we would not see this dependency and simply return `false`.
* [#9084](https://github.com/leanprover/lean4/pull/9084) adds `binrel%` macros for `!=` and `≠` notation defined in
`Init.Core`. This allows the elaborator to insert coercions on both
sides of the relation, instead of committing to the type on the left
hand side.
* [#9090](https://github.com/leanprover/lean4/pull/9090) fixes a bug in `whnfCore` where it would fail to reduce
applications of recursors/auxiliary defs.
* [#9097](https://github.com/leanprover/lean4/pull/9097) ensures that `mspec` uses the configured transparency setting
and makes `mvcgen` use default transparency when calling `mspec`.
* [#9099](https://github.com/leanprover/lean4/pull/9099) improves the “expected type mismatch” error message by omitting
the type's types when they are defeq, and putting them into separate
lines when not.
* [#9103](https://github.com/leanprover/lean4/pull/9103) prevents truncation of `panic!` messages containing null bytes.
* [#9108](https://github.com/leanprover/lean4/pull/9108) fixes an issue that may have caused inline expressions in
messages to be unnecessarily rendered on a separate line.
* [#9113](https://github.com/leanprover/lean4/pull/9113) improves the `grind` doc string and tries to make it more
approachable to new user.
* [#9130](https://github.com/leanprover/lean4/pull/9130) fixes unexpected occurrences of the `Grind.offset` gadget in
ground patterns. See new test
* [#9131](https://github.com/leanprover/lean4/pull/9131) adds a `usedLetOnly` parameter to `LocalContext.mkLambda` and
`LocalContext.mkForall`, to parallel the `MetavarContext` versions.
* [#9133](https://github.com/leanprover/lean4/pull/9133) adds support for `a^(m+n)` in the `grind` normalizer.
* [#9143](https://github.com/leanprover/lean4/pull/9143) removes a rather ugly hack in the module system, exposing the
bodies of theorems whose type mention `WellFounded`.
* [#9146](https://github.com/leanprover/lean4/pull/9146) adds "safe" polynomial operations to `grind ring`. The use the
usual combinators: `withIncRecDepth` and `checkSystem`.
* [#9149](https://github.com/leanprover/lean4/pull/9149) generalizes the `a^(m+n)` grind normalizer to any semirings.
Example:
```
variable [Field R]
* [#9150](https://github.com/leanprover/lean4/pull/9150) adds a missing case in the `toPoly` function used in `grind`.
* [#9153](https://github.com/leanprover/lean4/pull/9153) improves the linarith `markVars`, and ensures it does not
produce spurious issue messages.
* [#9168](https://github.com/leanprover/lean4/pull/9168) resolves a defeq diamond, which caused a problem in Mathlib:
```
import Mathlib
* [#9172](https://github.com/leanprover/lean4/pull/9172) fixes a bug at `matchEqBwdPat`. The type may contain pattern
variables.
* [#9173](https://github.com/leanprover/lean4/pull/9173) fixes an incompatibility in the experimental module system when
trying to combine wellfounded recursion with public exposed definitions.
* [#9176](https://github.com/leanprover/lean4/pull/9176) makes `mvcgen` split ifs rather than applying specifications.
Doing so fixes a bug reported by Rish.
* [#9182](https://github.com/leanprover/lean4/pull/9182) tries to improve the E-matching pattern inference for `grind`.
That said, we still need better tools for annotating and maintaining
`grind` annotations in libraries.
* [#9184](https://github.com/leanprover/lean4/pull/9184) fixes stealing of `⇓` syntax by the new notation for total
postconditions by demoting it to non-builtin syntax and scoping it to
`Std.Do`.
* [#9191](https://github.com/leanprover/lean4/pull/9191) lets the equation compiler unfold abstracted proofs again if
they would otherwise hide recursive calls.
This fixes #8939.
* [#9193](https://github.com/leanprover/lean4/pull/9193) fixes the unexpected kernel projection issue reported by issue
#9187
* [#9194](https://github.com/leanprover/lean4/pull/9194) makes the logic and tactics of `Std.Do` universe polymorphic, at
the cost of a few definitional properties arising from the switch from
`Prop` to `ULift Prop` in the base case `SPred []`.
* [#9196](https://github.com/leanprover/lean4/pull/9196) implements `forall` normalization using a simproc instead of
rewriting rules in `grind`. This is the first part of the PR; after
updating stage0, we must remove the normalization theorems.
* [#9200](https://github.com/leanprover/lean4/pull/9200) implements `exists` normalization using a simproc instead of
rewriting rules in `grind`. This is the first part of the PR; after
updating stage0, we must remove the normalization theorems.
* [#9202](https://github.com/leanprover/lean4/pull/9202) extends the `Eq` simproc used in `grind`. It covers more cases
now. It also adds 3 reducible declarations to the list of declarations
to unfold.
* [#9214](https://github.com/leanprover/lean4/pull/9214) implements support for local and scoped `grind_pattern`
commands.
* [#9225](https://github.com/leanprover/lean4/pull/9225) improves the `congr` tactic so that it can handle function
applications with fewer arguments than the arity of the head function.
This also fixes a bug where `congr` could not make progress with
`Set`-valued functions in Mathlib, since `Set` was being unfolded and
making such functions have an apparently higher arity.
* [#9228](https://github.com/leanprover/lean4/pull/9228) improves the startup time for `grind ring` by generating the
required type classes on demand. This optimization is particularly
relevant for files that make hundreds of calls to `grind`, such as
`tests/lean/run/grind_bitvec2.lean`. For example, before this change,
`grind` spent 6.87 seconds synthesizing type classes, compared to 3.92
seconds after this PR.
* [#9241](https://github.com/leanprover/lean4/pull/9241) ensures that the type class instances used to implement the
`ToInt` adapter (in `grind cutsat`) are generated on demand.
* [#9244](https://github.com/leanprover/lean4/pull/9244) improves the instance generation in the `grind linarith` module.
* [#9251](https://github.com/leanprover/lean4/pull/9251) demotes the builtin elaborators for `Std.Do.PostCond.total` and
`Std.Do.Triple` into macros, following the DefEq improvements of #9015.
* [#9267](https://github.com/leanprover/lean4/pull/9267) optimizes support for `Decidable` instances in `grind`. Because
`Decidable` is a subsingleton, the canonicalizer no longer wastes time
normalizing such instances, a significant performance bottleneck in
benchmarks like `grind_bitvec2.lean`. In addition, the
congruence-closure module now handles `Decidable` instances, and can
solve examples such as:
```lean
example (p q : Prop) (h₁ : Decidable p) (h₂ : Decidable (p ∧ q)) : (p ↔ q) → h₁ ≍ h₂ := by
grind
```
* [#9271](https://github.com/leanprover/lean4/pull/9271) improves the performance of the formula normalizer used in
`grind`.
* [#9287](https://github.com/leanprover/lean4/pull/9287) rewords the "application type mismatch" error message so that
the argument and its type precede the application expression.
* [#9293](https://github.com/leanprover/lean4/pull/9293) replaces the `reduceCtorEq` simproc used in `grind` by a much
more efficient one. The default one use in `simp` is just overhead
because the `grind` normalizer is already normalizing arithmetic.
In a separate PR, we will push performance improvements to the default
`reduceCtorEq`.
* [#9305](https://github.com/leanprover/lean4/pull/9305) uses the `mkCongrSimpForConst?` API in `simp` to reduce the
number of times the same congruence lemma is generated. Before this PR,
`grind` would spend `1.5`s creating congruence theorems during
normalization in the `grind_bitvec2.lean` benchmark. It now spends
`0.6`s. should make an even bigger difference after we merge
#9300.
* [#9315](https://github.com/leanprover/lean4/pull/9315) adds improves the "invalid named argument" error message in
function applications and match patterns by providing clickable hints
with valid argument names. In so doing, it also fixes an issue where
this error message would erroneously flag valid match-pattern argument
names.
* [#9316](https://github.com/leanprover/lean4/pull/9316) adds clickable code-action hints to the "invalid case name"
error message.
* [#9317](https://github.com/leanprover/lean4/pull/9317) adds to the "fields missing" error message for structure
instance notation a code-action hint that inserts all missing fields.
* [#9324](https://github.com/leanprover/lean4/pull/9324) improves the functions for checking whether two terms are
disequal in `grind`
* [#9325](https://github.com/leanprover/lean4/pull/9325) optimizes the Boolean disequality propagator used in `grind`.
* [#9326](https://github.com/leanprover/lean4/pull/9326) optimizes `propagateEqUp` used in `grind`.
* [#9340](https://github.com/leanprover/lean4/pull/9340) modifies the encoding from `Nat` to `Int` used in `grind
cutsat`. It is simpler, more extensible, and similar to the generic
`ToInt`. After update stage0, we will be able to delete the leftovers.
* [#9351](https://github.com/leanprover/lean4/pull/9351) optimizes the `grind` preprocessing steps by skipping steps when
the term is already present in the hash-consing table.
* [#9358](https://github.com/leanprover/lean4/pull/9358) adds support for generating lattice-theoretic (co)induction
proof principles for predicates defined via `mutual` blocks using
`inductive_fixpoint`/`coinductive_fixpoint` constructs.
* [#9367](https://github.com/leanprover/lean4/pull/9367) implements a minor optimization to the `grind` preprocessor.
* [#9369](https://github.com/leanprover/lean4/pull/9369) optimizes the `grind` preprocessor by skipping unnecessary steps
when possible.
* [#9371](https://github.com/leanprover/lean4/pull/9371) fixes an issue that caused some `deriving` handlers to fail when
the name of the type being declared matched that of a declaration in an
open namespace.
* [#9372](https://github.com/leanprover/lean4/pull/9372) fixes a performance issue that occurs when generating equation
lemmas for functions that use match-expressions containing several
literals. This issue was exposed by #9322 and arises from a combination
of factors:
1. Literal values are compiled into a chain of dependent if-then-else
expressions.
2. Dependent if-then-else expressions are significantly more expensive
to simplify than regular ones.
3. The `split` tactic selects a target, splits it, and then invokes
`simp` on the resulting subgoals. Moreover, `simp` traverses the entire
goal bottom-up and does not stop after reaching the target.
* [#9385](https://github.com/leanprover/lean4/pull/9385) replaces the `isDefEq` test in the `simpEq` simproc used in
`grind`. It is too expensive.
* [#9386](https://github.com/leanprover/lean4/pull/9386) improves a confusing error message that occurred when attempting
to project from a zero-field structure.
* [#9387](https://github.com/leanprover/lean4/pull/9387) adds a hint to the "invalid projection" message suggesting the
correct nested projection for expressions of the form `t.n` where `t` is
a tuple and `n > 2`.
* [#9395](https://github.com/leanprover/lean4/pull/9395) fixes a bug at `mkCongrSimpCore?`. It fixes the issue reported
by @joehendrix at #9388.
The fix is just commit: afc4ba617fe2ca5828e0e252558d893d7791d56b. The
rest of the PR is just cleaning up the file.
* [#9398](https://github.com/leanprover/lean4/pull/9398) avoids the expensive `inferType` call in `simpArith`. It also
cleans up some of the code and removes anti-patterns.
* [#9408](https://github.com/leanprover/lean4/pull/9408) implements a simple optimization: dependent implications are no
longer treated as E-matching theorems in `grind`. In
`grind_bitvec2.lean`, this change saves around 3 seconds, as many
dependent implications are generated. Example:
```lean
∀ (h : i + 1 ≤ w), x.abs.getLsbD i = x.abs[i]
```
* [#9414](https://github.com/leanprover/lean4/pull/9414) increases the number of cases where `isArrowProposition` returns
a result other than `.undef`. This function is used to implement the
`isProof` predicate, which is invoked on every subterm visited by
`simp`.
* [#9421](https://github.com/leanprover/lean4/pull/9421) fixes a bug that caused error explanations to "steal" the
Infoview's container in the Lean web editor.
* [#9423](https://github.com/leanprover/lean4/pull/9423) updates the formatting of, and adds explanations for, "unknown
identifier" errors as well as "failed to infer type" errors for binders
and definitions.
* [#9424](https://github.com/leanprover/lean4/pull/9424) improves the error messages produced by the `split` tactic,
including suggesting syntax fixes and related tactics with which it
might be confused.
* [#9443](https://github.com/leanprover/lean4/pull/9443) makes cdot function expansion take hygiene information into
account, fixing "parenthesis capturing" errors that can make erroneous
cdots trigger cdot expansion in conjunction with macros. For example,
given
```lean
macro "baz% " t:term : term => `(1 + ($t))
```
it used to be that `baz% ·` would expand to `1 + fun x => x`, but now
the parentheses in `($t)` do not capture the cdot. We also fix an
oversight where cdot function expansion ignored the fact that type
ascriptions and tuples were supposed to delimit expansion, and also now
the quotation prechecker ignores the identifier in `hygieneInfo`. (#9491
added the hygiene information to the parenthesis and cdot syntaxes.)
* [#9447](https://github.com/leanprover/lean4/pull/9447) ensures that `mvcgen` not only tries to close stateful subgoals
by assumption, but also pure Lean goals.
* [#9448](https://github.com/leanprover/lean4/pull/9448) addresses the lean crash (stack overflow) with nested induction
and the generation of the `SizeOf` spec lemmas, reported at #9018.
* [#9451](https://github.com/leanprover/lean4/pull/9451) adds support in the `mintro` tactic for introducing `let`/`have`
binders in stateful targets, akin to `intro`. This is useful when
specifications introduce such let bindings.
* [#9454](https://github.com/leanprover/lean4/pull/9454) introduces tactic `mleave` that leaves the `SPred` proof mode by
eta expanding through its abstractions and applying some mild
simplifications. This is useful to apply automation such as `grind`
afterwards.
* [#9464](https://github.com/leanprover/lean4/pull/9464) makes `PProdN.reduceProjs` also look for projection functions.
Previously, all redexes were created by the functions in `PProdN`, which
used primitive projections. But with `mkAdmProj` the projection
functions creep in via the types of the `admissible_pprod_fst` theorem.
So let's just reduce both of them.
* [#9472](https://github.com/leanprover/lean4/pull/9472) fixes another issue at the `congr_simp` theorems that was
affecting Mathlib. Many thanks to Johan Commelin for creating the mwe.
* [#9476](https://github.com/leanprover/lean4/pull/9476) fixes the bridge between `Nat` and `Int` in `grind cutsat`.
* [#9479](https://github.com/leanprover/lean4/pull/9479) improves the `evalInt?` function, which is used to evaluate
configuration parameters from the `ToInt` type class. also adds
a new `evalNat?` function for handling the `IsCharP` type class, and
introduces a configuration option:
```
grind (exp := <num>)
```
This option controls the maximum exponent size considered during
expression evaluation. Previously, `evalInt?` used `whnf`, which could
run out of stack space when reducing terms such as `2^1024`.
* [#9480](https://github.com/leanprover/lean4/pull/9480) adds a feature where `structure` constructors can override the
inferred binder kinds of the type's parameters. In the following, the
`(p)` binder on `toLp` causes `p` to be an explicit parameter to
`WithLp.toLp`:
```lean
structure WithLp (p : Nat) (V : Type) where toLp (p) ::
ofLp : V
```
This reflects the syntax of the feature added in #7742 for overriding
binder kinds of structure projections. Similarly, only those parameters
in the header of the `structure` may be updated; it is an error to try
to update binder kinds of parameters included via `variable`.
* [#9481](https://github.com/leanprover/lean4/pull/9481) fixes a kernel type mismatch that occurs when using `grind` on
goals containing non-standard `OfNat.ofNat` terms. For example, in issue
#9477, the `0` in the theorem `range_lower` has the form:
```lean
(@OfNat.ofNat
(Std.PRange.Bound (Std.PRange.RangeShape.lower (Std.PRange.RangeShape.mk Std.PRange.BoundShape.closed Std.PRange.BoundShape.open)) Nat)
(nat_lit 0)
(instOfNatNat (nat_lit 0)))
```
instead of the more standard form:
```lean
(@OfNat.ofNat
Nat
(nat_lit 0)
(instOfNatNat (nat_lit 0)))
```
* [#9487](https://github.com/leanprover/lean4/pull/9487) fixes an incorrect proof term constructed by `grind linarith`,
as reported in #9485.
* [#9491](https://github.com/leanprover/lean4/pull/9491) adds hygiene info to paren/tuple/typeAscription syntaxes, which
will be used to implement hygienic cdot function expansion in #9443.
* [#9496](https://github.com/leanprover/lean4/pull/9496) improves the error messages produced by the `set_option`
command.
* [#9500](https://github.com/leanprover/lean4/pull/9500) adds a `HPow \a Int \a` field to `Lean.Grind.Field`, and
sufficient axioms to connect it to the operations, so that in future we
can reason about exponents in `grind`. To avoid collisions, we also move
the `HPow \a Nat \a` field in `Semiring` from the extends clause to a
field. Finally, we add some failing tests about normalizing exponents.
* [#9505](https://github.com/leanprover/lean4/pull/9505) removes vestigial syntax definitions in
`Lean.Elab.Tactic.Do.VCGen` that when imported undefine the `mvcgen`
tactic. Now it should be possible to import Mathlib and still use
`mvcgen`.
* [#9506](https://github.com/leanprover/lean4/pull/9506) adds a few missing simp lemmas to `mleave`.
* [#9507](https://github.com/leanprover/lean4/pull/9507) makes `mvcgen` `mintro` let/have bindings.
* [#9509](https://github.com/leanprover/lean4/pull/9509) surfaces kernel diagnostics even in `example`.
* [#9512](https://github.com/leanprover/lean4/pull/9512) makes `mframe`, `mspec` and `mvcgen` respect hygiene.
Inaccessible stateful hypotheses can now be named with a new tactic
`mrename_i` that works analogously to `rename_i`.
* [#9516](https://github.com/leanprover/lean4/pull/9516) ensures that private declarations made inaccessible by the
module system are noted in the relevant error messages
* [#9518](https://github.com/leanprover/lean4/pull/9518) ensures previous "is marked as private" messages are still
triggered under the module system
* [#9520](https://github.com/leanprover/lean4/pull/9520) corrects the changes to `Lean.Grind.Field` made in #9500.
* [#9522](https://github.com/leanprover/lean4/pull/9522) uses `withAbstractAtoms` to prevent the kernel from accidentally
reducing the atoms in the arith normlizer while typechecking. This PR
also sets `implicitDefEqProofs := false` in the `grind` normalizer
* [#9532](https://github.com/leanprover/lean4/pull/9532) generalizes `Process.output` and `Process.run` with an optional
`String` argument that can be piped to `stdin`.
* [#9551](https://github.com/leanprover/lean4/pull/9551) fixes the error position for the "dependent elimination failed"
error for the `cases` tactic.
* [#9553](https://github.com/leanprover/lean4/pull/9553) fixes a bug introduced in #7830 where if the cursor is at the
indicated position
```lean
example (as bs : List Nat) : (as.append bs).length = as.length + bs.length := by
induction as with
| nil => -- cursor
| cons b bs ih =>
```
then the Infoview would show "no goals" rather than the `nil` goal. The
PR also fixes a separate bug where placing the cursor on the next line
after the `induction`/`cases` tactics like in
```lean
induction as with
| nil => sorry
| cons b bs ih => sorry
I -- < cursor
```
would report the original goal in the goal list. Furthermore, there are
numerous improvements to error recovery (including `allGoals`-type logic
for pre-tactics) and the visible tactic states when there are errors.
Adds `Tactic.throwOrLogErrorAt`/`Tactic.throwOrLogError` for throwing or
logging errors depending on the recovery state.
* [#9571](https://github.com/leanprover/lean4/pull/9571) restores the feature where in `induction`/`cases` for `Nat`, the
`zero` and `succ` labels are hoverable. This was added in #1660, but
broken in #3629 and #3655 when custom eliminators were added. In
general, if a custom eliminator `T.elim` for an inductive type `T` has
an alternative `foo`, and `T.foo` is a constant, then the `foo` label
will have `T.foo` hover information.
* [#9574](https://github.com/leanprover/lean4/pull/9574) adds the option `abstractProof` to control whether `grind`
automatically creates an auxiliary theorem for the generated proof or
not.
* [#9575](https://github.com/leanprover/lean4/pull/9575) optimizes the proof terms generated by `grind ring`. For
example, before this PR, the kernel took 2.22 seconds (on a M4 Max) to
type-check the proof in the benchmark `grind_ring_5.lean`; it now takes
only 0.63 seconds.
* [#9578](https://github.com/leanprover/lean4/pull/9578) fixes an issue in `grind`'s disequality proof construction. The
issue occurs when an equality is merged with the `False` equivalence
class, but it is not the root of its congruence class, and its
congruence root has not yet been merged into the `False` equivalence
class yet.
* [#9579](https://github.com/leanprover/lean4/pull/9579) ensures `ite` and `dite` are to selected as E-matching patterns.
They are bad patterns because the then/else branches are only
internalized after `grind` decided whether the condition is
`True`/`False`.
* [#9592](https://github.com/leanprover/lean4/pull/9592) updates the styling and wording of error messages produced in
inductive type declarations and anonymous constructor notation,
including hints for inferable constructor visibility updates.
* [#9595](https://github.com/leanprover/lean4/pull/9595) improves the error message displayed when writing an invalid
projection on a free variable of function type.
* [#9606](https://github.com/leanprover/lean4/pull/9606) adds notes to the deprecation warning when the replacement
constant has a different type, visibility, and/or namespace.
* [#9625](https://github.com/leanprover/lean4/pull/9625) improves trace messages around wf_preprocess.
* [#9628](https://github.com/leanprover/lean4/pull/9628) introduces a `mutual_induct` variant of the generated
(co)induction proof principle for mutually defined (co)inductive
predicates. Unlike the standard (co)induction principle (which projects
conclusions separately for each predicate), `mutual_induct` produces a
conjunction of all conclusions.
* [#9633](https://github.com/leanprover/lean4/pull/9633) updates various error messages produced by or associated with
built-in tactics and adapts their formatting to current conventions.
* [#9634](https://github.com/leanprover/lean4/pull/9634) modifies dot identifier notation so that `(.a : T)` resolves
`T.a` with respect to the root namespace, like for generalized field
notation. This lets the notation refer to private names, follow aliases,
and also use open namespaces. The LSP completions are improved to follow
how dot ident notation is resolved, but it doesn't yet take into account
aliases or open namespaces.
* [#9637](https://github.com/leanprover/lean4/pull/9637) improves the readability of the "maximum universe level offset
exceeded" error message.
* [#9646](https://github.com/leanprover/lean4/pull/9646) uses a more simple approach to proving the unfolding theorem for
a function defined by well-founded recursion. Instead of looping a bunch
of tactics, it uses simp in single-pass mode to (try to) exactly undo
the changes done in `WF.Fix`, using a dedicated theorem that pushes the
extra argument in for each matcher (or `casesOn`).
* [#9649](https://github.com/leanprover/lean4/pull/9649) fixes an issue where a macro unfolding to multiple commands
would not be accepted inside `mutual`
* [#9653](https://github.com/leanprover/lean4/pull/9653) adds error explanations for two common errors caused by large
elimination from `Prop`. To support this functionality, "nested" named
errors thrown by sub-tactics are now able to display their error code
and explanation.
* [#9666](https://github.com/leanprover/lean4/pull/9666) addresses an outstanding feature in the module system to
automatically mark `let rec` and `where` helper declarations as private
unless they are defined in a public context such as under `@[expose]`.
* [#9670](https://github.com/leanprover/lean4/pull/9670) add constructors `.intCast k` and `.natCast k` to
`CommRing.Expr`. We need them because terms such as `Nat.cast (R := α)
1` and `(1 : α)` are not definitionally equal. This is pervaise in
Mathlib for the numerals `0` and `1`.
* [#9671](https://github.com/leanprover/lean4/pull/9671) fixes support for `SMul.smul` in `grind ring`. `SMul.smul`
applications are now normalized. Example:
```lean
example (x : BitVec 2) : x - 2 • x + x = 0 := by
grind
```
* [#9675](https://github.com/leanprover/lean4/pull/9675) adds support for `Fin.val` in `grind cutsat`. Examples:
```lean
example (a b : Fin 2) (n : Nat) : n = 1 → ↑(a + b) ≠ n → a ≠ 0 → b = 0 → False := by
grind
* [#9676](https://github.com/leanprover/lean4/pull/9676) adds normalizers for nonstandard arithmetic instances. The types
`Nat` and `Int` have built-in support in `grind`, which uses the
standard instances for these types and assumes they are the ones in use.
However, users may define their own alternative instances that are
definitionally equal to the standard ones. normalizes such
instances using simprocs. This situation actually occurs in Mathlib.
Example:
```lean
class Distrib (R : Type _) extends Mul R where
* [#9679](https://github.com/leanprover/lean4/pull/9679) produces a warning for redundant `grind` arguments.
* [#9682](https://github.com/leanprover/lean4/pull/9682) fixes a regression introduced by an optimization in the
`unfoldReducible` step used by the `grind` normalizer. It also ensures
that projection functions are not reduced, as they are folded in a later
step.
* [#9686](https://github.com/leanprover/lean4/pull/9686) applies `clear` to implementation detail local declarations
during the `grind` preprocessing steps.
* [#9699](https://github.com/leanprover/lean4/pull/9699) adds propagation rules for functions that take singleton types.
This feature is useful for discharging verification conditions produced
by `mvcgen`. For example:
```lean
example (h : (fun (_ : Unit) => x + 1) = (fun _ => 1 + y)) : x = y := by
grind
```
* [#9700](https://github.com/leanprover/lean4/pull/9700) fixes assertion violations when `checkInvariants` is enabled in
`grind`
* [#9701](https://github.com/leanprover/lean4/pull/9701) switches to a non-verloading local `Std.Do.Triple` notation in
SpecLemmas.lean to work around a stage2 build failure.
* [#9702](https://github.com/leanprover/lean4/pull/9702) fixes an issue in the `match` elaborator where pattern variables
like `__x` would not have the kind `implDetail` in the local context.
Now `kindOfBinderName` is `LocalDeclKind.ofBinderName`.
* [#9704](https://github.com/leanprover/lean4/pull/9704) optimizes the proof terms produced by `grind cutsat`. Additional
performance improvements will be merged later.
* [#9706](https://github.com/leanprover/lean4/pull/9706) combines `Poly.combine_k` and `Poly.mul_k` steps used in the
`grind cutsat` proof terms.
* [#9710](https://github.com/leanprover/lean4/pull/9710) improves some of the proof terms produced by `grind ring` and
`grind cutsat`.
* [#9714](https://github.com/leanprover/lean4/pull/9714) adds a version of `CommRing.Expr.toPoly` optimized for kernel
reduction. We use this function not only to implement `grind ring`, but
also to interface the ring module with `grind cutsat`.
* [#9716](https://github.com/leanprover/lean4/pull/9716) moves the validation of cross-package `import all` to Lake and
the syntax validation of import keywords (`public`, `meta`, and `all`)
to the two import parsers.
* [#9728](https://github.com/leanprover/lean4/pull/9728) fixes #9724
* [#9735](https://github.com/leanprover/lean4/pull/9735) extends the propagation rule implemented in #9699 to constant
functions.
* [#9736](https://github.com/leanprover/lean4/pull/9736) implements the option `mvcgen +jp` to employ a slightly lossy VC
encoding for join points that prevents exponential VC blowup incurred by
naïve splitting on control flow.
* [#9754](https://github.com/leanprover/lean4/pull/9754) makes `mleave` apply `at *` and improves its simp set in order to
discharge some more trivialities (#9581).
* [#9755](https://github.com/leanprover/lean4/pull/9755) implements a `mrevert ∀n` tactic that "eta-reduces" the stateful
goal and is adjoint to `mintro ∀x1 ... ∀xn`.
* [#9767](https://github.com/leanprover/lean4/pull/9767) fixes equality congruence proof terms constructed by `grind`.
* [#9772](https://github.com/leanprover/lean4/pull/9772) fixes a bug in the projection over constructor propagator used
in `grind`. It may construct type-incorrect terms when an equivalence
class contains heterogeneous equalities.
* [#9776](https://github.com/leanprover/lean4/pull/9776) combines the simplification and unfold-reducible-constants steps
in `grind` to ensure that no potential normalization steps are missed.
* [#9780](https://github.com/leanprover/lean4/pull/9780) extends the test suite for `grind` working category theory, to
help debug outstanding problems in Mathlib.
* [#9781](https://github.com/leanprover/lean4/pull/9781) ensures that `mvcgen` is hygienic. The goals it generates should
now introduce all locals inaccessibly.
* [#9785](https://github.com/leanprover/lean4/pull/9785) splits out an implementation detail of
MVarId.getMVarDependencies into a top-level function. Aesop was relying
on the function defined in the where clause, which is no longer possible
after #9759.
* [#9798](https://github.com/leanprover/lean4/pull/9798) introduces `Lean.realizeValue`, a new metaprogramming API for
parallelism-aware caching of `MetaM` computations
* [#9800](https://github.com/leanprover/lean4/pull/9800) improves the delta deriving handler, giving it the ability to
process definitions with binders, as well as the ability to recursively
unfold definitions. Furthermore, delta deriving now tries all explicit
non-out-param arguments to a class, and it can handle "mixin" instance
arguments. The `deriving` syntax has been changed to accept general
terms, which makes it possible to derive specific instances with for
example `deriving OfNat _ 1` or `deriving Module R`. The class is
allowed to be a pi type, to add additional hypotheses; here is a Mathlib
example:
```lean
def Sym (α : Type*) (n : ℕ) :=
{ s : Multiset α // Multiset.card s = n }
deriving [DecidableEq α] → DecidableEq _
```
This underscore stands for where `Sym α n` may be inserted, which is
necessary when `→` is used. The `deriving instance` command can refer to
scoped variables when delta deriving as well. Breaking change: the
derived instance's name uses the `instance` command's name generator,
and the new instance is added to the current namespace.
* [#9804](https://github.com/leanprover/lean4/pull/9804) allows trailing comma in the argument list of `simp?`, `dsimp?`,
`simpa`, etc... Previously, it was only allowed in the non `?` variants
of `simp`, `dsimp`, `simp_all`.
* [#9807](https://github.com/leanprover/lean4/pull/9807) adds `Std.List.Zipper.pref` to the simp set of `mleave`.
* [#9809](https://github.com/leanprover/lean4/pull/9809) adds a script for analyzing `grind` E-matching annotations. The
script is useful for detecting matching loops. We plan to add
user-facing commands for running the script in the future.
* [#9813](https://github.com/leanprover/lean4/pull/9813) fixes an unexpected bound variable panic in `unfoldReducible`
used in `grind`.
* [#9814](https://github.com/leanprover/lean4/pull/9814) skips the `normalizeLevels` preprocessing step in `grind` when
it is not needed.
* [#9818](https://github.com/leanprover/lean4/pull/9818) fixes a bug where the `DecidableEq` deriving handler did not
take universe levels into account for enumerations (inductive types
whose constructors all have no fields). Closes #9541.
* [#9819](https://github.com/leanprover/lean4/pull/9819) makes the `unsafe t` term create an auxiliary opaque
declaration, rather than an auxiliary definition with opaque
reducibility hints.
* [#9831](https://github.com/leanprover/lean4/pull/9831) adds a delaborator for `Std.Range` notation.
* [#9832](https://github.com/leanprover/lean4/pull/9832) adds simp lemmas `SPred.entails_<n>` to replace
`SPred.entails_cons` which was dysfunctional as a simp lemma due to
#8074.
* [#9833](https://github.com/leanprover/lean4/pull/9833) works around a DefEq bug in `mspec` involving delayed
assignments.
* [#9834](https://github.com/leanprover/lean4/pull/9834) fixes a bug in `mvcgen` triggered by excess state arguments to
the `wp` application, a situation which arises when working with
`StateT` primitives.
* [#9841](https://github.com/leanprover/lean4/pull/9841) migrates the ⌜p⌝ notation for embedding pure `p : Prop` into
`SPred σs` to expand into a simple, first-order expression `SPred.pure p`
that can be supported by E-matching in `grind`.
* [#9843](https://github.com/leanprover/lean4/pull/9843) makes `mvcgen` produce deterministic case labels for the
generated VCs. Invariants will be named `inv<n>` and every other VC will
be named `vc<n>.*`, where the `*` part serves as a loose indication of
provenance.
* [#9852](https://github.com/leanprover/lean4/pull/9852) removes the `inShareCommon` quick filter used in `grind`
preprocessing steps. `shareCommon` is no longer used only for fully
preprocessed terms.
* [#9853](https://github.com/leanprover/lean4/pull/9853) adds `Nat` and `Int` numeral normalizers in `grind`.
* [#9857](https://github.com/leanprover/lean4/pull/9857) ensures `grind` can E-match patterns containing universe
polymorphic ground sub-patterns. For example, given
```
set_option pp.universes true in
attribute [grind?] Id.run_pure
```
the pattern
```
Id.run_pure.{u_1}: [@Id.run.{u_1} #1 (@pure.{u_1, u_1} `[Id.{u_1}] `[Applicative.toPure.{u_1, u_1}] _ #0)]
```
contains two nested universe polymorphic ground patterns
- `Id.{u_1}`
- `Applicative.toPure.{u_1, u_1}`
* [#9860](https://github.com/leanprover/lean4/pull/9860) fixes E-matching theorem activation in `grind`.
* [#9865](https://github.com/leanprover/lean4/pull/9865) adds improved support for proof-by-reflection to the kernel type
checker. It addresses the performance issue exposed by #9854. With this
PR, whenever the kernel type-checks an argument of the form `eagerReduce
_`, it enters "eager-reduction" mode. In this mode, the kernel is more
eager to reduce terms. The new `eagerReduce _` hint is often used to
wrap `Eq.refl true`. The new hint should not negatively impact any
existing Lean package.
* [#9867](https://github.com/leanprover/lean4/pull/9867) fixes a nondeterministic behavior in `grind ring`.
* [#9880](https://github.com/leanprover/lean4/pull/9880) ensures a local forall is activated at most once per pattern in
`grind`.
* [#9883](https://github.com/leanprover/lean4/pull/9883) refines the warning message for redundant `grind` arguments. It
is not based on the actual inferred pattern instead provided kind.
* [#9885](https://github.com/leanprover/lean4/pull/9885) is initially motivated by noticing `Lean.Grind.Preorder.toLE`
appearing in long Mathlib type class searches; this change will prevent
these searches. These changes are also helpful preparation for
potentially dropping the custom `Lean.Grind.*` type classes, and unifying
with the new type classes introduced in #9729.
````
````markdown
## Library
* [#7450](https://github.com/leanprover/lean4/pull/7450) implements `Nat.dfold`, a dependent analogue of `Nat.fold`.
* [#9096](https://github.com/leanprover/lean4/pull/9096) removes some unnecessary `Decidable*` instance arguments by
using lemmas in the `Classical` namespace instead of the `Decidable`
namespace.
* [#9121](https://github.com/leanprover/lean4/pull/9121) allows `grind` to case on the universe variants of `Prod`.
* [#9129](https://github.com/leanprover/lean4/pull/9129) fixes simp lemmas about boolean equalities to say `(!x) = y`
instead of `(!decide (x = y)) = true`
* [#9135](https://github.com/leanprover/lean4/pull/9135) allows the result type of `forIn`, `foldM` and `fold` on pure
iterators (`Iter`) to be in a different universe than the iterators.
* [#9142](https://github.com/leanprover/lean4/pull/9142) changes `Fin.reverseInduction` from using well-founded recursion
to using `let rec`, which makes it have better definitional equality.
Co-authored by @digama0. See the test below:
```lean
namespace Fin
* [#9145](https://github.com/leanprover/lean4/pull/9145) fixes two typos.
* [#9176](https://github.com/leanprover/lean4/pull/9176) makes `mvcgen` split ifs rather than applying specifications.
Doing so fixes a bug reported by Rish.
* [#9194](https://github.com/leanprover/lean4/pull/9194) makes the logic and tactics of `Std.Do` universe polymorphic, at
the cost of a few definitional properties arising from the switch from
`Prop` to `ULift Prop` in the base case `SPred []`.
* [#9249](https://github.com/leanprover/lean4/pull/9249) adds theorem `BitVec.clzAuxRec_eq_clzAuxRec_of_getLsbD_false` as
a more general statement than `BitVec.clzAuxRec_eq_clzAuxRec_of_le`,
replacing the latter in the bitblaster too.
* [#9260](https://github.com/leanprover/lean4/pull/9260) removes uses of `Lean.RBMap` in Lean itself.
* [#9263](https://github.com/leanprover/lean4/pull/9263) fixes `toISO8601String` to produce a string that conforms to the
ISO 8601 format specification. The previous implementation separated the
minutes and seconds fragments with a `.` instead of a `:` and included
timezone offsets without the hour and minute fragments separated by a
`:`.
* [#9285](https://github.com/leanprover/lean4/pull/9285) removes the unnecessary requirement of `BEq α` for
`Array.any_push`, `Array.any_push'`, `Array.all_push`, `Array.all_push'`
as well as `Vector.any_push` and `Vector.all_push`.
* [#9301](https://github.com/leanprover/lean4/pull/9301) adds a `simp` and a `grind` annotation on `Zipper`-related
theorems to improve reasoning about `Std.Do` invariants.
* [#9391](https://github.com/leanprover/lean4/pull/9391) replaces the proof of the simplification lemma `Nat.zero_mod`
with
`rfl` since it is, by design, a definitional equality. This solves an
issue
whereby the lemma could not be used by the simplifier when in 'dsimp'
mode.
* [#9441](https://github.com/leanprover/lean4/pull/9441) fixes the behavior of `String.prev`, aligning the runtime
implementation with the reference implementation. In particular, the
following statements hold now:
- `(s.prev p).byteIdx` is at least `p.byteIdx - 4` and at most
`p.byteIdx - 1`
- `s.prev 0 = 0`
- `s.prev` is monotone
* [#9449](https://github.com/leanprover/lean4/pull/9449) fix the behavior of `String.next` on the scalar boundary (`2 ^
63 - 1` on 64-bit platforms).
* [#9451](https://github.com/leanprover/lean4/pull/9451) adds support in the `mintro` tactic for introducing `let`/`have`
binders in stateful targets, akin to `intro`. This is useful when
specifications introduce such let bindings.
* [#9454](https://github.com/leanprover/lean4/pull/9454) introduces tactic `mleave` that leaves the `SPred` proof mode by
eta expanding through its abstractions and applying some mild
simplifications. This is useful to apply automation such as `grind`
afterwards.
* [#9504](https://github.com/leanprover/lean4/pull/9504) adds a few more `*.by_wp` "adequacy theorems" that allows to
prove facts about programs in `ReaderM` and `ExceptM` using the `Std.Do`
framework.
* [#9528](https://github.com/leanprover/lean4/pull/9528) adds `List.zipWithM` and `Array.zipWithM`.
* [#9529](https://github.com/leanprover/lean4/pull/9529) upstreams some helper instances for `NameSet` from Batteries.
* [#9538](https://github.com/leanprover/lean4/pull/9538) adds two lemmas related to `Iter.toArray`.
* [#9577](https://github.com/leanprover/lean4/pull/9577) adds lemmas about `UIntX.toBitVec` and `UIntX.ofBitVec` and `^`.
* [#9586](https://github.com/leanprover/lean4/pull/9586) adds componentwise algebraic operations on `Vector α n`, and
relevant instances.
* [#9594](https://github.com/leanprover/lean4/pull/9594) optimizes `Lean.Name.toString`, giving a 10% instruction
benefit.
* [#9609](https://github.com/leanprover/lean4/pull/9609) adds `@[grind =]` to `Prod.lex_def`. Note that `omega` has
special handling for `Prod.Lex`, and this is needed for `grind`'s cutsat
module to achieve parity.
* [#9616](https://github.com/leanprover/lean4/pull/9616) introduces checks to make sure that the IO functions produce
errors when inputs contain NUL bytes (instead of ignoring everything
after the first NUL byte).
* [#9620](https://github.com/leanprover/lean4/pull/9620) adds the separate directions of
`List.pairwise_iff_forall_sublist` as named lemmas.
* [#9621](https://github.com/leanprover/lean4/pull/9621) renames `Xor` to `XorOp`, to match `AndOp`, etc.
* [#9622](https://github.com/leanprover/lean4/pull/9622) adds a missing lemma about `List.sum`, and a grind annotation.
* [#9701](https://github.com/leanprover/lean4/pull/9701) switches to a non-verloading local `Std.Do.Triple` notation in
SpecLemmas.lean to work around a stage2 build failure.
* [#9721](https://github.com/leanprover/lean4/pull/9721) tags more `SInt` and `UInt` lemmas with `int_toBitVec` so
`bv_decide`
can handle casts between them and negation.
* [#9729](https://github.com/leanprover/lean4/pull/9729) introduces a canonical way to endow a type with an order
structure. The basic operations (`LE`, `LT`, `Min`, `Max`, and in later
PRs `BEq`, `Ord`, ...) and any higher-level property (a preorder, a
partial order, a linear order etc.) are then put in relation to `LE` as
necessary. The PR provides `IsLinearOrder` instances for many core types
and updates the signatures of some lemmas.
* [#9732](https://github.com/leanprover/lean4/pull/9732) re-implements `IO.waitAny` using Lean instead of C++. This is to
reduce the size and
complexity of `task_manager` in order to ease future refactorings.
* [#9736](https://github.com/leanprover/lean4/pull/9736) implements the option `mvcgen +jp` to employ a slightly lossy VC
encoding for join points that prevents exponential VC blowup incurred by
naïve splitting on control flow.
* [#9739](https://github.com/leanprover/lean4/pull/9739) removes the `instance` attribute from `lexOrd` that was
accidentally applied in `Std.Classes.Ord.Basic`.
* [#9757](https://github.com/leanprover/lean4/pull/9757) adds `grind` annotations for key `Std.Do.SPred` lemmas.
* [#9782](https://github.com/leanprover/lean4/pull/9782) corrects the `Inhabited` instance of `StdGen` to use a valid
initial state for the pseudorandom number generator. Previously, the
`default` generator had the property that `Prod.snd (stdNext default) =
default`, so it would produce only constant sequences.
* [#9787](https://github.com/leanprover/lean4/pull/9787) adds a simp lemma `PostCond.const_apply`.
* [#9792](https://github.com/leanprover/lean4/pull/9792) adds `@[expose]` to two definitions with `where` clauses that
Batteries proves theorems about.
* [#9799](https://github.com/leanprover/lean4/pull/9799) fixes the #9410 issue.
* [#9805](https://github.com/leanprover/lean4/pull/9805) improves the API for invariants and postconditions and as such
introduces a few breaking changes to the existing pre-release API around
`Std.Do`. It also adds Markus Himmel's `pairsSumToZero` example as a
test case.
* [#9832](https://github.com/leanprover/lean4/pull/9832) adds simp lemmas `SPred.entails_<n>` to replace
`SPred.entails_cons` which was dysfunctional as a simp lemma due to
#8074.
* [#9841](https://github.com/leanprover/lean4/pull/9841) migrates the ⌜p⌝ notation for embedding pure `p : Prop` into
`SPred σs` to expand into a simple, first-order expression `SPred.pure p`
that can be supported by E-matching in `grind`.
* [#9848](https://github.com/leanprover/lean4/pull/9848) adds `@[spec]` lemmas for `forIn` and `forIn'` at `Std.PRange`.
* [#9850](https://github.com/leanprover/lean4/pull/9850) adds a delaborator for `Std.PRange` notation.
## Compiler
* [#8691](https://github.com/leanprover/lean4/pull/8691) ensures that the state is reverted when compilation using the
new compiler fails. This is especially important for noncomputable
sections where the compiler might generate half-compiled functions which
may then be erroneously used while compiling other functions.
* [#9134](https://github.com/leanprover/lean4/pull/9134) changes ToIR to call `lowerEnumToScalarType?` with
`ConstructorVal.induct` rather than the name of the constructor itself.
This was an oversight in some refactoring of code in the new compiler
before landing it. It should not affect runtime of compiled code (due to
the extra tagging/untagging being optimized by LLVM), but it does make
IR for the interpreter slightly more efficient.
* [#9144](https://github.com/leanprover/lean4/pull/9144) adds support for representing more inductive as enums,
summarized up as extending support to those that fail to be enums
because of parameters or irrelevant fields. While this is nice to have,
it is actually motivated by correctness of a future desired
optimization. The existing type representation is unsound if we
implement `object`/`tobject` distinction between values guaranteed to be
an object pointer and those that may also be a tagged scalar. In
particular, types like the ones added in this PR's tests would have all
of their constructors encoded via tagged values, but under the natural
extension of the existing rules of type representation they would be
considered `object` rather than `tobject`.
* [#9154](https://github.com/leanprover/lean4/pull/9154) tightens the IR typing rules around applications of closures.
When re-reading some code, I realized that the code in `mkPartialApp`
has a clear typo—`.object` and `type` should be swapped. However, it
doesn't matter, because later IR passes smooth out the mismatch here. It
makes more sense to be strict up-front and require applications of
closures to always return an `.object`.
* [#9159](https://github.com/leanprover/lean4/pull/9159) enforces the non-inlining of _override impls in the base phase
of LCNF compilation. The current situation allows for constructor/cases
mismatches to be exposed to the simplifier, which triggers an assertion
failure. The reason this didn't show up sooner for Expr is that Expr has
a custom extern implementation of its computed field getter.
* [#9177](https://github.com/leanprover/lean4/pull/9177) makes the `pullInstances` pass avoid pulling any instance
expressions containing erased propositions, because we don't correctly
represent the dependencies that remain after erasure.
* [#9198](https://github.com/leanprover/lean4/pull/9198) changes the compiler's specialization analysis to consider
higher-order params that are rebundled in a way that only changes their
`Prop` arguments to be fixed. This means that they get specialized with
a mere `@[specialize]`, rather than the compiler having to opt-in to
more aggressive parameter-specific specialization.
* [#9207](https://github.com/leanprover/lean4/pull/9207) makes the offending declaration clickable in the error message
produced when something should be marked `noncomputable`.
* [#9209](https://github.com/leanprover/lean4/pull/9209) changes the `getLiteral` helper function of `elimDeadBranches`
to correctly handle inductives with constructors. This function is not
used as often as it could be, which makes this issue rare to hit outside
of targeted test cases.
* [#9218](https://github.com/leanprover/lean4/pull/9218) makes the LCNF `elimDeadBranches` pass handle unsafe decls a bit
more carefully. Now the result of an unsafe decl will only become ⊤ if
there is value flow from a recursive call.
* [#9221](https://github.com/leanprover/lean4/pull/9221) removes code that has the false assumption that LCNF local vars
can occur in types. There are other comments in `ElimDead.lean`
asserting that this is not possible, so this must have been a change
early in the development of the new compiler.
* [#9224](https://github.com/leanprover/lean4/pull/9224) changes the `toMono` pass to consider the type of an application
and erase all arguments corresponding to erased params. This enables a
lightweight form of relevance analysis by changing the mono type of a
decl. I would have liked to unify this with the behavior for
constructors, but my attempt to give constructors the same behavior in
#9222 (which was in preparation for this PR) had a minor performance
regression that is really incidental to the change. Still, I decided to
hold off on it for the time being. In the future, we can hopefully
extend this to constructors, extern decls, etc.
* [#9266](https://github.com/leanprover/lean4/pull/9266) adds support for `.mdata` in LCNF mono types (and then drops it
at the IR type level instead). This better matches the behavior of
extern decls in the C++ code of the old compiler, which is still being
used to create extern decls at the moment and will soon be replaced.
* [#9268](https://github.com/leanprover/lean4/pull/9268) moves the implementation of `lean_add_extern`/`addExtern` from
C++ into Lean. I believe is the last C++ helper function from the
library/compiler directory being relied upon by the new compiler. I put
it into its own file and duplicated some code because this function
needs to execute in CoreM, whereas the other IR functions live in their
own monad stack. After the C++ compiler is removed, we can move the IR
functions into CoreM.
* [#9275](https://github.com/leanprover/lean4/pull/9275) removes the old compiler written in C++.
* [#9279](https://github.com/leanprover/lean4/pull/9279) fixes the `compiler.extract_closed` option after migrating it to
Lean (and adds a test so it would be caught in the future).
* [#9310](https://github.com/leanprover/lean4/pull/9310) fixes IR constructor argument lowering to correctly handle an
irrelevant argument being passed for a relevant parameter in all cases.
This happened because constructor argument lowering (incompletely)
reimplemented general LCNF-to-IR argument lowering, and the fix is to
just adopt the generic helper functions. This is probably due to an
incomplete refactoring when the new compiler was still on a branch.
* [#9336](https://github.com/leanprover/lean4/pull/9336) changes the implementation of `trace.Compiler.result` to use the
decls as they are provided rather than looking them up in the LCNF mono
environment extension, which was seemingly done to save the trouble of
re-normalizing fvar IDs before printing the decl. This means that the
`._closed` decls created by the `extractClosed` pass will now be
included in the output, which was definitely confusing before if you
didn't know what was happening.
* [#9344](https://github.com/leanprover/lean4/pull/9344) correctly populates the `xType` field of the `IR.FnBody.case`
constructor. It turns out that there is no obvious consequence for this
being incorrect, because it is conservatively recomputed by the `Boxing`
pass.
* [#9393](https://github.com/leanprover/lean4/pull/9393) fixes an unsafe trick where a sentinel for a hash table of Exprs
(keyed by pointer) is created by constructing a value whose runtime
representation can never be a valid Expr. The value chosen for this
purpose was Unit.unit, which violates the inference that Expr has no
scalar constructors. Instead, we change this to a freshly allocated Unit
× Unit value.
* [#9411](https://github.com/leanprover/lean4/pull/9411) adds support for compilation of `casesOn` for subsingletons. We
rely on the elaborator's type checking to restrict this to inductives in
`Prop` that can actually eliminate into `Type n`. This does not yet
cover other recursors of these types (or of inductives not in `Prop` for
that matter).
* [#9703](https://github.com/leanprover/lean4/pull/9703) changes the LCNF `elimDeadBranches` pass so that it considers
all non-`Nat` literal types to be `⊤`. It turns out that fixing this to
correctly handle all of these types with the current abstract value
representation is surprisingly nontrivial, and it's better to just land
the fix first.
* [#9720](https://github.com/leanprover/lean4/pull/9720) removes an error which implicitly assumes that the sort of type
dependency between erased types present in the test being added can not
occur. It would be difficult to refine the error using only the
information present in LCNF types, and it is of very little ongoing
value (I don't recall it ever finding an actual problem), so it makes
more sense to delete it.
* [#9827](https://github.com/leanprover/lean4/pull/9827) changes the lowering of `Quot.lcInv` (the compiler-internal form
of `Quot.lift`) in `toMono` to support overapplication.
* [#9847](https://github.com/leanprover/lean4/pull/9847) adds a check for reursive decls in this bespoke inlining path,
which fixes a regression from the old compiler.
* [#9864](https://github.com/leanprover/lean4/pull/9864) adds new variants of `Array.getInternal` and
`Array.get!Internal` that return their argument borrowed, i.e. without a
reference count increment. These are intended for use by the compiler in
cases where it can determine that the array will continue to hold a
valid reference to the element for the returned value's lifetime.
## Pretty Printing
* [#8391](https://github.com/leanprover/lean4/pull/8391) adds an unexpander for `Vector.mk` that unexpands `Vector.mk
#[...] _` to `#v[...]`.
```lean
-- previously:
#check #v[1, 2, 3] -- { toArray := #[1, 2, 3], size_toArray := ⋯ } : Vector Nat 3
-- now:
#check #v[1, 2, 3] -- #v[1, 2, 3] : Vector Nat 3
```
* [#9475](https://github.com/leanprover/lean4/pull/9475) fixes the way some syntaxes are pretty printed due to missing
whitespace advice.
* [#9494](https://github.com/leanprover/lean4/pull/9494) fixes an issue that caused some error messages to attempt to
display hovers for nonexistent identifiers.
* [#9555](https://github.com/leanprover/lean4/pull/9555) allows hints in message data to specify custom preview spans
that extend beyond the edit region specified by the code action.
* [#9778](https://github.com/leanprover/lean4/pull/9778) modifies the pretty printing of anonymous metavariables to use
the index rather than the internal name. This leads to smaller numerical
suffixes in `?m.123` since the indices are numbered within a given
metavariable context rather than across an entire file, hence each
command gets its own numbering. This does not yet affect pretty printing
of universe level metavariables.
## Documentation
* [#9093](https://github.com/leanprover/lean4/pull/9093) adds a missing docstring for `ToFormat.toFormat`.
* [#9152](https://github.com/leanprover/lean4/pull/9152) fixes an obsolete docstring for `registerDerivingHandler`
* [#9593](https://github.com/leanprover/lean4/pull/9593) simplifies the docstring for `propext` significantly.
## Server
* [#9040](https://github.com/leanprover/lean4/pull/9040) improves the 'Go to Definition' UX, specifically:
- Using 'Go to Definition' on a type class projection will now extract
the specific instances that were involved and provide them as locations
to jump to. For example, using 'Go to Definition' on the `toString` of
`toString 0` will yield results for `ToString.toString` and `ToString
Nat`.
- Using 'Go to Definition' on a macro that produces syntax with type
class projections will now also extract the specific instances that were
involved and provide them as locations to jump to. For example, using
'Go to Definition' on the `+` of `1 + 1` will yield results for
`HAdd.hAdd`, `HAdd α α α` and `Add Nat`.
- Using 'Go to Declaration' will now provide all the results of 'Go to
Definition' in addition to the elaborator and the parser that were
involved. For example, using 'Go to Declaration' on the `+` of `1 + 1`
will yield results for `HAdd.hAdd`, `HAdd α α α`, `Add Nat`,
``macro_rules | `($x + $y) => ...`` and `infixl:65 " + " => HAdd.hAdd`.
- Using 'Go to Type Definition' on a value with a type that contains
multiple constants will now provide 'Go to Definition' results for each
constant. For example, using 'Go to Type Definition' on `x` for `x :
Array Nat` will yield results for `Array` and `Nat`.
* [#9163](https://github.com/leanprover/lean4/pull/9163) disables the use of the header produced by `lake setup-file` in
the server for now. It will be re-enabled once Lake takes into account
the header given by the server when processing workspace modules.
Without that, `setup-file` header can produce odd behavior when the file
on disk and in an editor disagree on whether the file participates in
the module system.
* [#9563](https://github.com/leanprover/lean4/pull/9563) performs some micro optimizations on fuzzy matching for a `~20%`
instructions win.
* [#9784](https://github.com/leanprover/lean4/pull/9784) ensures the editor progress bar better reflects the actual
progress of parallel elaboration.
## Lake
* [#9053](https://github.com/leanprover/lean4/pull/9053) updates Lake to resolve the `.olean` files for transitive
imports for Lean through the `modules` field of `lean --setup`. This
enables means the Lean can now directly use the `.olean` files from the
Lake cache without needed to locate them at a specific hierarchical
path.
* [#9101](https://github.com/leanprover/lean4/pull/9101) fixes a bug introduce by #9081 where the source file was dropped
from the module input trace and some entries were dropped from the
module job log.
* [#9162](https://github.com/leanprover/lean4/pull/9162) changes the key Lake uses for the `,ir` artifact in the content
hash data structure to `r`, maintaining the convention of single
character key names.
* [#9165](https://github.com/leanprover/lean4/pull/9165) fixes two issues with Lake's process of creating static
archives.
* [#9332](https://github.com/leanprover/lean4/pull/9332) changes the dependency cloning mechanism in lake so the log
message that lake is cloning a
dependency occurs before it is finished doing so (and instead before it
starts). This has been a
huge source of confusion for users that don't understand why lake seems
to be just stuck for no
reason when setting up a new project, the output now is:
```
λ lake +lean4 new math math
info: downloading mathlib `lean-toolchain` file
info: math: no previous manifest, creating one from scratch
info: leanprover-community/mathlib: cloning https://github.com/leanprover-community/mathlib4
<hang>
info: leanprover-community/mathlib: checking out revision 'cd11c28c6a0d514a41dd7be9a862a9c8815f8599'
```
* [#9434](https://github.com/leanprover/lean4/pull/9434) changes the Lake local cache infrastructure to restore
executables and shared and static libraries from the cache. This means
they keep their expected names, which some use cases still rely on.
* [#9435](https://github.com/leanprover/lean4/pull/9435) adds the `libPrefixOnWindows` package and library configuration
option. When enabled, Lake will prefix static and shared libraries with
`lib` on Windows (i.e., the same way it does on Unix).
* [#9436](https://github.com/leanprover/lean4/pull/9436) adds the number of jobs run to the final message Lake produces
on a successfully run of `lake build`.
* [#9478](https://github.com/leanprover/lean4/pull/9478) adds proper Lake support for `meta import`. Module IR is now
tracked in traces and in the pre-resolved modules Lake passes to `lean
--setup`.
* [#9525](https://github.com/leanprover/lean4/pull/9525) fixes Lake's handling of a module system `import all`.
Previously, Lake treated `import all` the same a non-module `import`,
importing all private data in the transitive import tree. Lake now
distinguishes the two, with `import all M` just importing the private
data of `M`. The direct private imports of `M` are followed, but they
are not promoted.
* [#9559](https://github.com/leanprover/lean4/pull/9559) changes `lake setup-file` to use the server-provided header for
workspace modules.
* [#9604](https://github.com/leanprover/lean4/pull/9604) restricts Lake's production of thin archives to only the Windows
core build (i.e., `bootstrap = true`). The unbundled `ar` usually used
for core builds on macOS does not support `--thin`, so we avoid using it
unless necessary.
* [#9677](https://github.com/leanprover/lean4/pull/9677) adds build times to each build step of the build monitor (under
`-v` or in CI) and delays exiting on a `--no-build` until after the
build monitor finishes. Thus, a `--no-build` failure will now report
which targets blocked Lake by needing a rebuild.
* [#9697](https://github.com/leanprover/lean4/pull/9697) fixes the handling in `lake lean` and `lake setup-file` of a
library source file with multiple dots (e.g., `src/Foo.Bar.lean`).
* [#9698](https://github.com/leanprover/lean4/pull/9698) adjusts the formatting type classes for `lake query` to no
longer require both a text and JSON form and instead work with any
combination of the two. The classes have also been renamed. In addition,
the query formatting of a text module header has been improved to only
produce valid headers.
## Other
* [#9106](https://github.com/leanprover/lean4/pull/9106) fixes `undefined symbol: lean::mpz::divexact(lean::mpz const&,
lean::mpz const&)` when building without `LEAN_USE_GMP`
* [#9114](https://github.com/leanprover/lean4/pull/9114) further improves release automation, automatically incorporating
material from `nightly-testing` and `bump/v4.X.0` branches in the bump
PRs to downstream repositories.
* [#9659](https://github.com/leanprover/lean4/pull/9659) fixes compatibility of the `trace.profiler.output` option with
newer versions of Firefox Profiler
```` |
reference-manual/Manual/Releases/v4_3_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.3.0 (2023-11-30)" =>
%%%
tag := "release-v4.3.0"
file := "v4.3.0"
%%%
```markdown
* `simp [f]` does not unfold partial applications of `f` anymore. See issue [#2042](https://github.com/leanprover/lean4/issues/2042).
To fix proofs affected by this change, use `unfold f` or `simp (config := { unfoldPartialApp := true }) [f]`.
* By default, `simp` will no longer try to use Decidable instances to rewrite terms. In particular, not all decidable goals will be closed by `simp`, and the `decide` tactic may be useful in such cases. The `decide` simp configuration option can be used to locally restore the old `simp` behavior, as in `simp (config := {decide := true})`; this includes using Decidable instances to verify side goals such as numeric inequalities.
* Many bug fixes:
* [Add left/right actions to term tree coercion elaborator and make `^`` a right action](https://github.com/leanprover/lean4/pull/2778)
* [Fix for #2775, don't catch max recursion depth errors](https://github.com/leanprover/lean4/pull/2790)
* [Reduction of `Decidable` instances very slow when using `cases` tactic](https://github.com/leanprover/lean4/issues/2552)
* [`simp` not rewriting in binder](https://github.com/leanprover/lean4/issues/1926)
* [`simp` unfolding `let` even with `zeta := false` option](https://github.com/leanprover/lean4/issues/2669)
* [`simp` (with beta/zeta disabled) and discrimination trees](https://github.com/leanprover/lean4/issues/2281)
* [unknown free variable introduced by `rw ... at h`](https://github.com/leanprover/lean4/issues/2711)
* [`dsimp` doesn't use `rfl` theorems which consist of an unapplied constant](https://github.com/leanprover/lean4/issues/2685)
* [`dsimp` does not close reflexive equality goals if they are wrapped in metadata](https://github.com/leanprover/lean4/issues/2514)
* [`rw [h]` uses `h` from the environment in preference to `h` from the local context](https://github.com/leanprover/lean4/issues/2729)
* [missing `withAssignableSyntheticOpaque` for `assumption` tactic](https://github.com/leanprover/lean4/issues/2361)
* [ignoring default value for field warning](https://github.com/leanprover/lean4/issues/2178)
* [Cancel outstanding tasks on document edit in the language server](https://github.com/leanprover/lean4/pull/2648).
* [Remove unnecessary `%` operations in `Fin.mod` and `Fin.div`](https://github.com/leanprover/lean4/pull/2688)
* [Avoid `DecidableEq` in `Array.mem`](https://github.com/leanprover/lean4/pull/2774)
* [Ensure `USize.size` unifies with `?m + 1`](https://github.com/leanprover/lean4/issues/1926)
* [Improve compatibility with emacs eglot client](https://github.com/leanprover/lean4/pull/2721)
**Lake:**
* [Sensible defaults for `lake new MyProject math`](https://github.com/leanprover/lean4/pull/2770)
* Changed `postUpdate?` configuration option to a `post_update` declaration. See the `post_update` syntax docstring for more information on the new syntax.
* [A manifest is automatically created on workspace load if one does not exists.](https://github.com/leanprover/lean4/pull/2680).
* The `:=` syntax for configuration declarations (i.e., `package`, `lean_lib`, and `lean_exe`) has been deprecated. For example, `package foo := {...}` is deprecated.
* [support for overriding package URLs via `LAKE_PKG_URL_MAP`](https://github.com/leanprover/lean4/pull/2709)
* Moved the default build directory (e.g., `build`), default packages directory (e.g., `lake-packages`), and the compiled configuration (e.g., `lakefile.olean`) into a new dedicated directory for Lake outputs, `.lake`. The cloud release build archives are also stored here, fixing [#2713](https://github.com/leanprover/lean4/issues/2713).
* Update manifest format to version 7 (see [lean4#2801](https://github.com/leanprover/lean4/pull/2801) for details on the changes).
* Deprecate the `manifestFile` field of a package configuration.
* There is now a more rigorous check on `lakefile.olean` compatibility (see [#2842](https://github.com/leanprover/lean4/pull/2842) for more details).
``` |
reference-manual/Manual/Releases/v4_27_0.lean | import VersoManual
import Manual.Meta
import Manual.Meta.Markdown
import Std.Data.Iterators
import Std.Data.TreeMap
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
open Std.Iterators
open Std (TreeMap)
open Std (HashMap)
open Std (Iterator Iter IterM IteratorLoop)
#doc (Manual) "Lean 4.27.0 (2026-01-24)" =>
%%%
tag := "release-v4.27.0"
file := "v4.27.0"
%%%
For this release, 372 changes landed. In addition to the 118 feature additions and 71 fixes listed below there were 28 refactoring changes, 13 documentation improvements, 25 performance improvements, 6 improvements to the test suite and 111 other changes.
# Highlights
## Module System Stabilized
[#11637](https://github.com/leanprover/lean4/pull/11637) declares the module system as no longer experimental and makes the {option}`experimental.module` option a no-op.
See the {ref "module-scopes"}[Modules and Visibility] section in the reference manual for the documentation.
## Backward Compatibility Options
[#11304](https://github.com/leanprover/lean4/pull/11304) documents that `backward.*` options are only temporary
migration aids and may disappear without further notice after 6 months
after their introduction. Users are kindly asked to report if they rely
on these options.
## Performance Gains
This release includes many performance improvements, notably:
- [#11162](https://github.com/leanprover/lean4/pull/11162) reduces the memory consumption of the language server (the
watchdog process in particular). In Mathlib, it reduces memory
consumption by about 1GB.
- [#11507](https://github.com/leanprover/lean4/pull/11507) optimizes the filesystem accesses during importing for a ~3% win
on Linux, potentially more on other platforms.
## Error Messages
This release contains a series of changes to error messages aimed at making them more helpful and actionable.
Specifically, some messages now have hints, suggestions, and links to explanations.
PRs:
[#11119](https://github.com/leanprover/lean4/pull/11119),
[#11245](https://github.com/leanprover/lean4/pull/11245),
[#11346](https://github.com/leanprover/lean4/pull/11346),
[#11347](https://github.com/leanprover/lean4/pull/11347),
[#11456](https://github.com/leanprover/lean4/pull/11456),
[#11482](https://github.com/leanprover/lean4/pull/11482),
[#11518](https://github.com/leanprover/lean4/pull/11518),
[#11554](https://github.com/leanprover/lean4/pull/11554),
[#11555](https://github.com/leanprover/lean4/pull/11555),
[#11621](https://github.com/leanprover/lean4/pull/11621).
## New Features in Grind
### Function-Valued Congruence Closure
[#11323](https://github.com/leanprover/lean4/pull/11323) introduces a new {tactic}`grind` option, `funCC` (enabled by default),
which extends congruence closure to _function-valued_ equalities. When
`funCC` is enabled, `grind` tracks equalities of *partially applied
functions*, allowing reasoning steps such as:
```
a : Nat → Nat
f : (Nat → Nat) → (Nat → Nat)
h : f a = a
⊢ (f a) m = a m
g : Nat → Nat
f : Nat → Nat → Nat
h : f a = g
⊢ f a b = g b
```
This feature substantially improves `grind`’s support for higher-order and
partially-applied function equalities, while preserving compatibility with
first-order SMT behavior when `funCC` is disabled.
See the PR description for more details on usage.
### Controlling Theorem Instantiation
[#11428](https://github.com/leanprover/lean4/pull/11428) implements support for *guards* in {keywordOf Lean.Parser.Command.grind_pattern}`grind_pattern`. The new
feature provides additional control over theorem instantiation. For
example, consider the following monotonicity theorem:
```lean
opaque f : Nat → Nat
theorem fMono : x ≤ y → f x ≤ f y := sorry
```
With the new `guard` feature, we can instruct {tactic}`grind` to instantiate the
theorem *only if* `x ≤ y` is already known to be true in the current `grind` state:
```lean
grind_pattern fMono => f x, f y where
guard x ≤ y
x =/= y
```
This allows for a significant reduction in the number of theorem instantiations.
See the PR description for a more detailed discussion and example proof traces.
### Supplying Arbitrary Parameters
[#11268](https://github.com/leanprover/lean4/pull/11268) implements support for arbitrary {tactic}`grind` parameters. The feature
is similar to the one available in {tactic}`simp`, where a proof term is treated
as a local universe-polymorphic lemma. This feature relies on `grind -revert` (see [#11248](https://github.com/leanprover/lean4/pull/11248)).
For example, users can now write:
```lean
def snd (p : α × β) : β := p.2
theorem snd_eq (a : α) (b : β) : snd (a, b) = b := rfl
/--
trace: [grind.ematch.instance] snd_eq (a + 1): snd (a + 1, Type) = Type
[grind.ematch.instance] snd_eq (a + 1): snd (a + 1, true) = true
-/
#guard_msgs (trace) in
set_option trace.grind.ematch.instance true in
example (a : Nat) :
(snd (a + 1, true), snd (a + 1, Type), snd (2, 2)) =
(true, Type, snd (2, 2)) := by
grind [snd_eq (a + 1)]
```
Note that in the example above, `snd_eq` is instantiated only twice, but with different universe parameters.
### Grind Revert
[#11248](https://github.com/leanprover/lean4/pull/11248) implements the option `revert`, which is set to `false` by
default.
This is an internal change related to reverting hypotheses.
With the new default, the traces, counterexamples, and proof terms produced by {tactic}`grind` are different.
To recover the old `grind` behavior, use `grind +revert`.
### Other New Features in Grind
- `BitVec` support in `grind ring` ([#11639](https://github.com/leanprover/lean4/pull/11639))
and `grind lia` ([#11640](https://github.com/leanprover/lean4/pull/11640));
- New configuration option, `grind -reducible`, which allows expansion of non-reducible declarations
during definitional equality tests ([#11480](https://github.com/leanprover/lean4/pull/11480));
- Support for heterogeneous constructor injectivity ([#11491](https://github.com/leanprover/lean4/pull/11491));
- Support for the `LawfulOfScientific` class ([#11331](https://github.com/leanprover/lean4/pull/11331));
- Syntax `use [ns Foo]` and `instantiate only [ns Foo]` inside a `grind` tactic block,
which has the effect of activating all grind patterns scoped to that
namespace ([#11335](https://github.com/leanprover/lean4/pull/11335));
- New `grind_pattern` constraints ([#11405](https://github.com/leanprover/lean4/pull/11405) and
[#11409](https://github.com/leanprover/lean4/pull/11409)).
## Well-Founded Recursion on `Nat`
Definitions that use well-founded recursion are generally irreducible.
With [#7965](https://github.com/leanprover/lean4/pull/7965), when the termination measure is of type {name}`Nat`,
such definitions can be reduced, and an explicit `@[semireducible]` annotation is accepted
without the usual warning.
## Library Highlights
This release completes the revision of the {name}`String` API, including dependently typed {name}`String.Pos`,
full API support for {name}`String.Slice`, and iterators using the new `Iterator` API.
There are also many additions to the {name}`TreeMap`/{name}`HashMap` API, including intersection, difference, and equality.
These updates include some *breaking changes*, namely:
- [#11180](https://github.com/leanprover/lean4/pull/11180) redefines {name}`String.take` and variants to operate on
{name}`String.Slice`. While previously functions returning a substring of the
input sometimes returned {name}`String` and sometimes returned
{name}`Substring.Raw`, they now uniformly return {name}`String.Slice`.
This is a breaking change, because many functions now have a different
return type. So for example, if `s` is a string and `f` is a function
accepting a string, `f (s.drop 1)` will no longer compile because
`s.drop 1` is a `String.Slice`. To fix this, insert a call to `copy` to
restore the old behavior: `f (s.drop 1).copy`.
Of course, in many cases, there will be more efficient options. For
example, don't write `f <| s.drop 1 |>.copy |>.dropEnd 1 |>.copy`, write
`f <| s.drop 1 |>.dropEnd 1 |>.copy` instead. Also, instead of `(s.drop
1).copy = "Hello"`, write `s.drop 1 == "Hello".toSlice`.
- [#11446](https://github.com/leanprover/lean4/pull/11446) moves many constants of the iterator API from `Std.Iterators` to
the `Std` namespace in order to make them more convenient to use. These
constants include, but are not limited to, {name}`Iter`, {name}`IterM` and
{name}`IteratorLoop`. This is a breaking change. If something breaks, try
adding `open Std` in order to make these constants available again. If
some constants in the `Std.Iterators` namespace cannot be found, they
can be found directly in `Std` now.
## Breaking Changes
- [#11474](https://github.com/leanprover/lean4/pull/11474) and
[11562](https://github.com/leanprover/lean4/pull/11562)
generalize the `noConfusion` constructions to heterogeneous
equalities (assuming propositional equalities between parameters and indices).
This is a breaking change for whoever uses the `noConfusion` principle
manually and explicitly for a type with indices
Pass suitable `rfl` arguments, and use `eq_of_heq` on the resulting equalities as needed.
- [#11490](https://github.com/leanprover/lean4/pull/11490) prevents `try` swallowing heartbeat errors from nested `simp`
calls, and more generally ensures the `isRuntime` flag is propagated by
`throwNestedTacticEx`. This prevents the behavior of proofs (especially
those using `aesop`) being affected by the current recursion depth or
heartbeat limit.
This breaks a single caller in Mathlib where `simp` uses a lemma of the
form `x = f (g x)` and stack overflows, which can be fixed by
generalizing over `g x`.
# Language
````markdown
* [#7965](https://github.com/leanprover/lean4/pull/7965) lets recursive functions defined by well-founded recursion use a
different `fix` function when the termination measure is of type `Nat`.
This fix-point operator use structural recursion on “fuel”, initialized
by the given measure, and is thus reasonable to reduce, e.g. in `by
decide` proofs.
* [#11196](https://github.com/leanprover/lean4/pull/11196) avoids match splitter calculation from testing all quadratically
many pairs of alternatives for overlaps, by keeping track of possible
overlaps during matcher calculation, storing that information in the
`MatcherInfo`, and using that during matcher calculation.
* [#11200](https://github.com/leanprover/lean4/pull/11200) changes how sparse case expressions represent the
none-of-the-above information. Instead of many `x.ctorIdx ≠ i`
hypotheses, it introduces a single `Nat.hasNotBit mask x.ctorIdx`
hypothesis which compresses that information into a bitmask. This avoids
a quadratic overhead during splitter generation, where all n assumptions
would be refined through `.subst` and `.cases` constructions for all n
assumption of the splitter alternative.
* [#11221](https://github.com/leanprover/lean4/pull/11221) lets `realizeConst` use `withDeclNameForAuxNaming` so that
auxiliary definitions created there get non-clashing names.
* [#11222](https://github.com/leanprover/lean4/pull/11222) implements `elabToSyntax` for creating scoped syntax `s :
Syntax` for an arbitrary elaborator `el : Option Expr -> TermElabM Expr`
such that `elabTerm s = el`.
* [#11236](https://github.com/leanprover/lean4/pull/11236) extracts two modules from `Match.MatchEqs`, in preparation of
#11220
and to use the module system to draw clear boundaries between concerns
here.
* [#11239](https://github.com/leanprover/lean4/pull/11239) adds a `Unit` assumption to alternatives of the splitter that
would otherwise not have arguments. This fixes #11211.
* [#11245](https://github.com/leanprover/lean4/pull/11245) improves the error message encountered in the case of a type
class instance resolution failure, and adds an error explanation that
discusses the common new-user case of binary operation overloading and
points to the `trace.Meta.synthInstance` option for advanced debugging.
* [#11256](https://github.com/leanprover/lean4/pull/11256) replaces `MatcherInfo.numAltParams` with a more detailed data
structure that allows us, in particular, to distinguish between an
alternative for a constructor with a `Unit` field and the alternative
for a nullary constructor, where an artificial `Unit` argument is
introduced.
* [#11261](https://github.com/leanprover/lean4/pull/11261) continues the homogenization between matchers and splitters,
following up on #11256. In particular it removes the ambiguity whether
`numParams` includes the `discrEqns` or not.
* [#11269](https://github.com/leanprover/lean4/pull/11269) adds support for decidable equality of empty lists and empty
arrays. Decidable equality for lists and arrays is suitably modified so
that all diamonds are definitionally equal.
* [#11292](https://github.com/leanprover/lean4/pull/11292) adds intersection operation on
`ExtDTreeMap`/`ExtTreeMap`/`ExtTreeSet` and proves several lemmas about
it.
* [#11301](https://github.com/leanprover/lean4/pull/11301) allows setting reducibilityCoreExt in async contexts (e.g. when
using `mkSparseCasesOn` in a realizable definition)
* [#11302](https://github.com/leanprover/lean4/pull/11302) renames the CTests tests to use filenames as test names. So
instead of
```
2080 - leanruntest_issue5767.lean (Failed)
```
we get
```
2080 - tests/lean/run/issue5767.lean (Failed)
```
which allows Ctrl-Click’ing on them in the VSCode terminal.
* [#11303](https://github.com/leanprover/lean4/pull/11303) renames rename wrongly named `backwards.` options to
`backward.`
* [#11304](https://github.com/leanprover/lean4/pull/11304) documents that `backward.*` options are only temporary
migration aids and may disappear without further notice after 6 months
after their introduction. Users are kindly asked to report if they rely
on these options.
* [#11305](https://github.com/leanprover/lean4/pull/11305) removes the `group` field from option descriptions. It is
unused, does not have a clear meaning and often matches the first
component of the option name.
* [#11307](https://github.com/leanprover/lean4/pull/11307) removes all code that sets the `Option.Decl.group` field, which
is unused and has no clearly documented meaning.
* [#11325](https://github.com/leanprover/lean4/pull/11325) adds `CoreM.toIO'`, the analogue of `CoreM.toIO` dropping the
state from the return type, and similarly for `TermElabM.toIO'` and
`MetaM.toIO'`.
* [#11333](https://github.com/leanprover/lean4/pull/11333) adds infrastructure for parallel execution across Lean's tactic
monads.
* [#11338](https://github.com/leanprover/lean4/pull/11338) upstreams the `with_weak_namespace` command from Mathlib:
`with_weak_namespace <id> <cmd>` changes the current namespace to `<id>`
for the duration of executing command `<cmd>`, without causing scoped
things to go out of scope. This is in preparation for upstreaming the
`scoped[Foo.Bar]` syntax from Mathlib, which will be useful now that we
are adding `grind` annotations in scopes.
* [#11346](https://github.com/leanprover/lean4/pull/11346) modifies the error message for type synthesis failure for the
case where the type class in question is potentially derivable using a
`deriving` command. Also changes the error explanation for type class
instance synthesis failure with an illustration of this pattern.
* [#11347](https://github.com/leanprover/lean4/pull/11347) adds a focused error explanation aimed at the case where someone
tries to use Natural-Numbers-Game-style `induction` proofs directly in
Lean, where such proofs are not syntactically valid.
* [#11353](https://github.com/leanprover/lean4/pull/11353) applies beta reduction to specialization keys, allowing us to
reuse specializations in more situations.
* [#11379](https://github.com/leanprover/lean4/pull/11379) sets `@[macro_inline]` on the (trivial) `.ctorIdx` for inductive
types with one constructor, to reduce the number of symbols generated by
the compiler.
* [#11385](https://github.com/leanprover/lean4/pull/11385) lets implicit instance names avoid name clashes with private
declarations. This fixes #10329.
* [#11408](https://github.com/leanprover/lean4/pull/11408) adds a difference operation on
`ExtDTreeMap`/`ExtTreeMap`/`TreeSet` and proves several lemmas about it.
* [#11422](https://github.com/leanprover/lean4/pull/11422) uses a kernel-reduction optimized variant of `Mon.mul` in `grind`.
* [#11425](https://github.com/leanprover/lean4/pull/11425) changes `Lean.Order.CCPO` and `.CompleteLattice` to carry a
Prop. This avoids the `CCPO IO` instance from being `noncomputable`.
* [#11432](https://github.com/leanprover/lean4/pull/11432) fixes a typo in the docstring of `#guard_mgs`.
* [#11453](https://github.com/leanprover/lean4/pull/11453) fixes undefined behavior where `delete` (instead of `delete[]`)
is called on an object allocated with `new[]`.
* [#11456](https://github.com/leanprover/lean4/pull/11456) refines several error messages, mostly involving invalid
use of field notation, generalized field notation, and numeric
projection. Provides a new error explanation for field notation.
* [#11463](https://github.com/leanprover/lean4/pull/11463) fixes a panic in `getEqnsFor?` when called on matchers generated
from match expressions in theorem types.
* [#11474](https://github.com/leanprover/lean4/pull/11474) generalizes the `noConfusion` constructions to heterogeneous
equalities (assuming propositional equalities between the indices). This
lays ground work for better support for applying injection to
heterogeneous equalities in grind.
* [#11476](https://github.com/leanprover/lean4/pull/11476) adds a `` {givenInstance}`C` `` documentation role that adds an
instance of `C` to the document's local assumptions.
* [#11482](https://github.com/leanprover/lean4/pull/11482) gives suggestions based on the currently-available constants
when projecting from an unknown type.
* [#11485](https://github.com/leanprover/lean4/pull/11485) ensures that `Nat`s in `.olean` files use a deterministic
serialization in the case where `LEAN_USE_GMP` is not set.
* [#11490](https://github.com/leanprover/lean4/pull/11490) prevents `try` swallowing heartbeat errors from nested `simp`
calls, and more generally ensures the `isRuntime` flag is propagated by
`throwNestedTacticEx`. This prevents the behavior of proofs (especially
those using `aesop`) being affected by the current recursion depth or
heartbeat limit.
* [#11492](https://github.com/leanprover/lean4/pull/11492) uses the helper functions withImplicitBinderInfos and
mkArrowN in more places.
* [#11493](https://github.com/leanprover/lean4/pull/11493) makes `Match.MatchEqs` a leaf module, to be less restricted in
which features we can use there.
* [#11502](https://github.com/leanprover/lean4/pull/11502) adds two benchmarks for elaborating match statements of many
`Nat` literals, one without and one with splitter generation.
* [#11508](https://github.com/leanprover/lean4/pull/11508) avoids generating hyps when not needed (i.e. if there is a
catch-all so no completeness checking needed) during matching on values.
This tweak was made possible by #11220.
* [#11510](https://github.com/leanprover/lean4/pull/11510) avoids running substCore twice in caseValues.
* [#11511](https://github.com/leanprover/lean4/pull/11511) implements a linter that warns when a deprecated coercion is
applied. It also warns when the `Option` coercion or the
`Subarray`-to-`Array` coercion is used in `Init` or `Std`. The linter is
currently limited to `Coe` instances; `CoeFun` instances etc. are not
considered.
* [#11518](https://github.com/leanprover/lean4/pull/11518) provides an additional hint when the type of an autobound
implicit is required to have function type or equality type — this
fails, and the existing error message does not address the fact that the
source of the error is an unknown identifier that was automatically
bound.
* [#11541](https://github.com/leanprover/lean4/pull/11541) adds support for underscores as digit separators in
String.toNat?, String.toInt?, and related parsing functions. This makes
the string parsing functions consistent with Lean's numeric literal
syntax, which already supports underscores for readability (e.g.,
100_000_000).
* [#11554](https://github.com/leanprover/lean4/pull/11554) adds `@[suggest_for]` annotations to Lean, allowing lean to
provide corrections for `.every` or `.some` methods in place of `.all`
or `.any` methods for most default-imported types (arrays, lists,
strings, substrings, and subarrays, and vectors).
* [#11555](https://github.com/leanprover/lean4/pull/11555) scans the environment for viable replacements for a dotted
identifier (like `.zero`) and suggests concrete alternatives as
replacements.
* [#11562](https://github.com/leanprover/lean4/pull/11562) makes the `noConfusion` principles even more heterogeneous, by
allowing not just indices but also parameters to differ.
* [#11566](https://github.com/leanprover/lean4/pull/11566) lets the compiler treat per-constructor `noConfusion` like the
general one, and moves some more logic closer to no confusion
generation.
* [#11571](https://github.com/leanprover/lean4/pull/11571) lets `whnf` not consult `isNoConfusion`, to speed up this hot
path a bit.
* [#11587](https://github.com/leanprover/lean4/pull/11587) adjusts the new `meta` keyword of the experimental module system
not to imply `partial` for general consistency.
* [#11607](https://github.com/leanprover/lean4/pull/11607) makes argument-less tactic invocations of `Std.Do` tactics such
as `mintro` emit a proper error message "`mintro` expects at least one
pattern" instead of claiming that `Std.Tactic.Do` needs to be imported.
* [#11611](https://github.com/leanprover/lean4/pull/11611) fixes a `noConfusion` compilation introduced by #11562.
* [#11619](https://github.com/leanprover/lean4/pull/11619) allows Lean to present suggestions based on `@[suggest_for]`
annotations for unknown identifiers without internal dots. (The
annotations in #11554 only gave suggestion for dotted identifiers like
`Array.every`->`Array.all` and not for bare identifiers like
`Result`->`Except` or `ℕ`->`Nat`.)
* [#11620](https://github.com/leanprover/lean4/pull/11620) ports Batteries.WF to Init.WFC for executable well-founded
fixpoints. It introduces `csimp` theorems to replace the recursors and
non-executable definitions with executable definitions.
* [#11621](https://github.com/leanprover/lean4/pull/11621) causes Lean to search through `@[suggest_for]` annotations on
certain errors that look like unknown identifiers that got incorrectly
autobound. This will correctly identify that a declaration of type
`Maybe String` should be `Option String` instead.
* [#11624](https://github.com/leanprover/lean4/pull/11624) fixes a SIGFPE crash on x86_64 when evaluating `INT_MIN / -1` or
`INT_MIN % -1` for signed integer types.
* [#11637](https://github.com/leanprover/lean4/pull/11637) declares the module system as no longer experimental and makes
the `experimental.module` option a no-op, to be removed.
* [#11644](https://github.com/leanprover/lean4/pull/11644) makes `.ctorIdx` not an abbrev; we don't want `grind` to unfold
it.
* [#11645](https://github.com/leanprover/lean4/pull/11645) fixes the docstring of `propagateForallPropUp`. It was
copy’n’pasta before.
* [#11652](https://github.com/leanprover/lean4/pull/11652) teaches `grind` how to reduce `.ctorIdx` applied to
constructors. It can also handle tasks like
```
xs ≍ Vec.cons x xs' → xs.ctorIdx = 1
```
thanks to a `.ctorIdx.hinj` theorem (generated on demand).
* [#11657](https://github.com/leanprover/lean4/pull/11657) improves upon #11652 by keeping the kernel-reduction-optimized
definition.
````
# Library
```markdown
* [#8406](https://github.com/leanprover/lean4/pull/8406) adds lemmas of the form `getElem_swapIfInBounds*` and deprecates
`getElem_swap'`.
* [#9302](https://github.com/leanprover/lean4/pull/9302) modifies `Option.instDecidableEq` and `Option.decidableEqNone`
so that the latter can be made into a global instance without causing
diamonds. It also adds `Option.decidableNoneEq`.
* [#10204](https://github.com/leanprover/lean4/pull/10204) changes the interface of the `ForIn`, `ForIn'`, and `ForM`
type classes to not take a `Monad m` parameter. This is a breaking change
for most downstream `instance`s, which will now need to assume
`[Monad m]`.
* [#10945](https://github.com/leanprover/lean4/pull/10945) adds `Std.Tricho r`, a type class for relations which identifies
them as trichotomous. This is preferred to `Std.Antisymm (¬ r · ·)` in
all cases (which it is equivalent to).
* [#11038](https://github.com/leanprover/lean4/pull/11038) introduces a new fixpoint combinator,
`WellFounded.extrinsicFix`. A termination proof, if provided at all, can
be given extrinsically, i.e., looking at the term from the outside, and
is only required if one intends to formally verify the behavior of the
fixpoint. The new combinator is then applied to the iterator API.
Consumers such as `toList` or `ForIn` no longer require a proof that the
underlying iterator is finite. If one wants to ensure the termination of
them intrinsically, there are strictly terminating variants available
as, for example, `it.ensureTermination.toList` instead of `it.toList`.
* [#11112](https://github.com/leanprover/lean4/pull/11112) adds intersection operation on `DHashMap`/`HashMap`/`HashSet`
and provides several lemmas about its behaviour.
* [#11141](https://github.com/leanprover/lean4/pull/11141) provides a polymorphic `ForIn` instance for slices and an MPL
`spec` lemma for the iteration over slices using `for ... in`. It also
provides a version specialized to `Subarray`.
* [#11165](https://github.com/leanprover/lean4/pull/11165) provides intersection on `DTreeMap`/`TreeMap`/`TreeSet`and
provides several lemmas about it.
* [#11178](https://github.com/leanprover/lean4/pull/11178) provides more lemmas about `Subarray` and `ListSlice` and it
also adds support for subslices of these two types of slices.
* [#11180](https://github.com/leanprover/lean4/pull/11180) redefines `String.take` and variants to operate on
`String.Slice`. While previously functions returning a substring of the
input sometimes returned `String` and sometimes returned
`Substring.Raw`, they now uniformly return `String.Slice`.
* [#11212](https://github.com/leanprover/lean4/pull/11212) adds support for difference operation for
`DHashMap`/`HashMap`/`HashSet` and proves several lemmas about it.
* [#11218](https://github.com/leanprover/lean4/pull/11218) renames `String.offsetOfPos` to `String.Pos.Raw.offsetOfPos` to
align with the other `String.Pos.Raw` operations.
* [#11222](https://github.com/leanprover/lean4/pull/11222) implements `elabToSyntax` for creating scoped syntax `s :
Syntax` for an arbitrary elaborator `el : Option Expr -> TermElabM Expr`
such that `elabTerm s = el`.
* [#11223](https://github.com/leanprover/lean4/pull/11223) adds missing lemmas relating `emptyWithCapacity`/`empty` and
`toList`/`keys`/`values` for `DHashMap`/`HashMap`/`HashSet`.
* [#11231](https://github.com/leanprover/lean4/pull/11231) adds several lemmas that relate
`getMin`/`getMin?`/`getMin!`/`getMinD` and insertion to the empty
(D)TreeMap/TreeSet and their extensional variants.
* [#11232](https://github.com/leanprover/lean4/pull/11232) deprecates `String.toSubstring` in favor of
`String.toRawSubstring` (cf. #11154).
* [#11235](https://github.com/leanprover/lean4/pull/11235) registers a node kind for `Lean.Parser.Term.elabToSyntax` in
order to support the `Lean.Elab.Term.elabToSyntax` functionality without
registering a dedicated parser for user-accessible syntax.
* [#11237](https://github.com/leanprover/lean4/pull/11237) fixes the error thrown by `UInt64.fromJson?` and
`USize.fromJson?` to use the missing `s!`.
* [#11240](https://github.com/leanprover/lean4/pull/11240) renames `String.ValidPos` to `String.Pos`, `String.endValidPos`
to `String.endPos` and `String.startValidPos` to `String.startPos`.
* [#11241](https://github.com/leanprover/lean4/pull/11241) provides intersection operation for
`ExtDHashMap`/`ExtHashMap`/`ExtHashSet` and proves several lemmas about
it.
* [#11242](https://github.com/leanprover/lean4/pull/11242) significantly changes the signature of the `ToIterator` type
class. The obtained iterators' state is no longer dependently typed and
is an `outParam` instead of being bundled inside the class. Among other
benefits, `simp` can now rewrite inside of `Slice.toList` and
`Slice.toArray`. The downside is that we lose flexibility. For example,
the former combinator-based implementation of `Subarray`'s iterators is
no longer feasible because the states are dependently typed. Therefore,
this PR provides a hand-written iterator for `Subarray`, which does not
require a dependently typed state and is faster than the previous one.
* [#11243](https://github.com/leanprover/lean4/pull/11243) adds `ofArray` to `DHashMap`/`HashMap`/`HashSet` and proves a
simp lemma allowing to rewrite `ofArray` to `ofList`.
* [#11250](https://github.com/leanprover/lean4/pull/11250) introduces a function `String.split` which is based on
`String.Slice.split` and therefore supports all pattern types and
returns a `Std.Iter String.Slice`.
* [#11255](https://github.com/leanprover/lean4/pull/11255) reduces the allocations when using string patterns. In
particular
`startsWith`, `dropPrefix?`, `endsWith`, `dropSuffix?` are optimized.
* [#11263](https://github.com/leanprover/lean4/pull/11263) fixes several memory leaks in the new `String` API.
* [#11266](https://github.com/leanprover/lean4/pull/11266) adds `BEq` instance for `DHashMap`/`HashMap`/`HashSet` and their
extensional variants and proves lemmas relating it to the equivalence of
hashmaps/equality of extensional variants.
* [#11267](https://github.com/leanprover/lean4/pull/11267) renames congruence lemmas for union on
`DHashMap`/`HashMap`/`HashSet`/`DTreeMap`/`TreeMap`/`TreeSet` to fit the
convention of being in the `Equiv` namespace.
* [#11276](https://github.com/leanprover/lean4/pull/11276) cleans up the API around `String.find` and moves it uniformly to
the new position types `String.ValidPos` and `String.Slice.Pos`
* [#11281](https://github.com/leanprover/lean4/pull/11281) adds a few deprecations for functions that never existed but
that are still helpful for people migrating their code post-#11180.
* [#11282](https://github.com/leanprover/lean4/pull/11282) adds the alias `String.Slice.any` for `String.Slice.contains`.
* [#11285](https://github.com/leanprover/lean4/pull/11285) adds `Std.Slice.Pattern` instances for `p : Char -> Prop` as
long as `DecidablePred p`, to allow things like `"hello".dropWhile (· =
'h')`.
* [#11286](https://github.com/leanprover/lean4/pull/11286) adds a function `String.Slice.length`, with the following
deprecation string: There is no constant-time length function on slices.
Use `s.positions.count` instead, or `isEmpty` if you only need to know
whether the slice is empty.
* [#11289](https://github.com/leanprover/lean4/pull/11289) redefines `String.foldl`, `String.isNat` to use their
`String.Slice` counterparts.
* [#11290](https://github.com/leanprover/lean4/pull/11290) renames `String.replaceStartEnd` to `String.slice`,
`String.replaceStart` to `String.sliceFrom`, and `String.replaceEnd` to
`String.sliceTo`, and similar for the corresponding functions on
`String.Slice`.
* [#11299](https://github.com/leanprover/lean4/pull/11299) add many `@[grind]` annotations for `Fin`, and updates the
tests.
* [#11308](https://github.com/leanprover/lean4/pull/11308) redefines `front` and `back` on `String` to go through
`String.Slice` and adds the new `String` functions `front?`, `back?`,
`positions`, `chars`, `revPositions`, `revChars`, `byteIterator`,
`revBytes`, `lines`.
* [#11316](https://github.com/leanprover/lean4/pull/11316) adds `grind_pattern Exists.choose_spec => P.choose`.
* [#11317](https://github.com/leanprover/lean4/pull/11317) adds `grind_pattern Subtype.property => self.val`.
* [#11321](https://github.com/leanprover/lean4/pull/11321) provides specialized lemmas about `Nat` ranges, including `simp`
annotations and induction principles for proving properties for all
ranges.
* [#11327](https://github.com/leanprover/lean4/pull/11327) adds two lemmas to prove `a / c < b / c`.
* [#11341](https://github.com/leanprover/lean4/pull/11341) adds a coercion from `String` to `String.Slice`.
* [#11343](https://github.com/leanprover/lean4/pull/11343) renames `String.bytes` to `String.toByteArray`.
* [#11354](https://github.com/leanprover/lean4/pull/11354) adds simple lemmas that show that searching from a position in a
string returns something that is at least that position.
* [#11357](https://github.com/leanprover/lean4/pull/11357) updates the `foldr`, `all`, `any` and `contains` functions on
`String` to be defined in terms of their `String.Slice` counterparts.
* [#11358](https://github.com/leanprover/lean4/pull/11358) adds `String.Slice.toInt?` and variants.
* [#11376](https://github.com/leanprover/lean4/pull/11376) aims to improve the performance of `String.contains`,
`String.find`, etc. when using patterns of type `Char` or `Char -> Bool`
by moving the needle out of the iterator state and thus working around
missing unboxing in the compiler.
* [#11380](https://github.com/leanprover/lean4/pull/11380) renames `String.Slice.Pos.ofSlice` to `String.Pos.ofToSlice` to
adhere with the (yet-to-be documented) naming convention for mapping
positions to positions. It then adds several new functions so that for
every way to construct a slice from a string and slice, there are now
functions for mapping positions forwards and backwards along this
construction.
* [#11384](https://github.com/leanprover/lean4/pull/11384) adds the necessary instances for `grind` to reason about
`String.Pos.Raw`, `String.Pos` and `String.Slice.Pos`.
* [#11399](https://github.com/leanprover/lean4/pull/11399) adds support for the difference operation for
`ExtDHashMap`/`ExtHashMap`/`ExtHashSet` and proves several lemmas about
it.
* [#11404](https://github.com/leanprover/lean4/pull/11404) adds BEq instance for `DTreeMap`/`TreeMap`/`TreeSet` and their
extensional variants and proves lemmas relating it to the equivalence of
hashmaps/equality of extensional variants.
* [#11407](https://github.com/leanprover/lean4/pull/11407) adds the difference operation on `DTreeMap`/`TreeMap`/`TreeSet`
and proves several lemmas about it.
* [#11421](https://github.com/leanprover/lean4/pull/11421) adds decidable equality to `DHashMap`/`HashMap`/`HashSet` and
their extensional variants.
* [#11439](https://github.com/leanprover/lean4/pull/11439) performs minor maintenance on the String API
* [#11448](https://github.com/leanprover/lean4/pull/11448) moves the `Inhabited` instances in constant `DTreeMap` (and
related) queries, such as `Const.get!`, where the `Inhabited` instance
can be provided before proving a key.
* [#11452](https://github.com/leanprover/lean4/pull/11452) adds lemmas stating that if a get operation returns a value,
then the queried key must be contained in the collection. These lemmas
are added for HashMap and TreeMap-based collections, with a similar
lemma also added for `Init.getElem`.
* [#11465](https://github.com/leanprover/lean4/pull/11465) fixes various typos across the codebase in documentation and
comments.
* [#11503](https://github.com/leanprover/lean4/pull/11503) marks `Char -> Bool` patterns as default instances for string
search. This means that things like `" ".find (·.isWhitespace)` can now
be elaborated without error.
* [#11521](https://github.com/leanprover/lean4/pull/11521) fixes a segmentation fault that was triggered when initializing
a new timer and a reset was called at the same time.
* [#11527](https://github.com/leanprover/lean4/pull/11527) adds decidable equality to `DTreeMap`/`TreeMap`/`TreeSet` and
their extensional variants.
* [#11528](https://github.com/leanprover/lean4/pull/11528) adds lemmas relating `minKey?` and `min?` on the keys list for
all `DTreeMap` and other containers derived from it.
* [#11542](https://github.com/leanprover/lean4/pull/11542) removes `@[grind =]` from `List.countP_eq_length_filter` and
`Array.countP_eq_size_filter`, as users reported this was problematic.
* [#11548](https://github.com/leanprover/lean4/pull/11548) adds `Lean.ToJson` and `Lean.FromJson` instances for
`String.Slice`.
* [#11565](https://github.com/leanprover/lean4/pull/11565) adds lemmas that relate `insert`/`insertIfNew` and `toList` on
`DTreeMap`/`DHashMap`-derived containers.
* [#11574](https://github.com/leanprover/lean4/pull/11574) adds a lemma that the cast of a natural number into any ordered
ring is non-negative. We can't annotate this directly for `grind`, but
will probably add this to `grind`'s linarith internals.
* [#11578](https://github.com/leanprover/lean4/pull/11578) refactors the usage of `get` operation on
`HashMap`/`TreeMap`/`ExtHashMap`/`ExtTreeMap` to `getElem` instance.
* [#11591](https://github.com/leanprover/lean4/pull/11591) adds missing lemmas about how `ReaderT.run`, `OptionT.run`,
`StateT.run`, and `ExceptT.run` interact with `MonadControl` operations.
* [#11596](https://github.com/leanprover/lean4/pull/11596) adds `@[suggest_for ℤ]` on `Int` and `@[suggest_for ℚ]` on
`Rat`, following the pattern established by `@[suggest_for ℕ]` on `Nat`
in #11554.
* [#11600](https://github.com/leanprover/lean4/pull/11600) adds a few lemmas about `EStateM.run` on basic operations.
* [#11625](https://github.com/leanprover/lean4/pull/11625) adds `@[expose]` to `decidable_of_bool` so that
proofs-by-`decide` elsewhere that reduce to `decidable_of_bool` continue
to reduce.
* [#11654](https://github.com/leanprover/lean4/pull/11654) updates the `grind` docstring. It was still mentioning `cutsat`
which has been renamed to `lia`. This issue was reported during ItaLean.
```
# Tactics
````markdown
* [#11226](https://github.com/leanprover/lean4/pull/11226) finally removes the old `grind` framework `SearchM`. It has been
replaced with the new `Action` framework.
* [#11244](https://github.com/leanprover/lean4/pull/11244) fixes minor issues in `grind`. In preparation for adding `grind
-revert`.
* [#11247](https://github.com/leanprover/lean4/pull/11247) fixes an issue in the `grind` preprocessor. `simp` may introduce
assigned (universe) metavariables (e.g., when performing
zeta-reduction).
* [#11248](https://github.com/leanprover/lean4/pull/11248) implements the option `revert`, which is set to `false` by
default. To recover the old `grind` behavior, you should use `grind
+revert`. Previously, `grind` used the `RevSimpIntro` idiom, i.e., it
would revert all hypotheses and then re-introduce them while simplifying
and applying eager `cases`. This idiom created several problems:
* Users reported that `grind` would include unnecessary parameters. See
[here](https://leanprover.zulipchat.com/#narrow/channel/270676-lean4/topic/Grind.20aggressively.20includes.20local.20hypotheses.2E/near/554887715).
* Unnecessary section variables were also being introduced. See the new
test contributed by Sebastian Graf.
* Finally, it prevented us from supporting arbitrary parameters as we do
in `simp`. In `simp`, I implemented a mechanism that simulates local
universe-polymorphic theorems, but this approach could not be used in
`grind` because there is no mechanism for reverting (and re-introducing)
local universe-polymorphic theorems. Adding such a mechanism would
require substantial work: I would need to modify the local context
object. I considered maintaining a substitution from the original
variables to the new ones, but this is also tricky, because the mapping
would have to be stored in the `grind` goal objects, and it is not just
a simple mapping. After reverting everything, I would need to keep a
sequence of original variables that must be added to the mapping as we
re-introduce them, but eager case splits complicate this quite a bit.
The whole approach felt overly messy.
* [#11265](https://github.com/leanprover/lean4/pull/11265) marks the automatically generated `sizeOf` theorems as `grind`
theorems.
* [#11268](https://github.com/leanprover/lean4/pull/11268) implements support for arbitrary `grind` parameters. The feature
is similar to the one available in `simp`, where a proof term is treated
as a local universe-polymorphic lemma. This feature relies on `grind
-revert` (see #11248). For example, users can now write:
```lean
def snd (p : α × β) : β := p.2
theorem snd_eq (a : α) (b : β) : snd (a, b) = b := rfl
* [#11273](https://github.com/leanprover/lean4/pull/11273) fixes a bug during proof construction in `grind`.
* [#11295](https://github.com/leanprover/lean4/pull/11295) fixes a bug in the propagation rules for `ite` and `dite` used
in `grind`. The bug prevented equalities from being propagated to the
satellite solvers. Here is an example affected by this issue.
* [#11315](https://github.com/leanprover/lean4/pull/11315) fixes an issue affecting `grind -revert`. In this mode, assigned
metavariables in hypotheses were not being instantiated. This issue was
affecting two files in Mathlib.
* [#11318](https://github.com/leanprover/lean4/pull/11318) fixes a local declaration internalization in `grind` that was
exposed when using `grind -revert`. This bug was affecting a `grind`
proof in Mathlib.
* [#11319](https://github.com/leanprover/lean4/pull/11319) improves the support for `Fin n` in `grind` when `n` is not a
numeral.
* [#11323](https://github.com/leanprover/lean4/pull/11323) introduces a new `grind` option, `funCC` (enabled by default),
which extends congruence closure to *function-valued* equalities. When
`funCC` is enabled, `grind` tracks equalities of **partially applied
functions**, allowing reasoning steps such as:
```lean
a : Nat → Nat
f : (Nat → Nat) → (Nat → Nat)
h : f a = a
⊢ (f a) m = a m
* [#11326](https://github.com/leanprover/lean4/pull/11326) ensures that users can provide `grind` proof parameters whose
types are not `forall`-quantified. Examples:
```lean
opaque f : Nat → Nat
axiom le_f (a : Nat) : a ≤ f a
* [#11330](https://github.com/leanprover/lean4/pull/11330) renames the `cutsat` tactic to `lia` for better alignment with
standard terminology in the theorem proving community.
* [#11331](https://github.com/leanprover/lean4/pull/11331) adds support for the `LawfulOfScientific` class in `grind`.
Examples:
```lean
open Lean Grind Std
variable [LE α] [LT α] [LawfulOrderLT α] [Field α] [OfScientific α]
[LawfulOfScientific α] [IsLinearOrder α] [OrderedRing α]
example : (2 / 3 : α) ≤ (0.67 : α) := by grind
example : (1.2 : α) ≤ (1.21 : α) := by grind
example : (2 / 3 : α) ≤ (67 / 100 : α) := by grind
example : (1.2345 : α) ≤ (1.2346 : α) := by grind
example : (2.3 : α) ≤ (4.5 : α) := by grind
example : (2.3 : α) ≤ (5/2 : α) := by grind
```
* [#11332](https://github.com/leanprover/lean4/pull/11332) adds a `grind_annotated "YYYY-MM-DD"` command that marks files
as manually annotated for grind.
* [#11334](https://github.com/leanprover/lean4/pull/11334) adds an explicit normalization layer for ring constraints in the
`grind linarith` module. For example, it will be used to clean up
denominators when the ring is a field.
* [#11335](https://github.com/leanprover/lean4/pull/11335) enables the syntax `use [ns Foo]` and `instantiate only [ns
Foo]` inside a `grind` tactic block, and has the effect of activating
all grind patterns scoped to that namespace. We can use this to
implement specialized tactics using `grind`, but only controlled subsets
of theorems.
* [#11348](https://github.com/leanprover/lean4/pull/11348) activates the `grind_annotated` command in
`Init.Data.List.Lemmas` by removing the TODO comment and uncommenting
the command.
* [#11350](https://github.com/leanprover/lean4/pull/11350) implements a helper simproc for `grind`. It is part of the
infrastructure used to cleanup denominators in `grind linarith`.
* [#11365](https://github.com/leanprover/lean4/pull/11365) enables parallelism in `try?`. Currently, we replace the
`attempt_all` stages (there are two, one for builtin tactics including
`grind` and `simp_all`, and a second one for all user extensions) with
parallel versions. We do not (yet?) change the behaviour of `first`
based stages.
* [#11373](https://github.com/leanprover/lean4/pull/11373) makes the library suggestions extension state available when
importing from `module` files.
* [#11375](https://github.com/leanprover/lean4/pull/11375) adds support for cleaning up denominators in `grind linarith`
when the type is a `Field`.
* [#11391](https://github.com/leanprover/lean4/pull/11391) implements new kinds of constraints for the `grind_pattern`
command. These constraints allow users to control theorem instantiation
in `grind`.
It requires a manual `update-stage0` because the change affects the
`.olean` format, and the PR fails without it.
* [#11396](https://github.com/leanprover/lean4/pull/11396) changes `set_library_suggestions` to create an auxiliary
definition marked with `@[library_suggestions]`, rather than storing
`Syntax` directly in the environment extension. This enables better
persistence and consistency of library suggestions across modules.
* [#11405](https://github.com/leanprover/lean4/pull/11405) implements the following `grind_pattern` constraints:
```lean
grind_pattern fax => f x where
depth x < 2
* [#11409](https://github.com/leanprover/lean4/pull/11409) implements support for the `grind_pattern` constraints
`is_value` and `is_strict_value`.
* [#11410](https://github.com/leanprover/lean4/pull/11410) fixes a kernel type mismatch error in grind's denominator
cleanup feature. When generating proofs involving inverse numerals (like
`2⁻¹`), the proof context is compacted to only include variables
actually used. This involves renaming variable indices - e.g., if
original indices were `{0: r, 1: 2⁻¹}` and only `2⁻¹` is used, it gets
renamed to index 0.
* [#11412](https://github.com/leanprover/lean4/pull/11412) fixes an issue where `grind` would fail after multiple
`norm_cast`
calls with the error "unexpected metadata found during internalization".
* [#11428](https://github.com/leanprover/lean4/pull/11428) implements support for **guards** in `grind_pattern`. The new
feature provides additional control over theorem instantiation. For
example, consider the following monotonicity theorem:
```lean
opaque f : Nat → Nat
theorem fMono : x ≤ y → f x ≤ f y := ...
```
* [#11429](https://github.com/leanprover/lean4/pull/11429) documents the `grind_pattern` command for manually selecting
theorem instantiation patterns, including multi-patterns and the
constraint system (`=/=`, `=?=`, `size`, `depth`, `is_ground`,
`is_value`, `is_strict_value`, `gen`, `max_insts`, `guard`, `check`).
* [#11462](https://github.com/leanprover/lean4/pull/11462) adds `solve_by_elim` as a fallback in the `try?` tactic's simple
tactics. When `rfl` and `assumption` both fail but `solve_by_elim`
succeeds (e.g., for goals requiring hypothesis chaining or
backtracking), `try?` will now suggest `solve_by_elim`.
* [#11464](https://github.com/leanprover/lean4/pull/11464) improves the error message when no library suggestions engine is
registered to recommend importing `Lean.LibrarySuggestions.Default` for
the built-in engine.
* [#11466](https://github.com/leanprover/lean4/pull/11466) removes the "first pass" behavior where `exact?` and `apply?`
would try `solve_by_elim` on the original goal before doing library
search. This simplifies the `librarySearch` API and focuses these
tactics on their primary purpose: finding library lemmas.
* [#11468](https://github.com/leanprover/lean4/pull/11468) adds `+suggestions` support to `solve_by_elim`, following the
pattern established by `grind +suggestions` and `simp_all +suggestions`.
* [#11469](https://github.com/leanprover/lean4/pull/11469) adds `+grind` and `+try?` options to `exact?` and `apply?`
tactics.
* [#11471](https://github.com/leanprover/lean4/pull/11471) fixes an incorrect reducibility setting when using `grind`
interactive mode.
* [#11480](https://github.com/leanprover/lean4/pull/11480) adds the `grind` option `reducible` (default: `true`). When
enabled, definitional equality tests expand only declarations marked as
`@[reducible]`.
Use `grind -reducible` to allow expansion of non-reducible declarations
during definitional equality tests.
This option affects only definitional equality; the canonicalizer and
theorem pattern internalization always unfold reducible declarations
regardless of this setting.
* [#11481](https://github.com/leanprover/lean4/pull/11481) fixes a bug in `grind?`. The suggestion using the `grind`
interactive mode was dropping the configuration options provided by the
user. In the following account, the third suggestion was dropping the
`-reducible` option.
* [#11484](https://github.com/leanprover/lean4/pull/11484) fixes a bug in the `grind` pattern validation. The bug affected
type classes that were propositions.
* [#11487](https://github.com/leanprover/lean4/pull/11487) adds a heterogeneous version of the constructor injectivity
theorems. These theorems are useful for indexed families, and will be
used in `grind`.
* [#11491](https://github.com/leanprover/lean4/pull/11491) implements heterogeneous constructor injectivity in `grind`.
* [#11494](https://github.com/leanprover/lean4/pull/11494) re-enables star-indexed lemmas as a fallback for `exact?` and
`apply?`.
* [#11519](https://github.com/leanprover/lean4/pull/11519) marks `Nat` power and divisibility theorems for `grind`. We use
the new `grind_pattern` constraints to control theorem instantiation.
Examples:
```lean
example {x m n : Nat} (h : x = 4 ^ (m + 1) * n) : x % 4 = 0 := by
grind
* [#11520](https://github.com/leanprover/lean4/pull/11520) implements the constraint `not_value x` in the `grind_pattern`
command. It is the negation of the constraint `is_value`.
* [#11522](https://github.com/leanprover/lean4/pull/11522) implements `grind` propagators for `Nat` operators that have a
simproc associated with them, but do not have any theory solver support.
Examples:
```lean
example (a b : Nat) : a = 3 → b = 6 → a &&& b = 2 := by grind
example (a b : Nat) : a = 3 → b = 6 → a ||| b = 7 := by grind
example (a b : Nat) : a = 3 → b = 6 → a ^^^ b = 5 := by grind
example (a b : Nat) : a = 3 → b = 6 → a <<< b = 192 := by grind
example (a b : Nat) : a = 1135 → b = 6 → a >>> b = 17 := by grind
```
* [#11547](https://github.com/leanprover/lean4/pull/11547) ensures the auxiliary definitions created by
`register_try?_tactic` are internal implementation details that should
not be visible to user-facing linters.
* [#11556](https://github.com/leanprover/lean4/pull/11556) adds a `+all` option to `exact?` and `apply?` that collects all
successful lemmas instead of stopping at the first complete solution.
* [#11573](https://github.com/leanprover/lean4/pull/11573) fixes `grind` rejecting dot notation terms, mistaking them for
local hypotheses.
* [#11579](https://github.com/leanprover/lean4/pull/11579) ensures that ground theorems are properly handled as `grind`
parameters. Additionally, `grind [(thm)]` and `grind [thm]` should be
handled the same way.
* [#11580](https://github.com/leanprover/lean4/pull/11580) adds a missing `Nat.cast` missing normalization rule for
`grind`. Example:
```lean
example (n : Nat) : Nat.cast n = n := by
grind
```
* [#11589](https://github.com/leanprover/lean4/pull/11589) improves indexing for `grind` patterns. We now include symbols
occurring in nested ground patterns. This important to minimize the
number of activated E-match theorems.
* [#11593](https://github.com/leanprover/lean4/pull/11593) fixes an issue where `grind` did not display deprecation
warnings when deprecated lemmas were used in its argument list.
* [#11594](https://github.com/leanprover/lean4/pull/11594) fixes `grind?` to include term parameters (like `[show P by
tac]`) in its suggestions. Previously, these were being dropped because
term arguments are stored in `extraFacts` and not tracked via E-matching
like named lemmas.
* [#11604](https://github.com/leanprover/lean4/pull/11604) fixes how theorems without parameters are handled in `grind`.
* [#11605](https://github.com/leanprover/lean4/pull/11605) fixes a bug in the internalizer of `a^p` terms in `grind
linarith`.
* [#11609](https://github.com/leanprover/lean4/pull/11609) improves the case-split heuristics in `grind`. In this PR, we do
not increment the number of case splits in the first case. The idea is
to leverage non-chronological backtracking: if the first case is solved
using a proof that doesn't depend on the case hypothesis, we backtrack
and close the original goal directly. In this scenario, the case-split
was "free", it didn't contribute to the proof. By not counting it, we
allow deeper exploration when case-splits turn out to be irrelevant.
The new heuristic addresses the second example in #11545
* [#11613](https://github.com/leanprover/lean4/pull/11613) ensures we apply the ring normalizer to equalities being
propagated from the `grind` core module to `grind lia`. It also ensures
we use the safe/managed polynomial functions when normalizing.
* [#11615](https://github.com/leanprover/lean4/pull/11615) adds a normalization rule for `Int.subNatNat` to `grind`.
* [#11628](https://github.com/leanprover/lean4/pull/11628) adds a few `*` normalization rules for `Semiring`s to `grind`.
* [#11629](https://github.com/leanprover/lean4/pull/11629) adds a missing condition in the pattern normalization code used
in `grind`. It should ignore support ground terms.
* [#11635](https://github.com/leanprover/lean4/pull/11635) ensures the pattern normalizer used in `grind` does violate
assumptions made by the gadgets `Grind.genPattern` and
`Grind.getHEqPattern`.
* [#11638](https://github.com/leanprover/lean4/pull/11638) fixes bitvector literal internalization in `grind`. The fix
ensures theorems indexed by `BitVec.ofNat` are properly activated.
* [#11639](https://github.com/leanprover/lean4/pull/11639) adds support for `BitVec.ofNat` in `grind ring`. Example:
```lean
example (x : BitVec 8) : (x - 16#8)*(x + 272#8) = x^2 := by
grind
```
* [#11640](https://github.com/leanprover/lean4/pull/11640) adds support for `BitVec.ofNat` in `grind lia`. Example:
```lean
example (x y : BitVec 8) : y < 254#8 → x > 2#8 + y → x > 1#8 + y := by
grind
```
* [#11653](https://github.com/leanprover/lean4/pull/11653) adds propagation rules corresponding to the `Semiring`
normalization rules introduced in #11628. The new rules apply only to
non-commutative semirings, since support for them in `grind` is limited.
The normalization rules introduced unexpected behavior in Mathlib
because they neutralize parameters such as `one_mul`: any theorem
instance associated with such a parameter is reduced to `True` by the
normalizer.
* [#11656](https://github.com/leanprover/lean4/pull/11656) adds support for `Int.sign`, `Int.fdiv`, `Int.tdiv`, `Int.fmod`,
`Int.tmod`, and `Int.bmod` to `grind`. These operations are just
preprocessed away. We assume that they are not very common in practice.
Examples:
```lean
example {x y : Int} : y = 0 → (x.fdiv y) = 0 := by grind
example {x y : Int} : y = 0 → (x.tdiv y) = 0 := by grind
example {x y : Int} : y = 0 → (x.fmod y) = x := by grind
example {x y : Int} : y = 1 → (x.fdiv (2 - y)) = x := by grind
example {x : Int} : x > 0 → x.sign = 1 := by grind
example {x : Int} : x < 0 → x.sign = -1 := by grind
example {x y : Int} : x.sign = 0 → x*y = 0 := by grind
```
* [#11658](https://github.com/leanprover/lean4/pull/11658) fixes a bug in the internalization of parametric literals in
`grind`. That is, literals whose type is `BitVec _` or `Fin _`.
* [#11659](https://github.com/leanprover/lean4/pull/11659) adds `MessageData.withNamingContext` when generating pattern
suggestions at `@[grind]`. It fixes another issue reported during
ItaLean.
* [#11660](https://github.com/leanprover/lean4/pull/11660) fixes another theorem activation issue in `grind`.
* [#11663](https://github.com/leanprover/lean4/pull/11663) fixes the `grind` pattern validator. It covers the case where an
instance is not tagged with the implicit instance binder. This happens
in declarations such as
```lean
ZeroMemClass.zero_mem {S : Type} {M : outParam Type} {inst1 : Zero M} {inst2 : SetLike S M}
[self : @ZeroMemClass S M inst1 inst2] (s : S) : 0 ∈ s
```
````
# Compiler
```markdown
* [#11082](https://github.com/leanprover/lean4/pull/11082) prevents symbol clashes between (non-`@[export]`) definitions
from different Lean packages.
* [#11185](https://github.com/leanprover/lean4/pull/11185) fixes the `reduceArity` compiler pass to consider
over-applications to functions that have their arity reduced.
Previously, this pass assumed that the amount of arguments to
applications was always the same as the number of parameters in the
signature. This is usually true, since the compiler eagerly introduces
parameters as long as the return type is a function type, resulting in a
function with a return type that isn't a function type. However, for
dependent types that sometimes are function types and sometimes not,
this assumption is broken, resulting in the additional parameters to be
dropped.
* [#11210](https://github.com/leanprover/lean4/pull/11210) fixes a bug in the LCNF simplifier unearthed while working on
#11078. In some situations caused by `unsafeCast`, the simplifier would
record incorrect information about `cases`, leading to further bugs down
the line.
* [#11215](https://github.com/leanprover/lean4/pull/11215) fixes an issue where header nesting levels were properly tracked
between, but not within, moduledocs.
* [#11217](https://github.com/leanprover/lean4/pull/11217) fixes fallout of the closure allocator changes in #10982. As far
as we know
this bug only meaningfully manifests in non default build configurations
without mimalloc such as:
`cmake --preset release -DUSE_MIMALLOC=OFF`
* [#11310](https://github.com/leanprover/lean4/pull/11310) makes the specializer (correctly) share more cache keys across
invocations, causing us to produce less code bloat.
* [#11340](https://github.com/leanprover/lean4/pull/11340) fixes a miscompilation when encountering projections of non
trivial structure types.
* [#11362](https://github.com/leanprover/lean4/pull/11362) accelerates termination of the ElimDeadBranches compiler pass.
* [#11366](https://github.com/leanprover/lean4/pull/11366) sorts the declarations fed into ElimDeadBranches in increasing
size. This can improve performance when we are dealing with a lot of
iterations.
* [#11381](https://github.com/leanprover/lean4/pull/11381) fixes a bug where the closed term extraction does not respect
the implicit invariant of the
c emitter to have closed term decls first, other decls second, within an
SCC. This bug has not yet
been triggered in the wild but was unearthed during work on upcoming
modifications of the
specializer.
* [#11383](https://github.com/leanprover/lean4/pull/11383) fixes the compilation of structure projections with unboxed
arguments marked `extern`, adding missing `dec` instructions. It led to
leaking single allocations when such functions were used as closures or
in the interpreter.
* [#11388](https://github.com/leanprover/lean4/pull/11388) is a followup of #11381 and enforces the invariants on ordering
of closed terms and constants required by the EmitC pass properly by
toposorting before saving the declarations into the Environment.
* [#11426](https://github.com/leanprover/lean4/pull/11426) closes #11356.
* [#11445](https://github.com/leanprover/lean4/pull/11445) slightly improves the types involved in creating boxed
declarations. Previously the type of
the vdecl used for the return was always `tobj` when returning a boxed
scalar. This is not the most
precise annotation we can give.
* [#11451](https://github.com/leanprover/lean4/pull/11451) adapts the lambda lifter in LCNF to eta contract instead of
lambda lift if possible. This prevents the creation of a few hundred
unnecessary lambdas across the code base.
* [#11517](https://github.com/leanprover/lean4/pull/11517) implements constant folding for Nat.mul
* [#11525](https://github.com/leanprover/lean4/pull/11525) makes the LCNF simplifier eliminate cases where all alts are
`.unreach` to just an `.unreach`.
an `.unreach`
* [#11530](https://github.com/leanprover/lean4/pull/11530) introduces the new `tagged_return` attribute. It allows users to
mark `extern` declarations to be guaranteed to always return `tagged`
return values. Unlike with `object` or `tobject` the compiler does not
emit reference counting operations for them. In the future information
from this attribute will be used for a more powerful analysis to remove
reference counts when possible.
* [#11576](https://github.com/leanprover/lean4/pull/11576) removes the old ElimDeadBranches pass and shifts the new one
past lambda lifting.
* [#11586](https://github.com/leanprover/lean4/pull/11586) allows projections on `tagged` values in the IR type system.
```
# Documentation
```markdown
* [#11119](https://github.com/leanprover/lean4/pull/11119) introduces a clarifying note to "undefined identifier" error
messages when the undefined identifier is in a syntactic position where
autobinding might generally apply, but where and autobinding is
disabled. A corresponding note is made in the `lean.unknownIdentifier`
error explanation.
* [#11364](https://github.com/leanprover/lean4/pull/11364) adds missing docstrings for constants that occur in the
reference manual.
* [#11472](https://github.com/leanprover/lean4/pull/11472) adds missing docstrings for the `mkSlice` methods.
* [#11550](https://github.com/leanprover/lean4/pull/11550) reviews the docstrings for `Std.Do` that will appear in the Lean
reference manual and adds those that were missing.
* [#11575](https://github.com/leanprover/lean4/pull/11575) fixes a typo in the docstring of the `cases` tactic.
* [#11595](https://github.com/leanprover/lean4/pull/11595) documents that tests in `tests/lean/run/` run with
`-Dlinter.all=false`, and explains how to enable specific linters when
testing linter behavior.
```
# Server
```markdown
* [#11162](https://github.com/leanprover/lean4/pull/11162) reduces the memory consumption of the language server (the
watchdog process in particular). In Mathlib, it reduces memory
consumption by about 1GB.
* [#11164](https://github.com/leanprover/lean4/pull/11164) ensures that the code action provided on unknown identifiers
correctly inserts `public` and/or `meta` in `module`s
* [#11577](https://github.com/leanprover/lean4/pull/11577) fixes the tactic framework reporting file progress bar ranges
that cover up progress inside tactic blocks nested in tactic
combinators. This is a purely visual change, incremental re-elaboration
inside supported combinators was not affected.
```
# Lake
```markdown
* [#11198](https://github.com/leanprover/lean4/pull/11198) fixes an error message in Lake which suggested incorrect
lakefile syntax.
* [#11216](https://github.com/leanprover/lean4/pull/11216) ensures that the `text` argument of `computeArtifact` is always
provided in Lake code, fixing a hashing bug with
`buildArtifactUnlessUpToDate` in the process.
* [#11270](https://github.com/leanprover/lean4/pull/11270) adds a module resolution procedure to Lake to disambiguate
modules that are defined in multiple packages.
* [#11500](https://github.com/leanprover/lean4/pull/11500) adds a workspace-index to the name of the package used by build
target. To clarify the distinction between the different uses of a
package's name, this PR also deprecates `Package.name` for more
use-specific variants (e.g., `Package.keyName`, `Package.prettyName`,
`Package.origName`).
```
# Other
````markdown
* [#11328](https://github.com/leanprover/lean4/pull/11328) fixes freeing memory accidentally retained for each document
version in the language server on certain elaboration workloads. The
issue must have existed since 4.18.0.
* [#11437](https://github.com/leanprover/lean4/pull/11437) adds recording functionality such that `shake` can more
precisely track whether an import should be preserved solely for its
`attribute` commands.
* [#11496](https://github.com/leanprover/lean4/pull/11496) implements new flags and annotations for `shake` for use in
Mathlib:
> Options:
> --keep-implied
> Preserves existing imports that are implied by other imports and thus
not technically needed
> anymore
>
> --keep-prefix
> If an import `X` would be replaced in favor of a more specific import
`X.Y...` it implies,
> preserves the original import instead. More generally, prefers
inserting `import X` even if it
> was not part of the original imports as long as it was in the original
transitive import closure
> of the current module.
>
> --keep-public
> Preserves all `public` imports to avoid breaking changes for external
downstream modules
>
> --add-public
> Adds new imports as `public` if they have been in the original public
closure of that module.
> In other words, public imports will not be removed from a module
unless they are unused even
> in the private scope, and those that are removed will be re-added as
`public` in downstream
> modules even if only needed in the private scope there. Unlike
`--keep-public`, this may
> introduce breaking changes but will still limit the number of inserted
imports.
>
> Annotations:
> The following annotations can be added to Lean files in order to
configure the behavior of
> `shake`. Only the substring `shake: ` directly followed by a directive
is checked for, so multiple
> directives can be mixed in one line such as `-- shake:
keep-downstream, shake: keep-all`, and they
> can be surrounded by arbitrary comments such as `-- shake: keep
(metaprogram output dependency)`.
>
> * `module -- shake: keep-downstream`:
> Preserves this module in all (current) downstream modules, adding new
imports of it if needed.
>
> * `module -- shake: keep-all`:
> Preserves all existing imports in this module as is. New imports now
needed because of upstream
> changes may still be added.
>
> * `import X -- shake: keep`:
> Preserves this specific import in the current module. The most common
use case is to preserve a
> public import that will be needed in downstream modules to make sense
of the output of a
> metaprogram defined in this module. For example, if a tactic is
defined that may synthesize a
> reference to a theorem when run, there is no way for `shake` to detect
this by itself and the
> module of that theorem should be publicly imported and annotated with
`keep` in the tactic's
> module.
> ```
> public import X -- shake: keep (metaprogram output dependency)
>
> ...
>
> elab \"my_tactic\" : tactic => do
> ... mkConst ``f -- `f`, defined in `X`, may appear in the output of
this tactic
> ```
* [#11507](https://github.com/leanprover/lean4/pull/11507) optimizes the filesystem accesses during importing for a ~3% win
on Linux, potentially more on other platforms.
```` |
reference-manual/Manual/Releases/v4_25_1.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.25.1 (2025-11-18)" =>
%%%
tag := "release-v4.25.1"
file := "v4.25.1"
%%%
```markdown
Lean `v4.25.1` is a bug fix release fixing a caching problem in `lake`, affecting certain downstream dependencies of `ProofWidgets4`.
``` |
reference-manual/Manual/Releases/v4_11_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.11.0 (2024-09-02)" =>
%%%
tag := "release-v4.11.0"
file := "v4.11.0"
%%%
````markdown
### Language features, tactics, and metaprograms
* The variable inclusion mechanism has been changed. Like before, when a definition mentions a variable, Lean will add it as an argument of the definition, but now in theorem bodies, variables are not included based on usage in order to ensure that changes to the proof cannot change the statement of the overall theorem. Instead, variables are only available to the proof if they have been mentioned in the theorem header or in an **`include` command** or are instance implicit and depend only on such variables. The **`omit` command** can be used to omit included variables.
See breaking changes below.
PRs: [#4883](https://github.com/leanprover/lean4/pull/4883), [#4814](https://github.com/leanprover/lean4/pull/4814), [#5000](https://github.com/leanprover/lean4/pull/5000), [#5036](https://github.com/leanprover/lean4/pull/5036), [#5138](https://github.com/leanprover/lean4/pull/5138), [0edf1b](https://github.com/leanprover/lean4/commit/0edf1bac392f7e2fe0266b28b51c498306363a84).
* **Recursive definitions**
* Structural recursion can now be explicitly requested using
```
termination_by structural x
```
in analogy to the existing `termination_by x` syntax that causes well-founded recursion to be used.
[#4542](https://github.com/leanprover/lean4/pull/4542)
* [#4672](https://github.com/leanprover/lean4/pull/4672) fixes a bug that could lead to ill-typed terms.
* The `termination_by?` syntax no longer forces the use of well-founded recursion, and when structural
recursion is inferred, it will print the result using the `termination_by structural` syntax.
* **Mutual structural recursion** is now supported. This feature supports both mutual recursion over a non-mutual
data type, as well as recursion over mutual or nested data types:
```lean
mutual
def Even : Nat → Prop
| 0 => True
| n+1 => Odd n
def Odd : Nat → Prop
| 0 => False
| n+1 => Even n
end
mutual
inductive A
| other : B → A
| empty
inductive B
| other : A → B
| empty
end
mutual
def A.size : A → Nat
| .other b => b.size + 1
| .empty => 0
def B.size : B → Nat
| .other a => a.size + 1
| .empty => 0
end
inductive Tree where | node : List Tree → Tree
mutual
def Tree.size : Tree → Nat
| node ts => Tree.list_size ts
def Tree.list_size : List Tree → Nat
| [] => 0
| t::ts => Tree.size t + Tree.list_size ts
end
```
Functional induction principles are generated for these functions as well (`A.size.induct`, `A.size.mutual_induct`).
Nested structural recursion is still not supported.
PRs: [#4639](https://github.com/leanprover/lean4/pull/4639), [#4715](https://github.com/leanprover/lean4/pull/4715), [#4642](https://github.com/leanprover/lean4/pull/4642), [#4656](https://github.com/leanprover/lean4/pull/4656), [#4684](https://github.com/leanprover/lean4/pull/4684), [#4715](https://github.com/leanprover/lean4/pull/4715), [#4728](https://github.com/leanprover/lean4/pull/4728), [#4575](https://github.com/leanprover/lean4/pull/4575), [#4731](https://github.com/leanprover/lean4/pull/4731), [#4658](https://github.com/leanprover/lean4/pull/4658), [#4734](https://github.com/leanprover/lean4/pull/4734), [#4738](https://github.com/leanprover/lean4/pull/4738), [#4718](https://github.com/leanprover/lean4/pull/4718), [#4733](https://github.com/leanprover/lean4/pull/4733), [#4787](https://github.com/leanprover/lean4/pull/4787), [#4788](https://github.com/leanprover/lean4/pull/4788), [#4789](https://github.com/leanprover/lean4/pull/4789), [#4807](https://github.com/leanprover/lean4/pull/4807), [#4772](https://github.com/leanprover/lean4/pull/4772)
* [#4809](https://github.com/leanprover/lean4/pull/4809) makes unnecessary `termination_by` clauses cause warnings, not errors.
* [#4831](https://github.com/leanprover/lean4/pull/4831) improves handling of nested structural recursion through non-recursive types.
* [#4839](https://github.com/leanprover/lean4/pull/4839) improves support for structural recursive over inductive predicates when there are reflexive arguments.
* `simp` tactic
* [#4784](https://github.com/leanprover/lean4/pull/4784) sets configuration `Simp.Config.implicitDefEqProofs` to `true` by default.
* `omega` tactic
* [#4612](https://github.com/leanprover/lean4/pull/4612) normalizes the order that constraints appear in error messages.
* [#4695](https://github.com/leanprover/lean4/pull/4695) prevents pushing casts into multiplications unless it produces a non-trivial linear combination.
* [#4989](https://github.com/leanprover/lean4/pull/4989) fixes a regression.
* `decide` tactic
* [#4711](https://github.com/leanprover/lean4/pull/4711) switches from using default transparency to *at least* default transparency when reducing the `Decidable` instance.
* [#4674](https://github.com/leanprover/lean4/pull/4674) adds detailed feedback on `decide` tactic failure. It tells you which `Decidable` instances it unfolded, if it get stuck on `Eq.rec` it gives a hint about avoiding tactics when defining `Decidable` instances, and if it gets stuck on `Classical.choice` it gives hints about classical instances being in scope. During this process, it processes `Decidable.rec`s and matches to pin blame on a non-reducing instance.
* `@[ext]` attribute
* [#4543](https://github.com/leanprover/lean4/pull/4543) and [#4762](https://github.com/leanprover/lean4/pull/4762) make `@[ext]` realize `ext_iff` theorems from user `ext` theorems. Fixes the attribute so that `@[local ext]` and `@[scoped ext]` are usable. The `@[ext (iff := false)]` option can be used to turn off `ext_iff` realization.
* [#4694](https://github.com/leanprover/lean4/pull/4694) makes "go to definition" work for the generated lemmas. Also adjusts the core library to make use of `ext_iff` generation.
* [#4710](https://github.com/leanprover/lean4/pull/4710) makes `ext_iff` theorem preserve inst implicit binder types, rather than making all binder types implicit.
* `#eval` command
* [#4810](https://github.com/leanprover/lean4/pull/4810) introduces a safer `#eval` command that prevents evaluation of terms that contain `sorry`. The motivation is that failing tactics, in conjunction with operations such as array accesses, can lead to the Lean process crashing. Users can use the new `#eval!` command to use the previous unsafe behavior. ([#4829](https://github.com/leanprover/lean4/pull/4829) adjusts a test.)
* [#4447](https://github.com/leanprover/lean4/pull/4447) adds `#discr_tree_key` and `#discr_tree_simp_key` commands, for helping debug discrimination tree failures. The `#discr_tree_key t` command prints the discrimination tree keys for a term `t` (or, if it is a single identifier, the type of that constant). It uses the default configuration for generating keys. The `#discr_tree_simp_key` command is similar to `#discr_tree_key`, but treats the underlying type as one of a simp lemma, that is it transforms it into an equality and produces the key of the left-hand side.
For example,
```
#discr_tree_key (∀ {a n : Nat}, bar a (OfNat.ofNat n))
-- bar _ (@OfNat.ofNat Nat _ _)
#discr_tree_simp_key Nat.add_assoc
-- @HAdd.hAdd Nat Nat Nat _ (@HAdd.hAdd Nat Nat Nat _ _ _) _
```
* [#4741](https://github.com/leanprover/lean4/pull/4741) changes option parsing to allow user-defined options from the command line. Initial options are now re-parsed and validated after importing. Command line option assignments prefixed with `weak.` are silently discarded if the option name without the prefix does not exist.
* **Deriving handlers**
* [7253ef](https://github.com/leanprover/lean4/commit/7253ef8751f76bcbe0e6f46dcfa8069699a2bac7) and [a04f3c](https://github.com/leanprover/lean4/commit/a04f3cab5a9fe2870825af6544ca13c5bb766706) improve the construction of the `BEq` deriving handler.
* [86af04](https://github.com/leanprover/lean4/commit/86af04cc08c0dbbe0e735ea13d16edea3465f850) makes `BEq` deriving handler work when there are dependently typed fields.
* [#4826](https://github.com/leanprover/lean4/pull/4826) refactors the `DecidableEq` deriving handle to use `termination_by structural`.
* **Metaprogramming**
* [#4593](https://github.com/leanprover/lean4/pull/4593) adds `unresolveNameGlobalAvoidingLocals`.
* [#4618](https://github.com/leanprover/lean4/pull/4618) deletes deprecated functions from 2022.
* [#4642](https://github.com/leanprover/lean4/pull/4642) adds `Meta.lambdaBoundedTelescope`.
* [#4731](https://github.com/leanprover/lean4/pull/4731) adds `Meta.withErasedFVars`, to enter a context with some fvars erased from the local context.
* [#4777](https://github.com/leanprover/lean4/pull/4777) adds assignment validation at `closeMainGoal`, preventing users from circumventing the occurs check for tactics such as `exact`.
* [#4807](https://github.com/leanprover/lean4/pull/4807) introduces `Lean.Meta.PProdN` module for packing and projecting nested `PProd`s.
* [#5170](https://github.com/leanprover/lean4/pull/5170) fixes `Syntax.unsetTrailing`. A consequence of this is that "go to definition" now works on the last module name in an `import` block (issue [#4958](https://github.com/leanprover/lean4/issues/4958)).
### Language server, widgets, and IDE extensions
* [#4727](https://github.com/leanprover/lean4/pull/4727) makes it so that responses to info view requests come as soon as the relevant tactic has finished execution.
* [#4580](https://github.com/leanprover/lean4/pull/4580) makes it so that whitespace changes do not invalidate imports, and so starting to type the first declaration after imports should no longer cause them to reload.
* [#4780](https://github.com/leanprover/lean4/pull/4780) fixes an issue where hovering over unimported builtin names could result in a panic.
### Pretty printing
* [#4558](https://github.com/leanprover/lean4/pull/4558) fixes the `pp.instantiateMVars` setting and changes the default value to `true`.
* [#4631](https://github.com/leanprover/lean4/pull/4631) makes sure syntax nodes always run their formatters. Fixes an issue where if `ppSpace` appears in a `macro` or `elab` command then it does not format with a space.
* [#4665](https://github.com/leanprover/lean4/pull/4665) fixes a bug where pretty printed signatures (for example in `#check`) were overly hoverable due to `pp.tagAppFns` being set.
* [#4724](https://github.com/leanprover/lean4/pull/4724) makes `match` pretty printer be sensitive to `pp.explicit`, which makes hovering over a `match` in the Infoview show the underlying term.
* [#4764](https://github.com/leanprover/lean4/pull/4764) documents why anonymous constructor notation isn't pretty printed with flattening.
* [#4786](https://github.com/leanprover/lean4/pull/4786) adjusts the parenthesizer so that only the parentheses are hoverable, implemented by having the parentheses "steal" the term info from the parenthesized expression.
* [#4854](https://github.com/leanprover/lean4/pull/4854) allows arbitrarily long sequences of optional arguments to be omitted from the end of applications, versus the previous conservative behavior of omitting up to one optional argument.
### Library
* `Nat`
* [#4597](https://github.com/leanprover/lean4/pull/4597) adds bitwise lemmas `Nat.and_le_(left|right)`.
* [#4874](https://github.com/leanprover/lean4/pull/4874) adds simprocs for simplifying bit expressions.
* `Int`
* [#4903](https://github.com/leanprover/lean4/pull/4903) fixes performance of `HPow Int Nat Int` synthesis by rewriting it as a `NatPow Int` instance.
* `UInt*` and `Fin`
* [#4605](https://github.com/leanprover/lean4/pull/4605) adds lemmas.
* [#4629](https://github.com/leanprover/lean4/pull/4629) adds `*.and_toNat`.
* `Option`
* [#4599](https://github.com/leanprover/lean4/pull/4599) adds `get` lemmas.
* [#4600](https://github.com/leanprover/lean4/pull/4600) adds `Option.or`, a version of `Option.orElse` that is strict in the second argument.
* `GetElem`
* [#4603](https://github.com/leanprover/lean4/pull/4603) adds `getElem_congr` to help with rewriting indices.
* `List` and `Array`
* Upstreamed from Batteries: [#4586](https://github.com/leanprover/lean4/pull/4586) upstreams `List.attach` and `Array.attach`, [#4697](https://github.com/leanprover/lean4/pull/4697) upstreams `List.Subset` and `List.Sublist` and API, [#4706](https://github.com/leanprover/lean4/pull/4706) upstreams basic material on `List.Pairwise` and `List.Nodup`, [#4720](https://github.com/leanprover/lean4/pull/4720) upstreams more `List.erase` API, [#4836](https://github.com/leanprover/lean4/pull/4836) and [#4837](https://github.com/leanprover/lean4/pull/4837) upstream `List.IsPrefix`/`List.IsSuffix`/`List.IsInfix` and add `Decidable` instances, [#4855](https://github.com/leanprover/lean4/pull/4855) upstreams `List.tail`, `List.findIdx`, `List.indexOf`, `List.countP`, `List.count`, and `List.range'`, [#4856](https://github.com/leanprover/lean4/pull/4856) upstreams more List lemmas, [#4866](https://github.com/leanprover/lean4/pull/4866) upstreams `List.pairwise_iff_getElem`, [#4865](https://github.com/leanprover/lean4/pull/4865) upstreams `List.eraseIdx` lemmas.
* [#4687](https://github.com/leanprover/lean4/pull/4687) adjusts `List.replicate` simp lemmas and simprocs.
* [#4704](https://github.com/leanprover/lean4/pull/4704) adds characterizations of `List.Sublist`.
* [#4707](https://github.com/leanprover/lean4/pull/4707) adds simp normal form tests for `List.Pairwise` and `List.Nodup`.
* [#4708](https://github.com/leanprover/lean4/pull/4708) and [#4815](https://github.com/leanprover/lean4/pull/4815) reorganize lemmas on list getters.
* [#4765](https://github.com/leanprover/lean4/pull/4765) adds simprocs for literal array accesses such as `#[1,2,3,4,5][2]`.
* [#4790](https://github.com/leanprover/lean4/pull/4790) removes type class assumptions for `List.Nodup.eraseP`.
* [#4801](https://github.com/leanprover/lean4/pull/4801) adds efficient `usize` functions for array types.
* [#4820](https://github.com/leanprover/lean4/pull/4820) changes `List.filterMapM` to run left-to-right.
* [#4835](https://github.com/leanprover/lean4/pull/4835) fills in and cleans up gaps in List API.
* [#4843](https://github.com/leanprover/lean4/pull/4843), [#4868](https://github.com/leanprover/lean4/pull/4868), and [#4877](https://github.com/leanprover/lean4/pull/4877) correct `List.Subset` lemmas.
* [#4863](https://github.com/leanprover/lean4/pull/4863) splits `Init.Data.List.Lemmas` into function-specific files.
* [#4875](https://github.com/leanprover/lean4/pull/4875) fixes statement of `List.take_takeWhile`.
* Lemmas: [#4602](https://github.com/leanprover/lean4/pull/4602), [#4627](https://github.com/leanprover/lean4/pull/4627), [#4678](https://github.com/leanprover/lean4/pull/4678) for `List.head` and `list.getLast`, [#4723](https://github.com/leanprover/lean4/pull/4723) for `List.erase`, [#4742](https://github.com/leanprover/lean4/pull/4742)
* `ByteArray`
* [#4582](https://github.com/leanprover/lean4/pull/4582) eliminates `partial` from `ByteArray.toList` and `ByteArray.findIdx?`.
* `BitVec`
* [#4568](https://github.com/leanprover/lean4/pull/4568) adds recurrence theorems for bitblasting multiplication.
* [#4571](https://github.com/leanprover/lean4/pull/4571) adds `shiftLeftRec` lemmas.
* [#4872](https://github.com/leanprover/lean4/pull/4872) adds `ushiftRightRec` and lemmas.
* [#4873](https://github.com/leanprover/lean4/pull/4873) adds `getLsb_replicate`.
* `Std.HashMap` added:
* [#4583](https://github.com/leanprover/lean4/pull/4583) **adds `Std.HashMap`** as a verified replacement for `Lean.HashMap`. See the PR for naming differences, but [#4725](https://github.com/leanprover/lean4/pull/4725) renames `HashMap.remove` to `HashMap.erase`.
* [#4682](https://github.com/leanprover/lean4/pull/4682) adds `Inhabited` instances.
* [#4732](https://github.com/leanprover/lean4/pull/4732) improves `BEq` argument order in hash map lemmas.
* [#4759](https://github.com/leanprover/lean4/pull/4759) makes lemmas resolve instances via unification.
* [#4771](https://github.com/leanprover/lean4/pull/4771) documents that hash maps should be used linearly to avoid expensive copies.
* [#4791](https://github.com/leanprover/lean4/pull/4791) removes `bif` from hash map lemmas, which is inconvenient to work with in practice.
* [#4803](https://github.com/leanprover/lean4/pull/4803) adds more lemmas.
* `SMap`
* [#4690](https://github.com/leanprover/lean4/pull/4690) upstreams `SMap.foldM`.
* `BEq`
* [#4607](https://github.com/leanprover/lean4/pull/4607) adds `PartialEquivBEq`, `ReflBEq`, `EquivBEq`, and `LawfulHashable` classes.
* `IO`
* [#4660](https://github.com/leanprover/lean4/pull/4660) adds `IO.Process.Child.tryWait`.
* [#4747](https://github.com/leanprover/lean4/pull/4747), [#4730](https://github.com/leanprover/lean4/pull/4730), and [#4756](https://github.com/leanprover/lean4/pull/4756) add `×'` syntax for `PProd`. Adds a delaborator for `PProd` and `MProd` values to pretty print as flattened angle bracket tuples.
* **Other fixes or improvements**
* [#4604](https://github.com/leanprover/lean4/pull/4604) adds lemmas for cond.
* [#4619](https://github.com/leanprover/lean4/pull/4619) changes some definitions into theorems.
* [#4616](https://github.com/leanprover/lean4/pull/4616) fixes some names with duplicated namespaces.
* [#4620](https://github.com/leanprover/lean4/pull/4620) fixes simp lemmas flagged by the simpNF linter.
* [#4666](https://github.com/leanprover/lean4/pull/4666) makes the `Antisymm` class be a `Prop`.
* [#4621](https://github.com/leanprover/lean4/pull/4621) cleans up unused arguments flagged by linter.
* [#4680](https://github.com/leanprover/lean4/pull/4680) adds imports for orphaned `Init` modules.
* [#4679](https://github.com/leanprover/lean4/pull/4679) adds imports for orphaned `Std.Data` modules.
* [#4688](https://github.com/leanprover/lean4/pull/4688) adds forward and backward directions of `not_exists`.
* [#4689](https://github.com/leanprover/lean4/pull/4689) upstreams `eq_iff_true_of_subsingleton`.
* [#4709](https://github.com/leanprover/lean4/pull/4709) fixes precedence handling for `Repr` instances for negative numbers for `Int` and `Float`.
* [#4760](https://github.com/leanprover/lean4/pull/4760) renames `TC` ("transitive closure") to `Relation.TransGen`.
* [#4842](https://github.com/leanprover/lean4/pull/4842) fixes `List` deprecations.
* [#4852](https://github.com/leanprover/lean4/pull/4852) upstreams some Mathlib attributes applied to lemmas.
* [93ac63](https://github.com/leanprover/lean4/commit/93ac635a89daa5a8e8ef33ec96b0bcbb5d7ec1ea) improves proof.
* [#4862](https://github.com/leanprover/lean4/pull/4862) and [#4878](https://github.com/leanprover/lean4/pull/4878) generalize the universe for `PSigma.exists` and rename it to `Exists.of_psigma_prop`.
* Typos: [#4737](https://github.com/leanprover/lean4/pull/4737), [7d2155](https://github.com/leanprover/lean4/commit/7d2155943c67c743409420b4546d47fadf73af1c)
* Docs: [#4782](https://github.com/leanprover/lean4/pull/4782), [#4869](https://github.com/leanprover/lean4/pull/4869), [#4648](https://github.com/leanprover/lean4/pull/4648)
### Lean internals
* **Elaboration**
* [#4596](https://github.com/leanprover/lean4/pull/4596) enforces `isDefEqStuckEx` at `unstuckMVar` procedure, causing isDefEq to throw a stuck defeq exception if the metavariable was created in a previous level. This results in some better error messages, and it helps `rw` succeed in synthesizing instances (see issue [#2736](https://github.com/leanprover/lean4/issues/2736)).
* [#4713](https://github.com/leanprover/lean4/pull/4713) fixes deprecation warnings when there are overloaded symbols.
* `elab_as_elim` algorithm:
* [#4722](https://github.com/leanprover/lean4/pull/4722) adds check that inferred motive is type-correct.
* [#4800](https://github.com/leanprover/lean4/pull/4800) elaborates arguments for parameters appearing in the types of targets.
* [#4817](https://github.com/leanprover/lean4/pull/4817) makes the algorithm correctly handle eliminators with explicit motive arguments.
* [#4792](https://github.com/leanprover/lean4/pull/4792) adds term elaborator for `Lean.Parser.Term.namedPattern` (e.g. `n@(n' + 1)`) to report errors when used in non-pattern-matching contexts.
* [#4818](https://github.com/leanprover/lean4/pull/4818) makes anonymous dot notation work when the expected type is a pi-type-valued type synonym.
* **Typeclass inference**
* [#4646](https://github.com/leanprover/lean4/pull/4646) improves `synthAppInstances`, the function responsible for synthesizing instances for the `rw` and `apply` tactics. Adds a synthesis loop to handle functions whose instances need to be synthesized in a complex order.
* **Inductive types**
* [#4684](https://github.com/leanprover/lean4/pull/4684) (backported as [98ee78](https://github.com/leanprover/lean4/commit/98ee789990f91ff5935627787b537911ef8773c4)) refactors `InductiveVal` to have a `numNested : Nat` field instead of `isNested : Bool`. This modifies the kernel.
* **Definitions**
* [#4776](https://github.com/leanprover/lean4/pull/4776) improves performance of `Replacement.apply`.
* [#4712](https://github.com/leanprover/lean4/pull/4712) fixes `.eq_def` theorem generation with messy universes.
* [#4841](https://github.com/leanprover/lean4/pull/4841) improves success of finding `T.below x` hypothesis when transforming `match` statements for `IndPredBelow`.
* **Diagnostics and profiling**
* [#4611](https://github.com/leanprover/lean4/pull/4611) makes kernel diagnostics appear when `diagnostics` is enabled even if it is the only section.
* [#4753](https://github.com/leanprover/lean4/pull/4753) adds missing `profileitM` functions.
* [#4754](https://github.com/leanprover/lean4/pull/4754) adds `Lean.Expr.numObjs` to compute the number of allocated sub-expressions in a given expression, primarily for diagnosing performance issues.
* [#4769](https://github.com/leanprover/lean4/pull/4769) adds missing `withTraceNode`s to improve `trace.profiler` output.
* [#4781](https://github.com/leanprover/lean4/pull/4781) and [#4882](https://github.com/leanprover/lean4/pull/4882) make the "use `set_option diagnostics true`" message be conditional on current setting of `diagnostics`.
* **Performance**
* [#4767](https://github.com/leanprover/lean4/pull/4767), [#4775](https://github.com/leanprover/lean4/pull/4775), and [#4887](https://github.com/leanprover/lean4/pull/4887) add `ShareCommon.shareCommon'` for sharing common terms. In an example with 16 million subterms, it is 20 times faster than the old `shareCommon` procedure.
* [#4779](https://github.com/leanprover/lean4/pull/4779) ensures `Expr.replaceExpr` preserves DAG structure in `Expr`s.
* [#4783](https://github.com/leanprover/lean4/pull/4783) documents performance issue in `Expr.replaceExpr`.
* [#4794](https://github.com/leanprover/lean4/pull/4794), [#4797](https://github.com/leanprover/lean4/pull/4797), [#4798](https://github.com/leanprover/lean4/pull/4798) make `for_each` use precise cache.
* [#4795](https://github.com/leanprover/lean4/pull/4795) makes `Expr.find?` and `Expr.findExt?` use the kernel implementations.
* [#4799](https://github.com/leanprover/lean4/pull/4799) makes `Expr.replace` use the kernel implementation.
* [#4871](https://github.com/leanprover/lean4/pull/4871) makes `Expr.foldConsts` use a precise cache.
* [#4890](https://github.com/leanprover/lean4/pull/4890) makes `expr_eq_fn` use a precise cache.
* **Utilities**
* [#4453](https://github.com/leanprover/lean4/pull/4453) upstreams `ToExpr FilePath` and `compile_time_search_path%`.
* **Module system**
* [#4652](https://github.com/leanprover/lean4/pull/4652) fixes handling of `const2ModIdx` in `finalizeImport`, making it prefer the original module for a declaration when a declaration is redeclared.
* **Kernel**
* [#4637](https://github.com/leanprover/lean4/pull/4637) adds a check to prevent large `Nat` exponentiations from evaluating. Elaborator reduction is controlled by the option `exponentiation.threshold`.
* [#4683](https://github.com/leanprover/lean4/pull/4683) updates comments in `kernel/declaration.h`, making sure they reflect the current Lean 4 types.
* [#4796](https://github.com/leanprover/lean4/pull/4796) improves performance by using `replace` with a precise cache.
* [#4700](https://github.com/leanprover/lean4/pull/4700) improves performance by fixing the implementation of move constructors and move assignment operators. Expression copying was taking 10% of total runtime in some workloads. See issue [#4698](https://github.com/leanprover/lean4/issues/4698).
* [#4702](https://github.com/leanprover/lean4/pull/4702) improves performance in `replace_rec_fn::apply` by avoiding expression copies. These copies represented about 13% of time spent in `save_result` in some workloads. See the same issue.
* **Other fixes or improvements**
* [#4590](https://github.com/leanprover/lean4/pull/4590) fixes a typo in some constants and `trace.profiler.useHeartbeats`.
* [#4617](https://github.com/leanprover/lean4/pull/4617) add 'since' dates to `deprecated` attributes.
* [#4625](https://github.com/leanprover/lean4/pull/4625) improves the robustness of the constructor-as-variable test.
* [#4740](https://github.com/leanprover/lean4/pull/4740) extends test with nice example reported on Zulip.
* [#4766](https://github.com/leanprover/lean4/pull/4766) moves `Syntax.hasIdent` to be available earlier and shakes dependencies.
* [#4881](https://github.com/leanprover/lean4/pull/4881) splits out `Lean.Language.Lean.Types`.
* [#4893](https://github.com/leanprover/lean4/pull/4893) adds `LEAN_EXPORT` for `sharecommon` functions.
* Typos: [#4635](https://github.com/leanprover/lean4/pull/4635), [#4719](https://github.com/leanprover/lean4/pull/4719), [af40e6](https://github.com/leanprover/lean4/commit/af40e618111581c82fc44de922368a02208b499f)
* Docs: [#4748](https://github.com/leanprover/lean4/pull/4748) (`Command.Scope`)
### Compiler, runtime, and FFI
* [#4661](https://github.com/leanprover/lean4/pull/4661) moves `Std` from `libleanshared` to much smaller `libInit_shared`. This fixes the Windows build.
* [#4668](https://github.com/leanprover/lean4/pull/4668) fixes initialization, explicitly initializing `Std` in `lean_initialize`.
* [#4746](https://github.com/leanprover/lean4/pull/4746) adjusts `shouldExport` to exclude more symbols to get below Windows symbol limit. Some exceptions are added by [#4884](https://github.com/leanprover/lean4/pull/4884) and [#4956](https://github.com/leanprover/lean4/pull/4956) to support Verso.
* [#4778](https://github.com/leanprover/lean4/pull/4778) adds `lean_is_exclusive_obj` (`Lean.isExclusiveUnsafe`) and `lean_set_external_data`.
* [#4515](https://github.com/leanprover/lean4/pull/4515) fixes calling programs with spaces on Windows.
### Lake
* [#4735](https://github.com/leanprover/lean4/pull/4735) improves a number of elements related to Git checkouts, cloud releases,
and related error handling.
* On error, Lake now prints all top-level logs. Top-level logs are those produced by Lake outside of the job monitor (e.g., when cloning dependencies).
* When fetching a remote for a dependency, Lake now forcibly fetches tags. This prevents potential errors caused by a repository recreating tags already fetched.
* Git error handling is now more informative.
* The builtin package facets `release`, `optRelease`, `extraDep` are now captions in the same manner as other facets.
* `afterReleaseSync` and `afterReleaseAsync` now fetch `optRelease` rather than `release`.
* Added support for optional jobs, whose failure does not cause the whole build to failure. Now `optRelease` is such a job.
* [#4608](https://github.com/leanprover/lean4/pull/4608) adds draft CI workflow when creating new projects.
* [#4847](https://github.com/leanprover/lean4/pull/4847) adds CLI options to control log levels. The `--log-level=<lv>` controls the minimum log level Lake should output. For instance, `--log-level=error` will only print errors (not warnings or info). Also, adds an analogous `--fail-level` option to control the minimum log level for build failures. The existing `--iofail` and `--wfail` options are respectively equivalent to `--fail-level=info` and `--fail-level=warning`.
* Docs: [#4853](https://github.com/leanprover/lean4/pull/4853)
### DevOps/CI
* **Workflows**
* [#4531](https://github.com/leanprover/lean4/pull/4531) makes release trigger an update of `release.lean-lang.org`.
* [#4598](https://github.com/leanprover/lean4/pull/4598) adjusts `pr-release` to the new `lakefile.lean` syntax.
* [#4632](https://github.com/leanprover/lean4/pull/4632) makes `pr-release` use the correct tag name.
* [#4638](https://github.com/leanprover/lean4/pull/4638) adds ability to manually trigger nightly release.
* [#4640](https://github.com/leanprover/lean4/pull/4640) adds more debugging output for `restart-on-label` CI.
* [#4663](https://github.com/leanprover/lean4/pull/4663) bumps up waiting for 10s to 30s for `restart-on-label`.
* [#4664](https://github.com/leanprover/lean4/pull/4664) bumps versions for `actions/checkout` and `actions/upload-artifacts`.
* [582d6e](https://github.com/leanprover/lean4/commit/582d6e7f7168e0dc0819099edaace27d913b893e) bumps version for `actions/download-artifact`.
* [6d9718](https://github.com/leanprover/lean4/commit/6d971827e253a4dc08cda3cf6524d7f37819eb47) adds back dropped `check-stage3`.
* [0768ad](https://github.com/leanprover/lean4/commit/0768ad4eb9020af0777587a25a692d181e857c14) adds Jira sync (for FRO).
* [#4830](https://github.com/leanprover/lean4/pull/4830) adds support to report CI errors on FRO Zulip.
* [#4838](https://github.com/leanprover/lean4/pull/4838) adds trigger for `nightly_bump_toolchain` on mathlib4 upon nightly release.
* [abf420](https://github.com/leanprover/lean4/commit/abf4206e9c0fcadf17b6f7933434fd1580175015) fixes msys2.
* [#4895](https://github.com/leanprover/lean4/pull/4895) deprecates Nix-based builds and removes interactive components. Users who prefer the flake build should maintain it externally.
* [#4693](https://github.com/leanprover/lean4/pull/4693), [#4458](https://github.com/leanprover/lean4/pull/4458), and [#4876](https://github.com/leanprover/lean4/pull/4876) update the **release checklist**.
* [#4669](https://github.com/leanprover/lean4/pull/4669) fixes the "max dynamic symbols" metric per static library.
* [#4691](https://github.com/leanprover/lean4/pull/4691) improves compatibility of `tests/list_simp` for retesting simp normal forms with Mathlib.
* [#4806](https://github.com/leanprover/lean4/pull/4806) updates the quickstart guide.
* [c02aa9](https://github.com/leanprover/lean4/commit/c02aa98c6a08c3a9b05f68039c071085a4ef70d7) documents the **triage team** in the contribution guide.
### Breaking changes
* For `@[ext]`-generated `ext` and `ext_iff` lemmas, the `x` and `y` term arguments are now implicit. Furthermore these two lemmas are now protected ([#4543](https://github.com/leanprover/lean4/pull/4543)).
* Now `trace.profiler.useHearbeats` is `trace.profiler.useHeartbeats` ([#4590](https://github.com/leanprover/lean4/pull/4590)).
* A bugfix in the structural recursion code may in some cases break existing code, when a parameter of the type of the recursive argument is bound behind indices of that type. This can usually be fixed by reordering the parameters of the function ([#4672](https://github.com/leanprover/lean4/pull/4672)).
* Now `List.filterMapM` sequences monadic actions left-to-right ([#4820](https://github.com/leanprover/lean4/pull/4820)).
* The effect of the `variable` command on proofs of `theorem`s has been changed. Whether such section variables are accessible in the proof now depends only on the theorem signature and other top-level commands, not on the proof itself. This change ensures that
* the statement of a theorem is independent of its proof. In other words, changes in the proof cannot change the theorem statement.
* tactics such as `induction` cannot accidentally include a section variable.
* the proof can be elaborated in parallel to subsequent declarations in a future version of Lean.
The effect of `variable`s on the theorem header as well as on other kinds of declarations is unchanged.
Specifically, section variables are included if they
* are directly referenced by the theorem header,
* are included via the new `include` command in the current section and not subsequently mentioned in an `omit` statement,
* are directly referenced by any variable included by these rules, OR
* are instance-implicit variables that reference only variables included by these rules.
For porting, a new option `deprecated.oldSectionVars` is included to locally switch back to the old behavior.
```` |
reference-manual/Manual/Releases/v4_0_0-m1.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.0.0-m1 (2021-01-04)" =>
%%%
tag := "release-v4.0.0-m1"
file := "v4.0.0-m1"
%%%
```markdown
The Lean development team is proud to announce the first milestone release of Lean 4. This release is aimed at experimentation with the new features of Lean 4, eventually leading to a full release of 4.0.0 ready for general use.
This release is the result of almost three years of work since the release of Lean 3.4.0, reworking, extending, and improving almost all aspects of Lean. More information about Lean 4 can be found in the [official documentation](https://leanprover.github.io/lean4/doc/) as well as in the introductory talk ["An overview of Lean 4"](https://www.youtube.com/watch?v=UeGvhfW1v9M) at Lean Together 2021.
Leonardo de Moura & Sebastian Ullrich
#### Acknowledgements
* Daniel Selsam - type class resolution, feedback, design discussions
* Marc Huisinga and Wojciech Nawrocki - Lean Server
* Joe Hendrix, Andrew Kent, Rob Dockins, Simon Winwood (Galois Inc) - early adopters, suggestions, feedback
* Daan Leijen, Simon Peyton Jones, Nikhil Swamy, Sebastian Graf, Max Wagner - design discussions, feedback, suggestions
``` |
reference-manual/Manual/Releases/v4_25_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.25.0 (2025-11-14)" =>
%%%
tag := "release-v4.25.0"
file := "v4.25.0"
%%%
````markdown
For this release, 398 changes landed. In addition to the 141 feature additions and 83 fixes listed below there were 21 refactoring changes, 9 documentation improvements, 4 performance improvements, 5 improvements to the test suite and 135 other changes.
## Highlights
Lean v4.25.0 release brings several exciting new features.
Editor integration adds interactivity to "try this" suggestions,
and Lake adds support for remote caching.
New language features include automated generation of specification theorems for
type class methods, coinductive predicates, and invariant suggestions in `mvcgen`.
`grind` receives an interactive mode that gives the user control over proof search
and can suggest reproducible proofs.
Its reasoning capabilities have been extended with support for injective
functions, non-commutative (semi)rings, and preorder and ordered ring structures.
The standard library features a redesigned `String` type and expanded async primitives.
Read on for the details!
### Apply "try this" Suggestions
[#10524](https://github.com/leanprover/lean4/pull/10524) adds support for interactivity (hover, go-to-definitions) for "try this"
messages that were introduced in [#9966](https://github.com/leanprover/lean4/pull/9966). In doing so, it moves the link
to apply a suggestion to a separate `[apply]` button in front of the
suggestion.
### Remote Caching with Lake
[#10188](https://github.com/leanprover/lean4/pull/10188) adds support for remote artifact caches (e.g., Reservoir) to
Lake. As part of this support, a new suite of `lake cache` CLI commands
has been introduced to help manage Lake's cache. Also, the existing
local cache support has been overhauled for better interplay with the
new remote support.
### Coinductive Predicates
[#10333](https://github.com/leanprover/lean4/pull/10333) introduces a `coinductive` keyword, that can be used to define
coinductive predicates via a syntax identical to the one for `inductive`
keyword.
For example, infinite sequence of transitions in a relation can be given by the following:
```lean
section
variable (α : Type)
coinductive infSeq (r : α → α → Prop) : α → Prop where
| step : r a b → infSeq r b → infSeq r a
/--
info: infSeq.coinduct (α : Type) (r : α → α → Prop) (pred : α → Prop) (hyp : ∀ (a : α), pred a → ∃ b, r a b ∧ pred b)
(a✝ : α) : pred a✝ → infSeq α r a✝
-/
#guard_msgs in
#check infSeq.coinduct
/--
info: infSeq.step (α : Type) (r : α → α → Prop) {a b : α} : r a b → infSeq α r b → infSeq α r a
-/
#guard_msgs in
#check infSeq.step
end
```
The machinery also supports `mutual` blocks, as well as mixing inductive and coinductive predicate definitions:
```lean
mutual
coinductive tick : Prop where
| mk : ¬tock → tick
inductive tock : Prop where
| mk : ¬tick → tock
end
/--
info: tick.mutual_induct (pred_1 pred_2 : Prop) (hyp_1 : pred_1 → pred_2 → False) (hyp_2 : (pred_1 → False) → pred_2) :
(pred_1 → tick) ∧ (tock → pred_2)
-/
#guard_msgs in
#check tick.mutual_induct
```
### Mvcgen Invariants Suggestions
[#10456](https://github.com/leanprover/lean4/pull/10456) and [#10566](https://github.com/leanprover/lean4/pull/10566)
implement `mvcgen invariants?` to suggest concrete invariants
based on how invariants are used in VCs.
These suggestions are intentionally simplistic and boil down to "this
holds at the start of the loop and this must hold at the end of the
loop":
```lean
import Std.Tactic.Do
open Std Do
def mySum (l : List Nat) : Nat := Id.run do
let mut acc := 0
for x in l do
acc := acc + x
return acc
/--
info: Try this:
[apply] invariants
· ⇓⟨xs, letMuts⟩ => ⌜xs.prefix = [] ∧ letMuts = 0 ∨ xs.suffix = [] ∧ letMuts = l.sum⌝
-/
#guard_msgs (info) in
theorem mySum_suggest_invariant (l : List Nat) : mySum l = l.sum := by
generalize h : mySum l = r
apply Id.of_wp_run_eq h
mvcgen invariants?
all_goals admit
```
When the loop body has an early return, it will helpfully suggest `Invariant.withEarlyReturn ...` as a skeleton:
```lean
import Std.Tactic.Do
import Std
open Std Do
def nodup (l : List Int) : Bool := Id.run do
let mut seen : HashSet Int := ∅
for x in l do
if x ∈ seen then
return false
seen := seen.insert x
return true
/--
info: Try this:
[apply] invariants
·
Invariant.withEarlyReturn (onReturn := fun r letMuts => ⌜l.Nodup ∧ (r = true ↔ l.Nodup)⌝) (onContinue :=
fun xs letMuts => ⌜xs.prefix = [] ∧ letMuts = ∅ ∨ xs.suffix = [] ∧ l.Nodup⌝)
-/
-- #guard_msgs (info) in
theorem nodup_suggest_invariant (l : List Int) : nodup l ↔ l.Nodup := by
generalize h : nodup l = r
apply Id.of_wp_run_eq h
mvcgen invariants?
all_goals admit
```
It still is the user's job to weaken this invariant such that it interpolates over all loop iterations,
but it is a good starting point for iterating. It is also useful because the user does not need to remember
the exact syntax.
### Grind
#### Interactive mode
`grind` has been extended with an interactive mode `grind => …`
([#10607](https://github.com/leanprover/lean4/pull/10607), [#10677](https://github.com/leanprover/lean4/pull/10677), ...)
```lean
example (x y : Nat) : x ≥ y + 1 → x > 0 := by
grind => skip; lia; done
```
Interactive mode comes with _anchors_ (also known as stable hash codes) for referencing terms occurring in a `grind` goal
([#10709](https://github.com/leanprover/lean4/pull/10709)).
In the interactive mode, it is possible to do the following:
- `instantiate` global and local theorems
([#10746](https://github.com/leanprover/lean4/pull/10746) and [#10841](https://github.com/leanprover/lean4/pull/10841));
- Inspect the state with `show_splits` and `show_state` ([#10709](https://github.com/leanprover/lean4/pull/10709)),
`show_true`, `show_false`, `show_asserted`, and `show_eqcs`
([#10690](https://github.com/leanprover/lean4/pull/10690));
- Inspect with filtering; each tactic may optionally have a suffix of the form `| filter?`
([#10828](https://github.com/leanprover/lean4/pull/10828));
- Make local assertions with `have` ([#10706](https://github.com/leanprover/lean4/pull/10706));
- Use tactics ([#10731](https://github.com/leanprover/lean4/pull/10731)):
- `focus <grind_tac_seq>`
- `next => <grind_tac_seq>`
- `any_goals <grind_tac_seq>`
- `all_goals <grind_tac_seq>`
- `grind_tac <;> grind_tac`
- `cases <anchor>`
- `tactic => <tac_seq>`
- Select anchors with `cases?`
([#10824](https://github.com/leanprover/lean4/pull/10824) - there's a screenshot in the PR description);
- Use grind solvers `ac`, `linarith`, `lia`, `ring` as actions
([#10812](https://github.com/leanprover/lean4/pull/10812) & [#10834](https://github.com/leanprover/lean4/pull/10834));
- Produce, when possible, a concrete grind script that closes the goal, using explicit grind tactic
steps, i.e., without any search, with `finish?` ([#10837](https://github.com/leanprover/lean4/pull/10837)):
```lean
/--
info: Try this:
[apply] ⏎
cases #b0f4
next => cases #50fc
next => cases #50fc <;> lia
-/
#guard_msgs in
example (p : Nat → Prop) (x y z w : Int) :
(x = 1 ∨ x = 2) →
(w = 1 ∨ w = 4) →
(y = 1 ∨ (∃ x : Nat, y = 3 - x ∧ p x)) →
(z = 1 ∨ z = 0) → x + y ≤ 6 := by
grind => finish?
```
The anchors in the generated script are based on stable hash codes.
Moreover, users can hover over them to see the exact term used in the case split.
#### Non-commutative (semi)ring normalization
- [#10375](https://github.com/leanprover/lean4/pull/10375) adds support for non-commutative ring normalization in `grind`.
The new normalizer also accounts for the `IsCharP` type class.
```lean
open Lean Grind
variable (R : Type u) [Ring R]
example (a b : R) : (a + 2 * b)^2 = a^2 + 2 * a * b + 2 * b * a + 4 * b^2 := by grind
variable [IsCharP R 4]
example (a b : R) : (a - b)^2 = a^2 - a * b - b * 5 * a + b^2 := by grind
```
- [#10421](https://github.com/leanprover/lean4/pull/10421) adds a normalizer for non-commutative semirings to `grind`.
```lean
open Lean.Grind
variable (R : Type u) [Semiring R]
example (a b : R) : (a + 2 * b)^2 = a^2 + 2 * a * b + 2 * b * a + 4 * b^2 := by grind
```
#### Injective functions
[#10445](https://github.com/leanprover/lean4/pull/10445),
[#10447](https://github.com/leanprover/lean4/pull/10447),
[#10482](https://github.com/leanprover/lean4/pull/10482), and
[#10483](https://github.com/leanprover/lean4/pull/10483) add support for injective functions in grind.
```lean
/-! Add some injectivity theorems. -/
def double (x : Nat) := 2*x
@[grind inj] theorem double_inj : Function.Injective double := by
grind [Function.Injective, double]
structure InjFn (α : Type) (β : Type) where
f : α → β
h : Function.Injective f
instance : CoeFun (InjFn α β) (fun _ => α → β) where
coe s := s.f
@[grind inj] theorem fn_inj (F : InjFn α β) : Function.Injective (F : α → β) := by
grind [Function.Injective, cases InjFn]
def toList (a : α) : List α := [a]
@[grind inj] theorem toList_inj : Function.Injective (toList : α → List α) := by
grind [Function.Injective, toList]
/-! Examples -/
example (x y : Nat) : toList (double x) = toList (double y) → x = y := by
grind
example (f : InjFn (List Nat) α) (x y z : Nat)
: f (toList (double x)) = f (toList y) →
y = double z →
x = z := by
grind
```
#### Grind order solver
Grind can now solve preorder and ordered ring problems
([#10562](https://github.com/leanprover/lean4/pull/10562), [#10598](https://github.com/leanprover/lean4/pull/10598) and [#10600](https://github.com/leanprover/lean4/pull/10600)).
The new solver, `grind order`, supports `Nat`, and handles positive and negative constraints.
```lean
open Lean Grind
example [LE α] [LT α] [Std.LawfulOrderLT α] [Std.IsLinearPreorder α] [CommRing α] [OrderedRing α]
(a b c d : α) : a - b ≤ 5 → ¬ (c ≤ b) → ¬ (d ≤ c + 2) → d ≤ a - 8 → False := by
grind -linarith (splits := 0)
```
#### New pattern inference heuristic
[#10422](https://github.com/leanprover/lean4/pull/10422) and [#10432](https://github.com/leanprover/lean4/pull/10432)
implement the new E-matching pattern inference heuristic for
`grind`. Here is a summary of the
new behavior.
- `[grind =]`, `[grind =_]`, `[grind _=_]`, `[grind <-=]`: no changes; we keep the current behavior.
- `[grind ->]`, `[grind <-]`, `[grind =>]`, `[grind <=]`: we stop using the _minimal indexable subexpression_ and instead use the first indexable one.
- `[grind! <mod>]`: behaves like `[grind <mod>]` but uses the minimal indexable subexpression restriction. We generate an error if the user writes `[grind! =]`, `[grind! =_]`, `[grind! _=_]`, or `[grind! <-=]`, since there is no pattern search in these cases.
- `[grind]`: it tries `=`, `=_`, `<-`, `->`, `<=`, `=>` with and without the minimal indexable subexpression restriction. For the ones that work, we generate a code action to encourage users to select the one they prefer.
- `[grind!]`: it tries `<-`, `->`, `<=`, `=>` using the minimal indexable subexpression restriction. For the ones that work, we generate a code action to encourage users to select the one they prefer.
- `[grind? <mod>]`: where `<mod>` is one of the modifiers above, it behaves like `[grind <mod>]` but also displays the pattern.
Example:
```lean
/--
info: Try these:
• [grind =] for pattern: [f (g #0)]
• [grind =_] for pattern: [r #0 #0]
• [grind! ←] for pattern: [g #0]
-/
#guard_msgs in
@[grind] axiom fg₇ : f (g x) = r x x
```
**Important**: Users can still use the old pattern inference heuristic
by setting:
```lean
set_option backward.grind.inferPattern true
```
### Specifications Derivation
Lean now provides automated generation of specification theorems for custom and derived type class instances:
- [#10302](https://github.com/leanprover/lean4/pull/10302) introduces the `@[method_specs]` attribute. It can be applied to
(certain) type class instances and define “specification theorems” for
the class’ operations, by taking the equational theorems of the
implementation function mentioned in the type class instance and
rephrasing them in terms of the overloaded operations. Fixes [#5295](https://github.com/leanprover/lean4/issues/5295).
```lean
inductive L α where
| nil : L α
| cons : α → L α → L α
def L.beqImpl [BEq α] : L α → L α → Bool
| nil, nil => true
| cons x xs, cons y ys => x == y && L.beqImpl xs ys
| _, _ => false
@[method_specs] instance [BEq α] : BEq (L α) := ⟨L.beqImpl⟩
/--
info: theorem instBEqL.beq_spec_2.{u_1} : ∀ {α : Type u_1} [inst : BEq α] (x_2 : α) (xs : L α) (y : α) (ys : L α),
(L.cons x_2 xs == L.cons y ys) = (x_2 == y && xs == ys)
-/
#guard_msgs(pass trace, all) in
#print sig instBEqL.beq_spec_2
```
- [#10346](https://github.com/leanprover/lean4/pull/10346) lets `deriving BEq` and `deriving Ord` use `@[method_specs]`
from [#10302](https://github.com/leanprover/lean4/pull/10302) when applicable (i.e. when not using `partial`).
```lean
inductive O (α : Type u) where
| none
| some : α → O α
deriving BEq, Ord
/--
info: theorem instBEqO.beq_spec_2.{u_1} : ∀ {α : Type u_1} [inst : BEq α] (a b : α), (O.some a == O.some b) = (a == b)
-/
#guard_msgs in #print sig instBEqO.beq_spec_2
/--
info: theorem instOrdO.compare_spec_2.{u_1} : ∀ {α : Type u_1} [inst : Ord α] (x : O α),
(x = O.none → False) → compare O.none x = Ordering.lt
-/
#guard_msgs in #print sig instOrdO.compare_spec_2
```
- [#10351](https://github.com/leanprover/lean4/pull/10351) adds the ability to do `deriving ReflBEq, LawfulBEq`. Both
classes have to be listed in the `deriving` clause.
This is meant to work with `deriving BEq` (but you can try to
use it on hand-rolled `@[methods_specs] instance : BEq…` instances).
Does not support mutual or nested inductives.
### Overhaul of the String Type
- [#10304](https://github.com/leanprover/lean4/pull/10304) redefines `String` to be the type of byte arrays `b`
for which `b.IsValidUtf8`. This moves the data model of strings much closer to the actual data representation at runtime.
- [#10457](https://github.com/leanprover/lean4/pull/10457) introduces safe alternatives to `String.Pos` and `Substring`
that can only represent valid positions/slices. Specifically, the PR
- introduces the predicate `String.Pos.IsValid`;
- proves several nontrivial equivalent conditions for `String.Pos.IsValid`;
- introduces `String.ValidPos`, which is a `String.Pos` with an `IsValid` proof;
- introduces `String.Slice`, which is like `Substring` but made from `String.ValidPos` instead of `Pos`;
- introduces `String.Pos.IsValidForSlice`, which is like `String.Pos.IsValid` but for slices;
- introduces `String.Slice.Pos`, which is like `String.ValidPos` but for slices;
- introduces various functions for converting between the two types of positions.
- [#10514](https://github.com/leanprover/lean4/pull/10514) defines the new `String.Slice` API.
- [#10713](https://github.com/leanprover/lean4/pull/10713) enforces rules around arithmetic of `String.Pos.Raw`.
**Breaking Change**: The `HAdd` and `HSub` instances for `String.Pos.Raw` are have been removed.
See the PR description for more information.
- [#10735](https://github.com/leanprover/lean4/pull/10735) moves many operations involving `String.Pos.Raw` to a the
`String.Pos.Raw` namespace.
**Breaking Change**: After this PR, `String.pos_lt_eq` is no longer a `simp` lemma.
Add `String.Pos.Raw.lt_iff` as a `simp` lemma if your proofs break.
### Async Framework
Async framework has been extended with:
- POSIX signal handlers ([#9258](https://github.com/leanprover/lean4/pull/9258));
- `Std.Sync.Notify`, an alternative to `CondVar` suited for concurrency ([#10368](https://github.com/leanprover/lean4/pull/10368));
- `Std.Broadcast`, a multi-consumer, multi-producer channel to `Std.Sync` ([#10369](https://github.com/leanprover/lean4/pull/10369));
- `StreamMap`, a type that enables multiplexing in asynchronous streams ([#10400](https://github.com/leanprover/lean4/pull/10400));
- `Std.CancellationToken` ([#10510](https://github.com/leanprover/lean4/pull/10510)).
### Iterators
- [#10686](https://github.com/leanprover/lean4/pull/10686) introduces `any`, `anyM`, `all` and `allM` for pure and monadic
iterators. It also provides lemmas about them.
- [#10728](https://github.com/leanprover/lean4/pull/10728) introduces the `flatMap` iterator combinator. It also adds
lemmas relating `flatMap` to `toList` and `toArray`.
- [#10761](https://github.com/leanprover/lean4/pull/10761) provides iterators on hash maps.
### InfoView Trace Search
[#10365](https://github.com/leanprover/lean4/pull/10365) implements the server-side for a new trace search mechanism in
the InfoView. See the PR description for a demo video.
### Linear Construction of Instances
There are now alternative implementations of `DerivingBEq` ([#10268](https://github.com/leanprover/lean4/pull/10268))
and `Deriving Ord` ([#10270](https://github.com/leanprover/lean4/pull/10270))
based on comparing `.ctorIdx` and using a dedicated matcher for comparing same constructors
(added in [#10152](https://github.com/leanprover/lean4/pull/10152)), to avoid the quadratic overhead of the
default match implementation.
New options `deriving.beq.linear_construction_threshold` and `deriving.ord.linear_construction_threshold`
set the constructor count threshold (10 by default) for using the new construction.
### Porting to the Module System
[#10807](https://github.com/leanprover/lean4/pull/10807) introduces the `backward.privateInPublic` option to aid in
porting projects to the module system by temporarily allowing access to
private declarations from the public scope, even across modules. A
warning will be generated by such accesses unless
`backward.privateInPublic.warn` is disabled.
### Breaking Changes
- [#10714](https://github.com/leanprover/lean4/pull/10714) removes support for reducible well-founded recursion, a Breaking
Change. Using `@[semireducible]` on a definition by well-founded
recursion prints a warning that this is no longer effective.
- [#10319](https://github.com/leanprover/lean4/pull/10319) "monomorphizes" the structure `Std.PRange shape α`, replacing it
with nine distinct structures `Std.Rcc`, `Std.Rco`, `Std.Rci` etc., one
for each possible shape of a range's bounds. This change was necessary
because the shape polymorphism is detrimental to attempts of automation.
**BREAKING CHANGE:** While range/slice notation itself is unchanged, this
essentially breaks the entire remaining (polymorphic) range and slice API
except for the dot-notation(`toList`, `iter`, ...). It is not possible to deprecate old
declarations that were formulated in a shape-polymorphic way that is not available anymore.
- [#10645](https://github.com/leanprover/lean4/pull/10645) renames `Stream` to `Std.Stream` so that the name becomes
available to mathlib after a deprecation cycle.
- [#10468](https://github.com/leanprover/lean4/pull/10468) refactors the Lake log monads to take a `LogConfig` structure
when run (rather than multiple arguments). This breaking change should
help minimize future breakages due to changes in configurations options.
- [#10660](https://github.com/leanprover/lean4/pull/10660) adds auto-completion for identifiers after `end`. It also fixes
a bug where completion in the whitespace after `set_option` would not
yield the full option list.
Breaking change: the `«end»` syntax is adjusted to take an `identWithPartialTrailingDot` instead of an `ident`.
## Language
* [#7844](https://github.com/leanprover/lean4/pull/7844) adds a simple implementation of MePo, from "Lightweight
relevance filtering for machine-generated resolution problems" by Meng
and Paulson.
* [#10158](https://github.com/leanprover/lean4/pull/10158) adds information about definitions blocked from unfolding via
the module system to type defeq errors.
* [#10268](https://github.com/leanprover/lean4/pull/10268) adds an alternative implementation of `DerivingBEq` based on
comparing `.ctorIdx` and using a dedicated matcher for comparing same
constructors (added in #10152), to avoid the quadratic overhead of the
default match implementation. The new option
`deriving.beq.linear_construction_threshold` sets the constructor count
threshold (10 by default) for using the new construction. Such instances
also allow `deriving ReflBEq, LawfulBeq`, although these proofs for
these properties are still quadratic.
* [#10270](https://github.com/leanprover/lean4/pull/10270) adds an alternative implementation of `Deriving Ord` based on
comparing `.ctorIdx` and using a dedicated matcher for comparing same
constructors (added in #10152). The new option
`deriving.ord.linear_construction_threshold` sets the constructor count
threshold (10 by default) for using the new construction.
* [#10302](https://github.com/leanprover/lean4/pull/10302) introduces the `@[specs]` attribute. It can be applied to
(certain) type class instances and define “specification theorems” for
the class’ operations, by taking the equational theorems of the
implementation function mentioned in the type class instance and
rephrasing them in terms of the overloaded operations. Fixes #5295.
* [#10333](https://github.com/leanprover/lean4/pull/10333) introduces a `coinductive` keyword, that can be used to define
coinductive predicates via a syntax identical to the one for `inductive`
keyword. The machinery relies on the implementation of elaboration of
inductive types and extracts an endomap on the appropriate space of the
predicates from the definition that is then fed to the
`PartialFixpoint`. Upon elaborating definitions, all the constructors
are declared through automatically generated lemmas.
* [#10346](https://github.com/leanprover/lean4/pull/10346) lets `deriving BEq` and `deriving Ord` use `@[method_specs]`
from #10302 when applicable (i.e. when not using `partial`).
* [#10351](https://github.com/leanprover/lean4/pull/10351) adds the ability to do `deriving ReflBEq, LawfulBEq`. Both
classes have to listed in the `deriving` clause. For `ReflBEq`, a simple
`simp`-based proof is used. For `LawfulBEq`, a dedicated,
syntax-directed tactic is used that should work for derived `BEq`
instances. This is meant to work with `deriving BEq` (but you can try to
use it on hand-rolled `@[methods_specs] instance : BEq…` instances).
Does not support mutual or nested inductives.
* [#10375](https://github.com/leanprover/lean4/pull/10375) adds support for non-commutative ring normalization in `grind`.
The new normalizer also accounts for the `IsCharP` type class. Examples:
```lean
open Lean Grind
variable (R : Type u) [Ring R]
example (a b : R) : (a + 2 * b)^2 = a^2 + 2 * a * b + 2 * b * a + 4 * b^2 := by grind
example (a b : R) : (a + 2 * b)^2 = a^2 + 2 * a * b + -b * (-4) * a - 2*b*a + 4 * b^2 := by grind
variable [IsCharP R 4]
example (a b : R) : (a - b)^2 = a^2 - a * b - b * 5 * a + b^2 := by grind
example (a b : R) : (a - b)^2 = 13*a^2 - a * b - b * 5 * a + b*3*b*3 := by grind
```
* [#10377](https://github.com/leanprover/lean4/pull/10377) fixes an issue where the "eta feature" in the app elaborator,
which is invoked when positional arguments are skipped due to named
arguments, results in variables that can be captured by those named
arguments. Now the temporary local variables that implement this feature
get fresh names. The names used for the closed lambda expression still
use the original parameter names.
* [#10378](https://github.com/leanprover/lean4/pull/10378) enables using `notation` items in
`infix`/`infixl`/`infixr`/`prefix`/`postfix`. The motivation for this is
to enable being able to use `pp.unicode`-aware parsers. A followup PR
can combine core parsers as such:
```lean
infixr:30 unicode(" ∨ ", " \\/ ") => Or
```
* [#10379](https://github.com/leanprover/lean4/pull/10379) modifies the syntax for tactic configurations. Previously just
`(ident` would commit to tactic configuration item parsing, but now it
needs to be `(ident :=`. This enables reliably using tactic
configurations before the `term` category. For example, given `syntax
"my_tac" optConfig term : tactic`, it used to be that `my_tac (x + y)`
would have an error on `+` with "expected `:=`", but now it parses the
term.
* [#10380](https://github.com/leanprover/lean4/pull/10380) implements sanity checks in the `grind ring` module to ensure
the instances synthesized by type class resolution are definitionally
equal to the corresponding ones in the `grind` core classes. The
definitional equality test is performed with reduction restricted to
reducible definitions and instances.
* [#10382](https://github.com/leanprover/lean4/pull/10382) makes the builtin Verso docstring elaborators bootstrap
correctly, adds the ability to postpone checks (which is necessary for
resolving forward references and bootstrapping issues), and fixes a
minor parser bug.
* [#10388](https://github.com/leanprover/lean4/pull/10388) fixes a bug where definitions with nested proofs that contain
`sorry` might not report "warning: declaration uses 'sorry'" if the
proof has the same type as another nested proof from a previous
declaration. The bug only affected log messages; `#print axioms` would
still correctly report uses of `sorryAx`.
* [#10391](https://github.com/leanprover/lean4/pull/10391) gives anonymous constructor notation (`⟨x,y⟩`) an error recovery
mechanism where if there are not enough arguments then synthetic sorries
are inserted for the missing arguments and an error is logged, rather
than outright failing.
* [#10392](https://github.com/leanprover/lean4/pull/10392) fixes an issue with the `if` tactic where errors were not placed
at the correct source ranges. It also adds some error recovery to avoid
additional errors about unsolved goals on the `if` token when the tactic
has incomplete syntax.
* [#10394](https://github.com/leanprover/lean4/pull/10394) adds the `reduceBEq` and `reduceOrd` simprocs. They rewrite
occurrences of `_ == _` resp. `Ord.compare _ _` if both arguments are
constructors and the corresponding instance has been marked with
`@[method_specs]` (introduced in #10302), which now by default is the
case for derived instances.
* [#10406](https://github.com/leanprover/lean4/pull/10406) improves upon #10302 to properly make the method spec theorems
private if the implementation function is not exposed.
* [#10415](https://github.com/leanprover/lean4/pull/10415) changes the order of steps tried when proving equational
theorems for structural recursion. In order to avoid goals that `split`
cannot handle, avoid unfolding the LHS of the equation to `.brecOn` and
`.rec` until after the RHS has been split into its final cases.
* [#10417](https://github.com/leanprover/lean4/pull/10417) changes the automation in `deriving_LawfulEq_tactic_step` to use
`with_reducible` when asserting the shape of the goal using `change`, so
that we do not accidentally unfold `x == x'` calls here. Fixes #10416.
* [#10419](https://github.com/leanprover/lean4/pull/10419) adds the helper theorem `eq_normS_nc` for normalizing
non-commutative semirings. We will use this theorem to justify
normalization steps in the `grind ring` module.
* [#10421](https://github.com/leanprover/lean4/pull/10421) adds a normalizer for non-commutative semirings to `grind`.
Examples:
```lean
open Lean.Grind
variable (R : Type u) [Semiring R]
example (a b c : R) : a * (b + c) = a * c + a * b := by grind
example (a b : R) : (a + 2 * b)^2 = a^2 + 2 * a * b + 2 * b * a + 4 * b^2 := by grind
example (a b : R) : b^2 + (a + 2 * b)^2 = a^2 + 2 * a * b + b * (1+1) * a * 1 + 5 * b^2 := by grind
example (a b : R) : a^3 + a^2*b + a*b*a + b*a^2 + a*b^2 + b*a*b + b^2*a + b^3 = (a+b)^3 := by grind
```
* [#10422](https://github.com/leanprover/lean4/pull/10422) implements the new E-matching pattern inference heuristic for
`grind`. It is not enabled yet. You can activate the new behavior using
`set_option backward.grind.inferPattern false`. Here is a summary of the
new behavior.
* [#10425](https://github.com/leanprover/lean4/pull/10425) lets the `split` tactic generalize discriminants that are not
free variables and proofs using `generalize`. If the only
non-fvar-discriminants are proofs, then this avoids the more elaborate
generalization strategy of `split`, which can fail with dependent
motives, thus mitigating issue #10424.
* [#10428](https://github.com/leanprover/lean4/pull/10428) makes explicit missing `grind` modifiers, and ensures `grind`
uses "minIndexable" for local theorems.
* [#10430](https://github.com/leanprover/lean4/pull/10430) ensures users can select the "minimal indexable subexpression"
condition in `grind` parameters. Example, they can now write `grind [!
-> thmName]`. `grind?` will include the `!` modifier whenever users had
used `@[grind!]`. also fixes a missing case in the new pattern
inference procedure.
It also adjusts some `grind` annotations and tests in preparation for
setting the new pattern inference heuristic as the new default.
* [#10432](https://github.com/leanprover/lean4/pull/10432) enables the new E-matching pattern inference heuristic for
`grind`, implemented in PR #10422.
**Important**: Users can still use the old pattern inference heuristic
by setting:
```lean
set_option backward.grind.inferPattern true
```
* [#10434](https://github.com/leanprover/lean4/pull/10434) adds `reprove N by T`, which effectively elaborates `example
type_of% N := by T`. It supports multiple identifiers. This is useful
for testing tactics.
* [#10438](https://github.com/leanprover/lean4/pull/10438) fixes an issue where notations and other overloadings would
signal kernel errors even though there exists a successful
interpretation.
* [#10440](https://github.com/leanprover/lean4/pull/10440) adds the `reduceCtorIdx` simproc which recognizes and reduces
`ctorIdx` applications. This is not on by default yet because it does
not use the discrimination tree (yet).
* [#10453](https://github.com/leanprover/lean4/pull/10453) makes `mvcgen` reduce through `let`s, so that it progresses over
`(have t := 42; fun _ => foo t) 23` by reduction to `have t := 42; foo
t` and then introducing `t`.
* [#10456](https://github.com/leanprover/lean4/pull/10456) implements `mvcgen invariants?` for providing initial invariant
skeletons for the user to flesh out. When the loop body has an early
return, it will helpfully suggest `Invariant.withEarlyReturn ...` as a
skeleton.
* [#10479](https://github.com/leanprover/lean4/pull/10479) implements module docstrings in Verso syntax, as well as adding
a number of improvements and fixes to Verso docstrings in general. In
particular, they now have language server support and are parsed at
parse time rather than elaboration time, so the snapshot's syntax tree
includes the parsed documentation.
* [#10506](https://github.com/leanprover/lean4/pull/10506) annotates the shadowing main definitions of `bv_decide`,
`mvcgen` and similar tactics in `Std` with the semantically richer
`tactic_alt` attribute so that `verso` will not warn about overloads.
* [#10507](https://github.com/leanprover/lean4/pull/10507) makes the missing docs linter aware of `tactic_alt`.
* [#10508](https://github.com/leanprover/lean4/pull/10508) allows `.congr_simp` theorems to be created not just for
definitoins, but any constant. This is important to make the machinery
work across module boundaries.
* [#10512](https://github.com/leanprover/lean4/pull/10512) adds some helper functions for the premise selection API, to
assist implementers.
* [#10533](https://github.com/leanprover/lean4/pull/10533) adds a docstring role for module names, called `module`. It also
improves the suggestions provided for code elements, making them more
relevant and proposing `lit`.
* [#10535](https://github.com/leanprover/lean4/pull/10535) ensures that `#guard` can be called under the module system
without issues.
* [#10536](https://github.com/leanprover/lean4/pull/10536) fixes `simp` in `-zeta -zetaUnused` mode from producing
incorrect proofs if in a `have` telescope a variable occurs in the
type of the body only transitively. Fixes #10353.
* [#10543](https://github.com/leanprover/lean4/pull/10543) lets `#print T.rec` show more information about a recursor, in
particular its reduction rules.
* [#10560](https://github.com/leanprover/lean4/pull/10560) adds highlighted Lean code to Verso docstrings and fixes smaller
quality-of-life issues.
* [#10563](https://github.com/leanprover/lean4/pull/10563) moves some `ReduceEval` instances about basic types up from the
`quote4` library.
* [#10566](https://github.com/leanprover/lean4/pull/10566) improves `mvcgen invariants?` to suggest concrete invariants
based on how invariants are used in VCs.
These suggestions are intentionally simplistic and boil down to "this
holds at the start of the loop and this must hold at the end of the
loop":
```lean
def mySum (l : List Nat) : Nat := Id.run do
let mut acc := 0
for x in l do
acc := acc + x
return acc
/--
info: Try this:
invariants
· ⇓⟨xs, letMuts⟩ => ⌜xs.prefix = [] ∧ letMuts = 0 ∨ xs.suffix = [] ∧ letMuts = l.sum⌝
-/
#guard_msgs (info) in
theorem mySum_suggest_invariant (l : List Nat) : mySum l = l.sum := by
generalize h : mySum l = r
apply Id.of_wp_run_eq h
mvcgen invariants?
all_goals admit
```
* [#10567](https://github.com/leanprover/lean4/pull/10567) fixes argument index calculation in `Lean.Expr.getArg!'`.
* [#10570](https://github.com/leanprover/lean4/pull/10570) adds support for case label like syntax in `mvcgen invariants`
in order to refer to inaccessible names. Example:
```lean
def copy (l : List Nat) : Id (Array Nat) := do
let mut acc := #[]
for x in l do
acc := acc.push x
return acc
theorem copy_labelled_invariants (l : List Nat) : ⦃⌜True⌝⦄ copy l ⦃⇓ r => ⌜r = l.toArray⌝⦄ := by
mvcgen [copy] invariants
| inv1 acc => ⇓ ⟨xs, letMuts⟩ => ⌜acc = l.toArray⌝
with admit
```
* [#10571](https://github.com/leanprover/lean4/pull/10571) ensures that `SPred` proof mode tactics such as `mspec`,
`mintro`, etc. immediately replace the main goal when entering the proof
mode. This prevents `No goals to be solved` errors.
* [#10612](https://github.com/leanprover/lean4/pull/10612) fixes an issue reported [on
Zulip](https://leanprover.zulipchat.com/#narrow/channel/239415-metaprogramming-.2F-tactics/topic/.60abstractMVars.60.20not.20instantiating.20level.20mvars/near/541918246)
where `abstractMVars` (which is used in type class inference and `simp`
argument elaboration) was not instantiating metavariables in the types
of metavariables, causing it to abstract already-assigned metavariables.
* [#10618](https://github.com/leanprover/lean4/pull/10618) removes superfluous `Monad` instances from the spec lemmas of
the `MonadExceptOf` lifting framework.
* [#10638](https://github.com/leanprover/lean4/pull/10638) disables the "experimental" warning for `mvcgen` by changing its
default.
* [#10639](https://github.com/leanprover/lean4/pull/10639) fixes hygiene of the local context for *all* goals generated by
`mvcgen`, not just those that get a fresh MVar as in #9781.
* [#10641](https://github.com/leanprover/lean4/pull/10641) ensures that the `mspec` and `mvcgen` tactics no longer
spuriously instantiate loop invariants by `rfl`.
* [#10644](https://github.com/leanprover/lean4/pull/10644) explicitly tries to synthesize synthetic MVars in `mspec`. Doing
so resolves a bug triggered by use of the loop invariant lemma for
`Std.PRange`.
* [#10650](https://github.com/leanprover/lean4/pull/10650) improves the error message for `mstart` when the goal is not a
`Prop`.
* [#10654](https://github.com/leanprover/lean4/pull/10654) avoid reducing at transparency all in equational theorem
generation. Fixes #10651.
* [#10663](https://github.com/leanprover/lean4/pull/10663) disables `{name}` suggestions for `.anonymous` and adds syntax
suggestions.
* [#10682](https://github.com/leanprover/lean4/pull/10682) changes the instance name for `deriving ToExpr` to be consistent
with other derived instance since #10271. Fixes #10678.
* [#10697](https://github.com/leanprover/lean4/pull/10697) lets `induction` print a warning if a variable occurring in the
`using` clause is generalized. Fixes #10683.
* [#10712](https://github.com/leanprover/lean4/pull/10712) lets `MVarId.cleanup` chase local declarations (a bit as if they
were equalities). Fixes #10710.
* [#10714](https://github.com/leanprover/lean4/pull/10714) removes support for reducible well-founded recursion, a Breaking
Change. Using `@[semireducible]` on a definition by well-founded
recursion prints a warning that this is no longer effective.
* [#10716](https://github.com/leanprover/lean4/pull/10716) adds a new helper parser for implementing parsers that contain
hexadecimal numbers. We are going to use it to implement anchors in the
`grind` interactive mode.
* [#10720](https://github.com/leanprover/lean4/pull/10720) re-enables the "experimental" warning for `mvcgen` by changing
its default. The official release has been postponed to justify small
breaking changes in the semantic foundations in the near future.
* [#10722](https://github.com/leanprover/lean4/pull/10722) changes where errors are displayed when trying to use
`coinductive` keyword when targeting things that do not live in `Prop`.
Instead of displaying the error above the first element of the mutual
block, it is displayed above the erroneous definition.
* [#10733](https://github.com/leanprover/lean4/pull/10733) unfolds auxiliary theorems more aggressively during termination
checking. This fixes #10721.
* [#10734](https://github.com/leanprover/lean4/pull/10734) follows upon #10606 and creates equational theorems uniformly
from the unfold theorem, there is only one handler registered in
`registerGetEqnsFn`.
* [#10780](https://github.com/leanprover/lean4/pull/10780) improves the error message when `decide +kernel` fails in the
kernel, but not the elaborator. Fixes #10766.
* [#10782](https://github.com/leanprover/lean4/pull/10782) implements a hint tactic `mvcgen?`, expanding to `mvcgen
invariants?`
* [#10783](https://github.com/leanprover/lean4/pull/10783) ensures that error messages such as “redundant alternative” have
the right error location even if the arms share their RHS. Fixes #10781.
* [#10793](https://github.com/leanprover/lean4/pull/10793) fixes #10792.
* [#10796](https://github.com/leanprover/lean4/pull/10796) changes match compilation to reject some pattern matches that
were previously accepted due to inaccessible patterns sometimes treated
like accessible ones. Fixes #10794.
* [#10807](https://github.com/leanprover/lean4/pull/10807) introduces the `backward.privateInPublic` option to aid in
porting projects to the module system by temporarily allowing access to
private declarations from the public scope, even across modules. A
warning will be generated by such accesses unless
`backward.privateInPublic.warn` is disabled.
* [#10839](https://github.com/leanprover/lean4/pull/10839) exposes the `optionValue` parser used to implement the
`set_option` notation.
## Library
* [#9258](https://github.com/leanprover/lean4/pull/9258) adds support for signal handlers to the Lean standard library.
* [#9298](https://github.com/leanprover/lean4/pull/9298) adds support the Count Trailing Zeros operation `BitVec.ctz` to
the bitvector library and to `bv_decide`, relying on the existing `clz`
circuit. We also build some theory around `BitVec.ctz` (analogous to the
theory existing for `BitVec.clz`) and introduce lemmas
`BitVec.[ctz_eq_reverse_clz, clz_eq_reverse_ctz, ctz_lt_iff_ne_zero,
getLsbD_false_of_lt_ctz, getLsbD_true_ctz_of_ne_zero,
two_pow_ctz_le_toNat_of_ne_zero, reverse_reverse_eq,
reverse_eq_zero_iff]`.
* [#9932](https://github.com/leanprover/lean4/pull/9932) adds `LawfulMonad` and `WPMonad` instances for `Option` and
`OptionT`.
* [#10304](https://github.com/leanprover/lean4/pull/10304) redefines `String` to be the type of byte arrays `b` for which
`b.IsValidUtf8`.
* [#10319](https://github.com/leanprover/lean4/pull/10319) "monomorphizes" the structure `Std.PRange shape α`, replacing it
with nine distinct structures `Std.Rcc`, `Std.Rco`, `Std.Rci` etc., one
for each possible shape of a range's bounds. This change was necessary
because the shape polymorphism is detrimental to attempts of automation.
* [#10366](https://github.com/leanprover/lean4/pull/10366) refactors the Async module to use the `Async` type in all of the
`Async` files.
* [#10367](https://github.com/leanprover/lean4/pull/10367) adds vectored write for TCP and UDP (that helps a lot with not
copying the arrays over and over) and fix a RC issue in TCP and UDP
cancel functions with the line `lean_dec((lean_object*)udp_socket);` and
a similar one that tries to decrement the object inside of the `socket`.
* [#10368](https://github.com/leanprover/lean4/pull/10368) adds `Notify` that is a structure that is similar to `CondVar`
but it's used for concurrency. The main difference between
`Std.Sync.Notify` and `Std.Condvar` is that depends on a `Std.Mutex` and
blocks the entire thread that the `Task` is using while waiting.
* [#10369](https://github.com/leanprover/lean4/pull/10369) adds a multi-consumer, multi-producer channel to Std.Sync.
* [#10370](https://github.com/leanprover/lean4/pull/10370) adds async type classes for streams.
* [#10400](https://github.com/leanprover/lean4/pull/10400) adds the StreamMap type that enables multiplexing in
asynchronous streams.
* [#10407](https://github.com/leanprover/lean4/pull/10407) adds `@[method_specs_simp]` in `Init` for type classes like
`HAppend`.
* [#10457](https://github.com/leanprover/lean4/pull/10457) introduces safe alternatives to `String.Pos` and `Substring`
that can only represent valid positions/slices.
* [#10487](https://github.com/leanprover/lean4/pull/10487) adds vectored write and fix rc issues in tcp and udp cancel
functions.
* [#10510](https://github.com/leanprover/lean4/pull/10510) adds a `Std.CancellationToken` type
* [#10514](https://github.com/leanprover/lean4/pull/10514) defines the new `String.Slice` API.
* [#10552](https://github.com/leanprover/lean4/pull/10552) ensures that `Substring.beq` is reflexive, and in particular
satisfies the equivalence `ss1 == ss2 <-> ss1.toString = ss2.toString`.
* [#10611](https://github.com/leanprover/lean4/pull/10611) adds a union operation on `DHashMap`/`HashMap`/`HashSet` and
their raw variants and provides lemmas about union operations.
* [#10618](https://github.com/leanprover/lean4/pull/10618) removes superfluous `Monad` instances from the spec lemmas of
the `MonadExceptOf` lifting framework.
* [#10624](https://github.com/leanprover/lean4/pull/10624) renames `String.Pos` to `String.Pos.Raw`.
* [#10627](https://github.com/leanprover/lean4/pull/10627) adds lemmas `forall_fin_zero` and `exists_fin_zero`. It also
marks lemmas `forall_fin_zero`, `forall_fin_one`, `forall_fin_two`,
`exists_fin_zero`, `exists_fin_one`, `exists_fin_two` with `simp`
attribute.
* [#10630](https://github.com/leanprover/lean4/pull/10630) aims to fix the Timer API selector to make it finish as soon as
possible when unregistered. This change makes the `Selectable.one`
function drop the `selectables` array as soon as possible, so when
combined with finalizers that have some effects like the TCP socket
finalizer, it runs it as soon as possible.
* [#10631](https://github.com/leanprover/lean4/pull/10631) exposes the definitions about `Int*`. The main reason is that
the `SInt` simprocs require many of them to be exposed. Furthermore,
`decide` now works with `Int*` operations. This fixes #10631.
* [#10633](https://github.com/leanprover/lean4/pull/10633) provides range support for the signed finite number types
`Int{8,16,32,64}` and `ISize`. The proof obligations are handled by
reducing all of them to proofs about an internal `UpwardEnumerable`
instance for `BitVec` interpreted as signed numbers.
* [#10634](https://github.com/leanprover/lean4/pull/10634) defines `ByteArray.validateUTF8`, uses it to show that
`ByteArray.IsValidUtf8` is decidable and redefines `String.fromUTF8` and
friends to use it.
* [#10636](https://github.com/leanprover/lean4/pull/10636) renames `String.getUtf8Byte` to `String.getUTF8Byte` in order to
adhere to the standard library naming convention.
* [#10642](https://github.com/leanprover/lean4/pull/10642) introduces `List.Cursor.pos` as an abbreviation for
`prefix.length`.
* [#10645](https://github.com/leanprover/lean4/pull/10645) renames `Stream` to `Std.Stream` so that the name becomes
available to mathlib after a deprecation cycle.
* [#10649](https://github.com/leanprover/lean4/pull/10649) renames `Nat.and_distrib_right` to `Nat.and_or_distrib_right`.
This is to make the name consistent with other theorems in the same file
(e.g. `Nat.and_or_distrib_left`).
* [#10653](https://github.com/leanprover/lean4/pull/10653) adds equational lemmas about (filter-)mapping and then folding
iterators.
* [#10667](https://github.com/leanprover/lean4/pull/10667) adds more selectors for TCP and Signals.
* [#10676](https://github.com/leanprover/lean4/pull/10676) adds the `IO.FS.hardLink` function, which can be used to create
hard links.
* [#10685](https://github.com/leanprover/lean4/pull/10685) introduces `LT` and `LE` instances on `String.ValidPos` and
`String.Slice.Pos`.
* [#10686](https://github.com/leanprover/lean4/pull/10686) introduces `any`, `anyM`, `all` and `allM` for pure and monadic
iterators. It also provides lemmas about them.
* [#10713](https://github.com/leanprover/lean4/pull/10713) enforces rules around arithmetic of `String.Pos.Raw`.
* [#10728](https://github.com/leanprover/lean4/pull/10728) introduces the `flatMap` iterator combinator. It also adds
lemmas relating `flatMap` to `toList` and `toArray`.
* [#10735](https://github.com/leanprover/lean4/pull/10735) moves many operations involving `String.Pos.Raw` to a the
`String.Pos.Raw` namespace with the eventual aim of freeing up the
`String` namespace to contain operations using `String.ValidPos` (to be
renamed to `String.Pos`) instead.
* [#10761](https://github.com/leanprover/lean4/pull/10761) provides iterators on hash maps.
## Tactics
* [#10445](https://github.com/leanprover/lean4/pull/10445) adds helper definitions in preparation for the upcoming
injective function support in `grind`.
* [#10447](https://github.com/leanprover/lean4/pull/10447) adds the `[grind inj]` attribute for marking injectivity
theorems for `grind`.
* [#10448](https://github.com/leanprover/lean4/pull/10448) modifies the "issues" grind diagnostics prints. Previously we
would just describe synthesis failures. These messages were confusing to
users, as in fact the linarith module continues to work, but less
capably. For most of the issues, we now explain the resulting change in
behaviour. There is a still a TODO to explain the change when
`IsOrderedRing` is not available.
* [#10449](https://github.com/leanprover/lean4/pull/10449) ensures that issues reported by the E-matching module are
displayed only when `set_option grind.debug true` is enabled. Users
reported that these messages are too distracting and not very useful.
They are more valuable for library developers when annotating their
libraries.
* [#10461](https://github.com/leanprover/lean4/pull/10461) fixes unnecessary case splits generated by the `grind mbtc`
module. Here, `mbtc` stands for model-based theory combination.
* [#10463](https://github.com/leanprover/lean4/pull/10463) adds `Nat.sub_zero` as a `grind` normalization rule.
* [#10465](https://github.com/leanprover/lean4/pull/10465) skips cast-like helper `grind` functions during `grind mbtc`
* [#10466](https://github.com/leanprover/lean4/pull/10466) reduces noise in the 'Equivalence classes' section of the
`grind` diagnostics. It now uses a notion of *support expressions*.
Right now, it is hard-coded, but we will probably make it extensible in
the future. The current definition is
* [#10469](https://github.com/leanprover/lean4/pull/10469) fixes an incorrect optimization in the `grind` canonicalizer.
See the new test for an example that exposes the problem.
* [#10472](https://github.com/leanprover/lean4/pull/10472) adds a code action for `grind` parameters. We need to use
`set_option grind.param.codeAction true` to enable the option. The PR
also adds a modifier to instruct `grind` to use the "default" pattern
inference strategy.
* [#10473](https://github.com/leanprover/lean4/pull/10473) ensures the code action messages produced by `grind` include the
full context
* [#10474](https://github.com/leanprover/lean4/pull/10474) adds a doc string for the `!` parameter modifier in `grind`.
* [#10477](https://github.com/leanprover/lean4/pull/10477) ensures sorts are internalized by `grind`.
* [#10480](https://github.com/leanprover/lean4/pull/10480) fixes a bug in the equality resolution frontend used in `grind`.
* [#10481](https://github.com/leanprover/lean4/pull/10481) generalizes the theorem activation function used in `grind`.
The goal is to reuse it to implement the injective function module.
* [#10482](https://github.com/leanprover/lean4/pull/10482) fixes symbol collection for the `@[grind inj]` attribute.
* [#10483](https://github.com/leanprover/lean4/pull/10483) completes support for injective functions in grind. See
examples:
```lean
/-! Add some injectivity theorems. -/
def double (x : Nat) := 2*x
@[grind inj] theorem double_inj : Function.Injective double := by
grind [Function.Injective, double]
structure InjFn (α : Type) (β : Type) where
f : α → β
h : Function.Injective f
instance : CoeFun (InjFn α β) (fun _ => α → β) where
coe s := s.f
@[grind inj] theorem fn_inj (F : InjFn α β) : Function.Injective (F : α → β) := by
grind [Function.Injective, cases InjFn]
def toList (a : α) : List α := [a]
@[grind inj] theorem toList_inj : Function.Injective (toList : α → List α) := by
grind [Function.Injective, toList]
/-! Examples -/
example (x y : Nat) : toList (double x) = toList (double y) → x = y := by
grind
example (f : InjFn (List Nat) α) (x y z : Nat)
: f (toList (double x)) = f (toList y) →
y = double z →
x = z := by
grind
```
* [#10486](https://github.com/leanprover/lean4/pull/10486) adds and expands `grind` related docstrings.
* [#10529](https://github.com/leanprover/lean4/pull/10529) adds some helper theorems for the upcoming `grind order` solver.
* [#10553](https://github.com/leanprover/lean4/pull/10553) implements infrastructure for the new `grind order` module.
* [#10562](https://github.com/leanprover/lean4/pull/10562) simplifies the `grind order` module, and internalizes the order
constraints. It removes the `Offset` type class because it introduced
too much complexity. We now cover the same use cases with a simpler
approach:
- Any type that implements at least `Std.IsPreorder`
- Arbitrary ordered rings.
- `Nat` by the `Nat.ToInt` adapter.
* [#10583](https://github.com/leanprover/lean4/pull/10583) allows users to declare additional `grind` constraint
propagators for declarations that already include propagators in core.
* [#10589](https://github.com/leanprover/lean4/pull/10589) adds helper theorems for implementing `grind order`
* [#10590](https://github.com/leanprover/lean4/pull/10590) implements proof term construction for `grind order`.
* [#10594](https://github.com/leanprover/lean4/pull/10594) implements proof construction for theory propagation in `grind
order`.
* [#10596](https://github.com/leanprover/lean4/pull/10596) implements the function for adding new edges to the graph used
by `grind order`. The graph maintains the transitive closure of all
asserted constraints.
* [#10598](https://github.com/leanprover/lean4/pull/10598) implements support for positive constraints in `grind order`.
The new module can already solve problems such as:
```lean
example [LE α] [LT α] [Std.LawfulOrderLT α] [Std.IsPreorder α]
(a b c : α) : a ≤ b → b ≤ c → c < a → False := by
grind
example [LE α] [LT α] [Std.LawfulOrderLT α] [Std.IsPreorder α]
(a b c d : α) : a ≤ b → b ≤ c → c < d → d ≤ a → False := by
grind
example [LE α] [Std.IsPreorder α]
(a b c : α) : a ≤ b → b ≤ c → a ≤ c := by
grind
example [LE α] [Std.IsPreorder α]
(a b c d : α) : a ≤ b → b ≤ c → c ≤ d → a ≤ d := by
grind
```
* [#10599](https://github.com/leanprover/lean4/pull/10599) fixes the support for `Nat` in `grind order`. This module uses
the `Nat.ToInt` adapter.
* [#10600](https://github.com/leanprover/lean4/pull/10600) implements support for negative constraints in `grind order`.
Examples:
```lean
open Lean Grind
example [LE α] [LT α] [Std.LawfulOrderLT α] [Std.IsLinearPreorder α]
(a b c d : α) : a ≤ b → ¬ (c ≤ b) → ¬ (d ≤ c) → d < a → False := by
grind -linarith (splits := 0)
example [LE α] [Std.IsLinearPreorder α]
(a b c d : α) : a ≤ b → ¬ (c ≤ b) → ¬ (d ≤ c) → ¬ (a ≤ d) → False := by
grind -linarith (splits := 0)
example [LE α] [LT α] [Std.LawfulOrderLT α] [Std.IsLinearPreorder α] [CommRing α] [OrderedRing α]
(a b c d : α) : a - b ≤ 5 → ¬ (c ≤ b) → ¬ (d ≤ c + 2) → d ≤ a - 8 → False := by
grind -linarith (splits := 0)
```
* [#10601](https://github.com/leanprover/lean4/pull/10601) fixes a panic in `grind order` when order is not a partial
order.
* [#10604](https://github.com/leanprover/lean4/pull/10604) implements the method `processNewEq` in `grind order`. It is
responsible for processing equalities propagated by the `grind` E-graph.
* [#10607](https://github.com/leanprover/lean4/pull/10607) adds infrastructure for the upcoming `grind` tactic mode, which
will be similar to the `conv` mode. The goal is to extend `grind` from a
terminal tactic into an interactive mode: `grind => …`.
* [#10677](https://github.com/leanprover/lean4/pull/10677) implements the basic tactics for the new `grind` interactive
mode. While many additional `grind` tactics will be added later, the
foundational framework is already operational. The following `grind`
tactics are currently implemented: `skip`, `done`, `finish`, `lia`, and
`ring`.
also removes the notion of `grind` fallback procedure since it
is subsumed by the new framework. Examples:
```lean
example (x y : Nat) : x ≥ y + 1 → x > 0 := by
grind => skip; lia; done
```
* [#10679](https://github.com/leanprover/lean4/pull/10679) fixes an issue where "Invalid alternative name" errors from
`induction` stick around after removing the offending alternative.
* [#10690](https://github.com/leanprover/lean4/pull/10690) adds the `instantiate`, `show_true`, `show_false`,
`show_asserted`, and `show_eqcs` tactics for the `grind` interactive
mode. The `show` tactic take an optional "filter" and are used to probe
the `grind` state. Example:
```lean
example (as bs cs : Array α) (v₁ v₂ : α)
(i₁ i₂ j : Nat)
(h₁ : i₁ < as.size)
(h₂ : bs = as.set i₁ v₁)
(h₃ : i₂ < bs.size)
(h₃ : cs = bs.set i₂ v₂)
(h₄ : i₁ ≠ j ∧ i₂ ≠ j)
(h₅ : j < cs.size)
(h₆ : j < as.size)
: cs[j] = as[j] := by
grind =>
instantiate
-- Display asserted facts with `generation > 0`
show_asserted gen > 0
-- Display propositions known to be `True`, containing `j`, and `generation > 0`
show_true j && gen > 0
-- Display equivalence classes with terms that contain `as` or `bs`
show_eqcs as || bs
instantiate
```
* [#10695](https://github.com/leanprover/lean4/pull/10695) fixes an issue where non-`macro` members of a `mutual` block
were discarded if there was at least one macro present.
* [#10706](https://github.com/leanprover/lean4/pull/10706) adds the `have` tactic for the `grind` interactive mode.
Example:
```lean
example {a b c d e : Nat}
: a > 0 → b > 0 → 2*c + e <= 2 → e = d + 1 → a*b + 2 > 2*c + d := by
grind =>
have : a*b > 0 := Nat.mul_pos h h_1
lia
```
* [#10707](https://github.com/leanprover/lean4/pull/10707) ensures the `finish` tactic in `grind` interactive mode fails
and reports diagnostics when goal is not closed.
* [#10709](https://github.com/leanprover/lean4/pull/10709) implements *anchors* (also known as stable hash codes) for
referencing terms occurring in a `grind` goal. It also introduces the
commands `show_splits` and `show_state`. The former displays the anchors
for candidate case splits in the current `grind` goal.
* [#10715](https://github.com/leanprover/lean4/pull/10715) improves anchor stability (aka stable hash codes) used to
reference terms in a `grind` goal.
* [#10731](https://github.com/leanprover/lean4/pull/10731) adds the following tactics to the `grind` interactive mode:
- `focus <grind_tac_seq>`
- `next => <grind_tac_seq>`
- `any_goals <grind_tac_seq>`
- `all_goals <grind_tac_seq>`
- `grind_tac <;> grind_tac`
- `cases <anchor>`
- `tactic => <tac_seq>`
* [#10737](https://github.com/leanprover/lean4/pull/10737) adds the tactics `linarith`, `ac`, `fail`, `first`, `try`,
`fail_if_success`, and `admit` to `grind` interactive mode.
* [#10740](https://github.com/leanprover/lean4/pull/10740) improves the tactics `ac`, `linarith`, `lia`, `ring` tactics in
`grind` interactive mode. They now fail if no progress has been made.
They also generate an info message with counterexample/basis if the goal
was not closed.
* [#10746](https://github.com/leanprover/lean4/pull/10746) implements parameters for the `instantiate` tactic in the
`grind` interactive mode. Users can now select both global and local
theorems. Local theorems are selected using anchors. It also adds the
`show_thms` tactic for displaying local theorems. Example:
```lean
example (as bs cs : Array α) (v₁ v₂ : α)
(i₁ i₂ j : Nat)
(h₁ : i₁ < as.size)
(h₂ : bs = as.set i₁ v₁)
(h₃ : i₂ < bs.size)
(h₃ : cs = bs.set i₂ v₂)
(h₄ : i₁ ≠ j ∧ i₂ ≠ j)
(h₅ : j < cs.size)
(h₆ : j < as.size)
: cs[j] = as[j] := by
grind =>
instantiate = Array.getElem_set
instantiate Array.getElem_set
```
* [#10747](https://github.com/leanprover/lean4/pull/10747) implements infrastructure for `finish?` and `grind?` tactics.
* [#10748](https://github.com/leanprover/lean4/pull/10748) implements the `repeat` tactical for the `grind` interactive
mode.
* [#10767](https://github.com/leanprover/lean4/pull/10767) implements the new control interface for implementing `grind`
search strategies. It will replace the `SearchM` framework.
* [#10778](https://github.com/leanprover/lean4/pull/10778) ensures that `grind` interactive mode is hygienic. It also adds
tactics for renaming inaccessible names: `rename_i h_1 ... h_n` and
`next h_1 ... h_n => ..`, and `expose_names` for automatically generated
tactic scripts. The PR also adds helper functions for implementing
case-split actions.
* [#10779](https://github.com/leanprover/lean4/pull/10779) implements hover information for `grind` anchors. Anchors are
stable hash codes for referencing terms in the grind state. The anchors
will be used when auto generating tactic scripts.
* [#10791](https://github.com/leanprover/lean4/pull/10791) adds a silent info message with the `grind` state in its
interactive mode. The message is shown only when there is exactly one
goal in the grind interactive mode. The condition is a workaround for
current limitations of our `InfoTree`.
* [#10798](https://github.com/leanprover/lean4/pull/10798) implements the `grind` actions `intro`, `intros`, `assertNext`,
`assertAll`.
* [#10801](https://github.com/leanprover/lean4/pull/10801) implements the `splitNext` action for `grind`.
* [#10808](https://github.com/leanprover/lean4/pull/10808) implements support for compressing auto-generated `grind` tactic
sequences.
* [#10811](https://github.com/leanprover/lean4/pull/10811) implements proper case-split anchor generation in the
`splitNext` action, which will be used to implement `grind?` and
`finish?`.
* [#10812](https://github.com/leanprover/lean4/pull/10812) implements `lia`, `linarith`, and `ac` actions for `grind`
interactive mode.
* [#10824](https://github.com/leanprover/lean4/pull/10824) implements the `cases?` tactic for the `grind` interactive mode.
It provides a convenient way to select anchors. Users can filter the
candidates using the filter language.
* [#10828](https://github.com/leanprover/lean4/pull/10828) implements a compact notation for inspecting the `grind` state
in interactive mode. Within a `grind` tactic block, each tactic may
optionally have a suffix of the form `| filter?`.
* [#10833](https://github.com/leanprover/lean4/pull/10833) implements infrastructure for evaluating `grind` tactics in the
`GrindM` monad. We are going to use it to check whether auto-generated
tactics can effectively close the original goal.
* [#10834](https://github.com/leanprover/lean4/pull/10834) implements the `ring` action for `grind`.
* [#10836](https://github.com/leanprover/lean4/pull/10836) implements support for `Action` in the `grind` solver extensions
(`SolverExtension`). It also provides the `Solvers.mkAction` function
that constructs an `Action` using all registered solvers. The generated
action is "fair," that is, a solver cannot prevent other solvers from
making progress.
* [#10837](https://github.com/leanprover/lean4/pull/10837) implements the `finish?` tactic for the `grind` interactive
mode. When it successfully closes the goal, it produces a code action
that allows the user to close the goal using explicit grind tactic
steps, i.e., without any search. It also makes explicit which solvers
have been used.
* [#10841](https://github.com/leanprover/lean4/pull/10841) improves the `grind` tactic generated by the `instantiate`
action in tracing mode. It also updates the syntax for the `instantiate`
tactic, making it similar to `simp`. For example:
* `instantiate only [thm1, thm2]` instantiates only theorems `thm1` and
`thm2`.
* `instantiate [thm1, thm2]` instantiates theorems marked with the
`@[grind]` attribute **and** theorems `thm1` and `thm2`.
* [#10843](https://github.com/leanprover/lean4/pull/10843) implements the `set_option` tactic in `grind` interactive mode.
* [#10846](https://github.com/leanprover/lean4/pull/10846) fixes a few issues on `instance only [...]` tactic generation at
`finish?`.
## Compiler
* [#10429](https://github.com/leanprover/lean4/pull/10429) fixes and overeager reuse of specialisation in the code
generator.
* [#10444](https://github.com/leanprover/lean4/pull/10444) fixes an overeager insertion of `inc` operations for large uint
constants.
* [#10488](https://github.com/leanprover/lean4/pull/10488) changes the way that scientific numerals are parsed in order to
give better error messages for (invalid) syntax like `32.succ`.
* [#10495](https://github.com/leanprover/lean4/pull/10495) fixes constant folding for UIntX in the code generator. This
optimization was previously simply dead code due to the way that uint
literals are encoded.
* [#10610](https://github.com/leanprover/lean4/pull/10610) ensures that even if a type is marked as `irreducible` the
compiler can see through it in
order to discover functions hidden behind type aliases.
* [#10626](https://github.com/leanprover/lean4/pull/10626) reduces the aggressiveness of the dead let eliminator from
lambda RC.
* [#10689](https://github.com/leanprover/lean4/pull/10689) fixes an oversight in the RC insertion phase in the code
generator.
## Pretty Printing
* [#10376](https://github.com/leanprover/lean4/pull/10376) modifies pretty printing of `fun` binders, suppressing the safe
shadowing feature among the binders in the same `fun`. For example,
rather than pretty printing as `fun x x => 0`, we now see `fun x x_1 =>
0`. The calculation is done per `fun`, so for example `fun x => id fun x
=> 0` pretty prints as-is, taking advantage of safe shadowing.
## Documentation
* [#10632](https://github.com/leanprover/lean4/pull/10632) adds missing docstrings for ByteArray and makes existing ones
consistent with our style.
* [#10640](https://github.com/leanprover/lean4/pull/10640) adds a missing docstring and applies our style guide to parts of
the String API.
## Server
* [#10365](https://github.com/leanprover/lean4/pull/10365) implements the server-side for a new trace search mechanism in
the InfoView.
* [#10442](https://github.com/leanprover/lean4/pull/10442) ensures that unknown identifier code actions are provided on
auto-implicits.
* [#10524](https://github.com/leanprover/lean4/pull/10524) adds support for interactivity to the combined "try this"
messages that were introduced in #9966. In doing so, it moves the link
to apply a suggestion to a separate `[apply]` button in front of the
suggestion. Hints with diffs remain unchanged, as they did not
previously support interacting with terms in the diff, either.
* [#10538](https://github.com/leanprover/lean4/pull/10538) fixes deadlocking `exit` calls in the language server.
* [#10584](https://github.com/leanprover/lean4/pull/10584) causes Verso docstrings to search for a name in the environment
that is at least as long as the current name, providing it as a
suggestion.
* [#10609](https://github.com/leanprover/lean4/pull/10609) fixes an LSP-non-compliance in the `FileSystemWatcher` that was
introduced in #925.
* [#10619](https://github.com/leanprover/lean4/pull/10619) fixes a bug in the unknown identifier code actions where it
would yield non-sensical suggestions for nested `open` declarations like
`open Foo.Bar`.
* [#10660](https://github.com/leanprover/lean4/pull/10660) adds auto-completion for identifiers after `end`. It also fixes
a bug where completion in the whitespace after `set_option` would not
yield the full option list.
* [#10662](https://github.com/leanprover/lean4/pull/10662) re-enables semantic tokens for Verso docstrings, after a prior
change accidentally disabled them. It also adds a test to prevent this
from happening again.
* [#10738](https://github.com/leanprover/lean4/pull/10738) fixes a regression introduced by #10307, where hovering the name
of an inductive type or constructor in its own declaration didn't show
the docstring. In the process, a bug in docstring handling for
coinductive types was discovered and also fixed. Tests are added to
prevent the regression from repeating in the future.
* [#10757](https://github.com/leanprover/lean4/pull/10757) fixes a bug in combination with VS Code where Lean code that
looks like CSS color codes would display a color picker decoration.
* [#10797](https://github.com/leanprover/lean4/pull/10797) fixes a bug in the unknown identifier code actions where the
identifiers wouldn't be correctly minimized in nested namespaces. It
also fixes a bug where identifiers would sometimes be minimized to
`[anonymous]`.
## Lake
* [#9855](https://github.com/leanprover/lean4/pull/9855) adds a new `allowImportAll` configuration option for packages
and libraries. When enabled by an upstream package or library,
downstream packages will be able to `import all` modules of that package
or library. This enables package authors to selectively choose which
`private` elements, if any, downstream packages may have access to.
* [#10188](https://github.com/leanprover/lean4/pull/10188) adds support for remote artifact caches (e.g., Reservoir) to
Lake. As part of this support, a new suite of `lake cache` CLI commands
has been introduced to help manage Lake's cache. Also, the existing
local cache support has been overhauled for better interplay with the
new remote support.
* [#10452](https://github.com/leanprover/lean4/pull/10452) refactors Lake's package naming procedure to allow packages to
be renamed by the consumer. With this, users can now require a package
using a different name than the one it was defined with.
* [#10459](https://github.com/leanprover/lean4/pull/10459) fixes a conditional check in a GitHub Action template generated
by Lake.
* [#10468](https://github.com/leanprover/lean4/pull/10468) refactors the Lake log monads to take a `LogConfig` structure
when run (rather than multiple arguments). This breaking change should
help minimize future breakages due to changes in configurations options.
* [#10551](https://github.com/leanprover/lean4/pull/10551) enables Reservoir packages to be required as dependencies at a
specific package version (i.e., the `version` specified in the package's
configuration file).
* [#10576](https://github.com/leanprover/lean4/pull/10576) adds a new package configuration option: `restoreAllArtifacts`.
When set to `true` and the Lake local artifact cache is enabled, Lake
will copy all cached artifacts into the build directory. This ensures
they are available for external consumers who expect build results to be
in the build directory.
* [#10578](https://github.com/leanprover/lean4/pull/10578) adds support for the CMake spelling of a build type (i.e.,
capitalized) to Lake's `buildType` configuration option.
* [#10579](https://github.com/leanprover/lean4/pull/10579) alters `libPrefixOnWindows` behavior to add the `lib` prefix to
the library's `libName` rather than just the file path. This means that
Lake's `-l` will now have the prefix on Windows. While this should not
matter to a MSYS2 build (which accepts both `lib`-prefixed and
unprefixed variants), it should ensure compatibility with MSVC (if that
is ever an issue).
* [#10730](https://github.com/leanprover/lean4/pull/10730) changes the Lake's remote cache interface to scope cache outputs
by toolchain and/or platform were useful.
* [#10741](https://github.com/leanprover/lean4/pull/10741) fixes a bug where partially up-to-date files built with `--old`
could be stored in the cache as fully up-to-date. Such files are no
longer cached. In addition, builds without traces now only perform an
modification time check with `--old`. Otherwise, they are considered
out-of-date.
## Other
* [#10383](https://github.com/leanprover/lean4/pull/10383) includes some improvements to the release process, making the
updating of `stable` branches more robust, and including `cslib` in the
release checklist.
* [#10389](https://github.com/leanprover/lean4/pull/10389) fixes a bug where string literal parsing ignored its trailing
whitespace setting.
* [#10460](https://github.com/leanprover/lean4/pull/10460) introduces a simple script that adjusts module headers in a
package for use of the module system, without further minimizing import
or annotation use.
* [#10476](https://github.com/leanprover/lean4/pull/10476) fixes the dead `let` elimination code in the kernel's
`infer_let` function.
* [#10575](https://github.com/leanprover/lean4/pull/10575) adds the necessary infrastructure for recording elaboration
dependencies that may not be apparent from the resulting environment
such as notations and other metaprograms. An adapted version of `shake`
from Mathlib is added to `script/` but may be moved to another location
or repo in the future.
* [#10777](https://github.com/leanprover/lean4/pull/10777) improves the scripts assisting with cutting Lean releases (by
reporting CI status of open PRs, and adding documentation), and adds a
`.claude/commands/release.md` prompt file so Claude can assist.
```` |
reference-manual/Manual/Releases/v4_13_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.13.0 (2024-11-01)" =>
%%%
tag := "release-v4.13.0"
file := "v4.13.0"
%%%
```markdown
**Full Changelog**: https://github.com/leanprover/lean4/compare/v4.12.0...v4.13.0
### Language features, tactics, and metaprograms
* `structure` command
* [#5511](https://github.com/leanprover/lean4/pull/5511) allows structure parents to be type synonyms.
* [#5531](https://github.com/leanprover/lean4/pull/5531) allows default values for structure fields to be noncomputable.
* `rfl` and `apply_rfl` tactics
* [#3714](https://github.com/leanprover/lean4/pull/3714), [#3718](https://github.com/leanprover/lean4/pull/3718) improve the `rfl` tactic and give better error messages.
* [#3772](https://github.com/leanprover/lean4/pull/3772) makes `rfl` no longer use kernel defeq for ground terms.
* [#5329](https://github.com/leanprover/lean4/pull/5329) tags `Iff.refl` with `@[refl]` (@Parcly-Taxel)
* [#5359](https://github.com/leanprover/lean4/pull/5359) ensures that the `rfl` tactic tries `Iff.rfl` (@Parcly-Taxel)
* `unfold` tactic
* [#4834](https://github.com/leanprover/lean4/pull/4834) let `unfold` do zeta-delta reduction of local definitions, incorporating functionality of the Mathlib `unfold_let` tactic.
* `omega` tactic
* [#5382](https://github.com/leanprover/lean4/pull/5382) fixes spurious error in [#5315](https://github.com/leanprover/lean4/issues/5315)
* [#5523](https://github.com/leanprover/lean4/pull/5523) supports `Int.toNat`
* `simp` tactic
* [#5479](https://github.com/leanprover/lean4/pull/5479) lets `simp` apply rules with higher-order patterns.
* `induction` tactic
* [#5494](https://github.com/leanprover/lean4/pull/5494) fixes `induction`’s "pre-tactic" block to always be indented, avoiding unintended uses of it.
* `ac_nf` tactic
* [#5524](https://github.com/leanprover/lean4/pull/5524) adds `ac_nf`, a counterpart to `ac_rfl`, for normalizing expressions with respect to associativity and commutativity. Tests it with `BitVec` expressions.
* `bv_decide`
* [#5211](https://github.com/leanprover/lean4/pull/5211) makes `extractLsb'` the primitive `bv_decide` understands, rather than `extractLsb` (@alexkeizer)
* [#5365](https://github.com/leanprover/lean4/pull/5365) adds `bv_decide` diagnoses.
* [#5375](https://github.com/leanprover/lean4/pull/5375) adds `bv_decide` normalization rules for `ofBool (a.getLsbD i)` and `ofBool a[i]` (@alexkeizer)
* [#5423](https://github.com/leanprover/lean4/pull/5423) enhances the rewriting rules of `bv_decide`
* [#5433](https://github.com/leanprover/lean4/pull/5433) presents the `bv_decide` counterexample at the API
* [#5484](https://github.com/leanprover/lean4/pull/5484) handles `BitVec.ofNat` with `Nat` fvars in `bv_decide`
* [#5506](https://github.com/leanprover/lean4/pull/5506), [#5507](https://github.com/leanprover/lean4/pull/5507) add `bv_normalize` rules.
* [#5568](https://github.com/leanprover/lean4/pull/5568) generalize the `bv_normalize` pipeline to support more general preprocessing passes
* [#5573](https://github.com/leanprover/lean4/pull/5573) gets `bv_normalize` up-to-date with the current `BitVec` rewrites
* Cleanups: [#5408](https://github.com/leanprover/lean4/pull/5408), [#5493](https://github.com/leanprover/lean4/pull/5493), [#5578](https://github.com/leanprover/lean4/pull/5578)
* Elaboration improvements
* [#5266](https://github.com/leanprover/lean4/pull/5266) preserve order of overapplied arguments in `elab_as_elim` procedure.
* [#5510](https://github.com/leanprover/lean4/pull/5510) generalizes `elab_as_elim` to allow arbitrary motive applications.
* [#5283](https://github.com/leanprover/lean4/pull/5283), [#5512](https://github.com/leanprover/lean4/pull/5512) refine how named arguments suppress explicit arguments. Breaking change: some previously omitted explicit arguments may need explicit `_` arguments now.
* [#5376](https://github.com/leanprover/lean4/pull/5376) modifies projection instance binder info for instances, making parameters that are instance implicit in the type be implicit.
* [#5402](https://github.com/leanprover/lean4/pull/5402) localizes universe metavariable errors to `let` bindings and `fun` binders if possible. Makes "cannot synthesize metavariable" errors take precedence over unsolved universe level errors.
* [#5419](https://github.com/leanprover/lean4/pull/5419) must not reduce `ite` in the discriminant of `match`-expression when reducibility setting is `.reducible`
* [#5474](https://github.com/leanprover/lean4/pull/5474) have autoparams report parameter/field on failure
* [#5530](https://github.com/leanprover/lean4/pull/5530) makes automatic instance names about types with hygienic names be hygienic.
* Deriving handlers
* [#5432](https://github.com/leanprover/lean4/pull/5432) makes `Repr` deriving instance handle explicit type parameters
* Functional induction
* [#5364](https://github.com/leanprover/lean4/pull/5364) adds more equalities in context, more careful cleanup.
* Linters
* [#5335](https://github.com/leanprover/lean4/pull/5335) fixes the unused variables linter complaining about match/tactic combinations
* [#5337](https://github.com/leanprover/lean4/pull/5337) fixes the unused variables linter complaining about some wildcard patterns
* Other fixes
* [#4768](https://github.com/leanprover/lean4/pull/4768) fixes a parse error when `..` appears with a `.` on the next line
* Metaprogramming
* [#3090](https://github.com/leanprover/lean4/pull/3090) handles level parameters in `Meta.evalExpr` (@eric-wieser)
* [#5401](https://github.com/leanprover/lean4/pull/5401) instance for `Inhabited (TacticM α)` (@alexkeizer)
* [#5412](https://github.com/leanprover/lean4/pull/5412) expose Kernel.check for debugging purposes
* [#5556](https://github.com/leanprover/lean4/pull/5556) improves the "invalid projection" type inference error in `inferType`.
* [#5587](https://github.com/leanprover/lean4/pull/5587) allows `MVarId.assertHypotheses` to set `BinderInfo` and `LocalDeclKind`.
* [#5588](https://github.com/leanprover/lean4/pull/5588) adds `MVarId.tryClearMany'`, a variant of `MVarId.tryClearMany`.
### Language server, widgets, and IDE extensions
* [#5205](https://github.com/leanprover/lean4/pull/5205) decreases the latency of auto-completion in tactic blocks.
* [#5237](https://github.com/leanprover/lean4/pull/5237) fixes symbol occurrence highlighting in VS Code not highlighting occurrences when moving the text cursor into the identifier from the right.
* [#5257](https://github.com/leanprover/lean4/pull/5257) fixes several instances of incorrect auto-completions being reported.
* [#5299](https://github.com/leanprover/lean4/pull/5299) allows auto-completion to report completions for global identifiers when the elaborator fails to provide context-specific auto-completions.
* [#5312](https://github.com/leanprover/lean4/pull/5312) fixes the server breaking when changing whitespace after the module header.
* [#5322](https://github.com/leanprover/lean4/pull/5322) fixes several instances of auto-completion reporting non-existent namespaces.
* [#5428](https://github.com/leanprover/lean4/pull/5428) makes sure to always report some recent file range as progress when waiting for elaboration.
### Pretty printing
* [#4979](https://github.com/leanprover/lean4/pull/4979) make pretty printer escape identifiers that are tokens.
* [#5389](https://github.com/leanprover/lean4/pull/5389) makes formatter use the current token table.
* [#5513](https://github.com/leanprover/lean4/pull/5513) use breakable instead of unbreakable whitespace when formatting tokens.
### Library
* [#5222](https://github.com/leanprover/lean4/pull/5222) reduces allocations in `Json.compress`.
* [#5231](https://github.com/leanprover/lean4/pull/5231) upstreams `Zero` and `NeZero`
* [#5292](https://github.com/leanprover/lean4/pull/5292) refactors `Lean.Elab.Deriving.FromToJson` (@arthur-adjedj)
* [#5415](https://github.com/leanprover/lean4/pull/5415) implements `Repr Empty` (@TomasPuverle)
* [#5421](https://github.com/leanprover/lean4/pull/5421) implements `To/FromJSON Empty` (@TomasPuverle)
* Logic
* [#5263](https://github.com/leanprover/lean4/pull/5263) allows simplifying `dite_not`/`decide_not` with only `Decidable (¬p)`.
* [#5268](https://github.com/leanprover/lean4/pull/5268) fixes binders on `ite_eq_left_iff`
* [#5284](https://github.com/leanprover/lean4/pull/5284) turns off `Inhabited (Sum α β)` instances
* [#5355](https://github.com/leanprover/lean4/pull/5355) adds simp lemmas for `LawfulBEq`
* [#5374](https://github.com/leanprover/lean4/pull/5374) add `Nonempty` instances for products, allowing more `partial` functions to elaborate successfully
* [#5447](https://github.com/leanprover/lean4/pull/5447) updates Pi instance names
* [#5454](https://github.com/leanprover/lean4/pull/5454) makes some instance arguments implicit
* [#5456](https://github.com/leanprover/lean4/pull/5456) adds `heq_comm`
* [#5529](https://github.com/leanprover/lean4/pull/5529) moves `@[simp]` from `exists_prop'` to `exists_prop`
* `Bool`
* [#5228](https://github.com/leanprover/lean4/pull/5228) fills gaps in Bool lemmas
* [#5332](https://github.com/leanprover/lean4/pull/5332) adds notation `^^` for Bool.xor
* [#5351](https://github.com/leanprover/lean4/pull/5351) removes `_root_.and` (and or/not/xor) and instead exports/uses `Bool.and` (etc.).
* `BitVec`
* [#5240](https://github.com/leanprover/lean4/pull/5240) removes BitVec simps with complicated RHS
* [#5247](https://github.com/leanprover/lean4/pull/5247) `BitVec.getElem_zeroExtend`
* [#5248](https://github.com/leanprover/lean4/pull/5248) simp lemmas for BitVec, improving confluence
* [#5249](https://github.com/leanprover/lean4/pull/5249) removes `@[simp]` from some BitVec lemmas
* [#5252](https://github.com/leanprover/lean4/pull/5252) changes `BitVec.intMin/Max` from abbrev to def
* [#5278](https://github.com/leanprover/lean4/pull/5278) adds `BitVec.getElem_truncate` (@tobiasgrosser)
* [#5281](https://github.com/leanprover/lean4/pull/5281) adds udiv/umod bitblasting for `bv_decide` (@bollu)
* [#5297](https://github.com/leanprover/lean4/pull/5297) `BitVec` unsigned order theoretic results
* [#5313](https://github.com/leanprover/lean4/pull/5313) adds more basic BitVec ordering theory for UInt
* [#5314](https://github.com/leanprover/lean4/pull/5314) adds `toNat_sub_of_le` (@bollu)
* [#5357](https://github.com/leanprover/lean4/pull/5357) adds `BitVec.truncate` lemmas
* [#5358](https://github.com/leanprover/lean4/pull/5358) introduces `BitVec.setWidth` to unify zeroExtend and truncate (@tobiasgrosser)
* [#5361](https://github.com/leanprover/lean4/pull/5361) some BitVec GetElem lemmas
* [#5385](https://github.com/leanprover/lean4/pull/5385) adds `BitVec.ofBool_[and|or|xor]_ofBool` theorems (@tobiasgrosser)
* [#5404](https://github.com/leanprover/lean4/pull/5404) more of `BitVec.getElem_*` (@tobiasgrosser)
* [#5410](https://github.com/leanprover/lean4/pull/5410) BitVec analogues of `Nat.{mul_two, two_mul, mul_succ, succ_mul}` (@bollu)
* [#5411](https://github.com/leanprover/lean4/pull/5411) `BitVec.toNat_{add,sub,mul_of_lt}` for BitVector non-overflow reasoning (@bollu)
* [#5413](https://github.com/leanprover/lean4/pull/5413) adds `_self`, `_zero`, and `_allOnes` for `BitVec.[and|or|xor]` (@tobiasgrosser)
* [#5416](https://github.com/leanprover/lean4/pull/5416) adds LawCommIdentity + IdempotentOp for `BitVec.[and|or|xor]` (@tobiasgrosser)
* [#5418](https://github.com/leanprover/lean4/pull/5418) decidable quantifers for BitVec
* [#5450](https://github.com/leanprover/lean4/pull/5450) adds `BitVec.toInt_[intMin|neg|neg_of_ne_intMin]` (@tobiasgrosser)
* [#5459](https://github.com/leanprover/lean4/pull/5459) missing BitVec lemmas
* [#5469](https://github.com/leanprover/lean4/pull/5469) adds `BitVec.[not_not, allOnes_shiftLeft_or_shiftLeft, allOnes_shiftLeft_and_shiftLeft]` (@luisacicolini)
* [#5478](https://github.com/leanprover/lean4/pull/5478) adds `BitVec.(shiftLeft_add_distrib, shiftLeft_ushiftRight)` (@luisacicolini)
* [#5487](https://github.com/leanprover/lean4/pull/5487) adds `sdiv_eq`, `smod_eq` to allow `sdiv`/`smod` bitblasting (@bollu)
* [#5491](https://github.com/leanprover/lean4/pull/5491) adds `BitVec.toNat_[abs|sdiv|smod]` (@tobiasgrosser)
* [#5492](https://github.com/leanprover/lean4/pull/5492) `BitVec.(not_sshiftRight, not_sshiftRight_not, getMsb_not, msb_not)` (@luisacicolini)
* [#5499](https://github.com/leanprover/lean4/pull/5499) `BitVec.Lemmas` - drop non-terminal simps (@tobiasgrosser)
* [#5505](https://github.com/leanprover/lean4/pull/5505) unsimps `BitVec.divRec_succ'`
* [#5508](https://github.com/leanprover/lean4/pull/5508) adds `BitVec.getElem_[add|add_add_bool|mul|rotateLeft|rotateRight…` (@tobiasgrosser)
* [#5554](https://github.com/leanprover/lean4/pull/5554) adds `Bitvec.[add, sub, mul]_eq_xor` and `width_one_cases` (@luisacicolini)
* `List`
* [#5242](https://github.com/leanprover/lean4/pull/5242) improve naming for `List.mergeSort` lemmas
* [#5302](https://github.com/leanprover/lean4/pull/5302) provide `mergeSort` comparator autoParam
* [#5373](https://github.com/leanprover/lean4/pull/5373) fix name of `List.length_mergeSort`
* [#5377](https://github.com/leanprover/lean4/pull/5377) upstream `map_mergeSort`
* [#5378](https://github.com/leanprover/lean4/pull/5378) modify signature of lemmas about `mergeSort`
* [#5245](https://github.com/leanprover/lean4/pull/5245) avoid importing `List.Basic` without List.Impl
* [#5260](https://github.com/leanprover/lean4/pull/5260) review of List API
* [#5264](https://github.com/leanprover/lean4/pull/5264) review of List API
* [#5269](https://github.com/leanprover/lean4/pull/5269) remove HashMap's duplicated Pairwise and Sublist
* [#5271](https://github.com/leanprover/lean4/pull/5271) remove @[simp] from `List.head_mem` and similar
* [#5273](https://github.com/leanprover/lean4/pull/5273) lemmas about `List.attach`
* [#5275](https://github.com/leanprover/lean4/pull/5275) reverse direction of `List.tail_map`
* [#5277](https://github.com/leanprover/lean4/pull/5277) more `List.attach` lemmas
* [#5285](https://github.com/leanprover/lean4/pull/5285) `List.count` lemmas
* [#5287](https://github.com/leanprover/lean4/pull/5287) use boolean predicates in `List.filter`
* [#5289](https://github.com/leanprover/lean4/pull/5289) `List.mem_ite_nil_left` and analogues
* [#5293](https://github.com/leanprover/lean4/pull/5293) cleanup of `List.findIdx` / `List.take` lemmas
* [#5294](https://github.com/leanprover/lean4/pull/5294) switch primes on `List.getElem_take`
* [#5300](https://github.com/leanprover/lean4/pull/5300) more `List.findIdx` theorems
* [#5310](https://github.com/leanprover/lean4/pull/5310) fix `List.all/any` lemmas
* [#5311](https://github.com/leanprover/lean4/pull/5311) fix `List.countP` lemmas
* [#5316](https://github.com/leanprover/lean4/pull/5316) `List.tail` lemma
* [#5331](https://github.com/leanprover/lean4/pull/5331) fix implicitness of `List.getElem_mem`
* [#5350](https://github.com/leanprover/lean4/pull/5350) `List.replicate` lemmas
* [#5352](https://github.com/leanprover/lean4/pull/5352) `List.attachWith` lemmas
* [#5353](https://github.com/leanprover/lean4/pull/5353) `List.head_mem_head?`
* [#5360](https://github.com/leanprover/lean4/pull/5360) lemmas about `List.tail`
* [#5391](https://github.com/leanprover/lean4/pull/5391) review of `List.erase` / `List.find` lemmas
* [#5392](https://github.com/leanprover/lean4/pull/5392) `List.fold` / `attach` lemmas
* [#5393](https://github.com/leanprover/lean4/pull/5393) `List.fold` relators
* [#5394](https://github.com/leanprover/lean4/pull/5394) lemmas about `List.maximum?`
* [#5403](https://github.com/leanprover/lean4/pull/5403) theorems about `List.toArray`
* [#5405](https://github.com/leanprover/lean4/pull/5405) reverse direction of `List.set_map`
* [#5448](https://github.com/leanprover/lean4/pull/5448) add lemmas about `List.IsPrefix` (@Command-Master)
* [#5460](https://github.com/leanprover/lean4/pull/5460) missing `List.set_replicate_self`
* [#5518](https://github.com/leanprover/lean4/pull/5518) rename `List.maximum?` to `max?`
* [#5519](https://github.com/leanprover/lean4/pull/5519) upstream `List.fold` lemmas
* [#5520](https://github.com/leanprover/lean4/pull/5520) restore `@[simp]` on `List.getElem_mem` etc.
* [#5521](https://github.com/leanprover/lean4/pull/5521) List simp fixes
* [#5550](https://github.com/leanprover/lean4/pull/5550) `List.unattach` and simp lemmas
* [#5594](https://github.com/leanprover/lean4/pull/5594) induction-friendly `List.min?_cons`
* `Array`
* [#5246](https://github.com/leanprover/lean4/pull/5246) cleanup imports of Array.Lemmas
* [#5255](https://github.com/leanprover/lean4/pull/5255) split Init.Data.Array.Lemmas for better bootstrapping
* [#5288](https://github.com/leanprover/lean4/pull/5288) rename `Array.data` to `Array.toList`
* [#5303](https://github.com/leanprover/lean4/pull/5303) cleanup of `List.getElem_append` variants
* [#5304](https://github.com/leanprover/lean4/pull/5304) `Array.not_mem_empty`
* [#5400](https://github.com/leanprover/lean4/pull/5400) reorganization in Array/Basic
* [#5420](https://github.com/leanprover/lean4/pull/5420) make `Array` functions either semireducible or use structural recursion
* [#5422](https://github.com/leanprover/lean4/pull/5422) refactor `DecidableEq (Array α)`
* [#5452](https://github.com/leanprover/lean4/pull/5452) refactor of Array
* [#5458](https://github.com/leanprover/lean4/pull/5458) cleanup of Array docstrings after refactor
* [#5461](https://github.com/leanprover/lean4/pull/5461) restore `@[simp]` on `Array.swapAt!_def`
* [#5465](https://github.com/leanprover/lean4/pull/5465) improve Array GetElem lemmas
* [#5466](https://github.com/leanprover/lean4/pull/5466) `Array.foldX` lemmas
* [#5472](https://github.com/leanprover/lean4/pull/5472) @[simp] lemmas about `List.toArray`
* [#5485](https://github.com/leanprover/lean4/pull/5485) reverse simp direction for `toArray_concat`
* [#5514](https://github.com/leanprover/lean4/pull/5514) `Array.eraseReps`
* [#5515](https://github.com/leanprover/lean4/pull/5515) upstream `Array.qsortOrd`
* [#5516](https://github.com/leanprover/lean4/pull/5516) upstream `Subarray.empty`
* [#5526](https://github.com/leanprover/lean4/pull/5526) fix name of `Array.length_toList`
* [#5527](https://github.com/leanprover/lean4/pull/5527) reduce use of deprecated lemmas in Array
* [#5534](https://github.com/leanprover/lean4/pull/5534) cleanup of Array GetElem lemmas
* [#5536](https://github.com/leanprover/lean4/pull/5536) fix `Array.modify` lemmas
* [#5551](https://github.com/leanprover/lean4/pull/5551) upstream `Array.flatten` lemmas
* [#5552](https://github.com/leanprover/lean4/pull/5552) switch obvious cases of array "bang"`[]!` indexing to rely on hypothesis (@TomasPuverle)
* [#5577](https://github.com/leanprover/lean4/pull/5577) add missing simp to `Array.size_feraseIdx`
* [#5586](https://github.com/leanprover/lean4/pull/5586) `Array/Option.unattach`
* `Option`
* [#5272](https://github.com/leanprover/lean4/pull/5272) remove @[simp] from `Option.pmap/pbind` and add simp lemmas
* [#5307](https://github.com/leanprover/lean4/pull/5307) restoring Option simp confluence
* [#5354](https://github.com/leanprover/lean4/pull/5354) remove @[simp] from `Option.bind_map`
* [#5532](https://github.com/leanprover/lean4/pull/5532) `Option.attach`
* [#5539](https://github.com/leanprover/lean4/pull/5539) fix explicitness of `Option.mem_toList`
* `Nat`
* [#5241](https://github.com/leanprover/lean4/pull/5241) add @[simp] to `Nat.add_eq_zero_iff`
* [#5261](https://github.com/leanprover/lean4/pull/5261) Nat bitwise lemmas
* [#5262](https://github.com/leanprover/lean4/pull/5262) `Nat.testBit_add_one` should not be a global simp lemma
* [#5267](https://github.com/leanprover/lean4/pull/5267) protect some Nat bitwise theorems
* [#5305](https://github.com/leanprover/lean4/pull/5305) rename Nat bitwise lemmas
* [#5306](https://github.com/leanprover/lean4/pull/5306) add `Nat.self_sub_mod` lemma
* [#5503](https://github.com/leanprover/lean4/pull/5503) restore @[simp] to upstreamed `Nat.lt_off_iff`
* `Int`
* [#5301](https://github.com/leanprover/lean4/pull/5301) rename `Int.div/mod` to `Int.tdiv/tmod`
* [#5320](https://github.com/leanprover/lean4/pull/5320) add `ediv_nonneg_of_nonpos_of_nonpos` to DivModLemmas (@sakehl)
* `Fin`
* [#5250](https://github.com/leanprover/lean4/pull/5250) missing lemma about `Fin.ofNat'`
* [#5356](https://github.com/leanprover/lean4/pull/5356) `Fin.ofNat'` uses `NeZero`
* [#5379](https://github.com/leanprover/lean4/pull/5379) remove some @[simp]s from Fin lemmas
* [#5380](https://github.com/leanprover/lean4/pull/5380) missing Fin @[simp] lemmas
* `HashMap`
* [#5244](https://github.com/leanprover/lean4/pull/5244) (`DHashMap`|`HashMap`|`HashSet`).(`getKey?`|`getKey`|`getKey!`|`getKeyD`)
* [#5362](https://github.com/leanprover/lean4/pull/5362) remove the last use of `Lean.(HashSet|HashMap)`
* [#5369](https://github.com/leanprover/lean4/pull/5369) `HashSet.ofArray`
* [#5370](https://github.com/leanprover/lean4/pull/5370) `HashSet.partition`
* [#5581](https://github.com/leanprover/lean4/pull/5581) `Singleton`/`Insert`/`Union` instances for `HashMap`/`Set`
* [#5582](https://github.com/leanprover/lean4/pull/5582) `HashSet.all`/`any`
* [#5590](https://github.com/leanprover/lean4/pull/5590) adding `Insert`/`Singleton`/`Union` instances for `HashMap`/`Set.Raw`
* [#5591](https://github.com/leanprover/lean4/pull/5591) `HashSet.Raw.all/any`
* `Monads`
* [#5463](https://github.com/leanprover/lean4/pull/5463) upstream some monad lemmas
* [#5464](https://github.com/leanprover/lean4/pull/5464) adjust simp attributes on monad lemmas
* [#5522](https://github.com/leanprover/lean4/pull/5522) more monadic simp lemmas
* Simp lemma cleanup
* [#5251](https://github.com/leanprover/lean4/pull/5251) remove redundant simp annotations
* [#5253](https://github.com/leanprover/lean4/pull/5253) remove Int simp lemmas that can't fire
* [#5254](https://github.com/leanprover/lean4/pull/5254) variables appearing on both sides of an iff should be implicit
* [#5381](https://github.com/leanprover/lean4/pull/5381) cleaning up redundant simp lemmas
### Compiler, runtime, and FFI
* [#4685](https://github.com/leanprover/lean4/pull/4685) fixes a typo in the C `run_new_frontend` signature
* [#4729](https://github.com/leanprover/lean4/pull/4729) has IR checker suggest using `noncomputable`
* [#5143](https://github.com/leanprover/lean4/pull/5143) adds a shared library for Lake
* [#5437](https://github.com/leanprover/lean4/pull/5437) removes (syntactically) duplicate imports (@euprunin)
* [#5462](https://github.com/leanprover/lean4/pull/5462) updates `src/lake/lakefile.toml` to the adjusted Lake build process
* [#5541](https://github.com/leanprover/lean4/pull/5541) removes new shared libs before build to better support Windows
* [#5558](https://github.com/leanprover/lean4/pull/5558) make `lean.h` compile with MSVC (@kant2002)
* [#5564](https://github.com/leanprover/lean4/pull/5564) removes non-conforming size-0 arrays (@eric-wieser)
### Lake
* Reservoir build cache. Lake will now attempt to fetch a pre-built copy of the package from Reservoir before building it. This is only enabled for packages in the leanprover or leanprover-community organizations on versions indexed by Reservoir. Users can force Lake to build packages from the source by passing --no-cache on the CLI or by setting the LAKE_NO_CACHE environment variable to true. [#5486](https://github.com/leanprover/lean4/pull/5486), [#5572](https://github.com/leanprover/lean4/pull/5572), [#5583](https://github.com/leanprover/lean4/pull/5583), [#5600](https://github.com/leanprover/lean4/pull/5600), [#5641](https://github.com/leanprover/lean4/pull/5641), [#5642](https://github.com/leanprover/lean4/pull/5642).
* [#5504](https://github.com/leanprover/lean4/pull/5504) lake new and lake init now produce TOML configurations by default.
* [#5878](https://github.com/leanprover/lean4/pull/5878) fixes a serious issue where Lake would delete path dependencies when attempting to cleanup a dependency required with an incorrect name.
* **Breaking changes**
* [#5641](https://github.com/leanprover/lean4/pull/5641) A Lake build of target within a package will no longer build a package's dependencies package-level extra target dependencies. At the technical level, a package's extraDep facet no longer transitively builds its dependencies’ extraDep facets (which include their extraDepTargets).
### Documentation fixes
* [#3918](https://github.com/leanprover/lean4/pull/3918) `@[builtin_doc]` attribute (@digama0)
* [#4305](https://github.com/leanprover/lean4/pull/4305) explains the borrow syntax (@eric-wieser)
* [#5349](https://github.com/leanprover/lean4/pull/5349) adds documentation for `groupBy.loop` (@vihdzp)
* [#5473](https://github.com/leanprover/lean4/pull/5473) fixes typo in `BitVec.mul` docstring (@llllvvuu)
* [#5476](https://github.com/leanprover/lean4/pull/5476) fixes typos in `Lean.MetavarContext`
* [#5481](https://github.com/leanprover/lean4/pull/5481) removes mention of `Lean.withSeconds` (@alexkeizer)
* [#5497](https://github.com/leanprover/lean4/pull/5497) updates documentation and tests for `toUIntX` functions (@TomasPuverle)
* [#5087](https://github.com/leanprover/lean4/pull/5087) mentions that `inferType` does not ensure type correctness
* Many fixes to spelling across the docstrings, (@euprunin): [#5425](https://github.com/leanprover/lean4/pull/5425) [#5426](https://github.com/leanprover/lean4/pull/5426) [#5427](https://github.com/leanprover/lean4/pull/5427) [#5430](https://github.com/leanprover/lean4/pull/5430) [#5431](https://github.com/leanprover/lean4/pull/5431) [#5434](https://github.com/leanprover/lean4/pull/5434) [#5435](https://github.com/leanprover/lean4/pull/5435) [#5436](https://github.com/leanprover/lean4/pull/5436) [#5438](https://github.com/leanprover/lean4/pull/5438) [#5439](https://github.com/leanprover/lean4/pull/5439) [#5440](https://github.com/leanprover/lean4/pull/5440) [#5599](https://github.com/leanprover/lean4/pull/5599)
### Changes to CI
* [#5343](https://github.com/leanprover/lean4/pull/5343) allows addition of `release-ci` label via comment (@thorimur)
* [#5344](https://github.com/leanprover/lean4/pull/5344) sets check level correctly during workflow (@thorimur)
* [#5444](https://github.com/leanprover/lean4/pull/5444) Mathlib's `lean-pr-testing-NNNN` branches should use Batteries' `lean-pr-testing-NNNN` branches
* [#5489](https://github.com/leanprover/lean4/pull/5489) commit `lake-manifest.json` when updating `lean-pr-testing` branches
* [#5490](https://github.com/leanprover/lean4/pull/5490) use separate secrets for commenting and branching in `pr-release.yml`
``` |
reference-manual/Manual/Releases/v4_1_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.1.0 (2023-09-26)" =>
%%%
tag := "release-v4.1.0"
file := "v4.1.0"
%%%
```markdown
* The error positioning on missing tokens has been [improved](https://github.com/leanprover/lean4/pull/2393). In particular, this should make it easier to spot errors in incomplete tactic proofs.
* After elaborating a configuration file, Lake will now cache the configuration to a `lakefile.olean`. Subsequent runs of Lake will import this OLean instead of elaborating the configuration file. This provides a significant performance improvement (benchmarks indicate that using the OLean cuts Lake's startup time in half), but there are some important details to keep in mind:
+ Lake will regenerate this OLean after each modification to the `lakefile.lean` or `lean-toolchain`. You can also force a reconfigure by passing the new `--reconfigure` / `-R` option to `lake`.
+ Lake configuration options (i.e., `-K`) will be fixed at the moment of elaboration. Setting these options when `lake` is using the cached configuration will have no effect. To change options, run `lake` with `-R` / `--reconfigure`.
+ **The `lakefile.olean` is a local configuration and should not be committed to Git. Therefore, existing Lake packages need to add it to their `.gitignore`.**
* The signature of `Lake.buildO` has changed, `args` has been split into `weakArgs` and `traceArgs`. `traceArgs` are included in the input trace and `weakArgs` are not. See Lake's [FFI example](https://github.com/leanprover/lean4/blob/releases/v4.1.0/src/lake/examples/ffi/lib/lakefile.lean) for a demonstration of how to adapt to this change.
* The signatures of `Lean.importModules`, `Lean.Elab.headerToImports`, and `Lean.Elab.parseImports`
* There is now [an `occs` field](https://github.com/leanprover/lean4/pull/2470)
in the configuration object for the `rewrite` tactic,
allowing control of which occurrences of a pattern should be rewritten.
This was previously a separate argument for `Lean.MVarId.rewrite`,
and this has been removed in favour of an additional field of `Rewrite.Config`.
It was not previously accessible from user tactics.
``` |
reference-manual/Manual/Releases/v4_4_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.4.0 (2023-12-31)" =>
%%%
tag := "release-v4.4.0"
file := "v4.4.0"
%%%
````markdown
* Lake and the language server now support per-package server options using the `moreServerOptions` config field, as well as options that apply to both the language server and `lean` using the `leanOptions` config field. Setting either of these fields instead of `moreServerArgs` ensures that viewing files from a dependency uses the options for that dependency. Additionally, `moreServerArgs` is being deprecated in favor of the `moreGlobalServerArgs` field. See PR [#2858](https://github.com/leanprover/lean4/pull/2858).
A Lakefile with the following deprecated package declaration:
```lean
def moreServerArgs := #[
"-Dpp.unicode.fun=true"
]
def moreLeanArgs := moreServerArgs
package SomePackage where
moreServerArgs := moreServerArgs
moreLeanArgs := moreLeanArgs
```
... can be updated to the following package declaration to use per-package options:
```lean
package SomePackage where
leanOptions := #[⟨`pp.unicode.fun, true⟩]
```
* [Rename request handler](https://github.com/leanprover/lean4/pull/2462).
* [Import auto-completion](https://github.com/leanprover/lean4/pull/2904).
* [`pp.beta`` to apply beta reduction when pretty printing](https://github.com/leanprover/lean4/pull/2864).
* [Embed and check githash in .olean](https://github.com/leanprover/lean4/pull/2766).
* [Guess lexicographic order for well-founded recursion](https://github.com/leanprover/lean4/pull/2874).
* [Allow trailing comma in tuples, lists, and tactics](https://github.com/leanprover/lean4/pull/2643).
Bug fixes for [#2628](https://github.com/leanprover/lean4/issues/2628), [#2883](https://github.com/leanprover/lean4/issues/2883),
[#2810](https://github.com/leanprover/lean4/issues/2810), [#2925](https://github.com/leanprover/lean4/issues/2925), and [#2914](https://github.com/leanprover/lean4/issues/2914).
**Lake:**
* `lake init .` and a bare `lake init` and will now use the current directory as the package name. [#2890](https://github.com/leanprover/lean4/pull/2890)
* `lake new` and `lake init` will now produce errors on invalid package names such as `..`, `foo/bar`, `Init`, `Lean`, `Lake`, and `Main`. See issue [#2637](https://github.com/leanprover/lean4/issues/2637) and PR [#2890](https://github.com/leanprover/lean4/pull/2890).
* `lean_lib` no longer converts its name to upper camel case (e.g., `lean_lib bar` will include modules named `bar.*` rather than `Bar.*`). See issue [#2567](https://github.com/leanprover/lean4/issues/2567) and PR [#2889](https://github.com/leanprover/lean4/pull/2889).
* Lean and Lake now properly support non-identifier library names (e.g., `lake new 123-hello` and `import «123Hello»` now work correctly). See issue [#2865](https://github.com/leanprover/lean4/issues/2865) and PR [#2889](https://github.com/leanprover/lean4/pull/2888).
* Lake now filters the environment extensions loaded from a compiled configuration (`lakefile.olean`) to include only those relevant to Lake's workspace loading process. This resolves segmentation faults caused by environment extension type mismatches (e.g., when defining custom elaborators via `elab` in configurations). See issue [#2632](https://github.com/leanprover/lean4/issues/2632) and PR [#2896](https://github.com/leanprover/lean4/pull/2896).
* Cloud releases will now properly be re-unpacked if the build directory is removed. See PR [#2928](https://github.com/leanprover/lean4/pull/2928).
* Lake's `math` template has been simplified. See PR [#2930](https://github.com/leanprover/lean4/pull/2930).
* `lake exe <target>` now parses `target` like a build target (as the help text states it should) rather than as a basic name. For example, `lake exe @mathlib/runLinter` should now work. See PR [#2932](https://github.com/leanprover/lean4/pull/2932).
* `lake new foo.bar [std]` now generates executables named `foo-bar` and `lake new foo.bar exe` properly creates `foo/bar.lean`. See PR [#2932](https://github.com/leanprover/lean4/pull/2932).
* Later packages and libraries in the dependency tree are now preferred over earlier ones. That is, the later ones "shadow" the earlier ones. Such an ordering is more consistent with how declarations generally work in programming languages. This will break any package that relied on the previous ordering. See issue [#2548](https://github.com/leanprover/lean4/issues/2548) and PR [#2937](https://github.com/leanprover/lean4/pull/2937).
* Executable roots are no longer mistakenly treated as importable. They will no longer be picked up by `findModule?`. See PR [#2937](https://github.com/leanprover/lean4/pull/2937).
```` |
reference-manual/Manual/Releases/v4_8_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.8.0 (2024-06-05)" =>
%%%
tag := "release-v4.8.0"
file := "v4.8.0"
%%%
````markdown
### Language features, tactics, and metaprograms
* **Functional induction principles.**
[#3432](https://github.com/leanprover/lean4/pull/3432), [#3620](https://github.com/leanprover/lean4/pull/3620),
[#3754](https://github.com/leanprover/lean4/pull/3754), [#3762](https://github.com/leanprover/lean4/pull/3762),
[#3738](https://github.com/leanprover/lean4/pull/3738), [#3776](https://github.com/leanprover/lean4/pull/3776),
[#3898](https://github.com/leanprover/lean4/pull/3898).
Derived from the definition of a (possibly mutually) recursive function,
a **functional induction principle** is created that is tailored to proofs about that function.
For example from:
```
def ackermann : Nat → Nat → Nat
| 0, m => m + 1
| n+1, 0 => ackermann n 1
| n+1, m+1 => ackermann n (ackermann (n + 1) m)
```
we get
```
ackermann.induct (motive : Nat → Nat → Prop) (case1 : ∀ (m : Nat), motive 0 m)
(case2 : ∀ (n : Nat), motive n 1 → motive (Nat.succ n) 0)
(case3 : ∀ (n m : Nat), motive (n + 1) m → motive n (ackermann (n + 1) m) → motive (Nat.succ n) (Nat.succ m))
(x x : Nat) : motive x x
```
It can be used in the `induction` tactic using the `using` syntax:
```
induction n, m using ackermann.induct
```
* The termination checker now recognizes more recursion patterns without an
explicit `termination_by`. In particular the idiom of counting up to an upper
bound, as in
```
def Array.sum (arr : Array Nat) (i acc : Nat) : Nat :=
if _ : i < arr.size then
Array.sum arr (i+1) (acc + arr[i])
else
acc
```
is recognized without having to say `termination_by arr.size - i`.
* [#3630](https://github.com/leanprover/lean4/pull/3630) makes `termination_by?` not use `sizeOf` when not needed
* [#3652](https://github.com/leanprover/lean4/pull/3652) improves the `termination_by` syntax.
* [#3658](https://github.com/leanprover/lean4/pull/3658) changes how termination arguments are elaborated.
* [#3665](https://github.com/leanprover/lean4/pull/3665) refactors GuessLex to allow inferring more complex termination arguments
* [#3666](https://github.com/leanprover/lean4/pull/3666) infers termination arguments such as `xs.size - i`
* [#3629](https://github.com/leanprover/lean4/pull/3629),
[#3655](https://github.com/leanprover/lean4/pull/3655),
[#3747](https://github.com/leanprover/lean4/pull/3747):
Adds `@[induction_eliminator]` and `@[cases_eliminator]` attributes to be able to define custom eliminators
for the `induction` and `cases` tactics, replacing the `@[eliminator]` attribute.
Gives custom eliminators for `Nat` so that `induction` and `cases` put goal states into terms of `0` and `n + 1`
rather than `Nat.zero` and `Nat.succ n`.
Added option `tactic.customEliminators` to control whether to use custom eliminators.
Added a hack for `rcases`/`rintro`/`obtain` to use the custom eliminator for `Nat`.
* **Shorter instances names.** There is a new algorithm for generating names for anonymous instances.
Across Std and Mathlib, the median ratio between lengths of new names and of old names is about 72%.
With the old algorithm, the longest name was 1660 characters, and now the longest name is 202 characters.
The new algorithm's 95th percentile name length is 67 characters, versus 278 for the old algorithm.
While the new algorithm produces names that are 1.2% less unique,
it avoids cross-project collisions by adding a module-based suffix
when it does not refer to declarations from the same "project" (modules that share the same root).
[#3089](https://github.com/leanprover/lean4/pull/3089)
and [#3934](https://github.com/leanprover/lean4/pull/3934).
* [8d2adf](https://github.com/leanprover/lean4/commit/8d2adf521d2b7636347a5b01bfe473bf0fcfaf31)
Importing two different files containing proofs of the same theorem is no longer considered an error.
This feature is particularly useful for theorems that are automatically generated on demand (e.g., equational theorems).
* [84b091](https://github.com/leanprover/lean4/commit/84b0919a116e9be12f933e764474f45d964ce85c)
Lean now generates an error if the type of a theorem is **not** a proposition.
* **Definition transparency.** [47a343](https://github.com/leanprover/lean4/commit/47a34316fc03ce936fddd2d3dce44784c5bcdfa9). `@[reducible]`, `@[semireducible]`, and `@[irreducible]` are now scoped and able to be set for imported declarations.
* `simp`/`dsimp`
* [#3607](https://github.com/leanprover/lean4/pull/3607) enables kernel projection reduction in `dsimp`
* [b24fbf](https://github.com/leanprover/lean4/commit/b24fbf44f3aaa112f5d799ef2a341772d1eb222d)
and [acdb00](https://github.com/leanprover/lean4/commit/acdb0054d5a0efa724cff596ac26852fad5724c4):
`dsimproc` command
to define defeq-preserving simplification procedures.
* [#3624](https://github.com/leanprover/lean4/pull/3624) makes `dsimp` normalize raw nat literals as `OfNat.ofNat` applications.
* [#3628](https://github.com/leanprover/lean4/pull/3628) makes `simp` correctly handle `OfScientific.ofScientific` literals.
* [#3654](https://github.com/leanprover/lean4/pull/3654) makes `dsimp?` report used simprocs.
* [dee074](https://github.com/leanprover/lean4/commit/dee074dcde03a37b7895a4901df2e4fa490c73c7) fixes equation theorem
handling in `simp` for non-recursive definitions.
* [#3819](https://github.com/leanprover/lean4/pull/3819) improved performance when simp encounters a loop.
* [#3821](https://github.com/leanprover/lean4/pull/3821) fixes discharger/cache interaction.
* [#3824](https://github.com/leanprover/lean4/pull/3824) keeps `simp` from breaking `Char` literals.
* [#3838](https://github.com/leanprover/lean4/pull/3838) allows `Nat` instances matching to be more lenient.
* [#3870](https://github.com/leanprover/lean4/pull/3870) documentation for `simp` configuration options.
* [#3972](https://github.com/leanprover/lean4/pull/3972) fixes simp caching.
* [#4044](https://github.com/leanprover/lean4/pull/4044) improves cache behavior for "well-behaved" dischargers.
* `omega`
* [#3639](https://github.com/leanprover/lean4/pull/3639), [#3766](https://github.com/leanprover/lean4/pull/3766),
[#3853](https://github.com/leanprover/lean4/pull/3853), [#3875](https://github.com/leanprover/lean4/pull/3875):
introduces a term canonicalizer.
* [#3736](https://github.com/leanprover/lean4/pull/3736) improves handling of positivity for the modulo operator for `Int`.
* [#3828](https://github.com/leanprover/lean4/pull/3828) makes it work as a `simp` discharger.
* [#3847](https://github.com/leanprover/lean4/pull/3847) adds helpful error messages.
* `rfl`
* [#3671](https://github.com/leanprover/lean4/pull/3671), [#3708](https://github.com/leanprover/lean4/pull/3708): upstreams the `@[refl]` attribute and the `rfl` tactic.
* [#3751](https://github.com/leanprover/lean4/pull/3751) makes `apply_rfl` not operate on `Eq` itself.
* [#4067](https://github.com/leanprover/lean4/pull/4067) improves error message when there are no goals.
* [#3719](https://github.com/leanprover/lean4/pull/3719) upstreams the `rw?` tactic, with fixes and improvements in
[#3783](https://github.com/leanprover/lean4/pull/3783), [#3794](https://github.com/leanprover/lean4/pull/3794),
[#3911](https://github.com/leanprover/lean4/pull/3911).
* `conv`
* [#3659](https://github.com/leanprover/lean4/pull/3659) adds a `conv` version of the `calc` tactic.
* [#3763](https://github.com/leanprover/lean4/pull/3763) makes `conv` clean up using `try with_reducible rfl` instead of `try rfl`.
* `#guard_msgs`
* [#3617](https://github.com/leanprover/lean4/pull/3617) introduces whitespace protection using the `⏎` character.
* [#3883](https://github.com/leanprover/lean4/pull/3883):
The `#guard_msgs` command now has options to change whitespace normalization and sensitivity to message ordering.
For example, `#guard_msgs (whitespace := lax) in cmd` collapses whitespace before checking messages,
and `#guard_msgs (ordering := sorted) in cmd` sorts the messages in lexicographic order before checking.
* [#3931](https://github.com/leanprover/lean4/pull/3931) adds an unused variables ignore function for `#guard_msgs`.
* [#3912](https://github.com/leanprover/lean4/pull/3912) adds a diff between the expected and actual outputs. This feature is currently
disabled by default, but can be enabled with `set_option guard_msgs.diff true`.
Depending on user feedback, this option may default to `true` in a future version of Lean.
* `do` **notation**
* [#3820](https://github.com/leanprover/lean4/pull/3820) makes it an error to lift `(<- ...)` out of a pure `if ... then ... else ...`
* **Lazy discrimination trees**
* [#3610](https://github.com/leanprover/lean4/pull/3610) fixes a name collision for `LazyDiscrTree` that could lead to cache poisoning.
* [#3677](https://github.com/leanprover/lean4/pull/3677) simplifies and fixes `LazyDiscrTree` handling for `exact?`/`apply?`.
* [#3685](https://github.com/leanprover/lean4/pull/3685) moves general `exact?`/`apply?` functionality into `LazyDiscrTree`.
* [#3769](https://github.com/leanprover/lean4/pull/3769) has lemma selection improvements for `rw?` and `LazyDiscrTree`.
* [#3818](https://github.com/leanprover/lean4/pull/3818) improves ordering of matches.
* [#3590](https://github.com/leanprover/lean4/pull/3590) adds `inductive.autoPromoteIndices` option to be able to disable auto promotion of indices in the `inductive` command.
* **Miscellaneous bug fixes and improvements**
* [#3606](https://github.com/leanprover/lean4/pull/3606) preserves `cache` and `dischargeDepth` fields in `Lean.Meta.Simp.Result.mkEqSymm`.
* [#3633](https://github.com/leanprover/lean4/pull/3633) makes `elabTermEnsuringType` respect `errToSorry`, improving error recovery of the `have` tactic.
* [#3647](https://github.com/leanprover/lean4/pull/3647) enables `noncomputable unsafe` definitions, for deferring implementations until later.
* [#3672](https://github.com/leanprover/lean4/pull/3672) adjust namespaces of tactics.
* [#3725](https://github.com/leanprover/lean4/pull/3725) fixes `Ord` derive handler for indexed inductive types with unused alternatives.
* [#3893](https://github.com/leanprover/lean4/pull/3893) improves performance of derived `Ord` instances.
* [#3771](https://github.com/leanprover/lean4/pull/3771) changes error reporting for failing tactic macros. Improves `rfl` error message.
* [#3745](https://github.com/leanprover/lean4/pull/3745) fixes elaboration of generalized field notation if the object of the notation is an optional parameter.
* [#3799](https://github.com/leanprover/lean4/pull/3799) makes commands such as `universe`, `variable`, `namespace`, etc. require that their argument appear in a later column.
Commands that can optionally parse an `ident` or parse any number of `ident`s generally should require
that the `ident` use `colGt`. This keeps typos in commands from being interpreted as identifiers.
* [#3815](https://github.com/leanprover/lean4/pull/3815) lets the `split` tactic be used for writing code.
* [#3822](https://github.com/leanprover/lean4/pull/3822) adds missing info in `induction` tactic for `with` clauses of the form `| cstr a b c => ?_`.
* [#3806](https://github.com/leanprover/lean4/pull/3806) fixes `withSetOptionIn` combinator.
* [#3844](https://github.com/leanprover/lean4/pull/3844) removes unused `trace.Elab.syntax` option.
* [#3896](https://github.com/leanprover/lean4/pull/3896) improves hover and go-to-def for `attribute` command.
* [#3989](https://github.com/leanprover/lean4/pull/3989) makes linter options more discoverable.
* [#3916](https://github.com/leanprover/lean4/pull/3916) fixes go-to-def for syntax defined with `@[builtin_term_parser]`.
* [#3962](https://github.com/leanprover/lean4/pull/3962) fixes how `solveByElim` handles `symm` lemmas, making `exact?`/`apply?` usable again.
* [#3968](https://github.com/leanprover/lean4/pull/3968) improves the `@[deprecated]` attribute, adding `(since := "<date>")` field.
* [#3768](https://github.com/leanprover/lean4/pull/3768) makes `#print` command show structure fields.
* [#3974](https://github.com/leanprover/lean4/pull/3974) makes `exact?%` behave like `by exact?` rather than `by apply?`.
* [#3994](https://github.com/leanprover/lean4/pull/3994) makes elaboration of `he ▸ h` notation more predictable.
* [#3991](https://github.com/leanprover/lean4/pull/3991) adjusts transparency for `decreasing_trivial` macros.
* [#4092](https://github.com/leanprover/lean4/pull/4092) improves performance of `binop%` and `binrel%` expression tree elaborators.
* **Docs:** [#3748](https://github.com/leanprover/lean4/pull/3748), [#3796](https://github.com/leanprover/lean4/pull/3796),
[#3800](https://github.com/leanprover/lean4/pull/3800), [#3874](https://github.com/leanprover/lean4/pull/3874),
[#3863](https://github.com/leanprover/lean4/pull/3863), [#3862](https://github.com/leanprover/lean4/pull/3862),
[#3891](https://github.com/leanprover/lean4/pull/3891), [#3873](https://github.com/leanprover/lean4/pull/3873),
[#3908](https://github.com/leanprover/lean4/pull/3908), [#3872](https://github.com/leanprover/lean4/pull/3872).
### Language server and IDE extensions
* [#3602](https://github.com/leanprover/lean4/pull/3602) enables `import` auto-completions.
* [#3608](https://github.com/leanprover/lean4/pull/3608) fixes issue [leanprover/vscode-lean4#392](https://github.com/leanprover/vscode-lean4/issues/392).
Diagnostic ranges had an off-by-one error that would misplace goal states for example.
* [#3014](https://github.com/leanprover/lean4/pull/3014) introduces snapshot trees, foundational work for incremental tactics and parallelism.
[#3849](https://github.com/leanprover/lean4/pull/3849) adds basic incrementality API.
* [#3271](https://github.com/leanprover/lean4/pull/3271) adds support for server-to-client requests.
* [#3656](https://github.com/leanprover/lean4/pull/3656) fixes jump to definition when there are conflicting names from different files.
Fixes issue [#1170](https://github.com/leanprover/lean4/issues/1170).
* [#3691](https://github.com/leanprover/lean4/pull/3691), [#3925](https://github.com/leanprover/lean4/pull/3925),
[#3932](https://github.com/leanprover/lean4/pull/3932) keep semantic tokens synchronized (used for semantic highlighting), with performance improvements.
* [#3247](https://github.com/leanprover/lean4/pull/3247) and [#3730](https://github.com/leanprover/lean4/pull/3730)
add diagnostics to run "Restart File" when a file dependency is saved.
* [#3722](https://github.com/leanprover/lean4/pull/3722) uses the correct module names when displaying references.
* [#3728](https://github.com/leanprover/lean4/pull/3728) makes errors in header reliably appear and makes the "Import out of date" warning be at "hint" severity.
[#3739](https://github.com/leanprover/lean4/pull/3739) simplifies the text of this warning.
* [#3778](https://github.com/leanprover/lean4/pull/3778) fixes [#3462](https://github.com/leanprover/lean4/issues/3462),
where info nodes from before the cursor would be used for computing completions.
* [#3985](https://github.com/leanprover/lean4/pull/3985) makes trace timings appear in Infoview.
### Pretty printing
* [#3797](https://github.com/leanprover/lean4/pull/3797) fixes the hovers over binders so that they show their types.
* [#3640](https://github.com/leanprover/lean4/pull/3640) and [#3735](https://github.com/leanprover/lean4/pull/3735): Adds attribute `@[pp_using_anonymous_constructor]` to make structures pretty print as `⟨x, y, z⟩`
rather than as `{a := x, b := y, c := z}`.
This attribute is applied to `Sigma`, `PSigma`, `PProd`, `Subtype`, `And`, and `Fin`.
* [#3749](https://github.com/leanprover/lean4/pull/3749)
Now structure instances pretty print with parent structures' fields inlined.
That is, if `B` extends `A`, then `{ toA := { x := 1 }, y := 2 }` now pretty prints as `{ x := 1, y := 2 }`.
Setting option `pp.structureInstances.flatten` to false turns this off.
* [#3737](https://github.com/leanprover/lean4/pull/3737), [#3744](https://github.com/leanprover/lean4/pull/3744)
and [#3750](https://github.com/leanprover/lean4/pull/3750):
Option `pp.structureProjections` is renamed to `pp.fieldNotation`, and there is now a suboption `pp.fieldNotation.generalized`
to enable pretty printing function applications using generalized field notation (defaults to true).
Field notation can be disabled on a function-by-function basis using the `@[pp_nodot]` attribute.
The notation is not used for theorems.
* [#4071](https://github.com/leanprover/lean4/pull/4071) fixes interaction between app unexpanders and `pp.fieldNotation.generalized`
* [#3625](https://github.com/leanprover/lean4/pull/3625) makes `delabConstWithSignature` (used by `#check`) have the ability to put arguments "after the colon"
to avoid printing inaccessible names.
* [#3798](https://github.com/leanprover/lean4/pull/3798),
[#3978](https://github.com/leanprover/lean4/pull/3978),
[#3798](https://github.com/leanprover/lean4/pull/3980):
Adds options `pp.mvars` (default: true) and `pp.mvars.withType` (default: false).
When `pp.mvars` is false, expression metavariables pretty print as `?_` and universe metavariables pretty print as `_`.
When `pp.mvars.withType` is true, expression metavariables pretty print with a type ascription.
These can be set when using `#guard_msgs` to make tests not depend on the particular names of metavariables.
* [#3917](https://github.com/leanprover/lean4/pull/3917) makes binders hoverable and gives them docstrings.
* [#4034](https://github.com/leanprover/lean4/pull/4034) makes hovers for RHS terms in `match` expressions in the Infoview reliably show the correct term.
### Library
* `Bool`/`Prop`
* [#3508](https://github.com/leanprover/lean4/pull/3508) improves `simp` confluence for `Bool` and `Prop` terms.
* Theorems: [#3604](https://github.com/leanprover/lean4/pull/3604)
* `Nat`
* [#3579](https://github.com/leanprover/lean4/pull/3579) makes `Nat.succ_eq_add_one` be a simp lemma, now that `induction`/`cases` uses `n + 1` instead of `Nat.succ n`.
* [#3808](https://github.com/leanprover/lean4/pull/3808) replaces `Nat.succ` simp rules with simprocs.
* [#3876](https://github.com/leanprover/lean4/pull/3876) adds faster `Nat.repr` implementation in C.
* `Int`
* Theorems: [#3890](https://github.com/leanprover/lean4/pull/3890)
* `UInt`s
* [#3960](https://github.com/leanprover/lean4/pull/3960) improves performance of upcasting.
* `Array` and `Subarray`
* [#3676](https://github.com/leanprover/lean4/pull/3676) removes `Array.eraseIdxAux`, `Array.eraseIdxSzAux`, and `Array.eraseIdx'`.
* [#3648](https://github.com/leanprover/lean4/pull/3648) simplifies `Array.findIdx?`.
* [#3851](https://github.com/leanprover/lean4/pull/3851) renames fields of `Subarray`.
* `List`
* [#3785](https://github.com/leanprover/lean4/pull/3785) upstreams tail-recursive List operations and `@[csimp]` lemmas.
* `BitVec`
* Theorems: [#3593](https://github.com/leanprover/lean4/pull/3593),
[#3593](https://github.com/leanprover/lean4/pull/3593), [#3597](https://github.com/leanprover/lean4/pull/3597),
[#3598](https://github.com/leanprover/lean4/pull/3598), [#3721](https://github.com/leanprover/lean4/pull/3721),
[#3729](https://github.com/leanprover/lean4/pull/3729), [#3880](https://github.com/leanprover/lean4/pull/3880),
[#4039](https://github.com/leanprover/lean4/pull/4039).
* [#3884](https://github.com/leanprover/lean4/pull/3884) protects `Std.BitVec`.
* `String`
* [#3832](https://github.com/leanprover/lean4/pull/3832) fixes `String.splitOn`.
* [#3959](https://github.com/leanprover/lean4/pull/3959) adds `String.Pos.isValid`.
* [#3959](https://github.com/leanprover/lean4/pull/3959) UTF-8 string validation.
* [#3961](https://github.com/leanprover/lean4/pull/3961) adds a model implementation for UTF-8 encoding and decoding.
* `IO`
* [#4097](https://github.com/leanprover/lean4/pull/4097) adds `IO.getTaskState` which returns whether a task is finished, actively running, or waiting on other Tasks to finish.
* **Refactors**
* [#3605](https://github.com/leanprover/lean4/pull/3605) reduces imports for `Init.Data.Nat` and `Init.Data.Int`.
* [#3613](https://github.com/leanprover/lean4/pull/3613) reduces imports for `Init.Omega.Int`.
* [#3634](https://github.com/leanprover/lean4/pull/3634) upstreams `Std.Data.Nat`
and [#3635](https://github.com/leanprover/lean4/pull/3635) upstreams `Std.Data.Int`.
* [#3790](https://github.com/leanprover/lean4/pull/3790) reduces more imports for `omega`.
* [#3694](https://github.com/leanprover/lean4/pull/3694) extends `GetElem` interface with `getElem!` and `getElem?` to simplify containers like `RBMap`.
* [#3865](https://github.com/leanprover/lean4/pull/3865) renames `Option.toMonad` (see breaking changes below).
* [#3882](https://github.com/leanprover/lean4/pull/3882) unifies `lexOrd` with `compareLex`.
* **Other fixes or improvements**
* [#3765](https://github.com/leanprover/lean4/pull/3765) makes `Quotient.sound` be a `theorem`.
* [#3645](https://github.com/leanprover/lean4/pull/3645) fixes `System.FilePath.parent` in the case of absolute paths.
* [#3660](https://github.com/leanprover/lean4/pull/3660) `ByteArray.toUInt64LE!` and `ByteArray.toUInt64BE!` were swapped.
* [#3881](https://github.com/leanprover/lean4/pull/3881), [#3887](https://github.com/leanprover/lean4/pull/3887) fix linearity issues in `HashMap.insertIfNew`, `HashSet.erase`, and `HashMap.erase`.
The `HashMap.insertIfNew` fix improves `import` performance.
* [#3830](https://github.com/leanprover/lean4/pull/3830) ensures linearity in `Parsec.many*Core`.
* [#3930](https://github.com/leanprover/lean4/pull/3930) adds `FS.Stream.isTty` field.
* [#3866](https://github.com/leanprover/lean4/pull/3866) deprecates `Option.toBool` in favor of `Option.isSome`.
* [#3975](https://github.com/leanprover/lean4/pull/3975) upstreams `Data.List.Init` and `Data.Array.Init` material from Std.
* [#3942](https://github.com/leanprover/lean4/pull/3942) adds instances that make `ac_rfl` work without Mathlib.
* [#4010](https://github.com/leanprover/lean4/pull/4010) changes `Fin.induction` to use structural induction.
* [02753f](https://github.com/leanprover/lean4/commit/02753f6e4c510c385efcbf71fa9a6bec50fce9ab)
fixes bug in `reduceLeDiff` simproc.
* [#4097](https://github.com/leanprover/lean4/pull/4097)
adds `IO.TaskState` and `IO.getTaskState` to get the task from the Lean runtime's task manager.
* **Docs:** [#3615](https://github.com/leanprover/lean4/pull/3615), [#3664](https://github.com/leanprover/lean4/pull/3664),
[#3707](https://github.com/leanprover/lean4/pull/3707), [#3734](https://github.com/leanprover/lean4/pull/3734),
[#3868](https://github.com/leanprover/lean4/pull/3868), [#3861](https://github.com/leanprover/lean4/pull/3861),
[#3869](https://github.com/leanprover/lean4/pull/3869), [#3858](https://github.com/leanprover/lean4/pull/3858),
[#3856](https://github.com/leanprover/lean4/pull/3856), [#3857](https://github.com/leanprover/lean4/pull/3857),
[#3867](https://github.com/leanprover/lean4/pull/3867), [#3864](https://github.com/leanprover/lean4/pull/3864),
[#3860](https://github.com/leanprover/lean4/pull/3860), [#3859](https://github.com/leanprover/lean4/pull/3859),
[#3871](https://github.com/leanprover/lean4/pull/3871), [#3919](https://github.com/leanprover/lean4/pull/3919).
### Lean internals
* **Defeq and WHNF algorithms**
* [#3616](https://github.com/leanprover/lean4/pull/3616) gives better support for reducing `Nat.rec` expressions.
* [#3774](https://github.com/leanprover/lean4/pull/3774) add tracing for "non-easy" WHNF cases.
* [#3807](https://github.com/leanprover/lean4/pull/3807) fixes an `isDefEq` performance issue, now trying structure eta *after* lazy delta reduction.
* [#3816](https://github.com/leanprover/lean4/pull/3816) fixes `.yesWithDeltaI` behavior to prevent increasing transparency level when reducing projections.
* [#3837](https://github.com/leanprover/lean4/pull/3837) improves heuristic at `isDefEq`.
* [#3965](https://github.com/leanprover/lean4/pull/3965) improves `isDefEq` for constraints of the form `t.i =?= s.i`.
* [#3977](https://github.com/leanprover/lean4/pull/3977) improves `isDefEqProj`.
* [#3981](https://github.com/leanprover/lean4/pull/3981) adds universe constraint approximations to be able to solve `u =?= max u ?v` using `?v = u`.
These approximations are only applied when universe constraints cannot be postponed anymore.
* [#4004](https://github.com/leanprover/lean4/pull/4004) improves `isDefEqProj` during type class resolution.
* [#4012](https://github.com/leanprover/lean4/pull/4012) adds `backward.isDefEq.lazyProjDelta` and `backward.isDefEq.lazyWhnfCore` backwards compatibility flags.
* **Kernel**
* [#3966](https://github.com/leanprover/lean4/pull/3966) removes dead code.
* [#4035](https://github.com/leanprover/lean4/pull/4035) fixes mismatch for `TheoremVal` between Lean and C++.
* **Discrimination trees**
* [423fed](https://github.com/leanprover/lean4/commit/423fed79a9de75705f34b3e8648db7e076c688d7)
and [3218b2](https://github.com/leanprover/lean4/commit/3218b25974d33e92807af3ce42198911c256ff1d):
simplify handling of dependent/non-dependent pi types.
* **Typeclass instance synthesis**
* [#3638](https://github.com/leanprover/lean4/pull/3638) eta-reduces synthesized instances
* [ce350f](https://github.com/leanprover/lean4/commit/ce350f348161e63fccde6c4a5fe1fd2070e7ce0f) fixes a linearity issue
* [917a31](https://github.com/leanprover/lean4/commit/917a31f694f0db44d6907cc2b1485459afe74d49)
improves performance by considering at most one answer for subgoals not containing metavariables.
[#4008](https://github.com/leanprover/lean4/pull/4008) adds `backward.synthInstance.canonInstances` backward compatibility flag.
* **Definition processing**
* [#3661](https://github.com/leanprover/lean4/pull/3661), [#3767](https://github.com/leanprover/lean4/pull/3767) changes automatically generated equational theorems to be named
using suffix `.eq_<idx>` instead of `._eq_<idx>`, and `.eq_def` instead of `._unfold`. (See breaking changes below.)
[#3675](https://github.com/leanprover/lean4/pull/3675) adds a mechanism to reserve names.
[#3803](https://github.com/leanprover/lean4/pull/3803) fixes reserved name resolution inside namespaces and fixes handling of `match`er declarations and equation lemmas.
* [#3662](https://github.com/leanprover/lean4/pull/3662) causes auxiliary definitions nested inside theorems to become `def`s if they are not proofs.
* [#4006](https://github.com/leanprover/lean4/pull/4006) makes proposition fields of `structure`s be theorems.
* [#4018](https://github.com/leanprover/lean4/pull/4018) makes it an error for a theorem to be `extern`.
* [#4047](https://github.com/leanprover/lean4/pull/4047) improves performance making equations for well-founded recursive definitions.
* **Refactors**
* [#3614](https://github.com/leanprover/lean4/pull/3614) avoids unfolding in `Lean.Meta.evalNat`.
* [#3621](https://github.com/leanprover/lean4/pull/3621) centralizes functionality for `Fix`/`GuessLex`/`FunInd` in the `ArgsPacker` module.
* [#3186](https://github.com/leanprover/lean4/pull/3186) rewrites the UnusedVariable linter to be more performant.
* [#3589](https://github.com/leanprover/lean4/pull/3589) removes coercion from `String` to `Name` (see breaking changes below).
* [#3237](https://github.com/leanprover/lean4/pull/3237) removes the `lines` field from `FileMap`.
* [#3951](https://github.com/leanprover/lean4/pull/3951) makes msg parameter to `throwTacticEx` optional.
* **Diagnostics**
* [#4016](https://github.com/leanprover/lean4/pull/4016), [#4019](https://github.com/leanprover/lean4/pull/4019),
[#4020](https://github.com/leanprover/lean4/pull/4020), [#4030](https://github.com/leanprover/lean4/pull/4030),
[#4031](https://github.com/leanprover/lean4/pull/4031),
[c3714b](https://github.com/leanprover/lean4/commit/c3714bdc6d46845c0428735b283c5b48b23cbcf7),
[#4049](https://github.com/leanprover/lean4/pull/4049) adds `set_option diagnostics true` for diagnostic counters.
Tracks number of unfolded declarations, instances, reducible declarations, used instances, recursor reductions,
`isDefEq` heuristic applications, among others.
This option is suggested in exceptional situations, such as at deterministic timeout and maximum recursion depth.
* [283587](https://github.com/leanprover/lean4/commit/283587987ab2eb3b56fbc3a19d5f33ab9e04a2ef)
adds diagnostic information for `simp`.
* [#4043](https://github.com/leanprover/lean4/pull/4043) adds diagnostic information for congruence theorems.
* [#4048](https://github.com/leanprover/lean4/pull/4048) display diagnostic information
for `set_option diagnostics true in <tactic>` and `set_option diagnostics true in <term>`.
* **Other features**
* [#3800](https://github.com/leanprover/lean4/pull/3800) adds environment extension to record which definitions use structural or well-founded recursion.
* [#3801](https://github.com/leanprover/lean4/pull/3801) `trace.profiler` can now export to Firefox Profiler.
* [#3918](https://github.com/leanprover/lean4/pull/3918), [#3953](https://github.com/leanprover/lean4/pull/3953) adds `@[builtin_doc]` attribute to make docs and location of a declaration available as a builtin.
* [#3939](https://github.com/leanprover/lean4/pull/3939) adds the `lean --json` CLI option to print messages as JSON.
* [#3075](https://github.com/leanprover/lean4/pull/3075) improves `test_extern` command.
* [#3970](https://github.com/leanprover/lean4/pull/3970) gives monadic generalization of `FindExpr`.
* **Docs:** [#3743](https://github.com/leanprover/lean4/pull/3743), [#3921](https://github.com/leanprover/lean4/pull/3921),
[#3954](https://github.com/leanprover/lean4/pull/3954).
* **Other fixes:** [#3622](https://github.com/leanprover/lean4/pull/3622),
[#3726](https://github.com/leanprover/lean4/pull/3726), [#3823](https://github.com/leanprover/lean4/pull/3823),
[#3897](https://github.com/leanprover/lean4/pull/3897), [#3964](https://github.com/leanprover/lean4/pull/3964),
[#3946](https://github.com/leanprover/lean4/pull/3946), [#4007](https://github.com/leanprover/lean4/pull/4007),
[#4026](https://github.com/leanprover/lean4/pull/4026).
### Compiler, runtime, and FFI
* [#3632](https://github.com/leanprover/lean4/pull/3632) makes it possible to allocate and free thread-local runtime resources for threads not started by Lean itself.
* [#3627](https://github.com/leanprover/lean4/pull/3627) improves error message about compacting closures.
* [#3692](https://github.com/leanprover/lean4/pull/3692) fixes deadlock in `IO.Promise.resolve`.
* [#3753](https://github.com/leanprover/lean4/pull/3753) catches error code from `MoveFileEx` on Windows.
* [#4028](https://github.com/leanprover/lean4/pull/4028) fixes a double `reset` bug in `ResetReuse` transformation.
* [6e731b](https://github.com/leanprover/lean4/commit/6e731b4370000a8e7a5cfb675a7f3d7635d21f58)
removes `interpreter` copy constructor to avoid potential memory safety issues.
### Lake
* **TOML Lake configurations**. [#3298](https://github.com/leanprover/lean4/pull/3298), [#4104](https://github.com/leanprover/lean4/pull/4104).
Lake packages can now use TOML as a alternative configuration file format instead of Lean. If the default `lakefile.lean` is missing, Lake will also look for a `lakefile.toml`. The TOML version of the configuration supports a restricted set of the Lake configuration options, only including those which can easily mapped to a TOML data structure. The TOML syntax itself fully compiles with the TOML v1.0.0 specification.
As part of the introduction of this new feature, we have been helping maintainers of some major packages within the ecosystem switch to this format. For example, the following is Aesop's new `lakefile.toml`:
**[leanprover-community/aesop/lakefile.toml](https://raw.githubusercontent.com/leanprover-community/aesop/de11e0ecf372976e6d627c210573146153090d2d/lakefile.toml)**
```toml
name = "aesop"
defaultTargets = ["Aesop"]
testRunner = "test"
precompileModules = false
[[require]]
name = "batteries"
git = "https://github.com/leanprover-community/batteries"
rev = "main"
[[lean_lib]]
name = "Aesop"
[[lean_lib]]
name = "AesopTest"
globs = ["AesopTest.+"]
leanOptions = {linter.unusedVariables = false}
[[lean_exe]]
name = "test"
srcDir = "scripts"
```
To assist users who wish to transition their packages between configuration file formats, there is also a new `lake translate-config` command for migrating to/from TOML.
Running `lake translate-config toml` will produce a `lakefile.toml` version of a package's `lakefile.lean`. Any configuration options unsupported by the TOML format will be discarded during translation, but the original `lakefile.lean` will remain so that you can verify the translation looks good before deleting it.
* **Build progress overhaul.** [#3835](https://github.com/leanprover/lean4/pull/3835), [#4115](https://github.com/leanprover/lean4/pull/4115), [#4127](https://github.com/leanprover/lean4/pull/4127), [#4220](https://github.com/leanprover/lean4/pull/4220), [#4232](https://github.com/leanprover/lean4/pull/4232), [#4236](https://github.com/leanprover/lean4/pull/4236).
Builds are now managed by a top-level Lake build monitor, this makes the output of Lake builds more standardized and enables producing prettier and more configurable progress reports.
As part of this change, job isolation has improved. Stray I/O and other build related errors in custom targets are now properly isolated and caught as part of their job. Import errors no longer cause Lake to abort the entire build and are instead localized to the build jobs of the modules in question.
Lake also now uses ANSI escape sequences to add color and produce progress lines that update in-place; this can be toggled on and off using `--ansi` / `--no-ansi`.
`--wfail` and `--iofail` options have been added that causes a build to fail if any of the jobs log a warning (`--wfail`) or produce any output or log information messages (`--iofail`). Unlike some other build systems, these options do **NOT** convert these logs into errors, and Lake does not abort jobs on such a log (i.e., dependent jobs will still continue unimpeded).
* `lake test`. [#3779](https://github.com/leanprover/lean4/pull/3779).
Lake now has a built-in `test` command which will run a script or executable labelled `@[test_runner]` (in Lean) or defined as the `testRunner` (in TOML) in the root package.
Lake also provides a `lake check-test` command which will exit with code `0` if the package has a properly configured test runner or error with `1` otherwise.
* `lake lean`. [#3793](https://github.com/leanprover/lean4/pull/3793).
The new command `lake lean <file> [-- <args...>]` functions like `lake env lean <file> <args...>`, except that it builds the imports of `file` before running `lean`. This makes it very useful for running test or example code that imports modules that are not guaranteed to have been built beforehand.
* **Miscellaneous bug fixes and improvements**
* [#3609](https://github.com/leanprover/lean4/pull/3609) `LEAN_GITHASH` environment variable to override the detected Git hash for Lean when computing traces, useful for testing custom builds of Lean.
* [#3795](https://github.com/leanprover/lean4/pull/3795) improves relative package directory path normalization in the pre-rename check.
* [#3957](https://github.com/leanprover/lean4/pull/3957) fixes handling of packages that appear multiple times in a dependency tree.
* [#3999](https://github.com/leanprover/lean4/pull/3999) makes it an error for there to be a mismatch between a package name and what it is required as. Also adds a special message for the `std`-to-`batteries` rename.
* [#4033](https://github.com/leanprover/lean4/pull/4033) fixes quiet mode.
* **Docs:** [#3704](https://github.com/leanprover/lean4/pull/3704).
### DevOps
* [#3536](https://github.com/leanprover/lean4/pull/3536) and [#3833](https://github.com/leanprover/lean4/pull/3833)
add a checklist for the release process.
* [#3600](https://github.com/leanprover/lean4/pull/3600) runs nix-ci more uniformly.
* [#3612](https://github.com/leanprover/lean4/pull/3612) avoids argument limits when building on Windows.
* [#3682](https://github.com/leanprover/lean4/pull/3682) builds Lean's `.o` files in parallel to rest of core.
* [#3601](https://github.com/leanprover/lean4/pull/3601)
changes the way Lean is built on Windows (see breaking changes below).
As a result, Lake now dynamically links executables with `supportInterpreter := true` on Windows
to `libleanshared.dll` and `libInit_shared.dll`. Therefore, such executables will not run
unless those shared libraries are co-located with the executables or part of `PATH`.
Running the executable via `lake exe` will ensure these libraries are part of `PATH`.
In a related change, the signature of the `nativeFacets` Lake configuration options has changed
from a static `Array` to a function `(shouldExport : Bool) → Array`.
See its docstring or Lake's [README](https://github.com/leanprover/lean4/blob/releases/v4.8.0/src/lake/README.md) for further details on the changed option.
* [#3690](https://github.com/leanprover/lean4/pull/3690) marks "Build matrix complete" as canceled if the build is canceled.
* [#3700](https://github.com/leanprover/lean4/pull/3700), [#3702](https://github.com/leanprover/lean4/pull/3702),
[#3701](https://github.com/leanprover/lean4/pull/3701), [#3834](https://github.com/leanprover/lean4/pull/3834),
[#3923](https://github.com/leanprover/lean4/pull/3923): fixes and improvements for std and mathlib CI.
* [#3712](https://github.com/leanprover/lean4/pull/3712) fixes `nix build .` on macOS.
* [#3717](https://github.com/leanprover/lean4/pull/3717) replaces `shell.nix` in devShell with `flake.nix`.
* [#3715](https://github.com/leanprover/lean4/pull/3715) and [#3790](https://github.com/leanprover/lean4/pull/3790) add test result summaries.
* [#3971](https://github.com/leanprover/lean4/pull/3971) prevents stage0 changes via the merge queue.
* [#3979](https://github.com/leanprover/lean4/pull/3979) adds handling for `changes-stage0` label.
* [#3952](https://github.com/leanprover/lean4/pull/3952) adds a script to summarize GitHub issues.
* [18a699](https://github.com/leanprover/lean4/commit/18a69914da53dbe37c91bc2b9ce65e1dc01752b6)
fixes asan linking
### Breaking changes
* Due to the major Lake build refactor, code using the affected parts of the Lake API or relying on the previous output format of Lake builds is likely to have been broken. We have tried to minimize the breakages and, where possible, old definitions have been marked `@[deprecated]` with a reference to the new alternative.
* Executables configured with `supportInterpreter := true` on Windows should now be run via `lake exe` to function properly.
* Automatically generated equational theorems are now named using suffix `.eq_<idx>` instead of `._eq_<idx>`, and `.eq_def` instead of `._unfold`. Example:
```
def fact : Nat → Nat
| 0 => 1
| n+1 => (n+1) * fact n
theorem ex : fact 0 = 1 := by unfold fact; decide
#check fact.eq_1
-- fact.eq_1 : fact 0 = 1
#check fact.eq_2
-- fact.eq_2 (n : Nat) : fact (Nat.succ n) = (n + 1) * fact n
#check fact.eq_def
/-
fact.eq_def :
∀ (x : Nat),
fact x =
match x with
| 0 => 1
| Nat.succ n => (n + 1) * fact n
-/
```
* The coercion from `String` to `Name` was removed. Previously, it was `Name.mkSimple`, which does not separate strings at dots, but experience showed that this is not always the desired coercion. For the previous behavior, manually insert a call to `Name.mkSimple`.
* The `Subarray` fields `as`, `h₁` and `h₂` have been renamed to `array`, `start_le_stop`, and `stop_le_array_size`, respectively. This more closely follows standard Lean conventions. Deprecated aliases for the field projections were added; these will be removed in a future release.
* The change to the instance name algorithm (described above) can break projects that made use of the auto-generated names.
* `Option.toMonad` has been renamed to `Option.getM` and the unneeded `[Monad m]` instance argument has been removed.
```` |
reference-manual/Manual/Releases/v4_20_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
-- TODO: figure out why this is needed with the new codegen
set_option maxRecDepth 9000
#doc (Manual) "Lean 4.20.0 (2025-06-02)" =>
%%%
tag := "release-v4.20.0"
file := "v4.20.0"
%%%
````markdown
For this release, 346 changes landed. In addition to the 108 feature additions and 85 fixes listed below there were 6 refactoring changes, 7 documentation improvements, 8 performance improvements, 4 improvements to the test suite and 126 other changes.
## Highlights
The Lean v4.20.0 release brings multiple new features, bug fixes, improvements to Lake, and groundwork for the module system.
### Language Features
* [#6432](https://github.com/leanprover/lean4/pull/6432) implements tactics called `extract_lets` and `lift_lets` that
manipulate `let`/`let_fun` expressions. The `extract_lets` tactic
creates new local declarations extracted from any `let` and `let_fun`
expressions in the main goal. For top-level lets in the target, it is
like the `intros` tactic, but in general it can extract lets from deeper
subexpressions as well. The `lift_lets` tactic moves `let` and `let_fun`
expressions as far out of an expression as possible, but it does not
extract any new local declarations. The option `extract_lets +lift`
combines these behaviors.
* [#7806](https://github.com/leanprover/lean4/pull/7806) modifies the syntaxes of the `ext`, `intro` and `enter` conv
tactics to accept `_`. The introduced binder is an inaccessible name.
* [#7830](https://github.com/leanprover/lean4/pull/7830) modifies the syntax of `induction`, `cases`, and other tactics
that use `Lean.Parser.Tactic.inductionAlts`. If a case omits `=> ...`
then it is assumed to be `=> ?_`. Example:
```lean
example (p : Nat × Nat) : p.1 = p.1 := by
cases p with | _ p1 p2
/-
case mk
p1 p2 : Nat
⊢ (p1, p2).fst = (p1, p2).fst
-/
```
This works with multiple cases as well. Example:
```lean
example (n : Nat) : n + 1 = 1 + n := by
induction n with | zero | succ n ih
/-
case zero
⊢ 0 + 1 = 1 + 0
case succ
n : Nat
ih : n + 1 = 1 + n
⊢ n + 1 + 1 = 1 + (n + 1)
-/
```
The `induction n with | zero | succ n ih` is short for `induction n with
| zero | succ n ih => ?_`, which is short for `induction n with | zero
=> ?_ | succ n ih => ?_`. Note that a consequence of parsing is that
only the last alternative can omit `=>`. Any `=>`-free alternatives
before an alternative with `=>` will be a part of that alternative.
* [#7831](https://github.com/leanprover/lean4/pull/7831) adds extensibility to the `evalAndSuggest` procedure used to
implement `try?`. Users can now implement their own handlers for any
tactic.
```lean
-- Install a `TryTactic` handler for `assumption`
@[try_tactic assumption]
def evalTryApply : TryTactic := fun tac => do
-- We just use the default implementation, but return a different tactic.
evalAssumption tac
`(tactic| (trace "worked"; assumption))
/-- info: Try this: · trace "worked"; assumption -/
#guard_msgs (info) in
example (h : False) : False := by
try? (max := 1) -- at most one solution
-- `try?` uses `evalAndSuggest` the attribute `[try_tactic]` is used to extend `evalAndSuggest`.
-- Let's define our own `try?` that uses `evalAndSuggest`
elab stx:"my_try?" : tactic => do
-- Things to try
let toTry ← `(tactic| attempt_all | assumption | apply True | rfl)
evalAndSuggest stx toTry
/--
info: Try these:
• · trace "worked"; assumption
• rfl
-/
#guard_msgs (info) in
example (a : Nat) (h : a = a) : a = a := by
my_try?
```
* [#8055](https://github.com/leanprover/lean4/pull/8055) adds an implementation of an async IO multiplexing framework as
well as an implementation of it for the `Timer` API in order to
demonstrate it.
* [#8088](https://github.com/leanprover/lean4/pull/8088) adds the “unfolding” variant of the functional induction and
functional cases principles, under the name `foo.induct_unfolding` resp.
`foo.fun_cases_unfolding`. These theorems combine induction over the
structure of a recursive function with the unfolding of that function,
and should be more reliable, easier to use and more efficient than just
case-splitting and then rewriting with equational theorems.
For example instead of
```
ackermann.induct
(motive : Nat → Nat → Prop)
(case1 : ∀ (m : Nat), motive 0 m)
(case2 : ∀ (n : Nat), motive n 1 → motive (Nat.succ n) 0)
(case3 : ∀ (n m : Nat), motive (n + 1) m → motive n (ackermann (n + 1) m) → motive (Nat.succ n) (Nat.succ m))
(x x : Nat) : motive x x
```
one gets
```
ackermann.fun_cases_unfolding
(motive : Nat → Nat → Nat → Prop)
(case1 : ∀ (m : Nat), motive 0 m (m + 1))
(case2 : ∀ (n : Nat), motive n.succ 0 (ackermann n 1))
(case3 : ∀ (n m : Nat), motive n.succ m.succ (ackermann n (ackermann (n + 1) m)))
(x✝ x✝¹ : Nat) : motive x✝ x✝¹ (ackermann x✝ x✝¹)
```
* [#8097](https://github.com/leanprover/lean4/pull/8097) adds support for inductive and coinductive predicates defined
using lattice theoretic structures on `Prop`. These are syntactically
defined using `greatest_fixpoint` or `least_fixpoint` termination
clauses for recursive `Prop`-valued functions. The functionality relies
on `partial_fixpoint` machinery and requires function definitions to be
monotone. For non-mutually recursive predicates, an appropriate
(co)induction proof principle (given by Park induction) is generated.
### Library Highlights
[#8004](https://github.com/leanprover/lean4/pull/8004) adds extensional hash maps and hash sets under the names
`Std.ExtDHashMap`, `Std.ExtHashMap` and `Std.ExtHashSet`. Extensional
hash maps work like regular hash maps, except that they have
extensionality lemmas which make them easier to use in proofs. This
however makes it also impossible to regularly iterate over its entries.
Other notable library developments in this release include:
- Updates to the `Option` API,
- Async runtime developments: added support for multiplexing via UDP and TCP sockets, as well as channels,
- New `BitVec` definitions related to overflow handling,
- New lemmas for `Nat.lcm`, and `Int` variants for `Nat.gcd` and `Nat.lcm`,
- Upstreams from Mathlib related to `Nat` and `Int`,
- Additions to numeric types APIs, such as `UIntX.ofInt`, `Fin.ofNat'_mul` and `Fin.mul_ofNat'`, `Int.toNat_sub''`,
- Updates to `Perm` API in `Array`, `List`, and added support for `Vector`,
- Additional lemmas for `Array`/`List`/`Vector`.
### Lake
* [#7909](https://github.com/leanprover/lean4/pull/7909) adds Lake support for building modules given their source file
path. This is made use of in both the CLI and the server.
### Breaking Changes
* [#7474](https://github.com/leanprover/lean4/pull/7474) updates `rw?`, `show_term`, and other tactic-suggesting tactics
to suggest `expose_names` when necessary and validate tactics prior to
suggesting them, as `exact?` already did, and it also ensures all such
tactics produce hover info in the messages showing tactic suggestions.
This introduces a **breaking change** in the `TryThis` API: the `type?` parameter
of `addRewriteSuggestion` is now an `LOption`, not an `Option`, to obviate the need
for a hack we previously used to indicate that a rewrite closed the goal.
* [#7789](https://github.com/leanprover/lean4/pull/7789) fixes `lean` potentially changing or interpreting arguments
after `--run`.
**Breaking change**: The Lean file to run must now be passed directly
after `--run`, which accidentally was not enforced before.
* [#7813](https://github.com/leanprover/lean4/pull/7813) fixes an issue where `let n : Nat := sorry` in the Infoview
pretty prints as ``n : ℕ := sorry `«Foo:17:17»``. This was caused by
top-level expressions being pretty printed with the same rules as
Infoview hovers. Closes [#6715](https://github.com/leanprover/lean4/issues/6715). Refactors `Lean.Widget.ppExprTagged`; now
it takes a delaborator, and downstream users should configure their own
pretty printer option overrides if necessary if they used the `explicit`
argument (see `Lean.Widget.makePopup.ppExprForPopup` for an example).
**Breaking change:** `ppExprTagged` does not set `pp.proofs` on the root
expression.
* [#7855](https://github.com/leanprover/lean4/pull/7855) moves `ReflBEq` to `Init.Core` and changes `LawfulBEq` to extend
`ReflBEq`.
**Breaking changes:**
- The `refl` field of `ReflBEq` has been renamed to `rfl` to match
`LawfulBEq`
- `LawfulBEq` extends `ReflBEq`, so in particular `LawfulBEq.rfl` is no
longer valid
* [#7873](https://github.com/leanprover/lean4/pull/7873) fixes a number of bugs related to the handling of the source
search path in the language server, where deleting files could cause
several features to stop functioning and both untitled files and files
that don't exist on disc could have conflicting module names.
See the PR description for the details on changes in URI <-> module name conversion.
**Breaking changes:**
- `Server.documentUriFromModule` has been renamed to
`Server.documentUriFromModule?` and doesn't take a `SearchPath` argument
anymore, as the `SearchPath` is now computed from the `LEAN_SRC_PATH`
environment variable. It has also been moved from `Lean.Server.GoTo` to
`Lean.Server.Utils`.
- `Server.moduleFromDocumentUri` does not take a `SearchPath` argument
anymore and won't return an `Option` anymore. It has also been moved
from `Lean.Server.GoTo` to `Lean.Server.Utils`.
- The `System.SearchPath.searchModuleNameOfUri` function has been
removed. It is recommended to use `Server.moduleFromDocumentUri`
instead.
- The `initSrcSearchPath` function has been renamed to
`getSrcSearchPath` and has been moved from `Lean.Util.Paths` to
`Lean.Util.Path`. It also doesn't need to take a `pkgSearchPath`
argument anymore.
* [#7967](https://github.com/leanprover/lean4/pull/7967) adds a `bootstrap` option to Lake which is used to identify the
core Lean package. This enables Lake to use the current stage's include
directory rather than the Lean toolchains when compiling Lean with Lean
in core.
**Breaking change:** The Lean library directory is no longer part of
`getLeanLinkSharedFlags`. FFI users should provide this option
separately when linking to Lean (e.g.. via `s!"-L{(←getLeanLibDir).toString}"`).
See the FFI example for a demonstration.
## Language
* [#6325](https://github.com/leanprover/lean4/pull/6325) ensures that environments can be loaded, repeatedly, without
executing arbitrary code
* [#6432](https://github.com/leanprover/lean4/pull/6432) implements tactics called `extract_lets` and `lift_lets` that
manipulate `let`/`let_fun` expressions. The `extract_lets` tactic
creates new local declarations extracted from any `let` and `let_fun`
expressions in the main goal. For top-level lets in the target, it is
like the `intros` tactic, but in general it can extract lets from deeper
subexpressions as well. The `lift_lets` tactic moves `let` and `let_fun`
expressions as far out of an expression as possible, but it does not
extract any new local declarations. The option `extract_lets +lift`
combines these behaviors.
* [#7474](https://github.com/leanprover/lean4/pull/7474) updates `rw?`, `show_term`, and other tactic-suggesting tactics
to suggest `expose_names` when necessary and validate tactics prior to
suggesting them, as `exact?` already did, and it also ensures all such
tactics produce hover info in the messages showing tactic suggestions.
* [#7797](https://github.com/leanprover/lean4/pull/7797) adds a monolithic `CommRing` class, for internal use by `grind`,
and includes instances for `Int`/`BitVec`/`IntX`/`UIntX`.
* [#7803](https://github.com/leanprover/lean4/pull/7803) adds normalization rules for function composition to `grind`.
* [#7806](https://github.com/leanprover/lean4/pull/7806) modifies the syntaxes of the `ext`, `intro` and `enter` conv
tactics to accept `_`. The introduced binder is an inaccessible name.
* [#7808](https://github.com/leanprover/lean4/pull/7808) adds missing forall normalization rules to `grind`.
* [#7816](https://github.com/leanprover/lean4/pull/7816) fixes an issue where `x.f.g` wouldn't work but `(x.f).g` would
when `x.f` is generalized field notation. The problem was that `x.f.g`
would assume `x : T` should be the first explicit argument to `T.f`. Now
it uses consistent argument insertion rules. Closes #6400.
* [#7825](https://github.com/leanprover/lean4/pull/7825) improves support for `Nat` in the `cutsat` procedure used in
`grind`:
- `cutsat` no longer *pollutes* the local context with facts of the form
`-1 * NatCast.natCast x <= 0` for each `x : Nat`. These facts are now
stored internally in the `cutsat` state.
- A single context is now used for all `Nat` terms.
* [#7829](https://github.com/leanprover/lean4/pull/7829) fixes an issue in the cutsat counterexamples. It removes the
optimization (`Cutsat.State.terms`) that was used to avoid the new
theorem `eq_def`. In the two new tests, prior to this PR, `cutsat`
produced a bogus counterexample with `b := 2`.
* [#7830](https://github.com/leanprover/lean4/pull/7830) modifies the syntax of `induction`, `cases`, and other tactics
that use `Lean.Parser.Tactic.inductionAlts`. If a case omits `=> ...`
then it is assumed to be `=> ?_`. Example:
```lean
example (p : Nat × Nat) : p.1 = p.1 := by
cases p with | _ p1 p2
/-
case mk
p1 p2 : Nat
⊢ (p1, p2).fst = (p1, p2).fst
-/
```
This works with multiple cases as well. Example:
```lean
example (n : Nat) : n + 1 = 1 + n := by
induction n with | zero | succ n ih
/-
case zero
⊢ 0 + 1 = 1 + 0
case succ
n : Nat
ih : n + 1 = 1 + n
⊢ n + 1 + 1 = 1 + (n + 1)
-/
```
The `induction n with | zero | succ n ih` is short for `induction n with
| zero | succ n ih => ?_`, which is short for `induction n with | zero
=> ?_ | succ n ih => ?_`. Note that a consequence of parsing is that
only the last alternative can omit `=>`. Any `=>`-free alternatives
before an alternative with `=>` will be a part of that alternative.
* [#7831](https://github.com/leanprover/lean4/pull/7831) adds extensibility to the `evalAndSuggest` procedure used to
implement `try?`. Users can now implement their own handlers for any
tactic. The new test demonstrates how this feature works.
* [#7859](https://github.com/leanprover/lean4/pull/7859) allows the LRAT parser to accept any proof that derives the
empty clause at somepoint, not necessarily in the last line. Some tools
like lrat-trim occasionally include deletions after the derivation of
the empty clause but the proof is sound as long as it soundly derives
the empty clause somewhere.
* [#7861](https://github.com/leanprover/lean4/pull/7861) fixes an issue that prevented theorems from being activated in
`grind`.
* [#7862](https://github.com/leanprover/lean4/pull/7862) improves the normalization of `Bool` terms in `grind`. Recall
that `grind` currently does not case split on Boolean terms to reduce
the size of the search space.
* [#7864](https://github.com/leanprover/lean4/pull/7864) adds support to `grind` for case splitting on implications of
the form `p -> q` and `(h : p) -> q h`. See the new option `(splitImp :=
true)`.
* [#7865](https://github.com/leanprover/lean4/pull/7865) adds a missing propagation rule for implication in `grind`. It
also avoids unnecessary case-splits on implications.
* [#7870](https://github.com/leanprover/lean4/pull/7870) adds a mixin type class for `Lean.Grind.CommRing` recording the
characteristic of the ring, and constructs instances for `Int`, `IntX`,
`UIntX`, and `BitVec`.
* [#7885](https://github.com/leanprover/lean4/pull/7885) fixes the counterexamples produced by the cutsat procedure in
`grind` for examples containing `Nat` terms.
* [#7892](https://github.com/leanprover/lean4/pull/7892) improves the support for `funext` in `grind`. We will push
another PR to minimize the number of case-splits later.
* [#7902](https://github.com/leanprover/lean4/pull/7902) introduces a dedicated option for checking whether elaborators
are running in the language server.
* [#7905](https://github.com/leanprover/lean4/pull/7905) fixes an issue introduced by bug #6125 where an `inductive` or
`structure` with an autoimplicit parameter with a type that has a
metavariable would lead to a panic. Closes #7788.
* [#7907](https://github.com/leanprover/lean4/pull/7907) fixes two bugs in `grind`.
1. Model-based theory combination was creating type-incorrect terms.
2. `Nat.cast` vs `NatCast.natCast` issue during normalization.
* [#7914](https://github.com/leanprover/lean4/pull/7914) adds a function hook `PersistentEnvExtension.saveEntriesFn` that
can be used to store server-only metadata such as position information
and docstrings that should not affect (re)builds.
* [#7920](https://github.com/leanprover/lean4/pull/7920) introduces a fast path based on comparing the (cached) hash
value to the `DecidableEq` instance of the core expression data type in
`bv_decide`'s bitblaster.
* [#7926](https://github.com/leanprover/lean4/pull/7926) fixes two issues that were preventing `grind` from solving
`getElem?_eq_some_iff`.
1. Missing propagation rule for `Exists p = False`
2. Missing conditions at `isCongrToPrevSplit` a filter for discarding
unnecessary case-splits.
* [#7937](https://github.com/leanprover/lean4/pull/7937) implements a lookahead feature to reduce the size of the search
space in `grind`. It is currently effective only for arithmetic atoms.
* [#7949](https://github.com/leanprover/lean4/pull/7949) adds the attribute `[grind ext]`. It is used to select which
`[ext]` theorems should be used by `grind`. The option `grind +extAll`
instructs `grind` to use all `[ext]` theorems available in the
environment.
After updating stage0, we need to add the builtin `[grind ext]`
annotations to key theorems such as `funext`.
* [#7950](https://github.com/leanprover/lean4/pull/7950) modifies `all_goals` so that in recovery mode it commits changes
to the state only for those goals for which the tactic succeeds (while
preserving the new message log state). Before, we were trusting that
failing tactics left things in a reasonable state, but now we roll back
and admit the goal. The changes also fix a bug where we were rolling
back only the metacontext state and not the tactic state, leading to an
inconsistent state (a goal list with metavariables not in the
metacontext). Closes #7883
* [#7952](https://github.com/leanprover/lean4/pull/7952) makes two improvements to the local context when there are
autobound implicits in `variable`s. First, the local context no longer
has two copies of every variable (the local context is rebuilt if the
types of autobound implicits have metavariables). Second, these
metavariables get names using the same algorithm used by binders that
appear in declarations (with `mkForallFVars'` instead of
`mkForallFVars`).
* [#7957](https://github.com/leanprover/lean4/pull/7957) ensures that `mkAppM` can be used to construct terms that are
only type-correct at default transparency, even if we are in
`withReducible` (e.g. in `simp`), so that `simp` does not stumble over
simplifying `let` expression with simplifiable type.reliable.
* [#7961](https://github.com/leanprover/lean4/pull/7961) fixes a bug in `bv_decide` where if it was presented with a match
on an enum with as many arms as constructors but the last arm being a
default match it would (wrongly) give up on the match.
* [#7975](https://github.com/leanprover/lean4/pull/7975) reduces the priority of the parent projections of
`Lean.Grind.CommRing`, to avoid these being used in type class inference
in Mathlib.
* [#7976](https://github.com/leanprover/lean4/pull/7976) ensure that `bv_decide` can handle the simp normal form of a
shift.
* [#7978](https://github.com/leanprover/lean4/pull/7978) adds a repro for a non-determinism problem in `grind`.
* [#7980](https://github.com/leanprover/lean4/pull/7980) adds a simple type for representing monomials in a `CommRing`.
This is going to be used in `grind`.
* [#7986](https://github.com/leanprover/lean4/pull/7986) implements reverse lexicographical and graded reverse
lexicographical orders for `CommRing` monomials.
* [#7989](https://github.com/leanprover/lean4/pull/7989) adds functions and theorems for `CommRing` multivariate
polynomials.
* [#7992](https://github.com/leanprover/lean4/pull/7992) add a function for converting `CommRing` expressions into
multivariate polynomials.
* [#7997](https://github.com/leanprover/lean4/pull/7997) removes all type annotations (optional parameters, auto
parameters, out params, semi-out params, not just optional parameters as
before) from the type of functional induction principles.
* [#8011](https://github.com/leanprover/lean4/pull/8011) adds `IsCharP` support to the multivariate‑polynomial library in
`CommRing`.
* [#8012](https://github.com/leanprover/lean4/pull/8012) adds the option `debug.terminalTacticsAsSorry`. When enabled,
terminal tactics such as `grind` and `omega` are replaced with `sorry`.
Useful for debugging and fixing bootstrapping issues.
* [#8014](https://github.com/leanprover/lean4/pull/8014) makes `RArray` universe polymorphic.
* [#8016](https://github.com/leanprover/lean4/pull/8016) fixes several issues in the `CommRing` multivariate polynomial
library:
1. Replaces the previous array type with the universe polymorphic
`RArray`.
2. Properly eliminates cancelled monomials.
3. Sorts monomials in decreasing order.
4. Marks the parameter `p` of the `IsCharP` class as an output
parameter.
5. Adds `LawfulBEq` instances for the types `Power`, `Mon`, and `Poly`.
* [#8025](https://github.com/leanprover/lean4/pull/8025) simplifies the `CommRing` monomials, and adds
1. Monomial `lcm`
2. Monomial division
3. S-polynomials
* [#8029](https://github.com/leanprover/lean4/pull/8029) implements basic support for `CommRing` in `grind`. Terms are
already being reified and normalized. We still need to process the
equations, but `grind` can already prove simple examples such as:
```lean
open Lean.Grind in
example [CommRing α] (x : α) : (x + 1)*(x - 1) = x^2 - 1 := by
grind +ring
* [#8032](https://github.com/leanprover/lean4/pull/8032) adds support to `grind` for detecting unsatisfiable commutative
ring equations when the ring characteristic is known. Examples:
```lean
example (x : Int) : (x + 1)*(x - 1) = x^2 → False := by
grind +ring
* [#8033](https://github.com/leanprover/lean4/pull/8033) adds functions for converting `CommRing` reified terms back into
Lean expressions.
* [#8036](https://github.com/leanprover/lean4/pull/8036) fixes a linearity issue in `bv_decide`'s bitblaster, caused by
the fact that the higher order combinators `AIG.RefVec.zip` and
`AIG.RefVec.fold` were not being properly specialised.
* [#8042](https://github.com/leanprover/lean4/pull/8042) makes `IntCast` a field of `Lean.Grind.CommRing`, along with
additional axioms relating it to negation of `OfNat`. This allows use to
use existing instances which are not definitionally equal to the
previously given construction.
* [#8043](https://github.com/leanprover/lean4/pull/8043) adds `NullCert` type for representing Nullstellensatz
certificates that will be produced by the new commutative ring procedure
in `grind`.
* [#8050](https://github.com/leanprover/lean4/pull/8050) fixes missing trace messages when produced inside `realizeConst`
* [#8055](https://github.com/leanprover/lean4/pull/8055) adds an implementation of an async IO multiplexing framework as
well as an implementation of it for the `Timer` API in order to
demonstrate it.
* [#8064](https://github.com/leanprover/lean4/pull/8064) adds a failing `grind` test, showing a bug where grind is trying
to assign a metavariable incorrectly.
* [#8065](https://github.com/leanprover/lean4/pull/8065) adds a (failing) test case for an obstacle I've been running
into setting up `grind` for `HashMap`.
* [#8068](https://github.com/leanprover/lean4/pull/8068) ensures that for modules opted into the experimental module
system, we do not import module docstrings or declaration ranges.
* [#8076](https://github.com/leanprover/lean4/pull/8076) fixes `simp?!`, `simp_all?!` and `dsimp?!` to do auto-unfolding.
* [#8077](https://github.com/leanprover/lean4/pull/8077) adds simprocs to simplify appends of non-overlapping Bitvector
adds. We add a simproc instead of just a `simp` lemma to ensure that we
correctly rewrite bitvector appends. Since bitvector appends lead to
computation at the bitvector width level, it seems to be more stable to
write a simproc.
* [#8083](https://github.com/leanprover/lean4/pull/8083) fixes #8081.
* [#8086](https://github.com/leanprover/lean4/pull/8086) makes sure that the functional induction principles for mutually
recursive structural functions with extra parameters are split deeply,
as expected.
* [#8088](https://github.com/leanprover/lean4/pull/8088) adds the “unfolding” variant of the functional induction and
functional cases principles, under the name `foo.induct_unfolding` resp.
`foo.fun_cases_unfolding`. These theorems combine induction over the
structure of a recursive function with the unfolding of that function,
and should be more reliable, easier to use and more efficient than just
case-splitting and then rewriting with equational theorems.
* [#8090](https://github.com/leanprover/lean4/pull/8090) adjusts the experimental module system to elide theorem bodies
(i.e. proofs) from being imported into other modules.
* [#8094](https://github.com/leanprover/lean4/pull/8094) fixes the generation of functional induction principles for
functions with nested nested well-founded recursion and late fixed
parameters. This is a follow-up for #7166. Fixes #8093.
* [#8096](https://github.com/leanprover/lean4/pull/8096) lets `induction` accept eliminator where the motive application
in the conclusion has complex arguments; these are abstracted over using
`kabstract` if possible. This feature will go well with unfolding
induction principles (#8088).
* [#8097](https://github.com/leanprover/lean4/pull/8097) adds support for inductive and coinductive predicates defined
using lattice theoretic structures on `Prop`. These are syntactically
defined using `greatest_fixpoint` or `least_fixpoint` termination
clauses for recursive `Prop`-valued functions. The functionality relies
on `partial_fixpoint` machinery and requires function definitions to be
monotone. For non-mutually recursive predicates, an appropriate
(co)induction proof principle (given by Park induction) is generated.
* [#8101](https://github.com/leanprover/lean4/pull/8101) fixes a parallelism regression where linters that e.g. check for
errors in the command would no longer find such messages.
* [#8102](https://github.com/leanprover/lean4/pull/8102) allows ASCII `<-` in `if let` clauses, for consistency with
bind, where both are allowed. Fixes #8098.
* [#8111](https://github.com/leanprover/lean4/pull/8111) adds the helper type class `NoZeroNatDivisors` for the
commutative ring procedure in `grind`. Core only implements it for
`Int`. It can be instantiated in Mathlib for any type `A` that
implements `NoZeroSMulDivisors Nat A`.
See `findSimp?` and `PolyDerivation` for details on how this instance
impacts the commutative ring procedure.
* [#8122](https://github.com/leanprover/lean4/pull/8122) implements the generation of compact proof terms for
Nullstellensatz certificates in the new commutative ring procedure in
`grind`. Some examples:
```lean
example [CommRing α] (x y : α) : x = 1 → y = 2 → 2*x + y = 4 := by
grind +ring
* [#8126](https://github.com/leanprover/lean4/pull/8126) implements the main loop of the new commutative ring procedure
in `grind`. In the main loop, for each polynomial `p` in the todo queue,
the procedure:
- Simplifies it using the current basis.
- Computes critical pairs with polynomials already in the basis and adds
them to the queue.
* [#8128](https://github.com/leanprover/lean4/pull/8128) implements equality propagation in the new commutative ring
procedure in `grind`. The idea is to propagate implied equalities back
to the `grind` core module that does congruence closure. In the
following example, the equalities: `x^2*y = 1` and `x*y^2 - y = 0` imply
that `y*x` is equal to `y*x*y`, which implies by congruence that `f
(y*x) = f (y*x*y)`.
```lean
example [CommRing α] (x y : α) (f : α → Nat) : x^2*y = 1 → x*y^2 - y = 0 → f (y*x) = f (y*x*y) := by
grind +ring
```
* [#8129](https://github.com/leanprover/lean4/pull/8129) updates the If-Normalization example, to separately give an
implementation and subsequently prove the spec (using fun_induction),
instead of previously building a term in the subtype directly. At the
same time, adds a (failing) `grind` test case illustrating a problem
with unused match witnesses.
* [#8131](https://github.com/leanprover/lean4/pull/8131) adds a configuration option that controls the maximum number of
steps the commutative-ring procedure in `grind` performs.
* [#8133](https://github.com/leanprover/lean4/pull/8133) fixes the monomial order used by the commutative ring procedure
in `grind`. The following new test now terminates quickly.
```lean
example [CommRing α] (a b c : α)
: a + b + c = 3 →
a^2 + b^2 + c^2 = 5 →
a^3 + b^3 + c^3 = 7 →
a^4 + b^4 + c^4 = 9 := by
grind +ring
```
* [#8134](https://github.com/leanprover/lean4/pull/8134) ensures that `set_option grind.debug true` works properly when
using `grind +ring`. It also adds the helper functions `mkPropEq` and
`mkExpectedPropHint`.
* [#8137](https://github.com/leanprover/lean4/pull/8137) improves equality propagation (also known as theory combination)
and polynomial simplification for rings that do not implement the
`NoZeroNatDivisors` class. With these fixes, `grind` can now solve:
```lean
example [CommRing α] (a b c : α) (f : α → Nat)
: a + b + c = 3 →
a^2 + b^2 + c^2 = 5 →
a^3 + b^3 + c^3 = 7 →
f (a^4 + b^4) + f (9 - c^4) ≠ 1 := by
grind +ring
```
This example uses the commutative ring procedure, the linear integer
arithmetic solver, and congruence closure.
For rings that implement `NoZeroNatDivisors`, a polynomial is now also
divided by the greatest common divisor (gcd) of its coefficients when it
is inserted into the basis.
* [#8157](https://github.com/leanprover/lean4/pull/8157) fixes an incompatibility of `replayConst` as used by e.g.
`aesop` with `native_decide`-using tactics such as `bv_decide`
* [#8158](https://github.com/leanprover/lean4/pull/8158) fixes the `grind +splitImp` and the arrow propagator. Given `p :
Prop`, the propagator was incorrectly assuming `A` was always a
proposition in an arrow `A -> p`. also adds a missing
normalization rule to `grind`.
* [#8159](https://github.com/leanprover/lean4/pull/8159) adds support for the following import variants to the
experimental module system:
* `private import`: Makes the imported constants available only in
non-exported contexts such as proofs. In particular, the import will not
be loaded, or required to exist at all, when the current module is
imported into other modules.
* `import all`: Makes non-exported information such as proofs of the
imported module available in non-exported contexts in the current
module. Main purpose is to allow for reasoning about imported
definitions when they would otherwise be opaque. TODO: adjust name
resolution so that imported `private` decls are accessible through
syntax.
* [#8161](https://github.com/leanprover/lean4/pull/8161) changes `Lean.Grind.CommRing` to inline the `NatCast` instance
(i.e. to be provided by the user) rather than constructing one from the
existing data. Without this change we can't construct instances in
Mathlib that `grind` can use.
* [#8163](https://github.com/leanprover/lean4/pull/8163) adds some currently failing tests for `grind +ring`, resulting
in either kernel type mismatches (bugs) or a kernel deep recursion
(perhaps just a too-large problem).
* [#8167](https://github.com/leanprover/lean4/pull/8167) improves the heuristics used to compute the basis and simplify
polynomials in the commutative procedure used in `grind`.
* [#8168](https://github.com/leanprover/lean4/pull/8168) fixes a bug when constructing the proof term for a
Nullstellensatz certificate produced by the new commutative ring
procedure in `grind`. The kernel was rejecting the proof term.
* [#8170](https://github.com/leanprover/lean4/pull/8170) adds the infrastructure for creating stepwise proof terms in the
commutative procedure used in `grind`.
* [#8189](https://github.com/leanprover/lean4/pull/8189) implements **stepwise proof terms** in the commutative ring
procedure used by `grind`. These terms serve as an alternative
representation to the traditional Nullstellensatz certificates, aiming
to address the **exponential worst-case complexity** often associated
with certificate construction.
* [#8231](https://github.com/leanprover/lean4/pull/8231) changes the behaviour of `apply?` so that the `sorry` it uses to
close the goal is non-synthetic. (Recall that correct use of synthetic
sorries requires that the tactic also generates an error message, which
we don't want to do in this situation.) Either this PR or #8230 are
sufficient to defend against the problem reported in #8212.
* [#8254](https://github.com/leanprover/lean4/pull/8254) fixes unintended inlining of `ToJson`, `FromJson`, and `Repr`
instances, which was causing exponential compilation times in `deriving`
clauses for large structures.
## Library
* [#6081](https://github.com/leanprover/lean4/pull/6081) adds an `inheritEnv` field to `IO.Process.SpawnArgs`. If
`false`, the spawned process does not inherit its parent's environment.
* [#7108](https://github.com/leanprover/lean4/pull/7108) proves `List.head_of_mem_head?` and the analogous
`List.getLast_of_mem_getLast?`.
* [#7400](https://github.com/leanprover/lean4/pull/7400) adds lemmas for the `filter`, `map` and `filterMap` functions of
the hash map.
* [#7659](https://github.com/leanprover/lean4/pull/7659) adds SMT-LIB operators to detect overflow
`BitVec.(umul_overflow, smul_overflow)`, according to the definitions
[here](https://github.com/SMT-LIB/SMT-LIB-2/blob/2.7/Theories/FixedSizeBitVectors.smt2),
and the theorems proving equivalence of such definitions with the
`BitVec` library functions (`umulOverflow_eq`, `smulOverflow_eq`).
Support theorems for these proofs are `BitVec.toInt_one_of_lt,
BitVec.toInt_mul_toInt_lt, BitVec.le_toInt_mul_toInt,
BitVec.toNat_mul_toNat_lt, BitVec.two_pow_le_toInt_mul_toInt_iff,
BitVec.toInt_mul_toInt_lt_neg_two_pow_iff` and `Int.neg_mul_le_mul,
Int.bmod_eq_self_of_le_mul_two, Int.mul_le_mul_of_natAbs_le,
Int.mul_le_mul_of_le_of_le_of_nonneg_of_nonpos, Int.pow_lt_pow`. The PR
also includes a set of tests.
* [#7671](https://github.com/leanprover/lean4/pull/7671) contains the theorem proving that signed division x.toInt /
y.toInt only overflows when `x = intMin w` and `y = allOnes w` (for `0 <
w`).
To show that this is the *only* case in which overflow happens, we refer
to overflow for negation
(`BitVec.sdivOverflow_eq_negOverflow_of_neg_one`): in fact,
`x.toInt/(allOnes w).toInt = - x.toInt`, i.e., the overflow conditions
are the same as `negOverflow` for `x`, and then reason about the signs
of the operands with the respective theorems.
These BitVec theorems themselves rely on numerous `Int.ediv_*` theorems,
that carefully set the bounds of signed division for integers.
* [#7761](https://github.com/leanprover/lean4/pull/7761) implements the core theorem for the Bitwuzla rewrites
[NORM_BV_NOT_OR_SHL](https://github.com/bitwuzla/bitwuzla/blob/e09c50818b798f990bd84bf61174553fef46d561/src/rewrite/rewrites_bv.cpp#L1495-L1510)
and
[BV_ADD_SHL](https://github.com/bitwuzla/bitwuzla/blob/e09c50818b798f990bd84bf61174553fef46d561/src/rewrite/rewrites_bv.cpp#L395-L401),
which convert the mixed-boolean-arithmetic expression into a purely
arithmetic expression:
```lean
theorem add_shiftLeft_eq_or_shiftLeft {x y : BitVec w} :
x + (y <<< x) = x ||| (y <<< x)
```
* [#7770](https://github.com/leanprover/lean4/pull/7770) adds a shared mutex (or read-write lock) as `Std.SharedMutex`.
* [#7774](https://github.com/leanprover/lean4/pull/7774) adds `Option.pfilter`, a variant of `Option.filter` and several
lemmas for it and other `Option` functions. These lemmas are split off
from #7400.
* [#7791](https://github.com/leanprover/lean4/pull/7791) adds lemmas about `Nat.lcm`.
* [#7802](https://github.com/leanprover/lean4/pull/7802) adds `Int.gcd` and `Int.lcm` variants of all `Nat.gcd` and
`Nat.lcm` lemmas.
* [#7818](https://github.com/leanprover/lean4/pull/7818) deprecates `Option.merge` and `Option.liftOrGet` in favor of
`Option.zipWith`.
* [#7819](https://github.com/leanprover/lean4/pull/7819) extends `Std.Channel` to provide a full sync and async API, as
well as unbounded, zero sized and bounded channels.
* [#7835](https://github.com/leanprover/lean4/pull/7835) adds `BitVec.[toInt_append|toFin_append]`.
* [#7847](https://github.com/leanprover/lean4/pull/7847) removes `@[simp]` from all deprecated theorems. `simp` will
still use such lemmas, without any warning message.
* [#7851](https://github.com/leanprover/lean4/pull/7851) partially reverts #7818, because the function called
`Option.zipWith` in that PR does not actually correspond to
`List.zipWith`. We choose `Option.merge` as the name instead.
* [#7855](https://github.com/leanprover/lean4/pull/7855) moves `ReflBEq` to `Init.Core` and changes `LawfulBEq` to extend
`ReflBEq`.
* [#7856](https://github.com/leanprover/lean4/pull/7856) changes definitions and theorems not to use the membership
instance on `Option` unless the theorem is specifically about the
membership instance.
* [#7869](https://github.com/leanprover/lean4/pull/7869) fixes a regression introduced in #7445 where the new
`Array.emptyWithCapacity` was accidentally not tagged with the correct
function to actually allocate the capacity.
* [#7871](https://github.com/leanprover/lean4/pull/7871) generalizes the type class assumptions on monadic `Option`
functions.
* [#7879](https://github.com/leanprover/lean4/pull/7879) adds `Int.toNat_emod`, analogous to `Int.toNat_add/mul`.
* [#7880](https://github.com/leanprover/lean4/pull/7880) adds the functions `UIntX.ofInt`, and basic lemmas.
* [#7886](https://github.com/leanprover/lean4/pull/7886) adds `UIntX.pow` and `Pow UIntX Nat` instances, and similarly
for signed fixed-width integers. These are currently only the naive
implementation, and will need to be subsequently replaced via
`@[extern]` with fast implementations (tracked at #7887).
* [#7888](https://github.com/leanprover/lean4/pull/7888) adds `Fin.ofNat'_mul` and `Fin.mul_ofNat'`, parallel to the
existing lemmas about `add`.
* [#7889](https://github.com/leanprover/lean4/pull/7889) adds `Int.toNat_sub''` a variant of `Int.toNat_sub` taking
inequality hypotheses, rather than expecting the arguments to be casts
of natural numbers. This is parallel to the existing `toNat_add` and
`toNat_mul`.
* [#7890](https://github.com/leanprover/lean4/pull/7890) adds missing lemmas about `Int.bmod`, parallel to lemmas about
the other `mod` variants.
* [#7891](https://github.com/leanprover/lean4/pull/7891) adds the rfl simp lemma `Int.cast x = x` for `x : Int`.
* [#7893](https://github.com/leanprover/lean4/pull/7893) adds `BitVec.pow` and `Pow (BitVec w) Nat`. The implementation
is the naive one, and should later be replaced by an `@[extern]`. This
is tracked at https://github.com/leanprover/lean4/issues/7887.
* [#7897](https://github.com/leanprover/lean4/pull/7897) cleans up the `Option` development, upstreaming some results
from mathlib in the process.
* [#7899](https://github.com/leanprover/lean4/pull/7899) shuffles some results about integers around to make sure that
all material that currently exists about `Int.bmod` is located in
`DivMod/Lemmas.lean` and not downstream of that.
* [#7901](https://github.com/leanprover/lean4/pull/7901) adds `instance [Pure f] : Inhabited (OptionT f α)`, so that
`Inhabited (OptionT Id Empty)` synthesizes.
* [#7912](https://github.com/leanprover/lean4/pull/7912) adds `List.Perm.take/drop`, and `Array.Perm.extract`,
restricting permutations to sublist / subarrays when they are constant
elsewhere.
* [#7913](https://github.com/leanprover/lean4/pull/7913) adds some missing `List/Array/Vector lemmas` about
`isSome_idxOf?`, `isSome_finIdxOf?`, `isSome_findFinIdx?,
`isSome_findIdx?` and the corresponding `isNone` versions.
* [#7933](https://github.com/leanprover/lean4/pull/7933) adds lemmas about `Int.bmod` to achieve parity between
`Int.bmod` and `Int.emod`/`Int.fmod`/`Int.tmod`. Furthermore, it adds
missing lemmas for `emod`/`fmod`/`tmod` and performs cleanup on names
and statements for all four operations, also with a view towards
increasing consistency with the corresponding `Nat.mod` lemmas.
* [#7938](https://github.com/leanprover/lean4/pull/7938) adds lemmas about `List/Array/Vector.countP/count` interacting
with `replace`. (Specializing to `_self` and `_ne` lemmas doesn't seem
useful, as there will still be an `if` on the RHS.)
* [#7939](https://github.com/leanprover/lean4/pull/7939) adds `Array.count_erase` and specializations.
* [#7953](https://github.com/leanprover/lean4/pull/7953) generalizes some type class hypotheses in the `List.Perm` API
(away from `DecidableEq`), and reproduces `List.Perm.mem_iff` for
`Array`, and fixes a mistake in the statement of `Array.Perm.extract`.
* [#7971](https://github.com/leanprover/lean4/pull/7971) upstreams much of the material from `Mathlib/Data/Nat/Init.lean`
and `Mathlib/Data/Nat/Basic.lean`.
* [#7983](https://github.com/leanprover/lean4/pull/7983) upstreams many of the results from `Mathlib/Data/Int/Init.lean`.
* [#7994](https://github.com/leanprover/lean4/pull/7994) reproduces the `Array.Perm` API for `Vector`. Both are still
significantly less developed than the API for `List.Perm`.
* [#7999](https://github.com/leanprover/lean4/pull/7999) replaces `Array.Perm` and `Vector.Perm` with one-field
structures. This avoids dot notation for `List` to work like e.g.
`h.cons 3` where `h` is an `Array.Perm`.
* [#8000](https://github.com/leanprover/lean4/pull/8000) deprecates some `Int.ofNat_*` lemmas in favor of
`Int.natCast_*`.
* [#8004](https://github.com/leanprover/lean4/pull/8004) adds extensional hash maps and hash sets under the names
`Std.ExtDHashMap`, `Std.ExtHashMap` and `Std.ExtHashSet`. Extensional
hash maps work like regular hash maps, except that they have
extensionality lemmas which make them easier to use in proofs. This
however makes it also impossible to regularly iterate over its entries.
* [#8030](https://github.com/leanprover/lean4/pull/8030) adds some missing lemmas about
`List/Array/Vector.findIdx?/findFinIdx?/findSome?/idxOf?`.
* [#8044](https://github.com/leanprover/lean4/pull/8044) introduces the modules `Std.Data.DTreeMap.Raw`,
`Std.Data.TreeMap.Raw` and `Std.Data.TreeSet.Raw` and imports them into
`Std.Data`. All modules related to the raw tree maps are imported into
these new modules so that they are now a transitive dependency of `Std`.
* [#8067](https://github.com/leanprover/lean4/pull/8067) fixes the behavior of `Substring.isNat` to disallow empty
strings.
* [#8078](https://github.com/leanprover/lean4/pull/8078) is a follow up to #8055 and implements a `Selector` for async
TCP in order to allow IO multiplexing using TCP sockets.
* [#8080](https://github.com/leanprover/lean4/pull/8080) fixes `Json.parse` to handle surrogate pairs correctly.
* [#8085](https://github.com/leanprover/lean4/pull/8085) moves the coercion `α → Option α` to the new file
`Init.Data.Option.Coe`. This file may not be imported anywhere in `Init`
or `Std`.
* [#8089](https://github.com/leanprover/lean4/pull/8089) adds optimized division functions for `Int` and `Nat` when the
arguments are known to be divisible (such as when normalizing
rationals). These are backed by the gmp functions `mpz_divexact` and
`mpz_divexact_ui`. See also leanprover-community/batteries#1202.
* [#8136](https://github.com/leanprover/lean4/pull/8136) adds an initial set of `@[grind]` annotations for
`List`/`Array`/`Vector`, enough to set up some regression tests using
`grind` in proofs about `List`. More annotations to follow.
* [#8139](https://github.com/leanprover/lean4/pull/8139) is a follow up to #8055 and implements a `Selector` for async
UDP in order to allow IO multiplexing using UDP sockets.
* [#8144](https://github.com/leanprover/lean4/pull/8144) changes the predicate for `Option.guard` to be `p : α → Bool`
instead of `p : α → Prop`. This brings it in line with other comparable
functions like `Option.filter`.
* [#8147](https://github.com/leanprover/lean4/pull/8147) adds `List.findRev?` and `List.findSomeRev?`, for parity with
the existing Array API, and simp lemmas converting these into existing
operations.
* [#8148](https://github.com/leanprover/lean4/pull/8148) generalises `List.eraseDups` to allow for an arbitrary
comparison relation. Further, it proves `eraseDups_append : (as ++
bs).eraseDups = as.eraseDups ++ (bs.removeAll as).eraseDups`.
* [#8150](https://github.com/leanprover/lean4/pull/8150) is a follow up to #8055 and implements a Selector for
`Std.Channel` in order to allow
multiplexing using channels.
* [#8154](https://github.com/leanprover/lean4/pull/8154) adds unconditional lemmas for
`HashMap.getElem?_insertMany_list`, alongside the existing ones that
have quite strong preconditions. Also for TreeMap (and
dependent/extensional variants).
* [#8175](https://github.com/leanprover/lean4/pull/8175) adds simp/grind lemmas about `List`/`Array`/`Vector.contains`.
In the presence of `LawfulBEq` these effectively already held, via
simplifying `contains` to `mem`, but now these also fire without
`LawfulBEq`.
* [#8184](https://github.com/leanprover/lean4/pull/8184) adds the `insertMany_append` lemma for all map variants.
## Compiler
* [#6063](https://github.com/leanprover/lean4/pull/6063) updates the version of LLVM and clang used by and shipped with
Lean to 19.1.2
* [#7824](https://github.com/leanprover/lean4/pull/7824) fixes an issue where uses of 'noncomputable' definitions can get
incorrectly compiled, while also removing the use of 'noncomputable'
definitions altogether. Some uses of 'noncomputable' definitions (e.g.
Classical.propDecidable) do not get compiled correctly by type erasure.
Running the optimizer on the result can lead to them being optimized
away, eluding the later IR-level check for uses of noncomputable
definitions.
* [#7838](https://github.com/leanprover/lean4/pull/7838) adds support for mpz objects (i.e., big nums) to the
`shareCommon` functions.
* [#7854](https://github.com/leanprover/lean4/pull/7854) introduces fundamental API to distribute module data across
multiple files in preparation for the module system.
* [#7945](https://github.com/leanprover/lean4/pull/7945) fixes a potential race between `IO.getTaskState` and the task in
question finishing, resulting in undefined behavior.
* [#7958](https://github.com/leanprover/lean4/pull/7958) ensures that after `main` is finished we still wait on dedicated
tasks instead of exiting forcefully. If users wish to violently kill
their dedicated tasks at the end of main instead they can run
`IO.Process.exit` at the end of `main` instead.
* [#7990](https://github.com/leanprover/lean4/pull/7990) adopts lcAny in more cases of type erasure in the new code
generator.
* [#7996](https://github.com/leanprover/lean4/pull/7996) disables CSE of local function declarations in the base phase of
the new compiler. This was introducing sharing between lambdas to bind
calls w/ `do` notation, which caused them to later no longer be inlined.
* [#8006](https://github.com/leanprover/lean4/pull/8006) changes the inlining heuristics of the new code generator to
match the old one, which ensures that monadic folds get sufficiently
inlined for their tail recursion to be exposed to the code generator.
* [#8007](https://github.com/leanprover/lean4/pull/8007) changes eager lambda lifting heuristics in the new compiler to
match the old compiler, which ensures that inlining/specializing monadic
code does not accidentally create mutual tail recursion that the code
generator can't handle.
* [#8008](https://github.com/leanprover/lean4/pull/8008) changes specialization in the new code generator to consider
callee params to be ground variables, which improves the specialization
of polymorphic functions.
* [#8009](https://github.com/leanprover/lean4/pull/8009) restricts lifting outside of cases expressions on values of a
Decidable type, since we can't correctly represent the dependency on the
erased proposition in the later stages of the compiler.
* [#8010](https://github.com/leanprover/lean4/pull/8010) fixes caseOn expressions with an implemented_by to work
correctly with hash consing, even when the elaborator produces terms
that reconstruct the discriminant rather than just reusing a variable.
* [#8015](https://github.com/leanprover/lean4/pull/8015) fixes the IR elim_dead_branches pass to correctly handle join
points with no params, which currently get considered unreachable. I was
not able to find an easy repro of this with the old compiler, but it
occurs when bootstrapping Lean with the new compiler.
* [#8017](https://github.com/leanprover/lean4/pull/8017) makes the IR elim_dead_branches pass correctly handle extern
functions by considering them as having a top return value. This fix is
required to bootstrap the Init/ directory with the new compiler.
* [#8023](https://github.com/leanprover/lean4/pull/8023) fixes the IR expand_reset_reuse pass to correctly handle
duplicate projections from the same base/index. This does not occur (at
least easily) with the old compiler, but it occurs when bootstrapping
Lean with the new compiler.
* [#8124](https://github.com/leanprover/lean4/pull/8124) correctly handles escaping functions in the LCNF
elimDeadBranches pass, by setting all params to top instead of
potentially leaving them at their default bottom value.
* [#8125](https://github.com/leanprover/lean4/pull/8125) adds support for the `init` attribute to the new compiler.
* [#8127](https://github.com/leanprover/lean4/pull/8127) adds support for borrowed params in the new compiler, which
requires adding support for .mdata expressions to LCNF type handling.
* [#8132](https://github.com/leanprover/lean4/pull/8132) adds support for lowering `casesOn` for builtin types in the new
compiler.
* [#8156](https://github.com/leanprover/lean4/pull/8156) fixes a bug where the old compiler's lcnf conversion expr cache
was not including all of the relevant information in the key, leading to
terms inadvertently being erased. The `root` variable is used to
determine whether lambda arguments to applications should get let
bindings or not, which in turn affects later decisions about type
erasure (erase_irrelevant assumes that any non-atomic argument is
irrelevant).
* [#8236](https://github.com/leanprover/lean4/pull/8236) fixes an issue where the combination of `extern_lib` and
`precompileModules` would lead to "symbol not found" errors.
## Pretty Printing
* [#7805](https://github.com/leanprover/lean4/pull/7805) modifies the pretty printing of raw natural number literals; now
both `pp.explicit` and `pp.natLit` enable the `nat_lit` prefix. An
effect of this is that the hover on such a literal in the Infoview has
the `nat_lit` prefix.
* [#7812](https://github.com/leanprover/lean4/pull/7812) modifies the pretty printing of pi types. Now `∀` will be
preferred over `→` for propositions if the domain is not a proposition.
For example, `∀ (n : Nat), True` pretty prints as `∀ (n : Nat), True`
rather than as `Nat → True`. There is also now an option `pp.foralls`
(default true) that when false disables using `∀` at all, for
pedagogical purposes. also adjusts instance implicit binder
pretty printing — nondependent pi types won't show the instance binder
name. Closes #1834.
* [#7813](https://github.com/leanprover/lean4/pull/7813) fixes an issue where `let n : Nat := sorry` in the Infoview
pretty prints as ``n : ℕ := sorry `«Foo:17:17»``. This was caused by
top-level expressions being pretty printed with the same rules as
Infoview hovers. Closes #6715. Refactors `Lean.Widget.ppExprTagged`; now
it takes a delaborator, and downstream users should configure their own
pretty printer option overrides if necessary if they used the `explicit`
argument (see `Lean.Widget.makePopup.ppExprForPopup` for an example).
Breaking change: `ppExprTagged` does not set `pp.proofs` on the root
expression.
* [#7840](https://github.com/leanprover/lean4/pull/7840) causes structure instance notation to be tagged with the
constructor when `pp.tagAppFns` is true. This will make docgen will have
`{` and `}` be links to the structure constructor.
* [#8022](https://github.com/leanprover/lean4/pull/8022) fixes a bug where pretty printing is done in a context with
cleared local instances. These were cleared since the local context is
updated during a name sanitization step, but preserving local instances
is valid since the modification to the local context only affects user
names.
## Documentation
* [#7947](https://github.com/leanprover/lean4/pull/7947) adds some docstrings to clarify the functions of
`Lean.mkFreshId`, `Lean.Core.mkFreshUserName`,
`Lean.Elab.Term.mkFreshBinderName`, and
`Lean.Meta.mkFreshBinderNameForTactic`.
* [#8018](https://github.com/leanprover/lean4/pull/8018) adjusts the RArray docstring to the new reality from #8014.
## Server
* [#7610](https://github.com/leanprover/lean4/pull/7610) adjusts the `TryThis` widget to also work in widget messages
rather than only as a panel widget. It also adds additional
documentation explaining why this change was needed.
* [#7873](https://github.com/leanprover/lean4/pull/7873) fixes a number of bugs related to the handling of the source
search path in the language server, where deleting files could cause
several features to stop functioning and both untitled files and files
that don't exist on disc could have conflicting module names.
* [#7882](https://github.com/leanprover/lean4/pull/7882) fixes a regression where elaboration of a previous document
version is not cancelled on changes to the document.
* [#8242](https://github.com/leanprover/lean4/pull/8242) fixes the 'goals accomplished' diagnostics. They were
accidentally broken in #7902.
## Lake
* [#7796](https://github.com/leanprover/lean4/pull/7796) moves Lean's shared library path before the workspace's in
Lake's augmented environment (e.g., `lake env`).
* [#7809](https://github.com/leanprover/lean4/pull/7809) fixes the order of libraries when loading them via
`--load-dynlib` or `--plugin` in `lean` and when linking them into a
shared library or executable. A `Dynlib` now tracks its dependencies and
they are topologically sorted before being passed to either linking or
loading.
* [#7822](https://github.com/leanprover/lean4/pull/7822) changes Lake to use normalized absolute paths for its various
files and directories.
* [#7860](https://github.com/leanprover/lean4/pull/7860) restores the use of builtins (e.g., initializer, elaborators,
and macros) for DSL features and the use of the Lake plugin in the
server.
* [#7906](https://github.com/leanprover/lean4/pull/7906) changes Lake build traces to track their mixed inputs. The
tracked inputs are saved as part of the `.trace` file, which can
significantly assist in debugging trace issues. In addition, this PR
tweaks some existing Lake traces. Most significant, module olean traces
no longer incorporate their module's source trace.
* [#7909](https://github.com/leanprover/lean4/pull/7909) adds Lake support for building modules given their source file
path. This is made use of in both the CLI and the sever.
* [#7963](https://github.com/leanprover/lean4/pull/7963) adds helper functions to convert between `Lake.EStateT` and
`EStateM`.
* [#7967](https://github.com/leanprover/lean4/pull/7967) adds a `bootstrap` option to Lake which is used to identify the
core Lean package. This enables Lake to use the current stage's include
directory rather than the Lean toolchains when compiling Lean with Lean
in core.
* [#7987](https://github.com/leanprover/lean4/pull/7987) fixes a bug in #7967 that broke external library linking.
* [#8026](https://github.com/leanprover/lean4/pull/8026) fixes bugs in #7809 and #7909 that were not caught partially
because the `badImport` test had been disabled.
* [#8048](https://github.com/leanprover/lean4/pull/8048) moves the Lake DSL syntax into a dedicated module with minimal
imports.
* [#8152](https://github.com/leanprover/lean4/pull/8152) fixes a regression where non-precompiled module builds would
`--load-dynlib` package `extern_lib` targets.
* [#8183](https://github.com/leanprover/lean4/pull/8183) makes Lake tests much more verbose in output. It also fixes some
bugs that had been missed due to disabled tests. Most significantly, the
target specifier `@pkg` (e.g., in `lake build`) is now always
interpreted as a package. It was previously ambiguously interpreted due
to changes in #7909.
* [#8190](https://github.com/leanprover/lean4/pull/8190) adds documentation for native library options (e.g., `dynlibs`,
`plugins`, `moreLinkObjs`, `moreLinkLibs`) and `needs` to the Lake
README. It is also includes information about specifying targets on the
Lake CLI and in Lean and TOML configuration files.
## Other
* [#7785](https://github.com/leanprover/lean4/pull/7785) adds further automation to the release process, taking care of
tagging, and creating new `bump/v4.X.0` branches automatically, and
fixing some bugs.
* [#7789](https://github.com/leanprover/lean4/pull/7789) fixes `lean` potentially changing or interpreting arguments
after `--run`.
* [#8060](https://github.com/leanprover/lean4/pull/8060) fixes a bug in the Lean kernel. During reduction of `Nat.pow`,
the kernel did not validate that the WHNF of the first argument is a
`Nat` literal before interpreting it as an `mpz` number. adds
the missing check.
```` |
reference-manual/Manual/Releases/v4_0_0-m2.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.0.0-m2 (2021-03-02)" =>
%%%
tag := "release-v4.0.0-m2"
file := "v4.0.0-m2"
%%%
```markdown
This is the second milestone release of Lean 4. With too many improvements and bug fixes in almost all parts of the system to list, we would like to single out major improvements to `simp` and other built-in tactics as well as support for a goal view that make the proving experience more comfortable.
``` |
reference-manual/Manual/Releases/v4_16_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.16.0 (2025-02-03)" =>
%%%
tag := "release-v4.16.0"
file := "v4.16.0"
%%%
````markdown
## Highlights
### Unique `sorry`s
[#5757](https://github.com/leanprover/lean4/pull/5757) makes it harder to create "fake" theorems about definitions that
are stubbed-out with `sorry` by ensuring that each `sorry` is not
definitionally equal to any other. For example, this now fails:
```lean
example : (sorry : Nat) = sorry := rfl -- fails
```
However, this still succeeds, since the `sorry` is a single
indeterminate `Nat`:
```lean
def f (n : Nat) : Nat := sorry
example : f 0 = f 1 := rfl -- succeeds
```
One can be more careful by putting parameters to the right of the colon:
```lean
def f : (n : Nat) → Nat := sorry
example : f 0 = f 1 := rfl -- fails
```
Most sources of synthetic sorries (recall: a sorry that originates from
the elaborator) are now unique, except for elaboration errors, since
making these unique tends to cause a confusing cascade of errors. In
general, however, such sorries are labeled. This enables "go to
definition" on `sorry` in the Infoview, which brings you to its origin.
The option `set_option pp.sorrySource true` causes the pretty printer to
show source position information on sorries.
### Separators in numeric literals
[#6204](https://github.com/leanprover/lean4/pull/6204) lets `_` be used in numeric literals as a separator. For
example, `1_000_000`, `0xff_ff` or `0b_10_11_01_00`. New lexical syntax:
```text
numeral10 : [0-9]+ ("_"+ [0-9]+)*
numeral2 : "0" [bB] ("_"* [0-1]+)+
numeral8 : "0" [oO] ("_"* [0-7]+)+
numeral16 : "0" [xX] ("_"* hex_char+)+
float : numeral10 "." numeral10? [eE[+-]numeral10]
```
### Additional new features
* [#6300](https://github.com/leanprover/lean4/pull/6300) adds the `debug.proofAsSorry` option. When enabled, the proofs
of theorems are ignored and replaced with `sorry`.
* [#6362](https://github.com/leanprover/lean4/pull/6362) adds the `--error=kind` option (shorthand: `-Ekind`) to the
`lean` CLI. When set, messages of `kind` (e.g.,
`linter.unusedVariables`) will be reported as errors. This setting does
nothing in interactive contexts (e.g., the server).
* [#6366](https://github.com/leanprover/lean4/pull/6366) adds support for `Float32` and fixes a bug in the runtime.
### Library updates
The Lean 4 library saw many changes that improve arithmetic reasoning, enhance data structure APIs,
and refine library organization. Key changes include better support for bitwise operations, shifts,
and conversions, expanded lemmas for `Array`, `Vector`, and `List`, and improved ordering definitions.
Some modules have been reorganized for clarity, and internal refinements ensure greater consistency and correctness.
### Breaking changes
[#6330](https://github.com/leanprover/lean4/pull/6330) removes unnecessary parameters from the functional induction
principles. This is a breaking change; broken code can typically be adjusted
simply by passing fewer parameters.
_This highlights section was contributed by Violetta Sim._
For this release, 201 changes landed. In addition to the 74 feature additions and 44 fixes listed below there were 7 refactoring changes, 5 documentation improvements and 62 chores.
## Language
* [#3696](https://github.com/leanprover/lean4/pull/3696) makes all message constructors handle pretty printer errors.
* [#4460](https://github.com/leanprover/lean4/pull/4460) runs all linters for a single command (together) on a separate
thread from further elaboration, making a first step towards
parallelizing the elaborator.
* [#5757](https://github.com/leanprover/lean4/pull/5757), see the highlights section above for details.
* [#6123](https://github.com/leanprover/lean4/pull/6123) ensures that the configuration in `Simp.Config` is used when
reducing terms and checking definitional equality in `simp`.
* [#6204](https://github.com/leanprover/lean4/pull/6204), see the highlights section above for details.
* [#6270](https://github.com/leanprover/lean4/pull/6270) fixes a bug that could cause the `injectivity` tactic to fail in
reducible mode, which could cause unfolding lemma generation to fail
(used by tactics such as `unfold`). In particular,
`Lean.Meta.isConstructorApp'?` was not aware that `n + 1` is equivalent
to `Nat.succ n`.
* [#6273](https://github.com/leanprover/lean4/pull/6273) modifies the "foo has been deprecated: use betterFoo instead"
warning so that foo and betterFoo are hoverable.
* [#6278](https://github.com/leanprover/lean4/pull/6278) enables simp configuration options to be passed to `norm_cast`.
* [#6286](https://github.com/leanprover/lean4/pull/6286) ensure `bv_decide` uses definitional equality in its reflection
procedure as much as possible. Previously it would build up explicit
congruence proofs for the kernel to check. This reduces the size of
proof terms passed to kernel speeds up checking of large reflection
proofs.
* [#6288](https://github.com/leanprover/lean4/pull/6288) uses Lean.RArray in bv_decide's reflection proofs. Giving
speedups on problems with lots of variables.
* [#6295](https://github.com/leanprover/lean4/pull/6295) sets up simprocs for all the remaining operations defined in
`Init.Data.Fin.Basic`
* [#6300](https://github.com/leanprover/lean4/pull/6300), see the highlights section above for details.
* [#6330](https://github.com/leanprover/lean4/pull/6330), see the highlights section above for details.
* [#6362](https://github.com/leanprover/lean4/pull/6362), see the highlights section above for details.
* [#6366](https://github.com/leanprover/lean4/pull/6366), see the highlights section above for details.
* [#6375](https://github.com/leanprover/lean4/pull/6375) fixes a bug in the simplifier. It was producing terms with loose
bound variables when eliminating unused `let_fun` expressions.
* [#6378](https://github.com/leanprover/lean4/pull/6378) adds an explanation to the error message when `cases` and
`induction` are applied to a term whose type is not an inductive type.
For `Prop`, these tactics now suggest the `by_cases` tactic. Example:
```
tactic 'cases' failed, major premise type is not an inductive type
Prop
```
* [#6381](https://github.com/leanprover/lean4/pull/6381) fixes a bug in `withTrackingZetaDelta` and
`withTrackingZetaDeltaSet`. The `MetaM` caches need to be reset. See new
test.
* [#6385](https://github.com/leanprover/lean4/pull/6385) fixes a bug in `simp_all?` that caused some local declarations
to be omitted from the `Try this:` suggestions.
* [#6386](https://github.com/leanprover/lean4/pull/6386) ensures that `revertAll` clears auxiliary declarations when
invoked directly by users.
* [#6387](https://github.com/leanprover/lean4/pull/6387) fixes a type error in the proof generated by the `contradiction`
tactic.
* [#6397](https://github.com/leanprover/lean4/pull/6397) ensures that `simp` and `dsimp` do not unfold definitions that
are not intended to be unfolded by the user. See issue #5755 for an
example affected by this issue.
* [#6398](https://github.com/leanprover/lean4/pull/6398) ensures `Meta.check` check projections.
* [#6412](https://github.com/leanprover/lean4/pull/6412) adds reserved names for congruence theorems used in the
simplifier and `grind` tactics. The idea is prevent the same congruence
theorems to be generated over and over again.
* [#6413](https://github.com/leanprover/lean4/pull/6413) introduces the following features to the WIP `grind` tactic:
- `Expr` internalization.
- Congruence theorem cache.
- Procedure for adding new facts
- New tracing options
- New preprocessing steps: fold projections and eliminate dangling
`Expr.mdata`
* [#6414](https://github.com/leanprover/lean4/pull/6414) fixes a bug in `Lean.Meta.Closure` that would introduce
under-applied delayed assignment metavariables, which would keep them
from ever getting instantiated. This bug affected `match` elaboration
when the expected type contained postponed elaboration problems, for
example tactic blocks.
* [#6419](https://github.com/leanprover/lean4/pull/6419) fixes multiple bugs in the WIP `grind` tactic. It also adds
support for printing the `grind` internal state.
* [#6428](https://github.com/leanprover/lean4/pull/6428) adds a new preprocessing step to the `grind` tactic:
universe-level normalization. The goal is to avoid missing equalities in
the congruence closure module.
* [#6430](https://github.com/leanprover/lean4/pull/6430) adds the predicate `Expr.fvarsSet a b`, which returns `true` if
and only if the free variables in `a` are a subset of the free variables
in `b`.
* [#6433](https://github.com/leanprover/lean4/pull/6433) adds a custom type and instance canonicalizer for the (WIP)
`grind` tactic. The `grind` tactic uses congruence closure but
disregards types, type formers, instances, and proofs. Proofs are
ignored due to proof irrelevance. Types, type formers, and instances are
considered supporting elements and are not factored into congruence
detection. Instead, `grind` only checks whether elements are
structurally equal, which, in the context of the `grind` tactic, is
equivalent to pointer equality. See new tests for examples where the
canonicalizer is important.
* [#6435](https://github.com/leanprover/lean4/pull/6435) implements the congruence table for the (WIP) `grind` tactic. It
also fixes several bugs, and adds a new preprocessing step.
* [#6437](https://github.com/leanprover/lean4/pull/6437) adds support for detecting congruent terms in the (WIP) `grind`
tactic. It also introduces the `grind.debug` option, which, when set to
`true`, checks many invariants after each equivalence class is merged.
This option is intended solely for debugging purposes.
* [#6438](https://github.com/leanprover/lean4/pull/6438) ensures `norm_cast` doesn't fail to act in the presence of
`no_index` annotations
* [#6441](https://github.com/leanprover/lean4/pull/6441) adds basic truth value propagation rules to the (WIP) `grind`
tactic.
* [#6442](https://github.com/leanprover/lean4/pull/6442) fixes the `checkParents` sanity check in `grind`.
* [#6443](https://github.com/leanprover/lean4/pull/6443) adds support for propagating the truth value of equalities in
the (WIP) `grind` tactic.
* [#6447](https://github.com/leanprover/lean4/pull/6447) refactors `grind` and adds support for invoking the simplifier
using the `GrindM` monad.
* [#6448](https://github.com/leanprover/lean4/pull/6448) declares the command `builtin_grind_propagator` for registering
equation propagator for `grind`. It also declares the auxiliary the
attribute.
* [#6449](https://github.com/leanprover/lean4/pull/6449) completes the implementation of the command
`builtin_grind_propagator`.
* [#6452](https://github.com/leanprover/lean4/pull/6452) adds support for generating (small) proofs for any two
expressions that belong to the same equivalence class in the `grind`
tactic state.
* [#6453](https://github.com/leanprover/lean4/pull/6453) improves bv_decide's performance in the presence of large
literals.
* [#6455](https://github.com/leanprover/lean4/pull/6455) fixes a bug in the equality proof generator in the (WIP) `grind`
tactic.
* [#6456](https://github.com/leanprover/lean4/pull/6456) fixes another bug in the equality proof generator in the (WIP)
`grind` tactic.
* [#6457](https://github.com/leanprover/lean4/pull/6457) adds support for generating congruence proofs for congruences
detected by the `grind` tactic.
* [#6458](https://github.com/leanprover/lean4/pull/6458) adds support for compact congruence proofs in the (WIP) `grind`
tactic. The `mkCongrProof` function now verifies whether the congruence
proof can be constructed using only `congr`, `congrFun`, and `congrArg`,
avoiding the need to generate the more complex `hcongr` auxiliary
theorems.
* [#6459](https://github.com/leanprover/lean4/pull/6459) adds the (WIP) `grind` tactic. It currently generates a warning
message to make it clear that the tactic is not ready for production.
* [#6461](https://github.com/leanprover/lean4/pull/6461) adds a new propagation rule for negation to the (WIP) `grind`
tactic.
* [#6463](https://github.com/leanprover/lean4/pull/6463) adds support for constructors to the (WIP) `grind` tactic. When
merging equivalence classes, `grind` checks for equalities between
constructors. If they are distinct, it closes the goal; if they are the
same, it applies injectivity.
* [#6464](https://github.com/leanprover/lean4/pull/6464) completes support for literal values in the (WIP) `grind`
tactic. `grind` now closes the goal whenever it merges two equivalence
classes with distinct literal values.
* [#6465](https://github.com/leanprover/lean4/pull/6465) adds support for projection functions to the (WIP) `grind`
tactic.
* [#6466](https://github.com/leanprover/lean4/pull/6466) completes the implementation of `addCongrTable` in the (WIP)
`grind` tactic. It also adds a new test to demonstrate why the extra
check is needed. It also updates the field `cgRoot` (congruence root).
* [#6468](https://github.com/leanprover/lean4/pull/6468) fixes issue #6467
* [#6469](https://github.com/leanprover/lean4/pull/6469) adds support code for implementing e-match in the (WIP) `grind`
tactic.
* [#6470](https://github.com/leanprover/lean4/pull/6470) introduces a command for specifying patterns used in the
heuristic instantiation of global theorems in the `grind` tactic. Note
that this PR only adds the parser.
* [#6472](https://github.com/leanprover/lean4/pull/6472) implements the command `grind_pattern`. The new command allows
users to associate patterns with theorems. These patterns are used for
performing heuristic instantiation with e-matching. In the future, we
will add the attributes `@[grind_eq]`, `@[grind_fwd]`, and
`@[grind_bwd]` to compute the patterns automatically for theorems.
* [#6473](https://github.com/leanprover/lean4/pull/6473) adds a deriving handler for the `ToExpr` class. It can handle
mutual and nested inductive types, however it falls back to creating
`partial` instances in such cases. This is upstreamed from the Mathlib
deriving handler written by @kmill, but has fixes to handle autoimplicit
universe level variables.
* [#6474](https://github.com/leanprover/lean4/pull/6474) adds pattern validation to the `grind_pattern` command. The new
`checkCoverage` function will also be used to implement the attributes
`@[grind_eq]`, `@[grind_fwd]`, and `@[grind_bwd]`.
* [#6475](https://github.com/leanprover/lean4/pull/6475) adds support for activating relevant theorems for the (WIP)
`grind` tactic. We say a theorem is relevant to a `grind` goal if the
symbols occurring in its patterns also occur in the goal.
* [#6478](https://github.com/leanprover/lean4/pull/6478) internalize nested ground patterns when activating ematch
theorems in the (WIP) `grind` tactic.
* [#6481](https://github.com/leanprover/lean4/pull/6481) implements E-matching for the (WIP) `grind` tactic. We still
need to finalize and internalize the new instances.
* [#6484](https://github.com/leanprover/lean4/pull/6484) addresses a few error messages where diffs weren't being
exposed.
* [#6485](https://github.com/leanprover/lean4/pull/6485) implements `Grind.EMatch.instantiateTheorem` in the (WIP)
`grind` tactic.
* [#6487](https://github.com/leanprover/lean4/pull/6487) adds source position information for `structure` parent
projections, supporting "go to definition". Closes #3063.
* [#6488](https://github.com/leanprover/lean4/pull/6488) fixes and refactors the E-matching module for the (WIP) `grind`
tactic.
* [#6490](https://github.com/leanprover/lean4/pull/6490) adds basic configuration options for the `grind` tactic.
* [#6492](https://github.com/leanprover/lean4/pull/6492) fixes a bug in the theorem instantiation procedure in the (WIP)
`grind` tactic.
* [#6497](https://github.com/leanprover/lean4/pull/6497) fixes another theorem instantiation bug in the `grind` tactic.
It also moves new instances to be processed to `Goal`.
* [#6498](https://github.com/leanprover/lean4/pull/6498) adds support in the `grind` tactic for propagating dependent
forall terms `forall (h : p), q[h]` where `p` is a proposition.
* [#6499](https://github.com/leanprover/lean4/pull/6499) fixes the proof canonicalizer for `grind`.
* [#6500](https://github.com/leanprover/lean4/pull/6500) fixes a bug in the `markNestedProofs` used in `grind`. See new
test.
* [#6502](https://github.com/leanprover/lean4/pull/6502) fixes a bug in the proof assembly procedure utilized by the
`grind` tactic.
* [#6503](https://github.com/leanprover/lean4/pull/6503) adds a simple strategy to the (WIP) `grind` tactic. It just
keeps internalizing new theorem instances found by E-matching.
* [#6506](https://github.com/leanprover/lean4/pull/6506) adds the `monotonicity` tactic, intended to be used inside the
`partial_fixpoint` feature.
* [#6508](https://github.com/leanprover/lean4/pull/6508) fixes a bug in the sanity checkers for the `grind` tactic. See
the new test for an example of a case where it was panicking.
* [#6509](https://github.com/leanprover/lean4/pull/6509) fixes a bug in the congruence closure data structure used in the
`grind` tactic. The new test includes an example that previously caused
a panic. A similar panic was also occurring in the test
`grind_nested_proofs.lean`.
* [#6510](https://github.com/leanprover/lean4/pull/6510) adds a custom congruence rule for equality in `grind`. The new
rule takes into account that `Eq` is a symmetric relation. In the
future, we will add support for arbitrary symmetric relations. The
current rule is important for propagating disequalities effectively in
`grind`.
* [#6512](https://github.com/leanprover/lean4/pull/6512) introduces support for user-defined fallback code in the `grind`
tactic. The fallback code can be utilized to inspect the state of
failing `grind` subgoals and/or invoke user-defined automation. Users
can now write `grind on_failure <code>`, where `<code>` should have the
type `GoalM Unit`. See the modified tests in this PR for examples.
* [#6513](https://github.com/leanprover/lean4/pull/6513) adds support for (dependent) if-then-else terms (i.e., `ite` and
`dite` applications) in the `grind` tactic.
* [#6514](https://github.com/leanprover/lean4/pull/6514) enhances the assertion of new facts in `grind` by avoiding the
creation of unnecessary metavariables.
## Library
* [#6182](https://github.com/leanprover/lean4/pull/6182) adds `BitVec.[toInt|toFin]_concat` and moves a couple of
theorems into the concat section, as `BitVec.msb_concat` is needed for
the `toInt_concat` proof.
* [#6188](https://github.com/leanprover/lean4/pull/6188) completes the `toNat` theorems for the bitwise operations
(`and`, `or`, `xor`, `shiftLeft`, `shiftRight`) of the UInt types and
adds `toBitVec` theorems as well. It also renames `and_toNat` to
`toNat_and` to fit with the current naming convention.
* [#6238](https://github.com/leanprover/lean4/pull/6238) adds theorems characterizing the value of the unsigned shift
right of a bitvector in terms of its 2s complement interpretation as an
integer.
Unsigned shift right by at least one bit makes the value of the
bitvector less than or equal to `2^(w-1)`,
makes the interpretation of the bitvector `Int` and `Nat` agree.
In the case when `n = 0`, then the shift right value equals the integer
interpretation.
* [#6244](https://github.com/leanprover/lean4/pull/6244) changes the implementation of `HashMap.toList`, so the ordering
agrees with `HashMap.toArray`.
* [#6272](https://github.com/leanprover/lean4/pull/6272) introduces the basic theory of permutations of `Array`s and
proves `Array.swap_perm`.
* [#6282](https://github.com/leanprover/lean4/pull/6282) moves `IO.Channel` and `IO.Mutex` from `Init` to `Std.Sync` and
renames them to `Std.Channel` and `Std.Mutex`.
* [#6294](https://github.com/leanprover/lean4/pull/6294) upstreams `List.length_flatMap`, `countP_flatMap` and
`count_flatMap` from Mathlib. These were not possible to state before we
upstreamed `List.sum`.
* [#6315](https://github.com/leanprover/lean4/pull/6315) adds `protected` to `Fin.cast` and `BitVec.cast`, to avoid
confusion with `_root_.cast`. These should mostly be used via
dot-notation in any case.
* [#6316](https://github.com/leanprover/lean4/pull/6316) adds lemmas simplifying `for` loops over `Option` into
`Option.pelim`, giving parity with lemmas simplifying `for` loops of
`List` into `List.fold`.
* [#6317](https://github.com/leanprover/lean4/pull/6317) completes the basic API for BitVec.ofBool.
* [#6318](https://github.com/leanprover/lean4/pull/6318) generalizes the universe level for `Array.find?`, by giving it a
separate implementation from `Array.findM?`.
* [#6324](https://github.com/leanprover/lean4/pull/6324) adds `GetElem` lemmas for the basic `Vector` operations.
* [#6333](https://github.com/leanprover/lean4/pull/6333) generalizes the panic functions to a type of `Sort u` rather
than `Type u`. This better supports universe polymorphic types and
avoids confusing errors.
* [#6334](https://github.com/leanprover/lean4/pull/6334) adds `Nat` theorems for distributing `>>>` over bitwise
operations, paralleling those of `BitVec`.
* [#6338](https://github.com/leanprover/lean4/pull/6338) adds `BitVec.[toFin|getMsbD]_setWidth` and
`[getMsb|msb]_signExtend` as well as `ofInt_toInt`.
* [#6341](https://github.com/leanprover/lean4/pull/6341) generalizes `DecidableRel` to allow a heterogeneous relation.
* [#6353](https://github.com/leanprover/lean4/pull/6353) reproduces the API around `List.any/all` for `Array.any/all`.
* [#6364](https://github.com/leanprover/lean4/pull/6364) makes fixes suggested by the Batteries environment linters,
particularly `simpNF`, and `unusedHavesSuffices`.
* [#6365](https://github.com/leanprover/lean4/pull/6365) expands the `Array.set` and `Array.setIfInBounds` lemmas to
match existing lemmas for `List.set`.
* [#6367](https://github.com/leanprover/lean4/pull/6367) brings Vector lemmas about membership and indexing to parity
with List and Array.
* [#6369](https://github.com/leanprover/lean4/pull/6369) adds lemmas about `Vector.set`, `anyM`, `any`, `allM`, and
`all`.
* [#6376](https://github.com/leanprover/lean4/pull/6376) adds theorems about `==` on `Vector`, reproducing those already
on `List` and `Array`.
* [#6379](https://github.com/leanprover/lean4/pull/6379) replaces the inductive predicate `List.lt` with an upstreamed version of `List.Lex` from Mathlib.
(Previously `Lex.lt` was defined in terms of `<`; now it is generalized to take an arbitrary relation.)
This subtly changes the notion of ordering on `List α`.
`List.lt` was a weaker relation: in particular if `l₁ < l₂`, then `a :: l₁ < b :: l₂` may hold according to `List.lt` even if `a` and `b` are merely incomparable (either neither `a < b` nor `b < a`), whereas according to `List.Lex` this would require `a = b`.
When `<` is total, in the sense that `¬ · < ·` is antisymmetric, then the two relations coincide.
Mathlib was already overriding the order instances for `List α`, so this change should not be noticed by anyone already using Mathlib.
We simultaneously add the boolean valued `List.lex` function, parameterised by a `BEq` type class and an arbitrary `lt` function. This will support the flexibility previously provided for `List.lt`, via a `==` function which is weaker than strict equality.
* [#6390](https://github.com/leanprover/lean4/pull/6390) redefines `Range.forIn'` and `Range.forM`, in preparation for
writing lemmas about them.
* [#6391](https://github.com/leanprover/lean4/pull/6391) requires that the step size in `Std.Range` is positive, to avoid
ill-specified behaviour.
* [#6396](https://github.com/leanprover/lean4/pull/6396) adds lemmas reducing for loops over `Std.Range` to for loops
over `List.range'`.
* [#6399](https://github.com/leanprover/lean4/pull/6399) adds basic lemmas about lexicographic order on Array and Vector,
achieving parity with List.
* [#6423](https://github.com/leanprover/lean4/pull/6423) adds missing lemmas about lexicographic order on
List/Array/Vector.
* [#6477](https://github.com/leanprover/lean4/pull/6477) adds the necessary domain theory that backs the
`partial_fixpoint` feature.
## Compiler
* [#6311](https://github.com/leanprover/lean4/pull/6311) adds support for `HEq` to the new code generator.
* [#6348](https://github.com/leanprover/lean4/pull/6348) adds support for `Float32` to the Lean runtime.
* [#6350](https://github.com/leanprover/lean4/pull/6350) adds missing features and fixes bugs in the `Float32` support
* [#6383](https://github.com/leanprover/lean4/pull/6383) ensures the new code generator produces code for `opaque`
definitions that are not tagged as `@[extern]`.
Remark: This is the behavior of the old code generator.
* [#6405](https://github.com/leanprover/lean4/pull/6405) adds support for erasure of `Decidable.decide` to the new code
generator. It also adds a new `Probe.runOnDeclsNamed` function, which is
helpful for writing targeted single-file tests of compiler internals.
* [#6415](https://github.com/leanprover/lean4/pull/6415) fixes a bug in the `sharecommon` module, which was returning
incorrect results for objects that had already been processed by
`sharecommon`. See the new test for an example that triggered the bug.
* [#6429](https://github.com/leanprover/lean4/pull/6429) adds support for extern LCNF decls, which is required for parity
with the existing code generator.
* [#6535](https://github.com/leanprover/lean4/pull/6535) avoids a linker warning on Windows.
* [#6547](https://github.com/leanprover/lean4/pull/6547) should prevent Lake from accidentally picking up other linkers
installed on the machine.
* [#6574](https://github.com/leanprover/lean4/pull/6574) actually prevents Lake from accidentally picking up other
toolchains installed on the machine.
## Pretty Printing
* [#5689](https://github.com/leanprover/lean4/pull/5689) adjusts the way the pretty printer unresolves names. It used to
make use of all `export`s when pretty printing, but now it only uses
`export`s that put names into parent namespaces (heuristic: these are
"API exports" that are intended by the library author), rather than
"horizontal exports" that put the names into an unrelated namespace,
which the dot notation feature in #6189 now incentivizes.
* [#5757](https://github.com/leanprover/lean4/pull/5757), aside from introducing labeled sorries, fixes the bug that the metadata attached to the pretty-printed representation of arguments with a borrow annotation (for example, the second argument of `String.append`), is inconsistent with the metadata attached to the regular arguments.
## Documentation
* [#6450](https://github.com/leanprover/lean4/pull/6450) adds a docstring to the `@[app_delab]` attribute.
## Server
* [#6279](https://github.com/leanprover/lean4/pull/6279) fixes a bug in structure instance field completion that caused
it to not function correctly for bracketed structure instances written
in Mathlib style.
* [#6408](https://github.com/leanprover/lean4/pull/6408) fixes a regression where goals that don't exist were being
displayed. The regression was triggered by #5835 and originally caused
by #4926.
## Lake
* [#6176](https://github.com/leanprover/lean4/pull/6176) changes Lake's build process to no longer use `leanc` for
compiling C files or linking shared libraries and executables. Instead,
it directly invokes the bundled compiler (or the native compiler if
none) using the necessary flags.
* [#6289](https://github.com/leanprover/lean4/pull/6289) adapts Lake modules to use `prelude` and includes them in the
`check-prelude` CI.
* [#6291](https://github.com/leanprover/lean4/pull/6291) ensures the log error position is properly preserved when
prepending stray log entries to the job log. It also adds comparison
support for `Log.Pos`.
* [#6388](https://github.com/leanprover/lean4/pull/6388) merges `BuildJob` and `Job`, deprecating the former. `Job` now
contains a trace as part of its state which can be interacted with
monadically. also simplifies the implementation of `OpaqueJob`.
* [#6411](https://github.com/leanprover/lean4/pull/6411) adds the ability to override package entries in a Lake manifest
via a separate JSON file. This file can be specified on the command line
with `--packages` or applied persistently by placing it at
`.lake/package-overrides.json`.
* [#6422](https://github.com/leanprover/lean4/pull/6422) fixes a bug in #6388 where the `Package.afterBuildCahe*`
functions would produce different traces depending on whether the cache
was fetched.
* [#6627](https://github.com/leanprover/lean4/pull/6627) aims to fix the trace issues reported by Mathlib that are
breaking `lake exe cache` in downstream projects.
* [#6631](https://github.com/leanprover/lean4/pull/6631) sets `MACOSX_DEPLOYMENT_TARGET` for shared libraries (it was
previously only set for executables).
## Other
* [#6285](https://github.com/leanprover/lean4/pull/6285) upstreams the `ToLevel` type class from mathlib and uses it to
fix the existing `ToExpr` instances so that they are truly universe
polymorphic (previously it generated malformed expressions when the
universe level was nonzero). We improve on the mathlib definition of
`ToLevel` to ensure the class always lives in `Type`, irrespective of
the universe parameter.
* [#6363](https://github.com/leanprover/lean4/pull/6363) fixes errors at load time in the comparison mode of the Firefox
profiler.
```` |
reference-manual/Manual/Releases/v4_22_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.22.0 (2025-08-14)" =>
%%%
tag := "release-v4.22.0"
file := "v4.22.0"
%%%
````markdown
For this release, 468 changes landed. In addition to the 185 feature additions and 85 fixes listed below there were 15 refactoring changes, 5 documentation improvements, 4 performance improvements, 0 improvements to the test suite and 174 other changes.
## Highlights
### Grind is released!
Lean now includes a new SMT-style tactic `grind`, along with annotations for the Lean standard library.
`grind` ships theory-specific solvers, including cutsat (superseding `omega`, with model construction)
and a new Gröbner basis solver.
Also see the [chapter on grind in the reference manual](https://lean-lang.org/doc/reference/latest//The--grind--tactic/#grind).
### New compiler
The old compiler has been replaced by the new compiler ([#8577](https://github.com/leanprover/lean4/pull/8577))!
This closes many long-standing issues, and lays the foundation for many
future features and performance improvements.
### New `math` project template
[#8866](https://github.com/leanprover/lean4/pull/8866) upgrades the `math` template for `lake init` and
`lake new` to meet rigorous Mathlib maintenance standards.
In comparison with the previous version (now available as `lake new ... math-lax`), the new template automatically provides:
* Strict linting options matching Mathlib.
* GitHub workflow for automatic upgrades to newer Lean and Mathlib releases.
* Automatic release tagging for toolchain upgrades.
* API documentation generated by [doc-gen4](https://github.com/leanprover/doc-gen4) and hosted on `github.io`.
* README with some GitHub-specific instructions.
### Signature help
[#8511](https://github.com/leanprover/lean4/pull/8511) implements signature help support in the editors.
See the demo in the PR description.
### Displaying import hierarchy
[#8654](https://github.com/leanprover/lean4/pull/8654) (together with [#620](https://github.com/leanprover/vscode-lean4/pull/620) for vscode-lean4) adds
a new module hierarchy component in
VS Code that can be used to navigate both the import tree of a module
and the imported-by tree of a module.
### Refactor of `have`/`let` semantics
TL;DR: nondependent `let` bindings are now transformed to `have` bindings for better performance.
Syntax of `have` and `let` is unified, and new options are added.
* [#8373](https://github.com/leanprover/lean4/pull/8373) enables transforming nondependent `let`s into `have`s
so `simp` works better without zeta reduction. Disable with `set_option cleanup.letToHave false`.
* [#8804](https://github.com/leanprover/lean4/pull/8804) implements first-class support for nondependent `let` expressions
in the elaborator. This has been given full support throughout the metaprogramming interface and the
elaborator.
* [#8914](https://github.com/leanprover/lean4/pull/8914) modifies `let` and `have` term syntaxes to be consistent with
each other. Adds configuration options; for example, `have` is
equivalent to `let +nondep`, for *nondependent* lets. Other options
include `+usedOnly` (for `let_tmp`), `+zeta` (for `letI`/`haveI`), and
`+postponeValue` (for `let_delayed`). There is also `let (eq := h) x := v; b`
for introducing `h : x = v` when elaborating `b`. The `eq` option
works for pattern matching as well, for example `let (eq := h) (x, y) := p; b`.
* [#8935](https://github.com/leanprover/lean4/pull/8935) adds the `+generalize` option to the `let` and `have` syntaxes.
For example, `have +generalize n := a + b; body` replaces all instances
of `a + b` in the expected type with `n` when elaborating `body`. This
can be likened to a term version of the `generalize` tactic. One can
combine this with `eq` in `have +generalize (eq := h) n := a + b; body`
as an analogue of `generalize h : n = a + b`.
* [#8954](https://github.com/leanprover/lean4/pull/8954) adds a procedure that efficiently transforms `let` expressions
into `have` expressions (`Meta.letToHave`). This is exposed as the
`let_to_have` tactic.
* [#9086](https://github.com/leanprover/lean4/pull/9086) deprecates `let_fun` syntax in favor of `have` and removes
`letFun` support from WHNF and `simp`.
### Simp
* **Flagging unused `simp` arguments**
[#8901](https://github.com/leanprover/lean4/pull/8901) adds a linter (`linter.unusedSimpArgs`) that complains when a
simp argument (`simp [foo]`) is unused, with a clickable suggestion to remove it.
Handles repeated simp calls correctly (e.g., inside `all_goals`), but skips macros.
* **Detection of possibly looping lemmas**
[#8865](https://github.com/leanprover/lean4/pull/8865) allows `simp` to recognize and warn about simp lemmas that are
likely looping in the current simp set. It does so automatically
whenever simplification fails with the dreaded “max recursion depth”
error, but it can be made to do it always with `set_option
linter.loopingSimpArgs true`. This check is not on by default because it
is somewhat costly, and can warn about simp calls that still happen to
work.
* **Faster `simp` via cache reuse**
[#8880](https://github.com/leanprover/lean4/pull/8880) makes `simp` consult
its own cache more often, to avoid replicating work.
* **Explicit `defeq` attribute for `dsimp`**
[#8419](https://github.com/leanprover/lean4/pull/8419) introduces an explicit `defeq` attribute to mark theorems that
can be used by `dsimp`. The benefit of an explicit attribute over the
prior logic of looking at the proof body is that we can reliably omit
theorem bodies across module boundaries. It also helps with intra-file
parallelism.
### Named errors with explanations
Lean now supports named error messages with associated explanations.
[#8649](https://github.com/leanprover/lean4/pull/8649) and [#8730](https://github.com/leanprover/lean4/pull/8730) add
macro syntax for registering
and throwing named errors, mechanisms for displaying error names in the Infoview and at the command line,
and the ability to link to [error explanations in the reference manual](https://lean-lang.org/doc/reference/latest/Error-Explanations/#The-Lean-Language-Reference--Error-Explanations).
This infrastructure lays the foundation for a searchable error index and improved diagnostics.
### `finally` section
[#8723](https://github.com/leanprover/lean4/pull/8723) implements a `finally` section following a (potentially empty)
`where` block. `where ... finally` opens a tactic sequence block in
which the goals are the unassigned metavariables from the definition
body and its auxiliary definitions that arise from use of `let rec` and
`where`.
This can be useful for discharging multiple proof obligations in the definition body
by a single invocation of a tactic such as `all_goals`:
```lean
example (i j : Nat) (xs : Array Nat) (hi : i < xs.size) (hj: j < xs.size) :=
match i with
| 0 => x
| _ => xs[i]'?_ + xs[j]'?_
where x := 13
finally all_goals assumption
```
### Polymorphic ranges and slices
[#8784](https://github.com/leanprover/lean4/pull/8784) introduces new syntax for ranges:
`1...*`, `1...=3`, `1...<3`, `1<...=2`, `*...=3.`.
[#8947](https://github.com/leanprover/lean4/pull/8947) extends this syntax to slices, allowing expressions like `xs[*...end]`.
### Library highlights
Notable additions to the standard library are:
* Iterators ([#8420](https://github.com/leanprover/lean4/pull/8420), [#8545](https://github.com/leanprover/lean4/pull/8545), [#8615](https://github.com/leanprover/lean4/pull/8615), [#8629](https://github.com/leanprover/lean4/pull/8629), [#8768](https://github.com/leanprover/lean4/pull/8768)),
* monadic interface for `Async` operations ([#8003](https://github.com/leanprover/lean4/pull/8003)),
* DNS functions ([#8072](https://github.com/leanprover/lean4/pull/8072)),
* system information functions ([#8109](https://github.com/leanprover/lean4/pull/8109)).
### Experimental: monadic verification framework
[#8995](https://github.com/leanprover/lean4/pull/8995) introduces a Hoare logic for monadic programs in
`Std.Do.Triple`, and assorted tactics:
* `mspec` for applying Hoare triple specifications,
* `mvcgen` to turn a Hoare triple proof obligation `⦃P⦄ prog ⦃Q⦄` into
pure verification conditions.
### Experimental: module system
The new module system (enabled by the `module` keyword before import statements) is available
for experimentation.
### Experimental: sharing oleans between different checkouts of the same repository
[#8922](https://github.com/leanprover/lean4/pull/8922) introduces a local artifact cache for Lake. When enabled, Lake
will share build artifacts (built files) across different instances of
the same package using an input- and content-addressed cache. Requires `export LAKE_ARTIFACT_CACHE=true` for now.
### Warnings about `sorry`s
[#8662](https://github.com/leanprover/lean4/pull/8662) adds a `warn.sorry` option (default true) that logs the
"declaration uses 'sorry'" warning when declarations contain `sorryAx`.
When false, the warning is not logged.
### Breaking changes
* [#8751](https://github.com/leanprover/lean4/pull/8751) adds the `nondep` field of `Expr.letE` to the C++ data model.
Breaking change: `Expr.updateLet!` is renamed to `Expr.updateLetE!`.
* [#8105](https://github.com/leanprover/lean4/pull/8105) adds support for server-sided `RpcRef` reuse and fixes a bug
where trace nodes in the InfoView would close while the file was still being processed.
Breaking change: Since `WithRpcRef` is now capable of tracking its identity
to decide which `WithRpcRef` usage constitutes a reuse, the constructor of
`WithRpcRef` has been made `private` to discourage downstream users from
creating `WithRpcRef` instances with manually-set `id`s. Instead, `WithRpcRef.mk`
(which lives in `BaseIO`) is now the preferred way to create `WithRpcRef` instances.
* [#8654](https://github.com/leanprover/lean4/pull/8654) adds server-side support for a new module hierarchy component in
VS Code.
Breaking change: This PR augments the .ilean format with the direct imports of a file
in order to implement the `$/lean/moduleHierarchy/importedBy` request and bumps the .ilean format version.
* [#8804](https://github.com/leanprover/lean4/pull/8804) implements first-class support for nondependent `let` expressions
in the elaborator.
Breaking change: Uses of `letLambdaTelescope`/`mkLetFVars` need to use `generalizeNondepLet := false`;
see the PR description for more info.
## Language
* [#6672](https://github.com/leanprover/lean4/pull/6672) filters out all declarations from `Lean.*`, `*.Tactic.*`, and
`*.Linter.*` from the results of `exact?` and `rw?`.
* [#7395](https://github.com/leanprover/lean4/pull/7395) changes the `show t` tactic to match its documentation.
Previously it was a synonym for `change t`, but now it finds the first
goal that unifies with the term `t` and moves it to the front of the
goal list.
* [#7639](https://github.com/leanprover/lean4/pull/7639) changes the generated `below` and `brecOn` implementations for
reflexive inductive types to support motives in `Sort u` rather than
`Type u`.
* [#8337](https://github.com/leanprover/lean4/pull/8337) adjusts the experimental module system to not export any private
declarations from modules.
* [#8373](https://github.com/leanprover/lean4/pull/8373) enables transforming nondependent `let`s into `have`s in a
number of contexts: the bodies of nonrecursive definitions, equation
lemmas, smart unfolding definitions, and types of theorems. A motivation
for this change is that when zeta reduction is disabled, `simp` can only
effectively rewrite `have` expressions (e.g. `split` uses `simp` with
zeta reduction disabled), and so we cache the nondependence calculations
by transforming `let`s to `have`s. The transformation can be disabled
using `set_option cleanup.letToHave false`.
* [#8387](https://github.com/leanprover/lean4/pull/8387) improves the error messages produced by `end` and prevents
invalid `end` commands from closing scopes on failure.
* [#8419](https://github.com/leanprover/lean4/pull/8419) introduces an explicit `defeq` attribute to mark theorems that
can be used by `dsimp`. The benefit of an explicit attribute over the
prior logic of looking at the proof body is that we can reliably omit
theorem bodies across module boundaries. It also helps with intra-file
parallelism.
* [#8519](https://github.com/leanprover/lean4/pull/8519) makes the equational theorems of non-exposed defs private. If
the author of a module chose not to expose the body of their function,
then they likely don't want that implementation to leak through
equational theorems. Helps with #8419.
* [#8543](https://github.com/leanprover/lean4/pull/8543) adds type classes for `grind` to embed types into `Int`, for
cutsat. This allows, for example, treating `Fin n`, or Mathlib's `ℕ+` in
a uniform and extensible way.
* [#8568](https://github.com/leanprover/lean4/pull/8568) modifies the `structure` elaborator to add local terminfo for
structure fields and explicit parent projections, enabling "go to
definition" when there are dependent fields.
* [#8574](https://github.com/leanprover/lean4/pull/8574) adds an additional diff mode to the error-message hint
suggestion widget that displays diffs per word rather than per
character.
* [#8596](https://github.com/leanprover/lean4/pull/8596) makes `guard_msgs.diff=true` the default. The main usage of
`#guard_msgs` is for writing tests, and this makes staring at altered
test outputs considerably less tiring.
* [#8609](https://github.com/leanprover/lean4/pull/8609) uses `grind` to shorten some proofs in the LRAT checker. The
intention is not particularly to improve the quality or maintainability
of these proofs (although hopefully this is a side effect), but just to
give `grind` a work out.
* [#8619](https://github.com/leanprover/lean4/pull/8619) fixes an internalization (aka preprocessing) issue in `grind`
when applying injectivity theorems.
* [#8621](https://github.com/leanprover/lean4/pull/8621) fixes a bug in the equality-resolution procedure used by
`grind`.
The procedure now performs a topological sort so that every simplified
theorem declaration is emitted **before** any place where it is
referenced.
Previously, applying equality resolution to
```lean
h : ∀ x, p x a → ∀ y, p y b → x ≠ y
```
in the example
```lean
example
(p : Nat → Nat → Prop)
(a b c : Nat)
(h : ∀ x, p x a → ∀ y, p y b → x ≠ y)
(h₁ : p c a)
(h₂ : p c b) :
False := by
grind
```
caused `grind` to produce the incorrect term
```lean
p ?y a → ∀ y, p y b → False
```
The patch eliminates this error, and the following correct simplified
theorem is generated
```lean
∀ y, p y a → p y b → False
```
* [#8622](https://github.com/leanprover/lean4/pull/8622) adds a test case / use case example for `grind`, setting up the
very basics of `IndexMap`, modelled on Rust's
[`indexmap`](https://docs.rs/indexmap/latest/indexmap/). It is not
intended as a complete implementation: just enough to exercise `grind`.
* [#8625](https://github.com/leanprover/lean4/pull/8625) improves the diagnostic information produced by `grind` when it
succeeds. We now include the list of case-splits performed, and the
number of application per function symbol.
* [#8633](https://github.com/leanprover/lean4/pull/8633) implements case-split tracking in `grind`. The information is
displayed when `grind` fails or diagnostic information is requested.
Examples:
- Failure
* [#8637](https://github.com/leanprover/lean4/pull/8637) adds background theorems for normalizing `IntModule` expressions
using reflection.
* [#8638](https://github.com/leanprover/lean4/pull/8638) improves the diagnostic information produced by `grind`. It now
sorts the equivalence classes by generation and then `Expr.lt`.
* [#8639](https://github.com/leanprover/lean4/pull/8639) completes the `ToInt` family of type classes which `grind` will
use to embed types into the integers for `cutsat`. It contains instances
for the usual concrete data types (`Fin`, `UIntX`, `IntX`, `BitVec`),
and is extensible (e.g. for Mathlib's `PNat`).
* [#8641](https://github.com/leanprover/lean4/pull/8641) adds the `#print sig $ident` variant of the `#print` command,
which omits the body. This is useful for testing meta-code, in the
```
#guard_msgs (drop trace, all) in #print sig foo
```
idiom. The benefit over `#check` is that it shows the declaration kind,
reducibility attributes (and in the future more built-in attributes,
like `@[defeq]` in #8419). (One downside is that `#check` shows unused
function parameter names, e.g. in induction principles; this could
probably be refined.)
* [#8645](https://github.com/leanprover/lean4/pull/8645) adds many helper theorems for the future `IntModule` linear
arithmetic procedure in `grind`.
It also adds helper theorems for normalizing input atoms and support for
disequality in the new linear arithmetic procedure in `grind`.
* [#8650](https://github.com/leanprover/lean4/pull/8650) adds helper theorems for coefficient normalization and equality
detection. This theorems are for the linear arithmetic procedure in
`grind`.
* [#8662](https://github.com/leanprover/lean4/pull/8662) adds a `warn.sorry` option (default true) that logs the
"declaration uses 'sorry'" warning when declarations contain `sorryAx`.
When false, the warning is not logged.
* [#8670](https://github.com/leanprover/lean4/pull/8670) adds helper theorems that will be used to interface the
`CommRing` module with the linarith procedure in `grind`.
* [#8671](https://github.com/leanprover/lean4/pull/8671) allow structures to have non-bracketed binders, making it
consistent with `inductive`.
* [#8677](https://github.com/leanprover/lean4/pull/8677) adds the basic infrastructure for the linarith module in
`grind`.
* [#8680](https://github.com/leanprover/lean4/pull/8680) adds the `reify?` and `denoteExpr` for the new linarith module
in `grind`.
* [#8682](https://github.com/leanprover/lean4/pull/8682) uses the `CommRing` module to normalize linarith inequalities.
* [#8687](https://github.com/leanprover/lean4/pull/8687) implements the infrastructure for constructing proof terms in
the linarith procedure in `grind`. It also adds the `ToExpr` instances
for the reified objects.
* [#8689](https://github.com/leanprover/lean4/pull/8689) implements proof term generation for the `CommRing` and
`linarith` interface. It also fixes the `CommRing` helper theorems.
* [#8690](https://github.com/leanprover/lean4/pull/8690) implements the main framework of the model search procedure for
the linarith component in grind. It currently handles only inequalities.
It can already solve simple goals such as
```lean
example [IntModule α] [Preorder α] [IntModule.IsOrdered α] (a b c : α)
: a < b → b < c → c < a → False := by
grind
* [#8693](https://github.com/leanprover/lean4/pull/8693) fixes the denotation functions used to interface the ring and
linarith modules in grind.
* [#8694](https://github.com/leanprover/lean4/pull/8694) implements special support for `One.one` in linarith when the
structure is a ordered ring. It also fixes bugs during initialization.
* [#8697](https://github.com/leanprover/lean4/pull/8697) implements support for inequalities in the `grind` linear
arithmetic procedure and simplifies its design. Some examples that can
already be solved:
```lean
open Lean.Grind
example [IntModule α] [Preorder α] [IntModule.IsOrdered α] (a b c d : α)
: a + d < c → b = a + (2:Int)*d → b - d > c → False := by
grind
* [#8708](https://github.com/leanprover/lean4/pull/8708) fixes an internalization bug in the interface between linarith
and ring modules in `grind`. The `CommRing` module may create new terms
during normalization.
* [#8713](https://github.com/leanprover/lean4/pull/8713) fixes a bug in the commutative ring module used in `grind`. It
was missing simplification opportunities.
* [#8715](https://github.com/leanprover/lean4/pull/8715) implements the basic infrastructure for processing disequalities
in the `grind linarith` module. We still have to implement backtracking.
* [#8723](https://github.com/leanprover/lean4/pull/8723) implements a `finally` section following a (potentially empty)
`where` block. `where ... finally` opens a tactic sequence block in
which the goals are the unassigned metavariables from the definition
body and its auxiliary definitions that arise from use of `let rec` and
`where`.
* [#8730](https://github.com/leanprover/lean4/pull/8730) adds support for throwing named errors with associated error
explanations. In particular, it adds elaborators for the syntax defined
in #8649, which use the error-explanation infrastructure added in #8651.
This includes completions, hovers, and jump-to-definition for error
names.
* [#8733](https://github.com/leanprover/lean4/pull/8733) implements disequality splitting and non-chronological
backtracking for the `grind` linarith procedure.
```lean
example [IntModule α] [LinearOrder α] [IntModule.IsOrdered α] (a b c d : α)
: a ≤ b → a - c ≥ 0 + d → d ≤ 0 → d ≥ 0 → b = c → a ≠ b → False := by
grind
```
* [#8751](https://github.com/leanprover/lean4/pull/8751) adds the `nondep` field of `Expr.letE` to the C++ data model.
Previously this field has been unused, and in followup PRs the
elaborator will use it to encode `have` expressions (non-dependent
`let`s). The kernel does not verify that `nondep` is correctly applied
during typechecking. The `letE` delaborator now prints `have`s when
`nondep` is true, though `have` still elaborates as `letFun` for now.
Breaking change: `Expr.updateLet!` is renamed to `Expr.updateLetE!`.
* [#8753](https://github.com/leanprover/lean4/pull/8753) fixes a bug in `simp` where it was not resetting the set of
zeta-delta reduced let definitions between `simp` calls. It also fixes a
bug where `simp` would report zeta-delta reduced let definitions that
weren't given as simp arguments (these extraneous let definitions appear
due to certain processes temporarily setting `zetaDelta := true`). This
PR also modifies the metaprogramming interface for the zeta-delta
tracking functions to be re-entrant and to prevent this kind of no-reset
bug from occurring again. Closes #6655.
* [#8756](https://github.com/leanprover/lean4/pull/8756) implements counterexamples for grind linarith. Example:
```lean
example [CommRing α] [LinearOrder α] [Ring.IsOrdered α] (a b c d : α)
: b ≥ 0 → c > b → d > b → a ≠ b + c → a > b + c → a < b + d → False := by
grind
```
produces the counterexample
```
a := 7/2
b := 1
c := 2
d := 3
```
* [#8759](https://github.com/leanprover/lean4/pull/8759) implements model-based theory combination for grind linarith.
Example:
```lean
example [CommRing α] [LinearOrder α] [Ring.IsOrdered α] (f : α → α → α) (x y z : α)
: z ≤ x → x ≤ 1 → z = 1 → f x y = 2 → f 1 y = 2 := by
grind
```
* [#8763](https://github.com/leanprover/lean4/pull/8763) corrects the handling of explicit `monotonicity` proofs for
mutual `partial_fixpoint` definitions.
* [#8773](https://github.com/leanprover/lean4/pull/8773) implements support for the heterogeneous `(k : Nat) * (a : R)`
in ordered modules. Example:
```lean
variable (R : Type u) [IntModule R] [LinearOrder R] [IntModule.IsOrdered R]
* [#8774](https://github.com/leanprover/lean4/pull/8774) adds an option for disabling the cutsat procedure in `grind`.
The linarith module takes over linear integer/nat constraints. Example:
```lean
set_option trace.grind.cutsat.assert true in -- cutsat should **not** process the following constraints
example (x y z : Int) (h1 : 2 * x < 3 * y) (h2 : -4 * x + 2 * z < 0) : ¬ 12*y - 4* z < 0 := by
grind -cutsat -- `linarith` module solves it
```
* [#8775](https://github.com/leanprover/lean4/pull/8775) adds a `grind` normalization theorem for `Int.negSucc`. Example:
```lean
example (p : Int) (n : Nat) (hmp : Int.negSucc (n + 1) + 1 = p)
(hnm : Int.negSucc (n + 1 + 1) + 1 = Int.negSucc (n + 1)) : p = Int.negSucc n := by
grind
```
* [#8776](https://github.com/leanprover/lean4/pull/8776) ensures that user provided `natCast` application are properly
internalized in the grind cutsat module.
* [#8777](https://github.com/leanprover/lean4/pull/8777) implements basic `Field` support in the commutative ring module
in `grind`. It is just division by numerals for now. Examples:
```lean
open Lean Grind
* [#8780](https://github.com/leanprover/lean4/pull/8780) makes Lean code generation respect the module name provided
through `lean --setup`.
* [#8786](https://github.com/leanprover/lean4/pull/8786) improves the support for fields in `grind`. New supported
examples:
```lean
example [Field α] [IsCharP α 0] (x : α) : x ≠ 0 → (4 / x)⁻¹ * ((3 * x^3) / x)^2 * ((1 / (2 * x))⁻¹)^3 = 18 * x^8 := by grind
example [Field α] (a : α) : 2 * a ≠ 0 → 1 / a + 1 / (2 * a) = 3 / (2 * a) := by grind
example [Field α] [IsCharP α 0] (a : α) : 1 / a + 1 / (2 * a) = 3 / (2 * a) := by grind
example [Field α] [IsCharP α 0] (a b : α) : 2*b - a = a + b → 1 / a + 1 / (2 * a) = 3 / b := by grind
example [Field α] [NoNatZeroDivisors α] (a : α) : 1 / a + 1 / (2 * a) = 3 / (2 * a) := by grind
example [Field α] {x y z w : α} : x / y = z / w → y ≠ 0 → w ≠ 0 → x * w = z * y := by grind
example [Field α] (a : α) : a = 0 → a ≠ 1 := by grind
example [Field α] (a : α) : a = 0 → a ≠ 1 - a := by grind
```
* [#8789](https://github.com/leanprover/lean4/pull/8789) implements the Rabinowitsch transformation for `Field`
disequalities in `grind`. For example, this transformation is necessary
for solving:
```lean
example [Field α] (a : α) : a^2 = 0 → a = 0 := by
grind
```
* [#8791](https://github.com/leanprover/lean4/pull/8791) ensures the `grind linarith` module is activated for any type
that implements only `IntModule`. That is, the type does not need to be
a preorder anymore.
* [#8792](https://github.com/leanprover/lean4/pull/8792) makes the `clear_value` tactic preserve the order of variables
in the local context. This is done by adding
`Lean.MVarId.withRevertedFrom`, which reverts all local variables
starting from a given variable, rather than only the ones that depend on
it.
* [#8794](https://github.com/leanprover/lean4/pull/8794) adds a module `Lean.Util.CollectLooseBVars` with a function
`Expr.collectLooseBVars` that collects the set of loose bound variables
in an expression. That is, it computes the set of all `i` such that
`e.hasLooseBVar i` is true.
* [#8795](https://github.com/leanprover/lean4/pull/8795) ensures that auxliary terms are not internalized by the ring and
linarith modules.
* [#8796](https://github.com/leanprover/lean4/pull/8796) fixes `grind linarith` term internalization and support for
`HSMul`.
* [#8798](https://github.com/leanprover/lean4/pull/8798) adds the following instance
```
instance [Field α] [LinearOrder α] [Ring.IsOrdered α] : IsCharP α 0
```
The goal is to ensure we do not perform unnecessary case-splits in our
test suite.
* [#8804](https://github.com/leanprover/lean4/pull/8804) implements first-class support for nondependent let expressions
in the elaborator; recall that a let expression `let x : t := v; b` is
called *nondependent* if `fun x : t => b` typechecks, and the notation
for a nondependent let expression is `have x := v; b`. Previously we
encoded `have` using the `letFun` function, but now we make use of the
`nondep` flag in the `Expr.letE` constructor for the encoding. This has
been given full support throughout the metaprogramming interface and the
elaborator. Key changes to the metaprogramming interface:
- Local context `ldecl`s with `nondep := true` are generally treated as
`cdecl`s. This is because in the body of a `have` expression the
variable is opaque. Functions like `LocalDecl.isLet` by default return
`false` for nondependent `ldecl`s. In the rare case where it is needed,
they take an additional optional `allowNondep : Bool` flag (defaults to
`false`) if the variable is being processed in a context where the value
is relevant.
- Functions such as `mkLetFVars` by default generalize nondependent let
variables and create lambda expressions for them. The
`generalizeNondepLet` flag (default true) can be set to false if `have`
expressions should be produced instead. **Breaking change:** Uses of
`letLambdaTelescope`/`mkLetFVars` need to use `generalizeNondepLet :=
false`. See the next item.
- There are now some mapping functions to make telescoping operations
more convenient. See `mapLetTelescope` and `mapLambdaLetTelescope`.
There is also `mapLetDecl` as a counterpart to `withLetDecl` for
creating `let`/`have` expressions.
- Important note about the `generalizeNondepLet` flag: it should only be
used for variables in a local context that the metaprogram "owns". Since
nondependent let variables are treated as constants in most cases, the
`value` field might refer to variables that do not exist, if for example
those variables were cleared or reverted. Using `mapLetDecl` is always
fine.
- The simplifier will cache its let dependence calculations in the
nondep field of let expressions.
- The `intro` tactic still produces *dependent* local variables. Given
that the simplifier will transform lets into haves, it would be
surprising if that would prevent `intro` from creating a local variable
whose value cannot be used.
* [#8809](https://github.com/leanprover/lean4/pull/8809) introduces the basic theory of ordered modules over Nat (i.e.
without subtraction), for `grind`. We'll solve problems here by
embedding them in the `IntModule` envelope.
* [#8810](https://github.com/leanprover/lean4/pull/8810) implements equality elimination in `grind linarith`. The current
implementation supports only `IntModule` and `IntModule` +
`NoNatZeroDivisors`
* [#8813](https://github.com/leanprover/lean4/pull/8813) adds some basic lemmas about `grind` internal notions of
modules.
* [#8815](https://github.com/leanprover/lean4/pull/8815) refactors the way simp arguments are elaborated: Instead of
changing the `SimpTheorems` structure as we go, this elaborates each
argument to a more declarative description of what it does, and then
apply those. This enables more interesting checks of simp arguments that
need to happen in the context of the eventually constructed simp context
(the checks in #8688), or after simp has run (unused argument linter
#8901).
* [#8828](https://github.com/leanprover/lean4/pull/8828) extends the experimental module system to support resolving
private names imported (transitively) through `import all`.
* [#8835](https://github.com/leanprover/lean4/pull/8835) defines the embedding of a `CommSemiring` into its `CommRing`
envelope, injective when the `CommSemiring` is cancellative. This will
be used by `grind` to prove results in `Nat`.
* [#8836](https://github.com/leanprover/lean4/pull/8836) generalizes #8835 to the noncommutative case, allowing us to
embed a `Lean.Grind.Semiring` into a `Lean.Grind.Ring`.
* [#8845](https://github.com/leanprover/lean4/pull/8845) implements the proof-by-reflection infrastructure for embedding
semiring terms as ring ones.
* [#8847](https://github.com/leanprover/lean4/pull/8847) relaxes the assumptions for `Lean.Grind.IsCharP` from `Ring` to
`Semiring`, and provides an alternative constructor for rings.
* [#8848](https://github.com/leanprover/lean4/pull/8848) generalizes the internal `grind` instance
```
instance [Field α] [LinearOrder α] [Ring.IsOrdered α] : IsCharP α 0
```
to
```
instance [Ring α] [Preorder α] [Ring.IsOrdered α] : IsCharP α 0
```
* [#8855](https://github.com/leanprover/lean4/pull/8855) refactors `Lean.Grind.NatModule/IntModule/Ring.IsOrdered`.
* [#8859](https://github.com/leanprover/lean4/pull/8859) shows the equivalence between `Lean.Grind.NatModule.IsOrdered`
and `Lean.Grind.IntModule.IsOrdered` over an `IntModule`.
* [#8865](https://github.com/leanprover/lean4/pull/8865) allows `simp` to recognize and warn about simp lemmas that are
likely looping in the current simp set. It does so automatically
whenever simplification fails with the dreaded “max recursion depth”
error fails, but it can be made to do it always with `set_option
linter.loopingSimpArgs true`. This check is not on by default because it
is somewhat costly, and can warn about simp calls that still happen to
work.
* [#8874](https://github.com/leanprover/lean4/pull/8874) skips attempting to compute a module name from the file name and
root directory (i.e., `lean -R`) if a name is already provided via `lean
--setup`.
* [#8880](https://github.com/leanprover/lean4/pull/8880) makes `simp` consult its own cache more often, to avoid
replicating work.
* [#8882](https://github.com/leanprover/lean4/pull/8882) adds `@[expose]` annotations to terms that appear in `grind`
proof certificates, so `grind` can be used in the module system. It's
possible/likely that I haven't identified all of them yet.
* [#8890](https://github.com/leanprover/lean4/pull/8890) adds docstrings to the `Lean.Grind` algebra type classes, as
these will appear in the reference manual explaining how to extend
`grind` algebra solvers to new types. Also removes some redundant
fields.
* [#8892](https://github.com/leanprover/lean4/pull/8892) corrects the pretty printing of `grind` modifiers. Previously
`@[grind →]` was being pretty printed as `@[grind→ ]` (Space on the
right of the symbol, rather than left.) This fixes the pretty printing
of attributes, and preserves the presence of spaces after the symbol in
the output of `grind?`.
* [#8893](https://github.com/leanprover/lean4/pull/8893) fixes a bug in the `dvd` propagation function in cutsat.
* [#8901](https://github.com/leanprover/lean4/pull/8901) adds a linter (`linter.unusedSimpArgs`) that complains when a
simp argument (`simp [foo]`) is unused. It should do the right thing if
the `simp` invocation is run multiple times, e.g. inside `all_goals`. It
does not trigger when the `simp` call is inside a macro. The linter
message contains a clickable hint to remove the simp argument.
* [#8903](https://github.com/leanprover/lean4/pull/8903) makes sure that the local instance cache calculation applies more
reductions. In #2199 there was an issue where metavariables could
prevent local variables from being considered as local instances. We use
a slightly different approach that ensures that, for example, `let`s at
the ends of telescopes do not cause similar problems. These reductions
were already being calculated, so this does not require any additional
work to be done.
* [#8909](https://github.com/leanprover/lean4/pull/8909) refactors the `NoNatZeroDivisors` to make sure it will work with
the new `Semiring` support.
* [#8910](https://github.com/leanprover/lean4/pull/8910) adds the `NoNatZeroDivisors` instance for `OfSemiring.Q α`
* [#8913](https://github.com/leanprover/lean4/pull/8913) cleans up `grind`'s internal order type classes, removing
unnecessary duplication.
* [#8914](https://github.com/leanprover/lean4/pull/8914) modifies `let` and `have` term syntaxes to be consistent with
each other. Adds configuration options; for example, `have` is
equivalent to `let +nondep`, for *nondependent* lets. Other options
include `+usedOnly` (for `let_tmp`), `+zeta` (for `letI`/`haveI`), and
`+postponeValue` (for `let_delayed`). There is also `let (eq := h) x :=
v; b` for introducing `h : x = v` when elaborating `b`. The `eq` option
works for pattern matching as well, for example `let (eq := h) (x, y) :=
p; b`.
* [#8918](https://github.com/leanprover/lean4/pull/8918) fixes the `guard_msgs.diff` default behavior so that the default
specified in the option definition is actually used everywhere.
* [#8921](https://github.com/leanprover/lean4/pull/8921) implements support for (commutative) semirings in `grind`. It
uses the Grothendieck completion to construct a (commutative) ring
`Lean.Grind.Ring.OfSemiring.Q α` from a (commutative) semiring `α`. This
construction is mostly useful for semirings that implement
`AddRightCancel α`. Otherwise, the function `toQ` is not injective.
Examples:
```lean
example (x y : Nat) : x^2*y = 1 → x*y^2 = y → y*x = 1 := by
grind
* [#8935](https://github.com/leanprover/lean4/pull/8935) adds the `+generalize` option to the `let` and `have` syntaxes.
For example, `have +generalize n := a + b; body` replaces all instances
of `a + b` in the expected type with `n` when elaborating `body`. This
can be likened to a term version of the `generalize` tactic. One can
combine this with `eq` in `have +generalize (eq := h) n := a + b; body`
as an analogue of `generalize h : n = a + b`.
* [#8937](https://github.com/leanprover/lean4/pull/8937) changes the output universe of the generated `below`
implementation for non-reflexive inductive types to match the
implementation for reflexive inductive types in #7639.
* [#8940](https://github.com/leanprover/lean4/pull/8940) introduces antitonicity lemmas that support the elaboration of
mixed inductive-coinductive predicates defined using the
`least_fixpoint` / `greatest_fixpoint` constructs.
* [#8943](https://github.com/leanprover/lean4/pull/8943) adds helper theorems for normalizing semirings that do not
implement `AddRightCancel`.
* [#8953](https://github.com/leanprover/lean4/pull/8953) implements support for normalization for commutative semirings
that do not implement `AddRightCancel`. Examples:
```lean
variable (R : Type u) [CommSemiring R]
* [#8954](https://github.com/leanprover/lean4/pull/8954) adds a procedure that efficiently transforms `let` expressions
into `have` expressions (`Meta.letToHave`). This is exposed as the
`let_to_have` tactic.
* [#8955](https://github.com/leanprover/lean4/pull/8955) fixes `Lean.MVarId.deltaLocalDecl`, which previously replaced
the local definition with the target.
* [#8957](https://github.com/leanprover/lean4/pull/8957) adds configuration options to the `let`/`have` tactic syntaxes.
For example, `let (eq := h) x := v` adds `h : x = v` to the local
context. The configuration options are the same as those for the
`let`/`have` term syntaxes.
* [#8958](https://github.com/leanprover/lean4/pull/8958) improves the case splitting strategy used in `grind`, and
ensures `grind` also considers simple `match`-conditions for
case-splitting. Example:
```lean
example (x y : Nat)
: 0 < match x, y with
| 0, 0 => 1
| _, _ => x + y := by -- x or y must be greater than 0
grind
```
* [#8959](https://github.com/leanprover/lean4/pull/8959) add instances showing that the Grothendieck (i.e. additive)
envelope of a semiring is an ordered ring if the original semiring is
ordered (and satisfies ExistsAddOfLE), and in this case the embedding is
monotone.
* [#8963](https://github.com/leanprover/lean4/pull/8963) embeds a NatModule into its IntModule completion, which is
injective when we have AddLeftCancel, and monotone when the modules are
ordered. Also adds some (failing) grind test cases that can be verified
once `grind` uses this embedding.
* [#8964](https://github.com/leanprover/lean4/pull/8964) adds `@[expose]` attributes to proof terms constructed by
`grind` that need to be evaluated in the kernel.
* [#8965](https://github.com/leanprover/lean4/pull/8965) revises @[grind] annotations on Nat bitwise operations.
* [#8968](https://github.com/leanprover/lean4/pull/8968) adds the following features to `simp`:
- A routine for simplifying `have` telescopes in a way that avoids
quadratic complexity arising from locally nameless expression
representations, like what #6220 did for `letFun` telescopes.
Furthermore, simp converts `letFun`s into `have`s (nondependent lets),
and we remove the #6220 routine since we are moving away from `letFun`
encodings of nondependent lets.
- A `+letToHave` configuration option (enabled by default) that converts
lets into haves when possible, when `-zeta` is set. Previously Lean
would need to do a full typecheck of the bodies of `let`s, but the
`letToHave` procedure can skip checking some subexpressions, and it
modifies the `let`s in an entire expression at once rather than one at a
time.
- A `+zetaHave` configuration option, to turn off zeta reduction of
`have`s specifically. The motivation is that dependent `let`s can only
be dsimped by let, so zeta reducing just the dependent lets is a
reasonable way to make progress. The `+zetaHave` option is also added to
the meta configuration.
- When `simp` is zeta reducing, it now uses an algorithm that avoids
complexity quadratic in the depth of the let telescope.
- Additionally, the zeta reduction routines in `simp`, `whnf`, and
`isDefEq` now all are consistent with how they apply the `zeta`,
`zetaHave`, and `zetaUnused` configurations.
* [#8971](https://github.com/leanprover/lean4/pull/8971) fixes `linter.simpUnusedSimpArgs` to check the syntax kind, to
not fire on `simp` calls behind macros. Fixes #8969
* [#8973](https://github.com/leanprover/lean4/pull/8973) refactors the juggling of universes in the linear
`noConfusionType` construction: Instead of using `PUnit.{…} → ` in the
to get the branches of `withCtorType` to the same universe level, we use
`PULift`.
* [#8978](https://github.com/leanprover/lean4/pull/8978) updates the `solveMonoStep` function used in the `monotonicity`
tactic to check for definitional equality between the current goal and
the monotonicity proof obtained from a recursive call. This ensures
soundness by preventing incorrect applications when
`Lean.Order.PartialOrder` instances differ—an issue that can arise with
`mutual` blocks defined using the `partial_fixpoint` keyword, where
different `Lean.Order.CCPO` structures may be involved.
* [#8980](https://github.com/leanprover/lean4/pull/8980) improves the consistency of error message formatting by
rendering addenda of several existing error messages as labeled notes
and hints.
* [#8983](https://github.com/leanprover/lean4/pull/8983) fixes a bug in congruence proof generation in `grind` for
over-applied functions.
* [#8986](https://github.com/leanprover/lean4/pull/8986) improves the error messages produced by invalid projections and
field notation. It also adds a hint to the "function expected" error
message noting the argument to which the term is being applied, which
can be helpful for debugging spurious "function expected" messages
actually caused by syntax errors.
* [#8991](https://github.com/leanprover/lean4/pull/8991) adds some missing `ToInt.X` type class instances for `grind`.
* [#8995](https://github.com/leanprover/lean4/pull/8995) introduces a Hoare logic for monadic programs in
`Std.Do.Triple`, and assorted tactics:
* `mspec` for applying Hoare triple specifications
* `mvcgen` to turn a Hoare triple proof obligation `⦃P⦄ prog ⦃Q⦄` into
pure verification conditions (i.e., without any traces of Hoare triples
or weakest preconditions reminiscent of `prog`). The resulting
verification conditions in the stateful logic of `Std.Do.SPred` can be
discharged manually with the tactics coming with its custom proof mode
or with automation such as `simp` and `grind`.
* [#8996](https://github.com/leanprover/lean4/pull/8996) provides the remaining instances for the `Lean.Grind.ToInt`
type classes.
* [#9004](https://github.com/leanprover/lean4/pull/9004) ensures that type-class synthesis failure errors in interpolated
strings are displayed at the interpolant at which they occurred.
* [#9005](https://github.com/leanprover/lean4/pull/9005) changes the definition of `Lean.Grind.ToInt.OfNat`, introducing
a `wrap` on the right-hand-side.
* [#9008](https://github.com/leanprover/lean4/pull/9008) implements the basic infrastructure for the generic `ToInt`
support in `cutsat`.
* [#9022](https://github.com/leanprover/lean4/pull/9022) completes the generic `toInt` infrastructure for embedding terms
implementing the `ToInt` type classes into `Int`.
* [#9026](https://github.com/leanprover/lean4/pull/9026) implements support for (non strict) `ToInt` inequalities in
`grind cutsat`. `grind cutsat` can solve simple problems such as:
```lean
example (a b c : Fin 11) : a ≤ b → b ≤ c → a ≤ c := by
grind
* [#9030](https://github.com/leanprover/lean4/pull/9030) fixes a couple of bootstrapping-related hiccups in the newly
added `Std.Do` module. More precisely,
* [#9035](https://github.com/leanprover/lean4/pull/9035) extends the list of acceptable characters to all the french ones
as well as some others,
by adding characters from the Latin-1-Supplement add Latin-Extended-A
unicode block.
* [#9038](https://github.com/leanprover/lean4/pull/9038) adds test cases for the VC generator and implements a few small
and tedious fixes to ensure they pass.
* [#9041](https://github.com/leanprover/lean4/pull/9041) makes `mspec` detect more viable assignments by `rfl` instead of
generating a VC.
* [#9044](https://github.com/leanprover/lean4/pull/9044) adjusts the experimental module system to make `private` the
default visibility modifier in `module`s, introducing `public` as a new
modifier instead. `public section` can be used to revert the default for
an entire section, though this is more intended to ease gradual adoption
of the new semantics such as in `Init` (and soon `Std`) where they
should be replaced by a future decl-by-decl re-review of visibilities.
* [#9045](https://github.com/leanprover/lean4/pull/9045) fixes a type error in `mvcgen` and makes it turn fewer natural
goals into synthetic opaque ones, so that tactics such as `trivial` may
instantiate them more easily.
* [#9048](https://github.com/leanprover/lean4/pull/9048) implements support for strict inequalities in the `ToInt`
adapter used in `grind cutsat`. Example:
```lean
example (a b c : Fin 11) : c ≤ 9 → a ≤ b → b < c → a < c + 1 := by
grind
```
* [#9050](https://github.com/leanprover/lean4/pull/9050) ensures the `ToInt` bounds are asserted for every `toInt a`
application internalized in `grind cutsat`.
* [#9051](https://github.com/leanprover/lean4/pull/9051) implements support for equalities and disequalities in `grind
cutsat`. We still have to improve the encoding. Examples:
```lean
example (a b c : Fin 11) : a ≤ 2 → b ≤ 3 → c = a + b → c ≤ 5 := by
grind
* [#9057](https://github.com/leanprover/lean4/pull/9057) introduces a simple variable-reordering heuristic for `cutsat`.
It is needed by the `ToInt` adapter to support finite types such as
`UInt64`. The current encoding into `Int` produces large coefficients,
which can enlarge the search space when an unfavorable variable order is
used. Example:
```lean
example (a b c : UInt64) : a ≤ 2 → b ≤ 3 → c - a - b = 0 → c ≤ 5 := by
grind
```
* [#9059](https://github.com/leanprover/lean4/pull/9059) adds helper theorems for normalizing coefficients in rings of
unknown characteristic.
* [#9062](https://github.com/leanprover/lean4/pull/9062) implements support for equations `<num> = 0` in rings and fields
of unknown characteristic. Examples:
```lean
example [Field α] (a : α) : (2 * a)⁻¹ = a⁻¹ / 2 := by grind
* [#9065](https://github.com/leanprover/lean4/pull/9065) improves the counterexamples produced by the `cutsat` procedure
in `grind` when using the `ToInt` gadget.
* [#9067](https://github.com/leanprover/lean4/pull/9067) adds a docstring for the `grind` tactic.
* [#9069](https://github.com/leanprover/lean4/pull/9069) implements support for the type class `LawfulEqCmp`. Examples:
```lean
example (a b c : Vector (List Nat) n)
: b = c → a.compareLex (List.compareLex compare) b = o → o = .eq → a = c := by
grind
* [#9073](https://github.com/leanprover/lean4/pull/9073) copies #9069 to handle `ReflCmp` the same way; we need to call
this in propagateUp rather than propagateDown.
* [#9074](https://github.com/leanprover/lean4/pull/9074) uses the commutative ring module to normalize nonlinear
polynomials in `grind cutsat`. Examples:
```lean
example (a b : Nat) (h₁ : a + 1 ≠ a * b * a) (h₂ : a * a * b ≤ a + 1) : b * a^2 < a + 1 := by
grind
* [#9076](https://github.com/leanprover/lean4/pull/9076) adds an unexpander for `OfSemiring.toQ`. This an auxiliary
function used by the `ring` module in `grind`, but we want to reduce the
clutter in the diagnostic information produced by `grind`. Example:
```
example [CommSemiring α] [AddRightCancel α] [IsCharP α 0] (x y : α)
: x^2*y = 1 → x*y^2 = y → x + y = 2 → False := by
grind
```
produces
```
[ring] Ring `Ring.OfSemiring.Q α` ▼
[basis] Basis ▼
[_] ↑x + ↑y + -2 = 0
[_] ↑y + -1 = 0
```
* [#9086](https://github.com/leanprover/lean4/pull/9086) deprecates `let_fun` syntax in favor of `have` and removes
`letFun` support from WHNF and `simp`.
* [#9087](https://github.com/leanprover/lean4/pull/9087) removes the `irreducible` attribute from `letFun`, which is one
step toward removing special `letFun` support; part of #9086.
````
````markdown
## Library
* [#8003](https://github.com/leanprover/lean4/pull/8003) adds a new monadic interface for `Async` operations.
* [#8072](https://github.com/leanprover/lean4/pull/8072) adds DNS functions to the standard library
* [#8109](https://github.com/leanprover/lean4/pull/8109) adds system information functions to the standard library
* [#8178](https://github.com/leanprover/lean4/pull/8178) provides a compact formula for the MSB of the sdiv. Most of the
work in the PR involves handling the corner cases of division
overflowing (e.g. `intMin / -1 = intMin`)
* [#8203](https://github.com/leanprover/lean4/pull/8203) adds trichotomy lemmas for unsigned and signed comparisons,
stating that only one of three cases may happen: either `x < y`, `x =
y`, or `x > y` (for both signed and unsigned comparisons). We use
explicit arguments so that users can write `rcases slt_trichotomy x y
with hlt | heq | hgt`.
* [#8205](https://github.com/leanprover/lean4/pull/8205) adds a simp lemma that simplifies T-division where the numerator
is a `Nat` into an E-division:
```lean
@[simp] theorem ofNat_tdiv_eq_ediv {a : Nat} {b : Int} : (a : Int).tdiv b = a / b :=
tdiv_eq_ediv_of_nonneg (by simp)
```
* [#8210](https://github.com/leanprover/lean4/pull/8210) adds an equivalence relation to tree maps akin to the existing
one for hash maps. In order to get many congruence lemmas to eventually
use for defining functions on extensional tree maps, almost all of the
remaining tree map functions have also been given lemmas to relate them
to list functions, although these aren't currently used to prove lemmas
other than congruence lemmas.
* [#8253](https://github.com/leanprover/lean4/pull/8253) adds `toInt_smod` and auxiliary lemmas necessary for its proof
(`msb_intMin_umod_neg_of_msb_true`,
`msb_neg_umod_neg_of_msb_true_of_msb_true`, `toInt_dvd_toInt_iff`,
`toInt_dvd_toInt_iff_of_msb_true_msb_false`,
`toInt_dvd_toInt_iff_of_msb_false_msb_true`,
`neg_toInt_neg_umod_eq_of_msb_true_msb_true`, `toNat_pos_of_ne_zero`,
`toInt_umod_neg_add`, `toInt_sub_neg_umod` and
`BitVec.[lt_of_msb_false_of_msb_true, msb_umod_of_msb_false_of_ne_zero`,
`neg_toInt_neg]`)
* [#8420](https://github.com/leanprover/lean4/pull/8420) provides the iterator combinator `drop` that transforms any
iterator into one that drops the first `n` elements.
* [#8534](https://github.com/leanprover/lean4/pull/8534) fixes `IO.FS.realPath` on windows to take symbolic links into
account.
* [#8545](https://github.com/leanprover/lean4/pull/8545) provides the means to reason about "equivalent" iterators.
Simply speaking, two iterators are equivalent if they behave the same as
long as consumers do not introspect their states.
* [#8546](https://github.com/leanprover/lean4/pull/8546) adds a new `BitVec.clz` operation and a corresponding `clz`
circuit to `bv_decide`, allowing to bitblast the count leading zeroes
operation. The AIG circuit is linear in the number of bits of the
original expression, making the bitblasting convenient wrt. rewriting.
`clz` is common in numerous compiler intrinsics (see
[here](https://clang.llvm.org/docs/LanguageExtensions.html#intrinsics-support-within-constant-expressions))
and architectures (see
[here](https://en.wikipedia.org/wiki/Find_first_set)).
* [#8573](https://github.com/leanprover/lean4/pull/8573) avoids the likely unexpected behavior of `removeDirAll` to
delete through symlinks and adds the new function
`IO.FS.symlinkMetadata`.
* [#8585](https://github.com/leanprover/lean4/pull/8585) makes the lemma `BitVec.extractLsb'_append_eq_ite` more usable
by using the "simple case" more often, and uses this simplification to
make `BitVec.extractLsb'_append_eq_of_add_lt` stronger, renaming it to
`BitVec.extractLsb'_append_eq_of_add_le`.
* [#8587](https://github.com/leanprover/lean4/pull/8587) adjusts the grind annotation on
`Std.HashMap.map_fst_toList_eq_keys` and variants, so `grind` can reason
bidirectionally between `m.keys` and `m.toList`.
* [#8590](https://github.com/leanprover/lean4/pull/8590) adds `@[grind]` to `getElem?_pos` and variants.
* [#8615](https://github.com/leanprover/lean4/pull/8615) provides a special empty iterator type. Although its behavior
can be emulated with a list iterator (for example), having a special
type has the advantage of being easier to optimize for the compiler.
* [#8620](https://github.com/leanprover/lean4/pull/8620) removes the `NatCast (Fin n)` global instance (both the direct
instance, and the indirect one via `Lean.Grind.Semiring`), as that
instance causes `x < n` (for `x : Fin k`, `n : Nat`) to be
elaborated as `x < ↑n` rather than `↑x < n`, which is undesirable. Note
however that in Mathlib this happens anyway!
* [#8629](https://github.com/leanprover/lean4/pull/8629) replaces special, more optimized `IteratorLoop` instances, for
which no lawfulness proof has been made, with the verified default
implementation. The specialization of the loop/collect implementations
is low priority, but having lawfulness instances for all iterators is
important for verification.
* [#8631](https://github.com/leanprover/lean4/pull/8631) generalizes `Std.Sat.AIG. relabel(Nat)_unsat_iff` to allow the
AIG type to be empty. We generalize the proof, by showing that in the
case when `α` is empty, the environment doesn't matter, since all
environments `α → Bool` are isomorphic.
* [#8640](https://github.com/leanprover/lean4/pull/8640) adds `BitVec.setWidth'_eq` to `bv_normalize` such that
`bv_decide` can reduce it and solve lemmas involving `setWidth'_eq`
* [#8669](https://github.com/leanprover/lean4/pull/8669) makes `unsafeBaseIO` `noinline`. The new compiler is better at
optimizing `Result`-like types, which can cause the final operation in
an `unsafeBaseIO` block to be dropped, since `unsafeBaseIO` is
discarding the state.
* [#8678](https://github.com/leanprover/lean4/pull/8678) makes the LHS of `isSome_finIdxOf?` and `isNone_finIdxOf?` more
general.
* [#8703](https://github.com/leanprover/lean4/pull/8703) corrects the `IteratorLoop` instance in `DropWhile`, which
previously triggered for arbitrary iterator types.
* [#8719](https://github.com/leanprover/lean4/pull/8719) adds grind annotations for
List/Array/Vector.eraseP/erase/eraseIdx. It also adds some missing
lemmas.
* [#8721](https://github.com/leanprover/lean4/pull/8721) adds the types `Std.ExtDTreeMap`, `Std.ExtTreeMap` and
`Std.ExtTreeSet` of extensional tree maps and sets. These are very
similar in construction to the existing extensional hash maps with one
exception: extensional tree maps and sets provide all functions from
regular tree maps and sets. This is possible because in contrast to hash
maps, tree maps are always ordered.
* [#8734](https://github.com/leanprover/lean4/pull/8734) adds the missing instance
```
instance decidableExistsFin (P : Fin n → Prop) [DecidablePred P] : Decidable (∃ i, P i)
```
* [#8740](https://github.com/leanprover/lean4/pull/8740) introduces associativity rules and preservation of `(umul, smul,
uadd, sadd)Overflow`flags.
* [#8741](https://github.com/leanprover/lean4/pull/8741) adds annotations for
`List/Array/Vector.find?/findSome?/idxOf?/findIdx?`.
* [#8742](https://github.com/leanprover/lean4/pull/8742) fixes a bug where the single-quote character `Char.ofNat 39`
would delaborate as `'''`, which causes a parse error if pasted back in
to the source code.
* [#8745](https://github.com/leanprover/lean4/pull/8745) adds a logic of stateful predicates `SPred` to `Std.Do` in order
to support reasoning about monadic programs. It comes with a dedicated
proof mode the tactics of which are accessible by importing
`Std.Tactic.Do`.
* [#8747](https://github.com/leanprover/lean4/pull/8747) adds grind annotations for \`List/Array/Vector.finRange\`
theorems.
* [#8748](https://github.com/leanprover/lean4/pull/8748) adds grind annotations for `Array/Vector.mapIdx` and `mapFinIdx`
theorems.
* [#8749](https://github.com/leanprover/lean4/pull/8749) adds grind annotations for `List/Array/Vector.ofFn` theorems and
additional `List.Impl` find operations.
* [#8750](https://github.com/leanprover/lean4/pull/8750) adds grind annotations for the
`List/Array/Vector.zipWith/zipWithAll/unzip` functions.
* [#8765](https://github.com/leanprover/lean4/pull/8765) adds grind annotations for `List.Perm`; involves a revision of
grind annotations for `List.countP/count` as well.
* [#8768](https://github.com/leanprover/lean4/pull/8768) introduces a `ForIn'` instance and a `size` function for
iterators in a minimal fashion. The `ForIn'` instance is not marked as
an instance because it is unclear which `Membership` relation is
sufficiently useful. The `ForIn'` instance existing as a `def` and
inducing the `ForIn` instance, it becomes possible to provide more
specialized `ForIn'` instances, with nice `Membership` relations, for
various types of iterators. The `size` function has no lemmas yet.
* [#8784](https://github.com/leanprover/lean4/pull/8784) introduces ranges that are polymorphic, in contrast to the
existing `Std.Range` which only supports natural numbers.
* [#8805](https://github.com/leanprover/lean4/pull/8805) continues adding `grind` annotations for `List/Array/Vector`
lemmas.
* [#8808](https://github.com/leanprover/lean4/pull/8808) adds the missing `le_of_add_left_le {n m k : Nat} (h : k + n ≤
m) : n ≤ m` and `le_add_left_of_le {n m k : Nat} (h : n ≤ m) : n ≤ k +
m`.
* [#8811](https://github.com/leanprover/lean4/pull/8811) adds theorems `BitVec.(toNat, toInt,
toFin)_shiftLeftZeroExtend`, completing the API for
`BitVec.shiftLeftZeroExtend`.
* [#8826](https://github.com/leanprover/lean4/pull/8826) corrects the definition of `Lean.Grind.NatModule`, which wasn't
previously useful.
* [#8827](https://github.com/leanprover/lean4/pull/8827) renames `BitVec.getLsb'` to `BitVec.getLsb`, now that older
deprecated definition occupying that name has been removed. (Similarly
for `BitVec.getMsb'`.)
* [#8829](https://github.com/leanprover/lean4/pull/8829) avoids importing all of `BitVec.Lemmas` and `BitVec.BitBlast`
into `UInt.Lemmas`. (They are still imported into `SInt.Lemmas`; this
seems much harder to avoid.)
* [#8830](https://github.com/leanprover/lean4/pull/8830) rearranges files under `Init.Grind`, moving out instances for
concrete algebraic types in `Init.GrindInstances`.
* [#8849](https://github.com/leanprover/lean4/pull/8849) adds `grind` annotations for `Sum`.
* [#8850](https://github.com/leanprover/lean4/pull/8850) adds `grind` annotations for `Prod`.
* [#8851](https://github.com/leanprover/lean4/pull/8851) adds grind annotations for `Function.curry`/`uncurry`.
* [#8852](https://github.com/leanprover/lean4/pull/8852) adds grind annotations for `Nat.testBit` and bitwise operations
on `Nat`.
* [#8853](https://github.com/leanprover/lean4/pull/8853) adds `grind` annotations relating `Nat.fold/foldRev/any/all` and
`Fin.foldl/foldr/foldlM/foldrM` to the corresponding operations on
`List.finRange`.
* [#8877](https://github.com/leanprover/lean4/pull/8877) adds grind annotations for
`List/Array/Vector.attach/attachWith/pmap`.
* [#8878](https://github.com/leanprover/lean4/pull/8878) adds grind annotations for List/Array/Vector monadic functions.
* [#8886](https://github.com/leanprover/lean4/pull/8886) adds `IO.FS.Stream.readToEnd` which parallels
`IO.FS.Handle.readToEnd` along with its upstream definitions (i.e.,
`readBinToEndInto` and `readBinToEnd`). It also removes an unnecessary
`partial` from `IO.FS.Handle.readBinToEnd`.
* [#8887](https://github.com/leanprover/lean4/pull/8887) generalizes `IO.FS.lines` with `IO.FS.Handle.lines` and adds the
parallel `IO.FS.Stream.lines` for streams.
* [#8897](https://github.com/leanprover/lean4/pull/8897) simplifies some `simp` calls.
* [#8905](https://github.com/leanprover/lean4/pull/8905) uses the linter from
https://github.com/leanprover/lean4/pull/8901 to clean up simp
arguments.
* [#8920](https://github.com/leanprover/lean4/pull/8920) uses the linter from #8901 to clean up more simp arguments,
completing #8905.
* [#8928](https://github.com/leanprover/lean4/pull/8928) adds a logic of stateful predicates `SPred` to `Std.Do` in order to
support reasoning about monadic programs. It comes with a dedicated
proof mode the tactics of which are accessible by importing
Std.Tactic.Do.
* [#8941](https://github.com/leanprover/lean4/pull/8941) adds `BitVec.(getElem, getLsbD, getMsbD)_(smod, sdiv, srem)`
theorems to complete the API for `sdiv`, `srem`, `smod`. Even though the
rhs is not particularly succinct (it's hard to find a meaning for what it
means to have "the n-th bit of the result of a signed division/modulo
operation"), these lemmas prevent the need to `unfold` operations.
* [#8947](https://github.com/leanprover/lean4/pull/8947) introduces polymorphic slices in their most basic form. They
come with a notation similar to the new range notation. `Subarray` is
now also a slice and can produce an iterator now. It is intended to
migrate more operations of `Subarray` to the `Slice` wrapper type to
make them available for slices of other types, too.
* [#8950](https://github.com/leanprover/lean4/pull/8950) adds `BitVec.toFin_(sdiv, smod, srem)` and `BitVec.toNat_srem`.
The strategy for the `rhs` of the `toFin_*` lemmas is to consider what
the corresponding `toNat_*` theorems do and push the `toFin` closerto
the operands. For the `rhs` of `BitVec.toNat_srem` I used the same
strategy as `BitVec.toNat_smod`.
* [#8967](https://github.com/leanprover/lean4/pull/8967) both adds initial `@[grind]` annotations for `BitVec`, and uses
`grind` to remove many proofs from `BitVec/Lemmas`.
* [#8974](https://github.com/leanprover/lean4/pull/8974) adds `BitVec.msb_(smod, srem)`.
* [#8977](https://github.com/leanprover/lean4/pull/8977) adds a generic `MonadLiftT Id m` instance. We do not implement a
`MonadLift Id m` instance because it would slow down instance resolution
and because it would create more non-canonical instances. This change
makes it possible to iterate over a pure iterator, such as `[1, 2,
3].iter`, in arbitrary monads.
* [#8992](https://github.com/leanprover/lean4/pull/8992) adds `PULift`, a more general form of `ULift` and `PLift` that
subsumes both.
* [#8995](https://github.com/leanprover/lean4/pull/8995) introduces a Hoare logic for monadic programs in
`Std.Do.Triple`, and assorted tactics:
* `mspec` for applying Hoare triple specifications
* `mvcgen` to turn a Hoare triple proof obligation `⦃P⦄ prog ⦃Q⦄` into
pure verification conditions (i.e., without any traces of Hoare triples
or weakest preconditions reminiscent of `prog`). The resulting
verification conditions in the stateful logic of `Std.Do.SPred` can be
discharged manually with the tactics coming with its custom proof mode
or with automation such as `simp` and `grind`.
* [#9027](https://github.com/leanprover/lean4/pull/9027) provides an iterator combinator that lifts the emitted values
into a higher universe level via `ULift`. This combinator is then used
to make the subarray iterators universe-polymorphic. Previously, they
were only available for `Subarray α` if `α : Type`.
* [#9030](https://github.com/leanprover/lean4/pull/9030) fixes a couple of bootstrapping-related hiccups in the newly
added `Std.Do` module. More precisely,
* [#9038](https://github.com/leanprover/lean4/pull/9038) adds test cases for the VC generator and implements a few small
and tedious fixes to ensure they pass.
* [#9049](https://github.com/leanprover/lean4/pull/9049) proves that the default `toList`, `toListRev` and `toArray`
functions on slices can be described in terms of the slice iterator.
Relying on new lemmas for the `uLift` and `attachWith` iterator
combinators, a more concrete description of said functions is given for
`Subarray`.
* [#9054](https://github.com/leanprover/lean4/pull/9054) corrects some inconsistencies in `TreeMap`/`HashMap` grind
annotations, for `isSome_get?_eq_contains` and `empty_eq_emptyc`.
* [#9055](https://github.com/leanprover/lean4/pull/9055) renames `Array/Vector.extract_push` to `extract_push_of_le`, and
replaces the lemma with one without a side condition.
* [#9058](https://github.com/leanprover/lean4/pull/9058) provides a `ToStream` instance for slices so that they can be
used in `for i in xs, j in ys do` notation.
* [#9075](https://github.com/leanprover/lean4/pull/9075) adds `BEq` instances for `ByteArray` and `FloatArray` (also a
`DecidableEq` instance for `ByteArray`).
## Compiler
* [#8594](https://github.com/leanprover/lean4/pull/8594) removes incorrect optimizations for strictOr/strictAnd from the
old compiler, along with deleting an incorrect test. In order to do
these optimizations correctly, nontermination analysis is required.
Arguably, the correct way to express these optimizations is by exposing
the implementation of strictOr/strictAnd to a nontermination-aware phase
of the compiler, and then having them follow from more general
transformations.
* [#8595](https://github.com/leanprover/lean4/pull/8595) wraps the invocation of the new compiler in `withoutExporting`.
This is not necessary for the old compiler because it uses more direct
access to the kernel environment.
* [#8602](https://github.com/leanprover/lean4/pull/8602) adds support to the new compiler for `Eq.recOn` (which is
supported by the old compiler but missing a test).
* [#8604](https://github.com/leanprover/lean4/pull/8604) adds support for the `compiler.extract_closed` option to the new
compiler, since this is used by the definition of `unsafeBaseIO`. We'll
revisit this once we switch to the new compiler and rethink its
relationship with IO.
* [#8614](https://github.com/leanprover/lean4/pull/8614) implements constant folding for `toNat` in the new compiler,
which improves parity with the old compiler.
* [#8616](https://github.com/leanprover/lean4/pull/8616) adds constant folding for `Nat.pow` to the new compiler,
following the same limits as the old compiler.
* [#8618](https://github.com/leanprover/lean4/pull/8618) implements LCNF constant folding for `Nat.nextPowerOfTwo`.
* [#8634](https://github.com/leanprover/lean4/pull/8634) makes `hasTrivialStructure?` return false for types whose
constructors have types that are erased, e.g. if they construct a
`Prop`.
* [#8636](https://github.com/leanprover/lean4/pull/8636) adds a function called `lean_setup_libuv` that initializes
required LIBUV components. It needs to be outside of
`lean_initialize_runtime_module` because it requires `argv` and `argc`
to work correctly.
* [#8647](https://github.com/leanprover/lean4/pull/8647) improves the precision of the new compiler's `noncomputable`
check for projections. There is no test included because while this was
reduced from Mathlib, the old compiler does not correctly handle the
reduced test case. It's not entirely clear to me if the check is passing
with the old compiler for correct reasons. A test will be added to the
new compiler's branch.
* [#8675](https://github.com/leanprover/lean4/pull/8675) increases the precision of the new compiler's non computable
check, particularly around irrelevant uses of `noncomputable` defs in
applications.
* [#8681](https://github.com/leanprover/lean4/pull/8681) adds an optimization to the LCNF simp pass where the
discriminant of a `cases` construct will only be mark used if it has a
non-default alternative.
* [#8683](https://github.com/leanprover/lean4/pull/8683) adds an optimization to the LCNF simp pass where the
discriminant of a single-alt cases is only marked as used if any param
is used.
* [#8709](https://github.com/leanprover/lean4/pull/8709) handles constants with erased types in `toMonoType`. It is much
harder to write a test case for this than you would think, because most
references to such types get replaced with `lcErased` earlier.
* [#8712](https://github.com/leanprover/lean4/pull/8712) optimizes let decls of an erased type to an erased value.
Specialization can create local functions that produce a Prop, and
there's no point in keeping them around.
* [#8716](https://github.com/leanprover/lean4/pull/8716) makes any type application of an erased term to be erased. This
comes up a bit more than one would expect in the implementation of Lean
itself.
* [#8717](https://github.com/leanprover/lean4/pull/8717) uses the fvar substitution mechanism to replace erased code.
This isn't entirely satisfactory, since LCNF's `.return` doesn't support
a general `Arg` (which has a `.erased` constructor), it only supports an
`FVarId`. This is in contrast to the IR `.ret`, which does support a
general `Arg`.
* [#8729](https://github.com/leanprover/lean4/pull/8729) changes LCNF's `FVarSubst` to use `Arg` rather than `Expr`. This
enforces the requirements on substitutions, which match the requirements
on `Arg`.
* [#8752](https://github.com/leanprover/lean4/pull/8752) fixes an issue where the `extendJoinPointContext` pass can lift
join points containing projections to the top level, as siblings of
`cases` constructs matching on other projections of the same base value.
This prevents the `structProjCases` pass from projecting both at once,
extending the lifetime of the parent value and breaking linearity at
runtime.
* [#8754](https://github.com/leanprover/lean4/pull/8754) changes the implementation of computed fields in the new
compiler, which should enable more optimizations (and remove a
questionable hack in `toLCNF` that was only suitable for bringup). We
convert `casesOn` to `cases` like we do for other inductive types, all
constructors get replaced by their real implementations late in the base
phase, and then the `cases` expression is rewritten to use the real
constructors in `toMono`.
* [#8758](https://github.com/leanprover/lean4/pull/8758) adds caching for the `hasTrivialStructure?` function for LCNF
types. This is one of the hottest small functions in the new compiler,
so adding a cache makes a lot of sense.
* [#8764](https://github.com/leanprover/lean4/pull/8764) changes the LCNF pass pipeline so checks are no longer run by
default after every pass, only after `init`, `saveBase`, `toMono` and
`saveMono`. This is a compile time improvement, and the utility of these
checks is decreased a bit after the decision to no longer attempt to
preserve types throughout compilation. They have not been a significant
way to discover issues during development of the new compiler.
* [#8802](https://github.com/leanprover/lean4/pull/8802) fixes a bug in `floatLetIn` where if one decl (e.g. a join
point) is floated into a case arm and it uses another decl (e.g. another
join point) that does not have any other existing uses in that arm, then
the second decl does not get floated in despite this being perfectly
legal. This was causing artificial array linearity issues in
`Lean.Elab.Tactic.BVDecide.LRAT.trim.useAnalysis`.
* [#8816](https://github.com/leanprover/lean4/pull/8816) adds constant folding for Char.ofNat in LCNF simp. This
implicitly relies on the representation of `Char` as `UInt32` rather
than making a separate `.char` literal type, which seems reasonable as
`Char` is erased by the trivial structure optimization in `toMono`.
* [#8822](https://github.com/leanprover/lean4/pull/8822) adds a cache for constructor info in toIR. This is called for
all constructors, projections, and cases alternatives, so it makes sense
to cache.
* [#8825](https://github.com/leanprover/lean4/pull/8825) improves IR generation for constructors of inductive types that
are represented by scalars. Surprisingly, this isn't required for
correctness, because the boxing pass will fix it up. The extra `unbox`
operation it inserts shouldn't matter when compiling to native code,
because it's trivial for a C compiler to optimize, but it does matter
for the interpreter.
* [#8831](https://github.com/leanprover/lean4/pull/8831) caches the result of `lowerEnumToScalarType`, which is used
heavily in LCNF to IR conversion.
* [#8885](https://github.com/leanprover/lean4/pull/8885) removes an old workaround around non-implemented C++11 features
in the thread finalization.
* [#8923](https://github.com/leanprover/lean4/pull/8923) implements `casesOn` for `Thunk` and `Task`. Since these are
builtin types, this needs to be special-cased in `toMono`.
* [#8952](https://github.com/leanprover/lean4/pull/8952) fixes the handling of the `never_extract` attribute in the
compiler's CSE pass. There is an interesting debate to be had about
exactly how hard the compiler should try to avoid duplicating anything
that transitively uses `never_extract`, but this is the simplest form
and roughly matches the check in the old compiler (although due to
different handling of local function decls in the two compilers, the
consequences might be slightly different).
* [#8956](https://github.com/leanprover/lean4/pull/8956) changes `toLCNF` to stop caching translations of expressions
upon seeing an expression marked `never_extract`. This is more
coarse-grained than it needs to be, but it is difficult to do any
better, as the new compiler's `Expr` cache is based on structural
identity (rather than the pointer identity of the old compiler).
* [#9003](https://github.com/leanprover/lean4/pull/9003) implements the validity check for the type of `main` in the new
compiler. There were no tests for this, so it slipped under the radar.
## Pretty Printing
* [#7954](https://github.com/leanprover/lean4/pull/7954) improves `pp.oneline`, where it now preserves tags when
truncating formatted syntax to a single line. Note that the `[...]`
continuation does not yet have any functionality to enable seeing the
untruncated syntax. Closes #3681.
* [#8617](https://github.com/leanprover/lean4/pull/8617) fixes (1) an issue where private names are not unresolved when
they are pretty printed, (2) an issue where in `pp.universes` mode names
were allowed to shadow local names, (3) an issue where in `match`
patterns constants shadowing locals wouldn't use `_root_`, and (4) an
issue where tactics might have an incorrect "try this" when
`pp.fullNames` is set. Adds more delaboration tests for name
unresolution.
* [#8626](https://github.com/leanprover/lean4/pull/8626) closes #3791, making sure that the Syntax formatter inserts
whitespace before and after comments in the leading and trailing text of
Syntax to avoid having comments comment out any following syntax, and to
avoid comments' lexical syntax from being interpreted as being part of
another syntax. If the text contains newlines before or after any
comments, they are formatted as hard newlines rather than soft newlines.
For example, `--` comments will have a hard newline after them. Note:
metaprograms generating Syntax with comments should be sure to include
newlines at the ends of `--` comments.
## Documentation
* [#8934](https://github.com/leanprover/lean4/pull/8934) adds explanations for a few errors concerning noncomputability,
redundant match alternatives, and invalid inductive declarations.
* [#8990](https://github.com/leanprover/lean4/pull/8990) adds missing docstrings for `grind`'s internal algebra
type classes, for inclusion in the reference manual.
* [#8998](https://github.com/leanprover/lean4/pull/8998) makes the docstrings related to `Format` and `Repr` have
consistent formatting and style, and adds missing docstrings.
## Server
* [#8105](https://github.com/leanprover/lean4/pull/8105) adds support for server-sided `RpcRef` reuse and fixes a bug
where trace nodes in the InfoView would close while the file was still
being processed.
* [#8511](https://github.com/leanprover/lean4/pull/8511) implements signature help support. When typing a function
application, editors with support for signature help will now display a
popup that designates the current (remaining) function type. This
removes the need to remember the function signature while typing the
function application, or having to constantly cycle between hovering
over the function identifier and typing the application. In VS Code, the
signature help can be triggered manually using `Ctrl+Shift+Space`.
* [#8654](https://github.com/leanprover/lean4/pull/8654) adds server-side support for a new module hierarchy component in
VS Code that can be used to navigate both the import tree of a module
and the imported-by tree of a module. Specifically, it implements new
requests `$/lean/prepareModuleHierarchy`,
`$/lean/moduleHierarchy/imports` and
`$/lean/moduleHierarchy/importedBy`. These requests are not supported by
standard LSP. Companion PR at
[leanprover/vscode-lean4#620](https://github.com/leanprover/vscode-lean4/pull/620).
* [#8699](https://github.com/leanprover/lean4/pull/8699) adds support to the server for the new module setup process by
changing how `lake setup-file` is used.
* [#8868](https://github.com/leanprover/lean4/pull/8868) ensures that code actions do not have to wait for the full file
to elaborate. This regression was accidentally introduced in #7665.
* [#9019](https://github.com/leanprover/lean4/pull/9019) fixes a bug where semantic highlighting would only highlight
keywords that started with an alphanumeric character. Now, it uses
`Lean.isIdFirst`.
## Lake
* [#7738](https://github.com/leanprover/lean4/pull/7738) makes memoization of built-in facets toggleable through a
`memoize` option on the facet configuration. Built-in facets which are
essentially aliases (e.g., `default`, `o`) have had memoization
disabled.
* [#8447](https://github.com/leanprover/lean4/pull/8447) makes use of `lean --setup` in Lake builds of Lean modules and
adds Lake support for the new `.olean` artifacts produced by the module
system.
* [#8613](https://github.com/leanprover/lean4/pull/8613) changes the Lake version syntax (to `5.0.0-src+<commit>`) to
ensure it is a well-formed SemVer,
* [#8656](https://github.com/leanprover/lean4/pull/8656) enables auto-implicits in the Lake math template. This resolves
an issue where new users sometimes set up a new project for math
formalization and then quickly realize that none of the code samples in
our official books and docs that use auto-implicits work in their
projects. With the introduction of [inlay hints for
auto-implicits](https://github.com/leanprover/lean4/pull/6768), we
consider the auto-implicit UX to be sufficiently usable that they can be
enabled by default in the math template.
Notably, this change does not affect Mathlib itself, which will proceed
to disable auto-implicits.
* [#8701](https://github.com/leanprover/lean4/pull/8701) exports `LeanOption` in the `Lean` namespace from the `Lake`
namespace. `LeanOption` was moved from `Lean` to `Lake` in #8447, which
can cause unnecessary breakage without this.
* [#8736](https://github.com/leanprover/lean4/pull/8736) partially reverts #8024 which introduced a significant Lake
performance regression during builds. Once the cause is discovered and
fixed, a similar PR will be made to revert this.
* [#8846](https://github.com/leanprover/lean4/pull/8846) reintroduces the basics of `lean --setup` integration into Lake
without the module computation which is still undergoing performance
debugging in #8787.
* [#8866](https://github.com/leanprover/lean4/pull/8866) upgrades the `math` template for `lake init` and `lake new` to
configures the new project to meet rigorous Mathlib maintenance
standards. In comparison with the previous version (now available as
`lake new ... math-lax`), this automatically provides:
* Strict linting options matching Mathlib.
* GitHub workflow for automatic upgrades to newer Lean and Mathlib
releases.
* Automatic release tagging for toolchain upgrades.
* API documentation generated by
[doc-gen4](https://github.com/leanprover/doc-gen4) and hosted on
`github.io`.
* README with some GitHub-specific instructions.
* [#8922](https://github.com/leanprover/lean4/pull/8922) introduces a local artifact cache for Lake. When enabled, Lake
will shared build artifacts (built files) across different instances of
the same package using an input- and content-addressed cache.
* [#8981](https://github.com/leanprover/lean4/pull/8981) removes Lake's usage of `lean -R` and `moduleNameOfFileName` to
pass module names to Lean. For workspace names, it now relies on
directly passing the module name through `lean --setup`. For
non-workspace modules passed to `lake lean` or `lake setup-file`, it
uses a fixed module name of `_unknown`.
* [#9068](https://github.com/leanprover/lean4/pull/9068) fixes some bugs with the local Lake artifact cache and cleans up
the surrounding API. It also adds the ability to opt-in to the cache on
packages without `enableArtifactCache` set using the
`LAKE_ARTIFACT_CACHE` environment variable.
* [#9081](https://github.com/leanprover/lean4/pull/9081) fixes a bug with Lake where the job monitor would sit on a
top-level build (e.g., `mathlib/Mathlib:default`) instead of reporting
module build progress.
* [#9101](https://github.com/leanprover/lean4/pull/9101) fixes a bug introduce by #9081 where the source file was dropped
from the module input trace and some entries were dropped from the
module job log.
## Other
* [#8702](https://github.com/leanprover/lean4/pull/8702) enhances the PR release workflow to create both short format and
SHA-suffixed release tags. Creates both pr-release-{PR_NUMBER} and
pr-release-{PR_NUMBER}-{SHORT_SHA} tags, generates separate releases for
both formats, adds separate GitHub status checks, and updates
Batteries/Mathlib testing branches to use SHA-suffixed tags for exact
commit traceability.
* [#8710](https://github.com/leanprover/lean4/pull/8710) pins the precise hash of softprops/action-gh-release to
* [#9033](https://github.com/leanprover/lean4/pull/9033) adds a Mathlib-like testing and feedback system for the
reference manual. Lean PRs will receive comments that reflect the status
of the language reference with respect to the PR.
* [#9092](https://github.com/leanprover/lean4/pull/9092) further updates release automation. The per-repository update
scripts `script/release_steps.py` now actually performs the tests,
rather than outputting a script for the release manager to run line by
line. It's been tested on `v4.21.0` (i.e. the easy case of a stable
release), and we'll debug its behaviour on `v4.22.0-rc1` tonight.
```` |
reference-manual/Manual/Releases/v4_0_0-m3.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
set_option linter.verso.markup.codeBlock false
#doc (Manual) "Lean 4.0.0-m3 (2022-01-31)" =>
%%%
tag := "release-v4.0.0-m3"
file := "v4.0.0-m3"
%%%
````markdown
This is the third milestone release of Lean 4, and the last planned milestone before an official
release. With almost 3000 commits improving and extending many parts of the system since the last
milestone, we are now close to completing all main features we have envisioned for Lean 4.
Contributors:
```
$ git shortlog -s -n v4.0.0-m2..v4.0.0-m3
1719 Leonardo de Moura
725 Sebastian Ullrich
149 Wojciech Nawrocki
93 Daniel Selsam
82 Gabriel Ebner
36 Joscha
35 Daniel Fabian
21 tydeu
14 Mario Carneiro
13 larsk21
12 Jannis Limperg
11 Chris Lovett
8 Henrik Böving
4 François G. Dorais
4 Siddharth
3 Joe Hendrix
3 Scott Morrison
3 ammkrn
2 Josh Levine
2 Mac
2 Mac Malone
2 Simon Hudon
2 pcpthm
1 Anders Christiansen Sørby
1 Andrei Cheremskoy
1 Arthur Paulino
1 Christian Pehle
1 Formally Verified Waffle Maker
1 Hunter Monroe
1 Jan Hrcek
1 Joshua Seaton
1 Kevin Buzzard
1 Lorenz Leutgeb
1 Mauricio Collares
1 Michael Burge
1 Paul Brinkmeier
1 Reijo Jaakkola
1 Severen Redwood
1 Siddharth Bhat
1 Tom Ball
1 Varun Gandhi
1 WojciechKarpiel
1 Xavier Noria
1 gabriel-doriath-dohler
1 zygi
1 Бакиновский Максим
```
```` |
reference-manual/Manual/Releases/v4_14_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.14.0 (2024-12-02)" =>
%%%
tag := "release-v4.14.0"
file := "v4.14.0"
%%%
````markdown
**Full Changelog**: https://github.com/leanprover/lean4/compare/v4.13.0...v4.14.0
### Language features, tactics, and metaprograms
* `structure` and `inductive` commands
* [#5517](https://github.com/leanprover/lean4/pull/5517) improves universe level inference for the resulting type of an `inductive` or `structure.` Recall that a `Prop`-valued inductive type is a syntactic subsingleton if it has at most one constructor and all the arguments to the constructor are in `Prop`. Such types have large elimination, so they could be defined in `Type` or `Prop` without any trouble. The way inference has changed is that if a type is a syntactic subsingleton with exactly one constructor, and the constructor has at least one parameter/field, then the `inductive`/`structure` command will prefer creating a `Prop` instead of a `Type`. The upshot is that the `: Prop` in `structure S : Prop` is often no longer needed. (With @arthur-adjedj).
* [#5842](https://github.com/leanprover/lean4/pull/5842) and [#5783](https://github.com/leanprover/lean4/pull/5783) implement a feature where the `structure` command can now define recursive inductive types:
```lean
structure Tree where
n : Nat
children : Fin n → Tree
def Tree.size : Tree → Nat
| {n, children} => Id.run do
let mut s := 0
for h : i in [0 : n] do
s := s + (children ⟨i, h.2⟩).size
pure s
```
* [#5814](https://github.com/leanprover/lean4/pull/5814) fixes a bug where Mathlib's `Type*` elaborator could lead to incorrect universe parameters with the `inductive` command.
* [#3152](https://github.com/leanprover/lean4/pull/3152) and [#5844](https://github.com/leanprover/lean4/pull/5844) fix bugs in default value processing for structure instance notation (with @arthur-adjedj).
* [#5399](https://github.com/leanprover/lean4/pull/5399) promotes instance synthesis order calculation failure from a soft error to a hard error.
* [#5542](https://github.com/leanprover/lean4/pull/5542) deprecates `:=` variants of `inductive` and `structure` (see breaking changes).
* **Application elaboration improvements**
* [#5671](https://github.com/leanprover/lean4/pull/5671) makes `@[elab_as_elim]` require at least one discriminant, since otherwise there is no advantage to this alternative elaborator.
* [#5528](https://github.com/leanprover/lean4/pull/5528) enables field notation in explicit mode. The syntax `@x.f` elaborates as `@S.f` with `x` supplied to the appropriate parameter.
* [#5692](https://github.com/leanprover/lean4/pull/5692) modifies the dot notation resolution algorithm so that it can apply `CoeFun` instances. For example, Mathlib has `Multiset.card : Multiset α →+ Nat`, and now with `m : Multiset α`, the notation `m.card` resolves to `⇑Multiset.card m`.
* [#5658](https://github.com/leanprover/lean4/pull/5658) fixes a bug where 'don't know how to synthesize implicit argument' errors might have the incorrect local context when the eta arguments feature is activated.
* [#5933](https://github.com/leanprover/lean4/pull/5933) fixes a bug where `..` ellipses in patterns made use of optparams and autoparams.
* [#5770](https://github.com/leanprover/lean4/pull/5770) makes dot notation for structures resolve using *all* ancestors. Adds a *resolution order* for generalized field notation. This is the order of namespaces visited during resolution when trying to resolve names. The algorithm to compute a resolution order is the commonly used C3 linearization (used for example by Python), which when successful ensures that immediate parents' namespaces are considered before more distant ancestors' namespaces. By default we use a relaxed version of the algorithm that tolerates inconsistencies, but using `set_option structure.strictResolutionOrder true` makes inconsistent parent orderings into warnings.
* **Recursion and induction principles**
* [#5619](https://github.com/leanprover/lean4/pull/5619) fixes functional induction principle generation to avoid over-eta-expanding in the preprocessing step.
* [#5766](https://github.com/leanprover/lean4/pull/5766) fixes structural nested recursion so that it is not confused when a nested type appears first.
* [#5803](https://github.com/leanprover/lean4/pull/5803) fixes a bug in functional induction principle generation when there are `let` bindings.
* [#5904](https://github.com/leanprover/lean4/pull/5904) improves functional induction principle generation to unfold aux definitions more carefully.
* [#5850](https://github.com/leanprover/lean4/pull/5850) refactors code for `Predefinition.Structural`.
* **Error messages**
* [#5276](https://github.com/leanprover/lean4/pull/5276) fixes a bug in "type mismatch" errors that would structurally assign metavariables during the algorithm to expose differences.
* [#5919](https://github.com/leanprover/lean4/pull/5919) makes "type mismatch" errors add type ascriptions to expose differences for numeric literals.
* [#5922](https://github.com/leanprover/lean4/pull/5922) makes "type mismatch" errors expose differences in the bodies of functions and pi types.
* [#5888](https://github.com/leanprover/lean4/pull/5888) improves the error message for invalid induction alternative names in `match` expressions (@josojo).
* [#5719](https://github.com/leanprover/lean4/pull/5719) improves `calc` error messages.
* [#5627](https://github.com/leanprover/lean4/pull/5627) and [#5663](https://github.com/leanprover/lean4/pull/5663) improve the **`#eval` command** and introduce some new features.
* Now results can be pretty printed if there is a `ToExpr` instance, which means **hoverable output**. If `ToExpr` fails, it then tries looking for a `Repr` or `ToString` instance like before. Setting `set_option eval.pp false` disables making use of `ToExpr` instances.
* There is now **auto-derivation** of `Repr` instances, enabled with the `pp.derive.repr` option (default to **true**). For example:
```lean
inductive Baz
| a | b
#eval Baz.a
-- Baz.a
```
It simply does `deriving instance Repr for Baz` when there's no way to represent `Baz`.
* The option `eval.type` controls whether or not to include the type in the output. For now the default is false.
* Now expressions such as `#eval do return 2`, where monad is unknown, work. It tries unifying the monad with `CommandElabM`, `TermElabM`, or `IO`.
* The classes `Lean.Eval` and `Lean.MetaEval` have been removed. These each used to be responsible for adapting monads and printing results. Now the `MonadEval` class is responsible for adapting monads for evaluation (it is similar to `MonadLift`, but instances are allowed to use default data when initializing state), and representing results is handled through a separate process.
* Error messages about failed instance synthesis are now more precise. Once it detects that a `MonadEval` class applies, then the error message will be specific about missing `ToExpr`/`Repr`/`ToString` instances.
* Fixes bugs where evaluating `MetaM` and `CoreM` wouldn't collect log messages.
* Fixes a bug where `let rec` could not be used in `#eval`.
* `partial` definitions
* [#5780](https://github.com/leanprover/lean4/pull/5780) improves the error message when `partial` fails to prove a type is inhabited. Add delta deriving.
* [#5821](https://github.com/leanprover/lean4/pull/5821) gives `partial` inhabitation the ability to create local `Inhabited` instances from parameters.
* **New tactic configuration syntax.** The configuration syntax for all core tactics has been given an upgrade. Rather than `simp (config := { contextual := true, maxSteps := 22})`, one can now write `simp +contextual (maxSteps := 22)`. Tactic authors can migrate by switching from `(config)?` to `optConfig` in tactic syntaxes and potentially deleting `mkOptionalNode` in elaborators. [#5883](https://github.com/leanprover/lean4/pull/5883), [#5898](https://github.com/leanprover/lean4/pull/5898), [#5928](https://github.com/leanprover/lean4/pull/5928), and [#5932](https://github.com/leanprover/lean4/pull/5932). (Tactic authors, see breaking changes.)
* `simp` tactic
* [#5632](https://github.com/leanprover/lean4/pull/5632) fixes the simpproc for `Fin` literals to reduce more consistently.
* [#5648](https://github.com/leanprover/lean4/pull/5648) fixes a bug in `simpa ... using t` where metavariables in `t` were not properly accounted for, and also improves the type mismatch error.
* [#5838](https://github.com/leanprover/lean4/pull/5838) fixes the docstring of `simp!` to actually talk about `simp!`.
* [#5870](https://github.com/leanprover/lean4/pull/5870) adds support for `attribute [simp ←]` (note the reverse direction). This adds the reverse of a theorem as a global simp theorem.
* `decide` tactic
* [#5665](https://github.com/leanprover/lean4/pull/5665) adds `decide!` tactic for using kernel reduction (warning: this is renamed to `decide +kernel` in a future release).
* `bv_decide` tactic
* [#5714](https://github.com/leanprover/lean4/pull/5714) adds inequality regression tests (@alexkeizer).
* [#5608](https://github.com/leanprover/lean4/pull/5608) adds `bv_toNat` tag for `toNat_ofInt` (@bollu).
* [#5618](https://github.com/leanprover/lean4/pull/5618) adds support for `at` in `ac_nf` and uses it in `bv_normalize` (@tobiasgrosser).
* [#5628](https://github.com/leanprover/lean4/pull/5628) adds udiv support.
* [#5635](https://github.com/leanprover/lean4/pull/5635) adds auxiliary bitblasters for negation and subtraction.
* [#5637](https://github.com/leanprover/lean4/pull/5637) adds more `getLsbD` bitblaster theory.
* [#5652](https://github.com/leanprover/lean4/pull/5652) adds umod support.
* [#5653](https://github.com/leanprover/lean4/pull/5653) adds performance benchmark for modulo.
* [#5655](https://github.com/leanprover/lean4/pull/5655) reduces error on `bv_check` to warning.
* [#5670](https://github.com/leanprover/lean4/pull/5670) adds `~~~(-x)` support.
* [#5673](https://github.com/leanprover/lean4/pull/5673) disables `ac_nf` by default.
* [#5675](https://github.com/leanprover/lean4/pull/5675) fixes context tracking in `bv_decide` counter example.
* [#5676](https://github.com/leanprover/lean4/pull/5676) adds an error when the LRAT proof is invalid.
* [#5781](https://github.com/leanprover/lean4/pull/5781) introduces uninterpreted symbols everywhere.
* [#5823](https://github.com/leanprover/lean4/pull/5823) adds `BitVec.sdiv` support.
* [#5852](https://github.com/leanprover/lean4/pull/5852) adds `BitVec.ofBool` support.
* [#5855](https://github.com/leanprover/lean4/pull/5855) adds `if` support.
* [#5869](https://github.com/leanprover/lean4/pull/5869) adds support for all the SMTLIB BitVec division/remainder operations.
* [#5886](https://github.com/leanprover/lean4/pull/5886) adds embedded constraint substitution.
* [#5918](https://github.com/leanprover/lean4/pull/5918) fixes loose mvars bug in `bv_normalize`.
* Documentation:
* [#5636](https://github.com/leanprover/lean4/pull/5636) adds remarks about multiplication.
* `conv` mode
* [#5861](https://github.com/leanprover/lean4/pull/5861) improves the `congr` conv tactic to handle "over-applied" functions.
* [#5894](https://github.com/leanprover/lean4/pull/5894) improves the `arg` conv tactic so that it can access more arguments and so that it can handle "over-applied" functions (it generates a specialized congruence lemma for the specific argument in question). Makes `arg 1` and `arg 2` apply to pi types in more situations. Adds negative indexing, for example `arg -2` is equivalent to the `lhs` tactic. Makes the `enter [...]` tactic show intermediate states like `rw`.
* **Other tactics**
* [#4846](https://github.com/leanprover/lean4/pull/4846) fixes a bug where `generalize ... at *` would apply to implementation details (@ymherklotz).
* [#5730](https://github.com/leanprover/lean4/pull/5730) upstreams the `classical` tactic combinator.
* [#5815](https://github.com/leanprover/lean4/pull/5815) improves the error message when trying to unfold a local hypothesis that is not a local definition.
* [#5862](https://github.com/leanprover/lean4/pull/5862) and [#5863](https://github.com/leanprover/lean4/pull/5863) change how `apply` and `simp` elaborate, making them not disable error recovery. This improves hovers and completions when the term has elaboration errors.
* `deriving` clauses
* [#5899](https://github.com/leanprover/lean4/pull/5899) adds declaration ranges for delta-derived instances.
* [#5265](https://github.com/leanprover/lean4/pull/5265) removes unused syntax in `deriving` clauses for providing arguments to deriving handlers (see breaking changes).
* [#5065](https://github.com/leanprover/lean4/pull/5065) upstreams and updates `#where`, a command that reports the current scope information.
* **Linters**
* [#5338](https://github.com/leanprover/lean4/pull/5338) makes the unused variables linter ignore variables defined in tactics by default now, avoiding performance bottlenecks.
* [#5644](https://github.com/leanprover/lean4/pull/5644) ensures that linters in general do not run on `#guard_msgs` itself.
* **Metaprogramming interface**
* [#5720](https://github.com/leanprover/lean4/pull/5720) adds `pushGoal`/`pushGoals` and `popGoal` for manipulating the goal state. These are an alternative to `replaceMainGoal` and `getMainGoal`, and with them you don't need to worry about making sure nothing clears assigned metavariables from the goal list between assigning the main goal and using `replaceMainGoal`. Modifies `closeMainGoalUsing`, which is like a `TacticM` version of `liftMetaTactic`. Now the callback is run in a context where the main goal is removed from the goal list, and the callback is free to modify the goal list. Furthermore, the `checkUnassigned` argument has been replaced with `checkNewUnassigned`, which checks whether the value assigned to the goal has any *new* metavariables, relative to the start of execution of the callback. Modifies `withCollectingNewGoalsFrom` to take the `parentTag` argument explicitly rather than indirectly via `getMainTag`. Modifies `elabTermWithHoles` to optionally take `parentTag?`.
* [#5563](https://github.com/leanprover/lean4/pull/5563) fixes `getFunInfo` and `inferType` to use `withAtLeastTransparency` rather than `withTransparency`.
* [#5679](https://github.com/leanprover/lean4/pull/5679) fixes `RecursorVal.getInduct` to return the name of major argument’s type. This makes "structure eta" work for nested inductives.
* [#5681](https://github.com/leanprover/lean4/pull/5681) removes unused `mkRecursorInfoForKernelRec`.
* [#5686](https://github.com/leanprover/lean4/pull/5686) makes discrimination trees index the domains of foralls, for better performance of the simplify and type class search.
* [#5760](https://github.com/leanprover/lean4/pull/5760) adds `Lean.Expr.name?` recognizer for `Name` expressions.
* [#5800](https://github.com/leanprover/lean4/pull/5800) modifies `liftCommandElabM` to preserve more state, fixing an issue where using it would drop messages.
* [#5857](https://github.com/leanprover/lean4/pull/5857) makes it possible to use dot notation in `m!` strings, for example `m!"{.ofConstName n}"`.
* [#5841](https://github.com/leanprover/lean4/pull/5841) and [#5853](https://github.com/leanprover/lean4/pull/5853) record the complete list of `structure` parents in the `StructureInfo` environment extension.
* **Other fixes or improvements**
* [#5566](https://github.com/leanprover/lean4/pull/5566) fixes a bug introduced in [#4781](https://github.com/leanprover/lean4/pull/4781) where heartbeat exceptions were no longer being handled properly. Now such exceptions are tagged with `runtime.maxHeartbeats` (@eric-wieser).
* [#5708](https://github.com/leanprover/lean4/pull/5708) modifies the proof objects produced by the proof-by-reflection tactics `ac_nf0` and `simp_arith` so that the kernel is less prone to reducing expensive atoms.
* [#5768](https://github.com/leanprover/lean4/pull/5768) adds a `#version` command that prints Lean's version information.
* [#5822](https://github.com/leanprover/lean4/pull/5822) fixes elaborator algorithms to match kernel algorithms for primitive projections (`Expr.proj`).
* [#5811](https://github.com/leanprover/lean4/pull/5811) improves the docstring for the `rwa` tactic.
### Language server, widgets, and IDE extensions
* [#5224](https://github.com/leanprover/lean4/pull/5224) fixes `WorkspaceClientCapabilities` to make `applyEdit` optional, in accordance with the LSP specification (@pzread).
* [#5340](https://github.com/leanprover/lean4/pull/5340) fixes a server deadlock when shutting down the language server and a desync between client and language server after a file worker crash.
* [#5560](https://github.com/leanprover/lean4/pull/5560) makes `initialize` and `builtin_initialize` participate in the call hierarchy and other requests.
* [#5650](https://github.com/leanprover/lean4/pull/5650) makes references in attributes participate in the call hierarchy and other requests.
* [#5666](https://github.com/leanprover/lean4/pull/5666) add auto-completion in tactic blocks without having to type the first character of the tactic, and adds tactic completion docs to tactic auto-completion items.
* [#5677](https://github.com/leanprover/lean4/pull/5677) fixes several cases where goal states were not displayed in certain text cursor positions.
* [#5707](https://github.com/leanprover/lean4/pull/5707) indicates deprecations in auto-completion items.
* [#5736](https://github.com/leanprover/lean4/pull/5736), [#5752](https://github.com/leanprover/lean4/pull/5752), [#5763](https://github.com/leanprover/lean4/pull/5763), [#5802](https://github.com/leanprover/lean4/pull/5802), and [#5805](https://github.com/leanprover/lean4/pull/5805) fix various performance issues in the language server.
* [#5801](https://github.com/leanprover/lean4/pull/5801) distinguishes theorem auto-completions from non-theorem auto-completions.
### Pretty printing
* [#5640](https://github.com/leanprover/lean4/pull/5640) fixes a bug where goal states in messages might print newlines as spaces.
* [#5643](https://github.com/leanprover/lean4/pull/5643) adds option `pp.mvars.delayed` (default false), which when false causes delayed assignment metavariables to pretty print with what they are assigned to. Now `fun x : Nat => ?a` pretty prints as `fun x : Nat => ?a` rather than `fun x ↦ ?m.7 x`.
* [#5711](https://github.com/leanprover/lean4/pull/5711) adds options `pp.mvars.anonymous` and `pp.mvars.levels`, which when false respectively cause expression metavariables and level metavariables to pretty print as `?_`.
* [#5710](https://github.com/leanprover/lean4/pull/5710) adjusts the `⋯` elaboration warning to mention `pp.maxSteps`.
* [#5759](https://github.com/leanprover/lean4/pull/5759) fixes the app unexpander for `sorryAx`.
* [#5827](https://github.com/leanprover/lean4/pull/5827) improves accuracy of binder names in the signature pretty printer (like in output of `#check`). Also fixes the issue where consecutive hygienic names pretty print without a space separating them, so we now have `(x✝ y✝ : Nat)` rather than `(x✝y✝ : Nat)`.
* [#5830](https://github.com/leanprover/lean4/pull/5830) makes sure all the core delaborators respond to `pp.explicit` when appropriate.
* [#5639](https://github.com/leanprover/lean4/pull/5639) makes sure name literals use escaping when pretty printing.
* [#5854](https://github.com/leanprover/lean4/pull/5854) adds delaborators for `<|>`, `<*>`, `>>`, `<*`, and `*>`.
### Library
* `Array`
* [#5687](https://github.com/leanprover/lean4/pull/5687) deprecates `Array.data`.
* [#5705](https://github.com/leanprover/lean4/pull/5705) uses a better default value for `Array.swapAt!`.
* [#5748](https://github.com/leanprover/lean4/pull/5748) moves `Array.mapIdx` lemmas to a new file.
* [#5749](https://github.com/leanprover/lean4/pull/5749) simplifies signature of `Array.mapIdx`.
* [#5758](https://github.com/leanprover/lean4/pull/5758) upstreams `Array.reduceOption`.
* [#5786](https://github.com/leanprover/lean4/pull/5786) adds simp lemmas for `Array.isEqv` and `BEq`.
* [#5796](https://github.com/leanprover/lean4/pull/5796) renames `Array.shrink` to `Array.take`, and relates it to `List.take`.
* [#5798](https://github.com/leanprover/lean4/pull/5798) upstreams `List.modify`, adds lemmas, relates to `Array.modify`.
* [#5799](https://github.com/leanprover/lean4/pull/5799) relates `Array.forIn` and `List.forIn`.
* [#5833](https://github.com/leanprover/lean4/pull/5833) adds `Array.forIn'`, and relates to `List`.
* [#5848](https://github.com/leanprover/lean4/pull/5848) fixes deprecations in `Init.Data.Array.Basic` to not recommend the deprecated constant.
* [#5895](https://github.com/leanprover/lean4/pull/5895) adds `LawfulBEq (Array α) ↔ LawfulBEq α`.
* [#5896](https://github.com/leanprover/lean4/pull/5896) moves `@[simp]` from `back_eq_back?` to `back_push`.
* [#5897](https://github.com/leanprover/lean4/pull/5897) renames `Array.back` to `back!`.
* `List`
* [#5605](https://github.com/leanprover/lean4/pull/5605) removes `List.redLength`.
* [#5696](https://github.com/leanprover/lean4/pull/5696) upstreams `List.mapIdx` and adds lemmas.
* [#5697](https://github.com/leanprover/lean4/pull/5697) upstreams `List.foldxM_map`.
* [#5701](https://github.com/leanprover/lean4/pull/5701) renames `List.join` to `List.flatten`.
* [#5703](https://github.com/leanprover/lean4/pull/5703) upstreams `List.sum`.
* [#5706](https://github.com/leanprover/lean4/pull/5706) marks `prefix_append_right_inj` as a simp lemma.
* [#5716](https://github.com/leanprover/lean4/pull/5716) fixes `List.drop_drop` addition order.
* [#5731](https://github.com/leanprover/lean4/pull/5731) renames `List.bind` and `Array.concatMap` to `flatMap`.
* [#5732](https://github.com/leanprover/lean4/pull/5732) renames `List.pure` to `List.singleton`.
* [#5742](https://github.com/leanprover/lean4/pull/5742) upstreams `ne_of_mem_of_not_mem`.
* [#5743](https://github.com/leanprover/lean4/pull/5743) upstreams `ne_of_apply_ne`.
* [#5816](https://github.com/leanprover/lean4/pull/5816) adds more `List.modify` lemmas.
* [#5879](https://github.com/leanprover/lean4/pull/5879) renames `List.groupBy` to `splitBy`.
* [#5913](https://github.com/leanprover/lean4/pull/5913) relates `for` loops over `List` with `foldlM`.
* `Nat`
* [#5694](https://github.com/leanprover/lean4/pull/5694) removes `instBEqNat`, which is redundant with `instBEqOfDecidableEq` but not defeq.
* [#5746](https://github.com/leanprover/lean4/pull/5746) deprecates `Nat.sum`.
* [#5785](https://github.com/leanprover/lean4/pull/5785) adds `Nat.forall_lt_succ` and variants.
* Fixed width integers
* [#5323](https://github.com/leanprover/lean4/pull/5323) redefine unsigned fixed width integers in terms of `BitVec`.
* [#5735](https://github.com/leanprover/lean4/pull/5735) adds `UIntX.[val_ofNat, toBitVec_ofNat]`.
* [#5790](https://github.com/leanprover/lean4/pull/5790) defines `Int8`.
* [#5901](https://github.com/leanprover/lean4/pull/5901) removes native code for `UInt8.modn`.
* `BitVec`
* [#5604](https://github.com/leanprover/lean4/pull/5604) completes `BitVec.[getMsbD|getLsbD|msb]` for shifts (@luisacicolini).
* [#5609](https://github.com/leanprover/lean4/pull/5609) adds lemmas for division when denominator is zero (@bollu).
* [#5620](https://github.com/leanprover/lean4/pull/5620) documents Bitblasting (@bollu)
* [#5623](https://github.com/leanprover/lean4/pull/5623) moves `BitVec.udiv/umod/sdiv/smod` after `add/sub/mul/lt` (@tobiasgrosser).
* [#5645](https://github.com/leanprover/lean4/pull/5645) defines `udiv` normal form to be `/`, resp. `umod` and `%` (@bollu).
* [#5646](https://github.com/leanprover/lean4/pull/5646) adds lemmas about arithmetic inequalities (@bollu).
* [#5680](https://github.com/leanprover/lean4/pull/5680) expands relationship with `toFin` (@tobiasgrosser).
* [#5691](https://github.com/leanprover/lean4/pull/5691) adds `BitVec.(getMSbD, msb)_(add, sub)` and `BitVec.getLsbD_sub` (@luisacicolini).
* [#5712](https://github.com/leanprover/lean4/pull/5712) adds `BitVec.[udiv|umod]_[zero|one|self]` (@tobiasgrosser).
* [#5718](https://github.com/leanprover/lean4/pull/5718) adds `BitVec.sdiv_[zero|one|self]` (@tobiasgrosser).
* [#5721](https://github.com/leanprover/lean4/pull/5721) adds `BitVec.(msb, getMsbD, getLsbD)_(neg, abs)` (@luisacicolini).
* [#5772](https://github.com/leanprover/lean4/pull/5772) adds `BitVec.toInt_sub`, simplifies `BitVec.toInt_neg` (@tobiasgrosser).
* [#5778](https://github.com/leanprover/lean4/pull/5778) prove that `intMin` the smallest signed bitvector (@alexkeizer).
* [#5851](https://github.com/leanprover/lean4/pull/5851) adds `(msb, getMsbD)_twoPow` (@luisacicolini).
* [#5858](https://github.com/leanprover/lean4/pull/5858) adds `BitVec.[zero_ushiftRight|zero_sshiftRight|zero_mul]` and cleans up BVDecide (@tobiasgrosser).
* [#5865](https://github.com/leanprover/lean4/pull/5865) adds `BitVec.(msb, getMsbD)_concat` (@luisacicolini).
* [#5881](https://github.com/leanprover/lean4/pull/5881) adds `Hashable (BitVec n)`
* `String`/`Char`
* [#5728](https://github.com/leanprover/lean4/pull/5728) upstreams `String.dropPrefix?`.
* [#5745](https://github.com/leanprover/lean4/pull/5745) changes `String.dropPrefix?` signature.
* [#5747](https://github.com/leanprover/lean4/pull/5747) adds `Hashable Char` instance
* `HashMap`
* [#5880](https://github.com/leanprover/lean4/pull/5880) adds interim implementation of `HashMap.modify`/`alter`
* **Other**
* [#5704](https://github.com/leanprover/lean4/pull/5704) removes `@[simp]` from `Option.isSome_eq_isSome`.
* [#5739](https://github.com/leanprover/lean4/pull/5739) upstreams material on `Prod`.
* [#5740](https://github.com/leanprover/lean4/pull/5740) moves `Antisymm` to `Std.Antisymm`.
* [#5741](https://github.com/leanprover/lean4/pull/5741) upstreams basic material on `Sum`.
* [#5756](https://github.com/leanprover/lean4/pull/5756) adds `Nat.log2_two_pow` (@spinylobster).
* [#5892](https://github.com/leanprover/lean4/pull/5892) removes duplicated `ForIn` instances.
* [#5900](https://github.com/leanprover/lean4/pull/5900) removes `@[simp]` from `Sum.forall` and `Sum.exists`.
* [#5812](https://github.com/leanprover/lean4/pull/5812) removes redundant `Decidable` assumptions (@FR-vdash-bot).
### Compiler, runtime, and FFI
* [#5685](https://github.com/leanprover/lean4/pull/5685) fixes help message flags, removes the `-f` flag and adds the `-g` flag (@James-Oswald).
* [#5930](https://github.com/leanprover/lean4/pull/5930) adds `--short-version` (`-V`) option to display short version (@juhp).
* [#5144](https://github.com/leanprover/lean4/pull/5144) switches all 64-bit platforms over to consistently using GMP for bignum arithmetic.
* [#5753](https://github.com/leanprover/lean4/pull/5753) raises the minimum supported Windows version to Windows 10 1903 (released May 2019).
### Lake
* [#5715](https://github.com/leanprover/lean4/pull/5715) changes `lake new math` to use `autoImplicit false` (@eric-wieser).
* [#5688](https://github.com/leanprover/lean4/pull/5688) makes `Lake` not create core aliases in the `Lake` namespace.
* [#5924](https://github.com/leanprover/lean4/pull/5924) adds a `text` option for `buildFile*` utilities.
* [#5789](https://github.com/leanprover/lean4/pull/5789) makes `lake init` not `git init` when inside git work tree (@haoxins).
* [#5684](https://github.com/leanprover/lean4/pull/5684) has Lake update a package's `lean-toolchain` file on `lake update` if it finds the package's direct dependencies use a newer compatible toolchain. To skip this step, use the `--keep-toolchain` CLI option. (See breaking changes.)
* [#6218](https://github.com/leanprover/lean4/pull/6218) makes Lake no longer automatically fetch GitHub cloud releases if the package build directory is already present (mirroring the behavior of the Reservoir cache). This prevents the cache from clobbering existing prebuilt artifacts. Users can still manually fetch the cache and clobber the build directory by running `lake build <pkg>:release`.
* [#6231](https://github.com/leanprover/lean4/pull/6231) improves the errors Lake produces when it fails to fetch a dependency from Reservoir. If the package is not indexed, it will produce a suggestion about how to require it from GitHub.
### Documentation
* [#5617](https://github.com/leanprover/lean4/pull/5617) fixes MSYS2 build instructions.
* [#5725](https://github.com/leanprover/lean4/pull/5725) points out that `OfScientific` is called with raw literals (@eric-wieser).
* [#5794](https://github.com/leanprover/lean4/pull/5794) adds a stub for application ellipsis notation (@eric-wieser).
### Breaking changes
* The syntax for providing arguments to deriving handlers has been removed, which was not used by any major Lean projects in the ecosystem. As a result, the `applyDerivingHandlers` now takes one fewer argument, `registerDerivingHandlerWithArgs` is now simply `registerDerivingHandler`, `DerivingHandler` no longer includes the unused parameter, and `DerivingHandlerNoArgs` has been deprecated. To migrate code, delete the unused `none` argument and use `registerDerivingHandler` and `DerivingHandler`. ([#5265](https://github.com/leanprover/lean4/pull/5265))
* The minimum supported Windows version has been raised to Windows 10 1903, released May 2019. ([#5753](https://github.com/leanprover/lean4/pull/5753))
* The `--lean` CLI option for `lake` was removed. Use the `LEAN` environment variable instead. ([#5684](https://github.com/leanprover/lean4/pull/5684))
* The `inductive ... :=`, `structure ... :=`, and `class ... :=` syntaxes have been deprecated in favor of the `... where` variants. The old syntax produces a warning, controlled by the `linter.deprecated` option. ([#5542](https://github.com/leanprover/lean4/pull/5542))
* The generated tactic configuration elaborators now land in `TacticM` to make use of the current recovery state. Commands that wish to elaborate configurations should now use `declare_command_config_elab` instead of `declare_config_elab` to get an elaborator landing in `CommandElabM`. Syntaxes should migrate to `optConfig` instead of `(config)?`, but the elaborators are reverse compatible. ([#5883](https://github.com/leanprover/lean4/pull/5883))
```` |
reference-manual/Manual/Releases/v4_18_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
-- TODO: investigate why this is needed in the new compiler
set_option maxRecDepth 9900
#doc (Manual) "Lean 4.18.0 (2025-04-02)" =>
%%%
tag := "release-v4.18.0"
file := "v4.18.0"
%%%
````markdown
For this release, 344 changes landed. In addition to the 166 feature additions and 38 fixes listed below there were 13 refactoring changes, 10 documentation improvements, 3 performance improvements, 4 improvements to the test suite and 109 other changes.
## Highlights
Lean v4.18 release brings a number of exciting new features:
* Inlay hints for auto implicits
The Language Server now uses inlay hints to show which variables are brought into scope implicitly, and where. The hint
reveals its type upon hover, and double-clicking the hint will insert the variable binding explicitly.
See the description of [#6768](https://github.com/leanprover/lean4/pull/6768/files) for a screenshort.
Note that this feature is only visible when `set_option autoImplicit true`, which is the default in plain Lean projects,
but not in mathlib
* [#6935](https://github.com/leanprover/lean4/pull/6935) adds the tactic `expose_names`. It creates a new goal whose
local context has been "exposed" so that every local declaration has a
clear, accessible name. If no local declarations require renaming, the
original goal is returned unchanged.
```lean
/--
info: α : Sort u_1
a b : α
h_1 : a = b
h_2 : True
h_3 : True ∨ False
h : b = a
⊢ b = a
-/
#guard_msgs (info) in
example (a b : α) (h : a = b) (_ : True) (_ : True ∨ False) (h : b = a) : b = a := by
expose_names
trace_state
rw [h]
```
This tactic intended for use in auto-generated tactic suggestions, and can also be useful
during proof exploration. It is still best practice to name variables where they are
brought into scope (`intro`, `case` etc.), and not use `expose_names` in a finished,
polished proof.
* [#7069](https://github.com/leanprover/lean4/pull/7069) adds the `fun_induction` and `fun_cases` tactics, which add
convenience around using functional induction and functional cases
principles.
```lean
fun_induction foo x y z
```
elaborates `foo x y z`, then looks up `foo.induct`, and then essentially does
```lean
induction z using foo.induct y
```
including and in particular figuring out which arguments are parameters,
targets or dropped. This only works for non-mutual functions so far.
Likewise there is the `fun_cases` tactic using `foo.fun_cases`.
* [#6744](https://github.com/leanprover/lean4/pull/6744) extend the preprocessing of well-founded recursive definitions
to bring assumptions like `h✝ : x ∈ xs`, if a recursive call is in the
argument of a higher-order function like `List.map`, into scope automatically.
In many cases this removes the need to use functions like `List.attach`.
This feature can be disabled with `set_option wf.preprocess false`.
* [#6634](https://github.com/leanprover/lean4/pull/6634) adds support for changing the binder annotations of existing
variables to and from strict-implicit and instance-implicit using the
`variable` command.
* [#7100](https://github.com/leanprover/lean4/pull/7100) modifies the `structure` syntax so that parents can be named,
like in
```lean
structure S extends toParent : P
```
**Breaking change:** The syntax is also modified so that the resultant
type comes *before* the `extends` clause, for example `structure S :
Prop extends P`. This is necessary to prevent a parsing ambiguity, but
also this is the natural place for the resultant type. Implements RFC
[#7099](https://github.com/leanprover/lean4/issues/7099).
* [#7103](https://github.com/leanprover/lean4/pull/7103) gives the `induction` tactic the ability to name hypotheses to
use when generalizing targets, just like in `cases`. For example,
`induction h : xs.length` leads to goals with hypotheses `h : xs.length
= 0` and `h : xs.length = n + 1`. Target handling is also slightly
modified for multi-target induction principles: it used to be that if
any target was not a free variable, all of the targets would be
generalized (thus causing free variables to lose their connection to the
local hypotheses they appear in); now only the non-free-variable targets
are generalized.
* [#6869](https://github.com/leanprover/lean4/pull/6869) adds a `recommended_spelling` command, which can be used for
recording the recommended spelling of a notation (for example, that the
recommended spelling of `∧` in identifiers is `and`). This information
is then appended to the relevant docstrings for easy lookup.
* [#6893](https://github.com/leanprover/lean4/pull/6893) adds support for plugins to the frontend and server.
* [#7061](https://github.com/leanprover/lean4/pull/7061) provides a basic API for a premise selection tool, which can be
provided in downstream libraries. It does not implement premise
selection itself!
And many more! Check out the *Language* section below.
Notably, a line of work has been carried out on the following
(see the corresponding subsections in the *Language* section for the details):
- the `try?` tactic, which has been re-implemented using `evalAndSuggest` tactic.
`try?` now supports referencing inaccessible local names and can provide
more complex suggestions, involving `exact?` and `fun_induction` tactics.
New configuration options have been added: `-only`, `+missing`, and `max:=<num>`,
as well as `merge`.
- `bv_decide` tactic. There are new features in preprocessing, added support
for enum inductives, `IntX` and `ISize`, and improved performance in LRAT trimming.
- normalization for linear integer arithmetic expressions has been implemented
and connected to `simp +arith`. [#7043](https://github.com/leanprover/lean4/pull/7043) deprecates the tactics `simp_arith`,
`simp_arith!`, `simp_all_arith` and `simp_all_arith!` in favor of `simp +arith`.
Important Library updates include:
* [#6914](https://github.com/leanprover/lean4/pull/6914) introduces ordered map data structures, namely `DTreeMap`,
`TreeMap`, `TreeSet` and their `.Raw` variants, into the standard
library. A collection of lemmas about the operations on these data structures has
been added in the subsequent PRs.
* [#7255](https://github.com/leanprover/lean4/pull/7255) fixes the definition of `Min (Option α)`. This is a **breaking
change**. This treats `none` as the least element,
so `min none x = min x none = none` for all `x : Option α`. Prior to
nightly-2025-02-27, we instead had `min none (some x) = min (some x)
none = some x`. Also adds basic lemmas relating `min`, `max`, `≤` and
`<` on `Option`.
Significant development has been made in the verification APIs of `BitVec`
and fixed-width integer types (`IntX`), along with ongoing work to align
`List/Array/Vector` APIs. Several lemmas about `Int.ediv/fdiv/tdiv` have
been strengthened.
[#6950](https://github.com/leanprover/lean4/pull/6950) adds [a style guide](https://github.com/leanprover/lean4/blob/master/doc/std/style.md) and [a naming convention](https://github.com/leanprover/lean4/blob/master/doc/std/naming.md) for the standard library.
_This summary of highlights was contributed by Violetta Sim._
## Language
* [#6634](https://github.com/leanprover/lean4/pull/6634) adds support for changing the binder annotations of existing
variables to and from strict-implicit and instance-implicit using the
`variable` command.
* [#6744](https://github.com/leanprover/lean4/pull/6744) extends the preprocessing of well-founded recursive definitions,
see the highlights section for details.
* [#6823](https://github.com/leanprover/lean4/pull/6823) adds a builtin tactic and a builtin attribute that are required
for the tree map. The tactic, `as_aux_lemma`, can generally be used to
wrap the proof term generated by a tactic sequence into a separate
auxiliary lemma in order to keep the proof term small. This can, in rare
cases, be necessary if the proof term will appear multiple times in the
encompassing term. The new attribute, `Std.Internal.tree_tac`, is
internal and should not be used outside of `Std`.
* [#6853](https://github.com/leanprover/lean4/pull/6853) adds support for anonymous equality proofs in `match`
expressions of the form `match _ : e with ...`.
* [#6869](https://github.com/leanprover/lean4/pull/6869) adds a `recommended_spelling` command; see the highlights
section for details.
* [#6891](https://github.com/leanprover/lean4/pull/6891) modifies `rewrite`/`rw` to abort rewriting if the elaborated
lemma has any immediate elaboration errors (detected by presence of
synthetic sorries). Rewriting still proceeds if there are elaboration
issues arising from pending synthetic metavariables, like instance
synthesis failures. The purpose of the change is to avoid obscure
"tactic 'rewrite' failed, equality or iff proof expected ?m.5" errors
when for example a lemma does not exist.
* [#6893](https://github.com/leanprover/lean4/pull/6893) adds support for plugins to the frontend and server.
* [#6935](https://github.com/leanprover/lean4/pull/6935) adds the tactic `expose_names`; see the highlights section
for details.
* [#6936](https://github.com/leanprover/lean4/pull/6936) fixes the `#discr_tree_simp_key` command, because it displays
the keys for just `lhs` in `lhs ≠ rhs`, but it should be `lhs = rhs`,
since that is what simp indexes.
* [#6939](https://github.com/leanprover/lean4/pull/6939) adds error messages for `inductive` declarations with
conflicting constructor names and `mutual` declarations with conflicting
names.
* [#6947](https://github.com/leanprover/lean4/pull/6947) adds the `binderNameHint` gadget. It can be used in rewrite and
simp rules to preserve a user-provided name where possible.
The expression `binderNameHint v binder e` defined to be `e`.
If it is used on the right-hand side of an equation that is applied by
a tactic like `rw` or `simp`, and `v` is a local variable, and `binder`
is an expression that (after beta-reduction) is a binder (so `fun w => …` or `∀ w, …`),
then it will rename `v` to the name used in the binder, and remove the `binderNameHint`.
A typical use of this gadget would be as follows; the gadget ensures
that after rewriting, the local variable is still `name`, and not `x`:
```lean
theorem all_eq_not_any_not (l : List α) (p : α → Bool) :
l.all p = !l.any fun x => binderNameHint x p (!p x) := sorry
example (names : List String) : names.all (fun name => "Waldo".isPrefixOf name) = true := by
rw [all_eq_not_any_not]
-- ⊢ (!names.any fun name => !"Waldo".isPrefixOf name) = true
```
This gadget is supported by `simp`, `dsimp` and `rw` in the right-hand-side
of an equation, but not in hypotheses or by other tactics.
* [#6951](https://github.com/leanprover/lean4/pull/6951) adds line breaks and indentations to simp's trace messages to
make them easier to read (IMHO).
* [#6964](https://github.com/leanprover/lean4/pull/6964) adds a convenience command `#info_trees in`, which prints the
info trees generated by the following command. It is useful for
debugging or learning about `InfoTree`.
* [#7039](https://github.com/leanprover/lean4/pull/7039) improves the well-founded definition preprocessing to propagate
`wfParam` through let expressions.
* [#7053](https://github.com/leanprover/lean4/pull/7053) makes `simp` heed the `binderNameHint` also in the assumptions
of congruence rules. Fixes #7052.
* [#7055](https://github.com/leanprover/lean4/pull/7055) improves array and vector literal syntax by allowing trailing
commas. For example, `#[1, 2, 3,]`.
* [#7061](https://github.com/leanprover/lean4/pull/7061) provides a basic API for a premise selection tool; see the
highlights section for details.
* [#7078](https://github.com/leanprover/lean4/pull/7078) implements simprocs for `Int` and `Nat` divides predicates.
* [#7088](https://github.com/leanprover/lean4/pull/7088) fixes the behavior of the indexed-access notation `xs[i]` in
cases where the proof of `i`'s validity is filled in during unification.
* [#7090](https://github.com/leanprover/lean4/pull/7090) strips `lib` prefixes and `_shared` suffixes from plugin names.
It also moves most of the dynlib processing code to Lean to make such
preprocessing more standard.
* [#7100](https://github.com/leanprover/lean4/pull/7100) modifies the `structure` syntax; see the highlights section for details.
* [#7103](https://github.com/leanprover/lean4/pull/7103) gives the `induction` tactic the ability to name hypotheses; see
the highlights section for details.
* [#7119](https://github.com/leanprover/lean4/pull/7119) makes linter names clickable in the `trace.profiler` output.
* [#7191](https://github.com/leanprover/lean4/pull/7191) fixes the indentation of "Try this" suggestions in widget-less
multiline messages, as they appear in `#guard_msgs` outputs.
* [#7192](https://github.com/leanprover/lean4/pull/7192) prevents `exact?` and `apply?` from suggesting tactics that
correspond to correct proofs but do not elaborate, and it allows these
tactics to suggest `expose_names` when needed.
* [#7200](https://github.com/leanprover/lean4/pull/7200) allows the debug form of DiscrTree.Key to line-wrap.
* [#7213](https://github.com/leanprover/lean4/pull/7213) adds `SetConsoleOutputCP(CP_UTF8)` during runtime initialization
to properly display Unicode on the Windows console. This effects both
the Lean executable itself and user executables (including Lake).
* [#7224](https://github.com/leanprover/lean4/pull/7224) make `induction … using` and `cases … using` complain if more
targets were given than expected by that eliminator.
* [#7294](https://github.com/leanprover/lean4/pull/7294) fixes bugs in `Std.Internal.Rat.floor` and
`Std.Internal.Rat.ceil`.
### Updates to the `try?` Tactic
* [#6961](https://github.com/leanprover/lean4/pull/6961) adds the auxiliary tactic `evalAndSuggest`. It will be used to
refactor `try?`.
* [#6965](https://github.com/leanprover/lean4/pull/6965) re-implements the `try?` tactic using the new `evalAndSuggest`
infrastructure.
* [#6967](https://github.com/leanprover/lean4/pull/6967) ensures `try?` can suggest tactics that need to reference
inaccessible local names.
Example:
```lean
/--
info: Try these:
• · expose_names; induction as, bs_1 using app.induct <;> grind [= app]
• · expose_names; induction as, bs_1 using app.induct <;> grind only [app]
-/
#guard_msgs (info) in
example : app (app as bs) cs = app as (app bs cs) := by
have bs := 20 -- shadows `bs` in the target
try?
```
* [#6979](https://github.com/leanprover/lean4/pull/6979) adds support for more complex suggestions in `try?`.
Example:
```lean
example (as : List α) (a : α) : concat as a = as ++ [a] := by
try?
```
suggestion
```
Try this: · induction as, a using concat.induct
· rfl
· simp_all
```
* [#6980](https://github.com/leanprover/lean4/pull/6980) improves the `try?` tactic runtime validation and error
messages. It also simplifies the implementation, and removes unnecessary
code.
* [#6981](https://github.com/leanprover/lean4/pull/6981) adds new configuration options to `try?`.
- `try? -only` omits `simp only` and `grind only` suggestions
- `try? +missing` enables partial solutions where some subgoals are
"solved" using `sorry`, and must be manually proved by the user.
- `try? (max:=<num>)` sets the maximum number of suggestions produced
(default is 8).
* [#6991](https://github.com/leanprover/lean4/pull/6991) improves how suggestions for the `<;>` combinator are generated.
* [#6994](https://github.com/leanprover/lean4/pull/6994) adds the `Try.Config.merge` flag (`true` by default) to the
`try?` tactic. When set to `true`, `try?` compresses suggestions such
as:
```lean
· induction xs, ys using bla.induct
· grind only [List.length_reverse]
· grind only [bla]
```
into:
```lean
induction xs, ys using bla.induct <;> grind only [List.length_reverse, bla]
```
* [#6995](https://github.com/leanprover/lean4/pull/6995) implements support for `exact?` in the `try?` tactic.
* [#7082](https://github.com/leanprover/lean4/pull/7082) makes `try?` use `fun_induction` instead of `induction … using
foo.induct`. It uses the argument-free short-hand `fun_induction foo` if
that is unambiguous. Avoids `expose_names` if not necessary by simply
trying without first.
### Functional Induction Tactic
* [#7069](https://github.com/leanprover/lean4/pull/7069) adds the `fun_induction` and `fun_cases` tactics, which add
convenience around using functional induction and functional cases
principles.
* [#7101](https://github.com/leanprover/lean4/pull/7101) implements `fun_induction foo`, which is like `fun_induction foo
x y z`, only that it picks the arguments to use from a unique suitable
call to `foo` in the goal.
* [#7127](https://github.com/leanprover/lean4/pull/7127) follows up on #7103 which changes the generaliziation behavior
of `induction`, to keep `fun_induction` in sync. Also fixes a `Syntax`
indexing off-by-one error.
### `bv_decide` Tactic
* [#6741](https://github.com/leanprover/lean4/pull/6741) implements two rules for bv_decide's preprocessor, lowering
`|||` to `&&&` in order to enable more term sharing + application of
rules about `&&&` as well as rewrites of the form `(a &&& b == -1#w) =
(a == -1#w && b == -1#w)` in order to preserve rewriting behavior that
already existed before this lowering.
* [#6924](https://github.com/leanprover/lean4/pull/6924) adds the EQUAL_ITE rules from Bitwuzla to the preprocessor of
bv_decide.
* [#6926](https://github.com/leanprover/lean4/pull/6926) adds the BV_EQUAL_CONST_NOT rules from Bitwuzla to the
preprocessor of bv_decide.
* [#6946](https://github.com/leanprover/lean4/pull/6946) implements basic support for handling of enum inductives in
`bv_decide`. It now supports equality on enum inductive variables (or
other uninterpreted atoms) and constants.
* [#7009](https://github.com/leanprover/lean4/pull/7009) ensures users get an error message saying which module to import
when they try to use `bv_decide`.
* [#7019](https://github.com/leanprover/lean4/pull/7019) properly spells out the trace nodes in bv_decide so they are
visible with just `trace.Meta.Tactic.bv` and `trace.Meta.Tactic.sat`
instead of always having to enable the profiler.
* [#7021](https://github.com/leanprover/lean4/pull/7021) adds theorems for interactions of extractLsb with `&&&`, `^^^`,
`~~~` and `bif` to bv_decide's preprocessor.
* [#7029](https://github.com/leanprover/lean4/pull/7029) adds simprocs to bv_decide's preprocessor that rewrite
multiplication with powers of two to constant shifts.
* [#7033](https://github.com/leanprover/lean4/pull/7033) improves presentation of counter examples for UIntX and enum
inductives in bv_decide.
* [#7242](https://github.com/leanprover/lean4/pull/7242) makes sure bv_decide can work with projections applied to `ite`
and `cond` in its structures pass.
* [#7257](https://github.com/leanprover/lean4/pull/7257) improves performance of LRAT trimming in bv_decide.
* [#7269](https://github.com/leanprover/lean4/pull/7269) implements support for `IntX` and `ISize` in `bv_decide`.
* [#7275](https://github.com/leanprover/lean4/pull/7275) adds all level 1 rewrites from Bitwuzla to the preprocessor of
bv_decide.
### Parallelizing Elaboration
* [#6770](https://github.com/leanprover/lean4/pull/6770) enables code generation to proceed in parallel to further
elaboration.
* [#6988](https://github.com/leanprover/lean4/pull/6988) ensures interrupting the kernel does not lead to wrong, sticky
error messages in the editor
* [#7047](https://github.com/leanprover/lean4/pull/7047) removes the `save` and `checkpoint` tactics that have been
superseded by incremental elaboration
* [#7076](https://github.com/leanprover/lean4/pull/7076) introduces the central parallelism API for ensuring that helper
declarations can be generated lazily without duplicating work or
creating conflicts across threads.
### Linear Integer Normalization in `simp +arith`
* [#7000](https://github.com/leanprover/lean4/pull/7000) adds helper theorems for justifying the linear integer
normalizer.
* [#7002](https://github.com/leanprover/lean4/pull/7002) implements the normalizer for linear integer arithmetic
expressions. It is not connect to `simp +arith` yet because of some
spurious `[simp]` attributes.
* [#7011](https://github.com/leanprover/lean4/pull/7011) adds `simp +arith` for integers. It uses the new `grind`
normalizer for linear integer arithmetic. We still need to implement
support for dividing the coefficients by their GCD. It also fixes
several bugs in the normalizer.
* [#7015](https://github.com/leanprover/lean4/pull/7015) makes sure `simp +arith` normalizes coefficients in linear
integer polynomials. There is still one todo: tightening the bound of
inequalities.
* [#7030](https://github.com/leanprover/lean4/pull/7030) adds completes the linear integer inequality normalizer for
`grind`. The missing normalization step replaces a linear inequality of
the form `a_1*x_1 + ... + a_n*x_n + b <= 0` with `a_1/k * x_1 + ... +
a_n/k * x_n + ceil(b/k) <= 0` where `k = gcd(a_1, ..., a_n)`.
`ceil(b/k)` is implemented using the helper `cdiv b k`.
* [#7040](https://github.com/leanprover/lean4/pull/7040) ensures that terms such as `f (2*x + y)` and `f (y + x + x)`
have the same normal form when using `simp +arith`
* [#7043](https://github.com/leanprover/lean4/pull/7043) deprecates the tactics `simp_arith`, `simp_arith!`,
`simp_all_arith` and `simp_all_arith!`. Users can just use the `+arith`
option.
### `grind` Tactic
The `grind` tactic is still is experimental and still under development. Avoid using it in production projects
* [#6902](https://github.com/leanprover/lean4/pull/6902) ensures `simp` diagnostic information in included in the `grind`
diagnostic message.
* [#6937](https://github.com/leanprover/lean4/pull/6937) improves `grind` error and trace messages by cleaning up local
declaration names.
* [#6940](https://github.com/leanprover/lean4/pull/6940) improves how the `grind` tactic performs case splits on `p <->
q`.
* [#7102](https://github.com/leanprover/lean4/pull/7102) modifies `grind` to run with the `reducible` transparency
setting. We do not want `grind` to unfold arbitrary terms during
definitional equality tests. also fixes several issues
introduced by this change. The most common problem was the lack of a
hint in proofs, particularly in those constructed using proof by
reflection. also introduces new sanity checks when `set_option
grind.debug true` is used.
* [#7231](https://github.com/leanprover/lean4/pull/7231) implements functions for constructing disequality proofs in
`grind`.
#### Cutsat Procedure (Solver for Linear Integer Arithmetic Problems)
* [#7077](https://github.com/leanprover/lean4/pull/7077) proves the helper theorems for justifying the "Div-Solve" rule
in the cutsat procedure.
* [#7091](https://github.com/leanprover/lean4/pull/7091) adds helper theorems for normalizing divisibility constraints.
They are going to be used to implement the cutsat procedure in the
`grind` tactic.
* [#7092](https://github.com/leanprover/lean4/pull/7092) implements divisibility constraint normalization in `simp
+arith`.
* [#7097](https://github.com/leanprover/lean4/pull/7097) implements several modifications for the cutsat procedure in
`grind`.
- The maximal variable is now at the beginning of linear polynomials.
- The old `LinearArith.Solver` was deleted, and the normalizer was moved
to `Simp`.
- cutsat first files were created, and basic infrastructure for
representing divisibility constraints was added.
* [#7122](https://github.com/leanprover/lean4/pull/7122) implements the divisibility constraint solver for the cutsat
procedure in the `grind` tactic.
* [#7124](https://github.com/leanprover/lean4/pull/7124) adds the helper theorems for justifying the divisibility
constraint solver in the cutsat procedure used by the `grind` tactic.
* [#7138](https://github.com/leanprover/lean4/pull/7138) implements proof generation for the divisibility constraint
solver in `grind`.
* [#7139](https://github.com/leanprover/lean4/pull/7139) uses a `let`-expression for storing the (shared) context in
proofs produced by the cutsat procedure in `grind`.
* [#7152](https://github.com/leanprover/lean4/pull/7152) implements the infrastructure for supporting integer inequality
constraints in the cutsat procedure.
* [#7155](https://github.com/leanprover/lean4/pull/7155) implements some infrastructure for the model search procedure in
cutsat.
* [#7156](https://github.com/leanprover/lean4/pull/7156) adds a helper theorem that will be used in divisibility
constraint conflict resolution during model construction.
* [#7176](https://github.com/leanprover/lean4/pull/7176) implements model construction for divisibility constraints in
the cutsat procedure.
* [#7183](https://github.com/leanprover/lean4/pull/7183) improves the cutsat model search procedure.
* [#7186](https://github.com/leanprover/lean4/pull/7186) simplifies the proofs and data structures used by cutsat.
* [#7193](https://github.com/leanprover/lean4/pull/7193) adds basic infrastructure for adding support for equalities in
cutsat.
* [#7194](https://github.com/leanprover/lean4/pull/7194) adds support theorems for solving equality in cutsat.
* [#7202](https://github.com/leanprover/lean4/pull/7202) adds support for internalizing terms relevant to the cutsat
module. This is required to implement equality propagation.
* [#7203](https://github.com/leanprover/lean4/pull/7203) improves the support for equalities in cutsat. It also
simplifies a few support theorems used to justify cutsat rules.
* [#7217](https://github.com/leanprover/lean4/pull/7217) improves the support for equalities in cutsat.
* [#7220](https://github.com/leanprover/lean4/pull/7220) implements the missing cases for equality propagation from the
`grind` core to the cutsat module.
* [#7234](https://github.com/leanprover/lean4/pull/7234) implements dIsequality propagation from `grind` core module to
cutsat.
* [#7244](https://github.com/leanprover/lean4/pull/7244) adds support for disequalities in the cutsat procedure used in
`grind`.
* [#7248](https://github.com/leanprover/lean4/pull/7248) implements simple equality propagation in cutsat `p <= 0 -> -p <= 0 -> p = 0`
* [#7252](https://github.com/leanprover/lean4/pull/7252) implements inequality refinement using disequalities. It
minimizes the number of case splits cutsat will have to perform.
* [#7267](https://github.com/leanprover/lean4/pull/7267) improves the cutsat search procedure. It adds support for find
an approximate rational solution, checks disequalities, and adds stubs
for all missing cases.
* [#7278](https://github.com/leanprover/lean4/pull/7278) adds counterexamples for linear integer constraints in the
`grind` tactic. This feature is implemented in the cutsat procedure.
* [#7279](https://github.com/leanprover/lean4/pull/7279) adds support theorems for the **Cooper-Dvd-Left** conflict
resolution rule used in the cutsat procedure. During model construction,
when attempting to extend the model to a variable `x`, cutsat may find a
conflict that involves two inequalities (the lower and upper bounds for
`x`) and a divisibility constraint:
```lean
a * x + p ≤ 0
b * x + q ≤ 0
d ∣ c * x + s
```
* [#7284](https://github.com/leanprover/lean4/pull/7284) implements non-choronological backtracking for the cutsat
procedure. The procedure has two main kinds of case-splits:
disequalities and Cooper resolvents. focus on the first kind.
* [#7290](https://github.com/leanprover/lean4/pull/7290) adds support theorems for the **Cooper-Left** conflict
resolution rule used in the cutsat procedure. During model
construction,when attempting to extend the model to a variable `x`,
cutsat may find a conflict that involves two inequalities (the lower and
upper bounds for `x`). This is a special case of Cooper-Dvd-Left when
there is no divisibility constraint.
* [#7292](https://github.com/leanprover/lean4/pull/7292) adds support theorems for the **Cooper-Dvd-Right** conflict
resolution rule used in the cutsat procedure. During model construction,
when attempting to extend the model to a variable `x`, cutsat may find a
conflict that involves two inequalities (the lower and upper bounds for
`x`) and a divisibility constraint.
* [#7293](https://github.com/leanprover/lean4/pull/7293) adds support theorems for the Cooper-Right conflict resolution
rule used in the cutsat procedure. During model construction, when
attempting to extend the model to a variable x, cutsat may find a
conflict that involves two inequalities (the lower and upper bounds for
x). This is a special case of Cooper-Dvd-Right when there is no
divisibility constraint.
* [#7409](https://github.com/leanprover/lean4/pull/7409) allows the use of `dsimp` during preprocessing of well-founded
definitions. This fixes regressions when using `if-then-else` without
giving a name to the condition, but where the condition is needed for
the termination proof, in cases where that subexpression is reachable
only by dsimp, but not by simp (e.g. inside a dependent let)
## Library
* [#5498](https://github.com/leanprover/lean4/pull/5498) makes `BitVec.getElem` the simp normal form in case a proof is
available and changes `ext` to return `x[i]` + a hypothesis that proves
that we are in-bounds. This aligns `BitVec` further with the API
conventions of the Lean standard datatypes.
* [#6326](https://github.com/leanprover/lean4/pull/6326) adds `BitVec.(getMsbD, msb)_replicate, replicate_one` theorems,
corrects a non-terminal `simp` in `BitVec.getLsbD_replicate` and
simplifies the proof of `BitVec.getElem_replicate` using the `cases`
tactic.
* [#6628](https://github.com/leanprover/lean4/pull/6628) adds SMT-LIB operators to detect overflow
`BitVec.(uadd_overflow, sadd_overflow)`, according to the definitions
[here](https://github.com/SMT-LIB/SMT-LIB-2/blob/2.7/Theories/FixedSizeBitVectors.smt2),
and the theorems proving equivalence of such definitions with the
`BitVec` library functions (`uaddOverflow_eq`, `saddOverflow_eq`).
Support theorems for these proofs are `BitVec.toNat_mod_cancel_of_lt,
BitVec.toInt_lt, BitVec.le_toInt, Int.bmod_neg_iff`. The PR also
includes a set of tests.
* [#6792](https://github.com/leanprover/lean4/pull/6792) adds theorems `BitVec.(getMsbD, msb)_(extractLsb', extractLsb),
getMsbD_extractLsb'_eq_getLsbD`.
* [#6795](https://github.com/leanprover/lean4/pull/6795) adds theorems `BitVec.(getElem_umod_of_lt, getElem_umod,
getLsbD_umod, getMsbD_umod)`. For the defiition of these theorems we
rely on `divRec`, excluding the case where `d=0#w`, which is treated
separately because there is no infrastructure to reason about this case
within `divRec`. In particular, our implementation follows the mathlib
standard [where division by 0 yields
0](https://github.com/leanprover/lean4/blob/c7c1e091c9f07ae6f8e8ff7246eb7650e2740dcb/src/Init/Data/BitVec/Basic.lean#L217),
while in [SMTLIB this yields
`allOnes`](https://github.com/leanprover/lean4/blob/c7c1e091c9f07ae6f8e8ff7246eb7650e2740dcb/src/Init/Data/BitVec/Basic.lean#L237).
* [#6830](https://github.com/leanprover/lean4/pull/6830) improves some files separation and standardize error messages in
UV modules
* [#6850](https://github.com/leanprover/lean4/pull/6850) adds some lemmas about the new tree map. These lemmas are about
the interactions of `empty`, `isEmpty`, `insert`, `contains`. Some
lemmas about the interaction of `contains` with the others will follow
in a later PR.
* [#6866](https://github.com/leanprover/lean4/pull/6866) adds missing `Hashable` instances for `PUnit` and `PEmpty`.
* [#6914](https://github.com/leanprover/lean4/pull/6914) introduces ordered map data structures, namely `DTreeMap`,
`TreeMap`, `TreeSet` and their `.Raw` variants, into the standard
library. There are still some operations missing that the hash map has.
As of now, the operations are unverified, but the corresponding lemmas
will follow in subsequent PRs. While the tree map has already been
optimized, more micro-optimization will follow as soon as the new code
generator is ready.
* [#6922](https://github.com/leanprover/lean4/pull/6922) adds `LawfulBEq` instances for `Array` and `Vector`.
* [#6948](https://github.com/leanprover/lean4/pull/6948) completes the alignment of `List/Array/Vectors` lemmas for
`insertIdx`.
* [#6954](https://github.com/leanprover/lean4/pull/6954) verifies the `toList`function for hash maps and dependent hash
maps.
* [#6958](https://github.com/leanprover/lean4/pull/6958) improves the `Promise` API by considering how dropped promises
can lead to never-finished tasks.
* [#6966](https://github.com/leanprover/lean4/pull/6966) adds an internal-use-only strict linter for the variable names
of `List`/`Array`/`Vector` variables, and begins cleaning up.
* [#6982](https://github.com/leanprover/lean4/pull/6982) improves some lemmas about monads and monadic operations on
Array/Vector, using @Rob23oa's work in
https://github.com/leanprover-community/batteries/pull/1109, and
adding/generalizing some additional lemmas.
* [#7013](https://github.com/leanprover/lean4/pull/7013) makes improvements to the simp set for List/Array/Vector/Option
to improve confluence, in preparation for `simp_lc`.
* [#7017](https://github.com/leanprover/lean4/pull/7017) renames the simp set `boolToPropSimps` to `bool_to_prop` and
`bv_toNat` to `bitvec_to_nat`. I'll be adding more similarly named simp
sets.
* [#7034](https://github.com/leanprover/lean4/pull/7034) adds `wf_preprocess` theorems for
`{List,Array}.{foldlM,foldrM,mapM,filterMapM,flatMapM}`
* [#7036](https://github.com/leanprover/lean4/pull/7036) adds some deprecated function aliases to the tree map in order
to ease the transition from the `RBMap` to the tree map.
* [#7046](https://github.com/leanprover/lean4/pull/7046) renames `UIntX.mk` to `UIntX.ofBitVec` and adds deprecations.
* [#7048](https://github.com/leanprover/lean4/pull/7048) adds the functions `IntX.ofBitVec`.
* [#7050](https://github.com/leanprover/lean4/pull/7050) renames the functions `UIntX.val` to `UIntX.toFin`.
* [#7051](https://github.com/leanprover/lean4/pull/7051) implements the methods `insertMany`, `ofList`, `ofArray`,
`foldr` and `foldrM` on the tree map.
* [#7056](https://github.com/leanprover/lean4/pull/7056) adds the `UIntX.ofFin` conversion functions.
* [#7057](https://github.com/leanprover/lean4/pull/7057) adds the function `UIntX.ofNatLT`. This is supposed to be a
replacement for `UIntX.ofNatCore` and `UIntX.ofNat'`, but for
bootstrapping reasons we need this function to exist in stage0 before we
can proceed with the renaming and deprecations, so this PR just adds the
function.
* [#7059](https://github.com/leanprover/lean4/pull/7059) moves away from using `List.get` / `List.get?` / `List.get!` and
`Array.get!`, in favour of using the `GetElem` mediated getters. In
particular it deprecates `List.get?`, `List.get!` and `Array.get?`. Also
adds `Array.back`, taking a proof, matching `List.getLast`.
* [#7062](https://github.com/leanprover/lean4/pull/7062) introduces the functions `UIntX.toIntX` as the public API to
obtain the `IntX` that is 2's complement equivalent to a given `UIntX`.
* [#7063](https://github.com/leanprover/lean4/pull/7063) adds `ISize.toInt8`, `ISize.toInt16`, `Int8.toISize`,
`Int16.toISize`.
* [#7064](https://github.com/leanprover/lean4/pull/7064) renames `BitVec.ofNatLt` to `BitVec.ofNatLT` and sets up
deprecations for the old name.
* [#7066](https://github.com/leanprover/lean4/pull/7066) renames `IntX.toNat` to `IntX.toNatClampNeg` (to reduce
surprises) and sets up a deprecation.
* [#7068](https://github.com/leanprover/lean4/pull/7068) is a follow-up to #7057 and adds a builtin dsimproc for
`UIntX.ofNatLT` which it turns out we need in stage0 before we can get
the deprecation of `UIntX.ofNatCore` in favor of `UIntX.ofNatLT` off the
ground.
* [#7070](https://github.com/leanprover/lean4/pull/7070) implements the methods `min`, `max`, `minKey`, `maxKey`,
`atIndex`, `getEntryLE`, `getKeyLE` and consorts on the tree map.
* [#7071](https://github.com/leanprover/lean4/pull/7071) unifies the existing functions `UIntX.ofNatCore` and
`UIntX.ofNat'` under a new name, `UIntX.ofNatLT`.
* [#7079](https://github.com/leanprover/lean4/pull/7079) introduces `Fin.toNat` as an alias for `Fin.val`. We add this
function for discoverability and consistency reasons. The normal form
for proofs remains `Fin.val`, and there is a `simp` lemma rewriting
`Fin.toNat` to `Fin.val`.
* [#7080](https://github.com/leanprover/lean4/pull/7080) adds the functions `UIntX.ofNatTruncate` (the version for
`UInt32` already exists).
* [#7081](https://github.com/leanprover/lean4/pull/7081) adds functions `IntX.ofIntLE`, `IntX.ofIntTruncate`, which are
analogous to the unsigned counterparts `UIntX.ofNatLT` and
`UInt.ofNatTruncate`.
* [#7083](https://github.com/leanprover/lean4/pull/7083) adds (value-based, not bitfield-based) conversion functions
between `Float`/`Float32` and `IntX`/`UIntX`.
* [#7105](https://github.com/leanprover/lean4/pull/7105) completes aligning `Array/Vector.extract` lemmas with the lemmas
for `List.take` and `List.drop`.
* [#7106](https://github.com/leanprover/lean4/pull/7106) completes the alignment of `List/Array/Vector.finRange` lemmas.
* [#7109](https://github.com/leanprover/lean4/pull/7109) implements the `getThenInsertIfNew?` and `partition` functions
on the tree map.
* [#7114](https://github.com/leanprover/lean4/pull/7114) implements the methods `values` and `valuesArray` on the tree
map.
* [#7116](https://github.com/leanprover/lean4/pull/7116) implements the `getKey` functions on the tree map. It also fixes
the naming of the `entryAtIdx` function on the tree set, which should
have been called `atIdx`.
* [#7118](https://github.com/leanprover/lean4/pull/7118) implements the functions `modify` and `alter` on the tree map.
* [#7128](https://github.com/leanprover/lean4/pull/7128) adds `Repr` and `Hashable` instances for `IntX`.
* [#7131](https://github.com/leanprover/lean4/pull/7131) adds `IntX.abs` functions. These are specified by `BitVec.abs`,
so they map `IntX.minValue` to `IntX.minValue`, similar to Rust's
`i8::abs`. In the future we might also have versions which take values
in `UIntX` and/or `Nat`.
* [#7137](https://github.com/leanprover/lean4/pull/7137) verifies the various fold and for variants for hashmaps.
* [#7151](https://github.com/leanprover/lean4/pull/7151) fixes a memory leak in `IO.FS.createTempFile`
* [#7158](https://github.com/leanprover/lean4/pull/7158) strengthens `Int.tdiv_eq_ediv`, by dropping an unnecessary
hypothesis, in preparation for further work on `ediv`/`tdiv`/`fdiv`
lemmas.
* [#7161](https://github.com/leanprover/lean4/pull/7161) adds all missing tree map lemmas about the interactions of the
functions `empty`, `isEmpty`, `contains`, `size`, `insert(IfNew)` and
`erase`.
* [#7162](https://github.com/leanprover/lean4/pull/7162) splits `Int.DivModLemmas` into a `Bootstrap` and `Lemmas` file,
where it is possible to use `omega` in `Lemmas`.
* [#7163](https://github.com/leanprover/lean4/pull/7163) gives an unconditional theorem expressing `Int.tdiv` in terms of
`Int.ediv`, not just for non-negative arguments.
* [#7165](https://github.com/leanprover/lean4/pull/7165) provides tree map lemmas about the interaction of
`containsThenInsert(IfNew)` with `contains` and `insert(IfNew)`.
* [#7167](https://github.com/leanprover/lean4/pull/7167) provides tree map lemmas for the interaction of `get?` with the
other operations for which lemmas already exist.
* [#7174](https://github.com/leanprover/lean4/pull/7174) adds the first batch of lemmas about iterated conversions
between finite types starting with something of type `UIntX`.
* [#7199](https://github.com/leanprover/lean4/pull/7199) adds theorems comparing `Int.ediv` with `tdiv` and `fdiv`, for
all signs of arguments. (Previously we just had the statements about the
cases in which they agree.)
* [#7201](https://github.com/leanprover/lean4/pull/7201) adds `Array/Vector.left/rightpad`. These will not receive any
verification theorems; simp just unfolds them to an `++` operation.
* [#7205](https://github.com/leanprover/lean4/pull/7205) completes alignment of
`List.getLast`/`List.getLast!`/`List.getLast?` lemmas with the
corresponding lemmas for Array and Vector.
* [#7206](https://github.com/leanprover/lean4/pull/7206) adds theorem `BitVec.toFin_abs`, completing the API for
`BitVec.*_abs`.
* [#7207](https://github.com/leanprover/lean4/pull/7207) provides lemmas for the tree map functions `get`, `get!` and
`getD` in relation to the other operations for which lemmas already
exist.
* [#7208](https://github.com/leanprover/lean4/pull/7208) aligns lemmas for `List.dropLast` / `Array.pop` / `Vector.pop`.
* [#7210](https://github.com/leanprover/lean4/pull/7210) adds the remaining lemmas about iterated conversions between
finite types starting with something of type `UIntX`.
* [#7214](https://github.com/leanprover/lean4/pull/7214) adds a `ForIn` instance for the `PersistentHashSet` type.
* [#7221](https://github.com/leanprover/lean4/pull/7221) provides lemmas about the tree map functions `getKey?`,
`getKey`, `getKey!`, `getKeyD` and `insertIfNew` and their interaction
with other functions for which lemmas already exist.
* [#7222](https://github.com/leanprover/lean4/pull/7222) removes the `simp` attribute from `ReflCmp.compare_self` because
it matches arbitrary function applications. Instead, a new `simp` lemma
`ReflOrd.compare_self` is introduced, which only matches applications of
`compare`.
* [#7229](https://github.com/leanprover/lean4/pull/7229) provides lemmas for the tree map function `getThenInsertIfNew?`.
* [#7235](https://github.com/leanprover/lean4/pull/7235) adds `Array.replace` and `Vector.replace`, proves the
correspondences with `List.replace`, and reproduces the basic API. In
order to do so, it fills in some gaps in the `List.findX` APIs.
* [#7237](https://github.com/leanprover/lean4/pull/7237) provides proofs that the raw tree map operations are well-formed
and refactors the file structure of the tree map, introducing new
modules `Std.{DTreeMap,TreeMap,TreeSet}.Raw` and splittting
`AdditionalOperations` into separate files for bundled and raw types.
* [#7245](https://github.com/leanprover/lean4/pull/7245) adds missing `@[specialize]` annotations to the `alter` and
`modify` functions in `Std.Data.DHashMap.Internal.AssocList`, which are
used by the corresponding hash map functions.
* [#7249](https://github.com/leanprover/lean4/pull/7249) completes alignment of theorems about
`List/Array/Vector.any/all`.
* [#7255](https://github.com/leanprover/lean4/pull/7255) fixes the definition of `Min (Option α)`. This is a breaking
change. This treats `none` as the least element,
so `min none x = min x none = none` for all `x : Option α`. Prior to
nightly-2025-02-27, we instead had `min none (some x) = min (some x)
none = some x`. Also adds basic lemmas relating `min`, `max`, `≤` and
`<` on `Option`.
* [#7259](https://github.com/leanprover/lean4/pull/7259) contains theorems about `IntX` that are required for `bv_decide`
and the `IntX` simprocs.
* [#7260](https://github.com/leanprover/lean4/pull/7260) provides lemmas about the tree map functions `keys` and `toList`
and their interactions with other functions for which lemmas already
exist. Moreover, a bug in `foldr` (calling `foldlM` instead of `foldrM`)
is fixed.
* [#7266](https://github.com/leanprover/lean4/pull/7266) begins the alignment of `Int.ediv/fdiv/tdiv` theorems.
* [#7268](https://github.com/leanprover/lean4/pull/7268) implements `Lean.ToExpr` for finite signed integers.
* [#7271](https://github.com/leanprover/lean4/pull/7271) changes the order of arguments of the folding function expected
by the tree map's `foldr` and `foldrM` functions so that they are
consistent with the API of `List`.
* [#7273](https://github.com/leanprover/lean4/pull/7273) fixes the statement of a `UIntX` conversion lemma.
* [#7277](https://github.com/leanprover/lean4/pull/7277) fixes a bug in Float32.ofInt, which previously returned a
Float(64).
## Compiler
* [#6928](https://github.com/leanprover/lean4/pull/6928) makes extern decls evaluate as ⊤ rather than the default value
of ⊥ in the LCNF elimDeadBranches analysis.
* [#6930](https://github.com/leanprover/lean4/pull/6930) changes the name generation of specialized LCNF decls so they
don't strip macro scopes. This avoids name collisions for
specializations created in distinct macro scopes. Since the normal
Name.append function checks for the presence of macro scopes, we need to
use appendCore.
* [#6976](https://github.com/leanprover/lean4/pull/6976) extends the behavior of the `sync` flag for `Task.map/bind` etc.
to encompass synchronous execution even when they first have to wait on
completion of the first task, drastically lowering the overhead of such
tasks. Thus the flag is now equivalent to e.g. .NET's
`TaskContinuationOptions.ExecuteSynchronously`.
* [#7037](https://github.com/leanprover/lean4/pull/7037) relaxes the minimum required glibc version for Lean and Lean
executables to 2.26 on x86-64 Linux
* [#7041](https://github.com/leanprover/lean4/pull/7041) marks several LCNF-specific environment extensions as having an
asyncMode of .sync rather than the default of .mainOnly, so they work
correctly even in async contexts.
* [#7086](https://github.com/leanprover/lean4/pull/7086) makes the arity reduction pass in the new code generator match
the old one when it comes to the behavior of decls with no used
parameters. This is important, because otherwise we might create a
top-level decl with no params that contains unreachable code, which
would get evaluated unconditionally during initialization. This actually
happens when initializing Init.Core built with the new code generator.
## Pretty Printing
* [#7074](https://github.com/leanprover/lean4/pull/7074) modifies the signature pretty printer to add hover information
for parameters in binders. This makes the binders be consistent with the
hovers in pi types.
## Documentation
* [#6886](https://github.com/leanprover/lean4/pull/6886) adds recommended spellings for many notations defined in Lean
core, using the `recommended_spelling` command from #6869.
* [#6950](https://github.com/leanprover/lean4/pull/6950) adds a style guide and a naming convention for the standard
library.
* [#6962](https://github.com/leanprover/lean4/pull/6962) improves the doc-string for `List.toArray`.
* [#6998](https://github.com/leanprover/lean4/pull/6998) modifies the `Prop` docstring to point out that every
proposition is propositionally equal to either `True` or `False`. This
will help point users toward seeing that `Prop` is like `Bool`.
* [#7026](https://github.com/leanprover/lean4/pull/7026) clarifies the styling of `do` blocks, and enhances the naming
conventions with information about the `ext` and `mono` name components
as well as advice about primed names and naming of simp sets.
* [#7111](https://github.com/leanprover/lean4/pull/7111) extends the standard library style guide with guidance on
universe variables, notations and Unicode usage, and structure
definitions.
## Server
* [#6329](https://github.com/leanprover/lean4/pull/6329) enables the language server to present multiple disjoint line
ranges as being worked on. Even before parallelism lands, we make use of
this feature to show post-elaboration tasks such as kernel checking on
the first line of a declaration to distinguish them from the final
tactic step.
* [#6768](https://github.com/leanprover/lean4/pull/6768) adds preliminary support for inlay hints, as well as support for
inlay hints that denote the auto-implicits of a function. Hovering over
an auto-implicit displays its type and double-clicking the auto-implicit
inserts it into the text document.
**Breaking Change**: The semantic highlighting request handler is not a pure
request handler anymore, but a stateful one. Notably, this means that clients
that extend the semantic highlighting of the Lean language server with the
`chainLspRequestHandler` function must now use the `chainStatefulLspRequestHandler`
function instead.
* [#6887](https://github.com/leanprover/lean4/pull/6887) fixes a bug where the goal state selection would sometimes
select incomplete incremental snapshots on whitespace, leading to an
incorrect "no goals" response. Fixes #6594, a regression that was
originally introduced in 4.11.0 by #4727.
* [#6959](https://github.com/leanprover/lean4/pull/6959) implements a number of refinements for the auto-implicit inlay
hints implemented in #6768.
Specifically:
- In #6768, there was a bug where the inlay hint edit delay could
accumulate on successive edits, which meant that it could sometimes take
much longer for inlay hints to show up. implements the basic
infrastructure for request cancellation and implements request
cancellation for semantic tokens and inlay hints to resolve the issue.
With this edit delay bug fixed, it made more sense to increase the edit
delay slightly from 2000ms to 3000ms.
- In #6768, we applied the edit delay to every single inlay hint request
in order to reduce the amount of inlay hint flickering. This meant that
the edit delay also had a significant effect on how far inlay hints
would lag behind the file progress bar. adjusts the edit delay
logic so that it only affects requests sent directly after a
corresponding `didChange` notification. Once the edit delay is used up,
all further semantic token requests are responded to without delay, so
that the only latency that affects how far the inlay hints lag behind
the progress bar is how often we emit refresh requests and how long VS
Code takes to respond to them.
- For inlay hints, refresh requests are now emitted 500ms after a
response to an inlay hint request, not 2000ms, which means that after
the edit delay, inlay hints should only lag behind the progress bar by
about up to 500ms. This is justifiable for inlay hints because the
response should be much smaller than e.g. is the case for semantic
tokens.
- In #6768, 'Restart File' did not prompt a refresh, but it does now.
- VS Code does not immediately remove old inlay hints from the document
when they are applied. In #6768, this meant that inlay hints would
linger around for a bit once applied. To mitigate this issue, this PR
adjusts the inlay hint edit delay logic to identify edits sent from the
client as being inlay hint applications, and sets the edit delay to 0ms
for the inlay hint requests following it. This means that inlay hints
are now applied immediately.
- In #6768, hovering over single-letter auto-implicit inlay hints was a
bit finicky because VS Code uses the regular cursor icon on inlay hints,
not the thin text cursor icon, which means that it is easy to put the
cursor in the wrong spot. We now add the separation character (` ` or
`{`) preceding an auto-implicit to the hover range as well, which makes
hovering over inlay hints much smoother.
* [#6978](https://github.com/leanprover/lean4/pull/6978) fixes a bug where both the inlay hint change invalidation logic
and the inlay hint edit delay logic were broken in untitled files.
Thanks to @Julian for spotting this!
* [#7054](https://github.com/leanprover/lean4/pull/7054) adds language server support for request cancellation to the
following expensive requests: Code actions, auto-completion, document
symbols, folding ranges and semantic highlighting. This means that when
the client informs the language server that a request is stale (e.g.
because it belongs to a previous state of the document), the language
server will now prematurely cancel the computation of the response in
order to reduce the CPU load for requests that will be discarded by the
client anyways.
* [#7087](https://github.com/leanprover/lean4/pull/7087) ensures that all tasks in the language server either use
dedicated tasks or reuse an existing thread from the thread pool. This
ensures that elaboration tasks cannot prevent language server tasks from
being scheduled. This is especially important with parallelism right
around the corner and elaboration becoming more likely to starve the
language server of computation, which could drive up language server
latencies significantly on machines with few cores.
* [#7112](https://github.com/leanprover/lean4/pull/7112) adds a tooltip describing what the auto-implicit inlay hints
denote, as well as auto-implicit inlay hints for instances.
* [#7134](https://github.com/leanprover/lean4/pull/7134) significantly improves the performance of auto-completion by
optimizing individual requests by a factor of ~2 and by giving language
clients like VS Code the opportunity to reuse the state of previous
completion requests, thus greatly reducing the latency for the
auto-completion list to update when adding more characters to an
identifier.
* [#7143](https://github.com/leanprover/lean4/pull/7143) makes the server consistently not report newlines between trace
nodes to the info view, enabling it to render them on dedicates lines
without extraneous spacing between them in all circumstances.
* [#7149](https://github.com/leanprover/lean4/pull/7149) adds a fast path to the inlay hint request that makes it reuse
already computed inlay hints from previous requests instead of
re-computing them. This is necessary because for some reason VS Code
emits an inlay hint request for every line you scroll, so we need to be
able to respond to these requests against the same document state
quickly. Otherwise, every single scrolled line would result in a request
that can take a few dozen ms to be responded to in long files, putting
unnecessary pressure on the CPU.
It also filters the result set by the inlay hints that have been
requested.
* [#7153](https://github.com/leanprover/lean4/pull/7153) changes the server to run `lake setup-file` on Lake
configuration files (e.g., `lakefile.lean`).
* [#7175](https://github.com/leanprover/lean4/pull/7175) fixes an `Elab.async` regression where elaboration tasks are
cancelled on document edit even though their result may be reused in the
new document version, reporting an incomplete result.
## Lake
* [#6829](https://github.com/leanprover/lean4/pull/6829) changes the error message for Lake configuration failure to
reflect that issues do not always arise from an invalid lakefile, but
sometimes arise from other issues like network errors. The new error
message encompasses all of these possibilities.
* [#6929](https://github.com/leanprover/lean4/pull/6929) passes the shared library of the previous stage's Lake as a
plugin to the next stage's Lake in the CMake build. This enables Lake to
use its own builtin elaborators / initializers at build time.
* [#7001](https://github.com/leanprover/lean4/pull/7001) adds support for plugins to Lake. Precompiled modules are now
loaded as plugins rather than via `--load-dynlib`.
* [#7024](https://github.com/leanprover/lean4/pull/7024) documents how to use Elan's `+` option with `lake new|init`. It
also provides an more informative error message if a `+` option leaks
into Lake (e.g., if a user provides the option to a Lake run without
Elan).
* [#7157](https://github.com/leanprover/lean4/pull/7157) changes `lake setup-file` to now use Lake as a plugin for files
which import Lake (or one of its submodules). Thus, the server will now
load Lake as a plugin when editing a Lake configuration written in Lean.
This further enables the use of builtin language extensions in Lake.
* [#7171](https://github.com/leanprover/lean4/pull/7171) changes the Lake DSL to use builtin elaborators, macros, and
initializers.
* [#7182](https://github.com/leanprover/lean4/pull/7182) makes `lake setup-file` succeed on an invalid Lean configuration
file.
* [#7209](https://github.com/leanprover/lean4/pull/7209) fixes broken Lake tests on Windows' new MSYS2. As of MSYS2
0.0.20250221, `OSTYPE` is now reported as `cygwin` instead of `msys`,
which must be accounted for in a few Lake tests.
* [#7211](https://github.com/leanprover/lean4/pull/7211) changes the job monitor to perform run job computation itself as
a separate job. Now progress will be reported eagerly, even before all
outstanding jobs have been discovered. Thus, the total job number
reported can now grow while jobs are still being computed (e.g., the `Y`
in `[X/Y[` may increase).
* [#7233](https://github.com/leanprover/lean4/pull/7233) uses the Lake plugin when Lake is built with Lake via
`USE_LAKE`.
* [#7291](https://github.com/leanprover/lean4/pull/7291) changes the Lake job monitor to display the last (i.e., newest)
running/unfinished job rather than the first. This avoids the monitor
focusing too long on any one job (e.g., "Running job computation").
* [#7399](https://github.com/leanprover/lean4/pull/7399) reverts the new builtin initializers, elaborators, and macros in
Lake back to non-builtin.
* [#7608](https://github.com/leanprover/lean4/pull/7608) removes the use of the Lake plugin in the Lake build and in
configuration files.
## Other
* [#7129](https://github.com/leanprover/lean4/pull/7129) optimizes the performance of the unused variables linter in the
case of a definition with a huge `Expr` representation
* [#7173](https://github.com/leanprover/lean4/pull/7173) introduces a trace node for each deriving handlers invocation
for the benefit of `trace.profiler`
* [#7184](https://github.com/leanprover/lean4/pull/7184) adds support for LEAN_BACKTRACE on macOS. This previously only
worked with glibc, but it can not be enabled for all Unix-like systems,
since e.g. Musl does not support it.
* [#7190](https://github.com/leanprover/lean4/pull/7190) makes the stage2 Leanc build use the stage2 oleans rather than
stage1 oleans. This was happening because Leanc's own OLEAN_OUT is at
the build root rather than the lib/lean subdirectory, so when the build
added this OLEAN_OUT to LEAN_PATH no oleans were found there and the
search fell back to the stage1 installation location.
```` |
reference-manual/Manual/Releases/v4_20_1.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.20.1 (2025-06-04)" =>
%%%
tag := "release-v4.20.1"
file := "v4.20.1"
%%%
```markdown
The 4.20.1 point release addresses a metaprogramming regression in `Lean.Environment.addDeclCore` ([#8610](https://github.com/leanprover/lean4/pull/8610)).
``` |
reference-manual/Manual/Releases/v4_6_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.6.0 (2024-02-29)" =>
%%%
tag := "release-v4.6.0"
file := "v4.6.0"
%%%
````markdown
* Add custom simplification procedures (aka `simproc`s) to `simp`. Simprocs can be triggered by the simplifier on a specified term-pattern. Here is an small example:
```lean
import Lean.Meta.Tactic.Simp.BuiltinSimprocs.Nat
def foo (x : Nat) : Nat :=
x + 10
/--
The `simproc` `reduceFoo` is invoked on terms that match the pattern `foo _`.
-/
simproc reduceFoo (foo _) :=
/- A term of type `Expr → SimpM Step -/
fun e => do
/-
The `Step` type has three constructors: `.done`, `.visit`, `.continue`.
* The constructor `.done` instructs `simp` that the result does
not need to be simplified further.
* The constructor `.visit` instructs `simp` to visit the resulting expression.
* The constructor `.continue` instructs `simp` to try other simplification procedures.
All three constructors take a `Result`. The `.continue` constructor may also take `none`.
`Result` has two fields `expr` (the new expression), and `proof?` (an optional proof).
If the new expression is definitionally equal to the input one, then `proof?` can be omitted or set to `none`.
-/
/- `simp` uses matching modulo reducibility. So, we ensure the term is a `foo`-application. -/
unless e.isAppOfArity ``foo 1 do
return .continue
/- `Nat.fromExpr?` tries to convert an expression into a `Nat` value -/
let some n ← Nat.fromExpr? e.appArg!
| return .continue
return .done { expr := Lean.mkNatLit (n+10) }
```
We disable simprocs support by using the command `set_option simprocs false`. This command is particularly useful when porting files to v4.6.0.
Simprocs can be scoped, manually added to `simp` commands, and suppressed using `-`. They are also supported by `simp?`. `simp only` does not execute any `simproc`. Here are some examples for the `simproc` defined above.
```lean
example : x + foo 2 = 12 + x := by
set_option simprocs false in
/- This `simp` command does not make progress since `simproc`s are disabled. -/
fail_if_success simp
simp_arith
example : x + foo 2 = 12 + x := by
/- `simp only` must not use the default simproc set. -/
fail_if_success simp only
simp_arith
example : x + foo 2 = 12 + x := by
/-
`simp only` does not use the default simproc set,
but we can provide simprocs as arguments. -/
simp only [reduceFoo]
simp_arith
example : x + foo 2 = 12 + x := by
/- We can use `-` to disable `simproc`s. -/
fail_if_success simp [-reduceFoo]
simp_arith
```
The command `register_simp_attr <id>` now creates a `simp` **and** a `simproc` set with the name `<id>`. The following command instructs Lean to insert the `reduceFoo` simplification procedure into the set `my_simp`. If no set is specified, Lean uses the default `simp` set.
```lean
simproc [my_simp] reduceFoo (foo _) := ...
```
* The syntax of the `termination_by` and `decreasing_by` termination hints is overhauled:
* They are now placed directly after the function they apply to, instead of
after the whole `mutual` block.
* Therefore, the function name no longer has to be mentioned in the hint.
* If the function has a `where` clause, the `termination_by` and
`decreasing_by` for that function come before the `where`. The
functions in the `where` clause can have their own termination hints, each
following the corresponding definition.
* The `termination_by` clause can only bind “extra parameters”, that are not
already bound by the function header, but are bound in a lambda (`:= fun x
y z =>`) or in patterns (`| x, n + 1 => …`). These extra parameters used to
be understood as a suffix of the function parameters; now it is a prefix.
Migration guide: In simple cases just remove the function name, and any
variables already bound at the header.
```diff
def foo : Nat → Nat → Nat := …
-termination_by foo a b => a - b
+termination_by a b => a - b
```
or
```diff
def foo : Nat → Nat → Nat := …
-termination_by _ a b => a - b
+termination_by a b => a - b
```
If the parameters are bound in the function header (before the `:`), remove them as well:
```diff
def foo (a b : Nat) : Nat := …
-termination_by foo a b => a - b
+termination_by a - b
```
Else, if there are multiple extra parameters, make sure to refer to the right
ones; the bound variables are interpreted from left to right, no longer from
right to left:
```diff
def foo : Nat → Nat → Nat → Nat
| a, b, c => …
-termination_by foo b c => b
+termination_by a b => b
```
In the case of a `mutual` block, place the termination arguments (without the
function name) next to the function definition:
```diff
-mutual
-def foo : Nat → Nat → Nat := …
-def bar : Nat → Nat := …
-end
-termination_by
- foo a b => a - b
- bar a => a
+mutual
+def foo : Nat → Nat → Nat := …
+termination_by a b => a - b
+def bar : Nat → Nat := …
+termination_by a => a
+end
```
Similarly, if you have (mutual) recursion through `where` or `let rec`, the
termination hints are now placed directly after the function they apply to:
```diff
-def foo (a b : Nat) : Nat := …
- where bar (x : Nat) : Nat := …
-termination_by
- foo a b => a - b
- bar x => x
+def foo (a b : Nat) : Nat := …
+termination_by a - b
+ where
+ bar (x : Nat) : Nat := …
+ termination_by x
-def foo (a b : Nat) : Nat :=
- let rec bar (x : Nat) : Nat := …
- …
-termination_by
- foo a b => a - b
- bar x => x
+def foo (a b : Nat) : Nat :=
+ let rec bar (x : Nat) : Nat := …
+ termination_by x
+ …
+termination_by a - b
```
In cases where a single `decreasing_by` clause applied to multiple mutually
recursive functions before, the tactic now has to be duplicated.
* The semantics of `decreasing_by` changed; the tactic is applied to all
termination proof goals together, not individually.
This helps when writing termination proofs interactively, as one can focus
each subgoal individually, for example using `·`. Previously, the given
tactic script had to work for _all_ goals, and one had to resort to tactic
combinators like `first`:
```diff
def foo (n : Nat) := … foo e1 … foo e2 …
-decreasing_by
-simp_wf
-first | apply something_about_e1; …
- | apply something_about_e2; …
+decreasing_by
+all_goals simp_wf
+· apply something_about_e1; …
+· apply something_about_e2; …
```
To obtain the old behaviour of applying a tactic to each goal individually,
use `all_goals`:
```diff
def foo (n : Nat) := …
-decreasing_by some_tactic
+decreasing_by all_goals some_tactic
```
In the case of mutual recursion each `decreasing_by` now applies to just its
function. If some functions in a recursive group do not have their own
`decreasing_by`, the default `decreasing_tactic` is used. If the same tactic
ought to be applied to multiple functions, the `decreasing_by` clause has to
be repeated at each of these functions.
* Modify `InfoTree.context` to facilitate augmenting it with partial contexts while elaborating a command. This breaks backwards compatibility with all downstream projects that traverse the `InfoTree` manually instead of going through the functions in `InfoUtils.lean`, as well as those manually creating and saving `InfoTree`s. See [PR #3159](https://github.com/leanprover/lean4/pull/3159) for how to migrate your code.
* Add language server support for [call hierarchy requests](https://www.youtube.com/watch?v=r5LA7ivUb2c) ([PR #3082](https://github.com/leanprover/lean4/pull/3082)). The change to the .ilean format in this PR means that projects must be fully rebuilt once in order to generate .ilean files with the new format before features like "find references" work correctly again.
* Structure instances with multiple sources (for example `{a, b, c with x := 0}`) now have their fields filled from these sources
in strict left-to-right order. Furthermore, the structure instance elaborator now aggressively use sources to fill in subobject
fields, which prevents unnecessary eta expansion of the sources,
and hence greatly reduces the reliance on costly structure eta reduction. This has a large impact on mathlib,
reducing total CPU instructions by 3% and enabling impactful refactors like leanprover-community/mathlib4#8386
which reduces the build time by almost 20%.
See [PR #2478](https://github.com/leanprover/lean4/pull/2478) and [RFC #2451](https://github.com/leanprover/lean4/issues/2451).
* Add pretty printer settings to omit deeply nested terms (`pp.deepTerms false` and `pp.deepTerms.threshold`) ([PR #3201](https://github.com/leanprover/lean4/pull/3201))
* Add pretty printer options `pp.numeralTypes` and `pp.natLit`.
When `pp.numeralTypes` is true, then natural number literals, integer literals, and rational number literals
are pretty printed with type ascriptions, such as `(2 : Rat)`, `(-2 : Rat)`, and `(-2 / 3 : Rat)`.
When `pp.natLit` is true, then raw natural number literals are pretty printed as `nat_lit 2`.
[PR #2933](https://github.com/leanprover/lean4/pull/2933) and [RFC #3021](https://github.com/leanprover/lean4/issues/3021).
Lake updates:
* improved platform information & control [#3226](https://github.com/leanprover/lean4/pull/3226)
* `lake update` from unsupported manifest versions [#3149](https://github.com/leanprover/lean4/pull/3149)
Other improvements:
* make `intro` be aware of `let_fun` [#3115](https://github.com/leanprover/lean4/pull/3115)
* produce simpler proof terms in `rw` [#3121](https://github.com/leanprover/lean4/pull/3121)
* fuse nested `mkCongrArg` calls in proofs generated by `simp` [#3203](https://github.com/leanprover/lean4/pull/3203)
* `induction using` followed by a general term [#3188](https://github.com/leanprover/lean4/pull/3188)
* allow generalization in `let` [#3060](https://github.com/leanprover/lean4/pull/3060), fixing [#3065](https://github.com/leanprover/lean4/issues/3065)
* reducing out-of-bounds `swap!` should return `a`, not `default`` [#3197](https://github.com/leanprover/lean4/pull/3197), fixing [#3196](https://github.com/leanprover/lean4/issues/3196)
* derive `BEq` on structure with `Prop`-fields [#3191](https://github.com/leanprover/lean4/pull/3191), fixing [#3140](https://github.com/leanprover/lean4/issues/3140)
* refine through more `casesOnApp`/`matcherApp` [#3176](https://github.com/leanprover/lean4/pull/3176), fixing [#3175](https://github.com/leanprover/lean4/pull/3175)
* do not strip dotted components from lean module names [#2994](https://github.com/leanprover/lean4/pull/2994), fixing [#2999](https://github.com/leanprover/lean4/issues/2999)
* fix `deriving` only deriving the first declaration for some handlers [#3058](https://github.com/leanprover/lean4/pull/3058), fixing [#3057](https://github.com/leanprover/lean4/issues/3057)
* do not instantiate metavariables in kabstract/rw for disallowed occurrences [#2539](https://github.com/leanprover/lean4/pull/2539), fixing [#2538](https://github.com/leanprover/lean4/issues/2538)
* hover info for `cases h : ...` [#3084](https://github.com/leanprover/lean4/pull/3084)
```` |
reference-manual/Manual/Releases/v4_0_0-m4.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.0.0-m4 (2022-03-27)" =>
%%%
tag := "release-v4.0.0-m4"
file := "v4.0.0-m4"
%%%
````markdown
This is the fourth milestone release of Lean 4. It contains many improvements and many new features.
We had more than 600 commits since the last milestone.
Contributors:
```
$ git shortlog -s -n v4.0.0-m3..v4.0.0-m4
501 Leonardo de Moura
65 Sebastian Ullrich
11 Daniel Fabian
10 larsk21
5 Gabriel Ebner
2 E.W.Ayers
2 Jonathan Coates
2 Joscha
2 Mario Carneiro
2 ammkrn
1 Chris Lovett
1 François G. Dorais
1 Jakob von Raumer
1 Lars
1 Patrick Stevens
1 Wojciech Nawrocki
1 Xubai Wang
1 casavaca
1 zygi
```
* `simp` now takes user-defined simp-attributes. You can define a new `simp` attribute by creating a file (e.g., `MySimp.lean`) containing
```lean
import Lean
open Lean.Meta
initialize my_ext : SimpExtension ← registerSimpAttr `my_simp "my own simp attribute"
```
If you don't need to access `my_ext`, you can also use the macro
```lean
import Lean
register_simp_attr my_simp "my own simp attribute"
```
Recall that the new `simp` attribute is not active in the Lean file where it was defined.
Here is a small example using the new feature.
```lean
import MySimp
def f (x : Nat) := x + 2
def g (x : Nat) := x + 1
@[my_simp] theorem f_eq : f x = x + 2 := rfl
@[my_simp] theorem g_eq : g x = x + 1 := rfl
example : f x + g x = 2*x + 3 := by
simp_arith [my_simp]
```
* Extend `match` syntax: multiple left-hand-sides in a single alternative. Example:
```lean
def fib : Nat → Nat
| 0 | 1 => 1
| n+2 => fib n + fib (n+1)
```
This feature was discussed at [issue 371](https://github.com/leanprover/lean4/issues/371). It was implemented as a macro expansion. Thus, the following is accepted.
```lean
inductive StrOrNum where
| S (s : String)
| I (i : Int)
def StrOrNum.asString (x : StrOrNum) :=
match x with
| I a | S a => toString a
```
* Improve `#eval` command. Now, when it fails to synthesize a `Lean.MetaEval` instance for the result type, it reduces the type and tries again. The following example now works without additional annotations
```lean
def Foo := List Nat
def test (x : Nat) : Foo :=
[x, x+1, x+2]
#eval test 4
```
* `rw` tactic can now apply auto-generated equation theorems for a given definition. Example:
```lean
example (a : Nat) (h : n = 1) : [a].length = n := by
rw [List.length]
trace_state -- .. |- [].length + 1 = n
rw [List.length]
trace_state -- .. |- 0 + 1 = n
rw [h]
```
* [Fuzzy matching for auto completion](https://github.com/leanprover/lean4/pull/1023)
* Extend dot-notation `x.field` for arrow types. If type of `x` is an arrow, we look up for `Function.field`.
For example, given `f : Nat → Nat` and `g : Nat → Nat`, `f.comp g` is now notation for `Function.comp f g`.
* The new `.<identifier>` notation is now also accepted where a function type is expected.
```lean
example (xs : List Nat) : List Nat := .map .succ xs
example (xs : List α) : Std.RBTree α ord := xs.foldl .insert ∅
```
* [Add code folding support to the language server](https://github.com/leanprover/lean4/pull/1014).
* Support notation `let <pattern> := <expr> | <else-case>` in `do` blocks.
* Remove support for "auto" `pure`. In the [Zulip thread](https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/for.2C.20unexpected.20need.20for.20type.20ascription/near/269083574), the consensus seemed to be that "auto" `pure` is more confusing than it's worth.
* Remove restriction in `congr` theorems that all function arguments on the left-hand-side must be free variables. For example, the following theorem is now a valid `congr` theorem.
```lean
@[congr]
theorem dep_congr [DecidableEq ι] {p : ι → Set α} [∀ i, Inhabited (p i)] :
∀ {i j} (h : i = j) (x : p i) (y : α) (hx : x = y), Pi.single (f := (p ·)) i x = Pi.single (f := (p ·)) j ⟨y, hx ▸ h ▸ x.2⟩ :=
```
* [Partially applied congruence theorems.](https://github.com/leanprover/lean4/issues/988)
* Improve elaboration postponement heuristic when expected type is a metavariable. Lean now reduces the expected type before performing the test.
* [Remove deprecated leanpkg](https://github.com/leanprover/lean4/pull/985) in favor of [Lake](https://github.com/leanprover/lake) now bundled with Lean.
* Various improvements to go-to-definition & find-all-references accuracy.
* Auto generated congruence lemmas with support for casts on proofs and `Decidable` instances (see [wishlist](https://github.com/leanprover/lean4/issues/988)).
* Rename option `autoBoundImplicitLocal` => `autoImplicit`.
* [Relax auto-implicit restrictions](https://github.com/leanprover/lean4/pull/1011). The command `set_option relaxedAutoImplicit false` disables the relaxations.
* `contradiction` tactic now closes the goal if there is a `False.elim` application in the target.
* Renamed tatic `byCases` => `by_cases` (motivation: enforcing naming convention).
* Local instances occurring in patterns are now considered by the type class resolution procedure. Example:
```lean
def concat : List ((α : Type) × ToString α × α) → String
| [] => ""
| ⟨_, _, a⟩ :: as => toString a ++ concat as
```
* Notation for providing the motive for `match` expressions has changed.
before:
```lean
match x, rfl : (y : Nat) → x = y → Nat with
| 0, h => ...
| x+1, h => ...
```
now:
```lean
match (motive := (y : Nat) → x = y → Nat) x, rfl with
| 0, h => ...
| x+1, h => ...
```
With this change, the notation for giving names to equality proofs in `match`-expressions is not whitespace sensitive anymore. That is,
we can now write
```lean
match h : sort.swap a b with
| (r₁, r₂) => ... -- `h : sort.swap a b = (r₁, r₂)`
```
* `(generalizing := true)` is the default behavior for `match` expressions even if the expected type is not a proposition. In the following example, we used to have to include `(generalizing := true)` manually.
```lean
inductive Fam : Type → Type 1 where
| any : Fam α
| nat : Nat → Fam Nat
example (a : α) (x : Fam α) : α :=
match x with
| Fam.any => a
| Fam.nat n => n
```
* We now use `PSum` (instead of `Sum`) when compiling mutually recursive definitions using well-founded recursion.
* Better support for parametric well-founded relations. See [issue #1017](https://github.com/leanprover/lean4/issues/1017). This change affects the low-level `termination_by'` hint because the fixed prefix of the function parameters in not "packed" anymore when constructing the well-founded relation type. For example, in the following definition, `as` is part of the fixed prefix, and is not packed anymore. In previous versions, the `termination_by'` term would be written as `measure fun ⟨as, i, _⟩ => as.size - i`
```lean
def sum (as : Array Nat) (i : Nat) (s : Nat) : Nat :=
if h : i < as.size then
sum as (i+1) (s + as.get ⟨i, h⟩)
else
s
termination_by' measure fun ⟨i, _⟩ => as.size - i
```
* Add `while <cond> do <do-block>`, `repeat <do-block>`, and `repeat <do-block> until <cond>` macros for `do`-block. These macros are based on `partial` definitions, and consequently are useful only for writing programs we don't want to prove anything about.
* Add `arith` option to `Simp.Config`, the macro `simp_arith` expands to `simp (config := { arith := true })`. Only `Nat` and linear arithmetic is currently supported. Example:
```lean
example : 0 < 1 + x ∧ x + y + 2 ≥ y + 1 := by
simp_arith
```
* Add `fail <string>?` tactic that always fail.
* Add support for acyclicity at dependent elimination. See [issue #1022](https://github.com/leanprover/lean4/issues/1022).
* Add `trace <string>` tactic for debugging purposes.
* Add nontrivial `SizeOf` instance for types `Unit → α`, and add support for them in the auto-generated `SizeOf` instances for user-defined inductive types. For example, given the inductive datatype
```lean
inductive LazyList (α : Type u) where
| nil : LazyList α
| cons (hd : α) (tl : LazyList α) : LazyList α
| delayed (t : Thunk (LazyList α)) : LazyList α
```
we now have `sizeOf (LazyList.delayed t) = 1 + sizeOf t` instead of `sizeOf (LazyList.delayed t) = 2`.
* Add support for guessing (very) simple well-founded relations when proving termination. For example, the following function does not require a `termination_by` annotation anymore.
```lean
def Array.insertAtAux (i : Nat) (as : Array α) (j : Nat) : Array α :=
if h : i < j then
let as := as.swap! (j-1) j;
insertAtAux i as (j-1)
else
as
```
* Add support for `for h : x in xs do ...` notation where `h : x ∈ xs`. This is mainly useful for showing termination.
* Auto implicit behavior changed for inductive families. An auto implicit argument occurring in inductive family index is also treated as an index (IF it is not fixed, see next item). For example
```lean
inductive HasType : Index n → Vector Ty n → Ty → Type where
```
is now interpreted as
```lean
inductive HasType : {n : Nat} → Index n → Vector Ty n → Ty → Type where
```
* To make the previous feature more convenient to use, we promote a fixed prefix of inductive family indices to parameters. For example, the following declaration is now accepted by Lean
```lean
inductive Lst : Type u → Type u
| nil : Lst α
| cons : α → Lst α → Lst α
```
and `α` in `Lst α` is a parameter. The actual number of parameters can be inspected using the command `#print Lst`. This feature also makes sure we still accept the declaration
```lean
inductive Sublist : List α → List α → Prop
| slnil : Sublist [] []
| cons l₁ l₂ a : Sublist l₁ l₂ → Sublist l₁ (a :: l₂)
| cons2 l₁ l₂ a : Sublist l₁ l₂ → Sublist (a :: l₁) (a :: l₂)
```
* Added auto implicit "chaining". Unassigned metavariables occurring in the auto implicit types now become new auto implicit locals. Consider the following example:
```lean
inductive HasType : Fin n → Vector Ty n → Ty → Type where
| stop : HasType 0 (ty :: ctx) ty
| pop : HasType k ctx ty → HasType k.succ (u :: ctx) ty
```
`ctx` is an auto implicit local in the two constructors, and it has type `ctx : Vector Ty ?m`. Without auto implicit "chaining", the metavariable `?m` will remain unassigned. The new feature creates yet another implicit local `n : Nat` and assigns `n` to `?m`. So, the declaration above is shorthand for
```lean
inductive HasType : {n : Nat} → Fin n → Vector Ty n → Ty → Type where
| stop : {ty : Ty} → {n : Nat} → {ctx : Vector Ty n} → HasType 0 (ty :: ctx) ty
| pop : {n : Nat} → {k : Fin n} → {ctx : Vector Ty n} → {ty : Ty} → HasType k ctx ty → HasType k.succ (u :: ctx) ty
```
* Eliminate auxiliary type annotations (e.g, `autoParam` and `optParam`) from recursor minor premises and projection declarations. Consider the following example
```lean
structure A :=
x : Nat
h : x = 1 := by trivial
example (a : A) : a.x = 1 := by
have aux := a.h
-- `aux` has now type `a.x = 1` instead of `autoParam (a.x = 1) auto✝`
exact aux
example (a : A) : a.x = 1 := by
cases a with
| mk x h =>
-- `h` has now type `x = 1` instead of `autoParam (x = 1) auto✝`
assumption
```
* We now accept overloaded notation in patterns, but we require the set of pattern variables in each alternative to be the same. Example:
```lean
inductive Vector (α : Type u) : Nat → Type u
| nil : Vector α 0
| cons : α → Vector α n → Vector α (n+1)
infix:67 " :: " => Vector.cons -- Overloading the `::` notation
def head1 (x : List α) (h : x ≠ []) : α :=
match x with
| a :: as => a -- `::` is `List.cons` here
def head2 (x : Vector α (n+1)) : α :=
match x with
| a :: as => a -- `::` is `Vector.cons` here
```
* New notation `.<identifier>` based on Swift. The namespace is inferred from the expected type. See [issue #944](https://github.com/leanprover/lean4/issues/944). Examples:
```lean
def f (x : Nat) : Except String Nat :=
if x > 0 then
.ok x
else
.error "x is zero"
namespace Lean.Elab
open Lsp
def identOf : Info → Option (RefIdent × Bool)
| .ofTermInfo ti => match ti.expr with
| .const n .. => some (.const n, ti.isBinder)
| .fvar id .. => some (.fvar id, ti.isBinder)
| _ => none
| .ofFieldInfo fi => some (.const fi.projName, false)
| _ => none
def isImplicit (bi : BinderInfo) : Bool :=
bi matches .implicit
end Lean.Elab
```
```` |
reference-manual/Manual/Releases/v4_10_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.10.0 (2024-07-31)" =>
%%%
tag := "release-v4.10.0"
file := "v4.10.0"
%%%
````markdown
### Language features, tactics, and metaprograms
* `split` tactic:
* [#4401](https://github.com/leanprover/lean4/pull/4401) improves the strategy `split` uses to generalize discriminants of matches and adds `trace.split.failure` trace class for diagnosing issues.
* `rw` tactic:
* [#4385](https://github.com/leanprover/lean4/pull/4385) prevents the tactic from claiming pre-existing goals are new subgoals.
* [dac1da](https://github.com/leanprover/lean4/commit/dac1dacc5b39911827af68247d575569d9c399b5) adds configuration for ordering new goals, like for `apply`.
* `simp` tactic:
* [#4430](https://github.com/leanprover/lean4/pull/4430) adds `dsimproc`s for `if` expressions (`ite` and `dite`).
* [#4434](https://github.com/leanprover/lean4/pull/4434) improves heuristics for unfolding. Equational lemmas now have priorities where more-specific equationals lemmas are tried first before a possible catch-all.
* [#4481](https://github.com/leanprover/lean4/pull/4481) fixes an issue where function-valued `OfNat` numeric literals would become denormalized.
* [#4467](https://github.com/leanprover/lean4/pull/4467) fixes an issue where dsimp theorems might not apply to literals.
* [#4484](https://github.com/leanprover/lean4/pull/4484) fixes the source position for the warning for deprecated simp arguments.
* [#4258](https://github.com/leanprover/lean4/pull/4258) adds docstrings for `dsimp` configuration.
* [#4567](https://github.com/leanprover/lean4/pull/4567) improves the accuracy of used simp lemmas reported by `simp?`.
* [fb9727](https://github.com/leanprover/lean4/commit/fb97275dcbb683efe6da87ed10a3f0cd064b88fd) adds (but does not implement) the simp configuration option `implicitDefEqProofs`, which will enable including `rfl`-theorems in proof terms.
* `omega` tactic:
* [#4360](https://github.com/leanprover/lean4/pull/4360) makes the tactic generate error messages lazily, improving its performance when used in tactic combinators.
* `bv_omega` tactic:
* [#4579](https://github.com/leanprover/lean4/pull/4579) works around changes to the definition of `Fin.sub` in this release.
* [#4490](https://github.com/leanprover/lean4/pull/4490) sets up groundwork for a tactic index in generated documentation, as there was in Lean 3. See PR description for details.
* **Commands**
* [#4370](https://github.com/leanprover/lean4/pull/4370) makes the `variable` command fully elaborate binders during validation, fixing an issue where some errors would be reported only at the next declaration.
* [#4408](https://github.com/leanprover/lean4/pull/4408) fixes a discrepancy in universe parameter order between `theorem` and `def` declarations.
* [#4493](https://github.com/leanprover/lean4/pull/4493) and
[#4482](https://github.com/leanprover/lean4/pull/4482) fix a discrepancy in the elaborators for `theorem`, `def`, and `example`,
making `Prop`-valued `example`s and other definition commands elaborate like `theorem`s.
* [8f023b](https://github.com/leanprover/lean4/commit/8f023b85c554186ae562774b8122322d856c674e), [3c4d6b](https://github.com/leanprover/lean4/commit/3c4d6ba8648eb04d90371eb3fdbd114d16949501) and [0783d0](https://github.com/leanprover/lean4/commit/0783d0fcbe31b626fbd3ed2f29d838e717f09101) change the `#reduce` command to be able to control what gets reduced.
For example, `#reduce (proofs := true) (types := false) e` reduces both proofs and types in the expression `e`.
By default, neither proofs or types are reduced.
* [#4489](https://github.com/leanprover/lean4/pull/4489) fixes an elaboration bug in `#check_tactic`.
* [#4505](https://github.com/leanprover/lean4/pull/4505) adds support for `open _root_.<namespace>`.
* **Options**
* [#4576](https://github.com/leanprover/lean4/pull/4576) adds the `debug.byAsSorry` option. Setting `set_option debug.byAsSorry true` causes all `by ...` terms to elaborate as `sorry`.
* [7b56eb](https://github.com/leanprover/lean4/commit/7b56eb20a03250472f4b145118ae885274d1f8f7) and [d8e719](https://github.com/leanprover/lean4/commit/d8e719f9ab7d049e423473dfc7a32867d32c856f) add the `debug.skipKernelTC` option. Setting `set_option debug.skipKernelTC true` turns off kernel typechecking. This is meant for temporarily working around kernel performance issues, and it compromises soundness since buggy tactics may produce invalid proofs, which will not be caught if this option is set to true.
* [#4301](https://github.com/leanprover/lean4/pull/4301)
adds a linter to flag situations where a local variable's name is one of
the argumentless constructors of its type. This can arise when a user either
doesn't open a namespace or doesn't add a dot or leading qualifier, as
in the following:
```lean
inductive Tree (α : Type) where
| leaf
| branch (left : Tree α) (val : α) (right : Tree α)
def depth : Tree α → Nat
| leaf => 0
```
With this linter, the `leaf` pattern is highlighted as a local
variable whose name overlaps with the constructor `Tree.leaf`.
The linter can be disabled with `set_option linter.constructorNameAsVariable false`.
Additionally, the error message that occurs when a name in a pattern that takes arguments isn't valid now suggests similar names that would be valid. This means that the following definition:
```lean
def length (list : List α) : Nat :=
match list with
| nil => 0
| cons x xs => length xs + 1
```
now results in the following warning:
```
warning: Local variable 'nil' resembles constructor 'List.nil' - write '.nil' (with a dot) or 'List.nil' to use the constructor.
note: this linter can be disabled with `set_option linter.constructorNameAsVariable false`
```
and error:
```
invalid pattern, constructor or constant marked with '[match_pattern]' expected
Suggestion: 'List.cons' is similar
```
* **Metaprogramming**
* [#4454](https://github.com/leanprover/lean4/pull/4454) adds public `Name.isInternalDetail` function for filtering declarations using naming conventions for internal names.
* **Other fixes or improvements**
* [#4416](https://github.com/leanprover/lean4/pull/4416) sorts the output of `#print axioms` for determinism.
* [#4528](https://github.com/leanprover/lean4/pull/4528) fixes error message range for the cdot focusing tactic.
### Language server, widgets, and IDE extensions
* [#4443](https://github.com/leanprover/lean4/pull/4443) makes the watchdog be more resilient against badly behaving clients.
### Pretty printing
* [#4433](https://github.com/leanprover/lean4/pull/4433) restores fallback pretty printers when context is not available, and documents `addMessageContext`.
* [#4556](https://github.com/leanprover/lean4/pull/4556) introduces `pp.maxSteps` option and sets the default value of `pp.deepTerms` to `false`. Together, these keep excessively large or deep terms from overwhelming the Infoview.
### Library
* [#4560](https://github.com/leanprover/lean4/pull/4560) splits `GetElem` class into `GetElem` and `GetElem?`.
This enables removing `Decidable` instance arguments from `GetElem.getElem?` and `GetElem.getElem!`, improving their rewritability.
See the docstrings for these classes for more information.
* `Array`
* [#4389](https://github.com/leanprover/lean4/pull/4389) makes `Array.toArrayAux_eq` be a `simp` lemma.
* [#4399](https://github.com/leanprover/lean4/pull/4399) improves robustness of the proof for `Array.reverse_data`.
* `List`
* [#4469](https://github.com/leanprover/lean4/pull/4469) and [#4475](https://github.com/leanprover/lean4/pull/4475) improve the organization of the `List` API.
* [#4470](https://github.com/leanprover/lean4/pull/4470) improves the `List.set` and `List.concat` API.
* [#4472](https://github.com/leanprover/lean4/pull/4472) upstreams lemmas about `List.filter` from Batteries.
* [#4473](https://github.com/leanprover/lean4/pull/4473) adjusts `@[simp]` attributes.
* [#4488](https://github.com/leanprover/lean4/pull/4488) makes `List.getElem?_eq_getElem` be a simp lemma.
* [#4487](https://github.com/leanprover/lean4/pull/4487) adds missing `List.replicate` API.
* [#4521](https://github.com/leanprover/lean4/pull/4521) adds lemmas about `List.map`.
* [#4500](https://github.com/leanprover/lean4/pull/4500) changes `List.length_cons` to use `as.length + 1` instead of `as.length.succ`.
* [#4524](https://github.com/leanprover/lean4/pull/4524) fixes the statement of `List.filter_congr`.
* [#4525](https://github.com/leanprover/lean4/pull/4525) changes binder explicitness in `List.bind_map`.
* [#4550](https://github.com/leanprover/lean4/pull/4550) adds `maximum?_eq_some_iff'` and `minimum?_eq_some_iff?`.
* [#4400](https://github.com/leanprover/lean4/pull/4400) switches the normal forms for indexing `List` and `Array` to `xs[n]` and `xs[n]?`.
* `HashMap`
* [#4372](https://github.com/leanprover/lean4/pull/4372) fixes linearity in `HashMap.insert` and `HashMap.erase`, leading to a 40% speedup in a replace-heavy workload.
* `Option`
* [#4403](https://github.com/leanprover/lean4/pull/4403) generalizes type of `Option.forM` from `Unit` to `PUnit`.
* [#4504](https://github.com/leanprover/lean4/pull/4504) remove simp attribute from `Option.elim` and instead adds it to individual reduction lemmas, making unfolding less aggressive.
* `Nat`
* [#4242](https://github.com/leanprover/lean4/pull/4242) adds missing theorems for `n + 1` and `n - 1` normal forms.
* [#4486](https://github.com/leanprover/lean4/pull/4486) makes `Nat.min_assoc` be a simp lemma.
* [#4522](https://github.com/leanprover/lean4/pull/4522) moves `@[simp]` from `Nat.pred_le` to `Nat.sub_one_le`.
* [#4532](https://github.com/leanprover/lean4/pull/4532) changes various `Nat.succ n` to `n + 1`.
* `Int`
* [#3850](https://github.com/leanprover/lean4/pull/3850) adds complete div/mod simprocs for `Int`.
* `String`/`Char`
* [#4357](https://github.com/leanprover/lean4/pull/4357) make the byte size interface be `Nat`-valued with functions `Char.utf8Size` and `String.utf8ByteSize`.
* [#4438](https://github.com/leanprover/lean4/pull/4438) upstreams `Char.ext` from Batteries and adds some `Char` documentation to the manual.
* `Fin`
* [#4421](https://github.com/leanprover/lean4/pull/4421) adjusts `Fin.sub` to be more performant in definitional equality checks.
* `Prod`
* [#4526](https://github.com/leanprover/lean4/pull/4526) adds missing `Prod.map` lemmas.
* [#4533](https://github.com/leanprover/lean4/pull/4533) fixes binder explicitness in lemmas.
* `BitVec`
* [#4428](https://github.com/leanprover/lean4/pull/4428) adds missing `simproc` for `BitVec` equality.
* [#4417](https://github.com/leanprover/lean4/pull/4417) adds `BitVec.twoPow` and lemmas, toward bitblasting multiplication for LeanSAT.
* `Std` library
* [#4499](https://github.com/leanprover/lean4/pull/4499) introduces `Std`, a library situated between `Init` and `Lean`, providing functionality not in the prelude both to Lean's implementation and to external users.
* **Other fixes or improvements**
* [#3056](https://github.com/leanprover/lean4/pull/3056) standardizes on using `(· == a)` over `(a == ·)`.
* [#4502](https://github.com/leanprover/lean4/pull/4502) fixes errors reported by running the library through the Batteries linters.
### Lean internals
* [#4391](https://github.com/leanprover/lean4/pull/4391) makes `getBitVecValue?` recognize `BitVec.ofNatLt`.
* [#4410](https://github.com/leanprover/lean4/pull/4410) adjusts `instantiateMVars` algorithm to zeta reduce `let` expressions while beta reducing instantiated metavariables.
* [#4420](https://github.com/leanprover/lean4/pull/4420) fixes occurs check for metavariable assignments to also take metavariable types into account.
* [#4425](https://github.com/leanprover/lean4/pull/4425) fixes `forEachModuleInDir` to iterate over each Lean file exactly once.
* [#3886](https://github.com/leanprover/lean4/pull/3886) adds support to build Lean core oleans using Lake.
* **Defeq and WHNF algorithms**
* [#4387](https://github.com/leanprover/lean4/pull/4387) improves performance of `isDefEq` by eta reducing lambda-abstracted terms during metavariable assignments, since these are beta reduced during metavariable instantiation anyway.
* [#4388](https://github.com/leanprover/lean4/pull/4388) removes redundant code in `isDefEqQuickOther`.
* **Typeclass inference**
* [#4530](https://github.com/leanprover/lean4/pull/4530) fixes handling of metavariables when caching results at `synthInstance?`.
* **Elaboration**
* [#4426](https://github.com/leanprover/lean4/pull/4426) makes feature where the "don't know how to synthesize implicit argument" error reports the name of the argument more reliable.
* [#4497](https://github.com/leanprover/lean4/pull/4497) fixes a name resolution bug for generalized field notation (dot notation).
* [#4536](https://github.com/leanprover/lean4/pull/4536) blocks the implicit lambda feature for `(e :)` notation.
* [#4562](https://github.com/leanprover/lean4/pull/4562) makes it be an error for there to be two functions with the same name in a `where`/`let rec` block.
* Recursion principles
* [#4549](https://github.com/leanprover/lean4/pull/4549) refactors `findRecArg`, extracting `withRecArgInfo`.
Errors are now reported in parameter order rather than the order they are tried (non-indices are tried first).
For every argument, it will say why it wasn't tried, even if the reason is obvious (e.g. a fixed prefix or is `Prop`-typed, etc.).
* Porting core C++ to Lean
* [#4474](https://github.com/leanprover/lean4/pull/4474) takes a step to refactor `constructions` toward a future port to Lean.
* [#4498](https://github.com/leanprover/lean4/pull/4498) ports `mk_definition_inferring_unsafe` to Lean.
* [#4516](https://github.com/leanprover/lean4/pull/4516) ports `recOn` construction to Lean.
* [#4517](https://github.com/leanprover/lean4/pull/4517), [#4653](https://github.com/leanprover/lean4/pull/4653), and [#4651](https://github.com/leanprover/lean4/pull/4651) port `below` and `brecOn` construction to Lean.
* Documentation
* [#4501](https://github.com/leanprover/lean4/pull/4501) adds a more-detailed docstring for `PersistentEnvExtension`.
* **Other fixes or improvements**
* [#4382](https://github.com/leanprover/lean4/pull/4382) removes `@[inline]` attribute from `NameMap.find?`, which caused respecialization at each call site.
* [5f9ded](https://github.com/leanprover/lean4/commit/5f9dedfe5ee9972acdebd669f228f487844a6156) improves output of `trace.Elab.snapshotTree`.
* [#4424](https://github.com/leanprover/lean4/pull/4424) removes "you might need to open '{dir}' in your editor" message that is now handled by Lake and the VS Code extension.
* [#4451](https://github.com/leanprover/lean4/pull/4451) improves the performance of `CollectMVars` and `FindMVar`.
* [#4479](https://github.com/leanprover/lean4/pull/4479) adds missing `DecidableEq` and `Repr` instances for intermediate structures used by the `BitVec` and `Fin` simprocs.
* [#4492](https://github.com/leanprover/lean4/pull/4492) adds tests for a previous `isDefEq` issue.
* [9096d6](https://github.com/leanprover/lean4/commit/9096d6fc7180fe533c504f662bcb61550e4a2492) removes `PersistentHashMap.size`.
* [#4508](https://github.com/leanprover/lean4/pull/4508) fixes `@[implemented_by]` for functions defined by well-founded recursion.
* [#4509](https://github.com/leanprover/lean4/pull/4509) adds additional tests for `apply?` tactic.
* [d6eab3](https://github.com/leanprover/lean4/commit/d6eab393f4df9d473b5736d636b178eb26d197e6) fixes a benchmark.
* [#4563](https://github.com/leanprover/lean4/pull/4563) adds a workaround for a bug in `IndPredBelow.mkBelowMatcher`.
* **Cleanup:** [#4380](https://github.com/leanprover/lean4/pull/4380), [#4431](https://github.com/leanprover/lean4/pull/4431), [#4494](https://github.com/leanprover/lean4/pull/4494), [e8f768](https://github.com/leanprover/lean4/commit/e8f768f9fd8cefc758533bc76e3a12b398ed4a39), [de2690](https://github.com/leanprover/lean4/commit/de269060d17a581ed87f40378dbec74032633b27), [d3a756](https://github.com/leanprover/lean4/commit/d3a7569c97123d022828106468d54e9224ed8207), [#4404](https://github.com/leanprover/lean4/pull/4404), [#4537](https://github.com/leanprover/lean4/pull/4537).
### Compiler, runtime, and FFI
* [d85d3d](https://github.com/leanprover/lean4/commit/d85d3d5f3a09ff95b2ee47c6f89ef50b7e339126) fixes criterion for tail-calls in ownership calculation.
* [#3963](https://github.com/leanprover/lean4/pull/3963) adds validation of UTF-8 at the C++-to-Lean boundary in the runtime.
* [#4512](https://github.com/leanprover/lean4/pull/4512) fixes missing unboxing in interpreter when loading initialized value.
* [#4477](https://github.com/leanprover/lean4/pull/4477) exposes the compiler flags for the bundled C compiler (clang).
### Lake
* [#4384](https://github.com/leanprover/lean4/pull/4384) deprecates `inputFile` and replaces it with `inputBinFile` and `inputTextFile`. Unlike `inputBinFile` (and `inputFile`), `inputTextFile` normalizes line endings, which helps ensure text file traces are platform-independent.
* [#4371](https://github.com/leanprover/lean4/pull/4371) simplifies dependency resolution code.
* [#4439](https://github.com/leanprover/lean4/pull/4439) touches up the Lake configuration DSL and makes other improvements:
string literals can now be used instead of identifiers for names,
avoids using French quotes in `lake new` and `lake init` templates,
changes the `exe` template to use `Main` for the main module,
improves the `math` template error if `lean-toolchain` fails to download,
and downgrades unknown configuration fields from an error to a warning to improve cross-version compatibility.
* [#4496](https://github.com/leanprover/lean4/pull/4496) tweaks `require` syntax and updates docs. Now `require` in TOML for a package name such as `doc-gen4` does not need French quotes.
* [#4485](https://github.com/leanprover/lean4/pull/4485) fixes a bug where package versions in indirect dependencies would take precedence over direct dependencies.
* [#4478](https://github.com/leanprover/lean4/pull/4478) fixes a bug where Lake incorrectly included the module dynamic library in a platform-independent trace.
* [#4529](https://github.com/leanprover/lean4/pull/4529) fixes some issues with bad import errors.
A bad import in an executable no longer prevents the executable's root
module from being built. This also fixes a problem where the location
of a transitive bad import would not been shown.
The root module of the executable now respects `nativeFacets`.
* [#4564](https://github.com/leanprover/lean4/pull/4564) fixes a bug where non-identifier script names could not be entered on the CLI without French quotes.
* [#4566](https://github.com/leanprover/lean4/pull/4566) addresses a few issues with precompiled libraries.
* Fixes a bug where Lake would always precompile the package of a module.
* If a module is precompiled, it now precompiles its imports. Previously, it would only do this if imported.
* [#4495](https://github.com/leanprover/lean4/pull/4495), [#4692](https://github.com/leanprover/lean4/pull/4692), [#4849](https://github.com/leanprover/lean4/pull/4849)
add a new type of `require` that fetches package metadata from a
registry API endpoint (e.g. Reservoir) and then clones a Git package
using the information provided. To require such a dependency, the new
syntax is:
```lean
require <scope> / <pkg-name> [@ git <rev>]
-- Examples:
require "leanprover" / "doc-gen4"
require "leanprover-community" / "proofwidgets" @ git "v0.0.39"
```
Or in TOML:
```toml
[[require]]
name = "<pkg-name>"
scope = "<scope>"
rev = "<rev>"
```
Unlike with Git dependencies, Lake can make use of the richer
information provided by the registry to determine the default branch of
the package. This means for repositories of packages like `doc-gen4`
which have a default branch that is not `master`, Lake will now use said
default branch (e.g., in `doc-gen4`'s case, `main`).
Lake also supports configuring the registry endpoint via an environment
variable: `RESERVIOR_API_URL`. Thus, any server providing a similar
interface to Reservoir can be used as the registry. Further
configuration options paralleling those of Cargo's [Alternative Registries](https://doc.rust-lang.org/cargo/reference/registries.html)
and [Source Replacement](https://doc.rust-lang.org/cargo/reference/source-replacement.html)
will come in the future.
### DevOps/CI
* [#4427](https://github.com/leanprover/lean4/pull/4427) uses Namespace runners for CI for `leanprover/lean4`.
* [#4440](https://github.com/leanprover/lean4/pull/4440) fixes speedcenter tests in CI.
* [#4441](https://github.com/leanprover/lean4/pull/4441) fixes that workflow change would break CI for unrebased PRs.
* [#4442](https://github.com/leanprover/lean4/pull/4442) fixes Wasm release-ci.
* [6d265b](https://github.com/leanprover/lean4/commit/6d265b42b117eef78089f479790587a399da7690) fixes for `github.event.pull_request.merge_commit_sha` sometimes not being available.
* [16cad2](https://github.com/leanprover/lean4/commit/16cad2b45c6a77efe4dce850dcdbaafaa7c91fc3) adds optimization for CI to not fetch complete history.
* [#4544](https://github.com/leanprover/lean4/pull/4544) causes releases to be marked as prerelease on GitHub.
* [#4446](https://github.com/leanprover/lean4/pull/4446) switches Lake to using `src/lake/lakefile.toml` to avoid needing to load a version of Lake to build Lake.
* Nix
* [5eb5fa](https://github.com/leanprover/lean4/commit/5eb5fa49cf9862e99a5bccff8d4ca1a062f81900) fixes `update-stage0-commit` for Nix.
* [#4476](https://github.com/leanprover/lean4/pull/4476) adds gdb to Nix shell.
* [e665a0](https://github.com/leanprover/lean4/commit/e665a0d716dc42ba79b339b95e01eb99fe932cb3) fixes `update-stage0` for Nix.
* [4808eb](https://github.com/leanprover/lean4/commit/4808eb7c4bfb98f212b865f06a97d46c44978a61) fixes `cacheRoots` for Nix.
* [#3811](https://github.com/leanprover/lean4/pull/3811) adds platform-dependent flag to lib target.
* [#4587](https://github.com/leanprover/lean4/pull/4587) adds linking of `-lStd` back into nix build flags on darwin.
### Breaking changes
* `Char.csize` is replaced by `Char.utf8Size` ([#4357](https://github.com/leanprover/lean4/pull/4357)).
* Library lemmas now are in terms of `(· == a)` over `(a == ·)` ([#3056](https://github.com/leanprover/lean4/pull/3056)).
* Now the normal forms for indexing into `List` and `Array` is `xs[n]` and `xs[n]?` rather than using functions like `List.get` ([#4400](https://github.com/leanprover/lean4/pull/4400)).
* Sometimes terms created via a sequence of unifications will be more eta reduced than before and proofs will require adaptation ([#4387](https://github.com/leanprover/lean4/pull/4387)).
* The `GetElem` class has been split into two; see the docstrings for `GetElem` and `GetElem?` for more information ([#4560](https://github.com/leanprover/lean4/pull/4560)).
```` |
reference-manual/Manual/Releases/v4_26_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.26.0 (2025-12-13)" =>
%%%
tag := "release-v4.26.0"
file := "v4.26.0"
%%%
````markdown
For this release, 264 changes landed. In addition to the 84 feature additions and 73 fixes listed below there were 10 refactoring changes, 7 documentation improvements, 13 performance improvements, 8 improvements to the test suite and 69 other changes.
## Highlights
### Dependencies by Semantic Version
[#10959](https://github.com/leanprover/lean4/pull/10959) enables Lake users to require Reservoir dependencies by a
semantic version range. On a `lake update`, Lake will fetch the
package's version information from Reservoir and select the newest
version of the package that satisfies the range.
### Grind
#### Grind Pattern
[#11189](https://github.com/leanprover/lean4/pull/11189) implements `grind_pattern` constraints. They are useful for
controlling theorem instantiation in `grind`. As an example, consider
the following two theorems:
```lean
theorem extract_empty {start stop : Nat} :
(#[] : Array α).extract start stop = #[] := …
theorem extract_extract {as : Array α} {i j k l : Nat} :
(as.extract i j).extract k l = as.extract (i + k) (min (i + l) j) := …
```
If both are used for theorem instantiation, an unbounded number of instances
is generated as soon as we add the term `#[].extract i j` to the `grind` context.
We can now prevent this by adding a `grind_pattern` constraint to `extract_extract`:
```lean
grind_pattern extract_extract => (as.extract i j).extract k l where
as =/= #[]
```
With this constraint, only one instance is generated, as expected:
```lean
/-- trace: [grind.ematch.instance] extract_empty: #[].extract i j = #[] -/
#guard_msgs (drop error, trace) in
set_option trace.grind.ematch.instance true in
example (as : Array Nat) (h : #[].extract i j = as) : False := by
grind only [= extract_empty, usr extract_extract]
```
#### Grind Lint
[#11157](https://github.com/leanprover/lean4/pull/11157) implements the `#grind_lint` command, a diagnostic tool for
analyzing the behavior of theorems annotated for theorem instantiation.
The command helps identify problematic theorems that produce excessive
or unbounded instance generation during E-matching, which can lead to
performance issues.
The main entry point is:
```
#grind_lint check
```
which analyzes all theorems marked with the `@[grind]` attribute.
For each theorem, it creates an artificial goal and runs `grind`,
collecting statistics about the number of instances produced.
Results are summarized using info messages, and detailed breakdowns are
shown for lemmas exceeding a configurable threshold.
Additional subcommands are provided for targeted inspection and control:
- `#grind_lint inspect thm`: analyzes one or more specific theorems in
detail
- `#grind_lint mute thm`: excludes a theorem from instantiation during
analysis
- `#grind_lint skip thm`: omits a theorem from being analyzed by
`#grind_lint check`
[#11167](https://github.com/leanprover/lean4/pull/11167) implements support for `#grind_lint check in module <module>`.
#### Grind Interactive Mode
Interactive mode gained several new features:
- ` · t_1 ... t_n` tactic combinator, which allows for more concise scripts generated by `finish?`
([#10975](https://github.com/leanprover/lean4/pull/10975)),
- configurability within the grind interactive mode with `set_config` tactic ([#10990](https://github.com/leanprover/lean4/pull/10990)),
- controlling `finish` and `finish?` with configuration options ([#10997](https://github.com/leanprover/lean4/pull/10997))
and parameters ([#11012](https://github.com/leanprover/lean4/pull/11012)),
- anchor support for restricting search space in `grind only` ([#11003](https://github.com/leanprover/lean4/pull/11003)),
- `cases_next`, a tactic to perform the next case-split ([#11148](https://github.com/leanprover/lean4/pull/11148)),
- `have <ident>? : <prop>` tactic, where the proposition is proved using the default `grind` search strategy;
useful for inspecting or querying the
current `grind` state ([#10919](https://github.com/leanprover/lean4/pull/10919)).
### User Extensions in `try?`
[#11149](https://github.com/leanprover/lean4/pull/11149) adds a user-extension mechanism for the `try?` tactic. You can
either use the `@[try_suggestion]` attribute on a declaration with
signature `` MVarId -> Try.Info -> MetaM (Array (TSyntax `tactic)) `` to
produce suggestions, or the `register_try?_tactic <stx>` command with a
fixed piece of syntax. User-extensions are only tried _after_ the
built-in try strategies have been tried and failed.
### Match Compilation
This release includes several performance optimizations in match compilation of large match statements (PRs [#10763](https://github.com/leanprover/lean4/pull/10763), [#11072](https://github.com/leanprover/lean4/pull/11072) and [#10823](https://github.com/leanprover/lean4/pull/10823)).
### Library Suggestions
- [#10920](https://github.com/leanprover/lean4/pull/10920)/[#11029](https://github.com/leanprover/lean4/pull/11029)
adds support for `grind +suggestions`, calling the currently
configured premise selection algorithm and including the results as
parameters to `grind`.
- [#11032](https://github.com/leanprover/lean4/pull/11032) implements `simp? +suggestions`, which uses the configured
library suggestion engine to add relevant theorems to the `simp` call.
- [#11030](https://github.com/leanprover/lean4/pull/11030) adds a library suggestion engine for local theorems.
### Library Highlights
- [#11019](https://github.com/leanprover/lean4/pull/11019) introduces slices of lists that are available via slice notation
(e.g., `xs[1...5]`).
- [#10933](https://github.com/leanprover/lean4/pull/10933) adds the basic infrastructure to perform termination proofs
about `String.ValidPos` and `String.Slice.Pos`.
### Breaking Changes
- [#10625](https://github.com/leanprover/lean4/pull/10625) implements zero cost `BaseIO` by erasing the `IO.RealWorld`
parameter from argument lists and structures. This is a **major breaking
change for FFI**.
## Language
* [#10763](https://github.com/leanprover/lean4/pull/10763) improves match compilation: Branch on variables in the order
suggested by the first remaining alternative, and do not branch when the
first remaining alternative does not require it. This fixes
https://github.com/leanprover/lean4/issues/10749. With `set_option
backwards.match.rowMajor false` the old behavior can be turned on.
* [#10823](https://github.com/leanprover/lean4/pull/10823) lets the match compilation procedure use sparse case analysis
when the patterns only match on some but not all constructors of an
inductive type. This way, less code is produce. Before, code handling
each of the other cases was then optimized and commoned-up by later
compilation pipeline, but that is wasteful to do.
* [#10826](https://github.com/leanprover/lean4/pull/10826) fixes the location of the “deprecated constant” and similar
error messages on field notation (`e.f`, `(e).f`, `e |>. f`). Fixes
#10821.
* [#10851](https://github.com/leanprover/lean4/pull/10851) lets match compilation use exfalso as soon as no alternatives
are left. This way, the compiler does not have to look at subsequent
case splits.
* [#10865](https://github.com/leanprover/lean4/pull/10865) makes the spec `Std.Do.Spec.forIn'_list` and friends more
universe polymorphic.
* [#10872](https://github.com/leanprover/lean4/pull/10872) improves the performance of `mvcgen` by an optimized
implementation for `try (mpure_intro; trivial)`. This tactic sequence is
used to eagerly discharge VCs and in the process instantiates schematic
variables.
* [#10926](https://github.com/leanprover/lean4/pull/10926) topologically sorts abstracted vars in
`Meta.Closure.mkValueTypeClosure` if MVars are being abstracted.
Fixes #10705
* [#10931](https://github.com/leanprover/lean4/pull/10931) strips the `Expr.mdata` that `WF.Fix` uses to associate goal
with recursive calls from the goal presented to the tactics.
Fixes #10895.
* [#10944](https://github.com/leanprover/lean4/pull/10944) runs enableRealizationsForConst on sizeOf declarations. Fixes
#10573.
* [#10980](https://github.com/leanprover/lean4/pull/10980) tries to preserve names of pattern variables in match
alternatives in `decreasing_by`, by telescoping into the concrete
alternative rather than the type of the matcher's alt. Fixes #10976.
* [#11011](https://github.com/leanprover/lean4/pull/11011) extracts some refactorings from #10763, including dropping dead
code and not failing in `inaccessibleAsCtor`, which leadas to (slightly)
better error messages, and also on the grounds that the failing
alternative may actually be unreachable.
* [#11024](https://github.com/leanprover/lean4/pull/11024) lets `Bool` have `.ctorIdx` like any other inductive.
* [#11068](https://github.com/leanprover/lean4/pull/11068) removes the `verifyEnum` functions from the bv_decide frontend.
These functions looked at the implementation of matchers to see if they
really do the matching that they claim to do. This breaks that
abstraction barrier, and should not be necessary, as only functions with
a `MatcherInfo` env entry are considered here, which should all play
nicely.
* [#11072](https://github.com/leanprover/lean4/pull/11072) adds “sparse casesOn” constructions. They are similar to
`.casesOn`, but have arms only for some constructors and a catch-all
(providing `t.ctorIdx ≠ 42` assumptions). The compiler has native
support for these constructors and now (because of the similarity) also
the per-constructor elimination principles.
* [#11094](https://github.com/leanprover/lean4/pull/11094) makes workspaceSymbol benchmarks `module`s, so that they are
less sensitive to additions of private symbols in the standard library.
* [#11095](https://github.com/leanprover/lean4/pull/11095) makes use of `hasIndepIndices`. That function was unused since
commit 54f6517ca36b237b40e02aac62ea36dbd4179758, but it seems it should
be used.
* [#11107](https://github.com/leanprover/lean4/pull/11107) tests the missing cases error.
* [#11122](https://github.com/leanprover/lean4/pull/11122) fixes a problem for structures with diamond inheritance: rather
than copying docstrings (which are not available unless `.server.olean`
is loaded), we link to them. Adds tests.
* [#11125](https://github.com/leanprover/lean4/pull/11125) adds a filter for premise selectors to ensure deprecated
theorems are not returned.
* [#11132](https://github.com/leanprover/lean4/pull/11132) adds support for `grind +suggestions` and `simp_all?
+suggestions` in `try?`. It outputs `grind only [X, Y, Z]` or `simp_all
only [X, Y, Z]` suggestions (rather than just `+suggestions`).
* [#11146](https://github.com/leanprover/lean4/pull/11146) fixes a bug in #11125. Added a test this time ...
* [#11150](https://github.com/leanprover/lean4/pull/11150) adds a new, inactive and unused `doElem_elab` attribute that
will allow users to register custom elaborators for `doElem`s in the
form of the new type `DoElab`. The old `do` elaborator is active by
default but can be switched off by disabling the new option
`backward.do.legacy`.
* [#11161](https://github.com/leanprover/lean4/pull/11161) adds getEntry/getEntry?/getEntry!/getEntryD operation on
DTreeMap.
* [#11184](https://github.com/leanprover/lean4/pull/11184) modifies the error message that is returned when more than one
synthetic metavariable can't be resolved.
* [#11190](https://github.com/leanprover/lean4/pull/11190) avoids running into an “unknown free variable” when printing the
“Failed to compile pattern matching” error. Fixes #11186.
* [#11191](https://github.com/leanprover/lean4/pull/11191) makes sure that inside a `realizeConst` the `maxHeartbeat`
option is effective.
## Library
* [#9515](https://github.com/leanprover/lean4/pull/9515) adds a missing lemma for the `List` API.
* [#10739](https://github.com/leanprover/lean4/pull/10739) adds two missing `NeZero` instances for `n^0` where `n : Nat`
and `n : Int`.
* [#10743](https://github.com/leanprover/lean4/pull/10743) renames theorems that use `sorted` in their name to instead use
`pairwise`.
* [#10765](https://github.com/leanprover/lean4/pull/10765) extends the `all`/`any` functions from hash sets to hash maps
and dependent hash maps and verifies them.
* [#10769](https://github.com/leanprover/lean4/pull/10769) adds a `find?` consumer in analogy to `List.find?` and variants
thereof.
* [#10776](https://github.com/leanprover/lean4/pull/10776) adds iterators and slices for `DTreeMap`/`TreeMap`/`TreeSet`
based on zippers and provides basic lemmas about them.
* [#10820](https://github.com/leanprover/lean4/pull/10820) shows that the iterators returned by `String.Slice.split` and
`String.Slice.splitInclusive` are finite as long as the forward matcher
iterator for the pattern is finite (which we already know for all of our
patterns).
* [#10852](https://github.com/leanprover/lean4/pull/10852) renames `String.Range` to `Lean.Syntax.Range`, to reflect that
it is not part of the standard library.
* [#10853](https://github.com/leanprover/lean4/pull/10853) renames `String.endPos` to `String.rawEndPos`, as in a future
release the name `String.endPos` will be taken by the function that is
currently called `String.endValidPos`.
* [#10854](https://github.com/leanprover/lean4/pull/10854) fixes the IPv4 address encoding from libuv to lean
* [#10865](https://github.com/leanprover/lean4/pull/10865) makes the spec `Std.Do.Spec.forIn'_list` and friends more
universe polymorphic.
* [#10896](https://github.com/leanprover/lean4/pull/10896) adds union operations on DTreeMap/TreeMap/TreeSet and their raw
variants and provides lemmas about union operations.
* [#10933](https://github.com/leanprover/lean4/pull/10933) adds the basic infrastructure to perform termination proofs
about `String.ValidPos` and `String.Slice.Pos`.
* [#10941](https://github.com/leanprover/lean4/pull/10941) removes a redundant instance requirement from
`Std.instIrreflLtOfIsPreorderOfLawfulOrderLT`.
* [#10946](https://github.com/leanprover/lean4/pull/10946) adds union operation on ExtDHashMap/ExtHashMap/ExtHashSet and
provides lemmas about union operations.
* [#10952](https://github.com/leanprover/lean4/pull/10952) replaces `Iter(M).size` with the `Iter(M).count`. While the
former used a special `IteratorSize` type class, the latter relies on
`IteratorLoop`. The `IteratorSize` class is deprecated. The PR also
renames lemmas about ranges by replacing `_Rcc` with `_rcc`, `_Rco` with
`_roo` (and so on) in names, in order to be more consistent with the
naming convention.
* [#10966](https://github.com/leanprover/lean4/pull/10966) fixes some mis-stated lemmas which should have been about the
`.Raw` variants of maps.
* [#10986](https://github.com/leanprover/lean4/pull/10986) defines `String.Slice.replace` and redefines `String.replace` to
use the `Slice` version.
* [#10993](https://github.com/leanprover/lean4/pull/10993) allows `grind` to work extensionally on extensional maps/sets.
* [#11006](https://github.com/leanprover/lean4/pull/11006) removes the duplicate lemmas
`Std.Do.SPred.{and_pure,or_pure,imp_pure,entails_pure_intro}`.
* [#11008](https://github.com/leanprover/lean4/pull/11008) inlines several Decidable instances for performance reasons.
* [#11017](https://github.com/leanprover/lean4/pull/11017) establishes `String.ofList` and `String.toList` as the preferred
method for converting between strings and lists of characters and
deprecates the alternatives `String.mk`, `List.asString` and
`String.data`.
* [#11019](https://github.com/leanprover/lean4/pull/11019) introduces slices of lists that are available via slice notation
(e.g., `xs[1...5]`).
* [#11021](https://github.com/leanprover/lean4/pull/11021) adds more theory about `Splits` for strings and deduces the
first user-facing `String` lemma, `String.toList_map`.
* [#11058](https://github.com/leanprover/lean4/pull/11058) changes `Nat.ble` by joining the two `Nat.ble Nat.zero _` cases
into one, allowing `decide (0 <= x) = true` and `decide (0 < succ x) =
true` to be solvable by `rfl`.
* [#11060](https://github.com/leanprover/lean4/pull/11060) adds list `min` and `max` operations to complement `min?` and
`max?` ones in the same vein as `head?` and `head`.
* [#11070](https://github.com/leanprover/lean4/pull/11070) adds union operation on ExtDHashMap/ExtHashMap/ExtHashSet and
provides lemmas about union operations.
* [#11076](https://github.com/leanprover/lean4/pull/11076) adds `getEntry`/`getEntry?`/`getEntry!`/`getEntryD` operation on
DHashMap.
* [#11100](https://github.com/leanprover/lean4/pull/11100) adds `theorem Int.ediv_pow {a b : Int} {n : Nat} (hab : b ∣ a) :
(a / b) ^ n = a ^ n / b ^ n` and related lemmas.
* [#11102](https://github.com/leanprover/lean4/pull/11102) adds some annotations missing in the Array bootstrapping files.
* [#11113](https://github.com/leanprover/lean4/pull/11113) adds some small missing lemmas.
* [#11123](https://github.com/leanprover/lean4/pull/11123) adds theorems about folds over flatMaps, for
`List`/`Array`/`Vector`.
* [#11127](https://github.com/leanprover/lean4/pull/11127) removes all uses of `String.Iterator` from core, preferring
`String.ValidPos` instead.
* [#11138](https://github.com/leanprover/lean4/pull/11138) adds a `csimp` lemma for faster runtime evaluation of `Int.pow`
in terms of `Nat.pow`.
* [#11139](https://github.com/leanprover/lean4/pull/11139) replaces #11138, which just added a `@[csimp]` lemma for
`Int.pow`, this time actually replacing the definition. This means we
not only get fast runtime behaviour, but take advantage of the special
kernel support for `Nat.pow`.
* [#11150](https://github.com/leanprover/lean4/pull/11150) adds a new, inactive and unused `doElem_elab` attribute that
will allow users to register custom elaborators for `doElem`s in the
form of the new type `DoElab`. The old `do` elaborator is active by
default but can be switched off by disabling the new option
`backward.do.legacy`.
* [#11152](https://github.com/leanprover/lean4/pull/11152) renames `String.Iterator` to `String.Legacy.Iterator`.
* [#11154](https://github.com/leanprover/lean4/pull/11154) renames `Substring` to `Substring.Raw`.
* [#11159](https://github.com/leanprover/lean4/pull/11159) adds lemmas about the sizes of ranges of Ints, analogous to the
Nat lemmas in `Init.Data.Range.Polymorphic.NatLemmas`. See also
https://leanprover.zulipchat.com/#narrow/channel/270676-lean4/topic/Reasonning.20about.20PRange.20sizes.20.28with.20.60Int.60.29/with/546466339.
## Tactics
* [#10848](https://github.com/leanprover/lean4/pull/10848) fixes an issue where adding a missing case name after the pipe
in `induction` would not remove the now-obsolete error message.
* [#10858](https://github.com/leanprover/lean4/pull/10858) improves the `done` tactic in `grind` interactive mode. It now
displays the `grind` state diagnostics for all unsolved subgoals.
* [#10859](https://github.com/leanprover/lean4/pull/10859) fixes auto-completion for `set_option` in `grind` interactive
mode.
* [#10862](https://github.com/leanprover/lean4/pull/10862) implements the `show_term` combinator in `grind` interactive
mode.
* [#10874](https://github.com/leanprover/lean4/pull/10874) uses the correct context for elaborating the `grind` state
filter.
* [#10877](https://github.com/leanprover/lean4/pull/10877) fixes theory propagation issue in `grind order`.
* [#10881](https://github.com/leanprover/lean4/pull/10881) fixes a proof instability source in `grind`.
* [#10887](https://github.com/leanprover/lean4/pull/10887) uses the new `TermInfo.isDisplayableTerm` when hovering over
`cases` tactic anchors in the `grind` interactive mode.
* [#10890](https://github.com/leanprover/lean4/pull/10890) adds a `+lax` configuration option for `grind`, causing it to
ignore parameters referring to non-existent theorems, or to theorems for
which we can't generate a pattern. This allows throwing large sets of
theorems (e.g. from a premise selection enginre) into `grind` to see
what happens.
* [#10899](https://github.com/leanprover/lean4/pull/10899) ensures the generated `instantiate` tactic instantiates the
theorems using the same order used by `finish?`
* [#10916](https://github.com/leanprover/lean4/pull/10916) implements parameter optimization for the generated
`instantiate` tactics produced by `finish?`.
We use a simple parameter optimizer that takes two sets as input: the
lower and upper bounds.
The lower bound consists of the theorems actually used in the proof
term, while the upper bound includes all the theorems instantiated in a
particular theorem instantiation step.
The lower bound is often sufficient to replay the proof, but in some
cases, additional theorems must be included because a theorem
instantiation may contribute to the proof by providing terms and many
not be present in the final proof term.
* [#10919](https://github.com/leanprover/lean4/pull/10919) implements the `have <ident>? : <prop>` tactic for the `grind`
interactive mode. The proposition is proved using the default `grind`
search strategy. This tactic is also useful for inspecting or querying
the current `grind` state.
* [#10920](https://github.com/leanprover/lean4/pull/10920) adds support for `grind +premises`, calling the currently
configured premise selection algorithm and including the results as
parameters to `grind`. (Recall that there is not currently a default
premise selector provided by Lean4: you need a downstream premise
selector to make use of this.)
* [#10936](https://github.com/leanprover/lean4/pull/10936) fixes issues in `grind => finish?` that were preventing
generated `grind` tactic scripts from being successfully replayed.
* [#10937](https://github.com/leanprover/lean4/pull/10937) fixes a missing counter reset at the `cases` tactic in `grind`
interactive mode.
* [#10938](https://github.com/leanprover/lean4/pull/10938) ensures solver `grind` tactics (e.g., `ac`, `ring`, `lia`, etc)
process pending facts after making progress.
* [#10939](https://github.com/leanprover/lean4/pull/10939) fixes another instance of the “default parameter value in
constructor” footgun, which was affecting the `cases` tactic in the
`grind` interactive mode.
* [#10948](https://github.com/leanprover/lean4/pull/10948) ensures that `finish?` produces partial tactic scripts
containing `sorry`s.
We may add an option to disable this feature in the future.
It is enabled by default because it provides a useful way to debug
`grind` failures.
* [#10949](https://github.com/leanprover/lean4/pull/10949) ensures that solver propagation steps are necessary in the
generated tactic script to close the goal.
* [#10950](https://github.com/leanprover/lean4/pull/10950) adds the `mbtc` tactic to the `grind` interactive mode. It
implements model-based theory combination. It also ensures `finish?` is
capable of generating it.
* [#10951](https://github.com/leanprover/lean4/pull/10951) fixes a bug in the `cutsat` incremental model construction. The
model was not being reset when new (unsatisfied) equalities were
asserted.
* [#10955](https://github.com/leanprover/lean4/pull/10955) fixes a regression in the `grind order` module introduced by
* [#10956](https://github.com/leanprover/lean4/pull/10956) fixes a bug in the equality propagation procedure in
`grind.order`. Specifically, it affects the procedure that asserts
equalities in the `grind` core state that are implied by (ring)
inequalities in the `grind.order` module.
* [#10960](https://github.com/leanprover/lean4/pull/10960) fixes a bug in the `grind linarith` model/counterexample
construction.
* [#10961](https://github.com/leanprover/lean4/pull/10961) adds support for scientific literals for `Rat` in `grind`.
`grind` does not yet add support for this kind of literal in arbitrary
fields.
* [#10962](https://github.com/leanprover/lean4/pull/10962) fixes a spurious warning message in `grind`.
* [#10964](https://github.com/leanprover/lean4/pull/10964) adds a propagator for `a^(n+m)` and removes its normalizer. This
change was motivated by issue #10661
* [#10965](https://github.com/leanprover/lean4/pull/10965) ensures that model-based theory combination in `grind cutsat`
considers nonlinear terms. Nonlinear multiplications such as `x * y` are
treated as uninterpreted symbols in `cutsat`.
* [#10971](https://github.com/leanprover/lean4/pull/10971) adds a `LawfulOfScientific` class, providing compatibility with
a `Lean.Grind.Field` structure.
* [#10975](https://github.com/leanprover/lean4/pull/10975) adds the combinator ` · t_1 ... t_n` to the `grind` interactive
mode. The `finish?` tactic now generates scripts using this combinator
to conform to Mathlib coding standards. The new format is also more
compact. Example:
```lean
/--
info: Try this:
[apply] ⏎
instantiate only [= mem_indices_of_mem, insert, = getElem_def]
instantiate only [= getElem?_neg, = getElem?_pos]
cases #f590
· cases #ffdf
· instantiate only
instantiate only [= Array.getElem_set]
· instantiate only
instantiate only [size, = HashMap.mem_insert, = HashMap.getElem_insert, = Array.getElem_push]
· instantiate only [= mem_indices_of_mem, = getElem_def]
instantiate only [usr getElem_indices_lt]
instantiate only [size]
cases #ffdf
· instantiate only [=_ WF]
instantiate only [= getElem?_neg, = getElem?_pos, = Array.getElem_set]
instantiate only [WF']
· instantiate only
instantiate only [= HashMap.mem_insert, = HashMap.getElem_insert, = Array.getElem_push]
-/
#guard_msgs in
example (m : IndexMap α β) (a a' : α) (b : β) (h : a' ∈ m.insert a b) :
(m.insert a b)[a'] = if h' : a' == a then b else m[a'] := by
grind => finish?
```
* [#10978](https://github.com/leanprover/lean4/pull/10978) implements the following `grind` improvements:
1. `set_option` can now be used to set `grind` configuration options in
the interactive mode.
2. Fixes a bug in the repeated theorem instantiation detection.
3. Adds the macro `use [...]` as a shorthand for `instantiate only
[...]`.
* [#10990](https://github.com/leanprover/lean4/pull/10990) adds the `set_config` tactic for setting `grind` configuration
options. It uses the same syntax used for setting configuration options
in the `grind` main tactic.
* [#10991](https://github.com/leanprover/lean4/pull/10991) renames `cutsat` in configuration options and trace messages to
`lia`.
* [#10992](https://github.com/leanprover/lean4/pull/10992) ensures that `grind +premises` silently drops warnings and
errors about bad suggestions.
* [#10997](https://github.com/leanprover/lean4/pull/10997) adds support for configuration options at `finish` and
`finish?`.
* [#11003](https://github.com/leanprover/lean4/pull/11003) adds support for specifying anchors to restrict the search space
in `grind` when using `grind only`. Anchors can limit which case splits
are performed and which local lemmas are instantiated.
* [#11012](https://github.com/leanprover/lean4/pull/11012) ensures the `grind` tactics `finish` and `finish?` can take
parameters.
* [#11026](https://github.com/leanprover/lean4/pull/11026) fixes a non-termination and missing propagation bug in `grind
order`. It also registers relevant case-splits for arithmetic.
* [#11028](https://github.com/leanprover/lean4/pull/11028) ensures that `grind? +premises` removes `+premises` from the
"Try this" suggestion.
* [#11029](https://github.com/leanprover/lean4/pull/11029) changes the terminology used from "premise selection" to
"library suggestions". This will be more understandable to users (we
don't assume anyone is familiar with the premise selection literature),
and avoids a conflict with the existing use of "premise" in Lean
terminology (e.g. "major premise" in induction, as well as generally the
synonym for "hypothesis"/"argument").
* [#11030](https://github.com/leanprover/lean4/pull/11030) adds a library suggestion engine for local theorems. To be
useful, I still need to write more combinators to re-rank and combine
suggestions from multiple engines.
* [#11032](https://github.com/leanprover/lean4/pull/11032) implements `simp? +suggestions`, which uses the configured
library suggestion engine to add relevant theorems to the `simp` call.
`simp +suggestions` without the `?` prints a message requiring adding
the `?`.
* [#11034](https://github.com/leanprover/lean4/pull/11034) adds a new suggestion to `finish?`. It now generates the `grind`
tactic script as before, and a `finish only` tactic. Example:
```lean
/--
info: Try these:
[apply] ⏎
instantiate only [findIdx, insert, = mem_indices_of_mem]
instantiate only [= getElem?_neg, = getElem?_pos]
cases #1bba
· instantiate only [findIdx]
· instantiate only
instantiate only [= HashMap.mem_insert, = HashMap.getElem_insert]
[apply] finish only [findIdx, insert, = mem_indices_of_mem, = getElem?_neg, = getElem?_pos, = HashMap.mem_insert,
= HashMap.getElem_insert, #1bba]
-/
example (m : IndexMap α β) (a : α) (b : β) :
(m.insert a b).findIdx a = if h : a ∈ m then m.findIdx a else m.size := by
grind => finish?
```
* [#11039](https://github.com/leanprover/lean4/pull/11039) fixes the `grind` invalid universe level regression reported in
#11036
* [#11040](https://github.com/leanprover/lean4/pull/11040) fixes a panic that occurred during the processing of generalized
E-matching patterns in `grind`.
* [#11047](https://github.com/leanprover/lean4/pull/11047) implements (nested term) equality propagation in `grind order`.
That is, it propagates implied equalities from `grind order` back to the
`grind` core. Examples:
```lean
open Lean Grind Std
* [#11049](https://github.com/leanprover/lean4/pull/11049) implements equality propagation for `Nat` in `grind order`.
`grind order` supports offset equalities for rings, but it has an
adapter for `Nat`. Example:
```lean
example (a b : Nat) (f : Nat → Int) : a ≤ b + 1 → b + 1 ≤ a → f (1 + a) = f (1 + b + 1) := by
grind -offset -mbtc -lia -linarith (splits := 0)
```
* [#11050](https://github.com/leanprover/lean4/pull/11050) fixes equality propagation for `Nat` in `grind order`.
* [#11051](https://github.com/leanprover/lean4/pull/11051) removes the `grind offset` module because it is (now) subsumed
by `grind order`.
* [#11057](https://github.com/leanprover/lean4/pull/11057) implements `grind?` using the new `grind => finish?`
infrastructure.
* [#11061](https://github.com/leanprover/lean4/pull/11061) fixes a deep recursion issue in the kernel when type-checking a
proof term produced by `grind`.
* [#11071](https://github.com/leanprover/lean4/pull/11071) ensures that the `denote` functions used to implement
proof-by-reflection terms in `grind` are abbreviations. This change
eliminates the need for the `withAbstractAtoms` gadget.
* [#11075](https://github.com/leanprover/lean4/pull/11075) updates `simp? +suggestions` so that if a name is ambiguous
(because of namespaces) all alternatives are used, rather than erroring.
* [#11077](https://github.com/leanprover/lean4/pull/11077) fixes the anchor values produced by `grind?`
* [#11080](https://github.com/leanprover/lean4/pull/11080) fixes a panic during equality propagation in the `grind ring`
module. If the maximum number of steps has been reached, the polynomials
may not be fully simplified.
* [#11084](https://github.com/leanprover/lean4/pull/11084) fixes a stack overflow that occurs when constructing a proof
term in `grind`.
* [#11087](https://github.com/leanprover/lean4/pull/11087) enables `grind` to case bash on `Sum` and `PSum`.
* [#11092](https://github.com/leanprover/lean4/pull/11092) ensures that `grind ac` denotation functions used in proof by
reflection are marked as `abbrev`.
* [#11098](https://github.com/leanprover/lean4/pull/11098) updates the `suggestions` tactic so the printed message includes
hoverable type information (and displays scores and flags when
relevant).
* [#11099](https://github.com/leanprover/lean4/pull/11099) improves the support for universe-metavariables in `grind`.
* [#11101](https://github.com/leanprover/lean4/pull/11101) fixes an initialization issue for local `Function.Injective f`
hypotheses.
* [#11126](https://github.com/leanprover/lean4/pull/11126) ensures `grind` does not fail when applying `injection` to a
hypothesis that cannot be cleared because of forward dependencies.
* [#11133](https://github.com/leanprover/lean4/pull/11133) fixes disequality propagation for constructor applications in
`grind`. The equivalence class representatives may be distinct
constructor applications, but we must ensure they have the same type.
Examples that were panic'ing before this PR:
```lean
example (a b : List Nat)
: a ≍ ([] : List Int) → b ≍ ([1] : List Int) → a = b ∨ p → p := by
grind
* [#11135](https://github.com/leanprover/lean4/pull/11135) ensures that `checkExp` is used in `grind lia` (formerly known
as `grind cutsat`) and `grind ring` to prevent stack overflows.
* [#11136](https://github.com/leanprover/lean4/pull/11136) adds support for `try?` to use induction; it will only perform
induction on inductive types defined in the current namespace and/or
module; so in particular for now it will not induct on built-in
inductives such as `Nat` or `List`.
* [#11137](https://github.com/leanprover/lean4/pull/11137) fixes a stackoverflow during proof construction in `grind`.
* [#11145](https://github.com/leanprover/lean4/pull/11145) fixes a bug in `isMatchCondCandidate` used in `grind`. The
missing condition was causing a "not internalized term" `grind` internal
error.
* [#11147](https://github.com/leanprover/lean4/pull/11147) refactors the implementation of the symmetric equality
congruence rule used in `grind`.
* [#11148](https://github.com/leanprover/lean4/pull/11148) addst the `cases_next` tactic to the `grind` interactive mode.
* [#11149](https://github.com/leanprover/lean4/pull/11149) adds a user-extension mechanism for the `try?` tactic. You can
either use the `@[try_suggestion]` attribute on a declaration with
signature ``MVarId -> Try.Info -> MetaM (Array (TSyntax `tactic))`` to
produce suggestions, or the `register_try?_tactic <stx>` command with a
fixed piece of syntax. User-extensions are only tried *after* the
built-in try strategies have been tried and failed.
* [#11157](https://github.com/leanprover/lean4/pull/11157) implements the `#grind_lint` command, a diagnostic tool for
analyzing the behavior of theorems annotated for theorem instantiation.
The command helps identify problematic theorems that produce excessive
or unbounded instance generation during E-matching, which can lead to
performance issues.
The main entry point is:
```
#grind_lint check
```
which analyzes all theorems marked with the `@[grind]` attribute.
For each theorem, it creates an artificial goal and runs `grind`,
collecting statistics about the number of instances produced.
Results are summarized using info messages, and detailed breakdowns are
shown for lemmas exceeding a configurable threshold.
Additional subcommands are provided for targeted inspection and control:
* `#grind_lint inspect thm`: analyzes one or more specific theorems in
detail
* `#grind_lint mute thm`: excludes a theorem from instantiation during
analysis
* `#grind_lint skip thm`: omits a theorem from being analyzed by
`#grind_lint check`
* [#11166](https://github.com/leanprover/lean4/pull/11166) implements the following improvements to the `#grind_lint`
command:
1. More informative messages when the number of instances exceeds the
minimum threshold.
2. A code action for `#grind_lint inspect` that inserts
`set_option trace.grind.ematch.instance true` whenever the number of
instances exceeds
the minimum threshold.
3. Displaying doc strings for `grind` configuration options in
`#grind_lint`.
4. Improve doc strings for `#grind_lint inspect` and `#grind_lint
check`.
* [#11167](https://github.com/leanprover/lean4/pull/11167) implements support for `#grind_lint check in module <module>`.
Mathlib does not use namespaces, so we need to restrict the
`#grind_lint` search space using module (prefix) names. Example:
```lean
/--
info: instantiating `Array.filterMap_some` triggers more than 100 additional `grind` theorem instantiations
---
info: Array.filterMap_some
[thm] instances
[thm] Array.filterMap_filterMap ↦ 94
[thm] Array.size_filterMap_le ↦ 5
[thm] Array.filterMap_some ↦ 1
---
info: instantiating `Array.range_succ` triggers 22 additional `grind` theorem instantiations
-/
#guard_msgs in
#grind_lint check (min := 20) in module Init.Data.Array
```
* [#11168](https://github.com/leanprover/lean4/pull/11168) changes the default library suggestions (e.g. for `grind
+suggestions` or `simp_all? +suggestions) to include the theorems from
the current file in addition to the output of Sine Qua Non.
* [#11170](https://github.com/leanprover/lean4/pull/11170) adds tactic and term mode macros for `∎` (typed `\qed`) which
expand to `try?`. The term mode version captures any produced
suggestions and prepends `by`.
* [#11171](https://github.com/leanprover/lean4/pull/11171) ensures that tactics using library suggestions set the caller
field, so the premise selection engine has access to this. We'll later
use this to filter out some modules for grind, which we know have
already been fully annotated.
* [#11172](https://github.com/leanprover/lean4/pull/11172) removes `simp_all? +suggestions` from `try?` for now. It's
really slow out in Mathlib; too often the suggestions cause `simp` to
loop. Until we have the ability for `try?` to move past a timeing-out
tactic (or maybe even until we have parallelism), it needs to be
removed.
* [#11174](https://github.com/leanprover/lean4/pull/11174) modifies the `try?` framework, so each subsidiary tactic runs
with a separate `maxHeartbeats` budget.
* [#11187](https://github.com/leanprover/lean4/pull/11187) adds syntax for specifying `grind_pattern` constraints and
extends the `EMatchTheorem` object.
* [#11189](https://github.com/leanprover/lean4/pull/11189) implements `grind_pattern` constraints. They are useful for
controlling theorem instantiation in `grind`. As an example, consider
the following two theorems:
```lean
theorem extract_empty {start stop : Nat} :
(#[] : Array α).extract start stop = #[] := …
* [#11193](https://github.com/leanprover/lean4/pull/11193) uses the new `grind_pattern` constraints to fix cases where an
unbounded number of theorem instantiations would be generated for
certain theorems in the standard library.
* [#11194](https://github.com/leanprover/lean4/pull/11194) the redundant `grind` parameter warning message. It now checks
the `grind` theorem instantiation constraints too.
* [#11197](https://github.com/leanprover/lean4/pull/11197) implements `try?` using the new `finish?` infrastructure. It
also removes the old tracing infrastructure, which is now obsolete.
Example:
```lean
/--
info: Try these:
[apply] grind
[apply] grind only [findIdx, insert, = mem_indices_of_mem, = getElem?_neg, = getElem?_pos, = HashMap.mem_insert,
= HashMap.getElem_insert, #1bba]
[apply] grind only [findIdx, insert, = mem_indices_of_mem, = getElem?_neg, = getElem?_pos, = HashMap.mem_insert,
= HashMap.getElem_insert]
[apply] grind =>
instantiate only [findIdx, insert, = mem_indices_of_mem]
instantiate only [= getElem?_neg, = getElem?_pos]
cases #1bba
· instantiate only [findIdx]
· instantiate only
instantiate only [= HashMap.mem_insert, = HashMap.getElem_insert]
-/
#guard_msgs in
example (m : IndexMap α β) (a : α) (b : β) :
(m.insert a b).findIdx a = if h : a ∈ m then m.findIdx a else m.size := by
try?
```
* [#11203](https://github.com/leanprover/lean4/pull/11203) fixes a few minor issues in the new `Action` framework used in
`grind`. The goal is to eventually delete the old `SearchM`
infrastructure. The main `solve` function used by `grind` is now based
on the `Action` framework. The PR also deletes dead code in `SearchM`.
* [#11204](https://github.com/leanprover/lean4/pull/11204) has `#grind_list check` produce a "Try this:" suggestion with
`#grind_list inspect` commands, as this is usually the next step in
dealing with problematic cases. We also fix the grind pattern for one
theorem, as part of testing the workflow. More to follow.
## Compiler
* [#10625](https://github.com/leanprover/lean4/pull/10625) implements zero cost `BaseIO` by erasing the `IO.RealWorld`
parameter from argument lists and structures. This is a **major breaking
change for FFI**.
* [#10727](https://github.com/leanprover/lean4/pull/10727) fixes name mangling to be unambiguous / injective by adding `00`
for disambiguation where necessary. Additionally, the inverse function,
`Lean.Name.unmangle` has been added which can be used to unmangle a
mangled identifier. This unmangler has been added to demonstrate the
injectivity but also to allow unmangling identifiers e.g. for debugging
purposes.
* [#10856](https://github.com/leanprover/lean4/pull/10856) performs more widening in ElimDeadBranches in an attempt to
improve performance in situations with a lot of local precision.
* [#10864](https://github.com/leanprover/lean4/pull/10864) reduces the amount of symbols in our DLLs by cutting open a
linking cycle of the shape:
`Environment -> Compiler -> Meta -> Environment`
* [#10982](https://github.com/leanprover/lean4/pull/10982) changes the closure allocator to use the general allocator
instead of the small object one.
This is because users may create closures with a gigantic amount of
closed variables which in turn
boost the size of the closure beyond the small object threshold.
* [#11000](https://github.com/leanprover/lean4/pull/11000) fixes a memleak caused by the Lean based `IO.waitAny`
implementation by reverting it.
* [#11010](https://github.com/leanprover/lean4/pull/11010) makes the eager lambda lifting heuristic more predictable by
blocking it from lifting from
any kind of inlineable function, not just `@[inline]`. It also adapts
the doc-string to describe
what is actually going on.
* [#11020](https://github.com/leanprover/lean4/pull/11020) improves the detection of situations where we branch multiple
times on the same value in the
code generator. Previously this would only consider repeated branching
on function arguments, now on
arbitrary values.
* [#11042](https://github.com/leanprover/lean4/pull/11042) fixes a case of overeager constant folding on UInts where the
compiler would mistakenly
assume `0 - x = x`.
* [#11043](https://github.com/leanprover/lean4/pull/11043) fixes a case of overeager constant folding on Nat where the
compiler would mistakenly assume `0 - x = x` (see also #11042 for the
same bug on UInts).
* [#11044](https://github.com/leanprover/lean4/pull/11044) enforces users of the constant folder API to provide proofs of
their algebraic properties,
thus hopefully avoiding bugs such as #11042 and #11043 in the future.
* [#11056](https://github.com/leanprover/lean4/pull/11056) fixes `ST.Ref.ptrEq` to act as described in the docs. This fixes
two bugs:
1. The recent `IO.RealWorld` elimination PR overlooked this function
(afaik this is the only one),
causing its return value to be generally wrong.
2. The implementation of `ptrEq` would previously always consider two
different cells with pointer
equivalent value to be pointer equal. However, the function is supposed
to check whether two
`Ref` are the same cell, not whether the contained elements are.
* [#11151](https://github.com/leanprover/lean4/pull/11151) fixes some details in the Markdown renderings of Verso
docstrings, and adds tests to keep them correct. Also adds tests for
Verso docstring metadata.
## Documentation
* [#11179](https://github.com/leanprover/lean4/pull/11179) removes most cases where an error message explained that it was
"probably due to metavariables," giving more explanation and a hint.
## Server
* [#10787](https://github.com/leanprover/lean4/pull/10787) revamps the server logging mechanism to allow filtering the log
output by LSP method.
* [#10805](https://github.com/leanprover/lean4/pull/10805) adds a field `isDisplayableTerm` to `TermInfo` and all utility
functions which create `TermInfo` that can be set to force the language
server to render the term in hover popups.
## Lake
* [#10861](https://github.com/leanprover/lean4/pull/10861) fixes `input_dir` tracking to also recurse through
subdirectories. The `filter` of an `input_dir` will be applied to each
file in the directory tree (the path names of directories will not be
checked).
* [#10883](https://github.com/leanprover/lean4/pull/10883) fixes a bug with Lake's cache where revisions were stored at the
incorrect path. Revisions were stored at `<rev>/<pkg>.jsonl` rather than
the correct `<pkg>/<rev>.jsonl`.
* [#10959](https://github.com/leanprover/lean4/pull/10959) enables Lake users to require Reservoir dependencies by a
semantic version range. On a `lake update`, Lake will fetch the
package's version information from Reservoir and select the newest
version of the package that satisfies the range.
* [#11062](https://github.com/leanprover/lean4/pull/11062) changes Lake's debug build type to use `-O0` instead of `-Og`
when compiling C code. `-Og` was found to be insufficient for debugging
compiled Lean code -- relevant code was stilled optimized out.
* [#11063](https://github.com/leanprover/lean4/pull/11063) changes the `math` and `math-lax` templates for `lake new` and
`lake init` to use the version of Mathlib corresponding to the current
Lean toolchain. Thus, `lake +x.y.z new <pkg> math` will use the Mathlib
for Lean `x.y.z`. On the other hand, `lake update` on such packages will
no longer update Mathlib automatically. Users will need to change the
Mathlib revision in the configuration file before updating.
* [#11117](https://github.com/leanprover/lean4/pull/11117) fixes a bug where Lake ignored `moreLinkObjs` and `moreLinkLibs`
on a `lean_exe`.
* [#11118](https://github.com/leanprover/lean4/pull/11118) adds `Job.sync` as a standard way of declaring a synchronous
job.
* [#11169](https://github.com/leanprover/lean4/pull/11169) changes all module build keys in Lake to be scoped by their
package. This enables building modules with the same name in different
packages (something previously only well-supported for executable
roots).
## Other
* [#11074](https://github.com/leanprover/lean4/pull/11074) adds a `.claude/claude.md`, with basic development instructions
for Claude Code to operate in this repository.
```` |
reference-manual/Manual/Releases/v4_2_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.2.0 (2023-10-31)" =>
%%%
tag := "release-v4.2.0"
file := "v4.2.0"
%%%
```markdown
* [isDefEq cache for terms not containing metavariables.](https://github.com/leanprover/lean4/pull/2644).
* Make [`Environment.mk`](https://github.com/leanprover/lean4/pull/2604) and [`Environment.add`](https://github.com/leanprover/lean4/pull/2642) private, and add [`replay`](https://github.com/leanprover/lean4/pull/2617) as a safer alternative.
* `IO.Process.output` no longer inherits the standard input of the caller.
* [Do not inhibit caching](https://github.com/leanprover/lean4/pull/2612) of default-level `match` reduction.
* [List the valid case tags](https://github.com/leanprover/lean4/pull/2629) when the user writes an invalid one.
* The derive handler for `DecidableEq` [now handles](https://github.com/leanprover/lean4/pull/2591) mutual inductive types.
* [Show path of failed import in Lake](https://github.com/leanprover/lean4/pull/2616).
* [Fix linker warnings on macOS](https://github.com/leanprover/lean4/pull/2598).
* **Lake:** Add `postUpdate?` package configuration option. Used by a package to specify some code which should be run after a successful `lake update` of the package or one of its downstream dependencies. ([lake#185](https://github.com/leanprover/lake/issues/185))
* Improvements to Lake startup time ([#2572](https://github.com/leanprover/lean4/pull/2572), [#2573](https://github.com/leanprover/lean4/pull/2573))
* `refine e` now replaces the main goal with metavariables which were created during elaboration of `e` and no longer captures pre-existing metavariables that occur in `e` ([#2502](https://github.com/leanprover/lean4/pull/2502)).
* This is accomplished via changes to `withCollectingNewGoalsFrom`, which also affects `elabTermWithHoles`, `refine'`, `calc` (tactic), and `specialize`. Likewise, all of these now only include newly-created metavariables in their output.
* Previously, both newly-created and pre-existing metavariables occurring in `e` were returned inconsistently in different edge cases, causing duplicated goals in the infoview (issue [#2495](https://github.com/leanprover/lean4/issues/2495)), erroneously closed goals (issue [#2434](https://github.com/leanprover/lean4/issues/2434)), and unintuitive behavior due to `refine e` capturing previously-created goals appearing unexpectedly in `e` (no issue; see PR).
``` |
reference-manual/Manual/Releases/v4_0_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.0.0 (2023-09-08)" =>
%%%
tag := "release-v4.0.0"
file := "v4.0.0"
%%%
````markdown
* [`Lean.Meta.getConst?` has been renamed](https://github.com/leanprover/lean4/pull/2454).
We have renamed `getConst?` to `getUnfoldableConst?` (and `getConstNoEx?` to `getUnfoldableConstNoEx?`).
These were not intended to be part of the public API, but downstream projects had been using them
(sometimes expecting different behaviour) incorrectly instead of `Lean.getConstInfo`.
* [`dsimp` / `simp` / `simp_all` now fail by default if they make no progress](https://github.com/leanprover/lean4/pull/2336).
This can be overridden with the `(config := { failIfUnchanged := false })` option.
This change was made to ease manual use of `simp` (with complicated goals it can be hard to tell if it was effective)
and to allow easier flow control in tactics internally using `simp`.
See the [summary discussion](https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/simp.20fails.20if.20no.20progress/near/380153295)
on zulip for more details.
* [`simp_all` now preserves order of hypotheses](https://github.com/leanprover/lean4/pull/2334).
In order to support the `failIfUnchanged` configuration option for `dsimp` / `simp` / `simp_all`
the way `simp_all` replaces hypotheses has changed.
In particular it is now more likely to preserve the order of hypotheses.
See [`simp_all` reorders hypotheses unnecessarily](https://github.com/leanprover/lean4/pull/2334).
(Previously all non-dependent propositional hypotheses were reverted and reintroduced.
Now only such hypotheses which were changed, or which come after a changed hypothesis,
are reverted and reintroduced.
This has the effect of preserving the ordering amongst the non-dependent propositional hypotheses,
but now any dependent or non-propositional hypotheses retain their position amongst the unchanged
non-dependent propositional hypotheses.)
This may affect proofs that use `rename_i`, `case ... =>`, or `next ... =>`.
* [New `have this` implementation](https://github.com/leanprover/lean4/pull/2247).
`this` is now a regular identifier again that is implicitly introduced by anonymous `have :=` for the remainder of the tactic block. It used to be a keyword that was visible in all scopes and led to unexpected behavior when explicitly used as a binder name.
* [Show type class and tactic names in profile output](https://github.com/leanprover/lean4/pull/2170).
* [Make `calc` require the sequence of relation/proof-s to have the same indentation](https://github.com/leanprover/lean4/pull/1844),
and [add `calc` alternative syntax allowing underscores `_` in the first relation](https://github.com/leanprover/lean4/pull/1844).
The flexible indentation in `calc` was often used to align the relation symbols:
```lean
example (x y : Nat) : (x + y) * (x + y) = x * x + y * x + x * y + y * y :=
calc
(x + y) * (x + y) = (x + y) * x + (x + y) * y := by rw [Nat.mul_add]
-- improper indentation
_ = x * x + y * x + (x + y) * y := by rw [Nat.add_mul]
_ = x * x + y * x + (x * y + y * y) := by rw [Nat.add_mul]
_ = x * x + y * x + x * y + y * y := by rw [←Nat.add_assoc]
```
This is no longer legal. The new syntax puts the first term right after the `calc` and each step has the same indentation:
```lean
example (x y : Nat) : (x + y) * (x + y) = x * x + y * x + x * y + y * y :=
calc (x + y) * (x + y)
_ = (x + y) * x + (x + y) * y := by rw [Nat.mul_add]
_ = x * x + y * x + (x + y) * y := by rw [Nat.add_mul]
_ = x * x + y * x + (x * y + y * y) := by rw [Nat.add_mul]
_ = x * x + y * x + x * y + y * y := by rw [←Nat.add_assoc]
```
* Update Lake to latest prerelease.
* [Make go-to-definition on a type class projection application go to the instance(s)](https://github.com/leanprover/lean4/pull/1767).
* [Include timings in trace messages when `profiler` is true](https://github.com/leanprover/lean4/pull/1995).
* [Pretty-print signatures in hover and `#check <ident>`](https://github.com/leanprover/lean4/pull/1943).
* [Introduce parser memoization to avoid exponential behavior](https://github.com/leanprover/lean4/pull/1799).
* [feat: allow `doSeq` in `let x <- e | seq`](https://github.com/leanprover/lean4/pull/1809).
* [Add hover/go-to-def/refs for options](https://github.com/leanprover/lean4/pull/1783).
* [Add empty type ascription syntax `(e :)`](https://github.com/leanprover/lean4/pull/1797).
* [Make tokens in `<|>` relevant to syntax match](https://github.com/leanprover/lean4/pull/1744).
* [Add `linter.deprecated` option to silence deprecation warnings](https://github.com/leanprover/lean4/pull/1768).
* [Improve fuzzy-matching heuristics](https://github.com/leanprover/lean4/pull/1710).
* [Implementation-detail hypotheses](https://github.com/leanprover/lean4/pull/1692).
* [Hover information for `cases`/`induction` case names](https://github.com/leanprover/lean4/pull/1660).
* [Prefer longer parse even if unsuccessful](https://github.com/leanprover/lean4/pull/1658).
* [Show declaration module in hover](https://github.com/leanprover/lean4/pull/1638).
* [New `conv` mode structuring tactics](https://github.com/leanprover/lean4/pull/1636).
* `simp` can track information and can print an equivalent `simp only`. [PR #1626](https://github.com/leanprover/lean4/pull/1626).
* Enforce uniform indentation in tactic blocks / do blocks. See issue [#1606](https://github.com/leanprover/lean4/issues/1606).
* Moved `AssocList`, `HashMap`, `HashSet`, `RBMap`, `RBSet`, `PersistentArray`, `PersistentHashMap`, `PersistentHashSet` to the Lean package. The [standard library](https://github.com/leanprover/std4) contains versions that will evolve independently to simplify bootstrapping process.
* Standard library moved to the [std4 GitHub repository](https://github.com/leanprover/std4).
* `InteractiveGoals` now has information that a client infoview can use to show what parts of the goal have changed after applying a tactic. [PR #1610](https://github.com/leanprover/lean4/pull/1610).
* Add `[inheritDoc]` attribute. [PR #1480](https://github.com/leanprover/lean4/pull/1480).
* Expose that `panic = default`. [PR #1614](https://github.com/leanprover/lean4/pull/1614).
* New [code generator](https://github.com/leanprover/lean4/tree/master/src/Lean/Compiler/LCNF) project has started.
* Remove description argument from `register_simp_attr`. [PR #1566](https://github.com/leanprover/lean4/pull/1566).
* [Additional concurrency primitives](https://github.com/leanprover/lean4/pull/1555).
* [Collapsible traces with messages](https://github.com/leanprover/lean4/pull/1448).
* [Hygienic resolution of namespaces](https://github.com/leanprover/lean4/pull/1442).
* [New `Float` functions](https://github.com/leanprover/lean4/pull/1460).
* Many new doc strings have been added to declarations at `Init`.
```` |
reference-manual/Manual/Releases/v4_12_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.12.0 (2024-10-01)" =>
%%%
tag := "release-v4.12.0"
file := "v4.12.0"
%%%
````markdown
### Language features, tactics, and metaprograms
* `bv_decide` tactic. This release introduces a new tactic for proving goals involving `BitVec` and `Bool`. It reduces the goal to a SAT instance that is refuted by an external solver, and the resulting LRAT proof is checked in Lean. This is used to synthesize a proof of the goal by reflection. As this process uses verified algorithms, proofs generated by this tactic use `Lean.ofReduceBool`, so this tactic includes the Lean compiler as part of the trusted code base. The external solver CaDiCaL is included with Lean and does not need to be installed separately to make use of `bv_decide`.
For example, we can use `bv_decide` to verify that a bit twiddling formula leaves at most one bit set:
```lean
def popcount (x : BitVec 64) : BitVec 64 :=
let rec go (x pop : BitVec 64) : Nat → BitVec 64
| 0 => pop
| n + 1 => go (x >>> 2) (pop + (x &&& 1)) n
go x 0 64
example (x : BitVec 64) : popcount ((x &&& (x - 1)) ^^^ x) ≤ 1 := by
simp only [popcount, popcount.go]
bv_decide
```
When the external solver fails to refute the SAT instance generated by `bv_decide`, it can report a counterexample:
```lean
/--
error: The prover found a counterexample, consider the following assignment:
x = 0xffffffffffffffff#64
-/
#guard_msgs in
example (x : BitVec 64) : x < x + 1 := by
bv_decide
```
See `Lean.Elab.Tactic.BVDecide` for a more detailed overview, and look in `tests/lean/run/bv_*` for examples.
[#5013](https://github.com/leanprover/lean4/pull/5013), [#5074](https://github.com/leanprover/lean4/pull/5074), [#5100](https://github.com/leanprover/lean4/pull/5100), [#5113](https://github.com/leanprover/lean4/pull/5113), [#5137](https://github.com/leanprover/lean4/pull/5137), [#5203](https://github.com/leanprover/lean4/pull/5203), [#5212](https://github.com/leanprover/lean4/pull/5212), [#5220](https://github.com/leanprover/lean4/pull/5220).
* `simp` tactic
* [#4988](https://github.com/leanprover/lean4/pull/4988) fixes a panic in the `reducePow` simproc.
* [#5071](https://github.com/leanprover/lean4/pull/5071) exposes the `index` option to the `dsimp` tactic, introduced to `simp` in [#4202](https://github.com/leanprover/lean4/pull/4202).
* [#5159](https://github.com/leanprover/lean4/pull/5159) fixes a panic at `Fin.isValue` simproc.
* [#5167](https://github.com/leanprover/lean4/pull/5167) and [#5175](https://github.com/leanprover/lean4/pull/5175) rename the `simpCtorEq` simproc to `reduceCtorEq` and makes it optional. (See breaking changes.)
* [#5187](https://github.com/leanprover/lean4/pull/5187) ensures `reduceCtorEq` is enabled in the `norm_cast` tactic.
* [#5073](https://github.com/leanprover/lean4/pull/5073) modifies the simp debug trace messages to tag with "dpre" and "dpost" instead of "pre" and "post" when in definitional rewrite mode. [#5054](https://github.com/leanprover/lean4/pull/5054) explains the `reduce` steps for `trace.Debug.Meta.Tactic.simp` trace messages.
* `ext` tactic
* [#4996](https://github.com/leanprover/lean4/pull/4996) reduces default maximum iteration depth from 1000000 to 100.
* `induction` tactic
* [#5117](https://github.com/leanprover/lean4/pull/5117) fixes a bug where `let` bindings in minor premises wouldn't be counted correctly.
* `omega` tactic
* [#5157](https://github.com/leanprover/lean4/pull/5157) fixes a panic.
* `conv` tactic
* [#5149](https://github.com/leanprover/lean4/pull/5149) improves `arg n` to handle subsingleton instance arguments.
* [#5044](https://github.com/leanprover/lean4/pull/5044) upstreams the `#time` command.
* [#5079](https://github.com/leanprover/lean4/pull/5079) makes `#check` and `#reduce` typecheck the elaborated terms.
* **Incrementality**
* [#4974](https://github.com/leanprover/lean4/pull/4974) fixes regression where we would not interrupt elaboration of previous document versions.
* [#5004](https://github.com/leanprover/lean4/pull/5004) fixes a performance regression.
* [#5001](https://github.com/leanprover/lean4/pull/5001) disables incremental body elaboration in presence of `where` clauses in declarations.
* [#5018](https://github.com/leanprover/lean4/pull/5018) enables infotrees on the command line for ilean generation.
* [#5040](https://github.com/leanprover/lean4/pull/5040) and [#5056](https://github.com/leanprover/lean4/pull/5056) improve performance of info trees.
* [#5090](https://github.com/leanprover/lean4/pull/5090) disables incrementality in the `case .. | ..` tactic.
* [#5312](https://github.com/leanprover/lean4/pull/5312) fixes a bug where changing whitespace after the module header could break subsequent commands.
* **Definitions**
* [#5016](https://github.com/leanprover/lean4/pull/5016) and [#5066](https://github.com/leanprover/lean4/pull/5066) add `clean_wf` tactic to clean up tactic state in `decreasing_by`. This can be disabled with `set_option debug.rawDecreasingByGoal false`.
* [#5055](https://github.com/leanprover/lean4/pull/5055) unifies equational theorems between structural and well-founded recursion.
* [#5041](https://github.com/leanprover/lean4/pull/5041) allows mutually recursive functions to use different parameter names among the “fixed parameter prefix”
* [#4154](https://github.com/leanprover/lean4/pull/4154) and [#5109](https://github.com/leanprover/lean4/pull/5109) add fine-grained equational lemmas for non-recursive functions. See breaking changes.
* [#5129](https://github.com/leanprover/lean4/pull/5129) unifies equation lemmas for recursive and non-recursive definitions. The `backward.eqns.deepRecursiveSplit` option can be set to `false` to get the old behavior. See breaking changes.
* [#5141](https://github.com/leanprover/lean4/pull/5141) adds `f.eq_unfold` lemmas. Now Lean produces the following zoo of rewrite rules:
```
Option.map.eq_1 : Option.map f none = none
Option.map.eq_2 : Option.map f (some x) = some (f x)
Option.map.eq_def : Option.map f p = match o with | none => none | (some x) => some (f x)
Option.map.eq_unfold : Option.map = fun f p => match o with | none => none | (some x) => some (f x)
```
The `f.eq_unfold` variant is especially useful to rewrite with `rw` under binders.
* [#5136](https://github.com/leanprover/lean4/pull/5136) fixes bugs in recursion over predicates.
* **Variable inclusion**
* [#5206](https://github.com/leanprover/lean4/pull/5206) documents that `include` currently only applies to theorems.
* **Elaboration**
* [#4926](https://github.com/leanprover/lean4/pull/4926) fixes a bug where autoparam errors were associated to an incorrect source position.
* [#4833](https://github.com/leanprover/lean4/pull/4833) fixes an issue where cdot anonymous functions (e.g. `(· + ·)`) would not handle ambiguous notation correctly. Numbers the parameters, making this example expand as `fun x1 x2 => x1 + x2` rather than `fun x x_1 => x + x_1`.
* [#5037](https://github.com/leanprover/lean4/pull/5037) improves strength of the tactic that proves array indexing is in bounds.
* [#5119](https://github.com/leanprover/lean4/pull/5119) fixes a bug in the tactic that proves indexing is in bounds where it could loop in the presence of mvars.
* [#5072](https://github.com/leanprover/lean4/pull/5072) makes the structure type clickable in "not a field of structure" errors for structure instance notation.
* [#4717](https://github.com/leanprover/lean4/pull/4717) fixes a bug where mutual `inductive` commands could create terms that the kernel rejects.
* [#5142](https://github.com/leanprover/lean4/pull/5142) fixes a bug where `variable` could fail when mixing binder updates and declarations.
* **Other fixes or improvements**
* [#5118](https://github.com/leanprover/lean4/pull/5118) changes the definition of the `syntheticHole` parser so that hovering over `_` in `?_` gives the docstring for synthetic holes.
* [#5173](https://github.com/leanprover/lean4/pull/5173) uses the emoji variant selector for ✅️,❌️,💥️ in messages, improving fonts selection.
* [#5183](https://github.com/leanprover/lean4/pull/5183) fixes a bug in `rename_i` where implementation detail hypotheses could be renamed.
### Language server, widgets, and IDE extensions
* [#4821](https://github.com/leanprover/lean4/pull/4821) resolves two language server bugs that especially affect Windows users. (1) Editing the header could result in the watchdog not correctly restarting the file worker, which would lead to the file seemingly being processed forever. (2) On an especially slow Windows machine, we found that starting the language server would sometimes not succeed at all. This PR also resolves an issue where we would not correctly emit messages that we received while the file worker is being restarted to the corresponding file worker after the restart.
* [#5006](https://github.com/leanprover/lean4/pull/5006) updates the user widget manual.
* [#5193](https://github.com/leanprover/lean4/pull/5193) updates the quickstart guide with the new display name for the Lean 4 extension ("Lean 4").
* [#5185](https://github.com/leanprover/lean4/pull/5185) fixes a bug where over time "import out of date" messages would accumulate.
* [#4900](https://github.com/leanprover/lean4/pull/4900) improves ilean loading performance by about a factor of two. Optimizes the JSON parser and the conversion from JSON to Lean data structures; see PR description for details.
* **Other fixes or improvements**
* [#5031](https://github.com/leanprover/lean4/pull/5031) localizes an instance in `Lsp.Diagnostics`.
### Pretty printing
* [#4976](https://github.com/leanprover/lean4/pull/4976) introduces `@[app_delab]`, a macro for creating delaborators for particular constants. The `@[app_delab ident]` syntax resolves `ident` to its constant name `name` and then expands to `@[delab app.name]`.
* [#4982](https://github.com/leanprover/lean4/pull/4982) fixes a bug where the pretty printer assumed structure projections were type correct (such terms can appear in type mismatch errors). Improves hoverability of `#print` output for structures.
* [#5218](https://github.com/leanprover/lean4/pull/5218) and [#5239](https://github.com/leanprover/lean4/pull/5239) add `pp.exprSizes` debugging option. When true, each pretty printed expression is prefixed with `[size a/b/c]`, where `a` is the size without sharing, `b` is the actual size, and `c` is the size with the maximum possible sharing.
### Library
* [#5020](https://github.com/leanprover/lean4/pull/5020) swaps the parameters to `Membership.mem`. A purpose of this change is to make set-like `CoeSort` coercions to refer to the eta-expanded function `fun x => Membership.mem s x`, which can reduce in many computations. Another is that having the `s` argument first leads to better discrimination tree keys. (See breaking changes.)
* `Array`
* [#4970](https://github.com/leanprover/lean4/pull/4970) adds `@[ext]` attribute to `Array.ext`.
* [#4957](https://github.com/leanprover/lean4/pull/4957) deprecates `Array.get_modify`.
* `List`
* [#4995](https://github.com/leanprover/lean4/pull/4995) upstreams `List.findIdx` lemmas.
* [#5029](https://github.com/leanprover/lean4/pull/5029), [#5048](https://github.com/leanprover/lean4/pull/5048) and [#5132](https://github.com/leanprover/lean4/pull/5132) add `List.Sublist` lemmas, some upstreamed. [#5077](https://github.com/leanprover/lean4/pull/5077) fixes implicitness in refl/rfl lemma binders. add `List.Sublist` theorems.
* [#5047](https://github.com/leanprover/lean4/pull/5047) upstreams `List.Pairwise` lemmas.
* [#5053](https://github.com/leanprover/lean4/pull/5053), [#5124](https://github.com/leanprover/lean4/pull/5124), and [#5161](https://github.com/leanprover/lean4/pull/5161) add `List.find?/findSome?/findIdx?` theorems.
* [#5039](https://github.com/leanprover/lean4/pull/5039) adds `List.foldlRecOn` and `List.foldrRecOn` recursion principles to prove things about `List.foldl` and `List.foldr`.
* [#5069](https://github.com/leanprover/lean4/pull/5069) upstreams `List.Perm`.
* [#5092](https://github.com/leanprover/lean4/pull/5092) and [#5107](https://github.com/leanprover/lean4/pull/5107) add `List.mergeSort` and a fast `@[csimp]` implementation.
* [#5103](https://github.com/leanprover/lean4/pull/5103) makes the simp lemmas for `List.subset` more aggressive.
* [#5106](https://github.com/leanprover/lean4/pull/5106) changes the statement of `List.getLast?_cons`.
* [#5123](https://github.com/leanprover/lean4/pull/5123) and [#5158](https://github.com/leanprover/lean4/pull/5158) add `List.range` and `List.iota` lemmas.
* [#5130](https://github.com/leanprover/lean4/pull/5130) adds `List.join` lemmas.
* [#5131](https://github.com/leanprover/lean4/pull/5131) adds `List.append` lemmas.
* [#5152](https://github.com/leanprover/lean4/pull/5152) adds `List.erase(|P|Idx)` lemmas.
* [#5127](https://github.com/leanprover/lean4/pull/5127) makes miscellaneous lemma updates.
* [#5153](https://github.com/leanprover/lean4/pull/5153) and [#5160](https://github.com/leanprover/lean4/pull/5160) add lemmas about `List.attach` and `List.pmap`.
* [#5164](https://github.com/leanprover/lean4/pull/5164), [#5177](https://github.com/leanprover/lean4/pull/5177), and [#5215](https://github.com/leanprover/lean4/pull/5215) add `List.find?` and `List.range'/range/iota` lemmas.
* [#5196](https://github.com/leanprover/lean4/pull/5196) adds `List.Pairwise_erase` and related lemmas.
* [#5151](https://github.com/leanprover/lean4/pull/5151) and [#5163](https://github.com/leanprover/lean4/pull/5163) improve confluence of `List` simp lemmas. [#5105](https://github.com/leanprover/lean4/pull/5105) and [#5102](https://github.com/leanprover/lean4/pull/5102) adjust `List` simp lemmas.
* [#5178](https://github.com/leanprover/lean4/pull/5178) removes `List.getLast_eq_iff_getLast_eq_some` as a simp lemma.
* [#5210](https://github.com/leanprover/lean4/pull/5210) reverses the meaning of `List.getElem_drop` and `List.getElem_drop'`.
* [#5214](https://github.com/leanprover/lean4/pull/5214) moves `@[csimp]` lemmas earlier where possible.
* `Nat` and `Int`
* [#5104](https://github.com/leanprover/lean4/pull/5104) adds `Nat.add_left_eq_self` and relatives.
* [#5146](https://github.com/leanprover/lean4/pull/5146) adds missing `Nat.and_xor_distrib_(left|right)`.
* [#5148](https://github.com/leanprover/lean4/pull/5148) and [#5190](https://github.com/leanprover/lean4/pull/5190) improve `Nat` and `Int` simp lemma confluence.
* [#5165](https://github.com/leanprover/lean4/pull/5165) adjusts `Int` simp lemmas.
* [#5166](https://github.com/leanprover/lean4/pull/5166) adds `Int` lemmas relating `neg` and `emod`/`mod`.
* [#5208](https://github.com/leanprover/lean4/pull/5208) reverses the direction of the `Int.toNat_sub` simp lemma.
* [#5209](https://github.com/leanprover/lean4/pull/5209) adds `Nat.bitwise` lemmas.
* [#5230](https://github.com/leanprover/lean4/pull/5230) corrects the docstrings for integer division and modulus.
* `Option`
* [#5128](https://github.com/leanprover/lean4/pull/5128) and [#5154](https://github.com/leanprover/lean4/pull/5154) add `Option` lemmas.
* `BitVec`
* [#4889](https://github.com/leanprover/lean4/pull/4889) adds `sshiftRight` bitblasting.
* [#4981](https://github.com/leanprover/lean4/pull/4981) adds `Std.Associative` and `Std.Commutative` instances for `BitVec.[and|or|xor]`.
* [#4913](https://github.com/leanprover/lean4/pull/4913) enables `missingDocs` error for `BitVec` modules.
* [#4930](https://github.com/leanprover/lean4/pull/4930) makes parameter names for `BitVec` more consistent.
* [#5098](https://github.com/leanprover/lean4/pull/5098) adds `BitVec.intMin`. Introduces `boolToPropSimps` simp set for converting from boolean to propositional expressions.
* [#5200](https://github.com/leanprover/lean4/pull/5200) and [#5217](https://github.com/leanprover/lean4/pull/5217) rename `BitVec.getLsb` to `BitVec.getLsbD`, etc., to bring naming in line with `List`/`Array`/etc.
* **Theorems:** [#4977](https://github.com/leanprover/lean4/pull/4977), [#4951](https://github.com/leanprover/lean4/pull/4951), [#4667](https://github.com/leanprover/lean4/pull/4667), [#5007](https://github.com/leanprover/lean4/pull/5007), [#4997](https://github.com/leanprover/lean4/pull/4997), [#5083](https://github.com/leanprover/lean4/pull/5083), [#5081](https://github.com/leanprover/lean4/pull/5081), [#4392](https://github.com/leanprover/lean4/pull/4392)
* `UInt`
* [#4514](https://github.com/leanprover/lean4/pull/4514) fixes naming convention for `UInt` lemmas.
* `Std.HashMap` and `Std.HashSet`
* [#4943](https://github.com/leanprover/lean4/pull/4943) deprecates variants of hash map query methods. (See breaking changes.)
* [#4917](https://github.com/leanprover/lean4/pull/4917) switches the library and Lean to `Std.HashMap` and `Std.HashSet` almost everywhere.
* [#4954](https://github.com/leanprover/lean4/pull/4954) deprecates `Lean.HashMap` and `Lean.HashSet`.
* [#5023](https://github.com/leanprover/lean4/pull/5023) cleans up lemma parameters.
* `Std.Sat` (for `bv_decide`)
* [#4933](https://github.com/leanprover/lean4/pull/4933) adds definitions of SAT and CNF.
* [#4953](https://github.com/leanprover/lean4/pull/4953) defines "and-inverter graphs" (AIGs) as described in section 3 of [Davis-Swords 2013](https://arxiv.org/pdf/1304.7861.pdf).
* **Parsec**
* [#4774](https://github.com/leanprover/lean4/pull/4774) generalizes the `Parsec` library, allowing parsing of iterable data beyond `String` such as `ByteArray`. (See breaking changes.)
* [#5115](https://github.com/leanprover/lean4/pull/5115) moves `Lean.Data.Parsec` to `Std.Internal.Parsec` for bootstrappng reasons.
* `Thunk`
* [#4969](https://github.com/leanprover/lean4/pull/4969) upstreams `Thunk.ext`.
* **IO**
* [#4973](https://github.com/leanprover/lean4/pull/4973) modifies `IO.FS.lines` to handle `\r\n` on all operating systems instead of just on Windows.
* [#5125](https://github.com/leanprover/lean4/pull/5125) adds `createTempFile` and `withTempFile` for creating temporary files that can only be read and written by the current user.
* **Other fixes or improvements**
* [#4945](https://github.com/leanprover/lean4/pull/4945) adds `Array`, `Bool` and `Prod` utilities from LeanSAT.
* [#4960](https://github.com/leanprover/lean4/pull/4960) adds `Relation.TransGen.trans`.
* [#5012](https://github.com/leanprover/lean4/pull/5012) states `WellFoundedRelation Nat` using `<`, not `Nat.lt`.
* [#5011](https://github.com/leanprover/lean4/pull/5011) uses `≠` instead of `Not (Eq ...)` in `Fin.ne_of_val_ne`.
* [#5197](https://github.com/leanprover/lean4/pull/5197) upstreams `Fin.le_antisymm`.
* [#5042](https://github.com/leanprover/lean4/pull/5042) reduces usage of `refine'`.
* [#5101](https://github.com/leanprover/lean4/pull/5101) adds about `if-then-else` and `Option`.
* [#5112](https://github.com/leanprover/lean4/pull/5112) adds basic instances for `ULift` and `PLift`.
* [#5133](https://github.com/leanprover/lean4/pull/5133) and [#5168](https://github.com/leanprover/lean4/pull/5168) make fixes from running the simpNF linter over Lean.
* [#5156](https://github.com/leanprover/lean4/pull/5156) removes a bad simp lemma in `omega` theory.
* [#5155](https://github.com/leanprover/lean4/pull/5155) improves confluence of `Bool` simp lemmas.
* [#5162](https://github.com/leanprover/lean4/pull/5162) improves confluence of `Function.comp` simp lemmas.
* [#5191](https://github.com/leanprover/lean4/pull/5191) improves confluence of `if-then-else` simp lemmas.
* [#5147](https://github.com/leanprover/lean4/pull/5147) adds `@[elab_as_elim]` to `Quot.rec`, `Nat.strongInductionOn` and `Nat.casesStrongInductionOn`, and also renames the latter two to `Nat.strongRecOn` and `Nat.casesStrongRecOn` (deprecated in [#5179](https://github.com/leanprover/lean4/pull/5179)).
* [#5180](https://github.com/leanprover/lean4/pull/5180) disables some simp lemmas with bad discrimination tree keys.
* [#5189](https://github.com/leanprover/lean4/pull/5189) cleans up internal simp lemmas that had leaked.
* [#5198](https://github.com/leanprover/lean4/pull/5198) cleans up `allowUnsafeReducibility`.
* [#5229](https://github.com/leanprover/lean4/pull/5229) removes unused lemmas from some `simp` tactics.
* [#5199](https://github.com/leanprover/lean4/pull/5199) removes >6 month deprecations.
### Lean internals
* **Performance**
* Some core algorithms have been rewritten in C++ for performance.
* [#4910](https://github.com/leanprover/lean4/pull/4910) and [#4912](https://github.com/leanprover/lean4/pull/4912) reimplement `instantiateLevelMVars`.
* [#4915](https://github.com/leanprover/lean4/pull/4915), [#4922](https://github.com/leanprover/lean4/pull/4922), and [#4931](https://github.com/leanprover/lean4/pull/4931) reimplement `instantiateExprMVars`, 30% faster on a benchmark.
* [#4934](https://github.com/leanprover/lean4/pull/4934) has optimizations for the kernel's `Expr` equality test.
* [#4990](https://github.com/leanprover/lean4/pull/4990) fixes bug in hashing for the kernel's `Expr` equality test.
* [#4935](https://github.com/leanprover/lean4/pull/4935) and [#4936](https://github.com/leanprover/lean4/pull/4936) skip some `PreDefinition` transformations if they are not needed.
* [#5225](https://github.com/leanprover/lean4/pull/5225) adds caching for visited exprs at `CheckAssignmentQuick` in `ExprDefEq`.
* [#5226](https://github.com/leanprover/lean4/pull/5226) maximizes term sharing at `instantiateMVarDeclMVars`, used by `runTactic`.
* **Diagnostics and profiling**
* [#4923](https://github.com/leanprover/lean4/pull/4923) adds profiling for `instantiateMVars` in `Lean.Elab.MutualDef`, which can be a bottleneck there.
* [#4924](https://github.com/leanprover/lean4/pull/4924) adds diagnostics for large theorems, controlled by the `diagnostics.threshold.proofSize` option.
* [#4897](https://github.com/leanprover/lean4/pull/4897) improves display of diagnostic results.
* **Other fixes or improvements**
* [#4921](https://github.com/leanprover/lean4/pull/4921) cleans up `Expr.betaRev`.
* [#4940](https://github.com/leanprover/lean4/pull/4940) fixes tests by not writing directly to stdout, which is unreliable now that elaboration and reporting are executed in separate threads.
* [#4955](https://github.com/leanprover/lean4/pull/4955) documents that `stderrAsMessages` is now the default on the command line as well.
* [#4647](https://github.com/leanprover/lean4/pull/4647) adjusts documentation for building on macOS.
* [#4987](https://github.com/leanprover/lean4/pull/4987) makes regular mvar assignments take precedence over delayed ones in `instantiateMVars`. Normally delayed assignment metavariables are never directly assigned, but on errors Lean assigns `sorry` to unassigned metavariables.
* [#4967](https://github.com/leanprover/lean4/pull/4967) adds linter name to errors when a linter crashes.
* [#5043](https://github.com/leanprover/lean4/pull/5043) cleans up command line snapshots logic.
* [#5067](https://github.com/leanprover/lean4/pull/5067) minimizes some imports.
* [#5068](https://github.com/leanprover/lean4/pull/5068) generalizes the monad for `addMatcherInfo`.
* [f71a1f](https://github.com/leanprover/lean4/commit/f71a1fb4ae958fccb3ad4d48786a8f47ced05c15) adds missing test for [#5126](https://github.com/leanprover/lean4/issues/5126).
* [#5201](https://github.com/leanprover/lean4/pull/5201) restores a test.
* [#3698](https://github.com/leanprover/lean4/pull/3698) fixes a bug where label attributes did not pass on the attribute kind.
* Typos: [#5080](https://github.com/leanprover/lean4/pull/5080), [#5150](https://github.com/leanprover/lean4/pull/5150), [#5202](https://github.com/leanprover/lean4/pull/5202)
### Compiler, runtime, and FFI
* [#3106](https://github.com/leanprover/lean4/pull/3106) moves frontend to new snapshot architecture. Note that `Frontend.processCommand` and `FrontendM` are no longer used by Lean core, but they will be preserved.
* [#4919](https://github.com/leanprover/lean4/pull/4919) adds missing include in runtime for `AUTO_THREAD_FINALIZATION` feature on Windows.
* [#4941](https://github.com/leanprover/lean4/pull/4941) adds more `LEAN_EXPORT`s for Windows.
* [#4911](https://github.com/leanprover/lean4/pull/4911) improves formatting of CLI help text for the frontend.
* [#4950](https://github.com/leanprover/lean4/pull/4950) improves file reading and writing.
* `readBinFile` and `readFile` now only require two system calls (`stat` + `read`) instead of one `read` per 1024 byte chunk.
* `Handle.getLine` and `Handle.putStr` no longer get tripped up by NUL characters.
* [#4971](https://github.com/leanprover/lean4/pull/4971) handles the SIGBUS signal when detecting stack overflows.
* [#5062](https://github.com/leanprover/lean4/pull/5062) avoids overwriting existing signal handlers, like in [rust-lang/rust#69685](https://github.com/rust-lang/rust/pull/69685).
* [#4860](https://github.com/leanprover/lean4/pull/4860) improves workarounds for building on Windows. Splits `libleanshared` on Windows to avoid symbol limit, removes the `LEAN_EXPORT` denylist workaround, adds missing `LEAN_EXPORT`s.
* [#4952](https://github.com/leanprover/lean4/pull/4952) output panics into Lean's redirected stderr, ensuring panics ARE visible as regular messages in the language server and properly ordered in relation to other messages on the command line.
* [#4963](https://github.com/leanprover/lean4/pull/4963) links LibUV.
### Lake
* [#5030](https://github.com/leanprover/lean4/pull/5030) removes dead code.
* [#4770](https://github.com/leanprover/lean4/pull/4770) adds additional fields to the package configuration which will be used by Reservoir. See the PR description for details.
### DevOps/CI
* [#4914](https://github.com/leanprover/lean4/pull/4914) and [#4937](https://github.com/leanprover/lean4/pull/4937) improve the release checklist.
* [#4925](https://github.com/leanprover/lean4/pull/4925) ignores stale leanpkg tests.
* [#5003](https://github.com/leanprover/lean4/pull/5003) upgrades `actions/cache` in CI.
* [#5010](https://github.com/leanprover/lean4/pull/5010) sets `save-always` in cache actions in CI.
* [#5008](https://github.com/leanprover/lean4/pull/5008) adds more libuv search patterns for the speedcenter.
* [#5009](https://github.com/leanprover/lean4/pull/5009) reduce number of runs in the speedcenter for "fast" benchmarks from 10 to 3.
* [#5014](https://github.com/leanprover/lean4/pull/5014) adjusts lakefile editing to use new `git` syntax in `pr-release` workflow.
* [#5025](https://github.com/leanprover/lean4/pull/5025) has `pr-release` workflow pass `--retry` to `curl`.
* [#5022](https://github.com/leanprover/lean4/pull/5022) builds MacOS Aarch64 release for PRs by default.
* [#5045](https://github.com/leanprover/lean4/pull/5045) adds libuv to the required packages heading in macos docs.
* [#5034](https://github.com/leanprover/lean4/pull/5034) fixes the install name of `libleanshared_1` on macOS.
* [#5051](https://github.com/leanprover/lean4/pull/5051) fixes Windows stage 0.
* [#5052](https://github.com/leanprover/lean4/pull/5052) fixes 32bit stage 0 builds in CI.
* [#5057](https://github.com/leanprover/lean4/pull/5057) avoids rebuilding `leanmanifest` in each build.
* [#5099](https://github.com/leanprover/lean4/pull/5099) makes `restart-on-label` workflow also filter by commit SHA.
* [#4325](https://github.com/leanprover/lean4/pull/4325) adds CaDiCaL.
### Breaking changes
* [LibUV](https://libuv.org/) is now required to build Lean. This change only affects developers who compile Lean themselves instead of obtaining toolchains via `elan`. We have updated the official build instructions with information on how to obtain LibUV on our supported platforms. ([#4963](https://github.com/leanprover/lean4/pull/4963))
* Recursive definitions with a `decreasing_by` clause that begins with `simp_wf` may break. Try removing `simp_wf` or replacing it with `simp`. ([#5016](https://github.com/leanprover/lean4/pull/5016))
* The behavior of `rw [f]` where `f` is a non-recursive function defined by pattern matching changed.
For example, preciously, `rw [Option.map]` would rewrite `Option.map f o` to `match o with … `. Now this rewrite fails because it will use the equational lemmas, and these require constructors – just like for `List.map`.
Remedies:
* Split on `o` before rewriting.
* Use `rw [Option.map.eq_def]`, which rewrites any (saturated) application of `Option.map`.
* Use `set_option backward.eqns.nonrecursive false` when *defining* the function in question.
([#4154](https://github.com/leanprover/lean4/pull/4154))
* The unified handling of equation lemmas for recursive and non-recursive functions can break existing code, as there now can be extra equational lemmas:
* Explicit uses of `f.eq_2` might have to be adjusted if the numbering changed.
* Uses of `rw [f]` or `simp [f]` may no longer apply if they previously matched (and introduced a `match` statement), when the equational lemmas got more fine-grained.
In this case either case analysis on the parameters before rewriting helps, or setting the option `backward.eqns.deepRecursiveSplit false` while *defining* the function.
([#5129](https://github.com/leanprover/lean4/pull/5129), [#5207](https://github.com/leanprover/lean4/pull/5207))
* The `reduceCtorEq` simproc is now optional, and it might need to be included in lists of simp lemmas, like `simp only [reduceCtorEq]`. This simproc is responsible for reducing equalities of constructors. ([#5167](https://github.com/leanprover/lean4/pull/5167))
* `Nat.strongInductionOn` is now `Nat.strongRecOn` and `Nat.caseStrongInductionOn` to `Nat.caseStrongRecOn`. ([#5147](https://github.com/leanprover/lean4/pull/5147))
* The parameters to `Membership.mem` have been swapped, which affects all `Membership` instances. ([#5020](https://github.com/leanprover/lean4/pull/5020))
* The meanings of `List.getElem_drop` and `List.getElem_drop'` have been reversed and the first is now a simp lemma. ([#5210](https://github.com/leanprover/lean4/pull/5210))
* The `Parsec` library has moved from `Lean.Data.Parsec` to `Std.Internal.Parsec`. The `Parsec` type is now more general with a parameter for an iterable. Users parsing strings can migrate to `Parser` in the `Std.Internal.Parsec.String` namespace, which also includes string-focused parsing combinators. ([#4774](https://github.com/leanprover/lean4/pull/4774))
* The `Lean` module has switched from `Lean.HashMap` and `Lean.HashSet` to `Std.HashMap` and `Std.HashSet` ([#4943](https://github.com/leanprover/lean4/pull/4943)). `Lean.HashMap` and `Lean.HashSet` are now deprecated ([#4954](https://github.com/leanprover/lean4/pull/4954)) and will be removed in a future release. Users of `Lean` APIs that interact with hash maps, for example `Lean.Environment.const2ModIdx`, might encounter minor breakage due to the following changes from `Lean.HashMap` to `Std.HashMap`:
* query functions use the term `get` instead of `find`, ([#4943](https://github.com/leanprover/lean4/pull/4943))
* the notation `map[key]` no longer returns an optional value but instead expects a proof that the key is present in the map. The previous behavior is available via the `map[key]?` notation.
```` |
reference-manual/Manual/Releases/v4_0_0-m5.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.0.0-m5 (2022-08-22)" =>
%%%
tag := "release-v4.0.0-m5"
file := "v4.0.0-m5"
%%%
````markdown
This is the fifth milestone release of Lean 4. It contains many improvements and many new features.
We had 1495 commits since the last milestone.
Contributors:
```
885 Leonardo de Moura
310 Sebastian Ullrich
69 E.W.Ayers
66 Wojciech Nawrocki
49 Gabriel Ebner
38 Mario Carneiro
22 larsk21
10 tydeu
6 Ed Ayers
6 Mariana Alanis
4 Chris Lovett
3 Jannis Limperg
2 François G. Dorais
2 Henrik Böving
2 Jakob von Raumer
2 Scott Morrison
2 Siddharth
1 Andrés Goens
1 Arthur Paulino
1 Connor Baker
1 Joscha
1 KaseQuark
1 Lars
1 Mac
1 Marcus Rossel
1 Patrick Massot
1 Siddharth Bhat
1 Timo
1 Vincent de Haan
1 William Blake
1 Yuri de Wit
1 ammkrn
1 asdasd1dsadsa
1 kzvi
```
* Update Lake to v4.0.0. See the [v4.0.0 release notes](https://github.com/leanprover/lake/releases/tag/v4.0.0) for detailed changes.
* Mutual declarations in different namespaces are now supported. Example:
```lean
mutual
def Foo.boo (x : Nat) :=
match x with
| 0 => 1
| x + 1 => 2*Boo.bla x
def Boo.bla (x : Nat) :=
match x with
| 0 => 2
| x+1 => 3*Foo.boo x
end
```
A `namespace` is automatically created for the common prefix. Example:
```lean
mutual
def Tst.Foo.boo (x : Nat) := ...
def Tst.Boo.bla (x : Nat) := ...
end
```
expands to
```lean
namespace Tst
mutual
def Foo.boo (x : Nat) := ...
def Boo.bla (x : Nat) := ...
end
end Tst
```
* Allow users to install their own `deriving` handlers for existing type classes.
See example at [Simple.lean](https://github.com/leanprover/lean4/blob/master/tests/pkg/deriving/UserDeriving/Simple.lean).
* Add tactic `congr (num)?`. See doc string for additional details.
* [Missing doc linter](https://github.com/leanprover/lean4/pull/1390)
* `match`-syntax notation now checks for unused alternatives. See issue [#1371](https://github.com/leanprover/lean4/issues/1371).
* Auto-completion for structure instance fields. Example:
```lean
example : Nat × Nat := {
f -- HERE
}
```
`fst` now appears in the list of auto-completion suggestions.
* Auto-completion for dotted identifier notation. Example:
```lean
example : Nat :=
.su -- HERE
```
`succ` now appears in the list of auto-completion suggestions.
* `nat_lit` is not needed anymore when declaring `OfNat` instances. See issues [#1389](https://github.com/leanprover/lean4/issues/1389) and [#875](https://github.com/leanprover/lean4/issues/875). Example:
```lean
inductive Bit where
| zero
| one
instance inst0 : OfNat Bit 0 where
ofNat := Bit.zero
instance : OfNat Bit 1 where
ofNat := Bit.one
example : Bit := 0
example : Bit := 1
```
* Add `[elabAsElim]` attribute (it is called `elab_as_eliminator` in Lean 3). Motivation: simplify the Mathlib port to Lean 4.
* `Trans` type class now accepts relations in `Type u`. See this [Zulip issue](https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Calc.20mode/near/291214574).
* Accept unescaped keywords as inductive constructor names. Escaping can often be avoided at use sites via dot notation.
```lean
inductive MyExpr
| let : ...
def f : MyExpr → MyExpr
| .let ... => .let ...
```
* Throw an error message at parametric local instances such as `[Nat -> Decidable p]`. The type class resolution procedure
cannot use this kind of local instance because the parameter does not have a forward dependency.
This check can be disabled using `set_option checkBinderAnnotations false`.
* Add option `pp.showLetValues`. When set to `false`, the info view hides the value of `let`-variables in a goal.
By default, it is `true` when visualizing tactic goals, and `false` otherwise.
See [issue #1345](https://github.com/leanprover/lean4/issues/1345) for additional details.
* Add option `warningAsError`. When set to true, warning messages are treated as errors.
* Support dotted notation and named arguments in patterns. Example:
```lean
def getForallBinderType (e : Expr) : Expr :=
match e with
| .forallE (binderType := type) .. => type
| _ => panic! "forall expected"
```
* "jump-to-definition" now works for function names embedded in the following attributes
`@[implementedBy funName]`, `@[tactic parserName]`, `@[termElab parserName]`, `@[commandElab parserName]`,
`@[builtinTactic parserName]`, `@[builtinTermElab parserName]`, and `@[builtinCommandElab parserName]`.
See [issue #1350](https://github.com/leanprover/lean4/issues/1350).
* Improve `MVarId` methods discoverability. See [issue #1346](https://github.com/leanprover/lean4/issues/1346).
We still have to add similar methods for `FVarId`, `LVarId`, `Expr`, and other objects.
Many existing methods have been marked as deprecated.
* Add attribute `[deprecated]` for marking deprecated declarations. Examples:
```lean
def g (x : Nat) := x + 1
-- Whenever `f` is used, a warning message is generated suggesting to use `g` instead.
@[deprecated g]
def f (x : Nat) := x + 1
#check f 0 -- warning: `f` has been deprecated, use `g` instead
-- Whenever `h` is used, a warning message is generated.
@[deprecated]
def h (x : Nat) := x + 1
#check h 0 -- warning: `h` has been deprecated
```
* Add type `LevelMVarId` (and abbreviation `LMVarId`) for universe level metavariable ids.
Motivation: prevent meta-programmers from mixing up universe and expression metavariable ids.
* Improve `calc` term and tactic. See [issue #1342](https://github.com/leanprover/lean4/issues/1342).
* [Relaxed antiquotation parsing](https://github.com/leanprover/lean4/pull/1272) further reduces the need for explicit `$x:p` antiquotation kind annotations.
* Add support for computed fields in inductives. Example:
```lean
inductive Exp
| var (i : Nat)
| app (a b : Exp)
with
@[computedField] hash : Exp → Nat
| .var i => i
| .app a b => a.hash * b.hash + 1
```
The result of the `Exp.hash` function is then stored as an extra "computed" field in the `.var` and `.app` constructors;
`Exp.hash` accesses this field and thus runs in constant time (even on dag-like values).
* Update `a[i]` notation. It is now based on the type class
```lean
class GetElem (cont : Type u) (idx : Type v) (elem : outParam (Type w)) (dom : outParam (cont → idx → Prop)) where
getElem (xs : cont) (i : idx) (h : dom xs i) : Elem
```
The notation `a[i]` is now defined as follows
```lean
macro:max x:term noWs "[" i:term "]" : term => `(getElem $x $i (by get_elem_tactic))
```
The proof that `i` is a valid index is synthesized using the tactic `get_elem_tactic`.
For example, the type `Array α` has the following instances
```lean
instance : GetElem (Array α) Nat α fun xs i => LT.lt i xs.size where ...
instance : GetElem (Array α) USize α fun xs i => LT.lt i.toNat xs.size where ...
```
You can use the notation `a[i]'h` to provide the proof manually.
Two other notations were introduced: `a[i]!` and `a[i]?`, For `a[i]!`, a panic error message is produced at
runtime if `i` is not a valid index. `a[i]?` has type `Option α`, and `a[i]?` evaluates to `none` if the
index `i` is not valid.
The three new notations are defined as follows:
```lean
@[inline] def getElem' [GetElem cont idx elem dom] (xs : cont) (i : idx) (h : dom xs i) : elem :=
getElem xs i h
@[inline] def getElem! [GetElem cont idx elem dom] [Inhabited elem] (xs : cont) (i : idx) [Decidable (dom xs i)] : elem :=
if h : _ then getElem xs i h else panic! "index out of bounds"
@[inline] def getElem? [GetElem cont idx elem dom] (xs : cont) (i : idx) [Decidable (dom xs i)] : Option elem :=
if h : _ then some (getElem xs i h) else none
macro:max x:term noWs "[" i:term "]" noWs "?" : term => `(getElem? $x $i)
macro:max x:term noWs "[" i:term "]" noWs "!" : term => `(getElem! $x $i)
macro x:term noWs "[" i:term "]'" h:term:max : term => `(getElem' $x $i $h)
```
See discussion on [Zulip](https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/String.2EgetOp/near/287855425).
Examples:
```lean
example (a : Array Int) (i : Nat) : Int :=
a[i] -- Error: failed to prove index is valid ...
example (a : Array Int) (i : Nat) (h : i < a.size) : Int :=
a[i] -- Ok
example (a : Array Int) (i : Nat) : Int :=
a[i]! -- Ok
example (a : Array Int) (i : Nat) : Option Int :=
a[i]? -- Ok
example (a : Array Int) (h : a.size = 2) : Int :=
a[0]'(by rw [h]; decide) -- Ok
example (a : Array Int) (h : a.size = 2) : Int :=
have : 0 < a.size := by rw [h]; decide
have : 1 < a.size := by rw [h]; decide
a[0] + a[1] -- Ok
example (a : Array Int) (i : USize) (h : i.toNat < a.size) : Int :=
a[i] -- Ok
```
The `get_elem_tactic` is defined as
```lean
macro "get_elem_tactic" : tactic =>
`(first
| get_elem_tactic_trivial
| fail "failed to prove index is valid, ..."
)
```
The `get_elem_tactic_trivial` auxiliary tactic can be extended using `macro_rules`. By default, it tries `trivial`, `simp_arith`, and a special case for `Fin`. In the future, it will also try `linarith`.
You can extend `get_elem_tactic_trivial` using `my_tactic` as follows
```lean
macro_rules
| `(tactic| get_elem_tactic_trivial) => `(tactic| my_tactic)
```
Note that `Idx`'s type in `GetElem` does not depend on `Cont`. So, you cannot write the instance `instance : GetElem (Array α) (Fin ??) α fun xs i => ...`, but the Lean library comes equipped with the following auxiliary instance:
```lean
instance [GetElem cont Nat elem dom] : GetElem cont (Fin n) elem fun xs i => dom xs i where
getElem xs i h := getElem xs i.1 h
```
and helper tactic
```lean
macro_rules
| `(tactic| get_elem_tactic_trivial) => `(tactic| apply Fin.val_lt_of_le; get_elem_tactic_trivial; done)
```
Example:
```lean
example (a : Array Nat) (i : Fin a.size) :=
a[i] -- Ok
example (a : Array Nat) (h : n ≤ a.size) (i : Fin n) :=
a[i] -- Ok
```
* Better support for qualified names in recursive declarations. The following is now supported:
```lean
namespace Nat
def fact : Nat → Nat
| 0 => 1
| n+1 => (n+1) * Nat.fact n
end Nat
```
* Add support for `CommandElabM` monad at `#eval`. Example:
```lean
import Lean
open Lean Elab Command
#eval do
let id := mkIdent `foo
elabCommand (← `(def $id := 10))
#eval foo -- 10
```
* Try to elaborate `do` notation even if the expected type is not available. We still delay elaboration when the expected type
is not available. This change is particularly useful when writing examples such as
```lean
#eval do
IO.println "hello"
IO.println "world"
```
That is, we don't have to use the idiom `#eval show IO _ from do ...` anymore.
Note that auto monadic lifting is less effective when the expected type is not available.
Monadic polymorphic functions (e.g., `ST.Ref.get`) also require the expected type.
* On Linux, panics now print a backtrace by default, which can be disabled by setting the environment variable `LEAN_BACKTRACE` to `0`.
Other platforms are TBD.
* The `group(·)` `syntax` combinator is now introduced automatically where necessary, such as when using multiple parsers inside `(...)+`.
* Add ["Typed Macros"](https://github.com/leanprover/lean4/pull/1251): syntax trees produced and accepted by syntax antiquotations now remember their syntax kinds, preventing accidental production of ill-formed syntax trees and reducing the need for explicit `:kind` antiquotation annotations. See PR for details.
* Aliases of protected definitions are protected too. Example:
```lean
protected def Nat.double (x : Nat) := 2*x
namespace Ex
export Nat (double) -- Add alias Ex.double for Nat.double
end Ex
open Ex
#check Ex.double -- Ok
#check double -- Error, `Ex.double` is alias for `Nat.double` which is protected
```
* Use `IO.getRandomBytes` to initialize random seed for `IO.rand`. See discussion at [this PR](https://github.com/leanprover/lean4-samples/pull/2).
* Improve dot notation and aliases interaction. See discussion on [Zulip](https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Namespace-based.20overloading.20does.20not.20find.20exports/near/282946185) for additional details.
Example:
```lean
def Set (α : Type) := α → Prop
def Set.union (s₁ s₂ : Set α) : Set α := fun a => s₁ a ∨ s₂ a
def FinSet (n : Nat) := Fin n → Prop
namespace FinSet
export Set (union) -- FinSet.union is now an alias for `Set.union`
end FinSet
example (x y : FinSet 10) : FinSet 10 :=
x.union y -- Works
```
* `ext` and `enter` conv tactics can now go inside let-declarations. Example:
```lean
example (g : Nat → Nat) (y : Nat) (h : let x := y + 1; g (0+x) = x) : g (y + 1) = y + 1 := by
conv at h => enter [x, 1, 1]; rw [Nat.zero_add]
/-
g : Nat → Nat
y : Nat
h : let x := y + 1;
g x = x
⊢ g (y + 1) = y + 1
-/
exact h
```
* Add `zeta` conv tactic to expand let-declarations. Example:
```lean
example (h : let x := y + 1; 0 + x = y) : False := by
conv at h => zeta; rw [Nat.zero_add]
/-
y : Nat
h : y + 1 = y
⊢ False
-/
simp_arith at h
```
* Improve namespace resolution. See issue [#1224](https://github.com/leanprover/lean4/issues/1224). Example:
```lean
import Lean
open Lean Parser Elab
open Tactic -- now opens both `Lean.Parser.Tactic` and `Lean.Elab.Tactic`
```
* Rename `constant` command to `opaque`. See discussion at [Zulip](https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/What.20is.20.60opaque.60.3F/near/284926171).
* Extend `induction` and `cases` syntax: multiple left-hand-sides in a single alternative. This extension is very similar to the one implemented for `match` expressions. Examples:
```lean
inductive Foo where
| mk1 (x : Nat) | mk2 (x : Nat) | mk3
def f (v : Foo) :=
match v with
| .mk1 x => x + 1
| .mk2 x => 2*x + 1
| .mk3 => 1
theorem f_gt_zero : f v > 0 := by
cases v with
| mk1 x | mk2 x => simp_arith! -- New feature used here!
| mk3 => decide
```
* [`let/if` indentation in `do` blocks in now supported.](https://github.com/leanprover/lean4/issues/1120)
* Add unnamed antiquotation `$_` for use in syntax quotation patterns.
* [Add unused variables linter](https://github.com/leanprover/lean4/pull/1159). Feedback welcome!
* Lean now generates an error if the body of a declaration body contains a universe parameter that does not occur in the declaration type, nor is an explicit parameter.
Examples:
```lean
/-
The following declaration now produces an error because `PUnit` is universe polymorphic,
but the universe parameter does not occur in the function type `Nat → Nat`
-/
def f (n : Nat) : Nat :=
let aux (_ : PUnit) : Nat := n + 1
aux ⟨⟩
/-
The following declaration is accepted because the universe parameter was explicitly provided in the
function signature.
-/
def g.{u} (n : Nat) : Nat :=
let aux (_ : PUnit.{u}) : Nat := n + 1
aux ⟨⟩
```
* Add `subst_vars` tactic.
* [Fix `autoParam` in structure fields lost in multiple inheritance.](https://github.com/leanprover/lean4/issues/1158).
* Add `[eliminator]` attribute. It allows users to specify default recursor/eliminators for the `induction` and `cases` tactics.
It is an alternative for the `using` notation. Example:
```lean
@[eliminator] protected def recDiag {motive : Nat → Nat → Sort u}
(zero_zero : motive 0 0)
(succ_zero : (x : Nat) → motive x 0 → motive (x + 1) 0)
(zero_succ : (y : Nat) → motive 0 y → motive 0 (y + 1))
(succ_succ : (x y : Nat) → motive x y → motive (x + 1) (y + 1))
(x y : Nat) : motive x y :=
let rec go : (x y : Nat) → motive x y
| 0, 0 => zero_zero
| x+1, 0 => succ_zero x (go x 0)
| 0, y+1 => zero_succ y (go 0 y)
| x+1, y+1 => succ_succ x y (go x y)
go x y
termination_by go x y => (x, y)
def f (x y : Nat) :=
match x, y with
| 0, 0 => 1
| x+1, 0 => f x 0
| 0, y+1 => f 0 y
| x+1, y+1 => f x y
termination_by f x y => (x, y)
example (x y : Nat) : f x y > 0 := by
induction x, y <;> simp [f, *]
```
* Add support for `casesOn` applications to structural and well-founded recursion modules.
This feature is useful when writing definitions using tactics. Example:
```lean
inductive Foo where
| a | b | c
| pair: Foo × Foo → Foo
def Foo.deq (a b : Foo) : Decidable (a = b) := by
cases a <;> cases b
any_goals apply isFalse Foo.noConfusion
any_goals apply isTrue rfl
case pair a b =>
let (a₁, a₂) := a
let (b₁, b₂) := b
exact match deq a₁ b₁, deq a₂ b₂ with
| isTrue h₁, isTrue h₂ => isTrue (by rw [h₁,h₂])
| isFalse h₁, _ => isFalse (fun h => by cases h; cases (h₁ rfl))
| _, isFalse h₂ => isFalse (fun h => by cases h; cases (h₂ rfl))
```
* `Option` is again a monad. The auxiliary type `OptionM` has been removed. See [Zulip thread](https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Do.20we.20still.20need.20OptionM.3F/near/279761084).
* Improve `split` tactic. It used to fail on `match` expressions of the form `match h : e with ...` where `e` is not a free variable.
The failure used to occur during generalization.
* New encoding for `match`-expressions that use the `h :` notation for discriminants. The information is not lost during delaboration,
and it is the foundation for a better `split` tactic. at delaboration time. Example:
```lean
#print Nat.decEq
/-
protected def Nat.decEq : (n m : Nat) → Decidable (n = m) :=
fun n m =>
match h : Nat.beq n m with
| true => isTrue (_ : n = m)
| false => isFalse (_ : ¬n = m)
-/
```
* `exists` tactic is now takes a comma separated list of terms.
* Add `dsimp` and `dsimp!` tactics. They guarantee the result term is definitionally equal, and only apply
`rfl`-theorems.
* Fix binder information for `match` patterns that use definitions tagged with `[matchPattern]` (e.g., `Nat.add`).
We now have proper binder information for the variable `y` in the following example.
```lean
def f (x : Nat) : Nat :=
match x with
| 0 => 1
| y + 1 => y
```
* (Fix) the default value for structure fields may now depend on the structure parameters. Example:
```lean
structure Something (i: Nat) where
n1: Nat := 1
n2: Nat := 1 + i
def s : Something 10 := {}
example : s.n2 = 11 := rfl
```
* Apply `rfl` theorems at the `dsimp` auxiliary method used by `simp`. `dsimp` can be used anywhere in an expression
because it preserves definitional equality.
* Refine auto bound implicit feature. It does not consider anymore unbound variables that have the same
name of a declaration being defined. Example:
```lean
def f : f → Bool := -- Error at second `f`
fun _ => true
inductive Foo : List Foo → Type -- Error at second `Foo`
| x : Foo []
```
Before this refinement, the declarations above would be accepted and the
second `f` and `Foo` would be treated as auto implicit variables. That is,
`f : {f : Sort u} → f → Bool`, and
`Foo : {Foo : Type u} → List Foo → Type`.
* Fix syntax highlighting for recursive declarations. Example
```lean
inductive List (α : Type u) where
| nil : List α -- `List` is not highlighted as a variable anymore
| cons (head : α) (tail : List α) : List α
def List.map (f : α → β) : List α → List β
| [] => []
| a::as => f a :: map f as -- `map` is not highlighted as a variable anymore
```
* Add `autoUnfold` option to `Lean.Meta.Simp.Config`, and the following macros
- `simp!` for `simp (config := { autoUnfold := true })`
- `simp_arith!` for `simp (config := { autoUnfold := true, arith := true })`
- `simp_all!` for `simp_all (config := { autoUnfold := true })`
- `simp_all_arith!` for `simp_all (config := { autoUnfold := true, arith := true })`
When the `autoUnfold` is set to true, `simp` tries to unfold the following kinds of definition
- Recursive definitions defined by structural recursion.
- Non-recursive definitions where the body is a `match`-expression. This
kind of definition is only unfolded if the `match` can be reduced.
Example:
```lean
def append (as bs : List α) : List α :=
match as with
| [] => bs
| a :: as => a :: append as bs
theorem append_nil (as : List α) : append as [] = as := by
induction as <;> simp_all!
theorem append_assoc (as bs cs : List α) : append (append as bs) cs = append as (append bs cs) := by
induction as <;> simp_all!
```
* Add `save` tactic for creating checkpoints more conveniently. Example:
```lean
example : <some-proposition> := by
tac_1
tac_2
save
tac_3
...
```
is equivalent to
```lean
example : <some-proposition> := by
checkpoint
tac_1
tac_2
tac_3
...
```
* Remove support for `{}` annotation from inductive datatype constructors. This annotation was barely used, and we can control the binder information for parameter bindings using the new inductive family indices to parameter promotion. Example: the following declaration using `{}`
```lean
inductive LE' (n : Nat) : Nat → Prop where
| refl {} : LE' n n -- Want `n` to be explicit
| succ : LE' n m → LE' n (m+1)
```
can now be written as
```lean
inductive LE' : Nat → Nat → Prop where
| refl (n : Nat) : LE' n n
| succ : LE' n m → LE' n (m+1)
```
In both cases, the inductive family has one parameter and one index.
Recall that the actual number of parameters can be retrieved using the command `#print`.
* Remove support for `{}` annotation in the `structure` command.
* Several improvements to LSP server. Examples: "jump to definition" in mutually recursive sections, fixed incorrect hover information in "match"-expression patterns, "jump to definition" for pattern variables, fixed auto-completion in function headers, etc.
* In `macro ... xs:p* ...` and similar macro bindings of combinators, `xs` now has the correct type `Array Syntax`
* Identifiers in syntax patterns now ignore macro scopes during matching.
* Improve binder names for constructor auto implicit parameters. Example, given the inductive datatype
```lean
inductive Member : α → List α → Type u
| head : Member a (a::as)
| tail : Member a bs → Member a (b::bs)
```
before:
```lean
#check @Member.head
-- @Member.head : {x : Type u_1} → {a : x} → {as : List x} → Member a (a :: as)
```
now:
```lean
#check @Member.head
-- @Member.head : {α : Type u_1} → {a : α} → {as : List α} → Member a (a :: as)
```
* Improve error message when constructor parameter universe level is too big.
* Add support for `for h : i in [start:stop] do .. ` where `h : i ∈ [start:stop]`. This feature is useful for proving
termination of functions such as:
```lean
inductive Expr where
| app (f : String) (args : Array Expr)
def Expr.size (e : Expr) : Nat := Id.run do
match e with
| app f args =>
let mut sz := 1
for h : i in [: args.size] do
-- h.upper : i < args.size
sz := sz + size (args.get ⟨i, h.upper⟩)
return sz
```
* Add tactic `case'`. It is similar to `case`, but does not admit the goal on failure.
For example, the new tactic is useful when writing tactic scripts where we need to use `case'`
at `first | ... | ...`, and we want to take the next alternative when `case'` fails.
* Add tactic macro
```lean
macro "stop" s:tacticSeq : tactic => `(repeat sorry)
```
See discussion on [Zulip](https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Partial.20evaluation.20of.20a.20file).
* When displaying goals, we do not display inaccessible proposition names
if they do not have forward dependencies. We still display their types.
For example, the goal
```lean
case node.inl.node
β : Type u_1
b : BinTree β
k : Nat
v : β
left : Tree β
key : Nat
value : β
right : Tree β
ihl : BST left → Tree.find? (Tree.insert left k v) k = some v
ihr : BST right → Tree.find? (Tree.insert right k v) k = some v
h✝ : k < key
a✝³ : BST left
a✝² : ForallTree (fun k v => k < key) left
a✝¹ : BST right
a✝ : ForallTree (fun k v => key < k) right
⊢ BST left
```
is now displayed as
```lean
case node.inl.node
β : Type u_1
b : BinTree β
k : Nat
v : β
left : Tree β
key : Nat
value : β
right : Tree β
ihl : BST left → Tree.find? (Tree.insert left k v) k = some v
ihr : BST right → Tree.find? (Tree.insert right k v) k = some v
: k < key
: BST left
: ForallTree (fun k v => k < key) left
: BST right
: ForallTree (fun k v => key < k) right
⊢ BST left
```
* The hypothesis name is now optional in the `by_cases` tactic.
* [Fix inconsistency between `syntax` and kind names](https://github.com/leanprover/lean4/issues/1090).
The node kinds `numLit`, `charLit`, `nameLit`, `strLit`, and `scientificLit` are now called
`num`, `char`, `name`, `str`, and `scientific` respectively. Example: we now write
```lean
macro_rules | `($n:num) => `("hello")
```
instead of
```lean
macro_rules | `($n:numLit) => `("hello")
```
* (Experimental) New `checkpoint <tactic-seq>` tactic for big interactive proofs.
* Rename tactic `nativeDecide` => `native_decide`.
* Antiquotations are now accepted in any syntax. The `incQuotDepth` `syntax` parser is therefore obsolete and has been removed.
* Renamed tactic `nativeDecide` => `native_decide`.
* "Cleanup" local context before elaborating a `match` alternative right-hand-side. Examples:
```lean
example (x : Nat) : Nat :=
match g x with
| (a, b) => _ -- Local context does not contain the auxiliary `_discr := g x` anymore
example (x : Nat × Nat) (h : x.1 > 0) : f x > 0 := by
match x with
| (a, b) => _ -- Local context does not contain the `h✝ : x.fst > 0` anymore
```
* Improve `let`-pattern (and `have`-pattern) macro expansion. In the following example,
```lean
example (x : Nat × Nat) : f x > 0 := by
let (a, b) := x
done
```
The resulting goal is now `... |- f (a, b) > 0` instead of `... |- f x > 0`.
* Add cross-compiled [aarch64 Linux](https://github.com/leanprover/lean4/pull/1066) and [aarch64 macOS](https://github.com/leanprover/lean4/pull/1076) releases.
* [Add tutorial-like examples to our documentation](https://github.com/leanprover/lean4/tree/master/doc/examples), rendered using LeanInk+Alectryon.
```` |
reference-manual/Manual/Releases/v4_28_0.lean | import VersoManual
import Manual.Meta
import Manual.Meta.Markdown
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
#doc (Manual) "Lean 4.28.0 (2026-02-17)" =>
%%%
tag := "release-v4.28.0"
file := "v4.28.0"
%%%
For this release, 309 changes landed. In addition to the 94 feature additions and 65 fixes listed below there were 19 refactoring changes, 8 documentation improvements, 34 performance improvements, 12 improvements to the test suite and 77 other changes.
# Language
* [#11553](https://github.com/leanprover/lean4/pull/11553) makes `simpH`, used in the match equation generator, produce a
proof term. This is in preparation for a bigger refactoring in #11512.
* [#11666](https://github.com/leanprover/lean4/pull/11666) makes sure that when a matcher is compiled using a sparse cases,
that equation generation also uses sparse cases to split.
This fixes #11665.
* [#11669](https://github.com/leanprover/lean4/pull/11669) makes sure that proofs about `ctorIdx` passed to `grind` pass
the `debug.grind` checks, despite reducing a `semireducible` definition.
* [#11670](https://github.com/leanprover/lean4/pull/11670) fixes the `grind` support for `Nat.ctorIdx`. Nat constructors
appear in `grind` as offsets or literals, and not as a node marked
`.constr`, so handle that case as well.
* [#11673](https://github.com/leanprover/lean4/pull/11673) fixes an issue where a `by` in the public scope could create an
auxiliary theorem for the proof whose type does not match the expected
type in the public scope.
* [#11696](https://github.com/leanprover/lean4/pull/11696) improves `match` generalization such that it abstracts
metavariables in types of local variables and in the result type of the
match over the match discriminants. Previously, a metavariable in the
result type would silently default to the behavior of `generalizing :=
false`, and a metavariable in the type of a free variable would lead to
an error (#8099). Example of a `match` that elaborates now but
previously wouldn't:
```
example (a : Nat) (ha : a = 37) :=
(match a with | 42 => by contradiction | n => n) = 37
```
This is because the result type of the `match` is a metavariable that
was not abstracted over `a` and hence generalization failed; the result
is that `contradiction` cannot pick up the proof `ha : 42 = 37`.
The old behavior can be recovered by passing `(generalizing := false)`
to the `match`.
* [#11698](https://github.com/leanprover/lean4/pull/11698) makes `mvcgen` early return after simplifying discriminants,
avoiding a rewrite on an ill-formed `match`.
* [#11714](https://github.com/leanprover/lean4/pull/11714) gives a focused error message when a user tries to name an
example, and tweaks error messages for attempts to define multiple
opaque names at once.
* [#11718](https://github.com/leanprover/lean4/pull/11718) adds a test for issue #11655, which it seems was fixed by #11695
* [#11721](https://github.com/leanprover/lean4/pull/11721) improves the performance of the functions for generating
congruence lemmas, used by `simp`
and a few other components.
* [#11726](https://github.com/leanprover/lean4/pull/11726) upstreams dependency-management commands from Mathlib:
- `#import_path Foo` prints the transitive import chain that brings
`Foo` into scope
- `assert_not_exists Foo` errors if declaration `Foo` exists (for
dependency management)
- `assert_not_imported Module` warns if `Module` is transitively
imported
- `#check_assertions` verifies all pending assertions are eventually
satisfied
* [#11731](https://github.com/leanprover/lean4/pull/11731) makes the cache in expr_eq_fn use mimalloc for a small
performance win across the board.
* [#11748](https://github.com/leanprover/lean4/pull/11748) fixes an edge case where some tactics did not allow access to
private declarations inside private proofs under the module system
* [#11756](https://github.com/leanprover/lean4/pull/11756) fixes an issue where `grind` fails when trying to unfold a
definition by pattern matching imported by `import all` (or from a
non-`module`).
* [#11780](https://github.com/leanprover/lean4/pull/11780) ensures that pretty-printing of unification hints inserts a
space after |- resp. ⊢.
* [#11871](https://github.com/leanprover/lean4/pull/11871) makes `mvcgen with tac` fail if `tac` fails on one of the VCs,
just as `induction ... with tac` fails if `tac` fails on one of the
goals. The old behavior can be recovered by writing `mvcgen with try
tac` instead.
* [#11875](https://github.com/leanprover/lean4/pull/11875) adds the directory `Meta/DiscrTree` and reorganizes the code
into different files. Motivation: we are going to have new functions for
retrieving simplification theorems for the new structural simplifier.
* [#11882](https://github.com/leanprover/lean4/pull/11882) adds a guard to `TagDeclarationExtension.tag` to check if the
declaration name is anonymous and return early if so. This prevents a
panic that could occur when modifiers like `meta` or `noncomputable` are
used in combination with syntax errors.
* [#11896](https://github.com/leanprover/lean4/pull/11896) fixes a panic that occurred when a theorem had a docstring on an
auxiliary definition within a `where` clause.
* [#11908](https://github.com/leanprover/lean4/pull/11908) adds two features to the message testing commands:
a new `#guard_panic` command that succeeds if the nested command produces
a panic message (useful for testing commands expected to panic), and a
`substring := true` option for `#guard_msgs` that checks if the docstring
appears as a substring of the output rather than requiring an exact match.
* [#11919](https://github.com/leanprover/lean4/pull/11919) improves the error message when `initialize` (or `opaque`) fails
to find an `Inhabited` or `Nonempty` instance.
* [#11926](https://github.com/leanprover/lean4/pull/11926) adds an `unsafe` modifier to an existing helper function user
`unsafeEIO`, and also leaves the function private.
* [#11933](https://github.com/leanprover/lean4/pull/11933) adds utility functions for managing the message log during
tactic
evaluation, and refactors existing code to use them.
* [#11940](https://github.com/leanprover/lean4/pull/11940) fixes module system visibiltity issues when trying to declare a
public inductive inside a mutual block.
* [#11941](https://github.com/leanprover/lean4/pull/11941) reverts #11696.
* [#11991](https://github.com/leanprover/lean4/pull/11991) fixes `declare_syntax_cat` declaring a local category leading to
import errors when used in `module` without `public section`.
* [#12026](https://github.com/leanprover/lean4/pull/12026) fixes an issue where attributes like `@[irreducible]` would not
be allowed under the module system unless combined with `@[exposed]`,
but the former may be helpful without the latter to ensure downstream
non-`module`s are also affected.
* [#12045](https://github.com/leanprover/lean4/pull/12045) disables the `import all` check across package boundaries. Now
any module can `import all` any other module.
* [#12048](https://github.com/leanprover/lean4/pull/12048) fixes a bug where `mvcgen` loses VCs, resulting in unassigned
metavariables. It is fixed by making all emitted VCs synthetic opaque.
* [#12122](https://github.com/leanprover/lean4/pull/12122) adds support for Verso docstrings in `where` clauses.
* [#12148](https://github.com/leanprover/lean4/pull/12148) reverts #12000, which introduced a regression where `simp`
incorrectly rejects valid rewrites for perm lemmas.
# Library
* [#11257](https://github.com/leanprover/lean4/pull/11257) adds the definition of `BitVec.cpop`, which relies on the more
general `BitVec.cpopNatRec`, and build some theory around it. The name
`cpop` aligns with the [RISCV ISA
nomenclature](https://msyksphinz-self.github.io/riscv-isadoc/#_cpop).
* [#11438](https://github.com/leanprover/lean4/pull/11438) renames the namespace `Std.Range` to `Std.Legacy.Range`. Instead
of using `Std.Range` and `[a:b]` notation, the new range type `Std.Rco`
and its corresponding `a...b` notation should be used. There are also
other ranges with open/closed/infinite boundary shapes in
`Std.Data.Range.Polymorphic` and the new range notation also works for
`Int`, `Int8`, `UInt8`, `Fin` etc.
* [#11446](https://github.com/leanprover/lean4/pull/11446) moves many constants of the iterator API from `Std.Iterators` to
the `Std` namespace in order to make them more convenient to use. These
constants include, but are not limited to, `Iter`, `IterM` and
`IteratorLoop`. This is a breaking change. If something breaks, try
adding `open Std` in order to make these constants available again. If
some constants in the `Std.Iterators` namespace cannot be found, they
can be found directly in `Std` now.
* [#11499](https://github.com/leanprover/lean4/pull/11499) adds the `Context` type for cancellation with context
propagation. It works by storing a tree of forks of the main context,
providing a way to control cancellation.
* [#11532](https://github.com/leanprover/lean4/pull/11532) adds the new operation `MonadAttach.attach` that attaches a
proof that a postcondition holds to the return value of a monadic
operation. Most non-CPS monads in the standard library support this
operation in a nontrivial way. The PR also changes the `filterMapM`,
`mapM` and `flatMapM` combinators so that they attach postconditions to
the user-provided monadic functions passed to them. This makes it
possible to prove termination for some of these for which it wasn't
possible before. Additionally, the PR adds many missing lemmas about
`filterMap(M)` and `map(M)` that were needed in the course of this PR.
* [#11693](https://github.com/leanprover/lean4/pull/11693) makes it possible to verify loops over iterators. It provides
MPL spec lemmas about `for` loops over pure iterators. It also provides
spec lemmas that rewrite loops over `mapM`, `filterMapM` or `filterM`
iterator combinators into loops over their base iterator.
* [#11705](https://github.com/leanprover/lean4/pull/11705) provides many lemmas about `Int` ranges, in analogy to those
about `Nat` ranges. A few necessary basic `Int` lemmas are added. The PR
also removes `simp` annotations on `Rcc.toList_eq_toList_rco`,
`Nat.toList_rcc_eq_toList_rco` and consorts.
* [#11706](https://github.com/leanprover/lean4/pull/11706) removes the `IteratorCollect` type class and hereby simplifies
the iterator API. Its limited advantages did not justify the complexity
cost.
* [#11710](https://github.com/leanprover/lean4/pull/11710) extends the get-elem tactic for ranges so that it supports
subarrays. Example:
```
example {a : Array Nat} (h : a.size = 28) : Id Unit := do
let mut x := 0
for h : i in *...(3 : Nat) do
x := a[1...4][i]
```
* [#11716](https://github.com/leanprover/lean4/pull/11716) adds more MPL spec lemmas for all combinations of `for` loops,
`fold(M)` and the `filter(M)/filterMap(M)/map(M)` iterator combinators.
These kinds of loops over these combinators (e.g. `it.mapM`) are first
transformed into loops over their base iterators (`it`), and if the base
iterator is of type `Iter _` or `IterM Id _`, then another spec lemma
exists for proving Hoare triples about it using an invariant and the
underlying list (`it.toList`). The PR also fixes a bug that MPL always
assigns the default priority to spec lemmas if `Std.Tactic.Do.Syntax` is
not imported and a bug that low-priority lemmas are preferred about
high-priority ones.
* [#11724](https://github.com/leanprover/lean4/pull/11724) adds more `event_loop_lock`s to fix race conditions.
* [#11728](https://github.com/leanprover/lean4/pull/11728) introduces some additional lemmas around `BitVec.extractLsb'`
and `BitVec.extractLsb`.
* [#11760](https://github.com/leanprover/lean4/pull/11760) allows `grind` to use `List.eq_nil_of_length_eq_zero` (and
`Array.eq_empty_of_size_eq_zero`), but only when it has already proved
the length is zero.
* [#11761](https://github.com/leanprover/lean4/pull/11761) adds some `grind_pattern` `guard` conditions to potentially
expensive theorems.
* [#11762](https://github.com/leanprover/lean4/pull/11762) moves the grind pattern from `Sublist.eq_of_length` to the
slightly more general `Sublist.eq_of_length_le`, and adds a grind
pattern guard so it only activates if we have a proof of the hypothesis.
* [#11767](https://github.com/leanprover/lean4/pull/11767) introduces two induction principles for bitvectors, based on the
concat and cons operations. We show how this principle can be useful to
reason about bitvectors by refactoring two population count lemmas
(`cpopNatRec_zero_le` and `toNat_cpop_append`) and introducing a new
lemma (`toNat_cpop_not`).
To use the induction principle we also move `cpopNatRec_cons_of_le` and
`cpopNatRec_cons_of_lt` earlier in the popcount section (they are the
building blocks enabling us to take advantage of the new induction
principle).
* [#11772](https://github.com/leanprover/lean4/pull/11772) fixes a bug in the optimized and unsafe implementation of
`Array.foldlM`.
* [#11774](https://github.com/leanprover/lean4/pull/11774) fixes a mismatch between the behavior of `foldlM` and
`foldlMUnsafe` in the three array
types. This mismatch is only exposed when manually specifying a `stop`
value greater than the size
of the array and only exploitable through `native_decide`.
* [#11779](https://github.com/leanprover/lean4/pull/11779) fixes an oversight in the initial #11772 PR.
* [#11784](https://github.com/leanprover/lean4/pull/11784) just adds an optional start position argument to
`PersistentArray.forM`
* [#11789](https://github.com/leanprover/lean4/pull/11789) makes the `FinitenessRelation` structure, which is helpful when
proving the finiteness of iterators, part of the public API. Previously,
it was marked internal and experimental.
* [#11794](https://github.com/leanprover/lean4/pull/11794) implements the function `getMaxFVar?` for implementing `SymM`
primitives.
* [#11834](https://github.com/leanprover/lean4/pull/11834) adds `num?` parameter to `mkPatternFromTheorem` to control how
many leading quantifiers are stripped when creating a pattern. This
enables matching theorems where only some quantifiers should be
converted to pattern variables.
* [#11848](https://github.com/leanprover/lean4/pull/11848) fixes a bug at `Name.beq` reported by
gasstationcodemanager@gmail.com
* [#11852](https://github.com/leanprover/lean4/pull/11852) changes the definition of the iterator combinators `takeWhileM`
and `dropWhileM` so that they use `MonadAttach`. This is only relevant
in rare cases, but makes it sometimes possible to prove such combinators
finite when the finiteness depends on properties of the monadic
predicate.
* [#11901](https://github.com/leanprover/lean4/pull/11901) adds `gcd_left_comm` lemmas for both `Nat` and `Int`:
- `Nat.gcd_left_comm`: `gcd m (gcd n k) = gcd n (gcd m k)`
- `Int.gcd_left_comm`: `gcd a (gcd b c) = gcd b (gcd a c)`
* [#11905](https://github.com/leanprover/lean4/pull/11905) provides a `Decidable` instance for `Nat.isPowerOfTwo` based on
the formula `(n ≠ 0) ∧ (n &&& (n - 1)) = 0`.
* [#11907](https://github.com/leanprover/lean4/pull/11907) implements `PersistentHashMap.findKeyD` and
`PersistentHashSet.findD`. The motivation is avoid two memory
allocations (`Prod.mk` and `Option.some`) when the collections contains
the key.
* [#11945](https://github.com/leanprover/lean4/pull/11945) changes the runtime implementation of the `Decidable (xs = #[])`
and `Decidable (#[] = xs)` instances to use `Array.isEmpty`. Previously,
`decide (xs = #[])` would first convert `xs` into a list and then
compare it against `List.nil`.
* [#11979](https://github.com/leanprover/lean4/pull/11979) adds `suggest_for` annotations such that `Int*.toNatClamp` is
suggested for `Int*.toNat`.
* [#11989](https://github.com/leanprover/lean4/pull/11989) removes a leftover `example` from
`src/Std/Tactic/BVDecide/Bitblast/BVExpr/Circuit/Lemmas/Operations/Clz.lean`.
* [#11993](https://github.com/leanprover/lean4/pull/11993) adds `grind` annotations to the lemmas about `Subarray` and
`ListSlice`.
* [#12058](https://github.com/leanprover/lean4/pull/12058) implements iteration over ranges for `Fin` and `Char`.
* [#12139](https://github.com/leanprover/lean4/pull/12139) adds `«term_⁻¹»` to the `recommended_spelling` for `inv`,
matching
the pattern used by all other operators which include both the function
and the syntax in their spelling lists.
# Tactics
* [#11664](https://github.com/leanprover/lean4/pull/11664) adds support for `Nat.cast` in `grind linarith`. It now uses
`Grind.OrderedRing.natCast_nonneg`. Example:
```
open Lean Grind Std
attribute [instance] Semiring.natCast
variable [Lean.Grind.CommRing R] [LE R] [LT R] [LawfulOrderLT R] [IsLinearOrder R] [OrderedRing R]
example (a : Nat) : 0 ≤ (a : R) := by grind
example (a b : Nat) : 0 ≤ (a : R) + (b : R) := by grind
```
* [#11677](https://github.com/leanprover/lean4/pull/11677) adds basic support for equality propagation in `grind linarith`
for the `IntModule` case. This covers only the basic case. See note in
the code.
We remark this feature is irrelevant for `CommRing` since `grind ring`
already has much better support for equality propagation.
* [#11678](https://github.com/leanprover/lean4/pull/11678) fixes a bug in `registerNonlinearOccsAt` used to implement
`grind lia`. This issue was originally reported at:
https://leanprover.zulipchat.com/#narrow/channel/113489-new-members/topic/Weirdness.20with.20cutsat/near/562099515
* [#11691](https://github.com/leanprover/lean4/pull/11691) fixes `grind` to support dot notation on declarations in the
lemma list.
* [#11700](https://github.com/leanprover/lean4/pull/11700) adds a link to the `grind` docstring. The link directs users to
the section describing `grind` in the reference manual.
* [#11712](https://github.com/leanprover/lean4/pull/11712) avoids invoking TC synthesis and other inference mechanisms in
the simprocs of `bv_decide`. This can give significant speedups on
problems that pressure these simprocs.
* [#11717](https://github.com/leanprover/lean4/pull/11717) improves the performance of `bv_decide`'s rewriter on large
problems.
* [#11736](https://github.com/leanprover/lean4/pull/11736) fixes an issue where `exact?` would not suggest private
declarations defined in the current module.
* [#11739](https://github.com/leanprover/lean4/pull/11739) turns even more commonly used `bv_decide` theorems that require
unification into fast simprocs
using syntactic equality. This pushes the overall performance across
sage/app7 to <= 1min10s for
every problem.
* [#11749](https://github.com/leanprover/lean4/pull/11749) fixes a bug in the function `selectNextSplit?` used in `grind`.
It was incorrectly computing the generation of each candidate.
* [#11758](https://github.com/leanprover/lean4/pull/11758) improves support for nonstandard `Int`/`Nat` instances in
`grind` and `simp +arith`.
* [#11765](https://github.com/leanprover/lean4/pull/11765) implements user-defined `grind` attributes. They are useful for
users that want to implement tactics using the `grind` infrastructure
(e.g., `progress*` in Aeneas). New `grind` attributes are declared using
the command
```
register_grind_attr my_grind
```
The command is similar to `register_simp_attr`. Recall that similar to
`register_simp_attr`, the new attribute cannot be used in the same file
it is declared.
```
opaque f : Nat → Nat
opaque g : Nat → Nat
@[my_grind] theorem fax : f (f x) = f x := sorry
example theorem fax2 : f (f (f x)) = f x := by
fail_if_success grind
grind [my_grind]
```
* [#11769](https://github.com/leanprover/lean4/pull/11769) uses the new support for user-defined `grind` attributes to
implement the default `[grind]` attribute.
* [#11770](https://github.com/leanprover/lean4/pull/11770) implements support for user-defined attributes at
`grind_pattern`. After declaring a `grind` attribute with
`register_grind_attr my_grind`, one can write:
```
grind_pattern [my_grind] fg => g (f x)
```
* [#11776](https://github.com/leanprover/lean4/pull/11776) adds the attributes `[grind norm]` and `[grind unfold]` for
controlling the `grind` normalizer/preprocessor.
* [#11785](https://github.com/leanprover/lean4/pull/11785) disables closed term extraction in the reflection terms used by
`bv_decide`. These terms do
not profit at all from closed term extraction but can in practice cause
thousands of new closed term
declarations which in turn slows down the compiler.
* [#11787](https://github.com/leanprover/lean4/pull/11787) adds support for incrementally processing local declarations in
`grind`. Instead of processing all hypotheses at once during goal
initialization, `grind` now tracks which local declarations have been
processed via `Goal.nextDeclIdx` and provides APIs to process new
hypotheses incrementally.
This feature will be used by the new `SymM` monad for efficient symbolic
simulation.
* [#11788](https://github.com/leanprover/lean4/pull/11788) introduces `SymM`, a new monad for implementing symbolic
simulators (e.g., verification condition generators) in Lean. The monad
addresses performance issues found in symbolic simulators built on top
of user-facing tactics like `apply` and `intros`.
* [#11792](https://github.com/leanprover/lean4/pull/11792) adds `isDebugEnabled` for checking whether `grind.debug` is set
to `true` when `grind` was initialized.
* [#11793](https://github.com/leanprover/lean4/pull/11793) adds functions for creating maximally shared terms from
maximally shared terms. It is more efficient than creating an expression
and then invoking `shareCommon`. We are going to use these functions for
implementing the symbolic simulation primitives.
* [#11797](https://github.com/leanprover/lean4/pull/11797) simplifies `AlphaShareCommon.State` by separating the persistent
and transient parts of the state.
* [#11800](https://github.com/leanprover/lean4/pull/11800) adds the function `Sym.replaceS`, which is similar to
`replace_fn` available in the kernel but assumes the input is maximally
shared and ensures the output is also maximally shared. The PR also
generalizes the `AlphaShareBuilder` API.
* [#11802](https://github.com/leanprover/lean4/pull/11802) adds the function `Sym.instantiateS` and its variants, which are
similar to `Expr.instantiate` but assumes the input is maximally shared
and ensures the output is also maximally shared.
* [#11803](https://github.com/leanprover/lean4/pull/11803) implements `intro` (and its variants) for `SymM`. These versions
do not use reduction or infer types, and ensure expressions are
maximally shared.
* [#11806](https://github.com/leanprover/lean4/pull/11806) refactors the `Goal` type used in `grind`. The new
representation allows multiple goals with different metavariables to
share the same `GoalState`. This is useful for automation such as
symbolic simulator, where applying theorems create multiple goals that
inherit the same E-graph, congruence closure and solvers state, and
other accumulated facts.
* [#11810](https://github.com/leanprover/lean4/pull/11810) adds a new transparency mode `.none` in which no definitions are
unfolded.
* [#11813](https://github.com/leanprover/lean4/pull/11813) introduces a fast pattern matching and unification module for
the symbolic simulation framework (`Sym`). The design prioritizes
performance by using a two-phase approach:
**Phase 1 (Syntactic Matching)**
- Patterns use de Bruijn indices for expression variables and renamed
level params (`_uvar.0`, `_uvar.1`, ...) for universe variables
- Matching is purely structural after reducible definitions are unfolded
during preprocessing
- Universe levels treat `max` and `imax` as uninterpreted functions (no
AC reasoning)
- Binders and term metavariables are deferred to Phase 2
**Phase 2 (Pending Constraints)**
- Handles binders (Miller patterns) and metavariable unification
- Converts remaining de Bruijn variables to metavariables
- Falls back to `isDefEq` when necessary
* [#11814](https://github.com/leanprover/lean4/pull/11814) implements `instantiateRevBetaS`, which is similar to
`instantiateRevS` but beta-reduces nested applications whose function
becomes a lambda after substitution.
* [#11815](https://github.com/leanprover/lean4/pull/11815) optimizes pattern matching by skipping proof and instance
arguments during Phase 1 (syntactic matching).
* [#11819](https://github.com/leanprover/lean4/pull/11819) adds some basic infrastructure for a structural (and cheaper)
`isDefEq` predicate for pattern matching and unification in `Sym`.
* [#11820](https://github.com/leanprover/lean4/pull/11820) adds optimized `abstractFVars` and `abstractFVarsRange` for
converting free variables to de Bruijn indices during pattern
matching/unification.
* [#11824](https://github.com/leanprover/lean4/pull/11824) implements `isDefEqS`, a lightweight structural definitional
equality for the symbolic simulation framework. Unlike the full
`isDefEq`, it avoids expensive operations while still supporting Miller
pattern unification.
* [#11825](https://github.com/leanprover/lean4/pull/11825) completes the new pattern matching and unification procedures
for the symbolic simulation framework using a two-phase approach.
* [#11833](https://github.com/leanprover/lean4/pull/11833) fixes a few typos, adds missing docstrings, and adds a (simple)
missing optimization.
* [#11837](https://github.com/leanprover/lean4/pull/11837) adds `BackwardRule` for efficient goal transformation via
backward chaining in `SymM`.
* [#11847](https://github.com/leanprover/lean4/pull/11847) adds a new `solverMode` field to `bv_decide`'s configuration,
allowing users to configure
the SAT solver for different kinds of workloads.
* [#11849](https://github.com/leanprover/lean4/pull/11849) fixes missing zetaDelta support at the pattern
matching/unification procedure in the new Sym framework.
* [#11850](https://github.com/leanprover/lean4/pull/11850) fixes a bug in the new pattern matching procedure for the Sym
framework. It was not correctly handling assigned metavariables during
pattern matching.
* [#11851](https://github.com/leanprover/lean4/pull/11851) fixes `Sym/Intro.lean` support for `have`-declarations.
* [#11856](https://github.com/leanprover/lean4/pull/11856) adds the basic infrastructure for the structural simplifier used
by the symbolic simulation (`Sym`) framework.
* [#11857](https://github.com/leanprover/lean4/pull/11857) adds an incremental variant of `shareCommon` for expressions
constructed from already-shared subterms. We use this when an expression
`e` was produced by a Lean API (e.g., `inferType`, `mkApp4`) that does
not preserve maximal sharing, but the inputs to that API were already
maximally shared. Unlike `shareCommon`, this function does not use a
local `Std.HashMap ExprPtr Expr` to track visited nodes. This is more
efficient when the number of new (unshared) nodes is small, which is the
common case when wrapping API calls that build a few constructor nodes
around shared inputs.
* [#11858](https://github.com/leanprover/lean4/pull/11858) changes `bv_decide`'s heuristic for what kinds of structures to
split on to also allow
splitting on structures where the fields have dependently typed widths.
For example:
```
structure Byte (w : Nat) where
/-- A two's complement integer value of width `w`. -/
val : BitVec w
/-- A per-bit poison mask of width `w`. -/
poison : BitVec w
```
This is to allow handling situations such as `(x : Byte 8)` where the
width becomes concrete after
splitting is done.
* [#11860](https://github.com/leanprover/lean4/pull/11860) adds `CongrInfo` analysis for function applications in the
symbolic simulator framework. `CongrInfo` determines how to build
congruence proofs for rewriting subterms efficiently, categorizing
functions into:
- `none`: no arguments can be rewritten (e.g., proofs)
- `fixedPrefix`: common case where implicit/instance arguments form a
fixed prefix and explicit arguments can be rewritten (e.g., `HAdd.hAdd`,
`Eq`)
- `interlaced`: rewritable and non-rewritable arguments alternate (e.g.,
`HEq`)
- `congrTheorem`: uses auto-generated congruence theorems for functions
with dependent proof arguments (e.g., `Array.eraseIdx`)
* [#11866](https://github.com/leanprover/lean4/pull/11866) implements the core simplification loop for the `Sym` framework,
with efficient congruence-based argument rewriting.
* [#11868](https://github.com/leanprover/lean4/pull/11868) implements `Sym.Simp.Theorem.rewrite?` for rewriting terms using
equational theorems in `Sym`.
* [#11869](https://github.com/leanprover/lean4/pull/11869) adds configuration flag `Meta.Context.cacheInferType`. You can
use it to disable the `inferType` cache at `MetaM`. We use this flag to
implement `SymM` because it has its own cache based on pointer equality.
* [#11878](https://github.com/leanprover/lean4/pull/11878) documents assumptions made by the symbolic simulation framework
regarding structural matching and definitional equality.
* [#11880](https://github.com/leanprover/lean4/pull/11880) adds a `with_unfolding_none` tactic that sets the transparency
mode to `.none`, in which no definitions are unfolded. This complements
the existing `with_unfolding_all` tactic and provides tactic-level
access to the `TransparencyMode.none` added in
https://github.com/leanprover/lean4/pull/11810.
* [#11881](https://github.com/leanprover/lean4/pull/11881) fixes an issue where `grind` failed to prove `f ≠ 0` from `f * r
≠ 0` when using `Lean.Grind.CommSemiring`, but succeeded with
`Lean.Grind.Semiring`.
* [#11884](https://github.com/leanprover/lean4/pull/11884) adds discrimination tree support for the symbolic simulation
framework.
The new `DiscrTree.lean` module converts `Pattern` values into
discrimination
tree keys, treating proof/instance arguments and pattern variables as
wildcards
(`Key.star`). Motivation: efficient pattern retrieval during rewriting.
* [#11886](https://github.com/leanprover/lean4/pull/11886) adds `getMatch` and `getMatchWithExtra` for retrieving patterns
from
discrimination trees in the symbolic simulation framework.
The PR also adds uses `DiscrTree` to implement indexing in `Sym.simp`.
* [#11888](https://github.com/leanprover/lean4/pull/11888) refactors `Sym.simp` to make it more general and customizable.
It also moves the code
to its own subdirectory `Meta/Sym/Simp`.
* [#11889](https://github.com/leanprover/lean4/pull/11889) improves the discrimination tree retrieval performance used by
`Sym.simp`.
* [#11890](https://github.com/leanprover/lean4/pull/11890) ensures that `Sym.simp` checks thresholds for maximum recursion
depth and maximum number of steps. It also invokes `checkSystem`.
Additionally, this PR simplifies the main loop. Assigned metavariables
and `zetaDelta` reduction are now handled by installing `pre`/`post`
methods.
* [#11892](https://github.com/leanprover/lean4/pull/11892) optimizes the construction on congruence proofs in `simp`.
It uses some of the ideas used in `Sym.simp`.
* [#11898](https://github.com/leanprover/lean4/pull/11898) adds support for simplifying lambda expressions in `Sym.simp`.
It is much more efficient than standard simp for very large lambda
expressions with many binders. The key idea is to generate a custom
function extensionality theorem for the type of the lambda being
simplified.
* [#11900](https://github.com/leanprover/lean4/pull/11900) adds a `done` flag to the result returned by `Simproc`s in
`Sym.simp`.
* [#11906](https://github.com/leanprover/lean4/pull/11906) tries to minimize the number of expressions created at
`AlphaShareCommon`.
* [#11909](https://github.com/leanprover/lean4/pull/11909) reorganizes the monad hierarchy for symbolic computation in
Lean.
* [#11911](https://github.com/leanprover/lean4/pull/11911) minimizes the number of expression allocations performed by
`replaceS` and `instantiateRevBetaS`.
* [#11914](https://github.com/leanprover/lean4/pull/11914) factors out the `have`-telescope support used in `simp`, and
implements it using the `MonadSimp` interface. The goal is to
use this nice infrastructure for both `Meta.simp` and `Sym.simp`.
* [#11918](https://github.com/leanprover/lean4/pull/11918) filters deprecated lemmas from `exact?` and `rw?` suggestions.
* [#11920](https://github.com/leanprover/lean4/pull/11920) implements support for simplifying `have` telescopes in
`Sym.simp`.
* [#11923](https://github.com/leanprover/lean4/pull/11923) adds a new option to the function `simpHaveTelescope` in which
the `have` telescope is simplified in two passes:
* In the first pass, only the values and the body are simplified.
* In the second pass, unused declarations are eliminated.
* [#11932](https://github.com/leanprover/lean4/pull/11932) eliminates super-linear kernel type checking overhead when
simplifying lambda expressions. I improved the proof term produced by
`mkFunext`. This function is used in `Sym.simp` when simplifying lambda
expressions.
* [#11946](https://github.com/leanprover/lean4/pull/11946) adds a `+locals` configuration option to the `grind` tactic that
automatically adds all definitions from the current file as e-match
theorems. This provides a convenient alternative to manually adding
`[local grind]` attributes to each definition. In the form `grind?
+locals`, it is also helpful for discovering which local declarations it
may be useful to add `[local grind]` attributes to.
* [#11947](https://github.com/leanprover/lean4/pull/11947) adds a `+locals` configuration option to the `simp`, `simp_all`,
and `dsimp` tactics that automatically adds all definitions from the
current file to unfold.
* [#11949](https://github.com/leanprover/lean4/pull/11949) adds a new `first_par` tactic combinator that runs multiple
tactics in parallel and returns the first successful result (cancelling
the others).
* [#11950](https://github.com/leanprover/lean4/pull/11950) implements `simpForall` and `simpArrow` in `Sym.simp`.
* [#11962](https://github.com/leanprover/lean4/pull/11962) fixes library suggestions to include private proof-valued
structure fields.
* [#11967](https://github.com/leanprover/lean4/pull/11967) implements a new strategy for simplifying `have`-telescopes in
`Sym.simp` that achieves linear kernel type-checking time instead of
quadratic.
* [#11974](https://github.com/leanprover/lean4/pull/11974) optimizes congruence proof construction in `Sym.simp` by
avoiding
`inferType` calls on expressions that are less likely to be cached.
Instead of
inferring types of expressions like `@HAdd.hAdd Nat Nat Nat instAdd 5`,
we infer
the type of the function prefix `@HAdd.hAdd Nat Nat Nat instAdd` and
traverse
the forall telescope.
* [#11976](https://github.com/leanprover/lean4/pull/11976) adds missing type checking for pattern variables during pattern
matching/unification to prevent incorrect matches.
* [#11985](https://github.com/leanprover/lean4/pull/11985) implements support for auto-generated congruence theorems in
`Sym.simp`, enabling simplification of functions with complex argument
dependencies such as proof arguments and `Decidable` instances.
* [#11999](https://github.com/leanprover/lean4/pull/11999) adds support for simplifying the arguments of over-applied and
under-applied function application terms in `Sym.simp`, completing the
implementation for all three congruence strategies (fixed prefix,
interlaced, and congruence theorems).
* [#12006](https://github.com/leanprover/lean4/pull/12006) fixes the pretty-printing of the `extract_lets` tactic.
Previously, the pretty-printer would expect a space after the
`extract_lets` tactic, when it was followed by another tactic on the
same line: for example,
`extract_lets; exact foo`
would be changed to
`extract_lets ; exact foo`.
* [#12012](https://github.com/leanprover/lean4/pull/12012) implements support for rewrite on over-applied terms in
`Sym.simp`. Example: rewriting `id f a` using `id_eq`.
* [#12031](https://github.com/leanprover/lean4/pull/12031) adds `Sym.Simp.evalGround`, a simplification procedure for
evaluating ground terms of builtin numeric types. It is designed for
`Sym.simp`.
* [#12032](https://github.com/leanprover/lean4/pull/12032) adds `Discharger`s to `Sym.simp`, and ensures the cached results
are consistent.
* [#12033](https://github.com/leanprover/lean4/pull/12033) adds support for conditional rewriting rules to `Sym.simp`.
* [#12035](https://github.com/leanprover/lean4/pull/12035) adds `simpControl`, a simproc that handles control-flow
expressions such as `if-then-else`. It simplifies conditions while
avoiding unnecessary work on branches that won't be taken.
* [#12039](https://github.com/leanprover/lean4/pull/12039) implements `match`-expression simplification for `Sym.simp`.
* [#12040](https://github.com/leanprover/lean4/pull/12040) adds simprocs for simplifying `cond` and dependent
`if-then-else` in `Sym.simp`.
* [#12053](https://github.com/leanprover/lean4/pull/12053) adds support for offset terms in `SymM`. This is essential for
handling equational theorems for functions that pattern match on natural
numbers in `Sym.simp`. Without this, it cannot handle simple examples
such as `pw (a + 2)` where `pw` pattern matches on `n+1`.
* [#12077](https://github.com/leanprover/lean4/pull/12077) implements simprocs for `String` and `Char`. It also ensures
reducible definitions are unfolded in `SymM`
* [#12096](https://github.com/leanprover/lean4/pull/12096) cleanups temporary metavariables generated when applying
rewriting rules in `Sym.simp`.
* [#12099](https://github.com/leanprover/lean4/pull/12099) ensures `Sym.simpGoal` does not use `mkAppM`. It also increases
the default number of maximum steps in `Sym.simp`.
* [#12100](https://github.com/leanprover/lean4/pull/12100) adds a comparison between `MetaM` and `SymM` for a benchmark was
proposed during the Lean@Google Hackathon.
* [#12101](https://github.com/leanprover/lean4/pull/12101) improves the the `Sym.simp` APIs. It is now easier to reuse the
simplifier cache between different simplification steps. We use the APIs
to improve the benchmark at #12100.
* [#12134](https://github.com/leanprover/lean4/pull/12134) adds a new benchmark `shallow_add_sub_cancel.lean` that
demonstrates symbolic simulation using a shallow embedding into monadic
`do` notation, as opposed to the deep embedding approach in
`add_sub_cancel.lean`.
* [#12143](https://github.com/leanprover/lean4/pull/12143) adds an API for building symbolic simulation engines and
verification
condition generators that leverage `grind`. The API wraps `Sym`
operations to
work with `grind`'s `Goal` type, enabling lightweight symbolic execution
while
carrying `grind` state for discharge steps.
* [#12145](https://github.com/leanprover/lean4/pull/12145) moves the pre-shared commonly used expressions from `GrindM` to
`SymM`.
* [#12147](https://github.com/leanprover/lean4/pull/12147) adds a new API for helping users write focused rewrites.
# Compiler
* [#11479](https://github.com/leanprover/lean4/pull/11479) enables the specializer to also recursively specialize in some
non trivial higher order situations.
* [#11729](https://github.com/leanprover/lean4/pull/11729) internalizes all arguments of Quot.lift during LCNF conversion,
preventing panics in certain
non trivial programs that use quotients.
* [#11874](https://github.com/leanprover/lean4/pull/11874) improves the performance of `getLine` by coalescing the locking
of the underlying `FILE*`.
* [#11916](https://github.com/leanprover/lean4/pull/11916) adds a symbol to the runtime for marking `Array`
non-linearities. This should allow users to
spot them more easily in profiles or hunt them down using a debugger.
* [#11983](https://github.com/leanprover/lean4/pull/11983) fixes the `floatLetIn` pass to not move variables in case it
could break linearity (owned variables being passed with RC 1). This
mostly improves the situation in the parser which previously had many
functions that were supposed to be linear in terms of `ParserState` but
the compiler made them non-linear. For an example of how this affected
parsers:
```
def optionalFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s
s.mkNode nullKind iniSz
```
previously moved the `let iniSz := ...` declaration into the `hasError`
branch. However, this means that at the point of calling the inner
parser (`p c s`), the original state `s` needs to have RC>1 because it
is used later in the `hasError` branch, breaking linearity. This fix
prevents such moves, keeping `iniSz` before the `p c s` call.
* [#12003](https://github.com/leanprover/lean4/pull/12003) splits up the SCC that the compiler manages into (potentially)
multiple ones after
performing lambda lifting. This aids both the closed term extractor and
the elimDeadBranches pass as
they are both negatively influenced when more declarations than required
are within one SCC.
* [#12008](https://github.com/leanprover/lean4/pull/12008) ensures that the LCNF simplifier already constant folds decision
procedures (`Decidable`
operations) in the base phase.
* [#12010](https://github.com/leanprover/lean4/pull/12010) fixe a superliniear behavior in the closed subterm extractor.
* [#12123](https://github.com/leanprover/lean4/pull/12123) fixes an issue that may sporadically trigger ASAN to got into a
deadlock when running a subprocess through the `IO.Process.spawn`
framework.
# Documentation
* [#11737](https://github.com/leanprover/lean4/pull/11737) replaces `ffi.md` with links to the corresponding sections of
the manual, so we don't have to keep two documents up to date.
* [#11912](https://github.com/leanprover/lean4/pull/11912) adds missing docstrings for parts of the iterator library, which
removes warnings and empty content in the manual.
* [#12047](https://github.com/leanprover/lean4/pull/12047) makes the automatic first token detection in tactic docs much
more robust, in addition to making it work in modules and other contexts
where builtin tactics are not in the environment. It also adds the
ability to override the tactic's first token as the user-visible name.
* [#12072](https://github.com/leanprover/lean4/pull/12072) enables tactic completion and docs for the `let rec` tactic,
which required a stage0 update after #12047.
* [#12093](https://github.com/leanprover/lean4/pull/12093) makes the Verso module docstring API more like the Markdown
module docstring API, enabling downstream consumers to use them the same
way.
# Server
* [#11536](https://github.com/leanprover/lean4/pull/11536) corrects the JSON Schema at
`src/lake/schemas/lakefile-toml-schema.json` to allow the table variant
of the `require.git` field in `lakefile.toml` as specified in the
[reference](https://lean-lang.org/doc/reference/latest/Build-Tools-and-Distribution/Lake/#Lake___Dependency-git).
* [#11630](https://github.com/leanprover/lean4/pull/11630) improves the performance of autocompletion and fuzzy matching by
introducing an ASCII fast path into one of their core loops and making
Char.toLower/toUpper more efficient.
* [#12000](https://github.com/leanprover/lean4/pull/12000) fixes an issue where go-to-definition would jump to the wrong
location in presence of async theorems.
* [#12004](https://github.com/leanprover/lean4/pull/12004) allows 'Go to Definition' to look through reducible definition
when looking for typeclass instance projections.
* [#12046](https://github.com/leanprover/lean4/pull/12046) fixes a bug where the unknown identifier code actions were
broken in NeoVim due to the language server not properly setting the
`data?` field for all code action items that it yields.
* [#12119](https://github.com/leanprover/lean4/pull/12119) fixes the call hierarchy for `where` declarations under the
module system
# Lake
* [#11683](https://github.com/leanprover/lean4/pull/11683) fixes an inconsistency in the way Lake and Lean view the
transitivity of a `meta import`. Lake now works as Lean expects and
includes the meta segment of all transitive imports of a `meta import`
in its transitive trace.
* [#11859](https://github.com/leanprover/lean4/pull/11859) removes the need to write `.ofNat` for numeric options in
`lakefile.lean`. Note that `lake translate-config` incorrectly assumed
this was already legal in earlier revisions.
* [#11921](https://github.com/leanprover/lean4/pull/11921) adds `lake shake` as a built-in Lake command, moving the shake
functionality from `script/Shake.lean` into the Lake CLI.
* [#12034](https://github.com/leanprover/lean4/pull/12034) changes the default of `enableArtifactCache` to use the
workspace's `enableArtifactCache` setting if the package is a dependency
and `LAKE_ARTIFACT_CACHE` is not set. This means that dependencies of a
project with `enableArtifactCache` set will also, by default, use Lake's
local artifact cache.
* [#12037](https://github.com/leanprover/lean4/pull/12037) fixes two Lake cache issues: a bug where a failed upload would
not produce an error and a mistake in the `--wfail` checks of the cache
commands.
* [#12076](https://github.com/leanprover/lean4/pull/12076) adds additional debugging information to a run of `lake build
--no-build` via a `.nobuild` trace file. When a build fails due to
needing a rebuild, Lake emits the new expected trace next as `.nobuild`
file next to the build's old `.trace`. The inputs recorded in these
files can then be compared to debug what caused the mismatch.
* [#12086](https://github.com/leanprover/lean4/pull/12086) fixes a bug where a `lake build --no-build` would exit with code
`3` if the optional job to fetch a GitHub or Reservoir release for a
package failed (even if nothing else needed rebuilding).
* [#12105](https://github.com/leanprover/lean4/pull/12105) fixes the `lake query` output for targets which produce an
`Array` or `List` of a value with a custom `QueryText` or `QueryJson`
instance (e.g., `deps` and `transDeps`).
* [#12112](https://github.com/leanprover/lean4/pull/12112) revives the ability to specify modules in dependencies via the
basic `+mod` target key.
# Other
* [#11727](https://github.com/leanprover/lean4/pull/11727) adds a Python script that helps find which commit introduced a
behavior change in Lean. It supports multiple bisection modes and
automatically downloads CI artifacts when available.
* [#11735](https://github.com/leanprover/lean4/pull/11735) adds a standalone script to download pre-built CI artifacts from
GitHub Actions. This allows us to quickly switch commits without
rebuilding.
* [#11887](https://github.com/leanprover/lean4/pull/11887) makes the external checker lean4checker available as the
existing `leanchecker` binary already known to elan, allowing for
out-of-the-box access to it.
* [#12121](https://github.com/leanprover/lean4/pull/12121) wraps info trees produced by the `lean` Verso docstring
codeblock in a context info node.
# Ffi
* [#12098](https://github.com/leanprover/lean4/pull/12098) removes the requirement that libraries compiled against the lean
headers must use `-fwrapv`. |
reference-manual/Manual/Releases/v4_24_0.lean | import VersoManual
import Manual.Meta.Markdown
open Manual
open Verso.Genre
#doc (Manual) "Lean 4.24.0 (2025-10-14)" =>
%%%
tag := "release-v4.24.0"
file := "v4.24.0"
%%%
````markdown
For this release, 377 changes landed. In addition to the 105 feature additions and 75 fixes listed below there were 25 refactoring changes, 9 documentation improvements, 21 performance improvements, 4 improvements to the test suite and 138 other changes.
## Highlights
Lean 4.24.0 release brings continued improvements to the module system and the verification framework,
strengthens the `grind` tactic, and advances the standard library.
The release also introduces more efficient constructions of `DecidableEq` instances and `noConfusion` ([#10152](https://github.com/leanprover/lean4/pull/10152) and [#10300](https://github.com/leanprover/lean4/pull/10300)),
optimizing compilation.
As an example for our continuous improvements to performance:
- [#10249](https://github.com/leanprover/lean4/pull/10249) speeds up auto-completion by a factor of ~3.5x through various
performance improvements in the language server.
As always, there are plenty of bug fixes and new features, some of which are listed below:
### "Try this" suggestions are rendered under 'Messages'
- [#9966](https://github.com/leanprover/lean4/pull/9966) adjusts the "try this" widget to be rendered as a widget message
under 'Messages', not a separate widget under a 'Suggestions' section.
The main benefit of this is that the message of the widget is not
duplicated between 'Messages' and 'Suggestions'.
### `invariants` and `with` sections in `mvcgen`
- [#9927](https://github.com/leanprover/lean4/pull/9927) implements extended `induction`-inspired syntax for `mvcgen`,
allowing optional `invariants` and `with` sections.
The example below gives the proof that `nodup` correctly checks for duplicates in a list.
```lean
import Std.Tactic.Do
import Std
open Std Do
def nodup (l : List Int) : Bool := Id.run do
let mut seen : HashSet Int := ∅
for x in l do
if x ∈ seen then
return false
seen := seen.insert x
return true
theorem nodup_correct (h : nodup l = r) : r = true ↔ l.Nodup := by
unfold nodup at h
apply Id.of_wp_run_eq h; clear h
mvcgen
invariants
· Invariant.withEarlyReturn
(onReturn := fun ret seen => ⌜ret = false ∧ ¬l.Nodup⌝)
(onContinue := fun xs seen =>
⌜(∀ x, x ∈ seen ↔ x ∈ xs.prefix) ∧ xs.prefix.Nodup⌝)
with grind
```
### Library: Dyadic rationals
- [#9993](https://github.com/leanprover/lean4/pull/9993) defines the dyadic rationals, showing they are an ordered ring
embedding into the rationals.
### Grind AC solver
`grind` can reason about associative, commutative, idempotent, and/or unital operations
([#10105](https://github.com/leanprover/lean4/pull/10105), [#10146](https://github.com/leanprover/lean4/pull/10146), etc..):
```lean
example (a b c : Nat) : max a (max b c) = max (max b 0) (max a c) := by
grind only
example {α} (as bs cs : List α) : as ++ (bs ++ cs) = ((as ++ []) ++ bs) ++ (cs ++ []) := by
grind only
example {α : Sort u} (op : α → α → α) (u : α) [Std.Associative op] [Std.Commutative op] [Std.IdempotentOp op] [Std.LawfulIdentity op u] (a b c : α)
: op (op a a) (op b c) = op (op (op b a) (op (op u b) b)) c := by
grind only
```
### Metaprogramming notes
- [#10306](https://github.com/leanprover/lean4/pull/10306) fixes a few bugs in the `rw` tactic.
Metaprogramming API: Instead of `Lean.MVarId.rewrite` prefer `Lean.Elab.Tactic.elabRewrite`
for elaborating rewrite theorems and applying rewrites to expressions.
### Breaking changes
- [#9749](https://github.com/leanprover/lean4/pull/9749) refactors the Lake codebase to use the new module system
throughout. Every module in `Lake` is now a `module`.
**Breaking change:** Since the module system encourages a `private`-by-default design,
the Lake API has switched from its previous `public`-by-default approach. As such,
many definitions that were previously public are now private. The newly private definitions
are not expected to have had significant user use, nonetheless, important use cases could be missed.
If a key API is now inaccessible but seems like it should be public, users are encouraged
to report this as an issue on GitHub.
## Language
* [#8891](https://github.com/leanprover/lean4/pull/8891) improves the error message produced when passing (automatically
redundant) local hypotheses to `grind`.
* [#9651](https://github.com/leanprover/lean4/pull/9651) modifies the generation of induction and partial correctness
lemmas for `mutual` blocks defined via `partial_fixpoint`. Additionally,
the generation of lattice-theoretic induction principles of functions
via `mutual` blocks is modified for consistency with `partial_fixpoint`.
* [#9674](https://github.com/leanprover/lean4/pull/9674) cleans up `optParam`/`autoParam`/etc. annotations before
elaborating definition bodies, theorem bodies, `fun` bodies, and `let`
function bodies. Both `variable`s and binders in declaration headers are
supported.
* [#9918](https://github.com/leanprover/lean4/pull/9918) prevents `rcases` and `obtain` from creating absurdly long case
tag names when taking single constructor types (like `Exists`) apart.
Fixes #6550
* [#9923](https://github.com/leanprover/lean4/pull/9923) adds a guard for a delaborator that is causing panics in
doc-gen4. This is a band-aid solution for now, and @sgraf812 will take a
look when they're back from leave.
* [#9926](https://github.com/leanprover/lean4/pull/9926) guards the `Std.Tactic.Do.MGoalEntails` delaborator by a check
ensuring that there are at least 3 arguments present, preventing
potential panics.
* [#9927](https://github.com/leanprover/lean4/pull/9927) implements extended `induction`-inspired syntax for `mvcgen`,
allowing optional `using invariants` and `with` sections.
* [#9930](https://github.com/leanprover/lean4/pull/9930) reverts the way `grind cutsat` embeds `Nat.sub` into `Int`. It
fixes a regression reported by David Renshaw on Zulip.
* [#9938](https://github.com/leanprover/lean4/pull/9938) removes a duplicate `mpure_intro` tactic definition.
* [#9939](https://github.com/leanprover/lean4/pull/9939) expands `mvcgen using invariants | $n => $t` to `mvcgen; case
inv<$n> => exact $t` to avoid MVar instantiation mishaps observable in
the test case for #9581.
* [#9942](https://github.com/leanprover/lean4/pull/9942) modifies `intro` to create tactic info localized to each
hypothesis, making it possible to see how `intro` works
variable-by-variable. Additionally:
- The tactic supports `intro rfl` to introduce an equality and
immediately substitute it, like `rintro rfl` (recall: the `rfl` pattern
is like doing `intro h; subst h`). The `rintro` tactic can also now
support `HEq` in `rfl` patterns if `eq_of_heq` applies.
- In `intro (h : t)`, elaboration of `t` is interleaved with unification
with the type of `h`, which prevents default instances from causing
unification to fail.
- Tactics that change types of hypotheses (including `intro (h : t)`,
`delta`, `dsimp`) now update the local instance cache.
* [#9945](https://github.com/leanprover/lean4/pull/9945) optimizes the proof terms produced by `grind cutsat`. It removes
unused entries from the context objects when generating the final proof,
significantly reducing the amount of junk in the resulting terms.
Example:
```lean
/--
trace: [grind.debug.proof] fun h h_1 h_2 h_3 h_4 h_5 h_6 h_7 h_8 =>
let ctx := RArray.leaf (f 2);
let p_1 := Poly.add 1 0 (Poly.num 0);
let p_2 := Poly.add (-1) 0 (Poly.num 1);
let p_3 := Poly.num 1;
le_unsat ctx p_3 (eagerReduce (Eq.refl true)) (le_combine ctx p_2 p_1 p_3 (eagerReduce (Eq.refl true)) h_8 h_1)
-/
#guard_msgs in -- Context should contain only `f 2`
open Lean Int Linear in
set_option trace.grind.debug.proof true in
example (f : Nat → Int) :
f 1 <= 0 → f 2 <= 0 → f 3 <= 0 → f 4 <= 0 → f 5 <= 0 →
f 6 <= 0 → f 7 <= 0 → f 8 <= 0 → -1 * f 2 + 1 <= 0 → False := by
grind
```
* [#9946](https://github.com/leanprover/lean4/pull/9946) optimizes the proof terms produced by `grind ring`. It is
similar to #9945, but for the ring module in `grind`.
It removes unused entries from the context objects when generating the
final proof, significantly reducing the amount of junk in the resulting
terms. Example:
```lean
/--
trace: [grind.debug.proof] fun h h_1 h_2 h_3 =>
Classical.byContradiction fun h_4 =>
let ctx := RArray.branch 1 (RArray.leaf x) (RArray.leaf x⁻¹);
let e_1 := (Expr.var 0).mul (Expr.var 1);
let e_2 := Expr.num 0;
let e_3 := Expr.num 1;
let e_4 := (Expr.var 0).pow 2;
let m_1 := Mon.mult (Power.mk 1 1) Mon.unit;
let m_2 := Mon.mult (Power.mk 0 1) Mon.unit;
let p_1 := Poly.num (-1);
let p_2 := Poly.add (-1) (Mon.mult (Power.mk 0 1) Mon.unit) (Poly.num 0);
let p_3 := Poly.add 1 (Mon.mult (Power.mk 0 2) Mon.unit) (Poly.num 0);
let p_4 := Poly.add 1 (Mon.mult (Power.mk 0 1) (Mon.mult (Power.mk 1 1) Mon.unit)) (Poly.num (-1));
let p_5 := Poly.add 1 (Mon.mult (Power.mk 0 1) Mon.unit) (Poly.num 0);
one_eq_zero_unsat ctx p_1 (eagerReduce (Eq.refl true))
(Stepwise.simp ctx 1 p_4 (-1) m_1 p_5 p_1 (eagerReduce (Eq.refl true))
(Stepwise.core ctx e_1 e_3 p_4 (eagerReduce (Eq.refl true)) (diseq0_to_eq x h_4))
(Stepwise.mul ctx p_2 (-1) p_5 (eagerReduce (Eq.refl true))
(Stepwise.superpose ctx 1 m_2 p_4 (-1) m_1 p_3 p_2 (eagerReduce (Eq.refl true))
(Stepwise.core ctx e_1 e_3 p_4 (eagerReduce (Eq.refl true)) (diseq0_to_eq x h_4))
(Stepwise.core ctx e_4 e_2 p_3 (eagerReduce (Eq.refl true)) h))))
-/
#guard_msgs in -- Context should contains only `x` and its inverse.
set_option trace.grind.debug.proof true in
set_option pp.structureInstances false in
open Lean Grind CommRing in
example [Field α] (x y z w : α) :
x^2 = 0 → y^2 = 0 → z^3 = 0 → w^2 = 0 → x = 0 := by
grind
```
* [#9947](https://github.com/leanprover/lean4/pull/9947) optimizes the proof terms produced by `grind linarith`. It is
similar to #9945, but for the `linarith` module in `grind`.
It removes unused entries from the context objects when generating the
final proof, significantly reducing the amount of junk in the resulting
terms.
* [#9951](https://github.com/leanprover/lean4/pull/9951) generates `.ctorIdx` functions for all inductive types, not just
enumeration types. This can be a building block for other constructions
(`BEq`, `noConfusion`) that are size-efficient even for large
inductives.
* [#9952](https://github.com/leanprover/lean4/pull/9952) adds “non-branching case statements”: For each inductive
constructor `T.con` this adds a function `T.con.with` that is similar
`T.casesOn`, but has only one arm (the one for `con`), and an additional
`t.toCtorIdx = 12` assumption.
* [#9954](https://github.com/leanprover/lean4/pull/9954) removes the option `grind +ringNull`. It provided an alternative
proof term construction for the `grind ring` module, but it was less
effective than the default proof construction mode and had effectively
become dead code.
also optimizes semiring normalization proof terms using the
infrastructure added in #9946.
**Remark:** After updating stage0, we can remove several background
theorems from the `Init/Grind` folder.
* [#9958](https://github.com/leanprover/lean4/pull/9958) ensures that equations in the `grind cutsat` module are
maintained in solved form. That is, given an equation `a*x + p = 0` used
to eliminate `x`, the linear polynomial `p` must not contain other
eliminated variables. Before this PR, equations were maintained in
triangular form. We are going to use the solved form to linearize
nonlinear terms.
* [#9968](https://github.com/leanprover/lean4/pull/9968) modifies macros, which implement non-atomic definitions and
```$cmd1 in $cmd2``` syntax. These macros involve implicit scopes,
introduced through ```section``` and ```namespace``` commands. Since
sections or namespaces are designed to delimit local attributes, this
has led to unintuitive behaviour when applying local attributes to
definitions appearing in the above-mentioned contexts. This has been
causing the following examples to fail:
```lean4
axiom A : Prop
* [#9974](https://github.com/leanprover/lean4/pull/9974) registers a parser alias for `Lean.Parser.Command.visibility`.
This avoids having to import `Lean.Parser.Command` in simple command
macros that use visibilities.
* [#9980](https://github.com/leanprover/lean4/pull/9980) fixes a bug in the dynamic variable reordering function used in
`grind cutsat`.
* [#9989](https://github.com/leanprover/lean4/pull/9989) changes the new extended syntax for `mvcgen` to `mvcgen
invariants ... with ...`.
* [#9995](https://github.com/leanprover/lean4/pull/9995) almost completely rewrites the inductive predicate recursion
algorithm; in particular `IndPredBelow` to function more consistently.
Historically, the `brecOn` generation through `IndPredBelow` has been
very error-prone -- this should be fixed now since the new algorithm is
very direct and doesn't rely on tactics or meta-variables at all.
Additionally, the new structural recursion procedure for inductive
predicates shares more code with regular structural recursion and thus
allows for mutual and nested recursion in the same way it was possible
with regular structural recursion. For example, the following works now:
```lean-4
mutual
* [#9996](https://github.com/leanprover/lean4/pull/9996) improves support for nonlinear monomials in `grind cutsat`. For
example, given a monomial `a * b`, if `cutsat` discovers that `a = 2`,
it now propagates that `a * b = 2 * b`.
Recall that nonlinear monomials like `a * b` are treated as variables in
`cutsat`, a procedure designed for linear integer arithmetic.
* [#10007](https://github.com/leanprover/lean4/pull/10007) lets #print print `private` before `protected`, matching the
syntax.
* [#10008](https://github.com/leanprover/lean4/pull/10008) fixes a bug in `#eval` where clicking on the evaluated
expression could show errors in the Infoview. This was caused by `#eval`
not saving the temporary environment that is used when elaborating the
expression.
* [#10010](https://github.com/leanprover/lean4/pull/10010) improves support for nonlinear `/` and `%` in `grind cutsat`.
For example, given `a / b`, if `cutsat` discovers that `b = 2`, it now
propagates that `a / b = b / 2`. is similar to #9996, but for
`/` and `%`. Example:
```lean
example (a b c d : Nat)
: b > 1 → d = 1 → b ≤ d + 1 → a % b = 1 → a = 2 * c → False := by
grind
```
* [#10020](https://github.com/leanprover/lean4/pull/10020) fixes a missing case for PR #10010.
* [#10021](https://github.com/leanprover/lean4/pull/10021) make some minor changes to the grind annotation analysis script,
including sorting results and handling errors. Still need to add an
external UI.
* [#10022](https://github.com/leanprover/lean4/pull/10022) improves support for `Fin n` in `grind cutsat` when `n` is not a
numeral. For example, the following goals can now be solved
automatically:
```lean
example (p d : Nat) (n : Fin (p + 1))
: 2 ≤ p → p ≤ d + 1 → d = 1 → n = 0 ∨ n = 1 ∨ n = 2 := by
grind
* [#10034](https://github.com/leanprover/lean4/pull/10034) changes the "declaration uses 'sorry'" error to pretty print an
actual `sorry` expression in the message. The effect is that the `sorry`
is hoverable and, if it's labeled, you can "go to definition" to see
where it came from.
* [#10038](https://github.com/leanprover/lean4/pull/10038) ensures `grind` error messages use `{.ofConstName declName}`
when referencing declaration names.
* [#10060](https://github.com/leanprover/lean4/pull/10060) allows for more fine-grained control over what derived instances
have exposed definitions under the module system: handlers should not
expose their implementation unless either the deriving item or a
surrounding section is marked with `@[expose]`. Built-in handlers to be
updated after a stage 0 update.
* [#10069](https://github.com/leanprover/lean4/pull/10069) adds helper theorems to support `NatModule` in `grind linarith`.
* [#10071](https://github.com/leanprover/lean4/pull/10071) improves support for `a^n` in `grind cutsat`. For example, if
`cutsat` discovers that `a` and `b` are equal to numerals, it now
propagates the equality.
It is similar to #9996, but for `a^b`.
Example:
```lean
example (n : Nat) : n = 2 → 2 ^ (n+1) = 8 := by
grind
```
* [#10085](https://github.com/leanprover/lean4/pull/10085) adds a parser alias for the `rawIdent` parser, so that it can be
used in `syntax` declarations in `Init`.
* [#10093](https://github.com/leanprover/lean4/pull/10093) adds background theorems for a new solver to be implemented in
`grind` that will support associative and commutative operators.
* [#10095](https://github.com/leanprover/lean4/pull/10095) modifies the `grind` algebra type classes to use `SMul x y`
instead of `HMul x y y`.
* [#10105](https://github.com/leanprover/lean4/pull/10105) adds support for detecting associative operators in `grind`. The
new AC module also detects whether the operator is commutative,
idempotent, and whether it has a neutral element. The information is
cached.
* [#10113](https://github.com/leanprover/lean4/pull/10113) deprecates `.toCtorIdx` for the more naturally named `.ctorIdx`
(and updates the standard library).
* [#10120](https://github.com/leanprover/lean4/pull/10120) fixes an issue where private definitions recursively invoked
using generalized field notation (dot notation) would give an "invalid
field" error. It also fixes an issue where "invalid field notation"
errors would pretty print the name of the declaration with a `_private`
prefix.
* [#10125](https://github.com/leanprover/lean4/pull/10125) allows `#guard_msgs` to report the relative positions of logged
messages with the config option `(positions := true)`.
* [#10129](https://github.com/leanprover/lean4/pull/10129) replaces the interim order type classes used by `Grind` with the
new publicly available classes in `Std`.
* [#10134](https://github.com/leanprover/lean4/pull/10134) makes the generation of functional induction principles more
robust when the user `let`-binds a variable that is then `match`'ed on.
Fixes #10132.
* [#10135](https://github.com/leanprover/lean4/pull/10135) lets the `ctorIdx` definition for single constructor inductives
avoid the pointless `.casesOn`, and uses `macro_inline` to avoid
compiling the function and wasting symbols.
* [#10141](https://github.com/leanprover/lean4/pull/10141) reverts the `macro_inline` part of #10135.
* [#10144](https://github.com/leanprover/lean4/pull/10144) changes the construction of a `CompleteLattice` instance on
predicates (maps intro `Prop`) inside of
`coinductive_fixpoint`/`inductive_fixpoint` machinery.
* [#10146](https://github.com/leanprover/lean4/pull/10146) implements the basic infrastructure for the new procedure
handling AC operators in `grind`. It already supports normalizing
disequalities. Future PRs will add support for simplification using
equalities, and computing critical pairs. Examples:
```lean
example {α : Sort u} (op : α → α → α) [Std.Associative op] (a b c : α)
: op a (op b c) = op (op a b) c := by
grind only
* [#10151](https://github.com/leanprover/lean4/pull/10151) ensures `where finally` tactics can access private data under
the module system even when the corresponding holes are in the public
scope as long as all of them are of proposition types.
* [#10152](https://github.com/leanprover/lean4/pull/10152) introduces an alternative construction for `DecidableEq`
instances that avoids the quadratic overhead of the default
construction.
* [#10166](https://github.com/leanprover/lean4/pull/10166) reviews the expected-to-fail-right-now tests for `grind`, moving
some (now passing) tests to the main test suite, updating some tests,
and adding some tests about normalisation of exponents.
* [#10177](https://github.com/leanprover/lean4/pull/10177) fixes a bug in the `grind` preprocessor exposed by #10160.
* [#10179](https://github.com/leanprover/lean4/pull/10179) fixes `grind` instance normalization procedure.
Some modules in grind use builtin instances defined directly in core
(e.g., `cutsat`), while others synthesize them using `synthInstance`
(e.g., `ring`). This inconsistency is problematic, as it may introduce
mismatches and result in two different representations for the same
term. fixes the issue.
* [#10183](https://github.com/leanprover/lean4/pull/10183) lets match equations be proved by `rfl` if possible, instead of
explicitly unfolding the LHS first. May lead to smaller proofs.
* [#10185](https://github.com/leanprover/lean4/pull/10185) documents all `grind` attribute modifiers (e.g., `=`, `usr`,
`ext`, etc).
* [#10186](https://github.com/leanprover/lean4/pull/10186) adds supports for simplifying disequalities in the `grind ac`
module.
* [#10189](https://github.com/leanprover/lean4/pull/10189) implements the proof terms for the new `grind ac` module.
Examples:
```lean
example {α : Sort u} (op : α → α → α) [Std.Associative op] (a b c d : α)
: op a (op b b) = op c d → op c (op d c) = op (op a b) (op b c) := by
grind only
* [#10205](https://github.com/leanprover/lean4/pull/10205) adds superposition for associative and commutative operators in
`grind ac`. Examples:
```lean
example (a b c d e f g h : Nat) :
max a b = max c d → max b e = max d f → max b g = max d h →
max (max f d) (max c g) = max (max e (max d (max b (max c e)))) h := by
grind -cutsat only
* [#10206](https://github.com/leanprover/lean4/pull/10206) adds superposition for associative (but non-commutative)
operators in `grind ac`. Examples:
```lean
example {α} (op : α → α → α) [Std.Associative op] (a b c d : α)
: op a b = c →
op b a = d →
op (op c a) (op b c) = op (op a d) (op d b) := by
grind
* [#10208](https://github.com/leanprover/lean4/pull/10208) adds the extra critical pairs to ensure the `grind ac` procedure
is complete when the operator is AC and idempotent. Example:
```lean
example {α : Sort u} (op : α → α → α) [Std.Associative op] [Std.Commutative op] [Std.IdempotentOp op]
(a b c d : α) : op a (op b b) = op d c → op (op b a) (op b c) = op c (op d c) := by
grind only
```
* [#10221](https://github.com/leanprover/lean4/pull/10221) adds the extra critical pairs to ensure the `grind ac` procedure
is complete when the operator is associative and idempotent, but not
commutative. Example:
```lean
example {α : Sort u} (op : α → α → α) [Std.Associative op] [Std.IdempotentOp op] (a b c d e f x y w : α)
: op d (op x c) = op a b →
op e (op f (op y w)) = op a (op b c) →
op d (op x c) = op e (op f (op y w)) := by
grind only
* [#10223](https://github.com/leanprover/lean4/pull/10223) implements equality propagation from the new AC module into the
`grind` core. Examples:
```lean
example {α β : Sort u} (f : α → β) (op : α → α → α) [Std.Associative op] [Std.Commutative op]
(a b c d : α) : op a (op b b) = op d c → f (op (op b a) (op b c)) = f (op c (op d c)) := by
grind only
* [#10230](https://github.com/leanprover/lean4/pull/10230) adds `MonoBind` for more monad transformers. This allows using
`partial_fixpoint` for more complicated monads based on `Option` and
`EIO`. Example:
```lean-4
abbrev M := ReaderT String (StateT String.Pos Option)
* [#10237](https://github.com/leanprover/lean4/pull/10237) fixes a missing case in the `grind` canonicalizer. Some types
may include terms or propositions that are internalized later in the
`grind` state.
* [#10239](https://github.com/leanprover/lean4/pull/10239) fixes the E-matching procedure for theorems that contain
universe parameters not referenced by any regular parameter. This kind
of theorem seldom happens in practice, but we do have instances in the
standard library. Example:
```
@[simp, grind =] theorem Std.Do.SPred.down_pure {φ : Prop} : (⌜φ⌝ : SPred []).down = φ := rfl
```
* [#10241](https://github.com/leanprover/lean4/pull/10241) adds some test cases for `grind` working with `Fin`. There are
many still failing tests in `tests/lean/grind/grind_fin.lean` which I'm
intending to triage and work on.
* [#10245](https://github.com/leanprover/lean4/pull/10245) changes the implementation of a function `unfoldPredRel` used in
(co)inductive predicate machinery, that unfolds pointwise order on
predicates to quantifications and implications. Previous implementation
relied on `withDeclsDND` that could not deal with types which depend on
each other. This caused the following example to fail:
```lean4
inductive infSeq_functor1.{u} {α : Type u} (r : α → α → Prop) (call : {α : Type u} → (r : α → α → Prop) → α → Prop) : α → Prop where
| step : r a b → infSeq_functor1 r call b → infSeq_functor1 r call a
* [#10265](https://github.com/leanprover/lean4/pull/10265) fixes a panic in `grind ring` exposed by #10242. `grind ring`
should not assume that all normalizations have been applied, because
some subterms cannot be rewritten by `simp` due to typing constraints.
Moreover, `grind` uses `preprocessLight` in a few places, and it skips
the simplifier/normalizer.
* [#10267](https://github.com/leanprover/lean4/pull/10267) implements the infrastructure for supporting `NatModule` in
`grind linarith` and uses it to handle disequalities. Another PR will
add support for equalities and inequalities. Example:
```lean
open Lean Grind
variable (M : Type) [NatModule M] [AddRightCancel M]
* [#10269](https://github.com/leanprover/lean4/pull/10269) changes the string interpolation procedure to omit redundant
empty parts. For example `s!"{1}{2}"` previously elaborated to `toString
"" ++ toString 1 ++ toString "" ++ toString 2 ++ toString ""` and now
elaborates to `toString 1 ++ toString 2`.
* [#10271](https://github.com/leanprover/lean4/pull/10271) changes the naming of the internal functions in deriving
instances like BEq to use accessible names. This is necessary to
reasonably easily prove things about these functions. For example after
`deriving BEq` for a type `T`, the implementation of `instBEqT` is in
`instBEqT.beq`.
* [#10273](https://github.com/leanprover/lean4/pull/10273) tries to do the right thing about the visibility of the
same-ctor-match-construct.
* [#10274](https://github.com/leanprover/lean4/pull/10274) changes the implementation of the linear `DecidableEq`
implementation to use `match decEq` rather than `if h : ` to compare the
constructor tags. Otherwise, the “smart unfolding” machinery will not
let `rfl` decide that different constructors are different.
* [#10277](https://github.com/leanprover/lean4/pull/10277) adds the missing instances `IsPartialOrder`, `IsLinearPreorder`
and `IsLinearOrder` for `OfNatModule.Q α`.
* [#10278](https://github.com/leanprover/lean4/pull/10278) adds support for `NatModule` equalities and inequalities in
`grind linarith`. Examples:
```lean
open Lean Grind Std
* [#10280](https://github.com/leanprover/lean4/pull/10280) adds the auxiliary theorem `Lean.Grind.Linarith.eq_normN` for
normalizing `NatModule` equations when the instance `AddRightCancel` is
not available.
* [#10281](https://github.com/leanprover/lean4/pull/10281) implements `NatModule` normalization when the `AddRightCancel`
instance is not available. Note that in this case, the embedding into
`IntModule` is not injective. Therefore, we use a custom normalizer,
similar to the `CommSemiring` normalizer used in the `grind ring`
module. Example:
```lean
open Lean Grind
example [NatModule α] (a b c : α)
: 2•a + 2•(b + 2•c) + 3•a = 4•a + c + 2•b + 3•c + a := by
grind
```
* [#10282](https://github.com/leanprover/lean4/pull/10282) improves the counterexamples produced by `grind linarith` for
`NatModule`s. `grind` now hides occurrences of the auxiliary function
`Grind.IntModule.OfNatModule.toQ`.
* [#10283](https://github.com/leanprover/lean4/pull/10283) implements diagnostic information for the `grind ac` module. It
now displays the basis, normalized disequalities, and additional
properties detected for each associative operator.
* [#10290](https://github.com/leanprover/lean4/pull/10290) adds infrastructure for registering new `grind` solvers. `grind`
already includes many solvers, and this PR is the first step toward
modularizing the design and supporting user-defined solvers.
* [#10294](https://github.com/leanprover/lean4/pull/10294) completes the `grind` solver extension design and ports the
`grind ac` solver to the new framework. Future PRs will document the API
and port the remaining solvers. An additional benefit of the new design
is faster build times.
* [#10296](https://github.com/leanprover/lean4/pull/10296) fixes a bug in an auxiliary function used to construct proof
terms in `grind cutsat`.
* [#10300](https://github.com/leanprover/lean4/pull/10300) offers an alternative `noConfusion` construction for the
off-diagonal use (i.e. for different constructors), based on comparing
the `.ctorIdx`. This should lead to faster type checking, as the kernel
only has to reduce `.ctorIdx` twice, instead of the complicate
`noConfusionType` construction.
* [#10301](https://github.com/leanprover/lean4/pull/10301) exposes ctorIdx and per-constructor eliminators. Fixes #10299.
* [#10306](https://github.com/leanprover/lean4/pull/10306) fixes a few bugs in the `rw` tactic: it could "steal" goals
because they appear in the type of the rewrite, it did not do an occurs
check, and new proof goals would not be synthetic opaque. also
lets the `rfl` tactic assign synthetic opaque metavariables so that it
is equivalent to `exact rfl`.
* [#10307](https://github.com/leanprover/lean4/pull/10307) upstreams the Verso parser and adds preliminary support for
Verso in docstrings. This will allow the compiler to check examples and
cross-references in documentation.
* [#10309](https://github.com/leanprover/lean4/pull/10309) modifies the `simpa` tactic so that in `simpa ... using e` there
is tactic info on the range `simpa ... using` that shows the simplified
goal.
* [#10313](https://github.com/leanprover/lean4/pull/10313) adds missing `grind` normalization rules for `natCast` and
`intCast` Examples:
```
open Lean.Grind
variable (R : Type) (a b : R)
* [#10314](https://github.com/leanprover/lean4/pull/10314) skips model based theory combination on instances.
* [#10315](https://github.com/leanprover/lean4/pull/10315) adds `T.ctor.noConfusion` declarations, which are
specializations of `T.noConfusion` to equalities between `T.ctor`. The
point is to avoid reducing the `T.noConfusionType` construction every
time we use `injection` or a similar tactic.
* [#10316](https://github.com/leanprover/lean4/pull/10316) shares common functionality relate to equalities between same
constructors, and when these are type-correct. In particular it uses the
more complete logic from `mkInjectivityThm` also in other places, such
as `CasesOnSameCtor` and the deriving code for `BEq`, `DecidableEq`,
`Ord`, for more consistency and better error messages.
* [#10321](https://github.com/leanprover/lean4/pull/10321) ensures that the auxiliary temporary metavariable IDs created by
the E-matching module used in `grind` are not affected by what has been
executed before invoking `grind`. The goal is to increase `grind`’s
robustness.
* [#10322](https://github.com/leanprover/lean4/pull/10322) introduces limited functionality frontends `cutsat` and
`grobner` for `grind`. We disable theorem instantiation (and case
splitting for `grobner`), and turn off all other solvers. Both still
allow `grind` configuration options, so for example one can use `cutsat
+ring` (or `grobner +cutsat`) to solve problems that require both.
* [#10323](https://github.com/leanprover/lean4/pull/10323) fixes the `grind` canonicalizer for `OfNat.ofNat` applications.
Example:
```lean
example {C : Type} (h : Fin 2 → C) :
-- `0` in the first `OfNat.ofNat` is not a raw literal
h (@OfNat.ofNat (Fin (1 + 1)) 0 Fin.instOfNat) = h 0 := by
grind
```
* [#10324](https://github.com/leanprover/lean4/pull/10324) disables an unused instance that causes expensive type class
searches.
* [#10325](https://github.com/leanprover/lean4/pull/10325) implements model-based theory combination for types `A` which
implement the `ToInt` interface. Examples:
```lean
example {C : Type} (h : Fin 4 → C) (x : Fin 4)
: 3 ≤ x → x ≤ 3 → h x = h (-1) := by
grind
* [#10326](https://github.com/leanprover/lean4/pull/10326) fixes a performance issue in `grind linarith`. It was creating
unnecessary `NatModule`/`IntModule` structures for commutative rings
without an order. This kind of type should be handled by `grind ring`
only.
* [#10331](https://github.com/leanprover/lean4/pull/10331) implements `mkNoConfusionImp` in Lean rather than in C. This
reduces our reliance on C, and may bring performance benefits from not
reducing `noConfusionType` during elaboration time (it still gets
reduced by the kernel when type-checking).
* [#10332](https://github.com/leanprover/lean4/pull/10332) ensures that the infotree recognizes `Classical.propDecidable`
as an instance, when below a `classical` tactic.
* [#10335](https://github.com/leanprover/lean4/pull/10335) fixes the nested proof term detection in `grind`. It must check
whether the gadget `Grind.nestedProof` is over-applied.
* [#10342](https://github.com/leanprover/lean4/pull/10342) implements a new E-matching pattern inference procedure that is
faithful to the behavior documented in the reference manual regarding
minimal indexable subexpressions. The old inference procedure was
failing to enforce this condition. For example, the manual documents
`[grind ->]` as follows
* [#10373](https://github.com/leanprover/lean4/pull/10373) adds a `pp.unicode` option and a `unicode("→", "->")` syntax
description alias for the lower-level `unicodeSymbol "→" "->"` parser.
The syntax is added to the `notation` command as well. When `pp.unicode`
is true (the default) then the first form is used when pretty printing,
and otherwise the second ASCII form is used. A variant, `unicode("→",
"->", preserveForPP)` causes the `->` form to be preferred; delaborators
can insert `→` directly into the syntax, which will be pretty printed
as-is; this allows notations like `fun` to use custom options such as
`pp.unicode.fun` to opt into the unicode form when pretty printing.
## Library
* [#7858](https://github.com/leanprover/lean4/pull/7858) implements the fast circuit for overflow detection in unsigned
multiplication used by Bitwuzla and proposed in:
https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=987767
* [#9127](https://github.com/leanprover/lean4/pull/9127) makes `saveModuleData` throw an IO.Error instead of panicking,
if given something that cannot be serialized. This doesn't really matter
for saving modules, but is handy when writing tools to save auxiliary
data in olean files via Batteries' `pickle`.
* [#9560](https://github.com/leanprover/lean4/pull/9560) fixes the `forIn` function, that previously caused the resulting
Promise to be dropped without a value when an exception was thrown
inside of it. It also corrects the parameter order of the `background`
function.
* [#9599](https://github.com/leanprover/lean4/pull/9599) adds the type `Std.Internal.Parsec.Error`, which contains the
constructors `.eof` (useful for checking if parsing failed due to not
having enough input and then retrying when more input arrives that is
useful in the HTTP server) and `.other`, which describes other errors.
It also adds documentation to many functions, along with some new
functions to the `ByteArray` Parsec, such as `peekWhen?`, `octDigit`,
`takeWhile`, `takeUntil`, `skipWhile`, and `skipUntil`.
* [#9632](https://github.com/leanprover/lean4/pull/9632) adds lemmas for the `TreeMap` operations `filter`, `map` and
`filterMap`. These lemmas existed already for hash maps and are simply
ported over from there.
* [#9685](https://github.com/leanprover/lean4/pull/9685) verifies `toArray` and related functions for hashmaps.
* [#9797](https://github.com/leanprover/lean4/pull/9797) provides the means to quickly provide all the order instances
associated with some high-level order structure (preorder, partial
order, linear preorder, linear order). This can be done via the factory
functions `PreorderPackage.ofLE`, `PartialOrderPackage.ofLE`,
`LinearPreorderPackage.ofLE` and `LinearOrderPackage.ofLE`.
* [#9908](https://github.com/leanprover/lean4/pull/9908) makes `IsPreorder`, `IsPartialOrder`, `IsLinearPreorder` and
`IsLinearOrder` extend `BEq` and `Ord` as appropriate, adds the
`LawfulOrderBEq` and `LawfulOrderOrd` type classes relating `BEq` and
`Ord` to `LE`, and adds many lemmas and instances.
* [#9916](https://github.com/leanprover/lean4/pull/9916) provides factories that derive order type classes in bulk, given
an `Ord` instance. If present, existing instances are preferred over
those derived from `Ord`. It is possible to specify any instance
manually if desired.
* [#9924](https://github.com/leanprover/lean4/pull/9924) fixes examples in the documentation for `PostCond`.
* [#9931](https://github.com/leanprover/lean4/pull/9931) implements `Std.Do.Triple.mp`, enabling users to compose two
specifications for the same program.
* [#9949](https://github.com/leanprover/lean4/pull/9949) allows most of the `List.lookup` lemmas to be used when
`LawfulBEq α` is not available.
* [#9957](https://github.com/leanprover/lean4/pull/9957) upstreams the definition of Rat from Batteries, for use in our
planned interval arithmetic tactic.
* [#9967](https://github.com/leanprover/lean4/pull/9967) removes local `Triple` notation from SpecLemmas.lean to work
around a bug that breaks the stage2 build.
* [#9979](https://github.com/leanprover/lean4/pull/9979) replaces `Std.Internal.Rat` with the new public `Rat` upstreamed
from Batteries.
* [#9987](https://github.com/leanprover/lean4/pull/9987) improves the tactic for proving that elements of a `Nat`-based
`PRange` are in-bounds by relying on the `omega` tactic.
* [#9993](https://github.com/leanprover/lean4/pull/9993) defines the dyadic rationals, showing they are an ordered ring
embedding into the rationals. We will use this for future interval
arithmetic tactics.
* [#9999](https://github.com/leanprover/lean4/pull/9999) reduces the number of `Nat.Bitwise` grind annotations we have
the deal with distributivity. The new smaller set encourages `grind` to
rewrite into DNF. The old behaviour just resulted in saturating up to
the instantiation limits.
* [#10000](https://github.com/leanprover/lean4/pull/10000) removes a `grind` annotation that fired on all `Option.map`s,
causing an avalanche of instantiations.
* [#10005](https://github.com/leanprover/lean4/pull/10005) shortens the work necessary to make a type compatible with the
polymorphic range notation. In the concrete case of `Nat`, it reduces
the required lines of code from 150 to 70.
* [#10015](https://github.com/leanprover/lean4/pull/10015) exposes the bodies of `Name.append`, `Name.appendCore`, and
`Name.hasMacroScopes`. This enables proof by reflection of the
concatenation of name literals when using the module system.
* [#10018](https://github.com/leanprover/lean4/pull/10018) derives `BEq` and `Hashable` for `Lean.Import`. Lake already did
this later, but it now done when defining `Import`.
* [#10019](https://github.com/leanprover/lean4/pull/10019) adds `@[expose]` to `Lean.ParserState.setPos`. This makes it
possible to prove in-boundedness for a state produced by `setPos` for
functions like `next'` and `get'` without needing to `import all`.
* [#10024](https://github.com/leanprover/lean4/pull/10024) adds useful declarations to the `LawfulOrderMin/Max` and
`LawfulOrderLeftLeaningMin/Max` API. In particular, it introduces
`.leftLeaningOfLE` factories for `Min` and `Max`. It also renames
`LawfulOrderMin/Max.of_le` to .of_le_min_iff` and `.of_max_le_iff` and
introduces a second variant with different arguments.
* [#10045](https://github.com/leanprover/lean4/pull/10045) implements the necessary type classes so that range notation
works for integers. For example, `((-2)...3).toList = [-2, -1, 0, 1, 2]
: List Int`.
* [#10049](https://github.com/leanprover/lean4/pull/10049) adds some background material needed for introducing the dyadic
rationals in #9993.
* [#10050](https://github.com/leanprover/lean4/pull/10050) fixes some naming issues in Data/Rat/Lemmas, and upstreams the
eliminator `numDenCasesOn` and its relatives.
* [#10059](https://github.com/leanprover/lean4/pull/10059) improves the names of definitions and lemmas in the polymorphic
range API. It also introduces a recommended spelling. For example, a
left-closed, right-open range is spelled `Rco` in analogy with Mathlib's
`Ico` intervals.
* [#10075](https://github.com/leanprover/lean4/pull/10075) contains lemmas about `Int` (minor amendments for BitVec and
Nat) that are being used in preparing the dyadics. This is all work of
@Rob23oba, which I'm pulling out of #9993 early to keep that one
manageable.
* [#10077](https://github.com/leanprover/lean4/pull/10077) upstreams lemmas about `Rat` from `Mathlib.Data.Rat.Defs` and
`Mathlib.Algebra.Order.Ring.Unbundled.Rat`, specifically enough to get
`Lean.Grind.Field Rat` and `Lean.Grind.OrderedRing Rat`. In addition to
the lemmas, instances for `Inv Rat`, `Pow Rat Nat` and `Pow Rat Int`
have been upstreamed.
* [#10107](https://github.com/leanprover/lean4/pull/10107) adds the `Lean.Grind.AddCommGroup` instance for `Rat`.
* [#10138](https://github.com/leanprover/lean4/pull/10138) adds lemmas about the `Dyadic.roundUp` and `Dyadic.roundDown`
operations.
* [#10159](https://github.com/leanprover/lean4/pull/10159) adds `nodup_keys` lemmas as corollaries of existing
`distinct_keys` to all `Map` variants.
* [#10162](https://github.com/leanprover/lean4/pull/10162) removes `grind →` annotations that fire too often, unhelpfully.
It would be nice for `grind` to instantiate these lemmas, but only if
they already see `xs ++ ys` and `#[]` in the same equivalence class, not
just as soon as it sees `xs ++ ys`.
* [#10163](https://github.com/leanprover/lean4/pull/10163) removes some (hopefully) unnecessary `grind` annotations that
cause instantiation explosions.
* [#10173](https://github.com/leanprover/lean4/pull/10173) removes the `extends Monad` from `MonadAwait` and `MonadAsync`
to avoid underdetermined instances.
* [#10182](https://github.com/leanprover/lean4/pull/10182) adds lemmas about `Nat.fold` and `Nat.foldRev` on sums, to match
the existing theorems about `dfold` and `dfoldRev`.
* [#10194](https://github.com/leanprover/lean4/pull/10194) adds the inverse of a dyadic rational, at a given precision, and
characterising lemmas. Also cleans up various parts of the `Int.DivMod`
and `Rat` APIs, and proves some characterising lemmas about
`Rat.toDyadic`.
* [#10216](https://github.com/leanprover/lean4/pull/10216) fixes #10193.
* [#10224](https://github.com/leanprover/lean4/pull/10224) generalizes the monadic operations for `HashMap`, `TreeMap`, and
`HashSet` to work for `m : Type u → Type v`.
* [#10227](https://github.com/leanprover/lean4/pull/10227) adds `@[grind]` annotations (nearly all `@[grind =]` annotations
parallel to existing `@[simp]`s) for `ReaderT`, `StateT`, `ExceptT`.
* [#10244](https://github.com/leanprover/lean4/pull/10244) adds more lemmas about the `toList` and `toArray` functions on
ranges and iterators. It also renames `Array.mem_toArray` into
`List.mem_toArray`.
* [#10247](https://github.com/leanprover/lean4/pull/10247) adds missing the lemmas `ofList_eq_insertMany_empty`,
`get?_eq_some_iff`, `getElem?_eq_some_iff` and `getKey?_eq_some_iff` to
all container types.
* [#10250](https://github.com/leanprover/lean4/pull/10250) fixes a bug in the `LinearOrderPackage.ofOrd` factory. If there
is a `LawfulEqOrd` instance available, it should automatically use it
instead of requiring the user to provide the `eq_of_compare` argument to
the factory. The PR also solves a hygiene-related problem making the
factories fail when `Std` is not open.
* [#10303](https://github.com/leanprover/lean4/pull/10303) adds range support to`BitVec` and the `UInt*` types. This means
that it is now possible to write, for example, `for i in (1 : UInt8)...5
do`, in order to loop over the values 1, 2, 3 and 4 of type `UInt8`.
* [#10341](https://github.com/leanprover/lean4/pull/10341) moves the definitions and basic facts about `Function.Injective`
and `Function.Surjective` up from Mathlib. We can do a better job of
arguing via injectivity in `grind` if these are available.
## Compiler
* [#9631](https://github.com/leanprover/lean4/pull/9631) makes `IO.RealWorld` opaque. It also adds a new compiler -only
`lcRealWorld` constant to represent this type within the compiler. By
default, an opaque type definition is treated like `lcAny`, whereas we
want a more efficient representation. At the moment, this isn't a big
difference, but in the future we would like to completely erase
`IO.RealWorld` at runtime.
* [#9922](https://github.com/leanprover/lean4/pull/9922) changes `internalizeCode` to replace all substitutions with
non-param-bound fvars in `Expr`s (which are all types) with `lcAny`,
preserving the invariant that there are no such dependencies. The
violation of this invariant across files caused test failures in a
pending PR, but it is difficult to write a direct test for it. In the
future, we should probably change the LCNF checker to detect this.
* [#9972](https://github.com/leanprover/lean4/pull/9972) fixes an issue when running Mathlib's `FintypeCat` as code,
where an erased type former is passed to a polymorphic function. We were
lowering the arrow type to`object`, which conflicts with the runtime
representation of an erased value as a tagged scalar.
* [#9977](https://github.com/leanprover/lean4/pull/9977) adds support for compilation of `casesOn` recursors of
subsingleton predicates.
* [#10023](https://github.com/leanprover/lean4/pull/10023) adds support for correctly handling computations on fields in
`casesOn` for inductive predicates that support large elimination. In
any such predicate, the only relevant fields allowed are those that are
also used as an index, in which case we can find the supplied index and
use that term instead.
* [#10032](https://github.com/leanprover/lean4/pull/10032) changes the handling of overapplied constructors when lowering
LCNF to IR from a (slightly implicit) assertion failure to producing
`unreachable`. Transformations on inlined unreachable code can produce
constructor applications with additional arguments.
* [#10040](https://github.com/leanprover/lean4/pull/10040) changes the `toMono` pass to replace decls with their `_redArg`
equivalent, which has the consequence of not considering arguments
deemed useless by the `reduceArity` pass for the purposes of the
`noncomputable` check.
* [#10070](https://github.com/leanprover/lean4/pull/10070) fixes the compilation of `noConfusion` by repairing an oversight
made when porting this code from the old compiler. The old compiler only
repeatedly expanded the major for each non-`Prop` field of the inductive
under consideration, mirroring the construction of `noConfusion` itself,
whereas the new compiler erroneously counted all fields.
* [#10133](https://github.com/leanprover/lean4/pull/10133) fixes compatibility of Lean-generated executables with Unicode
file system paths on Windows
* [#10214](https://github.com/leanprover/lean4/pull/10214) fixes #10213.
* [#10256](https://github.com/leanprover/lean4/pull/10256) corrects a mistake in `toIR` where it could over-apply a
function that has an IR decl but no mono decl.
* [#10355](https://github.com/leanprover/lean4/pull/10355) changes `toLCNF` to convert `.proj` for builtin types to use
projection functions instead.
## Pretty Printing
* [#10122](https://github.com/leanprover/lean4/pull/10122) adds support for pretty printing using generalized field
notation (dot notation) for private definitions on public types. It also
modifies dot notation elaboration to resolve names after removing the
private prefix, which enables using dot notation for private definitions
on private imported types.
* [#10373](https://github.com/leanprover/lean4/pull/10373) adds a `pp.unicode` option and a `unicode("→", "->")` syntax
description alias for the lower-level `unicodeSymbol "→" "->"` parser.
The syntax is added to the `notation` command as well. When `pp.unicode`
is true (the default) then the first form is used when pretty printing,
and otherwise the second ASCII form is used. A variant, `unicode("→",
"->", preserveForPP)` causes the `->` form to be preferred; delaborators
can insert `→` directly into the syntax, which will be pretty printed
as-is; this allows notations like `fun` to use custom options such as
`pp.unicode.fun` to opt into the unicode form when pretty printing.
* [#10374](https://github.com/leanprover/lean4/pull/10374) adds the options `pp.piBinderNames` and
`pp.piBinderNames.hygienic`. Enabling `pp.piBinderNames` causes
non-dependent pi binder names to be pretty printed, rather than be
omitted. When `pp.piBinderNames.hygienic` is false (the default) then
only non-hygienic such biner names are pretty printed. Setting `pp.all`
enables `pp.piBinderNames` if it is not otherwise explicitly set.
## Documentation
* [#9956](https://github.com/leanprover/lean4/pull/9956) adds additional information to the `let` and `have` tactic
docstrings about opaqueness, when to use each, and associated tactics.
## Server
* [#9966](https://github.com/leanprover/lean4/pull/9966) adjusts the "try this" widget to be rendered as a widget message
under 'Messages', not a separate widget under a 'Suggestions' section.
The main benefit of this is that the message of the widget is not
duplicated between 'Messages' and 'Suggestions'.
* [#10047](https://github.com/leanprover/lean4/pull/10047) ensures that hovering over `match` displays the type of the
match.
* [#10052](https://github.com/leanprover/lean4/pull/10052) fixes a bug that caused the Lean server process tree to survive
the closing of VS Code.
* [#10249](https://github.com/leanprover/lean4/pull/10249) speeds up auto-completion by a factor of ~3.5x through various
performance improvements in the language server. On one machine, with
`import Mathlib`, completing `i` used to take 3200ms and now instead
yields a result in 920ms.
## Lake
* [#9749](https://github.com/leanprover/lean4/pull/9749) refactors the Lake codebase to use the new module system
throughout. Every module in `Lake` is now a `module`.
* [#10276](https://github.com/leanprover/lean4/pull/10276) moves the `verLit` syntax into the `Lake.DSL` namespace to be
consistent with other code found in `Lake.DSL`.
## Other
* [#10043](https://github.com/leanprover/lean4/pull/10043) allows Lean's parser to run with a final position prior to the
end of the string, so it can be invoked on a sub-region of the input.
* [#10217](https://github.com/leanprover/lean4/pull/10217) ensures `@[init]` declarations such as from `initialize` are run
in the order they were declared on import.
* [#10262](https://github.com/leanprover/lean4/pull/10262) adds a new option `maxErrors` that limits the number of errors
printed from a single `lean` run, defaulting to 100. Processing is
aborted when the limit is reached, but this is tracked only on a
per-command level.
```` |
reference-manual/Manual/BuildTools/Lake.lean | import VersoManual
import Lean.Parser.Command
import Lake.Build.Package
import Lake.Build.Library
import Lake.Build.Module
import Manual.Meta
import Manual.BuildTools.Lake.CLI
import Manual.BuildTools.Lake.Config
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
set_option guard_msgs.diff true
open Lean.Elab.Tactic.GuardMsgs.WhitespaceMode
#doc (Manual) "Lake" =>
%%%
tag := "lake"
%%%
Lake is the standard Lean build tool.
It is responsible for:
* Configuring builds and building Lean code
* Fetching and building external dependencies
* Integrating with Reservoir, the Lean package server
* Running tests, linters, and other development workflows
Lake is extensible.
It provides a rich API that can be used to define incremental build tasks for software artifacts that are not written in Lean, to automate administrative tasks, and to integrate with external workflows.
For build configurations that do not need these features, Lake provides a declarative configuration language that can be written either in TOML or as a Lean file.
This section describes Lake's {ref "lake-cli"}[command-line interface], {ref "lake-config"}[configuration files], and {ref "lake-api"}[internal API].
All three share a set of concepts and terminology.
# Concepts and Terminology
%%%
tag := "lake-vocab"
%%%
A {deftech}_package_ is the basic unit of Lean code distribution.
A single package may contain multiple libraries or executable programs.
A package consist of a directory that contains a {tech}[package configuration] file together with source code.
Packages may {deftech}_require_ other packages, in which case those packages' code (more specifically, their {tech}[targets]) are made available.
The {deftech}_direct dependencies_ of a package are those that it requires, and the {deftech}_transitive dependencies_ are the direct dependencies of a package together with their transitive dependencies.
Packages may either be obtained from [Reservoir](https://reservoir.lean-lang.org/){TODO}[xref chapter], the Lean package repository, or from a manually-specified location.
{deftech}_Git dependencies_ are specified by a Git repository URL along with a revision (branch, tag, or hash) and must be cloned locally prior to build, while local {deftech}_path dependencies_ are specified by a path relative to the package's directory.
:::paragraph
A {deftech}_workspace_ is a directory on disk that contains a working copy of a {tech}[package]'s source code and the source code of all {tech}[transitive dependencies] that are not specified as local paths.
The package for which the workspace was created is the {deftech}_root package_.
The workspace also contains any built {tech}[artifacts] for the package, enabling {tech}[incremental builds].
Dependencies and artifacts do not need to be present for a directory to be considered a workspace; commands such as {lake}`update` and {lake}`build` produce them if they are missing.
Lake is typically used in a workspace.{margin}[{lake}`init` and {lake}`new`, which create workspaces, are exceptions.]
Workspaces typically have the following layout:
* `lean-toolchain`: The {tech}[toolchain file].
* `lakefile.toml` or `lakefile.lean`: The {tech}[package configuration] file for the root package.
* `lake-manifest.json`: The root package's {tech}[manifest].
* `.lake/`: Intermediate state managed by Lake, such as built {tech}[artifacts] and dependency source code.
* `.lake/lakefile.olean`: The root package's configuration, cached.
* `.lake/packages/`: The workspace's {deftech}_package directory_, which contains copies of all non-local transitive dependencies of the root package, with their built artifacts in their own `.lake` directories.
* `.lake/build/`: The {deftech}_build directory_, which contains built artifacts for the root package:
* `.lake/build/bin`: The package's {deftech}_binary directory_, which contains built executables.
* `.lake/build/lib`: The package's _library directory_, which contains built libraries and {tech}[`.olean` files].
* `.lake/build/ir`: The package's intermediate result directory, which contains generated intermediate artifacts, primarily C code.
:::
:::figure "Workspace Layout" (tag :="workspace-layout")

:::
:::paragraph
A {deftech}_package configuration_ file specifies the dependencies, settings, and targets of a package.
Packages can specify configuration options that apply to all their contained targets.
They can be written in two formats:
* The {ref "lake-config-toml"}[TOML format] (`lakefile.toml`) is used for fully declarative package configurations.
* The {ref "lake-config-lean"}[Lean format] (`lakefile.lean`) additionally supports the use of Lean code to configure the package in ways not supported by the declarative options.
:::
A {deftech}_manifest_ tracks the specific versions of other packages that are used in a package.
Together, a manifest and a {tech}[package configuration] file specify a unique set of transitive dependencies for the package.
Before building, Lake synchronizes the local copy of each dependency with the version specified in the manifest.
If no manifest is available, Lake fetches the latest matching versions of each dependency and creates a manifest.
It is an error if the package names listed in the manifest do not match those used by the package; the manifest must be updated using {lake}`update` prior to building.
Manifests should be considered part of the package's code and should normally be checked into source control.
:::paragraph
A {deftech}_target_ represents an output that can be requested by a user.
A persistent build output, such as object code, an executable binary, or an {tech}[`.olean` file], is called an {deftech}_artifact_.
In the process of producing an artifact, Lake may need to produce further artifacts; for example, compiling a Lean program into an executable requires that it and its dependencies be compiled to object files, which are themselves produced from C source files, which result from elaborating Lean sourcefiles and producing {tech}[`.olean` files].
Each link in this chain is a target, and Lake arranges for each to be built in turn.
At the start of the chain are the {deftech}_initial targets_:
* {tech}_Packages_ are units of Lean code that are distributed as a unit.
* {deftech}_Libraries_ are collections of Lean {tech}[module]s, organized hierarchically under one or more {deftech}_module roots_.
* {deftech}_Executables_ consist of a _single_ module that defines `main`.
* {deftech}_External libraries_ are non-Lean *static* libraries that will be linked to the binaries of the package and its dependents, including both their shared libraries and executables.
* {deftech}_Custom targets_ contain arbitrary code to run a build, written using Lake's internal API.
In addition to their Lean code, packages, libraries, and executables contain configuration settings that affect subsequent build steps.
Packages may specify a set of {deftech}_default targets_.
Default targets are the initial targets in the package that are to be built in contexts where a package is specified but specific targets are not.
:::
:::paragraph
The {deftech}_log_ contains information produced during a build.
Logs are saved so they can be replayed during {tech}[incremental builds].
Messages in the log have four levels, ordered by severity:
1. _Trace messages_ contain internal build details that are often specific to the machine on which the build is running, including the specific invocations of Lean and other tools that are passed to the shell.
2. _Informational messages_ contain general informational output that is not expected to indicate a problem with the code, such as the results of a {keywordOf Lean.Parser.Command.eval}`#eval` command.
3. _Warnings_ indicate potential problems, such as unused variable bindings.
4. _Errors_ explain why parsing and elaboration could not complete.
By default, trace messages are hidden and the others are shown.
The threshold can be adjusted using the {lakeOpt}`--log-level` option, the {lakeOpt}`--verbose` flag, or the {lakeOpt}`--quiet` flag.
:::
## Builds
:::paragraph
Producing a desired {tech}[artifact], such as a {tech}[`.olean` file] or an executable binary, is called a {deftech}_build_.
Builds are triggered by the {lake}`build` command or by other commands that require an artifact to be present, such as {lake}`exe`.
A build consists of the following steps:
: {deftech (key := "configure package")}[Configuring] the package
If {tech}[package configuration] file is newer than the cached configuration file `lakefile.olean`, then the package configuration is re-elaborated.
This also occurs when the cached file is missing or when the {lakeOpt}`--reconfigure` or {lakeOpt}`-R` flag is provided.
Changes to options using {lakeOpt}`-K` do not trigger re-elaboration of the configuration file; {lakeOpt}`-R` is necessary in these cases.
: Computing dependencies
The set of artifacts that are required to produce the desired output are determined, along with the {tech}[targets] and {tech}[facets] that produce them.
This process is recursive, and the result is a _graph_ of dependencies.
The dependencies in this graph are distinct from those declared for a package: packages depend on other packages, while build targets depend on other build targets, which may be in the same package or in a different one.
One facet of a given target may depend on other facets of the same target.
Lake automatically analyzes the imports of Lean modules to discover their dependencies, and the {tomlField Lake.LeanLibConfig}`extraDepTargets` field can be used to add additional dependencies to a target.
: Replaying traces
Rather than rebuilding everything in the dependency graph from scratch, Lake uses saved {deftech}_trace files_ to determine which artifacts require building.
During a build, Lake records which source files or other artifacts were used to produce each artifact, saving a hash of each input; these {deftech}_traces_ are saved in the {tech}[build directory].{margin}[More specifically, each artifact's trace file contains a Merkle tree hash mixture of its inputs' hashes.]
If the inputs are all unmodified, then the corresponding artifact is not rebuilt.
Trace files additionally record the {tech}[log] from each build task; these outputs are replayed as if the artifact had been built anew.
Reusing prior build products when possible is called an {deftech}_incremental build_.
: Building artifacts
When all unmodified dependencies in the dependency graph have been replayed from their trace files, Lake proceeds to build each artifact.
This involves running the appropriate build tool on the input files and saving the artifact and its trace file, as specified in the corresponding facet.
:::
Lake uses two separate hash algorithms.
Text files are hashed after normalizing newlines, so that files that differ only by platform-specific newline conventions are hashed identically.
Other files are hashed without any normalization.
Along with the trace files, Lean caches input hashes.
Whenever an artifact is built, its hash is saved in a separate file that can be re-read instead of computing the hash from scratch.
This is a performance optimization.
This feature can be disabled, causing all hashes to be recomputed from their inputs, using the {lakeOpt}`--rehash` command-line option.
:::paragraph
During a build, the following directories are provided to the underlying build tools:
* The {deftech}_source directory_ contains Lean source code that is available for import.
* The {deftech}_library directories_ contain {tech}[`.olean` files] along with the shared and static libraries that are available for linking; it normally consists of the {tech}[root package]'s library directory (found in `.lake/build/lib`), the library directories for the other packages in the workspace, the library directory for the current Lean toolchain, and the system library directory.
* The {deftech}_Lake home_ is the directory in which Lake is installed, including binaries, source code, and libraries.
The libraries in the Lake home are needed to elaborate Lake configuration files, which have access to the full power of Lean.
:::
## Facets
%%%
tag := "lake-facets"
%%%
A {deftech}_facet_ describes the production of a target from another.
Conceptually, any target may have facets.
However, executables, external libraries, and custom targets provide only a single implicit facet.
Packages, libraries, and modules have multiple facets that can be requested by name when invoking {lake}`build` to select the corresponding target.
When no facet is explicitly requested, but an initial target is designated, {lake}`build` produces the initial target's {deftech}_default facet_.
Each type of initial target has a corresponding default facet (e.g. producing an executable binary from an executable target or building a package's {tech}[default targets]); other facets may be explicitly requested in the {tech}[package configuration] or via Lake's {ref "lake-cli"}[command-line interface].
Lake's internal API may be used to write custom facets.
```lakeHelp "build"
Build targets
USAGE:
lake build [<targets>...] [-o <mappings>]
A target is specified with a string of the form:
[@[<package>]/][<target>|[+]<module>][:<facet>]
You can also use the source path of a module as a target. For example,
lake build Foo/Bar.lean:o
will build the Lean module (within the workspace) whose source file is
`Foo/Bar.lean` and compile the generated C file into a native object file.
The `@` and `+` markers can be used to disambiguate packages and modules
from file paths or other kinds of targets (e.g., executables or libraries).
LIBRARY FACETS: build the library's ...
leanArts (default) Lean artifacts (*.olean, *.ilean, *.c files)
static static artifact (*.a file)
shared shared artifact (*.so, *.dll, or *.dylib file)
MODULE FACETS: build the module's ...
deps dependencies (e.g., imports, shared libraries, etc.)
leanArts (default) Lean artifacts (*.olean, *.ilean, *.c files)
olean OLean (binary blob of Lean data for importers)
ilean ILean (binary blob of metadata for the Lean LSP server)
c compiled C file
bc compiled LLVM bitcode file
c.o compiled object file (of its C file)
bc.o compiled object file (of its LLVM bitcode file)
o compiled object file (of its configured backend)
dynlib shared library (e.g., for `--load-dynlib`)
TARGET EXAMPLES: build the ...
a default facet(s) of target `a`
@a default target(s) of package `a`
+A default facet(s) of module `A`
@/a default facet(s) of target `a` of the root package
@a/b default facet(s) of target `b` of package `a`
@a/+A:c C file of module `A` of package `a`
:foo facet `foo` of the root package
A bare `lake build` command will build the default target(s) of the root
package. Package dependencies are not updated during a build.
With the Lake cache enabled, the `-o` option will cause Lake to track the
input-to-outputs mappings of targets in the root package touched during the
build and write them to the specified file at the end of the build. These
mappings can then be used to upload build artifacts to a remote cache with
`lake cache put`.
```
::::paragraph
The facets available for packages are:
```lean -show
-- Always keep this in sync with the description below. It ensures that the list is complete.
/--
info: #[`package.barrel, `package.cache, `package.deps, `package.extraDep, `package.optBarrel, `package.optCache,
`package.optRelease, `package.release, `package.transDeps]
-/
#guard_msgs in
#eval Lake.initPackageFacetConfigs.toList.map (·.1) |>.toArray |>.qsort (·.toString < ·.toString)
```
: `extraDep`
The default facets of the package's extra dependency targets, specified in the {tomlField Lake.PackageConfig}`extraDepTargets` field.
: `deps`
The package's {tech}[direct dependencies].
: `transDeps`
The package's {tech}[transitive dependencies], topologically sorted.
: `optCache`
A package's optional cached build archive (e.g., from Reservoir or GitHub).
Will *not* cause the whole build to fail if the archive cannot be fetched.
: `cache`
A package's cached build archive (e.g., from Reservoir or GitHub).
Will cause the whole build to fail if the archive cannot be fetched.
: `optBarrel`
A package's optional cached build archive (e.g., from Reservoir or GitHub).
Will *not* cause the whole build to fail if the archive cannot be fetched.
: `barrel`
A package's cached build archive (e.g., from Reservoir or GitHub).
Will cause the whole build to fail if the archive cannot be fetched.
: `optRelease`
A package's optional build archive from a GitHub release.
Will *not* cause the whole build to fail if the release cannot be fetched.
: `release`
A package's build archive from a GitHub release.
Will cause the whole build to fail if the archive cannot be fetched.
::::
```lean -show
-- Always keep this in sync with the description below. It ensures that the list is complete.
/--
info: [`lean_lib.extraDep, `lean_lib.leanArts, `lean_lib.static.export, `lean_lib.shared, `lean_lib.modules, `lean_lib.static,
`lean_lib.default]
-/
#guard_msgs in
#eval Lake.initLibraryFacetConfigs.toList.map (·.1)
```
:::paragraph
The facets available for libraries are:
: `leanArts`
The artifacts that the Lean compiler produces for the library or executable ({tech (key := ".olean files")}`*.olean`, `*.ilean`, and `*.c` files).
: `static`
The static library produced by the C compiler from the `leanArts` (that is, a `*.a` file).
: `static.export`
The static library produced by the C compiler from the `leanArts` (that is, a `*.a` file), with exported symbols.
: `shared`
The shared library produced by the C compiler from the `leanArts` (that is, a `*.so`, `*.dll`, or `*.dylib` file, depending on the platform).
: `extraDep`
A Lean library's {tomlField Lake.LeanLibConfig}`extraDepTargets` and those of its package.
:::
:::paragraph
Executables have a single `exe` facet that consists of the executable binary.
:::
```lean -show
-- Always keep this in sync with the description below. It ensures that the list is complete.
/--
info: module.bc
module.bc.o
module.c
module.c.o
module.c.o.export
module.c.o.noexport
module.deps
module.dynlib
module.exportInfo
module.header
module.ilean
module.importAllArts
module.importArts
module.importInfo
module.imports
module.input
module.ir
module.lean
module.leanArts
module.o
module.o.export
module.o.noexport
module.olean
module.olean.private
module.olean.server
module.precompileImports
module.setup
module.transImports
-/
#guard_msgs in
#eval Lake.initModuleFacetConfigs.toList.toArray.map (·.1) |>.qsort (·.toString < ·.toString) |>.forM (IO.println)
```
:::paragraph
The facets available for modules are:
: `lean`
The module's Lean source file.
: `leanArts` (default)
The module's Lean artifacts (`*.olean`, `*.ilean`, `*.c` files).
: `deps`
The module's dependencies (e.g., imports or shared libraries).
: `olean`
The module's {tech}[`.olean` file]. {TODO}[Once module system lands fully, add docs for `olean.private` and `olean.server`]
: `ilean`
The module's `.ilean` file, which is metadata used by the Lean language server.
: `header`
The parsed module header of the module's source file.
: `input`
The module's processed Lean source file. Combines tracing the file with parsing its header.
: `imports`
The immediate imports of the Lean module, but not the full set of transitive imports. {TODO}[Once the module system lands fully, add docs here for `module.importAllArts`, `module.importArts`]
: `precompileImports`
The transitive imports of the Lean module, compiled to object code.
: `transImports`
The transitive imports of the Lean module, as {tech}[`.olean` files].
: `allImports`
Both the immediate and transitive imports of the Lean module.
: `setup`
All of a module's dependencies: transitive local imports and shared libraries to be loaded with `--load-dynlib`.
Returns the list of shared libraries to load along with their search path.
: `ir`
The `.ir` file produced by `lean` (with the {ref "module-structure"}[experimental module system] enabled).
: `c`
The C file produced by the Lean compiler.
: `bc`
LLVM bitcode file, produced by the Lean compiler.
: `c.o`
The compiled object file, produced from the C file. On Windows, this is equivalent to `.c.o.noexport`, while it is equivalent to `.c.o.export` on other platforms.
: `c.o.export`
The compiled object file, produced from the C file, with Lean symbols exported.
: `c.o.noexport`
The compiled object file, produced from the C file, with Lean symbols exported.
: `bc.o`
The compiled object file, produced from the LLVM bitcode file.
: `o`
The compiled object file for the configured backend.
: `dynlib`
A shared library (e.g., for the Lean option `--load-dynlib`){TODO}[Document Lean command line options, and cross-reference from here].
:::
## Scripts
%%%
tag := "lake-scripts"
%%%
Lake {tech}[package configuration] files may include {deftech}_Lake scripts_, which are embedded programs that can be executed from the command line.
Scripts are intended to be used for project-specific tasks that are not already well-served by Lake's other features.
While ordinary executable programs are run in the {name}`IO` {tech}[monad], scripts are run in {name Lake.ScriptM}`ScriptM`, which extends {name}`IO` with information about the workspace.
Because they are Lean definitions, Lake scripts can only be defined in the Lean configuration format.
:::::TODO
Restore the following once we can import enough of Lake to elaborate it
````
```lean -show
section
open Lake DSL
```
:::example "Listing Dependencies"
This Lake script lists all the transitive dependencies of the root package, along with their Git URLs, in alphabetical order.
Similar scripts could be used to check declared licenses, discover which dependencies have test drivers configured, or compute metrics about the transitive dependency set over time.
```lean
script "list-deps" := do
let mut results := #[]
for p in (← getWorkspace).packages do
if p.name ≠ (← getWorkspace).root.name then
results := results.push (p.name.toString, p.remoteUrl)
results := results.qsort (·.1 < ·.1)
IO.println "Dependencies:"
for (name, url) in results do
IO.println s!"{name}:\t{url}"
return 0
```
:::
```lean -show
end
```
````
:::::
## Test and Lint Drivers
%%%
tag := "test-lint-drivers"
%%%
A {deftech}_test driver_ is responsible for running the tests for a package.
Test drivers may be executable targets or {tech}[Lake scripts], in which case the {lake}`test` command runs them, or they may be libraries, in which case {lake}`test` causes them to be elaborated, with the expectation that test failures are registered as elaboration failures.
Similarly, a {deftech}_lint driver_ is responsible for checking the code for stylistic issues.
Lint drivers may be executables or scripts, which are run by {lake}`lint`.
A test or lint driver can be configured by either setting the {tomlField Lake.PackageConfig}`testDriver` or {tomlField Lake.PackageConfig}`lintDriver` package configuration options or by tagging a script, executable, or library with the `test_driver` or `lint_driver` attribute in a Lean-format configuration file.
A definition in a dependency can be used as a test or lint driver by using the `<pkg>/<name>` syntax for the appropriate configuration option.
:::TODO
Restore the `{attr}` role for `test_driver` and `lint_driver` above. Right now, importing the attributes crashes the compiler.
:::
## GitHub Release Builds
%%%
tag := "lake-github"
%%%
Lake supports uploading and downloading build artifacts (i.e., the archived build directory) to/from the GitHub releases of packages.
This enables end users to fetch pre-built artifacts from the cloud without needed to rebuild the package from source themselves.
The {envVar}`LAKE_NO_CACHE` environment variable can be used to disable this feature.
### Downloading
To download artifacts, one should configure the package options `releaseRepo` and `buildArchive` to point to the GitHub repository hosting the release and the correct artifact name within it (if the defaults are not sufficient).
Then, set `preferReleaseBuild := true` to tell Lake to fetch and unpack it as an extra package dependency.
Lake will only fetch release builds as part of its standard build process if the package wanting it is a dependency (as the root package is expected to modified and thus not often compatible with this scheme).
However, should one wish to fetch a release for a root package (e.g., after cloning the release's source but before editing), one can manually do so via `lake build :release`.
Lake internally uses `curl` to download the release and `tar` to unpack it, so the end user must have both tools installed in order to use this feature.
If Lake fails to fetch a release for any reason, it will move on to building from the source.
This mechanism is not technically limited to GitHub: any Git host that uses the same URL scheme works as well.
### Uploading
To upload a built package as an artifact to a GitHub release, Lake provides the {lake}`upload` command as a convenient shorthand.
This command uses `tar` to pack the package's build directory into an archive and uses `gh release upload` to attach it to a pre-existing GitHub release for the specified tag.
Thus, in order to use it, the package uploader (but not the downloader) needs to have `gh`, the GitHub CLI, installed and in `PATH`.
## Artifact Caches
%%%
tag := "lake-cache"
%%%
*This is an experimental feature that is still undergoing development.*
Lake supports a {deftech (key := "local cache")}_local artifact cache_ that stores individual build products, tracking the complete set of inputs that gave rise to them.
Each {tech}[toolchain] has its own cache because intermediate build products are not compatible between toolchain versions.
However, a toolchain's cache is shared between all local {tech}[workspaces] that use it, so common dependencies don't need to be rebuilt.
If two separate workspaces with the same toolchain depend on the same package, then they can share each others' build products.
Because it is an experimental feature, the local cache is disabled by default.
It is only enabled when the {envVar}`LAKE_ARTIFACT_CACHE` environment variable is set to `true` or when the {TODO}[ref] `enableArtifactCache` field is set to `true` in the {ref "lake-config"}[configuration file].
### Remote Artifact Caches
%%%
tag := "lake-cache-remote"
%%%
Build products can be retrieved from remote cache servers and placed into the local cache.
This makes it possible to completely avoid local builds.
The {lake}`cache get` command is used to download artifacts into the local cache.
Compared to {ref "lake-github"}[GitHub release builds], the remote artifact cache is much more fine-grained.
It tracks build products at the level of individual source files, {tech}[`.olean` files], and object code, rather than at the level of entire packages.
### Mappings
When passed the `-o` option, {lake}`build` tracks the inputs used to generate each build product.
These are stored to a {deftech}_mappings file_ in JSON lines format, where each line of the file must be a valid JSON object.
A mappings file tracks a single build, and includes all intermediate and final build products for the workspace's {tech}[root package], but not for its dependencies.
This includes build products that were already up to date and not regenerated.
The {lake}`cache put` command uploads the build products in the mappings file to the remote from the local cache to the remote cache.
### Configuration
:::paragraph
Remote artifact caches are configured using the following environment variables:
* {envVar}`LAKE_CACHE_KEY`
* {envVar}`LAKE_CACHE_ARTIFACT_ENDPOINT`
* {envVar}`LAKE_CACHE_REVISION_ENDPOINT`
:::
{include 0 Manual.BuildTools.Lake.CLI}
{include 0 Manual.BuildTools.Lake.Config}
# Script API Reference
%%%
tag := "lake-api"
%%%
In addition to ordinary {lean}`IO` effects, Lake scripts have access to the Lake environment (which provides information about the current toolchain, such as the location of the Lean compiler) and the current workspace.
This access is provided in {name Lake.ScriptM}`ScriptM`.
{docstring Lake.ScriptM}
## Accessing the Environment
Monads that provide access to information about the current Lake environment (such as the locations of Lean, Lake, and other tools) have {name Lake.MonadLakeEnv}`MonadLakeEnv` instances.
This is true for all of the monads in the Lake API, including {name Lake.ScriptM}`ScriptM`.
{docstring Lake.MonadLakeEnv}
{docstring Lake.getLakeEnv}
{docstring Lake.getNoCache}
{docstring Lake.getTryCache}
{docstring Lake.getPkgUrlMap}
{docstring Lake.getElanToolchain}
### Search Path Helpers
{docstring Lake.getEnvLeanPath}
{docstring Lake.getEnvLeanSrcPath}
{docstring Lake.getEnvSharedLibPath}
### Elan Install Helpers
{docstring Lake.getElanInstall?}
{docstring Lake.getElanHome?}
{docstring Lake.getElan?}
### Lean Install Helpers
{docstring Lake.getLeanInstall}
{docstring Lake.getLeanSysroot}
{docstring Lake.getLeanSrcDir}
{docstring Lake.getLeanLibDir}
{docstring Lake.getLeanIncludeDir}
{docstring Lake.getLeanSystemLibDir}
{docstring Lake.getLean}
{docstring Lake.getLeanc}
{docstring Lake.getLeanSharedLib}
{docstring Lake.getLeanAr}
{docstring Lake.getLeanCc}
{docstring Lake.getLeanCc?}
### Lake Install Helpers
{docstring Lake.getLakeInstall}
{docstring Lake.getLakeHome}
{docstring Lake.getLakeSrcDir}
{docstring Lake.getLakeLibDir}
{docstring Lake.getLake}
## Accessing the Workspace
Monads that provide access to information about the current Lake workspace have {name Lake.MonadWorkspace}`MonadWorkspace` instances.
In particular, there are instances for {name Lake.ScriptM}`ScriptM` and {name Lake.LakeM}`LakeM`.
```lean -show
section
open Lake
#synth MonadWorkspace ScriptM
end
```
{docstring Lake.MonadWorkspace}
{docstring Lake.getRootPackage}
{docstring Lake.findPackageByName?}
{docstring Lake.findPackageByKey?}
{docstring Lake.findModule?}
{docstring Lake.findLeanExe?}
{docstring Lake.findLeanLib?}
{docstring Lake.findExternLib?}
{docstring Lake.getLeanPath}
{docstring Lake.getLeanSrcPath}
{docstring Lake.getSharedLibPath}
{docstring Lake.getAugmentedLeanPath}
{docstring Lake.getAugmentedLeanSrcPath }
{docstring Lake.getAugmentedSharedLibPath}
{docstring Lake.getAugmentedEnv} |
reference-manual/Manual/BuildTools/Elan.lean | import VersoManual
import Manual.Meta
import Manual.Meta.ElanCheck
import Manual.Meta.ElanCmd
import Manual.Meta.ElanOpt
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
open Lean.Elab.Tactic.GuardMsgs.WhitespaceMode
#doc (Manual) "Managing Toolchains with Elan" =>
%%%
tag := "elan"
shortContextTitle := "Elan"
%%%
Elan is the Lean toolchain manager.
It is responsible both for installing {tech}[toolchains] and for running their constituent programs.
Elan makes it possible to seamlessly work on a variety of projects, each of which is designed to be built with a particular version of Lean, without having to manually install and select toolchain versions.
Each project is typically configured to use a particular version, which is transparently installed as needed, and changes to the Lean version are tracked automatically.
# Selecting Toolchains
%%%
tag := "elan-toolchain-versions"
%%%
When using Elan, the version of each tool on the {envVar}`PATH` is a proxy that invokes the correct version.
The proxy determines the appropriate toolchain version for the current context, ensures that it is installed, and then invokes the underlying tool in the appropriate toolchain installation.
These proxies can be instructed to use a specific version by passing it as an argument prefixed with `+`, so `lake +4.0.0` invokes `lake` version `4.0.0`, after installing it if necessary.
## Toolchain Identifiers
%%%
tag := "elan-channels"
%%%
Toolchains are specified by providing a toolchain identifier that is either a {deftech}_channel_, which identifies a particular type of Lean release, and optionally an origin, or a {deftech}_custom toolchain name_ established by {elan}`toolchain link`.
Channels may be:
: `stable`
The latest stable Lean release. Elan automatically tracks stable releases and offers to upgrade when a new one is released.
: `beta`
The latest release candidate. Release candidates are builds of Lean that are intended to become the next stable release. They are made available for widespread user testing.
: `nightly`
The latest nightly build. Nightly builds are useful for experimenting with new Lean features to provide feedback to the developers.
: A version number or specific nightly release
Each Lean version number identifies a channel that contains only that release.
The version number may optionally be preceded with a `v`, so `v4.17.0` and `4.17.0` are equivalent.
Similarly, `nightly-YYYY-MM-DD` specifies the nightly release from the specified date.
A project's {tech}[toolchain file] should typically contain a specific version of Lean, rather than a general channel, to make it easier to coordinate between developers and to build and test older versions of the project.
An archive of Lean releases and nightly builds is maintained.
: A custom local toolchain
The command {elan}`toolchain link` can be used to establish a custom toolchain name in Elan for a local build of Lean.
This is especially useful when working on the Lean compiler itself.
Specifying an {deftech}_origin_ instructs Elan to install Lean toolchains from a particular source.
By default, this is the official project repository on GitHub, identified as [`leanprover/lean4`](https://github.com/leanprover/lean4/releases).
If specified, an origin should precede the channel, with a colon, so `stable` is equivalent to `leanprover/lean4:stable`.
When installing nightly releases, `-nightly` is appended to the origin, so `leanprover/lean4:nightly-2025-03-25` consults the [`leanprover/lean4-nightly`](https://github.com/leanprover/lean4-nightly/releases) repository to download releases.
Origins are not used for custom toolchain names.
## Determining the Current Toolchain
%%%
tag := "elan-toolchain-config"
%%%
Elan associates toolchains with directories, and uses the toolchain of the most recent parent directory of the current working directory that has a configured toolchain.
A directory's toolchain may result from a toolchain file or from an override configured with {ref "elan-override"}[`elan override`].
The current toolchain is determined by first searching for a configured toolchain for the current directory, walking up through parent directories until a toolchain version is found or there are no more parents.
A directory has a configured toolchain if there is a configured {tech}[toolchain override] for the directory or if it contains a `lean-toolchain` file.
More recent parents take precedence over their ancestors, and if a directory has both an override and a toolchain file, then the override takes precedence.
If no directory toolchain is found, then Elan's configured {deftech}_default toolchain_ is used as a fallback.
The most common way to configure a Lean toolchain is with a {deftech}_toolchain file_.
The toolchain file is a text file named `lean-toolchain` that contains a single line with a valid {ref "elan-channels"}[toolchain identifier].
This file is typically located in the root directory of a project and checked in to version control with the code, ensuring that everyone working on the project uses the same version.
Updating to a new Lean toolchain requires only editing this file, and the new version is automatically downloaded and run the next time a Lean file is opened or built.
In certain advanced use cases where more flexibility is required, a {deftech}_toolchain override_ can be configured.
Like toolchain files, overrides associate a toolchain version with a directory and its children.
Unlike toolchain files, overrides are stored in Elan's configuration rather than in a local file.
They are typically used when a specific local configuration is required that does not make sense for other developers, such as testing a project with a locally-built Lean compiler.
# Toolchain Locations
%%%
tag := "elan-dir"
%%%
By default, Elan stores installed toolchains in `.elan/toolchains` in the user's home directory, and its proxies are kept in `.elan/bin`, which is added to the path when Elan is installed.
The environment variable {envVar +def}`ELAN_HOME` can be used to change this location.
It should be set both prior to installing Elan and in all sessions that use Lean in order to ensure that Elan's files are found.
# Command-Line Interface
%%%
tag := "elan-cli"
%%%
In addition to the proxies that automatically select, install, and invoke the correct versions of Lean tools, Elan provides a command-line interface for querying and configuring its settings.
This tool is called `elan`.
Like {ref "lake"}[Lake], its command-line interface is structured around subcommands.
Elan can be invoked with following flags:
: {elanOptDef flag}`--help` or {elanOptDef flag}`-h`
Describes the current subcommand in detail.
: {elanOptDef flag}`--verbose` or {elanOptDef flag}`-v`
Enables verbose output.
: {elanOptDef flag}`--version` or {elanOptDef flag}`-V`
Displays the Elan version.
```elanHelp
The Lean toolchain installer
USAGE:
elan [FLAGS] <SUBCOMMAND>
FLAGS:
-v, --verbose Enable verbose output
-h, --help Prints help information
-V, --version Prints version information
SUBCOMMANDS:
show Show the active and installed toolchains
default Set the default toolchain
toolchain Modify or query the installed toolchains
override Modify directory toolchain overrides
run Run a command with an environment configured for a given toolchain
which Display which binary will be run for a given command
self Modify the elan installation
completions Generate completion scripts for your shell
help Prints this message or the help of the given subcommand(s)
DISCUSSION:
elan manages your installations of the Lean theorem prover.
It places `lean` and `lake` binaries in your `PATH` that automatically
select and, if necessary, download the Lean version described in your
project's `lean-toolchain` file. You can also install, select, run,
and uninstall Lean versions manually using the commands of the `elan`
executable.
```
## Querying Toolchains
%%%
tag := "elan-show"
%%%
The {elan}`show` command displays the current toolchain (as determined by the current directory) and lists all installed toolchains.
```elanHelp "show"
elan-show
Show the active and installed toolchains
USAGE:
elan show
FLAGS:
-h, --help Prints help information
DISCUSSION:
Shows the name of the active toolchain and the version of `lean`.
If there are multiple toolchains installed then all installed
toolchains are listed as well.
```
:::elan show
Shows the name of the active toolchain and the version of `lean`.
If there are multiple toolchains installed, then they are all listed.
:::
Here is typical output from {elan}`show` in a project with a `lean-toolchain` file:
```
installed toolchains
--------------------
leanprover/lean4:nightly-2025-03-25
leanprover/lean4:v4.17.0 (resolved from default 'stable')
leanprover/lean4:v4.16.0
leanprover/lean4:v4.9.0
active toolchain
----------------
leanprover/lean4:v4.9.0 (overridden by '/PATH/TO/PROJECT/lean-toolchain')
Lean (version 4.9.0, arm64-apple-darwin23.5.0, commit 8f9843a4a5fe, Release)
```
The `installed toolchains` section lists all the toolchains currently available on the system.
The `active toolchain` section identifies the current toolchain and describes how it was selected.
In this case, the toolchain was selected due to a `lean-toolchain` file.
## Setting the Default Toolchain
%%%
tag := "elan-default"
%%%
Elan's configuration file specifies a {tech}[default toolchain] to be used when there is no `lean-toolchain` file or {tech}[toolchain override] for the current directory.
Rather than manually editing the file, this value is typically changed using the {elan}`default` command.
```elanHelp "default"
elan-default
Set the default toolchain
USAGE:
elan default <toolchain>
FLAGS:
-h, --help Prints help information
ARGS:
<toolchain> Toolchain name, such as 'stable', 'beta', 'nightly', or '4.3.0'. For more information see `elan
help toolchain`
DISCUSSION:
Sets the default toolchain to the one specified.
```
:::elan default "toolchain"
Sets the default toolchain to {elanMeta}`toolchain`, which should be a {ref "elan-channels"}[valid toolchain identifier] such as `stable`, `nightly`, or `4.17.0`.
:::
## Managing Installed Toolchains
%%%
tag := "elan-toolchain"
%%%
The `elan toolchain` family of subcommands is used to manage the installed toolchains.
Toolchains are stored in Elan's {ref "elan-dir"}[toolchain directory].
Installed toolchains can take up substantial disk space.
Elan tracks the Lean projects in which it is invoked, saving a list.
This list of projects can be used to determine which toolchains are in active use and automatically delete unused toolchain versions with {elan}`toolchain gc`.
```elanHelp "toolchain"
elan-toolchain
Modify or query the installed toolchains
USAGE:
elan toolchain <SUBCOMMAND>
FLAGS:
-h, --help Prints help information
SUBCOMMANDS:
list List installed toolchains
install Install a given toolchain
uninstall Uninstall a toolchain
link Create a custom toolchain by symlinking to a directory
gc Garbage-collect toolchains not used by any known project
help Prints this message or the help of the given subcommand(s)
DISCUSSION:
Many `elan` commands deal with *toolchains*, a single
installation of the Lean theorem prover. `elan` supports multiple
types of toolchains. The most basic track the official release
channels: 'stable', 'beta', and 'nightly'; but `elan` can also
install toolchains from the official archives and from local builds.
Standard release channel toolchain names have the following form:
[<origin>:]<channel>[-<date>]
<channel> = stable|beta|nightly|<version>
<date> = YYYY-MM-DD
'channel' is either a named release channel or an explicit version
number, such as '4.0.0'. Channel names can be optionally appended
with an archive date, as in 'nightly-2023-06-27', in which case
the toolchain is downloaded from the archive for that date.
'origin' can be used to refer to custom forks of Lean on Github;
the default is 'leanprover/lean4'. For nightly versions, '-nightly'
is appended to the value of 'origin'.
elan can also manage symlinked local toolchain builds, which are
often used to for developing Lean itself. For more information see
`elan toolchain help link`.
```
```elanHelp "toolchain" "list"
elan-toolchain-list
List installed toolchains
USAGE:
elan toolchain list
FLAGS:
-h, --help Prints help information
```
:::elan toolchain list
Lists the currently-installed toolchains. This is a subset of the output of {elan}`show`.
:::
```elanHelp "toolchain" "install"
elan-toolchain-install
Install a given toolchain
USAGE:
elan toolchain install <toolchain>...
FLAGS:
-h, --help Prints help information
ARGS:
<toolchain>... Toolchain name, such as 'stable', 'beta', 'nightly', or '4.3.0'. For more information see
`elan help toolchain`
```
:::elan toolchain install "toolchain"
Installs the indicated {elanMeta}`toolchain`.
The toolchain's name should be {ref "elan-channels"}[an identifier that's suitable for inclusion in a `lean-toolchain` file].
:::
```elanHelp "toolchain" "uninstall"
elan-toolchain-uninstall
Uninstall a toolchain
USAGE:
elan toolchain uninstall <toolchain>...
FLAGS:
-h, --help Prints help information
ARGS:
<toolchain>... Toolchain name, such as 'stable', 'beta', 'nightly', or '4.3.0'. For more information see
`elan help toolchain`
```
:::elan toolchain uninstall "toolchain"
Uninstalls the indicated {elanMeta}`toolchain`.
The toolchain's name should the name of an installed toolchain.
Use {elan}`toolchain list` to see the installed toolchains with their names.
:::
```elanHelp "toolchain" "link"
elan-toolchain-link
Create a custom toolchain by symlinking to a directory
USAGE:
elan toolchain link <toolchain> <path>
FLAGS:
-h, --help Prints help information
ARGS:
<toolchain> Toolchain name, such as 'stable', 'beta', 'nightly', or '4.3.0'. For more information see `elan
help toolchain`
<path>
DISCUSSION:
'toolchain' is the custom name to be assigned to the new toolchain.
'path' specifies the directory where the binaries and libraries for
the custom toolchain can be found. For example, when used for
development of Lean itself, toolchains can be linked directly out of
the Lean root directory. After building, you can test out different
compiler versions as follows:
$ elan toolchain link master <path/to/lean/root>
$ elan override set master
If you now compile a crate in the current directory, the custom
toolchain 'master' will be used.
```
:::elan toolchain link "«local-name» path"
Creates a new local toolchain named {elanMeta}`local-name`, using the Lean toolchain found at {elanMeta}`path`.
:::
```elanHelp "toolchain" "gc"
elan-toolchain-gc
Garbage-collect toolchains not used by any known project
USAGE:
elan toolchain gc [FLAGS]
FLAGS:
--delete Delete collected toolchains instead of only reporting them
-h, --help Prints help information
--json Format output as JSON
DISCUSSION:
Experimental. A toolchain is classified as 'in use' if
* it is the default toolchain,
* it is registered as an override, or
* there is a directory with a `lean-toolchain` file referencing the
toolchain and elan has been used in the directory before.
For safety reasons, the command currently requires passing `--delete`
to actually remove toolchains but this may be relaxed in the future
when the implementation is deemed stable.
```
:::elan toolchain gc "[\"--delete\"] [\"--json\"]"
This command is still considered experimental.
Determines which of the installed toolchains are in use, offering to delete those that are not.
All the installed toolchains are listed, separated into those that are in use and those that are not.
A toolchain is classified as “in use” if
* it is the default toolchain,
* it is registered as an override, or
* there is a directory with a `lean-toolchain` file referencing the toolchain and elan has been used in the directory before.
For safety reasons, {elan}`toolchain gc` will not actually delete any toolchains unless the {elanOptDef flag}`--delete` flag is passed.
This may be relaxed in the future when the implementation is deemed sufficiently mature.
The {elanOptDef flag}`--json` flag causes {elan}`toolchain gc` to emit the list of used and unused toolchains in a JSON format that's suitable for other tools.
:::
## Managing Directory Overrides
%%%
tag := "elan-override"
%%%
Directory-specific {tech}[toolchain overrides] are a local configuration that takes precedence over `lean-toolchain` files.
The `elan override` commands manage overrides.
```elanHelp "override"
elan-override
Modify directory toolchain overrides
USAGE:
elan override <SUBCOMMAND>
FLAGS:
-h, --help Prints help information
SUBCOMMANDS:
list List directory toolchain overrides
set Set the override toolchain for a directory
unset Remove the override toolchain for a directory
help Prints this message or the help of the given subcommand(s)
DISCUSSION:
Overrides configure elan to use a specific toolchain when
running in a specific directory.
elan will automatically select the Lean toolchain specified in
the `lean-toolchain` file when inside a Lean package, but
directories can also be assigned their own Lean toolchain manually
with `elan override`. When a directory has an override then any
time `lean` or `lake` is run inside that directory, or one of
its child directories, the override toolchain will be invoked.
To pin to a specific nightly:
$ elan override set nightly-2023-09-06
Or a specific stable release:
$ elan override set 4.0.0
To see the active toolchain use `elan show`. To remove the
override and use the default toolchain again, `elan override
unset`.
```
:::elan override list
Lists all the currently configured directory overrides in two columns.
The left column contains the directories in which the Lean version is overridden, and the right column lists the toolchain version.
:::
:::elan override set "toolchain"
Sets {elanMeta}`toolchain` as an override for the current directory.
:::
:::elan override unset "[\"--nonexistent\"] [\"--path\" path]"
If {elanOptDef flag}`--nonexistent` flag is provided, all overrides that are configured for directories that don't currently exist are removed.
If {elanOptDef option}`--path` is provided, then the override set for {elanMeta}`path` is removed.
Otherwise, the override for the current directory is removed.
:::
## Running Tools and Commands
%%%
tag := "elan-run"
%%%
The commands in this section provide the ability to run a command in a specific toolchain and to locate a tool from a particular toolchain on disk.
This can be useful when experimenting with different Lean versions, for cross-version testing, and for integrating Elan with other tools.
```elanHelp "run"
elan-run
Run a command with an environment configured for a given toolchain
USAGE:
elan run [FLAGS] <toolchain> <command>...
FLAGS:
-h, --help Prints help information
--install Install the requested toolchain if needed
ARGS:
<toolchain> Toolchain name, such as 'stable', 'beta', 'nightly', or '4.3.0'. For more information see `elan
help toolchain`
<command>...
DISCUSSION:
Configures an environment to use the given toolchain and then runs
the specified program. The command may be any program, not just
lean or lake. This can be used for testing arbitrary toolchains
without setting an override.
Commands explicitly proxied by `elan` (such as `lean` and
`lake`) also have a shorthand for this available. The toolchain
can be set by using `+toolchain` as the first argument. These are
equivalent:
$ lake +nightly build
$ elan run --install nightly lake build
```
:::elan run "[\"--install\"] toolchain command ..."
Configures an environment to use the given toolchain and then runs the specified program.
The toolchain will be installed if the {elanOptDef flag}`--install` flag is provided.
The command may be any program; it does not need to be a command that's part of a toolchain such as `lean` or `lake`.
This can be used for testing arbitrary toolchains without setting an override.
:::
```elanHelp "which"
elan-which
Display which binary will be run for a given command
USAGE:
elan which <command>
FLAGS:
-h, --help Prints help information
ARGS:
<command>
```
:::elan which "command"
Displays the full path to the toolchain-specific binary for {elanMeta}`command`.
:::
## Managing Elan
%%%
tag := "elan-self"
%%%
Elan can manage its own installation.
It can upgrade itself, remove itself, and help configure tab completion for many popular shells.
```elanHelp "self"
elan-self
Modify the elan installation
USAGE:
elan self <SUBCOMMAND>
FLAGS:
-h, --help Prints help information
SUBCOMMANDS:
update Download and install updates to elan
uninstall Uninstall elan.
help Prints this message or the help of the given subcommand(s)
```
```elanHelp "self" "update"
elan-self-update
Download and install updates to elan
USAGE:
elan self update
FLAGS:
-h, --help Prints help information
```
:::elan self update
Downloads and installs updates to Elan itself.
:::
:::elan self uninstall
Uninstalls Elan.
:::
```elanHelp "completions"
elan-completions
Generate completion scripts for your shell
USAGE:
elan completions [shell]
FLAGS:
-h, --help Prints help information
ARGS:
<shell> [possible values: zsh, bash, fish, powershell, elvish]
DISCUSSION:
One can generate a completion script for `elan` that is
compatible with a given shell. The script is output on `stdout`
allowing one to re-direct the output to the file of their
choosing. Where you place the file will depend on which shell, and
which operating system you are using. Your particular
configuration may also determine where these scripts need to be
placed.
Here are some common set ups for the three supported shells under
Unix and similar operating systems (such as GNU/Linux).
BASH:
Completion files are commonly stored in `/etc/bash_completion.d/`.
Run the command:
$ elan completions bash > /etc/bash_completion.d/elan.bash-completion
This installs the completion script. You may have to log out and
log back in to your shell session for the changes to take affect.
BASH (macOS/Homebrew):
Homebrew stores bash completion files within the Homebrew directory.
With the `bash-completion` brew formula installed, run the command:
$ elan completions bash > $(brew --prefix)/etc/bash_completion.d/elan.bash-completion
FISH:
Fish completion files are commonly stored in
`$HOME/.config/fish/completions`. Run the command:
$ elan completions fish > ~/.config/fish/completions/elan.fish
This installs the completion script. You may have to log out and
log back in to your shell session for the changes to take affect.
ZSH:
ZSH completions are commonly stored in any directory listed in
your `$fpath` variable. To use these completions, you must either
add the generated script to one of those directories, or add your
own to this list.
Adding a custom directory is often the safest bet if you are
unsure of which directory to use. First create the directory; for
this example we'll create a hidden directory inside our `$HOME`
directory:
$ mkdir ~/.zfunc
Then add the following lines to your `.zshrc` just before
`compinit`:
fpath+=~/.zfunc
Now you can install the completions script using the following
command:
$ elan completions zsh > ~/.zfunc/_elan
You must then either log out and log back in, or simply run
$ exec zsh
for the new completions to take affect.
CUSTOM LOCATIONS:
Alternatively, you could save these files to the place of your
choosing, such as a custom directory inside your $HOME. Doing so
will require you to add the proper directives, such as `source`ing
inside your login script. Consult your shells documentation for
how to add such directives.
POWERSHELL:
The powershell completion scripts require PowerShell v5.0+ (which
comes Windows 10, but can be downloaded separately for windows 7
or 8.1).
First, check if a profile has already been set
PS C:\> Test-Path $profile
If the above command returns `False` run the following
PS C:\> New-Item -path $profile -type file -force
Now open the file provided by `$profile` (if you used the
`New-Item` command it will be
`%USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1`
Next, we either save the completions file into our profile, or
into a separate file and source it inside our profile. To save the
completions into our profile simply use
PS C:\> elan completions powershell >>
%USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
```
:::elan completions "shell"
Generates shell completion scripts for Elan, enabling tab completion for Elan commands in a variety of shells.
See the output of `elan help completions` for a description of how to install them.
::: |
reference-manual/Manual/BuildTools/Lake/Config.lean | import VersoManual
import Lean.Parser.Command
import Lake.Config.Monad
import Lake.DSL
import Manual.Meta
import Manual.BuildTools.Lake.CLI
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
open Lean.Elab.Tactic.GuardMsgs.WhitespaceMode
open Lake.DSL
#doc (Manual) "Configuration File Format" =>
%%%
tag := "lake-config"
%%%
:::paragraph
Lake offers two formats for {tech}[package configuration] files:
: TOML
The TOML configuration format is fully declarative.
Projects that don't include custom targets, facets, or scripts can use the TOML format.
Because TOML parsers are available for a wide variety of languages, using this format facilitates integration with tools that are not written in Lean.
: Lean
The Lean configuration format is more flexible and allows for custom targets, facets, and scripts.
It features an embedded domain-specific language for describing the declarative subset of configuration options that is available from the TOML format.
Additionally, the Lake API can be used to express build configurations that are outside of the possibilities of the declarative options.
The command {lake}`translate-config` can be used to automatically convert between the two formats.
:::
Both formats are processed similarly by Lake, which extracts the {tech}[package configuration] from the configuration file in the form of internal structure types.
When the package is {tech (key := "configure package")}[configured], the resulting data structures are written to `lakefile.olean` in the {tech}[build directory].
# Declarative TOML Format
%%%
tag := "lake-config-toml"
%%%
TOML{margin}[[_Tom's Obvious Minimal Language_](https://toml.io/en/) is a standardized format for configuration files.] configuration files describe the most-used, declarative subset of Lake {tech}[package configuration] files.
TOML files denote _tables_, which map keys to values.
Values may consist of strings, numbers, arrays of values, or further tables.
Because TOML allows considerable flexibility in file structure, this reference documents the values that are expected rather than the specific syntax used to produce them.
The contents of {configFile}`lakefile.toml` should denote a TOML table that describes a Lean package.
This configuration consists of both scalar fields that describe the entire package, as well as the following fields that contain arrays of further tables:
* `require`
* `lean_lib`
* `lean_exe`
Fields that are not part of the configuration tables described here are presently ignored.
To reduce the risk of typos, this is likely to change in the future.
Field names not used by Lake should not be used to store metadata to be processed by other tools.
## Package Configuration
The top-level contents of `lakefile.toml` specify the options that apply to the package itself, including metadata such as the name and version, the locations of the files in the {tech}[workspace], compiler flags to be used for all {tech}[targets], and
The only mandatory field is `name`, which declares the package's name.
:::::tomlTableDocs root "Package Configuration" Lake.PackageConfig (skip := backend) (skip := releaseRepo?) (skip := buildArchive?) (skip := manifestFile) (skip := moreServerArgs) (skip := dynlibs) (skip := plugins)
::::tomlFieldCategory "Metadata" name version versionTags description keywords homepage license licenseFiles readmeFile reservoir
These options describe the package.
They are used by [Reservoir](https://reservoir.lean-lang.org/) to index and display packages.
If a field is left out, Reservoir may use information from the package's GitHub repository to fill in details.
:::tomlField Lake.PackageConfig name "The package name" "Package names" String
The package's name.
:::
::::
:::tomlFieldCategory "Layout" packagesDir srcDir buildDir leanLibDr nativeLibDir binDir irDir
These options control the top-level directory layout of the package and its build directory.
Further paths specified by libraries, executables, and targets within the package are relative to these directories.
:::
:::tomlFieldCategory "Building and Running" defaultTargets leanLibDir platformIndependent precompileModules moreServerOptions moreGlobalServerArgs buildType leanOptions moreLeanArgs weakLeanArgs moreLeancArgs weakLeancArgs moreLinkArgs weakLinkArgs extraDepTargets
These options configure how code is built and run in the package.
Libraries, executables, and other {tech}[targets] within a package can further add to parts of this configuration.
:::
:::tomlFieldCategory "Testing and Linting" testDriver testDriverArgs lintDriver lintDriverArgs
The CLI commands {lake}`test` and {lake}`lint` use definitions configured by the {tech}[workspace]'s {tech}[root package] to perform testing and linting.
The code that is run to perform tests and linting is referred to as the test or lint driver.
In Lean configuration files, these can be specified by applying the `@[test_driver]` or `@[lint_driver]` attributes to a {tech}[Lake script] or an executable or library target.
In both Lean and TOML configuration files, they can also be configured by setting these options.
A target or script `TGT` from a dependency `PKG` can be specified as a test or lint driver using the string `"PKG/TGT"`
:::
:::tomlFieldCategory "Cloud Releases" releaseRepo buildArchive preferReleaseBuild
These options define a cloud release for the package, as described in the section on {ref "lake-github"}[GitHub release builds].
:::
:::tomlField Lake.PackageConfig defaultTargets "default targets' names (array)" "default targets' names (array)" String (sort := 2)
{includeDocstring Lake.Package.defaultTargets -elab}
:::
:::::
:::::example "Minimal TOML Package Configuration"
The minimal TOML configuration for a Lean {tech}[package] sets only the package's name, using the default values for all other fields.
This package contains no {tech}[targets], so there is no code to be built.
::::lakeToml Lake.PackageConfig _root_
```toml
name = "example-package"
```
```expected
{wsIdx := 0,
baseName := `«example-package»,
keyName := `«example-package»,
origName := `«example-package»,
dir := FilePath.mk ".",
relDir := FilePath.mk ".",
config :=
{toWorkspaceConfig := { packagesDir := FilePath.mk ".lake/packages" },
toLeanConfig :=
{ buildType := Lake.BuildType.release,
leanOptions := #[],
moreLeanArgs := #[],
weakLeanArgs := #[],
moreLeancArgs := #[],
moreServerOptions := #[],
weakLeancArgs := #[],
moreLinkObjs := #[],
moreLinkLibs := #[],
moreLinkArgs := #[],
weakLinkArgs := #[],
backend := Lake.Backend.default,
platformIndependent := none,
dynlibs := #[],
plugins := #[] },
bootstrap := false,
manifestFile := none,
extraDepTargets := #[],
precompileModules := false,
moreGlobalServerArgs := #[],
srcDir := FilePath.mk ".",
buildDir := FilePath.mk ".lake/build",
leanLibDir := FilePath.mk "lib/lean",
nativeLibDir := FilePath.mk "lib",
binDir := FilePath.mk "bin",
irDir := FilePath.mk "ir",
releaseRepo := none,
buildArchive := ELIDED,
preferReleaseBuild := false,
testDriver := "",
testDriverArgs := #[],
lintDriver := "",
lintDriverArgs := #[],
version := { toSemVerCore := { major := 0, minor := 0, patch := 0 }, specialDescr := "" },
versionTags := { filter := #<fun>, name := `default, descr? := none},
description := "",
keywords := #[],
homepage := "",
license := "",
licenseFiles := #[FilePath.mk "LICENSE"],
readmeFile := FilePath.mk "README.md",
reservoir := true,
enableArtifactCache? := none,
restoreAllArtifacts := false,
libPrefixOnWindows := false,
allowImportAll := false},
configFile := FilePath.mk "lakefile",
relConfigFile := FilePath.mk "lakefile",
relManifestFile := FilePath.mk "lake-manifest.json",
scope := "",
remoteUrl := "",
depConfigs := #[],
targetDecls := #[],
targetDeclMap := {},
defaultTargets := #[],
scripts := {},
defaultScripts := #[],
postUpdateHooks := #[],
buildArchive := ELIDED,
testDriver := "",
lintDriver := "",
inputsRef? := none,
outputsRef? := none}
```
::::
:::::
:::::example "Library TOML Package Configuration"
The minimal TOML configuration for a Lean {tech}[package] sets the package's name and defines a library target.
This library is named `Sorting`, and its modules are expected under the `Sorting.*` hierarchy.
::::lakeToml Lake.PackageConfig _root_
```toml
name = "example-package"
defaultTargets = ["Sorting"]
[[lean_lib]]
name = "Sorting"
```
```expected
{wsIdx := 0,
baseName := `«example-package»,
keyName := `«example-package»,
origName := `«example-package»,
dir := FilePath.mk ".",
relDir := FilePath.mk ".",
config :=
{toWorkspaceConfig := { packagesDir := FilePath.mk ".lake/packages" },
toLeanConfig :=
{ buildType := Lake.BuildType.release,
leanOptions := #[],
moreLeanArgs := #[],
weakLeanArgs := #[],
moreLeancArgs := #[],
moreServerOptions := #[],
weakLeancArgs := #[],
moreLinkObjs := #[],
moreLinkLibs := #[],
moreLinkArgs := #[],
weakLinkArgs := #[],
backend := Lake.Backend.default,
platformIndependent := none,
dynlibs := #[],
plugins := #[] },
bootstrap := false,
manifestFile := none,
extraDepTargets := #[],
precompileModules := false,
moreGlobalServerArgs := #[],
srcDir := FilePath.mk ".",
buildDir := FilePath.mk ".lake/build",
leanLibDir := FilePath.mk "lib/lean",
nativeLibDir := FilePath.mk "lib",
binDir := FilePath.mk "bin",
irDir := FilePath.mk "ir",
releaseRepo := none,
buildArchive := ELIDED,
preferReleaseBuild := false,
testDriver := "",
testDriverArgs := #[],
lintDriver := "",
lintDriverArgs := #[],
version := { toSemVerCore := { major := 0, minor := 0, patch := 0 }, specialDescr := "" },
versionTags := { filter := #<fun>, name := `default, descr? := none},
description := "",
keywords := #[],
homepage := "",
license := "",
licenseFiles := #[FilePath.mk "LICENSE"],
readmeFile := FilePath.mk "README.md",
reservoir := true,
enableArtifactCache? := none,
restoreAllArtifacts := false,
libPrefixOnWindows := false,
allowImportAll := false},
configFile := FilePath.mk "lakefile",
relConfigFile := FilePath.mk "lakefile",
relManifestFile := FilePath.mk "lake-manifest.json",
scope := "",
remoteUrl := "",
depConfigs := #[],
targetDecls :=
#[{toConfigDecl :=
{pkg := `«example-package»,
name := `Sorting,
kind := `lean_lib,
config :=
{toLeanConfig :=
{ buildType := Lake.BuildType.release,
leanOptions := #[],
moreLeanArgs := #[],
weakLeanArgs := #[],
moreLeancArgs := #[],
moreServerOptions := #[],
weakLeancArgs := #[],
moreLinkObjs := #[],
moreLinkLibs := #[],
moreLinkArgs := #[],
weakLinkArgs := #[],
backend := Lake.Backend.default,
platformIndependent := none,
dynlibs := #[],
plugins := #[] },
srcDir := FilePath.mk ".",
roots := #[`Sorting],
globs := #[Lake.Glob.one `Sorting],
libName := "",
libPrefixOnWindows := false,
needs := #[],
extraDepTargets := #[],
precompileModules := false,
defaultFacets := #[`lean_lib.leanArts],
nativeFacets := #<fun>,
allowImportAll := false},
wf_data := …},
pkg_eq := …}],
targetDeclMap :=
{`Sorting ↦
{toPConfigDecl :=
{toConfigDecl :=
{pkg := `«example-package»,
name := `Sorting,
kind := `lean_lib,
config :=
{toLeanConfig :=
{ buildType := Lake.BuildType.release,
leanOptions := #[],
moreLeanArgs := #[],
weakLeanArgs := #[],
moreLeancArgs := #[],
moreServerOptions := #[],
weakLeancArgs := #[],
moreLinkObjs := #[],
moreLinkLibs := #[],
moreLinkArgs := #[],
weakLinkArgs := #[],
backend := Lake.Backend.default,
platformIndependent := none,
dynlibs := #[],
plugins := #[] },
srcDir := FilePath.mk ".",
roots := #[`Sorting],
globs := #[Lake.Glob.one `Sorting],
libName := "",
libPrefixOnWindows := false,
needs := #[],
extraDepTargets := #[],
precompileModules := false,
defaultFacets := #[`lean_lib.leanArts],
nativeFacets := #<fun>,
allowImportAll := false},
wf_data := …},
pkg_eq := …},
name_eq := …},
},
defaultTargets := #[`Sorting],
scripts := {},
defaultScripts := #[],
postUpdateHooks := #[],
buildArchive := ELIDED,
testDriver := "",
lintDriver := "",
inputsRef? := none,
outputsRef? := none}
```
::::
:::::
## Dependencies
Dependencies are specified in the {toml}`[[require]]` field array of a package configuration, which specifies both the name and the source of each package.
There are three kinds of sources:
* [Reservoir](https://reservoir.lean-lang.org/), or an alternative package registry
* Git repositories, which may be local paths or URLs
* Local paths
::::tomlTableDocs "require" "Requiring Packages" Lake.Dependency (skip := src?) (skip := opts) (skip := subdir) (skip := version?)
The {tomlField Lake.Dependency}`path` and {tomlField Lake.Dependency}`git` fields specify an explicit source for a dependency.
If neither are provided, then the dependency is fetched from [Reservoir](https://reservoir.lean-lang.org/), or an alternative registry if one has been configured.
The {tomlField Lake.Dependency}`scope` field is required when fetching a package from Reservoir.
:::tomlField Lake.Dependency path "Path" "Paths" System.FilePath
A dependency on the local filesystem, specified by its path.
:::
:::tomlField Lake.Dependency git "Git specification" "Git specifications" Lake.DependencySrc
A dependency in a Git repository, specified either by its URL as a string or by a table with the keys:
* `url`: the repository URL
* `subDir`: the subdirectory of the Git repository that contains the package's source code
:::
:::tomlField Lake.Dependency rev "Git revision" "Git revisions" String
For Git or Reservoir dependencies, this field specifies the Git revision, which may be a branch name, a tag name, or a specific hash.
On Reservoir, the `version` field takes precedence over this field.
:::
:::tomlField Lake.Dependency source "Package Source" "Package Sources" Lake.DependencySrc
A dependency source, specified as a self-contained table, which is used when neither the `git` nor the `path` key is present.
The key `type` should be either the string `"git"` or the string `"path"`.
If the type is `"path"`, then there must be a further key `"path"` whose value is a string that provides the location of the package on disk.
If the type is `"git"`, then the following keys should be present:
* `url`: the repository URL
* `rev`: the Git revision, which may be a branch name, a tag name, or a specific hash (optional)
* `subDir`: the subdirectory of the Git repository that contains the package's source code
:::
:::tomlField Lake.Dependency version "version as string" "versions as strings" String
{includeDocstring Lake.Dependency.version?}
:::
::::
:::::example "Requiring Packages from Reservoir"
The package `example` can be required from Reservoir using this TOML configuration:
::::lakeToml Lake.Dependency require
```toml
[[require]]
name = "example"
version = "2.12"
scope = "exampleDev"
```
```expected
#[{name := `example, scope := "exampleDev", version? := some "2.12", src? := none, opts := {}}]
```
::::
:::::
:::::example "Requiring Packages from Git"
The package `example` can be required from a Git repository using this TOML configuration:
::::lakeToml Lake.Dependency require
```toml
[[require]]
name = "example"
git = "https://git.example.com/example.git"
rev = "main"
version = "2.12"
```
```expected
#[{name := `example,
scope := "",
version? := some "2.12",
src? := some (Lake.DependencySrc.git "https://git.example.com/example.git" (some "main") none),
opts := {}}]
```
::::
In particular, the package will be checked out from the `main` branch, and the version number specified in the package's {tech (key := "package configuration")}[configuration] should match `2.12`.
:::::
:::::example "Requiring Packages from a Git tag"
The package `example` can be required from the tag `v2.12` in a Git repository using this TOML configuration:
::::lakeToml Lake.Dependency require
```toml
[[require]]
name = "example"
git = "https://git.example.com/example.git"
rev = "v2.12"
```
```expected
#[{name := `example,
scope := "",
version? := none,
src? := some (Lake.DependencySrc.git "https://git.example.com/example.git" (some "v2.12") none),
opts := {}}]
```
::::
The version number specified in the package's {tech (key := "package configuration")}[configuration] is not used.
:::::
:::::example "Requiring Reservoir Packages from a Git tag"
The package `example`, found using Reservoir, can be required from the tag `v2.12` in its Git repository using this TOML configuration:
::::lakeToml Lake.Dependency require
```toml
[[require]]
name = "example"
rev = "v2.12"
scope = "exampleDev"
```
```expected
#[{name := `example, scope := "exampleDev", version? := some "git#v2.12", src? := none, opts := {}}]
```
::::
The version number specified in the package's {tech (key := "package configuration")}[configuration] is not used.
:::::
:::::example "Requiring Packages from Paths"
The package `example` can be required from the local path `../example` using this TOML configuration:
::::lakeToml Lake.Dependency require
```toml
[[require]]
name = "example"
path = "../example"
```
```expected
#[{name := `example,
scope := "",
version? := none,
src? := some (Lake.DependencySrc.path (FilePath.mk "../example")),
opts := {}}]
```
::::
Dependencies on local paths are useful when developing multiple packages in a single repository, or when testing whether a change to a dependency fixes a bug in a downstream package.
:::::
:::::example "Sources as Tables"
The information about the package source can be written in an explicit table.
::::lakeToml Lake.Dependency require
```toml
[[require]]
name = "example"
source = {type = "git", url = "https://example.com/example.git"}
```
```expected
#[{name := `example,
scope := "",
version? := none,
src? := some (Lake.DependencySrc.git "https://example.com/example.git" none none),
opts := {}}]
```
::::
:::::
## Library Targets
Library targets are expected in the `lean_lib` array of tables.
::::tomlTableDocs "lean_lib" "Library Targets" Lake.LeanLibConfig (skip := backend) (skip := globs) (skip := nativeFacets)
:::tomlField Lake.LeanLibConfig name "The library name" "Library names" String
The library's name, which is typically the same as its single module root.
:::
::::
:::::example "Minimal Library Target"
This library declaration supplies only a name:
::::lakeToml Lake.LeanLibConfig lean_lib
```toml
[[lean_lib]]
name = "TacticTools"
```
```expected
#[{ name := TacticTools,
val := {toLeanConfig :=
{ buildType := Lake.BuildType.release,
leanOptions := #[],
moreLeanArgs := #[],
weakLeanArgs := #[],
moreLeancArgs := #[],
moreServerOptions := #[],
weakLeancArgs := #[],
moreLinkObjs := #[],
moreLinkLibs := #[],
moreLinkArgs := #[],
weakLinkArgs := #[],
backend := Lake.Backend.default,
platformIndependent := none,
dynlibs := #[],
plugins := #[] },
srcDir := FilePath.mk ".",
roots := #[`TacticTools],
globs := #[Lake.Glob.one `TacticTools],
libName := "",
libPrefixOnWindows := false,
needs := #[],
extraDepTargets := #[],
precompileModules := false,
defaultFacets := #[`lean_lib.leanArts],
nativeFacets := #<fun>,
allowImportAll := false}}]
```
::::
The library's source is located in the package's default source directory, in the module hierarchy rooted at `TacticTools`.
:::::
:::::example "Configured Library Target"
This library declaration supplies more options:
::::lakeToml Lake.LeanLibConfig lean_lib
```toml
[[lean_lib]]
name = "TacticTools"
srcDir = "src"
precompileModules = true
```
```expected
#[{ name := TacticTools,
val := {toLeanConfig :=
{ buildType := Lake.BuildType.release,
leanOptions := #[],
moreLeanArgs := #[],
weakLeanArgs := #[],
moreLeancArgs := #[],
moreServerOptions := #[],
weakLeancArgs := #[],
moreLinkObjs := #[],
moreLinkLibs := #[],
moreLinkArgs := #[],
weakLinkArgs := #[],
backend := Lake.Backend.default,
platformIndependent := none,
dynlibs := #[],
plugins := #[] },
srcDir := FilePath.mk "src",
roots := #[`TacticTools],
globs := #[Lake.Glob.one `TacticTools],
libName := "",
libPrefixOnWindows := false,
needs := #[],
extraDepTargets := #[],
precompileModules := true,
defaultFacets := #[`lean_lib.leanArts],
nativeFacets := #<fun>,
allowImportAll := false}}]
```
::::
The library's source is located in the directory `src`, in the module hierarchy rooted at `TacticTools`.
If its modules are accessed at elaboration time, they will be compiled to native code and linked in, rather than run in the interpreter.
:::::
## Executable Targets
:::: tomlTableDocs "lean_exe" "Executable Targets" Lake.LeanExeConfig (skip := backend) (skip := globs) (skip := nativeFacets)
:::tomlField Lake.LeanExeConfig name "The executable's name" "Executable names" String
The executable's name.
:::
::::
:::::example "Minimal Executable Target"
This executable declaration supplies only a name:
::::lakeToml Lake.LeanExeConfig lean_exe
```toml
[[lean_exe]]
name = "trustworthytool"
```
```expected
#[{ name := trustworthytool,
val := {toLeanConfig :=
{ buildType := Lake.BuildType.release,
leanOptions := #[],
moreLeanArgs := #[],
weakLeanArgs := #[],
moreLeancArgs := #[],
moreServerOptions := #[],
weakLeancArgs := #[],
moreLinkObjs := #[],
moreLinkLibs := #[],
moreLinkArgs := #[],
weakLinkArgs := #[],
backend := Lake.Backend.default,
platformIndependent := none,
dynlibs := #[],
plugins := #[] },
srcDir := FilePath.mk ".",
root := `trustworthytool,
exeName := "trustworthytool",
needs := #[],
extraDepTargets := #[],
supportInterpreter := false,
nativeFacets := #<fun>}}]
```
::::
```lean -show
def main : List String → IO UInt32 := fun _ => pure 0
```
The executable's {lean}`main` function is expected in a module named `trustworthytool.lean` in the package's default source file path.
The resulting executable is named `trustworthytool`.
:::::
:::::example "Configured Executable Target"
The name `trustworthy-tool` is not a valid Lean name due to the dash (`-`).
To use this name for an executable target, an explicit module root must be supplied.
Even though `trustworthy-tool` is a perfectly acceptable name for an executable, the target also specifies that the result of compilation and linking should be named `tt`.
::::lakeToml Lake.LeanExeConfig lean_exe
```toml
[[lean_exe]]
name = "trustworthy-tool"
root = "TrustworthyTool"
exeName = "tt"
```
```expected
#[{ name := «trustworthy-tool»,
val := {toLeanConfig :=
{ buildType := Lake.BuildType.release,
leanOptions := #[],
moreLeanArgs := #[],
weakLeanArgs := #[],
moreLeancArgs := #[],
moreServerOptions := #[],
weakLeancArgs := #[],
moreLinkObjs := #[],
moreLinkLibs := #[],
moreLinkArgs := #[],
weakLinkArgs := #[],
backend := Lake.Backend.default,
platformIndependent := none,
dynlibs := #[],
plugins := #[] },
srcDir := FilePath.mk ".",
root := `TrustworthyTool,
exeName := "tt",
needs := #[],
extraDepTargets := #[],
supportInterpreter := false,
nativeFacets := #<fun>}}]
```
::::
```lean -show
def main : List String → IO UInt32 := fun _ => pure 0
```
The executable's {lean}`main` function is expected in a module named `TrustworthyTool.lean` in the package's default source file path.
:::::
# Lean Format
%%%
tag := "lake-config-lean"
%%%
The Lean format for Lake {tech}[package configuration] files provides a domain-specific language for the declarative features that are supported in the TOML format.
Additionally, it provides the ability to write Lean code to implement any necessary build logic that is not expressible declaratively.
The Lean configuration file is named {configFile}`lakefile.lean`.
Because the Lean format is a Lean source file, it can be edited using all the features of the Lean language server.
Additionally, Lean's metaprogramming framework allows elaboration-time side effects to be used to implement features such as configuration steps that are conditional on the current platform.
However, a consequence of the Lean configuration format being a Lean file is that it is not feasible to process such files using tools that are not themselves written in Lean.
```lean -show
section
open Lake DSL
open Lean (NameMap)
```
## Declarative Fields
The declarative subset of the Lean configuration format uses sequences of declaration fields to specify configuration options.
:::syntax Lake.DSL.declField (title := "Declarative Fields") -open
{includeDocstring Lake.DSL.declField}
```grammar
$_ := $_
```
:::
## Packages
::::syntax command (title := "Package Configuration")
```grammar
$[$_:docComment]?
$[@[ $_,* ]]?
package $name:identOrStr
```
```grammar
$[$_:docComment]?
$[@[$_,*]]?
package $name where
$item*
```
```grammar
$[$_:docComment]?
$[@[$_,*]]?
package $_:identOrStr {
$[$_:declField];*
}
$[where
$[$_:letRecDecl];*]?
```
There can only be one {keywordOf Lake.DSL.packageCommand}`package` declaration per Lake configuration file.
The defined package configuration will be available for reference as `_package`.
::::
::::syntax command (title := "Post-Update Hooks")
```grammar
post_update $[$name]? $v
```
{includeDocstring Lake.DSL.postUpdateDecl}
::::
## Dependencies
Dependencies are specified using the {keywordOf Lake.DSL.requireDecl}`require` declaration.
:::syntax command (title := "Requiring Packages")
```grammar
$doc:docComment
require $name:depName $[@ $[git]? $_:term]? $[$_:fromClause]? $[with $_:term]?
```
The `@` clause specifies a package version, which is used when requiring a package from [Reservoir](https://reservoir.lean-lang.org/).
The version may either be a string that specifies the version declared in the package's {name Lake.PackageConfig.version}`version` field, or a specific Git revision.
Git revisions may be branch names, tag names, or commit hashes.
The optional {syntaxKind}`fromClause` specifies a package source other than Reservoir, which may be either a Git repository or a local path.
The {keywordOf Lake.DSL.requireDecl}`with` clause specifies a {lean}`NameMap String` of Lake options that will be used to configure the dependency.
This is equivalent to passing {lakeOpt}`-K` options to {lake}`build` when building the dependency on the command line.
:::
:::syntax fromClause -open (title := "Package Sources")
{includeDocstring Lake.DSL.fromClause}
```grammar
from $t:term
```
```grammar
from git $t $[@ $t]? $[/ $t]?
```
:::
## Targets
{tech}[Targets] are typically added to the set of default targets by applying the `default_target` attribute, rather than by explicitly listing them.
:::TODO
Fix `default_target` above—it's not working on CI, but it is working locally, with the `attr` role.
:::
:::syntax attr (title := "Specifying Default Targets") (label := "attribute") (namespace := Lake.DSL)
```grammar
default_target
```
Marks a target as a default, to be built when no other target is specified.
:::
### Libraries
:::syntax command (title := "Library Targets")
To define a library in which all configurable fields have their default values, use {keywordOf Lake.DSL.leanLibCommand}`lean_lib` with no further fields.
```grammar
$[$_:docComment]?
$[$_:attributes]?
lean_lib $_:identOrStr
```
The default configuration can be modified by providing the new values.
```grammar
$[$_:docComment]?
$[$_:attributes]?
lean_lib $_:identOrStr where
$field*
```
```grammar
$[$_:docComment]?
$[$_:attributes]?
lean_lib $_:identOrStr {
$[$_:declField];*
}
$[where
$[$_:letRecDecl];*]?
```
:::
The fields of {keywordOf Lake.DSL.leanLibCommand}`lean_lib` are those of the {name Lake.LeanLibConfig}`LeanLibConfig` structure.
{docstring Lake.LeanLibConfig}
### Executables
:::syntax command (title := "Executable Targets")
To define an executable in which all configurable fields have their default values, use {keywordOf Lake.DSL.leanExeCommand}`lean_exe` with no further fields.
```grammar
$[$_:docComment]? $[$_:attributes]?
lean_exe $_:identOrStr
```
The default configuration can be modified by providing the new values.
```grammar
$[$_:docComment]? $[$_:attributes]?
lean_exe $_:identOrStr where
$field*
```
```grammar
$[$_:docComment]? $[$_:attributes]?
lean_exe $_:identOrStr {
$[$_:declField];*
}
$[where
$[$_:letRecDecl];*]?
```
:::
The fields of {keywordOf Lake.DSL.leanExeCommand}`lean_exe` are those of the {name Lake.LeanExeConfig}`LeanExeConfig` structure.
{docstring Lake.LeanExeConfig}
### External Libraries
Because external libraries may be written in any language and require arbitrary build steps, they are defined as programs written in the {name Lake.FetchM}`FetchM` monad that produce a {name Lake.Job}`Job`.
External library targets should produce a build job that carries out the build and then returns the location of the resulting static library.
For the external library to link properly when {name Lake.PackageConfig.precompileModules}`precompileModules` is on, the static library produced by an {keyword}`extern_lib` target must follow the platform's naming conventions for libraries (i.e., be named foo.a on Windows or libfoo.a on Unix-like systems).
The utility function {name}`Lake.nameToStaticLib` converts a library name into its proper file name for current platform.
:::syntax command (title := "External Library Targets")
```grammar
$[$_:docComment]?
$[$_:attributes]?
extern_lib $_:identOrStr $_? := $_:term
$[where $_*]?
```
{includeDocstring Lake.DSL.externLibCommand}
:::
### Custom Targets
Custom targets may be used to define any incrementally-built artifact whatsoever, using the Lake API.
:::syntax command (title := "Custom Targets")
```grammar
$[$_:docComment]?
$[$_:attributes]?
target $_:identOrStr $_? : $ty:term := $_:term
$[where $_*]?
```
{includeDocstring Lake.DSL.externLibCommand}
:::
### Custom Facets
Custom facets allow additional artifacts to be incrementally built from a module, library, or package.
:::syntax command (title := "Custom Package Facets")
Package facets allow the production of an artifact or set of artifacts from a whole package.
The Lake API makes it possible to query a package for its libraries; thus, one common use for a package facet is to build a given facet of each library.
```grammar
$[$_:docComment]?
$[@[$_,*]]?
package_facet $_:identOrStr $_? : $ty:term := $_:term
$[where $_*]?
```
{includeDocstring Lake.DSL.packageFacetDecl}
:::
:::syntax command (title := "Custom Library Facets")
Library facets allow the production of an artifact or set of artifacts from a library.
The Lake API makes it possible to query a library for its modules; thus, one common use for a library facet is to build a given facet of each module.
```grammar
$[$_:docComment]?
$[@[$_,*]]?
library_facet $_:identOrStr $_? : $ty:term := $_:term
$[where $_*]?
```
{includeDocstring Lake.DSL.libraryFacetDecl}
:::
:::syntax command (title := "Custom Module Facets")
Module facets allow the production of an artifact or set of artifacts from a module, typically by invoking a command-line tool.
```grammar
$[$_:docComment]?
$[@[$_,*]]?
module_facet $_:identOrStr $_? : $ty:term := $_:term
$[where $_*]?
```
{includeDocstring Lake.DSL.moduleFacetDecl}
:::
## Configuration Value Types
{docstring Lake.BuildType}
In Lake's DSL, {deftech}_globs_ are patterns that match sets of module names.
There is a coercion from names to globs that match the name in question, and there are two postfix operators for constructing further globs.
```lean -show
section
example : Lake.Glob := `n
/-- info: instCoeNameGlob -/
#check_msgs in
#synth Coe Lean.Name Lake.Glob
open Lake DSL
/-- info: Lake.Glob.andSubmodules `n -/
#check_msgs in
#eval show Lake.Glob from `n.*
/-- info: Lake.Glob.submodules `n -/
#check_msgs in
#eval show Lake.Glob from `n.+
end
```
:::freeSyntax term (title := "Glob Syntax")
The glob pattern `N.*` matches `N` or any submodule for which `N` is a prefix.
```grammar
$_:name".*"
```
The glob pattern `N.+` matches any submodule for which `N` is a strict prefix, but not `N` itself.
```grammar
$_:name".+"
```
Whitespace is not permitted between the name and `.*` or `.+`.
:::
{docstring Lake.Glob}
{docstring Lake.LeanOption}
{docstring Lake.Backend}
## Scripts
Lake scripts are used to automate tasks that require access to a package configuration but do not participate in incremental builds of artifacts from code.
Scripts run in the {name Lake.ScriptM}`ScriptM` monad, which is {name}`IO` with an additional {tech}[reader monad] {tech (key := "monad transformer")}[transformer] that provides access to the package configuration.
In particular, a script should have the type {lean}`List String → ScriptM UInt32`.
Workspace information in scripts is primarily accessed via the {inst}`MonadWorkspace ScriptM` instance.
```lean -show
example : ScriptFn = (List String → ScriptM UInt32) := rfl
```
:::syntax command (title := "Script Declarations")
```grammar
$[$_:docComment]?
$[@[$_,*]]?
script $_:identOrStr $_? :=
$_:term
$[where
$_*]?
```
{includeDocstring Lake.DSL.scriptDecl}
:::
{docstring Lake.ScriptM}
:::syntax attr (label := "attribute") (title := "Default Scripts")
```grammar
default_script
```
Marks a {tech}[Lake script] as the {tech}[package]'s default.
:::
## Utilities
:::syntax term (title := "The Current Directory")
```grammar
__dir__
```
{includeDocstring Lake.DSL.dirConst}
:::
:::syntax term (title := "Configuration Options")
```grammar
get_config? $t
```
{includeDocstring Lake.DSL.getConfig}
:::
:::syntax command (title := "Compile-Time Conditionals")
```grammar
meta if $_ then
$_
$[else $_]?
```
{includeDocstring Lake.DSL.metaIf}
:::
:::syntax cmdDo (title := "Command Sequences")
```grammar
$_:command
```
```grammar
do
$_:command
$[$_:command]*
```
{includeDocstring Lake.DSL.cmdDo}
:::
:::syntax term (title := "Compile-Time Side Effects")
```grammar
run_io $t
```
{includeDocstring Lake.DSL.runIO}
::: |
reference-manual/Manual/BuildTools/Lake/CLI.lean | import VersoManual
import Lean.Parser.Command
import Manual.Meta
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
open Verso.Code.External (lit)
open Lean.Elab.Tactic.GuardMsgs.WhitespaceMode
#doc (Manual) "Command-Line Interface" =>
%%%
tag := "lake-cli"
%%%
```lakeHelp
USAGE:
lake [OPTIONS] <COMMAND>
COMMANDS:
new <name> <temp> create a Lean package in a new directory
init <name> <temp> create a Lean package in the current directory
build <targets>... build targets
query <targets>... build targets and output results
exe <exe> <args>... build an exe and run it in Lake's environment
check-build check if any default build targets are configured
test test the package using the configured test driver
check-test check if there is a properly configured test driver
lint lint the package using the configured lint driver
check-lint check if there is a properly configured lint driver
clean remove build outputs
shake minimize imports in source files
env <cmd> <args>... execute a command in Lake's environment
lean <file> elaborate a Lean file in Lake's context
update update dependencies and save them to the manifest
pack pack build artifacts into an archive for distribution
unpack unpack build artifacts from an distributed archive
upload <tag> upload build artifacts to a GitHub release
cache manage the Lake cache
script manage and run workspace scripts
scripts shorthand for `lake script list`
run <script> shorthand for `lake script run`
translate-config change language of the package configuration
serve start the Lean language server
BASIC OPTIONS:
--version print version and exit
--help, -h print help of the program or a command and exit
--dir, -d=file use the package configuration in a specific directory
--file, -f=file use a specific file for the package configuration
-K key[=value] set the configuration file option named key
--old only rebuild modified modules (ignore transitive deps)
--rehash, -H hash all files for traces (do not trust `.hash` files)
--update update dependencies on load (e.g., before a build)
--packages=file JSON file of package entries that override the manifest
--reconfigure, -R elaborate configuration files instead of using OLeans
--keep-toolchain do not update toolchain on workspace update
--no-build exit immediately if a build target is not up-to-date
--no-cache build packages locally; do not download build caches
--try-cache attempt to download build caches for supported packages
--json, -J output JSON-formatted results (in `lake query`)
--text output results as plain text (in `lake query`)
OUTPUT OPTIONS:
--quiet, -q hide informational logs and the progress indicator
--verbose, -v show trace logs (command invocations) and built targets
--ansi, --no-ansi toggle the use of ANSI escape codes to prettify output
--log-level=lv minimum log level to output on success
(levels: trace, info, warning, error)
--fail-level=lv minimum log level to fail a build (default: error)
--iofail fail build if any I/O or other info is logged
(same as --fail-level=info)
--wfail fail build if warnings are logged
(same as --fail-level=warning)
See `lake help <command>` for more information on a specific command.
```
Lake's command-line interface is structured into a series of subcommands.
All of the subcommands share the ability to be configured by certain environment variables and global command-line options.
Each subcommand should be understood as a utility in its own right, with its own required argument syntax and documentation.
:::paragraph
Some of Lake's commands delegate to other command-line utilities that are not included in a Lean distribution.
These utilities must be available on the `PATH` in order to use the corresponding features:
* `git` is required in order to access Git dependencies.
* `tar` is required to create or extract cloud build archives, and `curl` is required to fetch them.
* `gh` is required to upload build artifacts to GitHub releases.
Lean distributions include a C compiler toolchain.
:::
# Environment Variables
%%%
tag := "lake-environment"
%%%
```lakeHelp "env"
Execute a command in Lake's environment
USAGE:
lake env [<cmd>] [<args>...]
Spawns a new process executing `cmd` with the given `args` and with
the environment set based on the detected Lean/Lake installations and
the workspace configuration (if it exists).
Specifically, this command sets the following environment variables:
LAKE set to the detected Lake executable
LAKE_HOME set to the detected Lake home
LEAN_SYSROOT set to the detected Lean toolchain directory
LEAN_AR set to the detected Lean `ar` binary
LEAN_CC set to the detected `cc` (if not using the bundled one)
LEAN_PATH adds Lake's and the workspace's Lean library dirs
LEAN_SRC_PATH adds Lake's and the workspace's source dirs
PATH adds Lean's, Lake's, and the workspace's binary dirs
PATH adds Lean's and the workspace's library dirs (Windows)
DYLD_LIBRARY_PATH adds Lean's and the workspace's library dirs (MacOS)
LD_LIBRARY_PATH adds Lean's and the workspace's library dirs (other)
A bare `lake env` will print out the variables set and their values,
using the form NAME=VALUE like the POSIX `env` command.
```
When invoking the Lean compiler or other tools, Lake sets or modifies a number of environment variables.{index}[environment variables]
These values are system-dependent.
Invoking {lake}`env` without any arguments displays the environment variables and their values.
Otherwise, the provided command is invoked in Lake's environment.
::::paragraph
The following variables are set, overriding previous values:
:::table (align := left) -header
*
* {envVar +def}`LAKE`
* The detected Lake executable
*
* {envVar}`LAKE_HOME`
* The detected {tech}[Lake home]
*
* {envVar}`LEAN_SYSROOT`
* The detected Lean {tech}[toolchain] directory
*
* {envVar}`LEAN_AR`
* The detected Lean `ar` binary
*
* {envVar}`LEAN_CC`
* The detected C compiler (if not using the bundled one)
:::
::::
::::paragraph
The following variables are augmented with additional information:
:::table (align := left) -header
*
* {envVar}`LEAN_PATH`
* Lake's and the {tech}[workspace]'s Lean {tech}[library directories] are added.
*
* {envVar}`LEAN_SRC_PATH`
* Lake's and the {tech}[workspace]'s {tech}[source directories] are added.
*
* {envVar}`PATH`
* Lean's, Lake's, and the {tech}[workspace]'s {tech}[binary directories] are added.
On Windows, Lean's and the {tech}[workspace]'s {tech}[library directories] are also added.
*
* {envVar}`DYLD_LIBRARY_PATH`
* On macOS, Lean's and the {tech}[workspace]'s {tech}[library directories] are added.
*
* {envVar}`LD_LIBRARY_PATH`
* On platforms other than Windows and macOS, Lean's and the {tech}[workspace]'s {tech}[library directories] are added.
:::
::::
::::paragraph
Lake itself can be configured with the following environment variables:
:::table (align := left) -header
*
* {envVar +def}`ELAN_HOME`
* The location of the {ref "elan"}[Elan] installation, which is used for {ref "automatic-toolchain-updates"}[automatic toolchain updates].
*
* {envVar +def}`ELAN`
* The location of the `elan` binary, which is used for {ref "automatic-toolchain-updates"}[automatic toolchain updates].
If it is not set, an occurrence of `elan` must exist on the {envVar}`PATH`.
*
* {envVar +def}`LAKE_HOME`
* The location of the Lake installation.
This environment variable is only consulted when Lake is unable to determine its installation path from the location of the `lake` executable that's currently running.
*
* {envVar +def}`LEAN_SYSROOT`
* The location of the Lean installation, used to find the Lean compiler, the standard library, and other bundled tools.
Lake first checks whether its binary is colocated with a Lean install, using that installation if so.
If not, or if {envVar +def}`LAKE_OVERRIDE_LEAN` is true, then Lake consults {envVar}`LEAN_SYSROOT`.
If this is not set, Lake consults the {envVar +def}`LEAN` environment variable to find the Lean compiler, and attempts to find the Lean installation relative to the compiler.
If {envVar}`LEAN` is set but empty, Lake considers Lean to be disabled.
If {envVar}`LEAN_SYSROOT` and {envVar}`LEAN` are unset, the first occurrence of `lean` on the {envVar}`PATH` is used to find the installation.
*
* {envVar +def}`LEAN_CC` and {envVar +def}`LEAN_AR`
* If {envVar}`LEAN_CC` and/or {envVar}`LEAN_AR` is set, its value is used as the C compiler or `ar` command when building libraries.
If not, Lake will fall back to the bundled tool in the Lean installation.
If the bundled tool is not found, the value of {envVar +def}`CC` or {envVar +def}`AR`, followed by a `cc` or `ar` on the {envVar}`PATH`, are used.
*
* {envVar +def}`LAKE_NO_CACHE`
* If true, Lake does not use cached builds from [Reservoir](https://reservoir.lean-lang.org/) or {ref "lake-github"}[GitHub].
This environment variable can be overridden using the {lakeOpt}`--try-cache` command-line option.
*
* {envVar +def}`LAKE_ARTIFACT_CACHE`
* If true, Lake uses the artifact cache.
This is an experimental feature.
*
* {envVar +def}`LAKE_CACHE_KEY`
* Defines an authentication key for the {ref "lake-cache-remote"}[remote artifact cache].
*
* {envVar +def}`LAKE_CACHE_ARTIFACT_ENDPOINT`
* The base URL for the {ref "lake-cache-remote"}[remote artifact cache] used for artifact uploads.
If set, then {envVar}`LAKE_CACHE_REVISION_ENDPOINT` must also be set.
If neither of these are set, Lake will use Reservoir instead.
*
* {envVar +def}`LAKE_CACHE_REVISION_ENDPOINT`
* The base URL for the {ref "lake-cache-remote"}[remote artifact cache] used to upload the {tech (key := "mappings file")}[input/output mappings] for each artifact.
If set, then {envVar}`LAKE_CACHE_ARTIFACT_ENDPOINT` must also be set.
If neither of these are set, Lake will use Reservoir instead.
:::
::::
Lake considers an environment variable to be true when its value is `y`, `yes`, `t`, `true`, `on`, or `1`, compared case-insensitively.
It considers a variable to be false when its value is `n`, `no`, `f`, `false`, `off`, or `0`, compared case-insensitively.
If the variable is unset, or its value is neither true nor false, a default value is used.
```lean -show
-- Test the claim above
/--
info: def Lake.envToBool? : String → Option Bool :=
fun o =>
if ["y", "yes", "t", "true", "on", "1"].contains o.toLower = true then some true
else if ["n", "no", "f", "false", "off", "0"].contains o.toLower = true then some false else none
-/
#guard_msgs in
#print Lake.envToBool?
```
# Options
Lake's command-line interface provides a number of global options as well as subcommands that perform important tasks.
Single-character flags cannot be combined; `-HR` is not equivalent to `-H -R`.
: {lakeOptDef flag}`--version`
Lake outputs its version and exits without doing anything else.
: {lakeOptDef flag}`--help` or {lakeOptDef flag}`-h`
Lake outputs its version along with usage information and exits without doing anything else.
Subcommands may be used with {lakeOpt}`--help`, in which case usage information for the subcommand is output.
: {lakeOptDef option}`--dir DIR` or {lakeOptDef option}`-d=DIR`
Use the provided directory as location of the package instead of the current working directory.
This is not always equivalent to changing to the directory first, because the version of `lake` indicated by the current directory's {tech}[toolchain file] will be used, rather than that of `DIR`.
: {lakeOptDef option}`--file FILE` or {lakeOptDef option}`-f=FILE`
Use the specified {tech}[package configuration] file instead of the default.
: {lakeOptDef flag}`--old`
Only rebuild modified modules, ignoring transitive dependencies.
Modules that import the modified module will not be rebuilt.
In order to accomplish this, file modification times are used instead of hashes to determine whether a module has changed.
: {lakeOptDef flag}`--rehash` or {lakeOptDef flag}`-H`
Ignored cached file hashes, recomputing them.
Lake uses hashes of dependencies to determine whether to rebuild an artifact.
These hashes are cached on disk whenever a module is built.
To save time during builds, these cached hashes are used instead of recomputing each hash unless {lakeOpt}`--rehash` is specified.
: {lakeOptDef flag}`--update`
Update dependencies after the {tech}[package configuration] is loaded but prior to performing other tasks, such as a build.
This is equivalent to running `lake update` before the selected command, but it may be faster due to not having to load the configuration twice.
: {lakeOptDef option}`--packages=FILE`
Use the contents of `FILE` to specify the versions of some or all dependencies instead of the manifest.
`FILE` should be a syntactically valid manifest, but it does not need to be complete.
: {lakeOptDef flag}`--reconfigure` or {lakeOptDef flag}`-R`
Normally, the {tech}[package configuration] file is {tech (key := "elaborator") -normalize}[elaborated] when a package is first configured, with the result cached to a {tech}[`.olean` file] that is used for future invocations until the package configuration
Providing this flag causes the configuration file to be re-elaborated.
: {lakeOptDef flag}`--keep-toolchain`
By default, Lake attempts to update the local {tech}[workspace]'s {tech}[toolchain file].
Providing this flag disables {ref "automatic-toolchain-updates"}[automatic toolchain updates].
: {lakeOptDef flag}`--no-build`
Lake exits immediately if a build target is not up-to-date, returning a non-zero exit code.
: {lakeOptDef flag}`--no-cache`
Instead of using available cloud build caches, build all packages locally.
Build caches are not downloaded.
: {lakeOptDef flag}`--try-cache`
attempt to download build caches for supported packages
# Controlling Output
These options provide allow control over the {tech}[log] that is produced while building.
In addition to showing or hiding messages, a build can be made to fail when warnings or even information is emitted; this can be used to enforce a style guide that disallows output during builds.
: {lakeOptDef flag}`--quiet`, {lakeOptDef flag}`-q`
Hides informational logs and the progress indicator.
: {lakeOptDef flag}`--verbose`, {lakeOptDef flag}`-v`
Shows trace logs (typically command invocations) and built {tech}[targets].
: {lakeOptDef flag}`--ansi`, {lakeOptDef flag}`--no-ansi`
Enables or disables the use of [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) that add colors and animations to Lake's output.
: {lakeOptDef option}`--log-level=LV`
Sets the minimum level of {tech}[logs] to be shown when builds succeed.
`LV` may be `trace`, `info`, `warning`, or `error`, compared case-insensitively.
When a build fails, all levels are shown.
The default log level is `info`.
: {lakeOptDef option}`--fail-level=LV`
Sets the threshold at which a message in the {tech}[log] causes a build to be considered a failure.
If a message is emitted to the log with a level that is greater than or equal to the threshold, the build fails.
`LV` may be `trace`, `info`, `warning`, or `error`, compared case-insensitively; it is `error` by default.
: {lakeOptDef flag}`--iofail`
Causes builds to fail if any I/O or other info is logged.
This is equivalent to {lakeOpt}`--fail-level=info`.
: {lakeOptDef flag}`--wfail`
Causes builds to fail if any warnings are logged.
This is equivalent to {lakeOpt}`--fail-level=warning`.
# Automatic Toolchain Updates
%%%
tag := "automatic-toolchain-updates"
%%%
The {lake}`update` command checks for changes to dependencies, fetching their sources and updating the {tech}[manifest] accordingly.
By default, {lake}`update` also attempts to update the {tech}[root package]'s {tech}[toolchain file] when a new version of a dependency specifies an updated toolchain.
This behavior can be disabled with the {lakeOpt}`--keep-toolchain` flag.
:::paragraph
If multiple dependencies specify newer toolchains, Lake selects the newest compatible toolchain, if it exists.
To determine the newest compatible toolchain, Lake parses the toolchain listed in the packages' `lean-toolchain` files into four categories:
* Releases, which are compared by version number (e.g., `v4.4.0` < `v4.8.0` and `v4.6.0-rc1` < `v4.6.0`)
* Nightly builds, which are compared by date (e.g., `nightly-2024-01-10` < `nightly-2024-10-01`)
* Builds from pull requests to the Lean compiler, which are incomparable
* Other versions, which are also incomparable
Toolchain versions from multiple categories are incomparable.
If there is not a single newest toolchain, Lake will print a warning and continue updating without changing the toolchain.
:::
If Lake does find a new toolchain, then it updates the {tech}[workspace]'s `lean-toolchain` file accordingly and restarts the {lake}`update` using the new toolchain's Lake.
If {ref "elan"}[Elan] is detected, it will spawn the new Lake process via `elan run` with the same arguments Lake was initially run with.
If Elan is missing, it will prompt the user to restart Lake manually and exit with a special error code (namely, `4`).
The Elan executable used by Lake can be configured using the {envVar}`ELAN` environment variable.
# Creating Packages
```lakeHelp "new"
Create a Lean package in a new directory
USAGE:
lake [+<lean-version>] new <name> [<template>][.<language>]
If you are using Lake through Elan (which is standard), you can create a
package with a specific Lean version via the `+` option.
The initial configuration and starter files are based on the template:
std library and executable; default
exe executable only
lib library only
math-lax library only with a Mathlib dependency
math library with Mathlib standards for linting and workflows
Templates can be suffixed with `.lean` or `.toml` to produce a Lean or TOML
version of the configuration file, respectively. The default is TOML.
```
:::lake new "name [template][\".\"language]"
Running {lake}`new` creates an initial Lean package in a new directory.
This command is equivalent to creating a directory named {lakeMeta}`name` and then running {lake}`init`
:::
:::lake init "name [template][\".\"language]"
Running {lake}`init` creates an initial Lean package in the current directory.
The package's contents are based on a template, with the names of the {tech}[package], its {tech}[targets], and their {tech}[module roots] derived from the name of the current directory.
The {lakeMeta}`template` may be:
: `std` (default)
Creates a package that contains a library and an executable.
: `exe`
Creates a package that contains only an executable.
: `lib`
Creates a package that contains only a library.
: `math`
Creates a package that contains a library that depends on [Mathlib](https://github.com/leanprover-community/mathlib4).
The {lakeMeta}`language` selects the file format used for the {tech}[package configuration] file and may be `lean` (the default) or `toml`.
:::
:::TODO
Example of `lake init` or `lake new`
:::
# Building and Running
```lakeHelp "build"
Build targets
USAGE:
lake build [<targets>...] [-o <mappings>]
A target is specified with a string of the form:
[@[<package>]/][<target>|[+]<module>][:<facet>]
You can also use the source path of a module as a target. For example,
lake build Foo/Bar.lean:o
will build the Lean module (within the workspace) whose source file is
`Foo/Bar.lean` and compile the generated C file into a native object file.
The `@` and `+` markers can be used to disambiguate packages and modules
from file paths or other kinds of targets (e.g., executables or libraries).
LIBRARY FACETS: build the library's ...
leanArts (default) Lean artifacts (*.olean, *.ilean, *.c files)
static static artifact (*.a file)
shared shared artifact (*.so, *.dll, or *.dylib file)
MODULE FACETS: build the module's ...
deps dependencies (e.g., imports, shared libraries, etc.)
leanArts (default) Lean artifacts (*.olean, *.ilean, *.c files)
olean OLean (binary blob of Lean data for importers)
ilean ILean (binary blob of metadata for the Lean LSP server)
c compiled C file
bc compiled LLVM bitcode file
c.o compiled object file (of its C file)
bc.o compiled object file (of its LLVM bitcode file)
o compiled object file (of its configured backend)
dynlib shared library (e.g., for `--load-dynlib`)
TARGET EXAMPLES: build the ...
a default facet(s) of target `a`
@a default target(s) of package `a`
+A default facet(s) of module `A`
@/a default facet(s) of target `a` of the root package
@a/b default facet(s) of target `b` of package `a`
@a/+A:c C file of module `A` of package `a`
:foo facet `foo` of the root package
A bare `lake build` command will build the default target(s) of the root
package. Package dependencies are not updated during a build.
With the Lake cache enabled, the `-o` option will cause Lake to track the
input-to-outputs mappings of targets in the root package touched during the
build and write them to the specified file at the end of the build. These
mappings can then be used to upload build artifacts to a remote cache with
`lake cache put`.
```
::::lake build "[targets...] [\"-o\" mappings]"
Builds the specified facts of the specified targets.
Each of the {lakeMeta}`targets` is specified by a string of the form:
{lakeArgs}`[["@"]package["/"]][target|["+"]module][":"facet]`
The optional {keyword}`@` and {keyword}`+` markers can be used to disambiguate packages and modules from file paths as well as executables, and libraries, which are specified by name as {lakeMeta}`target`.
If not provided, {lakeMeta}`package` defaults to the {tech}[workspace]'s {tech}[root package].
If the same target name exists in multiple packages in the workspace, then the first occurrence of the target name found in a topological sort of the package dependency graph is selected.
Module targets may also be specified by their filename, with an optional facet after a colon.
The available {tech}[facets] depend on whether a package, library, executable, or module is to be built.
They are listed in {ref "lake-facets"}[the section on facets].
When using the {ref "lake-cache"}[local artifact cache], the {lakeOptDef option}`-o` option saves a {tech}[mappings file] that tracks the inputs and outputs of each step in the build.
This file can be used with {lake}`cache get` and {lake}`cache put` to interact with a remote cache.
The mappings file is in JSON Lines format, with one valid JSON object per line, and its filename extension is conventionally `.jsonl`.
::::
::::example "Target and Facet Specifications"
:::table
*
- `a`
- The {tech}[default facet](s) of target `a`
*
- `@a`
- The {tech}[default targets] of {tech}[package] `a`
*
- `+A`
- The Lean artifacts of module `A` (because the default facet of modules is `leanArts`)
*
- `@a/b`
- The default facet of target `b` of package `a`
*
- `@a/+A:c`
- The C file compiled from module `A` of package `a`
*
- `:foo`
- The {tech}[root package]'s facet `foo`
*
- `A/B/C.lean:o`
- The compiled object code for the module in the file `A/B/C.lean`
:::
::::
```lakeHelp "check-build"
Check if any default build targets are configured
USAGE:
lake check-build
Exits with code 0 if the workspace's root package has any
default targets configured. Errors (with code 1) otherwise.
Does NOT verify that the configured default targets are valid.
It merely verifies that some are specified.
```
:::lake «check-build»
Exits with code 0 if the {tech}[workspace]'s {tech}[root package] has any {tech}[default targets] configured.
Errors (with exit code 1) otherwise.
{lake}`check-build` does *not* verify that the configured default targets are valid.
It merely verifies that at least one is specified.
:::
```lakeHelp "exe"
Build an executable target and run it in Lake's environment
USAGE:
lake exe <exe-target> [<args>...]
ALIAS: lake exec
Looks for the executable target in the workspace (see `lake help build` to
learn how to specify targets), builds it if it is out of date, and then runs
it with the given `args` in Lake's environment (see `lake help env` for how
the environment is set up).
```
```lakeHelp "query"
Build targets and output results
USAGE:
lake query [<targets>...]
Builds a set of targets, reporting progress on standard error and outputting
the results on standard out. Target results are output in the same order they
are listed and end with a newline. If `--json` is set, results are formatted as
JSON. Otherwise, they are printed as raw strings. Targets which do not have
output configured will be printed as an empty string or `null`.
See `lake help build` for information on and examples of targets.
```
:::lake query "[targets...]"
Builds a set of targets, reporting progress on standard error and outputting the results on standard out.
Target results are output in the same order they are listed and end with a newline.
If `--json` is set, results are formatted as JSON.
Otherwise, they are printed as raw strings.
Targets which do not have output configured will be printed as an empty string or `null`.
For executable targets, the output is the path to the built executable.
Targets are specified using the same syntax as in {lake}`build`.
:::
:::lake exe "«exe-target» [args...]" (alias := exec)
Looks for the executable target {lakeMeta}`exe-target` in the workspace, builds it if it is out of date, and then runs
it with the given {lakeMeta}`args` in Lake's environment.
See {lake}`build` for the syntax of target specifications and {lake}`env` for a description of how the environment is set up.
:::
```lakeHelp "clean"
Remove build outputs
USAGE:
lake clean [<package>...]
If no package is specified, deletes the build directories of every package in
the workspace. Otherwise, just deletes those of the specified packages.
```
:::lake clean "[packages...]"
If no package is specified, deletes the {tech}[build directories] of every package in the workspace.
Otherwise, it just deletes those of the specified {lakeMeta}`packages`.
:::
```lakeHelp "env"
Execute a command in Lake's environment
USAGE:
lake env [<cmd>] [<args>...]
Spawns a new process executing `cmd` with the given `args` and with
the environment set based on the detected Lean/Lake installations and
the workspace configuration (if it exists).
Specifically, this command sets the following environment variables:
LAKE set to the detected Lake executable
LAKE_HOME set to the detected Lake home
LEAN_SYSROOT set to the detected Lean toolchain directory
LEAN_AR set to the detected Lean `ar` binary
LEAN_CC set to the detected `cc` (if not using the bundled one)
LEAN_PATH adds Lake's and the workspace's Lean library dirs
LEAN_SRC_PATH adds Lake's and the workspace's source dirs
PATH adds Lean's, Lake's, and the workspace's binary dirs
PATH adds Lean's and the workspace's library dirs (Windows)
DYLD_LIBRARY_PATH adds Lean's and the workspace's library dirs (MacOS)
LD_LIBRARY_PATH adds Lean's and the workspace's library dirs (other)
A bare `lake env` will print out the variables set and their values,
using the form NAME=VALUE like the POSIX `env` command.
```
::::lake env "[cmd [args...]]"
When {lakeMeta}`cmd` is provided, it is executed in {ref "lake-environment"}[the Lake environment] with arguments {lakeMeta}`args`.
If {lakeMeta}`cmd` is not provided, Lake prints the environment in which it runs tools.
This environment is system-specific.
::::
```lakeHelp "lean"
Elaborate a Lean file in the context of the Lake workspace
USAGE:
lake lean <file> [-- <args>...]
Build the imports of the given file and then runs `lean` on it using
the workspace's root package's additional Lean arguments and the given args
(in that order). The `lean` process is executed in Lake's environment like
`lake env lean` (see `lake help env` for how the environment is set up).
```
:::lake lean "file [\"--\" args...]"
Builds the imports of the given {lakeMeta}`file` and then runs `lean` on it using the {tech}[workspace]'s {tech}[root package]'s additional Lean arguments and the given {lakeMeta}`args`, in that order.
The `lean` process is executed in {ref "lake-environment"}[Lake's environment].
:::
# Module Imports
```lakeHelp shake
Minimize imports in Lean source files
USAGE:
lake shake [OPTIONS] [<MODULE>...]
Checks the current project for unused imports by analyzing generated `.olean`
files to deduce required imports and ensuring that every import contributes
some constant or other elaboration dependency.
ARGUMENTS:
<MODULE> A module path like `Mathlib`. All files transitively
reachable from the provided module(s) will be checked.
If not specified, uses the package's default targets.
OPTIONS:
--force Skip the `lake build --no-build` sanity check
--keep-implied Preserve imports implied by other imports
--keep-prefix Prefer parent module imports over specific submodules
--keep-public Preserve all `public` imports for API stability
--add-public Add new imports as `public` if they were in the
original public closure
--explain Show which constants require each import
--fix Apply suggested fixes directly to source files
--gh-style Output in GitHub problem matcher format
ANNOTATIONS:
Source files can contain special comments to control shake behavior:
* `module -- shake: keep-downstream`
Preserves this module in all downstream modules
* `module -- shake: keep-all`
Preserves all existing imports in this module
* `import X -- shake: keep`
Preserves this specific import
```
::::lake shake "[options...] [module ...]"
Checks the current project for unused imports by analyzing generated {tech}[`.olean` files] to deduce required imports, ensuring that every import contributes some constant or other elaboration dependency.
If a {lakeMeta}`module` is specified, then it and all files that are transitively reachable from it are checked. Otherwise, the package's {tech}[default targets] are checked.
:::paragraph
Source files can contain special comments to control the behavior of {lake}`shake`:
: `module -- shake: keep-downstream`
Preserves this module in all downstream modules.
: `module -- shake: keep-all`
Preserves all existing imports in this module.
: `import X -- shake: keep`
Preserves this specific import.
:::
:::paragraph
The {lakeMeta}`options` may be:
: `--force`
Skip the `lake build --no-build` sanity check
: `--keep-implied`
Preserve imports implied by other imports
: `--keep-prefix`
Prefer parent module imports over specific submodules
: `--keep-public`
Preserve all `public` imports for API stability
: `--add-public`
Add new imports as `public` if they were in the original public closure
: `--explain`
Show which constants require each import
: `--fix`
Apply suggested fixes directly to source files
: `--gh-style`
Output in GitHub problem matcher format
:::
::::
# Development Tools
Lake includes support for specifying standard development tools and workflows.
On the command line, these tools can be invoked using the appropriate `lake` subcommands.
## Tests and Linters
```lakeHelp test
Test the workspace's root package using its configured test driver
USAGE:
lake test [-- <args>...]
A test driver can be configured by either setting the 'testDriver'
package configuration option or by tagging a script, executable, or library
`@[test_driver]`. A definition in a dependency can be used as a test driver
by using the `<pkg>/<name>` syntax for the 'testDriver' configuration option.
A script test driver will be run with the package configuration's
`testDriverArgs` plus the CLI `args`. An executable test driver will be
built and then run like a script. A library test driver will just be built.
```
:::lake test " [\"--\" args...]"
Test the workspace's root package using its configured {tech}[test driver].
A test driver that is an executable will be built and then run with the package configuration's `testDriverArgs` plus the CLI {lakeMeta}`args`.
A test driver that is a {tech}[Lake script] is run with the same arguments as an executable test driver.
A library test driver will just be built; it is expected that tests are implemented such that failures cause the build to fail via elaboration-time errors.
:::
```lakeHelp lint
Lint the workspace's root package using its configured lint driver
USAGE:
lake lint [-- <args>...]
A lint driver can be configured by either setting the `lintDriver` package
configuration option by tagging a script or executable `@[lint_driver]`.
A definition in dependency can be used as a test driver by using the
`<pkg>/<name>` syntax for the 'testDriver' configuration option.
A script lint driver will be run with the package configuration's
`lintDriverArgs` plus the CLI `args`. An executable lint driver will be
built and then run like a script.
```
:::lake lint " [\"--\" args...]"
Lint the workspace's root package using its configured lint driver
A script lint driver will be run with the package configuration's
`lintDriverArgs` plus the CLI `args`. An executable lint driver will be
built and then run like a script.
:::
```lakeHelp "check-test"
Check if there is a properly configured test driver
USAGE:
lake check-test
Exits with code 0 if the workspace's root package has a properly
configured lint driver. Errors (with code 1) otherwise.
Does NOT verify that the configured test driver actually exists in the
package or its dependencies. It merely verifies that one is specified.
```
:::lake «check-test»
Check if there is a properly configured test driver
Exits with code 0 if the workspace's root package has a properly
configured lint driver. Errors (with code 1) otherwise.
Does NOT verify that the configured test driver actually exists in the
package or its dependencies. It merely verifies that one is specified.
This is useful for distinguishing between failing tests and incorrectly configured packages.
:::
```lakeHelp "check-lint"
Check if there is a properly configured lint driver
USAGE:
lake check-lint
Exits with code 0 if the workspace's root package has a properly
configured lint driver. Errors (with code 1) otherwise.
Does NOT verify that the configured lint driver actually exists in the
package or its dependencies. It merely verifies that one is specified.
```
:::lake «check-lint»
Check if there is a properly configured lint driver
Exits with code 0 if the workspace's root package has a properly
configured lint driver. Errors (with code 1) otherwise.
Does NOT verify that the configured lint driver actually exists in the
package or its dependencies. It merely verifies that one is specified.
This is useful for distinguishing between failing lints and incorrectly configured packages.
:::
## Scripts
```lakeHelp script
Manage Lake scripts
USAGE:
lake script <COMMAND>
COMMANDS:
list list available scripts
run <script> run a script
doc <script> print the docstring of a given script
See `lake script help <command>` for more information on a specific command.
```
```lakeHelp scripts
List available scripts
USAGE:
lake script list
ALIAS: lake scripts
This command prints the list of all available scripts in the workspace.
```
:::lake script list (alias := scripts)
Lists the available {ref "lake-scripts"}[scripts] in the workspace.
:::
```lakeHelp run
Run a script
USAGE:
lake script run [[<package>/]<script>] [<args>...]
ALIAS: lake run
This command runs the `script` of the workspace (or the specific `package`),
passing `args` to it.
A bare `lake run` command will run the default script(s) of the root package
(with no arguments).
```
:::lake script run "[[package\"/\"]script [args...]]" (alias := run)
This command runs the {lakeMeta}`script` of the workspace (or the specified {lakeMeta}`package`),
passing {lakeMeta}`args` to it.
A bare {lake}`run` command will run the default script(s) of the root package(with no arguments).
:::
:::lake script doc "script"
Prints the documentation comment for {lakeMeta}`script`.
:::
## Language Server
```lakeHelp serve
Start the Lean language server
USAGE:
lake serve [-- <args>...]
Run the language server of the Lean installation (i.e., via `lean --server`)
with the package configuration's `moreServerArgs` field and `args`.
```
:::lake serve "[\"--\" args...]"
Runs the Lean language server in the workspace's root project with the {tech}[package configuration]'s `moreServerArgs` field and {lakeMeta}`args`.
This command is typically invoked by editors or other tooling, rather than manually.
:::
# Dependency Management
```lakeHelp update
Update dependencies and save them to the manifest
USAGE:
lake update [<package>...]
ALIAS: lake upgrade
Updates the Lake package manifest (i.e., `lake-manifest.json`),
downloading and upgrading packages as needed. For each new (transitive) git
dependency, the appropriate commit is cloned into a subdirectory of
`packagesDir`. No copy is made of local dependencies.
If a set of packages are specified, said dependencies are upgraded to
the latest version compatible with the package's configuration (or removed if
removed from the configuration). If there are dependencies on multiple versions
of the same package, the version materialized is undefined.
A bare `lake update` will upgrade all dependencies.
```
:::lake update "[packages...]"
Updates the Lake package {tech}[manifest] (i.e., `lake-manifest.json`), downloading and upgrading packages as needed.
For each new (transitive) {tech}[Git dependency], the appropriate commit is cloned into a subdirectory of the workspace's {tech}[package directory].
No copy is made of local dependencies.
If a set of packages {lakeMeta}`packages` is specified, then these dependencies are upgraded to the latest version compatible with the package's configuration (or removed if removed from the configuration).
If there are dependencies on multiple versions of the same package, an arbitrary version is selected.
A bare {lake}`update` will upgrade all dependencies.
:::
# Packaging and Distribution
```lakeHelp "upload"
Upload build artifacts to a GitHub release
USAGE:
lake upload <tag>
Packs the root package's `buildDir` into a `tar.gz` archive using `tar` and
then uploads the asset to the pre-existing GitHub release `tag` using `gh`.
```
:::lake upload "tag"
Packs the root package's `buildDir` into a `tar.gz` archive using `tar` and then uploads the asset to the pre-existing [GitHub](https://github.com) release {lakeMeta}`tag` using [`gh`](https://cli.github.com/).
Other hosts are not yet supported.
:::
## Cached Cloud Builds
*These commands are still experimental.*
They are likely change in future versions of Lake based on user feedback.
Packages that use Reservoir cloud build archives should enable the {tomlField Lake.PackageConfig}`platformIndependent` setting.
```lakeHelp "pack"
Pack build artifacts into an archive for distribution
USAGE:
lake pack [<file.tgz>]
Packs the root package's `buildDir` into a gzip tar archive using `tar`.
If a path for the archive is not specified, creates an archive in the package's
Lake directory (`.lake`) named according to its `buildArchive` setting.
Does NOT build any artifacts. It just packs the existing ones.
```
:::lake pack "[archive.tar.gz]"
Packs the root package's {tech}[build directory] into a gzipped tar archive using `tar`.
If a path for the archive is not specified, the archive in the package's Lake directory (`.lake`) and named according to its `buildArchive` setting.
This command does not build any artifacts: it only archives what is present.
Users should ensure that the desired artifacts are present before running this command.
:::
```lakeHelp "unpack"
Unpack build artifacts from a distributed archive
USAGE:
lake unpack [<file.tgz>]
Unpack build artifacts from the gzip tar archive `file.tgz` into the root
package's `buildDir`. If a path for the archive is not specified, uses the
the package's `buildArchive` in its Lake directory (`.lake`).
```
:::lake unpack "[archive.tar.gz]"
Unpacks the contents of the gzipped tar archive {lakeMeta}`archive.tgz` into the root package's {tech}[build directory].
If {lakeMeta}`archive.tgz` is not specified, the package's `buildArchive` setting is used to determine a filename, and the file is expected in package's Lake directory (`.lake`).
:::
# Local Caches
{lake}`cache get` and {lake}`cache put` are used to interact with remote cache servers.
These commands are *experimental*, and are only useful if the {ref "lake-cache"}[local cache] is enabled.
Both commands can be configured to use a {deftech}[cache scope], which is a server-specific identifier for a set of artifacts for a package.
On Reservoir, scopes are currently identical with GitHub repositories, but may include toolchain and platform information in the future.
Other remote artifact caches may use any scope scheme that they want.
Cache scopes are specified using the {lakeOptDef option}`--scope=` option.
Cache scopes are not identical to the scopes used to require packages from Reservoir.
```lakeCacheHelp
Manage the Lake cache
USAGE:
lake cache <COMMAND>
COMMANDS:
get [<mappings>] download artifacts into the Lake cache
put <mappings> upload artifacts to a remote cache
See `lake cache help <command>` for more information on a specific command.
```
```lakeCacheHelp get
Download artifacts from a remote service into the Lake cache
USAGE:
lake cache get [<mappings>]
OPTIONS:
--max-revs=<n> backtrack up to n revisions (default: 100)
--rev=<commit-hash> uses this exact revision to lookup artifacts
--repo=<github-repo> GitHub repository of the package or a fork
--platform=<target-triple> with Reservoir or --repo, sets the platform
--toolchain=<name> with Reservoir or --repo, sets the toolchain
--scope=<remote-scope> scope for a custom endpoint
Downloads artifacts for packages in the workspace from a remote cache service.
The cache service used can be configured via the environment variables:
LAKE_CACHE_ARTIFACT_ENDPOINT base URL for artifact downloads
LAKE_CACHE_REVISION_ENDPOINT base URL for the mapping download
If neither of these are set, Lake will use Reservoir.
If an input-to-outputs mappings file, `--scope`, or `--repo` is provided,
Lake will download artifacts for the root package. Otherwise, it will use
Reservoir to download artifacts for each dependency in workspace (in order).
Non-Reservoir dependencies will be skipped.
To determine the artifacts to download, Lake searches for input-to-output
mappings for a given build of the package via the cache service. This mapping
is identified by a Git revision and prefixed with a scope derived from the
package's name, GitHub repository, Lean toolchain, and current platform.
The exact configuration can be customized using options.
For Reservoir, setting `--repo` will make Lake lookup artifacts for the root
package by a repository name, rather than the package's. This can be used to
download artifacts for a fork of the Reservoir package (if such artifacts are
available). The `--platform` and `--toolchain` options can be used to download
artifacts for a different platform/toolchain configuration than Lake detects.
For a custom endpoint, the full prefix Lake uses can be set via `--scope`.
If `--rev` is not set, Lake uses the package's current revision to lookup
artifacts. If no mappings are found, Lake will backtrack the Git history up to
`--max-revs`, looking for a revision with mappings. If `--max-revs` is 0, Lake
will search the repository's entire history (or as far as Git will allow).
If a download for an artifact fails or the download process for a whole
package fails, Lake will report this and continue on to the next. Once done,
if any download failed, Lake will exit with a nonzero status code.
```
:::lake cache get "[mappings] [\"--max-revs=\" cn] [\"--rev=\" «commit-hash»] [\"--repo=\" «github-repo»] [\"--platform=\" «target-triple»] [\"--toolchain=\"«name»] [\"--scope=\" «remote-scope»]"
Downloads artifacts for packages in the workspace from a remote cache service to the local Lake {tech (key:="local cache")}[artifact cache].
The remote cache service used can be configured using {envVar}`LAKE_CACHE_ARTIFACT_ENDPOINT` and {envVar}`LAKE_CACHE_REVISION_ENDPOINT`.
If neither of these are set, Lake will use Reservoir instead.
If an input-to-outputs {lakeMeta}`mappings` file, a {lakeMeta}`remote-scope`, or a {lakeMeta}`github-repo` is provided, Lake will download artifacts for the root package.
Otherwise, it will download artifacts for each package in the root's dependency tree in order (using Reservoir).
Non-Reservoir dependencies will be skipped.
For Reservoir, setting {lakeOpt}`--repo` will make Lake lookup artifacts for the root package by a repository name, rather than the package's.
This can be used to download artifacts for a fork of the Reservoir package (if such artifacts are available).
The {lakeOpt}`--platform` and {lakeOpt}`--toolchain` options can be used to download artifacts for a different platform/toolchain configuration than Lake detects.
For a custom endpoint, the full prefix Lake uses can be set via {lakeOpt}`--scope`.
If `--rev` is not set, Lake uses the package's current revision to look up artifacts.
Lake will download the artifacts for the most recent commit with available mappings.
It will backtrack up to {lakeOptDef option}`--max-revs`, which defaults to 100.
If set to 0, Lake will search the repository's whole history, or as far back as Git will allow.
While downloading, Lake will continue on when a download for an artifact fails or if the download process for a whole package fails.
However, it will report this and exit with a nonzero status code in such cases.
:::
```lakeCacheHelp put
Upload artifacts from the Lake cache to a remote service
USAGE:
lake cache put <mappings> <scope-option>
Uploads the input-to-outputs mappings contained in the specified file along
with the corresponding output artifacts to a remote cache. The cache service
used is configured via the environment variables:
LAKE_CACHE_KEY authentication key for requests
LAKE_CACHE_ARTIFACT_ENDPOINT base URL for artifact uploads
LAKE_CACHE_REVISION_ENDPOINT base URL for the mapping upload
Files are uploaded using the AWS Signature Version 4 authentication protocol
via `curl`. Thus, the service should generally be an S3-compatible bucket.
Since Lake does not currently use cryptographically secure hashes for
artifacts and outputs, uploads to the cache are prefixed with a scope to avoid
clashes. This scoped is configured with the following options:
--scope=<remote-scope> sets a fixed scope
--repo=<github-repo> uses the repository + toolchain & platform
--toolchain=<name> with --repo, sets the toolchain
--platform=<target-triple> with --repo, sets the platform
At least one of `--scope` or `--repo` must be set. If `--repo` is used, Lake
will produce a scope by augmenting the repository with toolchain and platform
information as it deems necessary. If `--scope` is set, Lake will use the
specified scope verbatim.
Artifacts are uploaded to the artifact endpoint with a file name derived
from their Lake content hash (and prefixed by the repository or scope).
The mappings file is uploaded to the revision endpoint with a file name
derived from the package's current Git revision (and prefixed by the
full scope). As such, the command will warn if the work tree currently
has changes.
```
::::lake cache put "mappings «scope-option»"
Uploads the input-to-outputs mappings contained in the specified file along with the corresponding output artifacts to a remote cache.
The remote cache service used can be configured using {envVar}`LAKE_CACHE_KEY`, {envVar}`LAKE_CACHE_ARTIFACT_ENDPOINT` and {envVar}`LAKE_CACHE_REVISION_ENDPOINT`.
Files are uploaded using the AWS Signature Version 4 authentication protocol via `curl`. Thus, the service should generally be an S3-compatible bucket.
Since Lake does not currently use cryptographically secure hashes for
artifacts and outputs, uploads to the cache are prefixed with a scope to avoid
clashes. This scoped is configured with the following options:
:::table -header
*
* {lakeOpt}`--scope`{lit}`=`{lakeMeta}`<remote-scope>`
* Sets a fixed scope
*
* {lakeOptDef option}`--repo`{lit}`=`{lakeMeta}`<github-repo>`
* Uses the repository + toolchain & platform
*
* {lakeOptDef option}`--toolchain`{lit}`=`{lakeMeta}`<name>`
* With {lakeOpt}`--repo`, sets the toolchain
*
* {lakeOptDef option}`--platform`{lit}`=`{lakeMeta}`<target-triple>`
* With {lakeOpt}`--repo`, sets the platform
:::
At least one of {lakeOpt}`--scope` or {lakeOpt}`--repo` must be set.
If {lakeOpt}`--repo` is used, Lake will produce a scope by augmenting the repository with toolchain and platform information as it deems necessary.
If {lakeOpt}`--scope` is set, Lake will use the specified scope verbatim.
Artifacts are uploaded to the artifact endpoint with a file name derived from their Lake content hash (and prefixed by the repository or scope).
The mappings file is uploaded to the revision endpoint with a file name derived from the package's current Git revision (and prefixed by the full scope).
As such, the command will warn if the work tree currently has changes.
::::
# Configuration Files
```lakeHelp "translate-config"
Translate a Lake configuration file into a different language
USAGE:
lake translate-config <lang> [<out-file>]
Translates the loaded package's configuration into another of
Lake's supported configuration languages (i.e., either `lean` or `toml`).
The produced file is written to `out-file` or, if not provided, the path of
the configuration file with the new language's extension. If the output file
already exists, Lake will error.
Translation is lossy. It does not preserve comments or formatting and
non-declarative configuration will be discarded.
```
:::lake «translate-config» "lang [«out-file»]"
Translates the loaded package's configuration into another of Lake's supported configuration languages (i.e., either `lean` or `toml`).
The produced file is written to `out-file` or, if not provided, the path of the configuration file with the new language's extension.
If the output file already exists, Lake will error.
Translation is lossy.
It does not preserve comments or formatting and non-declarative configuration is discarded.
::: |
reference-manual/Manual/BasicTypes/Subtype.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.Array.Subarray
import Manual.BasicTypes.Array.FFI
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Subtypes" =>
%%%
tag := "Subtype"
%%%
The structure {name}`Subtype` represents the elements of a type that satisfy some predicate.
They are used pervasively both in mathematics and in programming; in mathematics, they are used similarly to subsets, while in programming, they allow information that is known about a value to be represented in a way that is visible to Lean's logic.
Syntactically, an element of a {name}`Subtype` resembles a tuple of the base type's element and the proof that it satisfies the proposition.
They differ from dependent pair types ({name}`Sigma`) in that the second element is a proof of a proposition rather than data, and from existential quantification in that the entire {name}`Subtype` is a type rather than a proposition.
Even though they are pairs syntactically, {name}`Subtype` should really be thought of as elements of the base type with associated proof obligations.
Subtypes are {ref "inductive-types-trivial-wrappers"}[trivial wrappers].
They are thus represented identically to the base type in compiled code.
{docstring Subtype}
::::leanSection
```lean -show
variable {α : Type u} {p : Prop}
```
:::syntax term (title := "Subtypes")
```grammar
{ $x : $t:term // $t:term }
```
{lean}`{ x : α // p }` is a notation for {lean}`Subtype fun (x : α) => p`.
The type ascription may be omitted:
```grammar
{ $x:ident // $t:term }
```
{lean}`{ x // p }` is a notation for {lean}`Subtype fun (x : _) => p`.
:::
::::
Due to {tech}[proof irrelevance] and {tech (key := "η-equivalence")}[η-equality], two elements of a subtype are definitionally equal when the elements of the base type are definitionally equal.
In a proof, the {tactic}`ext` tactic can be used to transform a goal of equality of elements of a subtype into equality of their values.
:::example "Definitional Equality of Subtypes"
The non-empty strings {lean}`s1` and {lean}`s2` are definitionally equal despite the fact that their embedded proof terms are different.
No case splitting is needed in order to prove that they are equal.
```lean
def NonEmptyString := { x : String // x ≠ "" }
def s1 : NonEmptyString :=
⟨"equal", ne_of_beq_false rfl⟩
def s2 : NonEmptyString where
val := "equal"
property :=
fun h =>
List.cons_ne_nil _ _ (String.data_eq_of_eq h)
theorem s1_eq_s2 : s1 = s2 := by rfl
```
:::
:::example "Extensional Equality of Subtypes"
The non-empty strings {lean}`s1` and {lean}`s2` are definitionally equal.
Ignoring that fact, the equality of the embedded strings can be used to prove that they are equal.
The {tactic}`ext` tactic transforms a goal that consists of equality of non-empty strings into a goal that consists of equality of the strings.
```lean
abbrev NonEmptyString := { x : String // x ≠ "" }
def s1 : NonEmptyString :=
⟨"equal", ne_of_beq_false rfl⟩
def s2 : NonEmptyString where
val := "equal"
property :=
fun h =>
List.cons_ne_nil _ _ (String.data_eq_of_eq h)
theorem s1_eq_s2 : s1 = s2 := by
ext
dsimp only [s1, s2]
rfl
```
:::
There is a coercion from a subtype to its base type.
This allows subtypes to be used in positions where the base type is expected, essentially erasing the proof that the value satisfies the predicate.
:::example "Subtype Coercions"
Elements of subtypes can be coerced to their base type.
Here, {name}`nine` is coerced from a subtype of `Nat` that contains multiples of {lean (type := "Nat")}`3` to {lean}`Nat`.
```lean (name := subtype_coe)
abbrev DivBy3 := { x : Nat // x % 3 = 0 }
def nine : DivBy3 := ⟨9, by rfl⟩
set_option eval.type true in
#eval Nat.succ nine
```
```leanOutput subtype_coe
10 : Nat
```
::: |
reference-manual/Manual/BasicTypes/Sum.lean | import VersoManual
import Manual.Meta
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Sum Types" =>
%%%
tag := "sum-types"
%%%
{deftech}_Sum types_ represent a choice between two types: an element of the sum is an element of one of the other types, paired with an indication of which type it came from.
Sums are also known as disjoint unions, discriminated unions, or tagged unions.
The constructors of a sum are also called {deftech}_injections_; mathematically, they can be considered as injective functions from each summand to the sum.
::::leanSection
```lean -show
universe u v
```
:::paragraph
There are two varieties of the sum type:
* {lean}`Sum` is {tech (key := "universe polymorphism")}[polymorphic] over all {lean}`Type` {tech}[universes], and is never a {tech}[proposition].
* {lean}`PSum` is allows the summands to be propositions or types. Unlike {name}`Or`, the {name}`PSum` of two propositions is still a type, and non-propositional code can check which injection was used to construct a given value.
Manually-written Lean code almost always uses only {lean}`Sum`, while {lean}`PSum` is used as part of the implementation of proof automation.
This is because it imposes problematic constraints that universe level unification cannot solve.
In particular, this type is in the universe {lean}`Sort (max 1 u v)`, which can cause problems for universe level unification because the equation `max 1 u v = ?u + 1` has no solution in level arithmetic.
`PSum` is usually only used in automation that constructs sums of arbitrary types.
:::
::::
{docstring Sum}
{docstring PSum}
# Syntax
%%%
tag := "sum-syntax"
%%%
The names {name}`Sum` and {name}`PSum` are rarely written explicitly.
Most code uses the corresponding infix operators.
```lean -show
section
variable {α : Type u} {β : Type v}
```
:::syntax term (title := "Sum Types")
```grammar
$_ ⊕ $_
```
{lean}`α ⊕ β` is notation for {lean}`Sum α β`.
:::
```lean -show
end
```
```lean -show
section
variable {α : Sort u} {β : Sort v}
```
:::syntax term (title := "Potentially-Propositional Sum Types")
```grammar
$_ ⊕' $_
```
{lean}`α ⊕' β` is notation for {lean}`PSum α β`.
:::
```lean -show
end
```
# API Reference
%%%
tag := "sum-api"
%%%
Sum types are primarily used with {tech}[pattern matching] rather than explicit function calls from an API.
As such, their primary API is the constructors {name Sum.inl}`inl` and {name Sum.inr}`inr`.
## Case Distinction
{docstring Sum.isLeft}
{docstring Sum.isRight}
## Extracting Values
{docstring Sum.elim}
{docstring Sum.getLeft}
{docstring Sum.getLeft?}
{docstring Sum.getRight}
{docstring Sum.getRight?}
## Transformations
{docstring Sum.map}
{docstring Sum.swap}
## Inhabited
The {name}`Inhabited` definitions for {name}`Sum` and {name}`PSum` are not registered as instances.
This is because there are two separate ways to construct a default value (via {name Sum.inl}`inl` or {name Sum.inr}`inr`), and instance synthesis might result in either choice.
The result could be situations where two identically-written terms elaborate differently and are not {tech (key := "definitional equality")}[definitionally equal].
Both types have {name}`Nonempty` instances, for which {tech}[proof irrelevance] makes the choice of {name Sum.inl}`inl` or {name Sum.inr}`inr` not matter.
This is enough to enable {keyword}`partial` functions.
For situations that require an {name}`Inhabited` instance, such as programs that use {keyword}`panic!`, the instance can be explicitly used by adding it to the local context with {keywordOf Lean.Parser.Term.have}`have` or {keywordOf Lean.Parser.Term.let}`let`.
:::example "Inhabited Sum Types"
In Lean's logic, {keywordOf Lean.Parser.Term.panic}`panic!` is equivalent to the default value specified in its type's {name}`Inhabited` instance.
This means that the type must have such an instance—a {name}`Nonempty` instance combined with the axiom of choice would render the program non-computable.
Products have the right instance:
```lean
example : Nat × String := panic! "Can't find it"
```
Sums do not, by default:
```lean +error (name := panic)
example : Nat ⊕ String := panic! "Can't find it"
```
```leanOutput panic
failed to synthesize instance of type class
Inhabited (Nat ⊕ String)
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
The desired instance can be made available to instance synthesis using {keywordOf Lean.Parser.Term.have}`have`:
```lean
example : Nat ⊕ String :=
have : Inhabited (Nat ⊕ String) := Sum.inhabitedLeft
panic! "Can't find it"
```
:::
{docstring Sum.inhabitedLeft}
{docstring Sum.inhabitedRight}
{docstring PSum.inhabitedLeft}
{docstring PSum.inhabitedRight} |
reference-manual/Manual/BasicTypes/String.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.String.Logical
import Manual.BasicTypes.String.Literals
import Manual.BasicTypes.String.FFI
import Manual.BasicTypes.String.Substrings
import Manual.BasicTypes.String.Slice
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option maxHeartbeats 250000
#doc (Manual) "Strings" =>
%%%
tag := "String"
%%%
Strings represent Unicode text.
Strings are specially supported by Lean:
* They have a _logical model_ that specifies their behavior in terms of {name}`ByteArray`s that contain UTF-8 scalar values.
* In compiled code, they have a run-time representation that additionally includes a cached length, measured as the number of scalar values.
The Lean runtime provides optimized implementations of string operations.
* There is {ref "string-syntax"}[string literal syntax] for writing strings.
UTF-8 is a variable-width encoding.
A character may be encoded as a one, two, three, or four byte code unit.
The fact that strings are UTF-8-encoded byte arrays is visible in the API:
* There is no operation to project a particular character out of the string, as this would be a performance trap. {ref "string-iterators"}[Use an iterator] in a loop instead of a {name}`Nat`.
* Strings are indexed by {name}`String.Pos`, which internally records _byte counts_ rather than _character counts_, and thus takes constant time.
{name}`String.Pos` includes a proof that the byte count in fact points at the beginning of a UTF-8 code unit.
Aside from `0`, these should not be constructed directly, but rather updated using {name}`String.next` and {name}`String.prev`.
{include 0 Manual.BasicTypes.String.Logical}
# Run-Time Representation
%%%
tag := "string-runtime"
%%%
:::figure "Memory layout of strings" (tag := "stringffi")

:::
Strings are represented as {tech}[dynamic arrays] of bytes, encoded in UTF-8.
After the object header, a string contains:
: byte count
The number of bytes that currently contain valid string data
: capacity
The number of bytes presently allocated for the string
: length
The length of the encoded string, which may be shorter than the byte count due to UTF-8 multi-byte characters
: data
The actual character data in the string, null-terminated
Many string functions in the Lean runtime check whether they have exclusive access to their argument by consulting the reference count in the object header.
If they do, and the string's capacity is sufficient, then the existing string can be mutated rather than allocating fresh memory.
Otherwise, a new string must be allocated.
## Performance Notes
%%%
tag := "string-performance"
%%%
Despite the fact that they appear to be an ordinary constructor and projection, {name}`String.ofByteArray` and {name}`String.toByteArray` take *time linear in the length of the string*.
This is because byte arrays and strings do not have an identical representation, so the contents of the byte array must be copied to a new object.
{include 0 Manual.BasicTypes.String.Literals}
# API Reference
%%%
tag := "string-api"
%%%
## Constructing
%%%
tag := "string-api-build"
%%%
{docstring String.singleton}
{docstring String.append}
{docstring String.join}
{docstring String.intercalate}
## Conversions
%%%
tag := "string-api-convert"
%%%
{docstring String.toList}
{docstring String.isNat}
{docstring String.toNat?}
{docstring String.toNat!}
{docstring String.isInt}
{docstring String.toInt?}
{docstring String.toInt!}
{docstring String.toFormat}
## Properties
%%%
tag := "string-api-props"
%%%
{docstring String.isEmpty}
{docstring String.length}
## Positions
%%%
tag := "string-api-valid-pos"
%%%
{docstring String.Pos}
### In Strings
{docstring String.startPos}
{docstring String.endPos}
{docstring String.pos}
{docstring String.pos?}
{docstring String.pos!}
{docstring String.extract}
### Lookups
{docstring String.Pos.get}
{docstring String.Pos.get!}
{docstring String.Pos.get?}
{docstring String.Pos.set}
### Modifications
{docstring String.Pos.modify}
{docstring String.Pos.byte}
### Adjustment
{docstring String.Pos.prev}
{docstring String.Pos.prev!}
{docstring String.Pos.prev?}
{docstring String.Pos.next}
{docstring String.Pos.next!}
{docstring String.Pos.next?}
### Other Strings
{docstring String.Pos.cast}
{docstring String.Pos.ofCopy}
{docstring String.Pos.toSetOfLE}
{docstring String.Pos.toModifyOfLE}
{docstring String.Pos.toSlice}
## Raw Positions
%%%
tag := "string-api-pos"
%%%
{docstring String.Pos.Raw}
### Byte Position
{docstring String.Pos.Raw.offsetOfPos}
### Validity
{docstring String.Pos.Raw.isValid}
{docstring String.Pos.Raw.isValidForSlice}
### Boundaries
{docstring String.rawEndPos}
{docstring String.Pos.Raw.atEnd}
### Comparisons
{docstring String.Pos.Raw.min}
{docstring String.Pos.Raw.byteDistance}
{docstring String.Pos.Raw.substrEq}
### Adjustment
{docstring String.Pos.Raw.prev}
{docstring String.Pos.Raw.next}
{docstring String.Pos.Raw.next'}
{docstring String.Pos.Raw.nextUntil}
{docstring String.Pos.Raw.nextWhile}
{docstring String.Pos.Raw.inc}
{docstring String.Pos.Raw.increaseBy}
{docstring String.Pos.Raw.offsetBy}
{docstring String.Pos.Raw.dec}
{docstring String.Pos.Raw.decreaseBy}
{docstring String.Pos.Raw.unoffsetBy}
### String Lookups
{docstring String.Pos.Raw.extract}
{docstring String.Pos.Raw.get}
{docstring String.Pos.Raw.get!}
{docstring String.Pos.Raw.get'}
{docstring String.Pos.Raw.get?}
### String Modifications
{docstring String.Pos.Raw.set}
{docstring String.Pos.Raw.modify}
## Lookups and Modifications
%%%
tag := "string-api-lookup"
%%%
Operations that select a sub-region of a string (for example, a prefix or suffix of it) return a {ref "string-api-slice"}[slice] into the original string rather than allocating a new string.
Use {name}`String.Slice.copy` to convert the slice into a new string.
{docstring String.take}
{docstring String.takeWhile}
{docstring String.takeEnd}
{docstring String.takeEndWhile}
{docstring String.drop}
{docstring String.dropWhile}
{docstring String.dropEnd}
{docstring String.dropEndWhile}
{docstring String.dropPrefix?}
{docstring String.dropPrefix}
{docstring String.dropSuffix?}
{docstring String.dropSuffix}
{docstring String.trimAscii}
{docstring String.trimAsciiStart}
{docstring String.trimAsciiEnd}
{docstring String.removeLeadingSpaces}
{docstring String.front}
{docstring String.back}
{docstring String.find}
{docstring String.revFind?}
{docstring String.contains}
{docstring String.replace}
{docstring String.find}
## Folds and Aggregation
%%%
tag := "string-api-fold"
%%%
{docstring String.map}
{docstring String.foldl}
{docstring String.foldr}
{docstring String.all}
{docstring String.any}
## Comparisons
%%%
tag := "string-api-compare"
%%%
The {inst}`LT String` instance is defined by the lexicographic ordering on strings based on the {inst}`LT Char` instance.
Logically, this is modeled by the lexicographic ordering on the lists that model strings, so `List.Lex` defines the order.
It is decidable, and the decision procedure is overridden at runtime with efficient code that takes advantage of the run-time representation of strings.
{docstring String.le}
{docstring String.firstDiffPos}
{docstring String.isPrefixOf}
{docstring String.startsWith}
{docstring String.endsWith}
{docstring String.decEq}
{docstring String.hash}
## Manipulation
%%%
tag := "string-api-modify"
%%%
{docstring String.splitToList}
{docstring String.splitOn}
{docstring String.push}
{docstring String.pushn}
{docstring String.capitalize}
{docstring String.decapitalize}
{docstring String.toUpper}
{docstring String.toLower}
## Legacy Iterators
%%%
tag := "string-iterators"
%%%
For backwards compatibility, Lean includes legacy string iterators.
Fundamentally, a {name}`String.Legacy.Iterator` is a pair of a string and a valid position in the string.
Iterators provide functions for getting the current character ({name String.Legacy.Iterator.curr}`curr`), replacing the current character ({name String.Legacy.Iterator.setCurr}`setCurr`), checking whether the iterator can move to the left or the right ({name String.Legacy.Iterator.hasPrev}`hasPrev` and {name String.Legacy.Iterator.hasNext}`hasNext`, respectively), and moving the iterator ({name String.Legacy.Iterator.prev}`prev` and {name String.Legacy.Iterator.next}`next`, respectively).
Clients are responsible for checking whether they've reached the beginning or end of the string; otherwise, the iterator ensures that its position always points at a character.
However, {name}`String.Legacy.Iterator` does not include proofs of these well-formedness conditions, which can make it more difficult to use in verified code.
{docstring String.Legacy.Iterator}
{docstring String.Legacy.iter}
{docstring String.Legacy.mkIterator}
{docstring String.Legacy.Iterator.curr}
{docstring String.Legacy.Iterator.curr'}
{docstring String.Legacy.Iterator.hasNext}
{docstring String.Legacy.Iterator.next}
{docstring String.Legacy.Iterator.next'}
{docstring String.Legacy.Iterator.forward}
{docstring String.Legacy.Iterator.nextn}
{docstring String.Legacy.Iterator.hasPrev}
{docstring String.Legacy.Iterator.prev}
{docstring String.Legacy.Iterator.prevn}
{docstring String.Legacy.Iterator.atEnd}
{docstring String.Legacy.Iterator.toEnd}
{docstring String.Legacy.Iterator.setCurr}
{docstring String.Legacy.Iterator.find}
{docstring String.Legacy.Iterator.foldUntil}
{docstring String.Legacy.Iterator.extract}
{docstring String.Legacy.Iterator.remainingToString}
{docstring String.Legacy.Iterator.remainingBytes}
{docstring String.Legacy.Iterator.pos}
{docstring String.Legacy.Iterator.toString}
{include 2 Manual.BasicTypes.String.Slice}
{include 2 Manual.BasicTypes.String.Substrings}
## Metaprogramming
%%%
tag := "string-api-meta"
%%%
{docstring String.toName}
{docstring String.quote}
## Encodings
%%%
tag := "string-api-encoding"
%%%
{docstring String.getUTF8Byte}
{docstring String.utf8ByteSize}
{docstring String.utf8EncodeChar}
{docstring String.fromUTF8}
{docstring String.fromUTF8?}
{docstring String.fromUTF8!}
{docstring String.toUTF8}
{docstring String.crlfToLf}
{include 0 Manual.BasicTypes.String.FFI} |
reference-manual/Manual/BasicTypes/Fin.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
#doc (Manual) "Finite Natural Numbers" =>
%%%
tag := "Fin"
%%%
```lean -show
section
variable (n : Nat)
```
For any {tech}[natural number] {lean}`n`, the {lean}`Fin n` is a type that contains all the natural numbers that are strictly less than {lean}`n`.
In other words, {lean}`Fin n` has exactly {lean}`n` elements.
It can be used to represent the valid indices into a list or array, or it can serve as a canonical {lean}`n`-element type.
{docstring Fin}
{lean}`Fin` is closely related to {name}`UInt8`, {name}`UInt16`, {name}`UInt32`, {name}`UInt64`, and {name}`USize`, which also represent finite non-negative integral types.
However, these types are backed by bitvectors rather than by natural numbers, and they have fixed bounds.
{lean}`Fin` is comparatively more flexible, but also less convenient for low-level reasoning.
In particular, using bitvectors rather than proofs that a number is less than some power of two avoids needing to take care to avoid evaluating the concrete bound.
# Run-Time Characteristics
Because {lean}`Fin n` is a structure in which only a single field is not a proof, it is a {ref "inductive-types-trivial-wrappers"}[trivial wrapper].
This means that it is represented identically to the underlying natural number in compiled code.
# Coercions and Literals
There is a {tech}[coercion] from {lean}`Fin n` to {lean}`Nat` that discards the proof that the number is less than the bound.
In particular, this coercion is precisely the projection {name}`Fin.val`.
One consequence of this is that uses of {name}`Fin.val` are displayed as coercions rather than explicit projections in proof states.
:::example "Coercing from {name}`Fin` to {name}`Nat`"
A {lean}`Fin n` can be used where a {lean}`Nat` is expected:
```lean (name := oneFinCoe)
#eval let one : Fin 3 := ⟨1, by omega⟩; (one : Nat)
```
```leanOutput oneFinCoe
1
```
Uses of {name}`Fin.val` show up as coercions in proof states:
```proofState
∀(n : Nat) (i : Fin n), i < n := by
intro n i
/--
n : Nat
i : Fin n
⊢ ↑i < n
-/
```
:::
Natural number literals may be used for {lean}`Fin` types, implemented as usual via an {name}`OfNat` instance.
The {name}`OfNat` instance for {lean}`Fin n` requires that the upper bound {lean}`n` is not zero, but does not check that the literal is less than {lean}`n`.
If the literal is larger than the type can represent, the remainder when dividing it by {lean}`n` is used.
:::example "Numeric Literals for {name}`Fin`"
If {lean}`n > 0`, then natural number literals can be used for {lean}`Fin n`:
```lean
example : Fin 5 := 3
example : Fin 20 := 19
```
When the literal is greater than or equal to {lean}`n`, the remainder when dividing by {lean}`n` is used:
```lean (name := fivethree)
#eval (5 : Fin 3)
```
```leanOutput fivethree
2
```
```lean (name := fourthree)
#eval ([0, 1, 2, 3, 4, 5, 6] : List (Fin 3))
```
```leanOutput fourthree
[0, 1, 2, 0, 1, 2, 0]
```
If Lean can't synthesize an instance of {lean}`NeZero n`, then there is no {lean}`OfNat (Fin n)` instance:
```lean +error (name := fin0)
example : Fin 0 := 0
```
```leanOutput fin0
failed to synthesize instance of type class
OfNat (Fin 0) 0
numerals are polymorphic in Lean, but the numeral `0` cannot be used in a context where the expected type is
Fin 0
due to the absence of the instance above
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
```lean +error (name := finK)
example (k : Nat) : Fin k := 0
```
```leanOutput finK
failed to synthesize instance of type class
OfNat (Fin k) 0
numerals are polymorphic in Lean, but the numeral `0` cannot be used in a context where the expected type is
Fin k
due to the absence of the instance above
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
:::
# API Reference
## Construction
{docstring Fin.last}
{docstring Fin.succ}
{docstring Fin.pred}
## Arithmetic
Typically, arithmetic operations on {name}`Fin` should be accessed using Lean's overloaded arithmetic notation, particularly via the instances {inst}`Add (Fin n)`, {inst}`Sub (Fin n)`, {inst}`Mul (Fin n)`, {inst}`Div (Fin n)`, and {inst}`Mod (Fin n)`.
Heterogeneous operators such as {lean}`Fin.natAdd` do not have corresponding heterogeneous instances (e.g. {name}`HAdd`) to avoid confusing type inference behavior.
{docstring Fin.add}
{docstring Fin.natAdd}
{docstring Fin.addNat}
{docstring Fin.mul}
{docstring Fin.sub}
{docstring Fin.subNat}
{docstring Fin.div}
{docstring Fin.mod}
{docstring Fin.modn}
{docstring Fin.log2}
## Bitwise Operations
Typically, bitwise operations on {name}`Fin` should be accessed using Lean's overloaded bitwise operators, particularly via the instances {inst}`ShiftLeft (Fin n)`, {inst}`ShiftRight (Fin n)`, {inst}`AndOp (Fin n)`, {inst}`OrOp (Fin n)`, {inst}`Xor (Fin n)`
{docstring Fin.shiftLeft}
{docstring Fin.shiftRight}
{docstring Fin.land}
{docstring Fin.lor}
{docstring Fin.xor}
## Conversions
{docstring Fin.toNat}
{docstring Fin.ofNat}
{docstring Fin.cast}
{docstring Fin.castLT}
{docstring Fin.castLE}
{docstring Fin.castAdd}
{docstring Fin.castSucc}
{docstring Fin.rev}
{docstring Fin.elim0}
## Iteration
{docstring Fin.foldr}
{docstring Fin.foldrM}
{docstring Fin.foldl}
{docstring Fin.foldlM}
{docstring Fin.hIterate}
{docstring Fin.hIterateFrom}
## Reasoning
{docstring Fin.induction}
{docstring Fin.inductionOn}
{docstring Fin.reverseInduction}
{docstring Fin.cases}
{docstring Fin.lastCases}
{docstring Fin.addCases}
{docstring Fin.succRec}
{docstring Fin.succRecOn} |
reference-manual/Manual/BasicTypes/Float.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.Array.Subarray
import Manual.BasicTypes.Array.FFI
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Floating-Point Numbers" =>
%%%
tag := "Float"
%%%
Floating-point numbers are a an approximation of the real numbers that are efficiently implemented in computer hardware.
Computations that use floating-point numbers are very efficient; however, the nature of the way that they approximate the real numbers is complex, with many corner cases.
The IEEE 754 standard, which defines the floating-point format that is used on modern computers, allows hardware designers to make certain choices, and real systems differ in these small details.
For example, there are many distinct bit representations of `NaN`, the indicator that a result is undefined, and some platforms differ with respect to _which_ `NaN` is returned from adding two `NaN`s.
Lean exposes the underlying platform's floating-point values for use in programming, but they are not encoded in Lean's logic.
They are represented by an opaque type.
This means that the {tech}[kernel] is not capable of computing with or reasoning about floating-point values without additional {ref "axioms"}[axioms].
A consequence of this is that equality of floating-point numbers is not decidable.
Furthermore, comparisons between floating-point values are decidable, but the code that does so is opaque; in practice, the decision procedure can only be used in compiled code.
Lean provides two floating-point types: {name}`Float` represents 64-bit floating point values, while {name}`Float32` represents 32-bit floating point values.
The precision of {name}`Float` does not vary based on the platform that Lean is running on.
{docstring Float (label := "type") +hideStructureConstructor +hideFields}
{docstring Float32 (label := "type") +hideStructureConstructor +hideFields}
:::example "No Kernel Reasoning About Floating-Point Numbers"
The Lean kernel can compare expressions of type {lean}`Float` for syntactic equality, so {lean (type := "Float")}`0.0` is definitionally equal to itself.
```lean
example : (0.0 : Float) = (0.0 : Float) := by rfl
```
Terms that require reduction to become syntactically equal cannot be checked by the kernel:
```lean +error (name := zeroPlusZero)
example : (0.0 : Float) = (0.0 + 0.0 : Float) := by rfl
```
```leanOutput zeroPlusZero
Tactic `rfl` failed: The left-hand side
0.0
is not definitionally equal to the right-hand side
0.0 + 0.0
⊢ 0.0 = 0.0 + 0.0
```
Similarly, the kernel cannot evaluate {lean}`Bool`-valued comparisons of floating-point numbers while checking definitional equality:
```lean +error (name := zeroPlusZero') -keep
theorem Float.zero_eq_zero_plus_zero :
((0.0 : Float) == (0.0 + 0.0 : Float)) = true :=
by rfl
```
```leanOutput zeroPlusZero'
Tactic `rfl` failed: The left-hand side
0.0 == 0.0 + 0.0
is not definitionally equal to the right-hand side
true
⊢ (0.0 == 0.0 + 0.0) = true
```
However, the {tactic}`native_decide` tactic can invoke the underlying platform's floating-point primitives that are used by Lean for run-time programs:
```lean
theorem Float.zero_eq_zero_plus_zero :
((0.0 : Float) == (0.0 + 0.0 : Float)) = true := by
native_decide
```
This tactic uses the axiom {name}`Lean.trustCompiler`, which states that the Lean compiler, interpreter and the low-level implementations of built-in operators are trusted in addition to the kernel.
```lean (name := ofRed)
#print axioms Float.zero_eq_zero_plus_zero
```
```leanOutput ofRed
'Float.zero_eq_zero_plus_zero' depends on axioms: [Classical.choice, Lean.ofReduceBool, Lean.trustCompiler]
```
:::
:::example "Floating-Point Equality Is Not Reflexive"
Floating-point operations may produce `NaN` values that indicate an undefined result.
These values are not comparable with each other; in particular, all comparisons involving `NaN` will return `false`, including equality.
```lean
#eval ((0.0 : Float) / 0.0) == ((0.0 : Float) / 0.0)
```
:::
:::example "Floating-Point Equality Is Not a Congruence"
Applying a function to two equal floating-point numbers may not result in equal numbers.
In particular, positive and negative zero are distinct values that are equated by floating-point equality, but division by positive or negative zero yields positive or negative infinite values.
```lean (name := divZeroPosNeg)
def neg0 : Float := -0.0
def pos0 : Float := 0.0
#eval (neg0 == pos0, 1.0 / neg0 == 1.0 / pos0)
```
```leanOutput divZeroPosNeg
(true, false)
```
:::
# Syntax
Lean does not have dedicated floating-point literals.
Instead, floating-point literals are resolved via the appropriate instances of the {name}`OfScientific` and {name}`Neg` type classes.
:::example "Floating-Point Literals"
The term
```leanTerm
(-2.523 : Float)
```
is syntactic sugar for
```leanTerm
(Neg.neg (OfScientific.ofScientific 22523 true 4) : Float)
```
and the term
```leanTerm
(413.52 : Float32)
```
is syntactic sugar for
```leanTerm
(OfScientific.ofScientific 41352 true 2 : Float32)
```
```lean -show
example : (-2.2523 : Float) = (Neg.neg (OfScientific.ofScientific 22523 true 4) : Float) := by simp [OfScientific.ofScientific]
example : (413.52 : Float32) = (OfScientific.ofScientific 41352 true 2 : Float32) := by simp [OfScientific.ofScientific]
```
:::
# API Reference
%%%
tag := "Float-api"
%%%
## Properties
Floating-point numbers fall into one of three categories:
* Finite numbers are ordinary floating-point values.
* Infinities, which may be positive or negative, result from division by zero.
* `NaN`s, which are not numbers, result from other undefined operations, such as the square root of a negative number.
{docstring Float.isInf}
{docstring Float32.isInf}
{docstring Float.isNaN}
{docstring Float32.isNaN}
{docstring Float.isFinite}
{docstring Float32.isFinite}
## Syntax
These operations exist to support the {inst}`OfScientific Float` and {inst}`OfScientific Float32` instances and are normally invoked indirectly as a result of a literal value.
{docstring Float.ofScientific}
{docstring Float32.ofScientific}
## Conversions
{docstring Float.toBits}
{docstring Float32.toBits}
{docstring Float.ofBits}
{docstring Float32.ofBits}
{docstring Float.toFloat32}
{docstring Float32.toFloat}
{docstring Float.toString}
{docstring Float32.toString}
{docstring Float.toUInt8}
{docstring Float.toInt8}
{docstring Float32.toUInt8}
{docstring Float32.toInt8}
{docstring Float.toUInt16}
{docstring Float.toInt16}
{docstring Float32.toUInt16}
{docstring Float32.toInt16}
{docstring Float.toUInt32}
{docstring Float32.toUInt32}
{docstring Float.toInt32}
{docstring Float32.toInt32}
{docstring Float.toUInt64}
{docstring Float.toInt64}
{docstring Float32.toUInt64}
{docstring Float32.toInt64}
{docstring Float.toUSize}
{docstring Float32.toUSize}
{docstring Float.toISize}
{docstring Float32.toISize}
{docstring Float.ofInt}
{docstring Float32.ofInt}
{docstring Float.ofNat}
{docstring Float32.ofNat}
{docstring Float.ofBinaryScientific}
{docstring Float32.ofBinaryScientific}
{docstring Float.frExp}
{docstring Float32.frExp}
## Comparisons
{docstring Float.beq}
{docstring Float32.beq}
### Inequalities
The decision procedures for inequalities are opaque constants in the logic.
They can only be used via the {name}`Lean.ofReduceBool` axiom, e.g. via the {tactic}`native_decide` tactic.
{docstring Float.le}
{docstring Float32.le}
{docstring Float.lt}
{docstring Float32.lt}
{docstring Float.decLe}
{docstring Float32.decLe}
{docstring Float.decLt}
{docstring Float32.decLt}
## Arithmetic
Arithmetic operations on floating-point values are typically invoked via the {inst}`Add Float`, {inst}`Sub Float`, {inst}`Mul Float`, {inst}`Div Float`, and {inst}`HomogeneousPow Float` instances, along with the corresponding {name}`Float32` instances.
{docstring Float.add}
{docstring Float32.add}
{docstring Float.sub}
{docstring Float32.sub}
{docstring Float.mul}
{docstring Float32.mul}
{docstring Float.div}
{docstring Float32.div}
{docstring Float.pow}
{docstring Float32.pow}
{docstring Float.exp}
{docstring Float32.exp}
{docstring Float.exp2}
{docstring Float32.exp2}
### Roots
Computing the square root of a negative number yields `NaN`.
{docstring Float.sqrt}
{docstring Float32.sqrt}
{docstring Float.cbrt}
{docstring Float32.cbrt}
## Logarithms
{docstring Float.log}
{docstring Float32.log}
{docstring Float.log10}
{docstring Float32.log10}
{docstring Float.log2}
{docstring Float32.log2}
## Scaling
{docstring Float.scaleB}
{docstring Float32.scaleB}
## Rounding
{docstring Float.round}
{docstring Float32.round}
{docstring Float.floor}
{docstring Float32.floor}
{docstring Float.ceil}
{docstring Float32.ceil}
## Trigonometry
### Sine
{docstring Float.sin}
{docstring Float32.sin}
{docstring Float.sinh}
{docstring Float32.sinh}
{docstring Float.asin}
{docstring Float32.asin}
{docstring Float.asinh}
{docstring Float32.asinh}
### Cosine
{docstring Float.cos}
{docstring Float32.cos}
{docstring Float.cosh}
{docstring Float32.cosh}
{docstring Float.acos}
{docstring Float32.acos}
{docstring Float.acosh}
{docstring Float32.acosh}
### Tangent
{docstring Float.tan}
{docstring Float32.tan}
{docstring Float.tanh}
{docstring Float32.tanh}
{docstring Float.atan}
{docstring Float32.atan}
{docstring Float.atanh}
{docstring Float32.atanh}
{docstring Float.atan2}
{docstring Float32.atan2}
## Negation and Absolute Value
{docstring Float.abs}
{docstring Float32.abs}
{docstring Float.neg}
{docstring Float32.neg} |
reference-manual/Manual/BasicTypes/Int.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
#doc (Manual) "Integers" =>
%%%
tag := "Int"
%%%
The integers are whole numbers, both positive and negative.
Integers are arbitrary-precision, limited only by the capability of the hardware on which Lean is running; for fixed-width integers that are used in programming and computer science, please see the {ref "fixed-ints"}[section on fixed-precision integers].
Integers are specially supported by Lean's implementation.
The logical model of the integers is based on the natural numbers: each integer is modeled as either a natural number or the negative successor of a natural number.
Operations on the integers are specified using this model, which is used in the kernel and in interpreted code.
In these contexts, integer code inherits the performance benefits of the natural numbers' special support.
In compiled code, integers are represented as efficient arbitrary-precision integers, and sufficiently small numbers are stored as values that don't require indirection through a pointer.
Arithmetic operations are implemented by primitives that take advantage of the efficient representations.
# Logical Model
%%%
tag := "int-model"
%%%
Integers are represented either as a natural number or as the negation of the successor of a natural number.
{docstring Int}
This representation of the integers has a number of useful properties.
It is relatively simple to use and to understand.
Unlike a pair of a sign and a {lean}`Nat`, there is a unique representation for $`0`, which simplifies reasoning about equality.
Integers can also be represented as a pair of natural numbers in which one is subtracted from the other, but this requires a {ref "quotients"}[quotient type] to be well-behaved, and quotient types can be laborious to work with due to the need to prove that functions respect the equivalence relation.
# Run-Time Representation
%%%
tag := "int-runtime"
%%%
Like {ref "nat-runtime"}[natural numbers], sufficiently-small integers are represented without pointers: the lowest-order bit in an object pointer is used to indicate that the value is not, in fact, a pointer.
If an integer is too large to fit in the remaining bits, it is instead allocated as an ordinary Lean object that consists of an object header and an arbitrary-precision integer.
# Syntax
%%%
tag := "int-syntax"
%%%
```lean -show
section
variable (n : Nat)
```
The {lean}`OfNat Int` instance allows numerals to be used as literals, both in expression and in pattern contexts.
{lean}`(OfNat.ofNat n : Int)` reduces to the constructor application {lean}`Int.ofNat n`.
The {inst}`Neg Int` instance allows negation to be used as well.
```lean -show
open Int
```
On top of these instances, there is special syntax for the constructor {lean}`Int.negSucc` that is available when the `Int` namespace is opened.
The notation {lean}`-[ n +1]` is suggestive of $`-(n + 1)`, which is the meaning of {lean}`Int.negSucc n`.
:::syntax term (title := "Negative Successor")
{lean}`-[ n +1]` is notation for {lean}`Int.negSucc n`.
```grammar
-[ $_ +1]
```
:::
```lean -show
end
```
# API Reference
## Properties
{docstring Int.sign}
## Conversions
{docstring Int.natAbs}
{docstring Int.toNat}
{docstring Int.toNat?}
{docstring Int.toISize}
{docstring Int.toInt8}
{docstring Int.toInt16}
{docstring Int.toInt32}
{docstring Int.toInt64}
{docstring Int.repr}
## Arithmetic
Typically, arithmetic operations on integers are accessed using Lean's overloaded arithmetic notation.
In particular, the instances of {inst}`Add Int`, {inst}`Neg Int`, {inst}`Sub Int`, and {inst}`Mul Int` allow ordinary infix operators to be used.
{ref "int-div"}[Division] is somewhat more intricate, because there are multiple sensible notions of division on integers.
{docstring Int.add}
{docstring Int.sub}
{docstring Int.subNatNat}
{docstring Int.neg}
{docstring Int.negOfNat}
{docstring Int.mul}
{docstring Int.pow}
{docstring Int.gcd}
{docstring Int.lcm}
### Division
%%%
tag := "int-div"
%%%
The {inst}`Div Int` and {inst}`Mod Int` instances implement Euclidean division, described in the reference for {name}`Int.ediv`.
This is not, however, the only sensible convention for rounding and remainders in division.
Four pairs of division and modulus functions are available, implementing various conventions.
:::example "Division by 0"
In all integer division conventions, division by {lean (type := "Int")}`0` is defined to be {lean (type := "Int")}`0`:
```lean (name := div0)
#eval Int.ediv 5 0
#eval Int.ediv 0 0
#eval Int.ediv (-5) 0
#eval Int.bdiv 5 0
#eval Int.bdiv 0 0
#eval Int.bdiv (-5) 0
#eval Int.fdiv 5 0
#eval Int.fdiv 0 0
#eval Int.fdiv (-5) 0
#eval Int.tdiv 5 0
#eval Int.tdiv 0 0
#eval Int.tdiv (-5) 0
```
All evaluate to 0.
```leanOutput div0
0
```
:::
{docstring Int.ediv}
{docstring Int.emod}
{docstring Int.tdiv}
{docstring Int.tmod}
{docstring Int.bdiv}
{docstring Int.bmod}
{docstring Int.fdiv}
{docstring Int.fmod}
## Bitwise Operators
Bitwise operators on {name}`Int` can be understood as bitwise operators on an infinite stream of bits that are the twos-complement representation of integers.
{docstring Int.not}
{docstring Int.shiftRight}
## Comparisons
Equality and inequality tests on {lean}`Int` are typically performed using the decidability of its equality and ordering relations or using the {inst}`BEq Int` and {inst}`Ord Int` instances.
```lean -show
example (i j : Int) : Decidable (i ≤ j) := inferInstance
example (i j : Int) : Decidable (i < j) := inferInstance
example (i j : Int) : Decidable (i = j) := inferInstance
```
{docstring Int.le}
{docstring Int.lt}
{docstring Int.decEq} |
reference-manual/Manual/BasicTypes/Option.lean | import VersoManual
import Manual.Meta
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Optional Values" =>
%%%
tag := "option"
%%%
:::::leanSection
```lean -show
variable {α : Type u} (v : α) {β : Type v}
```
{lean}`Option α` is the type of values which are either {lean}`some v` for some {lean}`v`` : `{lean}`α`, or {lean (type := "Option α")}`none`.
In functional programming, this type is used similarly to nullable types: {lean (type := "Option α")}`none` represents the absence of a value.
Additionally, partial functions from {lean}`α` to {lean}`β` can be represented by the type {lean}`α → Option β`, where {lean (type := "Option β")}`none` results when the function is undefined for some input.
Computationally, these partial functions represent the possibility of failure or errors, and they correspond to a program that can terminate early but not throw an informative exception.
{lean}`Option` can also be thought of as being similar to a list that contains at most one element.
From this perspective, iterating over {lean}`Option` consists of carrying out an operation only when a value is present.
The {lean}`Option` API makes frequent use of this perspective.
::::leanSection
:::example "Options as Nullability"
```imports -show
import Std
```
```lean -show
open Std (HashMap)
variable {Coll} [BEq α] [Hashable α] (a : α) (b : β) {xs : Coll} [GetElem Coll α β fun _ _ => True] {i : α} {m : HashMap α β}
```
The function {name}`Std.HashMap.get?` looks up a specified key `a : α` inside a {lean}`HashMap α β`:
```signature
Std.HashMap.get?.{u, v} {α : Type u} {β : Type v}
[BEq α] [Hashable α]
(m : HashMap α β) (a : α) :
Option β
```
Because there is no way to know in advance whether the key is actually in the map, the return type is {lean}`Option β`, where {lean (type := "Option β")}`none` means the key was not in the map, and {lean}`some b` means that the key was found and `b` is the value retrieved.
The {lean}`xs[i]` syntax, which is used to index into collections when there is an available proof that {lean}`i` is a valid index into {lean}`xs`, has a variant {lean}`xs[i]?` that returns an optional value depending on whether the given index is valid.
If {lean}`m`` : `{lean}`HashMap α β` and {lean}`a`` : `{lean}`α`, then {lean}`m[a]?` is equivalent to {lean}`HashMap.get? m a`.
:::
::::
:::example "Options as Safe Nullability"
In many programming languages, it is important to remember to check for the null value.
When using {name}`Option`, the type system requires these checks in the right places: {lean}`Option α` and {lean}`α` are not the same type, and converting from one to the other requires handling the case of {lean (type := "Option α")}`none`.
This can be done via helpers such as {name}`Option.getD`, or with pattern matching.
```imports -show
import Std
```
```lean
def postalCodes : Std.HashMap Nat String :=
Std.HashMap.emptyWithCapacity 1 |>.insert 12345 "Schenectady"
```
```lean (name := getD)
#eval postalCodes[12346]?.getD "not found"
```
```leanOutput getD
"not found"
```
```lean (name := m)
#eval
match postalCodes[12346]? with
| none => "not found"
| some city => city
```
```leanOutput m
"not found"
```
```lean (name := iflet)
#eval
if let some city := postalCodes[12345]? then
city
else
"not found"
```
```leanOutput iflet
"Schenectady"
```
:::
:::::
{docstring Option}
# Coercions
```lean -show
section
variable {α : Type u} (line : String)
```
There is a {tech}[coercion] from {lean}`α` to {lean}`Option α` that wraps a value in {lean}`some`.
This allows {name}`Option` to be used in a style similar to nullable types in other languages, where values that are missing are indicated by {name}`none` and values that are present are not specially marked.
:::example "Coercions and {name}`Option`"
In {lean}`getAlpha`, a line of input is read.
If the line consists only of letters (after removing whitespace from the beginning and end of it), then it is returned; otherwise, the function returns {name}`none`.
```lean
def getAlpha : IO (Option String) := do
let line := (← (← IO.getStdin).getLine).trim
if line.length > 0 && line.all Char.isAlpha then
return line
else
return none
```
In the successful case, there is no explicit {name}`some` wrapped around {lean}`line`.
The {name}`some` is automatically inserted by the coercion.
:::
```lean -show
end
```
# API Reference
## Extracting Values
{docstring Option.get}
{docstring Option.get!}
{docstring Option.getD}
{docstring Option.getDM}
{docstring Option.getM}
{docstring Option.elim}
{docstring Option.elimM}
{docstring Option.merge}
## Properties and Comparisons
{docstring Option.isNone}
{docstring Option.isSome}
{docstring Option.isEqSome}
:::leanSection
```lean -show
variable {α} [DecidableEq α] [LT α] [Min α] [Max α]
```
Ordering of optional values typically uses the {inst}`DecidableEq (Option α)`, {inst}`LT (Option α)`, {inst}`Min (Option α)`, and {inst}`Max (Option α)` instances.
:::
{docstring Option.min}
{docstring Option.max}
{docstring Option.lt}
{docstring Option.decidableEqNone}
## Conversion
{docstring Option.toArray}
{docstring Option.toList}
{docstring Option.repr}
{docstring Option.format}
## Control
{name}`Option` can be thought of as describing a computation that may fail to return a value.
The {inst}`Monad Option` instance, along with {inst}`Alternative Option`, is based on this understanding.
Returning {name}`none` can also be thought of as throwing an exception that contains no interesting information, which is captured in the {inst}`MonadExcept Unit Option` instance.
{docstring Option.guard}
{docstring Option.bind}
{docstring Option.bindM}
{docstring Option.join}
{docstring Option.sequence}
{docstring Option.tryCatch}
{docstring Option.or}
{docstring Option.orElse}
## Iteration
{name}`Option` can be thought of as a collection that contains at most one value.
From this perspective, iteration operators can be understood as performing some operation on the contained value, if present, or doing nothing if not.
{docstring Option.all}
{docstring Option.any}
{docstring Option.filter}
{docstring Option.filterM}
{docstring Option.forM}
{docstring Option.map}
{docstring Option.mapA}
{docstring Option.mapM}
## Recursion Helpers
{docstring Option.attach}
{docstring Option.attachWith}
{docstring Option.unattach}
## Reasoning
{docstring Option.choice}
{docstring Option.pbind}
{docstring Option.pelim}
{docstring Option.pmap} |
reference-manual/Manual/BasicTypes/Products.lean | import VersoManual
import Manual.Meta
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Tuples" =>
%%%
tag := "tuples"
%%%
:::paragraph
The Lean standard library includes a variety of tuple-like types.
In practice, they differ in four ways:
* whether the first projection is a type or a proposition
* whether the second projection is a type or a proposition
* whether the second projection's type depends on the first projection's value
* whether the type as a whole is a proposition or type
:::
:::table +header
* + Type
+ First Projection
+ Second Projection
+ Dependent?
+ Universe
* + {name}`Prod`
+ {lean (universes := "u")}`Type u`
+ {lean (universes := "v")}`Type v`
+ ❌️
+ {lean (universes := "u v")}`Type (max u v)`
* + {name}`And`
+ {lean (universes := "u v")}`Prop`
+ {lean (universes := "u v")}`Prop`
+ ❌️
+ {lean (universes := "u v")}`Prop`
* + {name}`Sigma`
+ {lean (universes := "u")}`Type u`
+ {lean (universes := "v")}`Type v`
+ ✔
+ {lean (universes := "u v")}`Type (max u v)`
* + {name}`Subtype`
+ {lean (universes := "u")}`Type u`
+ {lean (universes := "v")}`Prop`
+ ✔
+ {lean (universes := "u v")}`Type u`
* + {name}`Exists`
+ {lean (universes := "u")}`Type u`
+ {lean (universes := "v")}`Prop`
+ ✔
+ {lean (universes := "u v")}`Prop`
:::
:::paragraph
Some potential rows in this table do not exist in the library:
* There is no dependent pair where the first projection is a proposition, because {tech}[proof irrelevance] renders this meaningless.
* There is no non-dependent pair that combines a type with a proposition because the situation is rare in practice: grouping data with _unrelated_ proofs is uncommon.
:::
These differences lead to very different use cases.
{name}`Prod` and its variants {name}`PProd` and {name}`MProd` simply group data together—they are products.
Because its second projection is dependent, {name}`Sigma` has the character of a sum: for each element of the first projection's type, there may be a different type in the second projection.
{name}`Subtype` selects the values of a type that satisfy a predicate.
Even though it syntactically resembles a pair, in practice it is treated as an actual subset.
{name}`And` is a logical connective, and {name}`Exists` is a quantifier.
This chapter documents the tuple-like pairs, namely {name}`Prod` and {name}`Sigma`.
# Ordered Pairs
%%%
tag := "pairs"
%%%
```lean -show
section
variable {α : Type u} {β : Type v} {γ : Type w} {x : α} {y : β} {z : γ}
```
The type {lean}`α × β`, which is a {tech}[notation] for {lean}`Prod α β`, contains ordered pairs in which the first item is an {lean}`α` and the second is a {lean}`β`.
These pairs are written in parentheses, separated by commas.
Larger tuples are represented as nested tuples, so {lean}`α × β × γ` is equivalent to {lean}`α × (β × γ)` and {lean}`(x, y, z)` is equivalent to {lean}`(x, (y, z))`.
:::syntax term (title := "Product Types")
```grammar
$_ × $_
```
The product {lean}`Prod α β` is written {lean}`α × β`.
:::
:::syntax term (title := "Pairs")
```grammar
($_, $_)
```
:::
{docstring Prod}
```lean -show
section
variable {α : Sort u} {β : Sort v} {γ : Type w}
```
There are also the variants {lean}`α ×' β` (which is notation for {lean}`PProd α β`) and {lean}`MProd`, which differ with respect to {tech}[universe] levels: like {name}`PSum`, {name}`PProd` allows either {lean}`α` or {lean}`β` to be a proposition, while {lean}`MProd` requires that both be types at the _same_ universe level.
Generally speaking, {name}`PProd` is primarily used in the implementation of proof automation and the elaborator, as it tends to give rise to universe level unification problems that can't be solved.
{lean}`MProd`, on the other hand, can simplify universe level issues in certain advanced use cases.
```lean -show
end
```
:::syntax term (title := "Products of Arbitrary Sorts")
```grammar
$_ ×' $_
```
The product {lean}`PProd α β`, in which both types could be propositions, is written {lean}`α × β`.
:::
{docstring PProd}
{docstring MProd}
## API Reference
%%%
tag := "prod-api"
%%%
As a mere pair, the primary API for {lean}`Prod` is provided by pattern matching and by the first and second projections {name}`Prod.fst` and {name}`Prod.snd`.
### Transformation
{docstring Prod.map}
{docstring Prod.swap}
### Natural Number Ranges
{docstring Prod.allI}
{docstring Prod.anyI}
{docstring Prod.foldI}
### Ordering
{docstring Prod.lexLt}
# Dependent Pairs
%%%
tag := "sigma-types"
%%%
{deftech}_Dependent pairs_, also known as {deftech}_dependent sums_ or {deftech}_Σ-types_,{see "Σ-types"}[Sigma types]{index}[Σ-types] are pairs in which the second term's type may depend on the _value_ of the first term.
They are closely related to the existential quantifier{TODO}[xref] and {name}`Subtype`.
Unlike existentially quantified statements, dependent pairs are in the {lean}`Type` universe and are computationally relevant data.
Unlike subtypes, the second term is also computationally relevant data.
Like ordinary pairs, dependent pairs may be nested; this nesting is right-associative.
:::syntax term (title := "Dependent Pair Types")
```grammar
($x:ident : $t) × $t
```
```grammar
Σ $x:ident $[$_:ident]* $[: $t]?, $_
```
```grammar
Σ ($x:ident $[$x:ident]* : $t), $_
```
Dependent pair types bind one or more variables, which are then in scope in the final term.
If there is one variable, then its type is a that of the first element in the pair and the final term is the type of the second element in the pair.
If there is more than one variable, the types are nested right-associatively.
The identifiers may also be `_`.
With parentheses, multiple bound variables may have different types, while the unparenthesized variant requires that all have the same type.
:::
::::example "Nested Dependent Pair Types"
:::paragraph
The type
```leanTerm
Σ n k : Nat, Fin (n * k)
```
is equivalent to
```leanTerm
Σ n : Nat, Σ k : Nat, Fin (n * k)
```
and
```leanTerm
(n : Nat) × (k : Nat) × Fin (n * k)
```
:::
:::paragraph
The type
```leanTerm
Σ (n k : Nat) (i : Fin (n * k)) , Fin i.val
```
is equivalent to
```leanTerm
Σ (n : Nat), Σ (k : Nat), Σ (i : Fin (n * k)) , Fin i.val
```
and
```leanTerm
(n : Nat) × (k : Nat) × (i : Fin (n * k)) × Fin i.val
```
:::
The two styles of annotation cannot be mixed in a single {keywordOf «termΣ_,_»}`Σ`-type:
```syntaxError mixedNesting (category := term)
Σ n k (i : Fin (n * k)) , Fin i.val
```
```leanOutput mixedNesting
<example>:1:5-1:7: unexpected token '('; expected ','
```
::::
```lean -show
section
variable {α : Type} (x : α)
```
::::paragraph
Dependent pairs are typically used in one of two ways:
1. They can be used to “package” a concrete type index together with a value of the indexed family, used when the index value is not known ahead of time.
The type {lean}`Σ n, Fin n` is a pair of a natural number and some other number that's strictly smaller.
This is the most common way to use dependent pairs.
2. :::paragraph
The first element can be thought of as a “tag” that's used to select from among different types for the second term.
This is similar to the way that selecting a constructor of a sum type determines the types of the constructor's arguments.
For example, the type
```leanTerm
Σ (b : Bool), if b then Unit else α
```
is equivalent to {lean}`Option α`, where {lean (type := "Option α")}`none` is {lean (type := "Σ (b : Bool), if b then Unit else α")}`⟨true, ()⟩` and {lean (type := "Option α")}`some x` is {lean (type := "Σ (b : Bool), if b then Unit else α")}`⟨false, x⟩`.
Using dependent pairs this way is uncommon, because it's typically much easier to define a special-purpose {tech}[inductive type] directly.
:::
::::
```lean -show
end
```
{docstring Sigma}
:::::example "Dependent Pairs with Data"
::::ioExample
The type {name}`Vector`, which associates a known length with an array, can be placed in a dependent pair with the length itself.
While this is logically equivalent to just using {name}`Array`, this construction is sometimes necessary to bridge gaps in an API.
```ioLean
def getNLinesRev : (n : Nat) → IO (Vector String n)
| 0 => pure #v[]
| n + 1 => do
let xs ← getNLinesRev n
return xs.push (← (← IO.getStdin).getLine)
def getNLines (n : Nat) : IO (Vector String n) := do
return (← getNLinesRev n).reverse
partial def getValues : IO (Σ n, Vector String n) := do
let stdin ← IO.getStdin
IO.println "How many lines to read?"
let howMany ← stdin.getLine
if let some howMany := howMany.trimAscii.copy.toNat? then
return ⟨howMany, (← getNLines howMany)⟩
else
IO.eprintln "Please enter a number."
getValues
def main : IO Unit := do
let values ← getValues
IO.println s!"Got {values.fst} values. They are:"
for x in values.snd do
IO.println x.trimAscii
```
:::paragraph
When calling the program with this standard input:
```stdin
4
Apples
Quince
Plums
Raspberries
```
the output is:
```stdout
How many lines to read?
Got 4 values. They are:
Raspberries
Plums
Quince
Apples
```
:::
::::
:::::
:::example "Dependent Pairs as Sums"
{name}`Sigma` can be used to implement sum types.
The {name}`Bool` in the first projection of {name}`Sum'` indicates which type the second projection is drawn from.
```lean
def Sum' (α : Type) (β : Type) : Type :=
Σ (b : Bool),
match b with
| true => α
| false => β
```
The injections pair a tag (a {name}`Bool`) with a value of the indicated type.
Annotating them with {attr}`match_pattern` allows them to be used in patterns as well as in ordinary terms.
```lean
variable {α β : Type}
@[match_pattern]
def Sum'.inl (x : α) : Sum' α β := ⟨true, x⟩
@[match_pattern]
def Sum'.inr (x : β) : Sum' α β := ⟨false, x⟩
def Sum'.swap : Sum' α β → Sum' β α
| .inl x => .inr x
| .inr y => .inl y
```
:::
Just as {name}`Prod` has a variant {name}`PProd` that accepts propositions as well as types, {name}`PSigma` allows its projections to be propositions.
This has the same drawbacks as {name}`PProd`: it is much more likely to lead to failures of universe level unification.
However, {name}`PSigma` can be necessary when implementing custom proof automation or in some rare, advanced use cases.
:::syntax term (title := "Fully-Polymorphic Dependent Pair Types")
```grammar
Σ' $x:ident $[$_:ident]* $[: $t]? , $_
```
```grammar
Σ' ($x:ident $[$x:ident]* : $t), $_
```
The rules for nesting {keyword}`Σ'`, as well as those that govern its binding structure, are the same as those for {keywordOf «termΣ_,_»}`Σ`.
:::
{docstring PSigma} |
reference-manual/Manual/BasicTypes/List.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.List.Predicates
import Manual.BasicTypes.List.Comparisons
import Manual.BasicTypes.List.Partitioning
import Manual.BasicTypes.List.Modification
import Manual.BasicTypes.List.Transformation
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option maxHeartbeats 250000
#doc (Manual) "Linked Lists" =>
%%%
tag := "List"
%%%
Linked lists, implemented as the {tech}[inductive type] {name}`List`, contain an ordered sequence of elements.
Unlike {ref "Array"}[arrays], Lean compiles lists according to the ordinary rules for inductive types; however, some operations on lists are replaced by tail-recursive equivalents in compiled code using the {attr}`csimp` mechanism.{TODO}[Write and xref from here]
Lean provides syntax for both literal lists and the constructor {name}`List.cons`.
{docstring List}
# Syntax
%%%
tag := "list-syntax"
%%%
List literals are written in square brackets, with the elements of the list separated by commas.
The constructor {name}`List.cons` that adds an element to the front of a list is represented by the infix operator {keywordOf «term_::_»}`::`.
The syntax for lists can be used both in ordinary terms and in patterns.
:::syntax term (title := "List Literals")
```grammar
[$_,*]
```
{includeDocstring «term[_]»}
:::
:::syntax term (title := "List Construction")
```grammar
$_ :: $_
```
{includeDocstring «term_::_»}
:::
:::example "Constructing Lists"
All of these examples are equivalent:
```lean
example : List Nat := [1, 2, 3]
example : List Nat := 1 :: [2, 3]
example : List Nat := 1 :: 2 :: [3]
example : List Nat := 1 :: 2 :: 3 :: []
example : List Nat := 1 :: 2 :: 3 :: .nil
example : List Nat := 1 :: 2 :: .cons 3 .nil
example : List Nat := .cons 1 (.cons 2 (.cons 3 .nil))
```
:::
:::example "Pattern Matching and Lists"
All of these functions are equivalent:
```lean
def split : List α → List α × List α
| [] => ([], [])
| [x] => ([x], [])
| x :: x' :: xs =>
let (ys, zs) := split xs
(x :: ys, x' :: zs)
```
```lean
def split' : List α → List α × List α
| .nil => (.nil, .nil)
| x :: [] => (.singleton x, .nil)
| x :: x' :: xs =>
let (ys, zs) := split xs
(x :: ys, x' :: zs)
```
```lean
def split'' : List α → List α × List α
| .nil => (.nil, .nil)
| .cons x .nil => (.singleton x, .nil)
| .cons x (.cons x' xs) =>
let (ys, zs) := split xs
(.cons x ys, .cons x' zs)
```
```lean -show
-- Test claim
example : @split = @split' := by
funext α xs
induction xs using split.induct <;> simp [split, split', List.singleton]
example : @split = @split'' := by
funext α xs
induction xs using split.induct <;> simp [split, split'', List.singleton]
```
:::
# Performance Notes
%%%
tag := "list-performance"
%%%
The representation of lists is not overridden or modified by the compiler: they are linked lists, with a pointer indirection for each element.
Calculating the length of a list requires a full traversal, and modifying an element in a list requires a traversal and reallocation of the prefix of the list that is prior to the element being modified.
Due to Lean's reference-counting-based memory management, operations such as {name}`List.map` that traverse a list, allocating a new {name}`List.cons` constructor for each in the prior list, can reuse the original list's memory when there are no other references to it.
Because of the important role played by lists in specifications, most list functions are written as straightforwardly as possible using structural recursion.
This makes it easier to write proofs by induction, but it also means that these operations consume stack space proportional to the length of the list.
There are tail-recursive versions of many list functions that are equivalent to the non-tail-recursive versions, but are more difficult to use when reasoning.
In compiled code, the tail-recursive versions are automatically used instead of the non-tail-recursive versions.
# API Reference
%%%
tag := "list-api-reference"
%%%
{include 2 Manual.BasicTypes.List.Predicates}
## Constructing Lists
{docstring List.singleton}
{docstring List.concat}
{docstring List.replicate}
{docstring List.replicateTR}
{docstring List.ofFn}
{docstring List.append}
{docstring List.appendTR}
{docstring List.range}
{docstring List.range'}
{docstring List.range'TR}
{docstring List.finRange}
## Length
{docstring List.length}
{docstring List.lengthTR}
{docstring List.isEmpty}
## Head and Tail
{docstring List.head}
{docstring List.head?}
{docstring List.headD}
{docstring List.head!}
{docstring List.tail}
{docstring List.tail!}
{docstring List.tail?}
{docstring List.tailD}
## Lookups
{docstring List.get}
{docstring List.getD}
{docstring List.getLast}
{docstring List.getLast?}
{docstring List.getLastD}
{docstring List.getLast!}
{docstring List.lookup}
{docstring List.max?}
{docstring List.min?}
## Queries
{docstring List.count}
{docstring List.countP}
{docstring List.idxOf}
{docstring List.idxOf?}
{docstring List.finIdxOf?}
{docstring List.find?}
{docstring List.findFinIdx?}
{docstring List.findIdx}
{docstring List.findIdx?}
{docstring List.findM?}
{docstring List.findSome?}
{docstring List.findSomeM?}
## Conversions
{docstring List.toArray}
{docstring List.toArrayImpl}
{docstring List.toByteArray}
{docstring List.toFloatArray}
{docstring List.toString}
{include 2 Manual.BasicTypes.List.Modification}
## Sorting
{docstring List.mergeSort}
{docstring List.merge}
## Iteration
{docstring List.iter}
{docstring List.iterM}
{docstring List.forA}
{docstring List.forM}
{docstring List.firstM}
{docstring List.sum}
### Folds
:::paragraph
Folds are operators that combine the elements of a list using a function.
They come in two varieties, named after the nesting of the function calls:
: {deftech}[Left folds]
Left folds combine the elements from the head of the list towards the end.
The head of the list is combined with the initial value, and the result of this operation is then combined with the next value, and so forth.
: {deftech}[Right folds]
Right folds combine the elements from the end of the list towards the start, as if each {name List.cons}`cons` constructor were replaced by a call to the combining function and {name List.nil}`nil` were replaced by the initial value.
Monadic folds, indicated with an `-M` suffix, allow the combining function to use effects in a {tech}[monad], which may include stopping the fold early.
:::
{docstring List.foldl}
{docstring List.foldlM}
{docstring List.foldlRecOn}
{docstring List.foldr}
{docstring List.foldrM}
{docstring List.foldrRecOn}
{docstring List.foldrTR}
{include 2 Manual.BasicTypes.List.Transformation}
## Filtering
{docstring List.filter}
{docstring List.filterTR}
{docstring List.filterM}
{docstring List.filterRevM}
{docstring List.filterMap}
{docstring List.filterMapTR}
{docstring List.filterMapM}
{include Manual.BasicTypes.List.Partitioning}
## Element Predicates
{docstring List.contains}
{docstring List.elem}
{docstring List.all}
{docstring List.allM}
{docstring List.any}
{docstring List.anyM}
{docstring List.and}
{docstring List.or}
{include 2 Manual.BasicTypes.List.Comparisons}
## Termination Helpers
{docstring List.attach}
{docstring List.attachWith}
{docstring List.unattach}
{docstring List.pmap} |
reference-manual/Manual/BasicTypes/Maps.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.Maps.TreeSet
import Manual.BasicTypes.Maps.TreeMap
import Std.Data.HashMap
import Std.Data.HashMap.Raw
import Std.Data.HashMap.RawLemmas
import Std.Data.DHashMap
import Std.Data.DHashMap.Raw
import Std.Data.DHashMap.RawLemmas
import Std.Data.ExtHashMap
import Std.Data.TreeMap
import Std.Data.DTreeMap
import Std.Data.DTreeMap.Raw
import Std.Data.ExtHashSet
import Std.Data.TreeSet
import Std.Data.HashSet
import Std.Data.HashSet.Raw
import Std.Data.HashSet.RawLemmas
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option maxHeartbeats 1000000
#doc (Manual) "Maps and Sets" =>
%%%
tag := "maps"
%%%
A {deftech}_map_ is a data structure that associates keys with values.
They are also referred to as {deftech}_dictionaries_, {deftech}_associative arrays_, or simply as hash tables.
::::paragraph
In Lean, maps may have the following properties:
: Representation
The in-memory representation of a map may be either a tree or a hash table.
Tree-based representations are better when the {ref "reference-counting"}[reference] to the data structure is shared, because hash tables are based on {ref "Array"}[arrays].
Arrays are copied in full on modification when the reference is not unique, while only the path from the root of the tree to the modified nodes must be copied on modification of a tree.
Hash tables, on the other hand, can be more efficient when references are not shared, because non-shared arrays can be modified in constant time.
Furthermore, tree-based maps store data in order and thus support ordered traversals of the data.
: Extensionality
Maps can be viewed as partial functions from keys to values.
{deftech}_Extensional maps_{index (subterm := "extensional")}[map] are maps for which propositional equality matches this interpretation.
This can be convenient for reasoning, but it also rules out some useful operations that would be able to distinguish between them.
In general, extensional maps should be used only when needed for verification.
: Dependent or Not
A {deftech}_dependent map_{index (subterm := "dependent")}[map] is one in which the type of each value is determined by its corresponding key, rather than being constant.
Dependent maps have more expressive power, but are also more difficult to use.
They impose more requirements on their users.
For example, many operations on {name Std.DHashMap}`DHashMap` require {name}`LawfulBEq` instances rather than {name}`BEq`.
::::
::::: leanSection
```lean -show
open Std
```
:::table +header
*
- Map
- Representation
- Extensional?
- Dependent?
*
- {name}`TreeMap`
- Tree
- No
- No
*
- {name}`DTreeMap`
- Tree
- No
- Yes
*
- {name}`HashMap`
- Hash Table
- No
- No
*
- {name}`DHashMap`
- Hash Table
- No
- Yes
*
- {name}`ExtHashMap`
- Hash Table
- Yes
- No
*
- {name}`ExtDHashMap`
- Hash Table
- Yes
- Yes
:::
:::::
A map can always be used as a set by setting its type of values to {name}`Unit`.
The following set types are provided:
* {name}`Std.HashSet` is a set based on hash tables. Its performance characteristics are like those of {name}`Std.HashMap`: it is based on arrays and can be efficiently updated, but only when not shared.
* {name}`Std.TreeSet` is a set based on balanced trees. Its performance characteristics are like those of {name}`Std.TreeMap`.
* {name}`Std.ExtHashSet` is an extensional hash set type that matches the mathematical notion of finite sets: two sets are equal if they contain the same elements.
# Library Design
All the basic operations on maps and sets are fully verified.
They are proven correct with respect to simpler models implemented with lists.
At the same time, maps and sets have predictable performance.
Some types include additional operations that are not yet fully verified.
These operations are useful, and not all programs need full verification.
Examples include {name Std.HashMap.partition}`HashMap.partition` and {name Std.TreeMap.filterMap}`TreeMap.filterMap`.
## Fused Operations
It is common to modify a table based on its pre-existing contents.
To avoid having to traverse a data structure twice, many query/modification pairs are provided in “fused” variants that perform a query while modifying a map or set.
In some cases, the result of the query affects the modification.
For example, {name}`Std.HashMap` provides {name Std.HashMap.containsThenInsert}`containsThenInsert`, which inserts a key-value pair into a map while signalling whether it was previously found, and {name Std.HashMap.containsThenInsertIfNew}`containsThenInsertIfNew`, which inserts the new mapping only if it was not previously present.
The {name Std.HashMap.alter}`alter` function modifies the value for a given key without having to search for the key multiple times; the alternation is performed by a function in which missing values are represented by {name}`none`.
## Raw Data and Invariants
%%%
tag := "raw-data"
%%%
Both hash-based and tree-based maps rely on certain internal well-formedness invariants, such as that trees are balanced and ordered.
In Lean's standard library, these data structures are represented as a pair of the underlying data with a proof that it is well formed.
This fact is mostly an internal implementation detail; however, it is relevant to users in one situation: this representation prevents them from being used in {tech}[nested inductive types].
To enable their use in nested inductive types, the standard library provides “{deftech}[raw]” variants of each container along with separate “unbundled” versions of their invariants.
These use the following naming convention:
* `T.Raw` is the version of type `T` without its invariants. For example, {name}`Std.HashMap.Raw` is a version of {name}`Std.HashMap` without the embedded proofs.
* `T.Raw.WF` is the corresponding well-formedness predicate. For example, {name}`Std.HashMap.Raw.WF` asserts that a {name}`Std.HashMap.Raw` is well-formed.
* Each operation on `T`, called `T.f`, has a corresponding operation on `T.Raw` called `T.Raw.f`. For example, {name}`Std.HashMap.Raw.insert` is the version of {name}`Std.HashMap.insert` to be used with raw hash maps.
* Each operation `T.Raw.f` has an associated well-formedness lemma `T.Raw.WF.f`. For example, {name}`Std.HashMap.Raw.WF.insert` asserts that inserting a new key-value pair into a well-formed raw hash map results in a well-formed raw hash map.
Because the vast majority of use cases do not require them, not all lemmas about raw types are imported by default with the data structures.
It is usually necessary to import `Std.Data.T.RawLemmas` (where `T` is the data structure in question).
A nested inductive type that occurs inside a map or set should be defined in three stages:
1. First, define a raw version of the nested inductive type that uses the raw version of the map or set type. Define any necessary operations.
2. Next, define an inductive predicate that asserts that all maps or sets in the raw nested type are well formed. Show that the operations on the raw type preserve well-formedness.
3. Construct an appropriate interface to the nested inductive type by defining an API that proves well-formedness properties as needed, hiding them from users.
:::example "Nested Inductive Types with `Std.HashMap`"
```imports -show
import Std
```
This example requires that `Std.Data.HashMap.RawLemmas` is imported.
To keep the code shorter, the `Std` namespace is opened:
```lean
open Std
```
The map of an adventure game may consist of a series of rooms, connected by passages.
Each room has a description, and each passage faces in a particular direction.
This can be represented as a recursive structure.
```lean +error (name:=badNesting) -keep
structure Maze where
description : String
passages : HashMap String Maze
```
This definition is rejected:
```leanOutput badNesting
(kernel) application type mismatch
DHashMap.Raw.WF inner
argument has type
_nested.Std.DHashMap.Raw_3
but function has type
(DHashMap.Raw String fun x => Maze) → Prop
```
Making this work requires separating the well-formedness predicates from the structure.
The first step is to redefine the type without embedded hash map invariants:
```lean
structure RawMaze where
description : String
passages : Std.HashMap.Raw String RawMaze
```
The most basic raw maze has no passages:
```lean
def RawMaze.base (description : String) : RawMaze where
description := description
passages := ∅
```
A passage to a further maze can be added to a raw maze using {name}`RawMaze.insert`:
```lean
def RawMaze.insert (maze : RawMaze)
(direction : String) (next : RawMaze) : RawMaze :=
{ maze with
passages := maze.passages.insert direction next
}
```
The second step is to define a well-formedness predicate for {name}`RawMaze` that ensures that each included hash map is well-formed.
If the {name RawMaze.passages}`passages` field itself is well-formed, and all raw mazes included in it are well-formed, then a raw maze is well-formed.
```lean
inductive RawMaze.WF : RawMaze → Prop
| mk {description passages} :
(∀ (dir : String) v, passages[dir]? = some v → WF v) →
passages.WF →
WF { description, passages := passages }
```
Base mazes are well-formed, and inserting a passage to a well-formed maze into some other well-formed maze produces a well-formed maze:
```lean
theorem RawMaze.base_wf (description : String) :
RawMaze.WF (.base description) := by
constructor
. intro v h h'
simp [Std.HashMap.Raw.getElem?_empty] at *
. exact HashMap.Raw.WF.empty
def RawMaze.insert_wf (maze : RawMaze) :
WF maze → WF next → WF (maze.insert dir next) := by
let ⟨desc, passages⟩ := maze
intro ⟨wfMore, wfPassages⟩ wfNext
constructor
. intro dir' v
rw [HashMap.Raw.getElem?_insert wfPassages]
split <;> intros <;> simp_all [wfMore dir']
. simp_all [HashMap.Raw.WF.insert]
```
Finally, a more friendly interface can be defined that frees users from worrying about well-formedness.
A {name}`Maze` bundles up a {name}`RawMaze` with a proof that it is well-formed:
```lean
structure Maze where
raw : RawMaze
wf : raw.WF
```
The {name Maze.base}`base` and {name Maze.insert}`insert` operators take care of the well-formedness proof obligations:
```lean
def Maze.base (description : String) : Maze where
raw := .base description
wf := by apply RawMaze.base_wf
def Maze.insert (maze : Maze)
(dir : String) (next : Maze) : Maze where
raw := maze.raw.insert dir next.raw
wf := RawMaze.insert_wf maze.raw maze.wf next.wf
```
Users of the {name}`Maze` API may either check the description of the current maze or attempt to go in a direction to a new maze:
```lean
def Maze.description (maze : Maze) : String :=
maze.raw.description
def Maze.go? (maze : Maze) (dir : String) : Option Maze :=
match h : maze.raw.passages[dir]? with
| none => none
| some m' =>
Maze.mk m' <| by
let ⟨r, wf⟩ := maze
let ⟨wfAll, _⟩ := wf
apply wfAll dir
apply h
```
:::
## Suitable Operators for Uniqueness
Care should be taken when working with data structures to ensure that as many references are unique as possible, which enables Lean to use destructive mutation behind the scenes while maintaining a pure functional interface.
The map and set library provides operators that can be used to maintain uniqueness of references.
In particular, when possible, operations such as {name Std.HashMap.alter}`alter` or {name Std.HashMap.modify}`modify` should be preferred over explicitly retrieving a value, modifying it, and reinserting it.
These operations avoid creating a second reference to the value during modification.
:::example "Modifying Values in Maps"
```imports -show
import Std
```
```lean
open Std
```
The function {name}`addAlias` is used to track aliases of a string in some data set.
One way to add an alias is to first look up the existing aliases, defaulting to the empty array, then insert the new alias, and finally save the resulting array in the map:
```lean
def addAlias (aliases : HashMap String (Array String))
(key value : String) :
HashMap String (Array String) :=
let prior := aliases.getD key #[]
aliases.insert key (prior.push value)
```
This implementation has poor performance characteristics.
Because the map retains a reference to the prior values, the array must be copied rather than mutated.
A better implementation explicitly erases the prior value from the map before modifying it:
```lean
def addAlias' (aliases : HashMap String (Array String))
(key value : String) :
HashMap String (Array String) :=
let prior := aliases.getD key #[]
let aliases := aliases.erase key
aliases.insert key (prior.push value)
```
Using {name}`HashMap.alter` is even better.
It removes the need to explicitly delete and re-insert the value:
```lean
def addAlias'' (aliases : HashMap String (Array String))
(key value : String) :
HashMap String (Array String) :=
aliases.alter key fun prior? =>
some ((prior?.getD #[]).push value)
```
:::
# Hash Maps
%%%
tag := "HashMap"
%%%
The declarations in this section should be imported using `import Std.HashMap`.
{docstring Std.HashMap +hideFields +hideStructureConstructor}
## Creation
{docstring Std.HashMap.emptyWithCapacity}
## Properties
{docstring Std.HashMap.size}
{docstring Std.HashMap.isEmpty}
{docstring Std.HashMap.Equiv}
:::syntax term (title := "Equivalence") (namespace := Std.HashMap)
The relation {name Std.HashMap.Equiv}`HashMap.Equiv` can also be written with an infix operator, which is scoped to its namespace:
```grammar
$_ ~m $_
```
:::
## Queries
{docstring Std.HashMap.contains}
{docstring Std.HashMap.get}
{docstring Std.HashMap.get!}
{docstring Std.HashMap.get?}
{docstring Std.HashMap.getD}
{docstring Std.HashMap.getKey}
{docstring Std.HashMap.getKey!}
{docstring Std.HashMap.getKey?}
{docstring Std.HashMap.getKeyD}
{docstring Std.HashMap.keys}
{docstring Std.HashMap.keysArray}
{docstring Std.HashMap.values}
{docstring Std.HashMap.valuesArray}
## Modification
{docstring Std.HashMap.alter}
{docstring Std.HashMap.modify}
{docstring Std.HashMap.containsThenInsert}
{docstring Std.HashMap.containsThenInsertIfNew}
{docstring Std.HashMap.erase}
{docstring Std.HashMap.filter}
{docstring Std.HashMap.filterMap}
{docstring Std.HashMap.insert}
{docstring Std.HashMap.insertIfNew}
{docstring Std.HashMap.getThenInsertIfNew?}
{docstring Std.HashMap.insertMany}
{docstring Std.HashMap.insertManyIfNewUnit}
{docstring Std.HashMap.partition}
{docstring Std.HashMap.union}
## Iteration
{docstring Std.HashMap.iter}
{docstring Std.HashMap.keysIter}
{docstring Std.HashMap.valuesIter}
{docstring Std.HashMap.map}
{docstring Std.HashMap.fold}
{docstring Std.HashMap.foldM}
{docstring Std.HashMap.forIn}
{docstring Std.HashMap.forM}
## Conversion
{docstring Std.HashMap.ofList}
{docstring Std.HashMap.toArray}
{docstring Std.HashMap.toList}
{docstring Std.HashMap.unitOfArray}
{docstring Std.HashMap.unitOfList}
## Unbundled Variants
Unbundled maps separate well-formedness proofs from data.
This is primarily useful when defining {ref "raw-data"}[nested inductive types].
To use these variants, import the modules `Std.HashMap.Raw` and `Std.HashMap.RawLemmas`.
{docstring Std.HashMap.Raw}
{docstring Std.HashMap.Raw.WF}
# Dependent Hash Maps
%%%
tag := "DHashMap"
%%%
The declarations in this section should be imported using `import Std.DHashMap`.
{docstring Std.DHashMap +hideFields +hideStructureConstructor}
## Creation
{docstring Std.DHashMap.emptyWithCapacity}
## Properties
{docstring Std.DHashMap.size}
{docstring Std.DHashMap.isEmpty}
{docstring Std.DHashMap.Equiv}
:::syntax term (title := "Equivalence") (namespace := Std.DHashMap)
The relation {name Std.DHashMap.Equiv}`DHashMap.Equiv` can also be written with an infix operator, which is scoped to its namespace:
```grammar
$_ ~m $_
```
:::
## Queries
{docstring Std.DHashMap.contains}
{docstring Std.DHashMap.get}
{docstring Std.DHashMap.get!}
{docstring Std.DHashMap.get?}
{docstring Std.DHashMap.getD}
{docstring Std.DHashMap.getKey}
{docstring Std.DHashMap.getKey!}
{docstring Std.DHashMap.getKey?}
{docstring Std.DHashMap.getKeyD}
{docstring Std.DHashMap.keys}
{docstring Std.DHashMap.keysArray}
{docstring Std.DHashMap.values}
{docstring Std.DHashMap.valuesArray}
## Modification
{docstring Std.DHashMap.alter}
{docstring Std.DHashMap.modify}
{docstring Std.DHashMap.containsThenInsert}
{docstring Std.DHashMap.containsThenInsertIfNew}
{docstring Std.DHashMap.erase}
{docstring Std.DHashMap.filter}
{docstring Std.DHashMap.filterMap}
{docstring Std.DHashMap.insert}
{docstring Std.DHashMap.insertIfNew}
{docstring Std.DHashMap.getThenInsertIfNew?}
{docstring Std.DHashMap.insertMany}
{docstring Std.DHashMap.partition}
{docstring Std.DHashMap.union}
## Iteration
{docstring Std.DHashMap.iter}
{docstring Std.DHashMap.keysIter}
{docstring Std.DHashMap.valuesIter}
{docstring Std.DHashMap.map}
{docstring Std.DHashMap.fold}
{docstring Std.DHashMap.foldM}
{docstring Std.DHashMap.forIn}
{docstring Std.DHashMap.forM}
## Conversion
{docstring Std.DHashMap.ofList}
{docstring Std.DHashMap.toArray}
{docstring Std.DHashMap.toList}
## Unbundled Variants
Unbundled maps separate well-formedness proofs from data.
This is primarily useful when defining {ref "raw-data"}[nested inductive types].
To use these variants, import the modules `Std.DHashMap.Raw` and `Std.DHashMap.RawLemmas`.
{docstring Std.DHashMap.Raw}
{docstring Std.DHashMap.Raw.WF}
# Extensional Hash Maps
%%%
tag := "ExtHashMap"
%%%
The declarations in this section should be imported using `import Std.ExtHashMap`.
{docstring Std.ExtHashMap +hideFields +hideStructureConstructor}
## Creation
{docstring Std.ExtHashMap.emptyWithCapacity}
## Properties
{docstring Std.ExtHashMap.size}
{docstring Std.ExtHashMap.isEmpty}
## Queries
{docstring Std.ExtHashMap.contains}
{docstring Std.ExtHashMap.get}
{docstring Std.ExtHashMap.get!}
{docstring Std.ExtHashMap.get?}
{docstring Std.ExtHashMap.getD}
{docstring Std.ExtHashMap.getKey}
{docstring Std.ExtHashMap.getKey!}
{docstring Std.ExtHashMap.getKey?}
{docstring Std.ExtHashMap.getKeyD}
## Modification
{docstring Std.ExtHashMap.alter}
{docstring Std.ExtHashMap.modify}
{docstring Std.ExtHashMap.containsThenInsert}
{docstring Std.ExtHashMap.containsThenInsertIfNew}
{docstring Std.ExtHashMap.erase}
{docstring Std.ExtHashMap.filter}
{docstring Std.ExtHashMap.filterMap}
{docstring Std.ExtHashMap.insert}
{docstring Std.ExtHashMap.insertIfNew}
{docstring Std.ExtHashMap.getThenInsertIfNew?}
{docstring Std.ExtHashMap.insertMany}
{docstring Std.ExtHashMap.insertManyIfNewUnit}
## Iteration
{docstring Std.ExtHashMap.map}
## Conversion
{docstring Std.ExtHashMap.ofList}
{docstring Std.ExtHashMap.unitOfArray}
{docstring Std.ExtHashMap.unitOfList}
# Extensional Dependent Hash Maps
%%%
tag := "ExtDHashMap"
%%%
The declarations in this section should be imported using `import Std.ExtDHashMap`.
{docstring Std.ExtDHashMap +hideFields +hideStructureConstructor}
## Creation
{docstring Std.ExtDHashMap.emptyWithCapacity}
## Properties
{docstring Std.ExtDHashMap.size}
{docstring Std.ExtDHashMap.isEmpty}
## Queries
{docstring Std.ExtDHashMap.contains}
{docstring Std.ExtDHashMap.get}
{docstring Std.ExtDHashMap.get!}
{docstring Std.ExtDHashMap.get?}
{docstring Std.ExtDHashMap.getD}
{docstring Std.ExtDHashMap.getKey}
{docstring Std.ExtDHashMap.getKey!}
{docstring Std.ExtDHashMap.getKey?}
{docstring Std.ExtDHashMap.getKeyD}
## Modification
{docstring Std.ExtDHashMap.alter}
{docstring Std.ExtDHashMap.modify}
{docstring Std.ExtDHashMap.containsThenInsert}
{docstring Std.ExtDHashMap.containsThenInsertIfNew}
{docstring Std.ExtDHashMap.erase}
{docstring Std.ExtDHashMap.filter}
{docstring Std.ExtDHashMap.filterMap}
{docstring Std.ExtDHashMap.insert}
{docstring Std.ExtDHashMap.insertIfNew}
{docstring Std.ExtDHashMap.getThenInsertIfNew?}
{docstring Std.ExtDHashMap.insertMany}
## Iteration
{docstring Std.ExtDHashMap.map}
## Conversion
{docstring Std.ExtDHashMap.ofList}
# Hash Sets
%%%
tag := "HashSet"
%%%
{docstring Std.HashSet}
## Creation
{docstring Std.HashSet.emptyWithCapacity}
## Properties
{docstring Std.HashSet.isEmpty}
{docstring Std.HashSet.size}
{docstring Std.HashSet.Equiv}
:::syntax term (title := "Equivalence") (namespace := Std.HashMap)
The relation {name Std.HashSet.Equiv}`HashSet.Equiv` can also be written with an infix operator, which is scoped to its namespace:
```grammar
$_ ~m $_
```
:::
## Queries
{docstring Std.HashSet.contains}
{docstring Std.HashSet.get}
{docstring Std.HashSet.get!}
{docstring Std.HashSet.get?}
{docstring Std.HashSet.getD}
## Modification
{docstring Std.HashSet.insert}
{docstring Std.HashSet.insertMany}
{docstring Std.HashSet.erase}
{docstring Std.HashSet.filter}
{docstring Std.HashSet.containsThenInsert}
{docstring Std.HashSet.partition}
{docstring Std.HashSet.union}
## Iteration
{docstring Std.HashSet.iter}
{docstring Std.HashSet.all}
{docstring Std.HashSet.any}
{docstring Std.HashSet.fold}
{docstring Std.HashSet.foldM}
{docstring Std.HashSet.forIn}
{docstring Std.HashSet.forM}
## Conversion
{docstring Std.HashSet.ofList}
{docstring Std.HashSet.toList}
{docstring Std.HashSet.ofArray}
{docstring Std.HashSet.toArray}
## Unbundled Variants
Unbundled maps separate well-formedness proofs from data.
This is primarily useful when defining {ref "raw-data"}[nested inductive types].
To use these variants, import the modules `Std.HashSet.Raw` and `Std.HashSet.RawLemmas`.
{docstring Std.HashSet.Raw}
{docstring Std.HashSet.Raw.WF}
# Extensional Hash Sets
%%%
tag := "ExtHashSet"
%%%
{docstring Std.ExtHashSet}
## Creation
{docstring Std.ExtHashSet.emptyWithCapacity}
## Properties
{docstring Std.ExtHashSet.isEmpty}
{docstring Std.ExtHashSet.size}
## Queries
{docstring Std.ExtHashSet.contains}
{docstring Std.ExtHashSet.get}
{docstring Std.ExtHashSet.get!}
{docstring Std.ExtHashSet.get?}
{docstring Std.ExtHashSet.getD}
## Modification
{docstring Std.ExtHashSet.insert}
{docstring Std.ExtHashSet.insertMany}
{docstring Std.ExtHashSet.erase}
{docstring Std.ExtHashSet.filter}
{docstring Std.ExtHashSet.containsThenInsert}
## Conversion
{docstring Std.ExtHashSet.ofList}
{docstring Std.ExtHashSet.ofArray}
{include 1 Manual.BasicTypes.Maps.TreeMap}
# Dependent Tree-Based Maps
%%%
tag := "DTreeMap"
%%%
The declarations in this section should be imported using `import Std.DTreeMap`.
{docstring Std.DTreeMap +hideFields +hideStructureConstructor}
## Creation
{docstring Std.DTreeMap.empty}
## Properties
{docstring Std.DTreeMap.size}
{docstring Std.DTreeMap.isEmpty}
## Queries
{docstring Std.DTreeMap.contains}
{docstring Std.DTreeMap.get}
{docstring Std.DTreeMap.get!}
{docstring Std.DTreeMap.get?}
{docstring Std.DTreeMap.getD}
{docstring Std.DTreeMap.getKey}
{docstring Std.DTreeMap.getKey!}
{docstring Std.DTreeMap.getKey?}
{docstring Std.DTreeMap.getKeyD}
{docstring Std.DTreeMap.keys}
{docstring Std.DTreeMap.keysArray}
{docstring Std.DTreeMap.values}
{docstring Std.DTreeMap.valuesArray}
## Modification
{docstring Std.DTreeMap.alter}
{docstring Std.DTreeMap.modify}
{docstring Std.DTreeMap.containsThenInsert}
{docstring Std.DTreeMap.containsThenInsertIfNew}
{docstring Std.DTreeMap.erase}
{docstring Std.DTreeMap.filter}
{docstring Std.DTreeMap.filterMap}
{docstring Std.DTreeMap.insert}
{docstring Std.DTreeMap.insertIfNew}
{docstring Std.DTreeMap.getThenInsertIfNew?}
{docstring Std.DTreeMap.insertMany}
{docstring Std.DTreeMap.partition}
## Iteration
{docstring Std.DTreeMap.iter}
{docstring Std.DTreeMap.keysIter}
{docstring Std.DTreeMap.valuesIter}
{docstring Std.DTreeMap.map}
{docstring Std.DTreeMap.foldl}
{docstring Std.DTreeMap.foldlM}
{docstring Std.DTreeMap.forIn}
{docstring Std.DTreeMap.forM}
## Conversion
{docstring Std.DTreeMap.ofList}
{docstring Std.DTreeMap.toArray}
{docstring Std.DTreeMap.toList}
## Unbundled Variants
Unbundled maps separate well-formedness proofs from data.
This is primarily useful when defining {ref "raw-data"}[nested inductive types].
To use these variants, import the module `Std.DTreeMap.Raw`.
{docstring Std.DTreeMap.Raw}
{docstring Std.DTreeMap.Raw.WF}
{include 1 Manual.BasicTypes.Maps.TreeSet} |
reference-manual/Manual/BasicTypes/Nat.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
#doc (Manual) "Natural Numbers" =>
%%%
tag := "Nat"
%%%
The {deftech}[natural numbers] are nonnegative integers.
Logically, they are the numbers 0, 1, 2, 3, …, generated from the constructors {lean}`Nat.zero` and {lean}`Nat.succ`.
Lean imposes no upper bound on the representation of natural numbers other than physical constraints imposed by the available memory of the computer.
Because the natural numbers are fundamental to both mathematical reasoning and programming, they are specially supported by Lean's implementation. The logical model of the natural numbers is as an {tech}[inductive type], and arithmetic operations are specified using this model. In Lean's kernel, the interpreter, and compiled code, closed natural numbers are represented as efficient arbitrary-precision integers. Sufficiently small numbers are values that don't require indirection through a pointer. Arithmetic operations are implemented by primitives that take advantage of the efficient representations.
# Logical Model
%%%
tag := "nat-model"
%%%
{docstring Nat}
::::leanSection
```lean -show
variable (i : Nat)
```
:::example "Proofs by Induction"
The natural numbers are an {tech}[inductive type], so the {tactic}`induction` tactic can be used to prove universally-quantified statements.
A proof by induction requires a base case and an induction step.
The base case is a proof that the statement is true for `0`.
The induction step is a proof that the truth of the statement for some arbitrary number {lean}`i` implies its truth for {lean}`i + 1`.
This proof uses the lemma `Nat.succ_lt_succ` in its induction step.
```lean
example (n : Nat) : n < n + 1 := by
induction n with
| zero =>
show 0 < 1
decide
| succ i ih => -- ih : i < i + 1
show i + 1 < i + 1 + 1
exact Nat.succ_lt_succ ih
```
:::
::::
## Peano Axioms
%%%
tag := "peano-axioms"
%%%
The Peano axioms are a consequence of this definition.
The induction principle generated for {lean}`Nat` is the one demanded by the axiom of induction:
```signature
Nat.rec.{u} {motive : Nat → Sort u}
(zero : motive zero)
(succ : (n : Nat) → motive n → motive n.succ)
(t : Nat) :
motive t
```
This induction principle also implements primitive recursion.
The injectivity of {lean}`Nat.succ` and the disjointness of {lean}`Nat.succ` and `Nat.zero` are consequences of the induction principle, using a construction typically called “no confusion”:
```lean
def NoConfusion : Nat → Nat → Prop
| 0, 0 => True
| 0, _ + 1 | _ + 1, 0 => False
| n + 1, k + 1 => n = k
theorem noConfusionDiagonal (n : Nat) :
NoConfusion n n :=
Nat.rec True.intro (fun _ _ => rfl) n
theorem noConfusion (n k : Nat) (eq : n = k) :
NoConfusion n k :=
eq ▸ noConfusionDiagonal n
theorem succ_injective : n + 1 = k + 1 → n = k :=
noConfusion (n + 1) (k + 1)
theorem succ_not_zero : ¬n + 1 = 0 :=
noConfusion (n + 1) 0
```
# Run-Time Representation
%%%
tag := "nat-runtime"
%%%
The representation suggested by the declaration of `Nat` would be horrendously inefficient, as it's essentially a linked list.
The length of the list would be the number.
With this representation, addition would take time linear in the size of one of the addends, and numbers would take at least as many machine words as their magnitude in memory.
Thus, natural numbers have special support in both the kernel and the compiler that avoids this overhead.
In the kernel, there are special `Nat` literal values that use a widely-trusted, efficient arbitrary-precision integer library (usually [GMP](https://gmplib.org/)).
Basic functions such as addition are overridden by primitives that use this representation.
Because they are part of the kernel, if these primitives did not correspond to their definitions as Lean functions, it could undermine soundness.
In compiled code, sufficiently-small natural numbers are represented without pointer indirections: the lowest-order bit in an object pointer is used to indicate that the value is not, in fact, a pointer, and the remaining bits are used to store the number.
31 bits are available on 32-bits architectures for pointer-free {lean}`Nat`s, while 63 bits are available on 64-bit architectures.
In other words, natural numbers smaller than $`2^{31} = 2,147,483,648` or $`2^{63} = 9,223,372,036,854,775,808` do not require allocations.
If an natural number is too large for this representation, it is instead allocated as an ordinary Lean object that consists of an object header and an arbitrary-precision integer value.
## Performance Notes
%%%
tag := "nat-performance"
%%%
Using Lean's built-in arithmetic operators, rather than redefining them, is essential.
The logical model of {lean}`Nat` is essentially a linked list, so addition would take time linear in the size of one argument.
Still worse, multiplication takes quadratic time in this model.
While defining arithmetic from scratch can be a useful learning exercise, these redefined operations will not be nearly as fast.
# Syntax
%%%
tag := "nat-syntax"
%%%
Natural number literals are overridden using the {lean}`OfNat` type class, which is described in the {ref "nat-literals"}[section on literal syntax].
# API Reference
%%%
tag := "nat-api"
%%%
## Arithmetic
%%%
tag := "nat-api-arithmetic"
%%%
{docstring Nat.pred}
{docstring Nat.add}
{docstring Nat.sub}
{docstring Nat.mul}
{docstring Nat.div}
{docstring Nat.mod}
{docstring Nat.modCore}
{docstring Nat.pow}
{docstring Nat.log2}
### Bitwise Operations
%%%
tag := "nat-api-bitwise"
%%%
{docstring Nat.shiftLeft}
{docstring Nat.shiftRight}
{docstring Nat.xor}
{docstring Nat.lor}
{docstring Nat.land}
{docstring Nat.bitwise}
{docstring Nat.testBit}
## Minimum and Maximum
%%%
tag := "nat-api-minmax"
%%%
{docstring Nat.min}
{docstring Nat.max}
## GCD and LCM
%%%
tag := "nat-api-gcd-lcm"
%%%
{docstring Nat.gcd}
{docstring Nat.lcm}
## Powers of Two
%%%
tag := "nat-api-pow2"
%%%
{docstring Nat.isPowerOfTwo}
{docstring Nat.nextPowerOfTwo}
## Comparisons
%%%
tag := "nat-api-comparison"
%%%
### Boolean Comparisons
%%%
tag := "nat-api-comparison-bool"
%%%
{docstring Nat.beq}
{docstring Nat.ble}
{docstring Nat.blt}
### Decidable Equality
%%%
tag := "nat-api-deceq"
%%%
{docstring Nat.decEq}
{docstring Nat.decLe}
{docstring Nat.decLt}
### Predicates
%%%
tag := "nat-api-predicates"
%%%
{docstring Nat.le}
{docstring Nat.lt}
## Iteration
%%%
tag := "nat-api-iteration"
%%%
Many iteration operators come in two versions: a structurally recursive version and a tail-recursive version.
The structurally recursive version is typically easier to use in contexts where definitional equality is important, as it will compute when only some prefix of a natural number is known.
{docstring Nat.repeat}
{docstring Nat.repeatTR}
{docstring Nat.fold}
{docstring Nat.foldTR}
{docstring Nat.foldM}
{docstring Nat.foldRev}
{docstring Nat.foldRevM}
{docstring Nat.forM}
{docstring Nat.forRevM}
{docstring Nat.all}
{docstring Nat.allTR}
{docstring Nat.any}
{docstring Nat.anyTR}
{docstring Nat.allM}
{docstring Nat.anyM}
## Conversion
%%%
tag := "nat-api-conversion"
%%%
{docstring Nat.toUInt8}
{docstring Nat.toUInt16}
{docstring Nat.toUInt32}
{docstring Nat.toUInt64}
{docstring Nat.toUSize}
{docstring Nat.toInt8}
{docstring Nat.toInt16}
{docstring Nat.toInt32}
{docstring Nat.toInt64}
{docstring Nat.toISize}
{docstring Nat.toFloat}
{docstring Nat.toFloat32}
{docstring Nat.isValidChar}
{docstring Nat.repr}
{docstring Nat.toDigits}
{docstring Nat.digitChar}
{docstring Nat.toSubscriptString}
{docstring Nat.toSuperscriptString}
{docstring Nat.toSuperDigits}
{docstring Nat.toSubDigits}
{docstring Nat.subDigitChar}
{docstring Nat.superDigitChar}
## Elimination
%%%
tag := "nat-api-elim"
%%%
The recursion principle that is automatically generated for {lean}`Nat` results in proof goals that are phrased in terms of {lean}`Nat.zero` and {lean}`Nat.succ`.
This is not particularly user-friendly, so an alternative logically-equivalent recursion principle is provided that results in goals that are phrased in terms of {lean}`0` and `n + 1`.
{tech}[Custom eliminators] for the {tactic}`induction` and {tactic}`cases` tactics can be supplied using the {attr}`induction_eliminator` and {attr}`cases_eliminator` attributes.
{docstring Nat.recAux}
{docstring Nat.casesAuxOn}
### Alternative Induction Principles
%%%
tag := "nat-api-induction"
%%%
{docstring Nat.strongRecOn}
{docstring Nat.caseStrongRecOn}
{docstring Nat.div.inductionOn}
{docstring Nat.div2Induction}
{docstring Nat.mod.inductionOn} |
reference-manual/Manual/BasicTypes/Thunk.lean | import VersoManual
import Manual.Meta
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Lazy Computations" =>
%%%
tag := "Thunk"
%%%
A {deftech}_thunk_ delays the computation of a value.
In particular, the {name}`Thunk` type is used to delay the computation of a value in compiled code until it is explicitly requested—this request is called {deftech (key := "force")}_forcing_ the thunk.
The computed value is saved, so subsequent requests do not result in recomputation.
Computing values at most once, when explicitly requested, is called {deftech}_lazy evaluation_.{index}[call-by-need]
This caching is invisible to Lean's logic, in which {name}`Thunk` is equivalent to a function from {name}`Unit`.
# Logical Model
%%%
tag := "Thunk-model"
%%%
Thunks are modeled as a single-field structure that contains a function from {lean}`Unit`.
The structure's field is private, so the function itself cannot be directly accessed.
Instead, {name}`Thunk.get` should be used.
From the perspective of the logic, they are equivalent; {name}`Thunk.get` exists to be overridden in the compiler by the platform primitive that implements lazy evaluation.
{docstring Thunk}
# Runtime Representation
%%%
tag := "Thunk-runtime"
%%%
:::figure "Memory layout of thunks" (tag := "thunkffi")

:::
Thunks are one of the primitive object types supported by the Lean runtime.
The object header contains a specific tag that indicates that an object is a thunk.
:::paragraph
Thunks have two fields:
* `m_value` is a pointer to a saved value, which is a null pointer if the value has not yet been computed.
* `m_closure` is a closure which is to be called when the value should be computed.
The runtime system maintains the invariant that either the closure or the saved value is a null pointer.
If both are null pointers, then the thunk is being forced on another thread.
:::
When a thunk is {tech (key := "force")}[forced], the runtime system first checks whether the saved value has already been computed, returning it if so.
Otherwise, it attempts to acquire a lock on the closure by atomically swapping it with a null pointer.
If the lock is acquired, it is invoked to compute the value; the computed value is stored in the saved value field and the reference to the closure is dropped.
If not, then another thread is already computing the value; the system waits until it is computed.
# Coercions
%%%
tag := "Thunk-coercions"
%%%
:::leanSection
```lean -show
variable {α : Type u} {e : α}
```
There is a coercion from any type {lean}`α` to {lean}`Thunk α` that converts a term {lean}`e` into {lean}`Thunk.mk fun () => e`.
Because the elaborator {ref "coercion-insertion"}[unfolds coercions], evaluation of the original term {lean}`e` is delayed; the coercion is not equivalent to {name}`Thunk.pure`.
:::
:::example "Lazy Lists"
Lazy lists are lists that may contain thunks.
The {name LazyList.delayed}`delayed` constructor causes part of the list to be computed on demand.
```lean
inductive LazyList (α : Type u) where
| nil
| cons : α → LazyList α → LazyList α
| delayed : Thunk (LazyList α) → LazyList α
deriving Inhabited
```
Lazy lists can be converted to ordinary lists by forcing all the embedded thunks.
```lean
def LazyList.toList : LazyList α → List α
| .nil => []
| .cons x xs => x :: xs.toList
| .delayed xs => xs.get.toList
```
Many operations on lazy lists can be implemented without forcing the embedded thunks, instead building up further thunks.
The body of {name LazyList.delayed}`delayed` does not need to be an explicit call to {name}`Thunk.mk` because of the coercion.
```lean
def LazyList.take : Nat → LazyList α → LazyList α
| 0, _ => .nil
| _, .nil => .nil
| n + 1, .cons x xs => .cons x <| .delayed <| take n xs
| n + 1, .delayed xs => .delayed <| take (n + 1) xs.get
def LazyList.ofFn (f : Fin n → α) : LazyList α :=
Fin.foldr n (init := .nil) fun i xs =>
.delayed <| LazyList.cons (f i) xs
def LazyList.append (xs ys : LazyList α) : LazyList α :=
.delayed <|
match xs with
| .nil => ys
| .cons x xs' => LazyList.cons x (append xs' ys)
| .delayed xs' => append xs'.get ys
```
Laziness is ordinarily invisible to Lean programs: there is no way to check whether a thunk has been forced.
However, {keywordOf Lean.Parser.Term.dbgTrace}`dbg_trace` can be used to gain insight into thunk evaluation.
```lean
def observe (tag : String) (i : Fin n) : Nat :=
dbg_trace "{tag}: {i.val}"
i.val
```
The lazy lists {lean}`xs` and {lean}`ys` emit traces when evaluated.
```lean
def xs := LazyList.ofFn (n := 3) (observe "xs")
def ys := LazyList.ofFn (n := 3) (observe "ys")
```
Converting {lean}`xs` to an ordinary list forces all of the embedded thunks:
```lean (name := lazy1)
#eval xs.toList
```
```leanOutput lazy1
xs: 0
xs: 1
xs: 2
```
```leanOutput lazy1
[0, 1, 2]
```
Likewise, converting {lean}`xs.append ys` to an ordinary list forces the embedded thunks:
```lean (name := lazy2)
#eval xs.append ys |>.toList
```
```leanOutput lazy2
xs: 0
xs: 1
xs: 2
ys: 0
ys: 1
ys: 2
```
```leanOutput lazy2
[0, 1, 2, 0, 1, 2]
```
Appending {lean}`xs` to itself before forcing the thunks results in a single set of traces, because each thunk's code is evaluated just once:
```lean (name := lazy3)
#eval xs.append xs |>.toList
```
```leanOutput lazy3
xs: 0
xs: 1
xs: 2
```
```leanOutput lazy3
[0, 1, 2, 0, 1, 2]
```
Finally, taking a prefix of {lean}`xs.append ys` results in only some of the thunks in {lean}`ys` being evaluated:
```lean (name := lazy4)
#eval xs.append ys |>.take 4 |>.toList
```
```leanOutput lazy4
xs: 0
xs: 1
xs: 2
ys: 0
```
```leanOutput lazy4
[0, 1, 2, 0]
```
:::
# API Reference
%%%
tag := "Thunk-api"
%%%
{docstring Thunk.get}
{docstring Thunk.map}
{docstring Thunk.pure}
{docstring Thunk.bind} |
reference-manual/Manual/BasicTypes/BitVec.lean | import VersoManual
import Manual.Meta
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.typography.dashes false -- There's a reference to a Figure 5-2 below that should not be an en dash
set_option maxRecDepth 768
#doc (Manual) "Bitvectors" =>
%%%
tag := "BitVec"
%%%
Bitvectors are fixed-width sequences of binary digits.
They are frequently used in software verification, because they closely model efficient data structures and operations that are similar to hardware.
A bitvector can be understood from two perspectives: as a sequence of bits, or as a number encoded by a sequence of bits.
When a bitvector represents a number, it can do so as either a signed or an unsigned number.
Signed numbers are represented in two's complement form.
# Logical Model
Bitvectors are represented as a wrapper around a {name}`Fin` with a suitable bound.
Because {name}`Fin` itself is a wrapper around a {name}`Nat`, bitvectors are able to use the kernel's special support for efficient computation with natural numbers.
{docstring BitVec}
# Runtime Representation
Bitvectors are represented as a {lean}`Fin` with the corresponding range.
Because {name}`BitVec` is a {ref "inductive-types-trivial-wrappers"}[trivial wrapper] around {name}`Fin` and {name}`Fin` is a trivial wrapper around {name}`Nat`, bitvectors use the same runtime representation as {name}`Nat` in compiled code.
# Syntax
:::leanSection
```lean -show
variable {w n : Nat}
```
There is an {inst}`OfNat (BitVec w) n` instance for all widths {lean}`w` and natural numbers {lean}`n`.
Natural number literals, including those that use hexadecimal or binary notation, may be used to represent bitvectors in contexts where the expected type is known.
When the expected type is not known, a dedicated syntax allows the width of the bitvector to be specified along with its value.
:::
:::example "Numeric Literals for Bitvectors"
The following literals are all equivalent:
```lean
example : BitVec 8 := 0xff
example : BitVec 8 := 255
example : BitVec 8 := 0b1111_1111
```
```lean -show
-- Inline test
example : (0xff : BitVec 8) = 255 := by rfl
example : (0b1111_1111 : BitVec 8) = 255 := by rfl
```
:::
:::syntax term (title := "Fixed-Width Bitvector Literals")
```grammar
$_:num#$_
```
This notation pairs a numeric literal with a term that denotes its width.
Spaces are forbidden around the `#`.
Literals that overflow the width of the bitvector are truncated.
:::
:::::example "Fixed-Width Bitvector Literals"
Bitvectors may be represented by natural number literals, so {lean}`(5 : BitVec 8)` is a valid bitvector.
Additionally, a width may be specified directly in the literal:
```leanTerm
5#8
```
Spaces are not allowed on either side of the `#`:
```syntaxError spc1 (category := term)
5 #8
```
```leanOutput spc1
<example>:1:2-1:3: expected end of input
```
```syntaxError spc2 (category := term)
5# 8
```
```leanOutput spc2
<example>:1:3-1:4: expected no space before
```
A numeric literal is required to the left of the `#`:
```syntaxError spc3 (category := term)
(3 + 2)#8
```
```leanOutput spc3
<example>:1:7-1:8: expected end of input
```
However, a term is allowed to the right of the `#`:
```leanTerm
5#(4 + 4)
```
If the literal is too large to fit in the specified number of bits, then it is truncated:
```lean (name := overflow)
#eval 7#2
```
```leanOutput overflow
3#2
```
:::::
:::syntax term (title := "Bounded Bitvector Literals") (namespace := BitVec)
```grammar
$_:num#'$_
```
This notation is available only when the `BitVec` namespace has been opened.
Rather than an explicit width, it expects a proof that the literal value is representable by a bitvector of the corresponding width.
:::
::::::leanSection
:::::example "Bounded Bitvector Literals"
The bounded bitvector literal notation ensures that literals do not overflow the specified number of bits.
The notation is only available when the `BitVec` namespace has been opened.
```lean
open BitVec
```
Literals that are in bounds require a proof to that effect:
```lean
example : BitVec 8 := 1#'(by decide)
```
Literals that are not in bounds are not allowed:
```lean +error (name := oob)
example : BitVec 8 := 256#'(by decide)
```
```leanOutput oob
Tactic `decide` proved that the proposition
256 < 2 ^ 8
is false
```
:::::
::::::
# Automation
%%%
tag := "BitVec-automation"
%%%
In addition to the full suite of automation and tools provided by Lean for every type, the {tactic}`bv_decide` tactic can solve many bitvector-related problems.
This tactic invokes an external automated theorem prover (`cadical`) and reconstructs the proof that it provides in Lean's own logic.
The resulting proofs rely only on the axiom {name}`Lean.ofReduceBool`; the external prover is not part of the trusted code base.
:::example "Popcount"
```imports -show
import Std.Tactic.BVDecide
```
The function {lean}`popcount` returns the number of set bits in a bitvector.
It can be implemented as a 32-iteration loop that tests each bit, incrementing a counter if the bit is set:
```lean
def popcount_spec (x : BitVec 32) : BitVec 32 :=
(32 : Nat).fold (init := 0) fun i _ pop =>
pop + ((x >>> i) &&& 1)
```
An alternative implementation of {lean}`popcount` is described in _Hacker's Delight, Second Edition_, by Henry S. Warren,
Jr. in Figure 5-2 on p. 82.
It uses low-level bitwise operations to compute the same value with far fewer operations:
```lean
def popcount (x : BitVec 32) : BitVec 32 :=
let x := x - ((x >>> 1) &&& 0x55555555)
let x := (x &&& 0x33333333) + ((x >>> 2) &&& 0x33333333)
let x := (x + (x >>> 4)) &&& 0x0F0F0F0F
let x := x + (x >>> 8)
let x := x + (x >>> 16)
let x := x &&& 0x0000003F
x
```
These two implementations can be proven equivalent using {tactic}`bv_decide`:
```lean
theorem popcount_correct : popcount = popcount_spec := by
funext x
simp [popcount, popcount_spec]
bv_decide
```
:::
# API Reference
%%%
tag := "BitVec-api"
%%%
## Bounds
{docstring BitVec.intMax}
{docstring BitVec.intMin}
## Construction
{docstring BitVec.fill}
{docstring BitVec.zero}
{docstring BitVec.allOnes}
{docstring BitVec.twoPow}
## Conversion
{docstring BitVec.toHex}
{docstring BitVec.toInt}
{docstring BitVec.toNat}
{docstring BitVec.ofBool}
{docstring BitVec.ofBoolListBE}
{docstring BitVec.ofBoolListLE}
{docstring BitVec.ofInt}
{docstring BitVec.ofNat}
{docstring BitVec.ofNatLT}
{docstring BitVec.cast}
## Comparisons
{docstring BitVec.ule}
{docstring BitVec.sle}
{docstring BitVec.ult}
{docstring BitVec.slt}
{docstring BitVec.decEq}
## Hashing
{docstring BitVec.hash}
## Sequence Operations
These operations treat bitvectors as sequences of bits, rather than as encodings of numbers.
{docstring BitVec.nil}
{docstring BitVec.cons}
{docstring BitVec.concat}
{docstring BitVec.shiftConcat}
{docstring BitVec.truncate}
{docstring BitVec.setWidth}
{docstring BitVec.setWidth'}
{docstring BitVec.append}
{docstring BitVec.replicate}
{docstring BitVec.reverse}
{docstring BitVec.rotateLeft}
{docstring BitVec.rotateRight}
### Bit Extraction
{docstring BitVec.msb}
{docstring BitVec.getMsbD}
{docstring BitVec.getMsb}
{docstring BitVec.getMsb?}
{docstring BitVec.getLsbD}
{docstring BitVec.getLsb}
{docstring BitVec.getLsb?}
{docstring BitVec.extractLsb}
{docstring BitVec.extractLsb'}
## Bitwise Operators
These operators modify the individual bits of one or more bitvectors.
{docstring BitVec.and}
{docstring BitVec.or}
{docstring BitVec.not}
{docstring BitVec.xor}
{docstring BitVec.zeroExtend}
{docstring BitVec.signExtend}
{docstring BitVec.ushiftRight}
{docstring BitVec.sshiftRight}
{docstring BitVec.sshiftRight'}
{docstring BitVec.shiftLeft}
{docstring BitVec.shiftLeftZeroExtend}
## Arithmetic
These operators treat bitvectors as numbers.
Some operations are signed, while others are unsigned.
Because bitvectors are understood as two's complement numbers, addition, subtraction and multiplication coincide for the signed and unsigned interpretations.
{docstring BitVec.add}
{docstring BitVec.sub}
{docstring BitVec.mul}
### Unsigned Operations
{docstring BitVec.udiv}
{docstring BitVec.smtUDiv}
{docstring BitVec.umod}
{docstring BitVec.uaddOverflow}
{docstring BitVec.usubOverflow}
### Signed Operations
{docstring BitVec.abs}
{docstring BitVec.neg}
{docstring BitVec.sdiv}
{docstring BitVec.smtSDiv}
{docstring BitVec.smod}
{docstring BitVec.srem}
{docstring BitVec.saddOverflow}
{docstring BitVec.ssubOverflow}
## Iteration
{docstring BitVec.iunfoldr}
{docstring BitVec.iunfoldr_replace}
## Proof Automation
### Bit Blasting
The standard library contains a number of helper implementations that are useful to implement bit blasting, which is the technique used by {tactic}`bv_decide` to encode propositions as Boolean satisfiability problems for external solvers.
{docstring BitVec.adc}
{docstring BitVec.adcb}
{docstring BitVec.carry}
{docstring BitVec.mulRec}
{docstring BitVec.divRec}
{docstring BitVec.divSubtractShift}
{docstring BitVec.shiftLeftRec}
{docstring BitVec.sshiftRightRec}
{docstring BitVec.ushiftRightRec} |
reference-manual/Manual/BasicTypes/Empty.lean | import VersoManual
import Manual.Meta
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "The Empty Type" =>
%%%
tag := "empty"
%%%
The empty type {name}`Empty` represents impossible values.
It is an inductive type with no constructors whatsoever.
While the trivial type {name}`Unit`, which has a single constructor that takes no parameters, can be used to model computations where a result is unwanted or uninteresting, {name}`Empty` can be used in situations where no computation should be possible at all.
Instantiating a polymorphic type with {name}`Empty` can mark some of its constructors—those with a parameter of the corresponding type—as impossible; this can rule out certain code paths that are not desired.
The presence of a term with type {name}`Empty` indicates that an impossible code path has been reached.
There will never be a value with this type, due to the lack of constructors.
On an impossible code path, there's no reason to write further code; the function {name}`Empty.elim` can be used to escape an impossible path.
The universe-polymorphic equivalent of {name}`Empty` is {name}`PEmpty`.
{docstring Empty}
{docstring PEmpty}
:::example "Impossible Code Paths"
The type signature of the function {lean}`f` indicates that it might throw exceptions, but allows the exception type to be anything:
```lean
def f (n : Nat) : Except ε Nat := pure n
```
Instantiating {lean}`f`'s exception type with {lean}`Empty` exploits the fact that {lean}`f` never actually throws an exception to convert it to a function whose type indicates that no exceptions will be thrown.
In particular, it allows {lean}`Empty.elim` to be used to avoid handing the impossible exception value.
```lean
def g (n : Nat) : Nat :=
match f (ε := Empty) n with
| .error e =>
Empty.elim e
| .ok v => v
```
:::
# API Reference
{docstring Empty.elim}
{docstring PEmpty.elim} |
reference-manual/Manual/BasicTypes/ByteArray.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.Array.Subarray
import Manual.BasicTypes.Array.FFI
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option verso.docstring.allowMissing true -- TODO remove after docstrings are merged
example := Char
#doc (Manual) "Byte Arrays" =>
%%%
tag := "ByteArray"
%%%
Byte arrays are a specialized array type that can only contain elements of type {name}`UInt8`.
Due to this restriction, they can use a much more efficient representation, with no pointer indirections.
Like other arrays, byte arrays are represented in compiled code as {tech}[dynamic arrays], and the Lean runtime specially optimizes array operations.
The operations that modify byte arrays first check the array's {ref "reference-counting"}[reference count], and if there are no other references to the array, it is modified in place.
There is no literal syntax for byte arrays.
{name}`List.toByteArray` can be used to construct an array from a list literal.
{docstring ByteArray}
# API Reference
## Constructing Byte Arrays
{docstring ByteArray.empty}
{docstring ByteArray.emptyWithCapacity}
{docstring ByteArray.append}
{docstring ByteArray.fastAppend}
{docstring ByteArray.copySlice}
## Size
{docstring ByteArray.size}
{docstring ByteArray.usize}
{docstring ByteArray.isEmpty}
## Lookups
{docstring ByteArray.get}
{docstring ByteArray.uget}
{docstring ByteArray.get!}
{docstring ByteArray.extract}
## Conversions
{docstring ByteArray.toList}
{docstring ByteArray.toUInt64BE!}
{docstring ByteArray.toUInt64LE!}
### UTF-8
{docstring ByteArray.utf8Decode?}
{docstring ByteArray.utf8DecodeChar?}
{docstring ByteArray.utf8DecodeChar}
## Modification
{docstring ByteArray.push}
{docstring ByteArray.set}
{docstring ByteArray.uset}
{docstring ByteArray.set!}
## Iteration
{docstring ByteArray.foldl}
{docstring ByteArray.foldlM}
{docstring ByteArray.forIn}
## Iterators
{docstring ByteArray.iter}
{docstring ByteArray.Iterator}
{docstring ByteArray.Iterator.pos}
{docstring ByteArray.Iterator.atEnd}
{docstring ByteArray.Iterator.hasNext}
{docstring ByteArray.Iterator.hasPrev}
{docstring ByteArray.Iterator.curr}
{docstring ByteArray.Iterator.curr'}
{docstring ByteArray.Iterator.next}
{docstring ByteArray.Iterator.next'}
{docstring ByteArray.Iterator.forward}
{docstring ByteArray.Iterator.nextn}
{docstring ByteArray.Iterator.prev}
{docstring ByteArray.Iterator.prevn}
{docstring ByteArray.Iterator.remainingBytes}
{docstring ByteArray.Iterator.toEnd}
## Slices
{docstring ByteArray.toByteSlice}
{docstring ByteSlice}
{docstring ByteSlice.beq}
{docstring ByteSlice.byteArray}
{docstring ByteSlice.contains}
{docstring ByteSlice.empty}
{docstring ByteSlice.foldr}
{docstring ByteSlice.foldrM}
{docstring ByteSlice.forM}
{docstring ByteSlice.get}
{docstring ByteSlice.get!}
{docstring ByteSlice.getD}
{docstring ByteSlice.ofByteArray}
{docstring ByteSlice.size}
{docstring ByteSlice.slice}
{docstring ByteSlice.start}
{docstring ByteSlice.stop}
{docstring ByteSlice.toByteArray}
## Element Predicates
{docstring ByteArray.findIdx?}
{docstring ByteArray.findFinIdx?} |
reference-manual/Manual/BasicTypes/Range.lean | import VersoManual
import Manual.Meta
import Manual.Interaction.FormatRepr
open Lean.MessageSeverity
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option format.width 60
#doc (Manual) "Ranges" =>
%%%
tag := "ranges"
%%%
A {deftech}_range_ represents a series of consecutive elements of some type, from a lower bound to an upper bound.
The bounds may be open, in which case the bound value is not part of the range, or closed, in which case the bound value is part of the range.
Either bound may be omitted, in which case the range extends infinitely in the corresponding direction.
Ranges have dedicated syntax that consists of a starting point, {keyword}`...`, and an ending point.
The starting point may be either `*`, which denotes a range that continues infinitely downwards, or a term, which denotes a range with a specific starting value.
By default, ranges are left-closed: they contain their starting points.
A trailing `<` indicates that the range is left-open and does not contain its starting point.
The ending point may be `*`, in which case the range continues infinitely upwards, or a term, which denotes a range with a specific ending value.
By default, ranges are right-open: they do not contain their ending points.
The ending point may be prefixed with `<` to indicate that it is right-open; this is the default and does not change the meaning, but may be easier to read.
It may also be prefixed with `=` to indicate that the range is right-closed and contains its ending point.
:::example "Ranges of Natural Numbers"
The range that contains the numbers {lean}`3` through {lean}`6` can be written in a variety of ways:
```lean (name := rng1)
#eval (3...7).toList
```
```leanOutput rng1
[3, 4, 5, 6]
```
```lean (name := rng2)
#eval (3...=6).toList
```
```leanOutput rng2
[3, 4, 5, 6]
```
```lean (name := rng3)
#eval (2<...=6).toList
```
```leanOutput rng3
[3, 4, 5, 6]
```
:::
:::example "Finite and Infinite Ranges"
This range cannot be converted to a list, because it is infinite:
```lean (name := rng4) +error
#eval (3...*).toList
```
Finiteness of a left-closed, right-unbounded range is indicated by the presence of an instance of {name}`Std.Rxi.IsAlwaysFinite`, which does not exist for {name}`Nat`.
{name}`Std.Rco` is the type of these ranges, and the name {name}`Std.Rxi.IsAlwaysFinite` indicates that it determines finiteness for all right-unbounded ranges.
```leanOutput rng4
failed to synthesize instance of type class
Std.Rxi.IsAlwaysFinite Nat
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
Attempting to enumerate the negative integers leads to a similar error, this time because there is no way to determine the least element:
```lean (name := intrange) +error
#eval (*...(0 : Int)).toList
```
```leanOutput intrange
failed to synthesize instance of type class
Std.PRange.Least? Int
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
Unbounded ranges in finite types indicate that the range extends to the greatest element of the type.
Because {name}`UInt8` has 256 elements, this range contains 253 elements:
```lean (name := uintrange)
#eval ((3 : UInt8)...*).toArray.size
```
```leanOutput uintrange
253
```
:::
:::syntax term (title := "Range Syntax")
This range is left-closed, right-open, and indicates {name}`Std.Rco`:
```grammar
$a...$b
```
This range is left-closed, right-open, and indicates {name}`Std.Rco`:
```grammar
$a...<$b
```
This range is left-closed, right-closed, and indicates {name}`Std.Rcc`:
```grammar
$a...=$b
```
This range is left-closed, right-infinite, and indicates {name}`Std.Rci`:
```grammar
$a...*
```
This range is left-open, right-open, and indicates {name}`Std.Roo`:
```grammar
$a<...$b
```
This range is left-open, right-open, and indicates {name}`Std.Roo`:
```grammar
$a<...<$b
```
This range is left-open, right-closed, and indicates {name}`Std.Roc`:
```grammar
$a<...=$b
```
This range is left-open, right-infinite, and indicates {name}`Std.Roi`:
```grammar
$a<...*
```
This range is left-infinite, right-open, and indicates {name}`Std.Rio`:
```grammar
*...$b
```
This range is left-infinite, right-open, and indicates {name}`Std.Ric`:
```grammar
*...<$b
```
This range is left-infinite, right-closed, and indicates {name}`Std.Ric`:
```grammar
*...=$b
```
This range is infinite on both sides, and indicates {name}`Std.Rii`:
```grammar
*...*
```
:::
# Range Types
{docstring Std.Rco +allowMissing}
{docstring Std.Rco.iter}
{docstring Std.Rco.toArray}
{docstring Std.Rco.toList}
{docstring Std.Rco.size}
{docstring Std.Rco.isEmpty}
{docstring Std.Rcc +allowMissing}
{docstring Std.Rcc.iter}
{docstring Std.Rcc.toArray}
{docstring Std.Rcc.toList}
{docstring Std.Rcc.size}
{docstring Std.Rcc.isEmpty}
{docstring Std.Rci +allowMissing}
{docstring Std.Rci.iter}
{docstring Std.Rci.toArray}
{docstring Std.Rci.toList}
{docstring Std.Rci.size}
{docstring Std.Rci.isEmpty}
{docstring Std.Roo +allowMissing}
{docstring Std.Roo.iter}
{docstring Std.Roo.toArray}
{docstring Std.Roo.toList}
{docstring Std.Roo.size}
{docstring Std.Roo.isEmpty}
{docstring Std.Roc +allowMissing}
{docstring Std.Roc.iter}
{docstring Std.Roc.toArray}
{docstring Std.Roc.toList}
{docstring Std.Roc.size}
{docstring Std.Roc.isEmpty}
{docstring Std.Roi +allowMissing}
{docstring Std.Roi.iter}
{docstring Std.Roi.toArray}
{docstring Std.Roi.toList}
{docstring Std.Roi.size}
{docstring Std.Roi.isEmpty}
{docstring Std.Rio +allowMissing}
{docstring Std.Rio.iter}
{docstring Std.Rio.toArray}
{docstring Std.Rio.toList}
{docstring Std.Rio.size}
{docstring Std.Rio.isEmpty}
{docstring Std.Ric +allowMissing}
{docstring Std.Ric.iter}
{docstring Std.Ric.toArray}
{docstring Std.Ric.toList}
{docstring Std.Ric.size}
{docstring Std.Ric.isEmpty}
{docstring Std.Rii}
{docstring Std.Rii.iter}
{docstring Std.Rii.toArray}
{docstring Std.Rii.toList}
{docstring Std.Rii.size}
{docstring Std.Rii.isEmpty}
# Range-Related Type Classes
{docstring Std.PRange.UpwardEnumerable}
{docstring Std.PRange.UpwardEnumerable.LE}
{docstring Std.PRange.UpwardEnumerable.LT}
{docstring Std.PRange.LawfulUpwardEnumerable}
{docstring Std.PRange.Least?}
{docstring Std.PRange.InfinitelyUpwardEnumerable +allowMissing}
{docstring Std.PRange.LinearlyUpwardEnumerable +allowMissing}
{docstring Std.Rxi.IsAlwaysFinite +allowMissing}
{docstring Std.Rxi.HasSize}
{docstring Std.Rxc.IsAlwaysFinite +allowMissing}
{docstring Std.Rxc.HasSize}
# Implementing Ranges
The built-in range types may be used with any type, but their usefulness depends on the presence of certain type class instances.
Generally speaking, ranges are either checked for membership, enumerated or iterated over.
To check whether an value is contained in a range, {name}`DecidableLT` and {name}`DecidableLE` instances are used to compare the value to the range's respective open and closed endpoints.
To get an iterator for a range, instances of {name}`Std.PRange.UpwardEnumerable` and {name}`Std.PRange.LawfulUpwardEnumerable` are all that's needed.
To iterate directly over it in a {keywordOf Lean.Parser.Term.doFor}`for` loop, {name}`Std.PRange.LawfulUpwardEnumerableLE` and {name}`Std.PRange.LawfulUpwardEnumerableLT` are required as well.
To enumerate a range (e.g. by calling {name Std.Rco.toList}`toList`), it must be proven finite.
This is done by supplying instances of {name}`Std.Rxi.IsAlwaysFinite`, {name}`Std.Rxc.IsAlwaysFinite`, or {name}`Std.Rxo.IsAlwaysFinite`.
::::example "Implementing Ranges" (open := true)
The enumeration type {name}`Day` represents the days of the week:
```lean
inductive Day where
| mo | tu | we | th | fr | sa | su
deriving Repr
```
:::paragraph
```imports -show
import Std.Data.Iterators
```
While it's already possible to use this type in ranges, they're not particularly useful.
There's no membership instance:
```lean +error (name := noMem)
#eval Day.we ∈ (Day.mo...=Day.fr)
```
```leanOutput noMem
failed to synthesize instance of type class
Membership Day (Std.Rcc Day)
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
Ranges can't be iterated over:
```lean +error (name := noIter)
#eval show IO Unit from
for d in Day.mo...=Day.fr do
IO.println s!"It's {repr d}"
```
```leanOutput noIter
failed to synthesize instance for 'for_in%' notation
ForIn (EIO IO.Error) (Std.Rcc Day) ?m.11
```
Nor can they be enumerated, even though the type is finite:
```lean +error (name := noEnum)
#eval (Day.sa...*).toList
```
```leanOutput noEnum
failed to synthesize instance of type class
Std.PRange.UpwardEnumerable Day
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
:::
:::paragraph
Membership tests require {name}`DecidableLT` and {name}`DecidableLE` instances.
An easy way to get these is to number each day, and compare the numbers:
```lean
def Day.toNat : Day → Nat
| mo => 0
| tu => 1
| we => 2
| th => 3
| fr => 4
| sa => 5
| su => 6
instance : LT Day where
lt d1 d2 := d1.toNat < d2.toNat
instance : LE Day where
le d1 d2 := d1.toNat ≤ d2.toNat
instance : DecidableLT Day :=
fun d1 d2 => inferInstanceAs (Decidable (d1.toNat < d2.toNat))
instance : DecidableLE Day :=
fun d1 d2 => inferInstanceAs (Decidable (d1.toNat ≤ d2.toNat))
```
:::
:::paragraph
With these instances available, membership tests work as expected:
```lean
def Day.isWeekday (d : Day) : Bool := d ∈ Day.mo...Day.sa
```
```lean (name := thursday)
#eval Day.th.isWeekday
```
```leanOutput thursday
true
```
```lean (name := saturday)
#eval Day.sa.isWeekday
```
```leanOutput saturday
false
```
:::
:::paragraph
Iteration and enumeration are both variants on repeatedly applying a successor function until either the upper bound of the range or the largest element of the type is reached.
This successor function is {name}`Std.PRange.UpwardEnumerable.succ?`.
It's also convenient to have a definition of the function in {name}`Day`'s namespace for use with generalized field notation:
```lean
def Day.succ? : Day → Option Day
| mo => some tu
| tu => some we
| we => some th
| th => some fr
| fr => some sa
| sa => some su
| su => none
instance : Std.PRange.UpwardEnumerable Day where
succ? := Day.succ?
```
:::
Iteration also requires a proof that the implementation of {name Std.PRange.UpwardEnumerable.succ?}`succ?` is sensible.
Its properties are expressed in terms of {name}`Std.PRange.UpwardEnumerable.succMany?`, which iterates the application of {name Std.PRange.UpwardEnumerable.succ?}`succ?` a certain number of times and has a default implementation in terms of {name}`Nat.repeat` and {name Std.PRange.UpwardEnumerable.succ?}`succ?`.
In particular, an instance of {name Std.PRange.LawfulUpwardEnumerable}`LawfulUpwardEnumerable` requires proofs that {name}`Std.PRange.UpwardEnumerable.succMany?` corresponds to the default implementation along with a proof that repeatedly applying the successor never yields the same element again.
:::paragraph
The first step is to write two helper lemmas for the two proofs about {name Std.PRange.UpwardEnumerable.succMany?}`succMany?`.
While they could be written inline in the instance declaration, it's convenient for them to have the {attrs}`@[simp]` attribute.
```lean
@[simp]
theorem Day.succMany?_zero (d : Day) :
Std.PRange.succMany? 0 d = some d := by
simp [Std.PRange.succMany?, Nat.repeat]
@[simp]
theorem Day.succMany?_add_one (n : Nat) (d : Day) :
Std.PRange.succMany? (n + 1) d =
(Std.PRange.succMany? n d).bind Std.PRange.succ? := by
simp [Std.PRange.succMany?, Nat.repeat, Std.PRange.succ?]
```
Proving that there are no cycles in successor uses a convenient helper lemma that calculates the number of successor steps between any two days.
It is marked {attrs}`@[grind →]` because when assumptions that match its premises are present, it adds a great deal of new information:
```lean
@[grind →]
theorem Day.succMany?_steps {d d' : Day} {steps} :
Std.PRange.succMany? steps d = some d' →
if d ≤ d' then steps = d'.toNat - d.toNat
else False := by
intro h
match steps with
| 0 | 1 | 2 | 3 | 4 | 5 | 6 =>
cases d <;> cases d' <;>
simp_all +decide [Std.PRange.succMany?, Nat.repeat, Day.succ?]
| n + 7 =>
simp at h
cases h' : (Std.PRange.succMany? n d) with
| none =>
simp_all
| some d'' =>
rw [h'] at h
cases d'' <;> contradiction
```
With that helper, the proof is quite short:
```lean
instance : Std.PRange.LawfulUpwardEnumerable Day where
ne_of_lt d1 d2 h := by grind [Std.PRange.UpwardEnumerable.LT]
succMany?_zero := Day.succMany?_zero
succMany?_add_one := Day.succMany?_add_one
```
:::
:::paragraph
Proving the three kinds of enumerable ranges to be finite makes it possible to enumerate ranges of days:
```lean
instance : Std.Rxo.IsAlwaysFinite Day where
finite init hi :=
⟨7, by cases init <;> simp [Std.PRange.succ?, Day.succ?]⟩
instance : Std.Rxc.IsAlwaysFinite Day where
finite init hi :=
⟨7, by cases init <;> simp [Std.PRange.succ?, Day.succ?]⟩
instance : Std.Rxi.IsAlwaysFinite Day where
finite init := ⟨7, by cases init <;> rfl⟩
```
```lean (name := allWeekdays)
def allWeekdays : List Day := (Day.mo...Day.sa).toList
#eval allWeekdays
```
```leanOutput allWeekdays
[Day.mo, Day.tu, Day.we, Day.th, Day.fr]
```
Adding a {name}`Std.PRange.Least?` instance allows enumeration of left-unbounded ranges:
```lean (name := allWeekdays')
instance : Std.PRange.Least? Day where
least? := some .mo
def allWeekdays' : List Day := (*...Day.sa).toList
#eval allWeekdays'
```
```leanOutput allWeekdays'
[Day.mo, Day.tu, Day.we, Day.th, Day.fr]
```
It's also possible to create an iterator that can be enumerated, but it can't yet be used with {keywordOf Lean.Parser.Term.doFor}`for`:
```lean (name := iterEnum)
#eval (Day.we...Day.fr).iter.toList
```
```leanOutput iterEnum
[Day.we, Day.th]
```
```lean (name := iterForNo) +error
#eval show IO Unit from do
for d in (Day.mo...Day.th).iter do
IO.println s!"It's {repr d}."
```
```leanOutput iterForNo
failed to synthesize instance for 'for_in%' notation
ForIn (EIO IO.Error) (Std.Iter Day) ?m.12
```
:::
:::paragraph
The last step to enable iteration, thus making ranges of days fully-featured, is to prove that the less-than and less-than-or-equal-to relations on {name}`Day` correspond to the notions of inequality that are derived from iterating the successor function.
This is captured in the classes {name}`Std.PRange.LawfulUpwardEnumerableLT` and {name}`Std.PRange.LawfulUpwardEnumerableLE`, which require that the two notions are logically equivalent:
```lean
instance : Std.PRange.LawfulUpwardEnumerableLT Day where
lt_iff d1 d2 := by
constructor
. intro lt
simp only [Std.PRange.UpwardEnumerable.LT, Day.succMany?_add_one]
exists d2.toNat - d1.toNat.succ
cases d1 <;> cases d2 <;>
simp_all [Day.toNat, Std.PRange.succ?, Day.succ?] <;>
contradiction
. intro ⟨steps, eq⟩
have := Day.succMany?_steps eq
cases d1 <;> cases d2 <;>
simp only [if_false_right] at this <;>
cases this <;> first | decide | contradiction
instance : Std.PRange.LawfulUpwardEnumerableLE Day where
le_iff d1 d2 := by
constructor
. intro le
simp only [Std.PRange.UpwardEnumerable.LE]
exists d2.toNat - d1.toNat
cases d1 <;> cases d2 <;>
simp_all [Day.toNat, Std.PRange.succ?, Day.succ?] <;>
contradiction
. intro ⟨steps, eq⟩
have := Day.succMany?_steps eq
cases d1 <;> cases d2 <;>
simp only [if_false_right] at this <;>
cases this <;> grind
```
:::
:::paragraph
It is now possible to iterate over ranges of days:
```lean (name := done)
#eval show IO Unit from do
for x in (Day.mo...Day.th).iter do
IO.println s!"It's {repr x}"
```
```leanOutput done
It's Day.mo
It's Day.tu
It's Day.we
```
:::
::::
# Ranges and Slices
Range syntax can be used with data structures that support slicing to select a slice of the structure.
:::example "Slicing Lists"
Lists may be sliced with any of the interval types:
```lean
def groceries :=
["apples", "bananas", "coffee", "dates", "endive", "fennel"]
```
```lean (name := rco)
#eval groceries[1...4] |>.toList
```
```leanOutput rco
["bananas", "coffee", "dates"]
```
```lean (name := rcc)
#eval groceries[1...=4] |>.toList
```
```leanOutput rcc
["bananas", "coffee", "dates", "endive"]
```
```lean (name := rci)
#eval groceries[1...*] |>.toList
```
```leanOutput rci
["bananas", "coffee", "dates", "endive", "fennel"]
```
```lean (name := roo)
#eval groceries[1<...4] |>.toList
```
```leanOutput roo
["coffee", "dates"]
```
```lean (name := roc)
#eval groceries[1<...=4] |>.toList
```
```leanOutput roc
["coffee", "dates", "endive"]
```
```lean (name := ric)
#eval groceries[*...=4] |>.toList
```
```leanOutput ric
["apples", "bananas", "coffee", "dates", "endive"]
```
```lean (name := rio)
#eval groceries[*...4] |>.toList
```
```leanOutput rio
["apples", "bananas", "coffee", "dates"]
```
```lean (name := rii)
#eval groceries[*...*] |>.toList
```
```leanOutput rii
["apples", "bananas", "coffee", "dates", "endive", "fennel"]
```
:::
:::example "Custom Slices"
A {name}`Triple` contains three values of the same type:
```lean
structure Triple (α : Type u) where
fst : α
snd : α
thd : α
deriving Repr
```
Positions in a triple may be any of the fields, or just after {name Triple.thd}`thd`:
```lean
inductive TriplePos where
| fst | snd | thd | done
deriving Repr
```
A slice of a triple consists of a triple, a starting position, and a stopping position.
The starting position is inclusive, and the stopping position exclusive:
```lean
structure TripleSlice (α : Type u) where
triple : Triple α
start : TriplePos
stop : TriplePos
deriving Repr
```
Ranges of {name}`TriplePos` can be used to select a slice from a triple by implementing instances of each supported range type's {name Std.Rco.Sliceable}`Sliceable` class.
For example, {name}`Std.Rco.Sliceable` allows left-closed, right-open ranges to be used to slice {name}`Triple`s:
```lean
instance : Std.Rco.Sliceable (Triple α) TriplePos (TripleSlice α) where
mkSlice triple range :=
{ triple, start := range.lower, stop := range.upper }
```
```lean (name := slice)
def abc : Triple Char := ⟨'a', 'b', 'c'⟩
open TriplePos in
#eval abc[snd...thd]
```
```leanOutput slice
{ triple := { fst := 'a', snd := 'b', thd := 'c' }, start := TriplePos.snd, stop := TriplePos.thd }
```
Infinite ranges have only a lower bound:
```lean (name := slice2)
instance : Std.Rci.Sliceable (Triple α) TriplePos (TripleSlice α) where
mkSlice triple range :=
{ triple, start := range.lower, stop := .done }
open TriplePos in
#eval abc[snd...*]
```
```leanOutput slice2
{ triple := { fst := 'a', snd := 'b', thd := 'c' }, start := TriplePos.snd, stop := TriplePos.done }
```
:::
{docstring Std.Rco.Sliceable +allowMissing}
{docstring Std.Rcc.Sliceable +allowMissing}
{docstring Std.Rci.Sliceable +allowMissing}
{docstring Std.Roo.Sliceable +allowMissing}
{docstring Std.Roc.Sliceable +allowMissing}
{docstring Std.Roi.Sliceable +allowMissing}
{docstring Std.Rio.Sliceable +allowMissing}
{docstring Std.Ric.Sliceable +allowMissing}
{docstring Std.Rii.Sliceable +allowMissing} |
reference-manual/Manual/BasicTypes/Char.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.Array.Subarray
import Manual.BasicTypes.Array.FFI
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Characters" =>
%%%
tag := "Char"
%%%
Characters are represented by the type {name}`Char`, which may be any Unicode [scalar value](http://www.unicode.org/glossary/#unicode_scalar_value).
While {ref "String"}[strings] are UTF-8-encoded arrays of bytes, characters are represented by full 32-bit values.
Lean provides special {ref "char-syntax"}[syntax] for character literals.
# Logical Model
%%%
tag := "char-model"
%%%
From the perspective of Lean's logic, characters consist of a 32-bit unsigned integer paired with a proof that it is a valid Unicode scalar value.
{docstring Char}
# Run-Time Representation
%%%
tag := "char-runtime"
%%%
As a {ref "inductive-types-trivial-wrappers"}[trivial wrapper], characters are represented identically to {lean}`UInt32`.
In particular, characters are represented as 32-bit immediate values in monomorphic contexts.
In other words, a field of a constructor or structure of type {lean}`Char` does not require indirection to access.
In polymorphic contexts, characters are {tech}[boxed].
# Syntax
%%%
tag := "char-syntax"
%%%
Character literals consist of a single character or an escape sequence enclosed in single quotes (`'`, Unicode `'APOSTROPHE' (U+0027)`).
Between these single quotes, the character literal may contain character other that `'`, including newlines, which are included literally (with the caveat that all newlines in a Lean source file are interpreted as `'\n'`, regardless of file encoding and platform).
Special characters may be escaped with a backslash, so `'\''` is a character literal that contains a single quote.
The following forms of escape sequences are accepted:
: `\r`, `\n`, `\t`, `\\`, `\"`, `\'`
These escape sequences have the usual meaning, mapping to `CR`, `LF`, tab, backslash, double quote, and single quote, respectively.
: `\xNN`
When `NN` is a sequence of two hexadecimal digits, this escape denotes the character whose Unicode code point is indicated by the two-digit hexadecimal code.
: `\uNNNN`
When `NN` is a sequence of two hexadecimal digits, this escape denotes the character whose Unicode code point is indicated by the four-digit hexadecimal code.
# API Reference
%%%
tag := "char-api"
%%%
## Conversions
{docstring Char.ofNat}
{docstring Char.toNat}
{docstring Char.isValidCharNat}
{docstring Char.ofUInt8}
{docstring Char.toUInt8}
There are two ways to convert a character to a string.
{name}`Char.toString` converts a character to a singleton string that consists of only that character, while {name}`Char.quote` converts the character to a string representation of the corresponding character literal.
{docstring Char.toString}
{docstring Char.quote}
:::example "From Characters to Strings"
{name}`Char.toString` produces a string that contains only the character in question:
```lean (name := e)
#eval 'e'.toString
```
```leanOutput e
"e"
```
```lean (name := e')
#eval '\x65'.toString
```
```leanOutput e'
"e"
```
```lean (name := n')
#eval '"'.toString
```
```leanOutput n'
"\""
```
{name}`Char.quote` produces a string that contains a character literal, suitably escaped:
```lean (name := eq)
#eval 'e'.quote
```
```leanOutput eq
"'e'"
```
```lean (name := eq')
#eval '\x65'.quote
```
```leanOutput eq'
"'e'"
```
```lean (name := nq')
#eval '"'.quote
```
```leanOutput nq'
"'\\\"'"
```
:::
## Character Classes
%%%
tag := "char-api-classes"
%%%
{docstring Char.isAlpha}
{docstring Char.isAlphanum}
{docstring Char.isDigit}
{docstring Char.isLower}
{docstring Char.isUpper}
{docstring Char.isWhitespace}
## Case Conversion
{docstring Char.toUpper}
{docstring Char.toLower}
## Comparisons
{docstring Char.le}
{docstring Char.lt}
## Unicode
{docstring Char.utf8Size}
{docstring Char.utf16Size} |
reference-manual/Manual/BasicTypes/Array.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.Array.Subarray
import Manual.BasicTypes.Array.FFI
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option maxHeartbeats 500000
example := Char
#doc (Manual) "Arrays" =>
%%%
tag := "Array"
%%%
The {lean}`Array` type represents sequences of elements, addressable by their position in the sequence.
Arrays are specially supported by Lean:
* They have a _logical model_ that specifies their behavior in terms of lists of elements, which specifies the meaning of each operation on arrays.
* They have an optimized run-time representation in compiled code as {tech}[dynamic arrays], and the Lean runtime specially optimizes array operations.
* There is {ref "array-syntax"}[array literal syntax] for writing arrays.
Arrays can be vastly more efficient than lists or other sequences in compiled code.
In part, this is because they offer good locality: because all the elements of the sequence are next to each other in memory, the processor's caches can be used efficiently.
Even more importantly, if there is only a single reference to an array, operations that might otherwise copy or allocate a data structure can be implemented via mutation.
Lean code that uses an array in such a way that there's only ever one unique reference (that is, uses it {deftech}_linearly_) avoids the performance overhead of persistent data structures while still being as convenient to write, read, and prove things about as ordinary pure functional programs.
# Logical Model
{docstring Array}
The logical model of arrays is a structure that contains a single field, which is a list of elements.
This is convenient when specifying and proving properties of array-processing functions at a low level.
# Run-Time Representation
%%%
tag := "array-runtime"
%%%
Lean's arrays are {deftech}_dynamic arrays_, which are blocks of continuous memory with a defined capacity, not all of which is typically in use.
As long as the number of elements in the array is less than the capacity, new items can be added to the end without reallocating or moving the data.
Adding items to an array that has no extra space results in a reallocation that doubles the capacity.
The amortized overhead scales linearly with the size of the array.
The values in the array are represented as described in the {ref "inductive-types-ffi"}[section on the foreign function interface].
:::figure "Memory layout of arrays" (tag := "arrayffi")

:::
After the object header, an array contains:
: size
The number of objects currently stored in the array
: capacity
The number of objects that fit in the memory allocated for the array
: data
The values in the array
Many array functions in the Lean runtime check whether they have exclusive access to their argument by consulting the reference count in the object header.
If they do, and the array's capacity is sufficient, then the existing array can be mutated rather than allocating fresh memory.
Otherwise, a new array must be allocated.
## Performance Notes
%%%
tag := "array-performance"
%%%
Despite the fact that they appear to be an ordinary constructor and projection, {name}`Array.mk` and {name}`Array.toList` take *time linear in the size of the array* in compiled code.
This is because converting between linked lists and packed arrays must necessarily visit each element.
Mutable arrays can be used to write very efficient code.
However, they are a poor persistent data structure.
Updating a shared array rules out mutation, and requires time linear in the size of the array.
When using arrays in performance-critical code, it's important to ensure that they are used {tech}[linearly].
# Syntax
%%%
tag := "array-syntax"
%%%
Array literals allow arrays to be written directly in code.
They may be used in expression or pattern contexts.
:::syntax term (title := "Array Literals")
Array literals begin with `#[` and contain a comma-separated sequence of terms, terminating with `]`.
```grammar
#[$t,*]
```
:::
::::keepEnv
:::example "Array Literals"
Array literals may be used as expressions or as patterns.
```lean
def oneTwoThree : Array Nat := #[1, 2, 3]
#eval
match oneTwoThree with
| #[x, y, z] => some ((x + z) / y)
| _ => none
```
:::
::::
Additionally, {ref "subarray"}[sub-arrays] may be extracted using the following syntax:
:::syntax term (title := "Sub-Arrays")
A start index followed by a colon constructs a sub-array that contains the values from the start index onwards (inclusive):
```grammar
$t[$t:term :]
```
Providing start and end indices constructs a sub-array that contains the values from the start index (inclusive) to the end index (exclusive):
```grammar
$t[$t:term : $_:term]
```
:::
::::keepEnv
:::example "Sub-Array Syntax"
The array {lean}`ten` contains the first ten natural numbers.
```lean
def ten : Array Nat :=
.range 10
```
A sub-array that represents the second half of {lean}`ten` can be constructed using the sub-array syntax:
```lean (name := subarr1)
#eval ten[5:]
```
```leanOutput subarr1
#[5, 6, 7, 8, 9].toSubarray
```
Similarly, sub-array that contains two through five can be constructed by providing a stopping point:
```lean (name := subarr2)
#eval ten[2:6]
```
```leanOutput subarr2
#[2, 3, 4, 5].toSubarray
```
Because sub-arrays merely store the start and end indices of interest in the underlying array, the array itself can be recovered:
```lean (name := subarr3)
#eval ten[2:6].array == ten
```
```leanOutput subarr3
true
```
:::
::::
# API Reference
%%%
tag := "array-api"
%%%
## Constructing Arrays
{docstring Array.empty}
{docstring Array.emptyWithCapacity}
{docstring Array.singleton}
{docstring Array.range}
{docstring Array.range'}
{docstring Array.finRange}
{docstring Array.ofFn}
{docstring Array.replicate}
{docstring Array.append}
{docstring Array.appendList}
{docstring Array.leftpad}
{docstring Array.rightpad}
## Size
{docstring Array.size}
{docstring Array.usize}
{docstring Array.isEmpty}
## Lookups
{docstring Array.extract}
{docstring Array.getD}
{docstring Array.uget}
{docstring Array.back}
{docstring Array.back?}
{docstring Array.back!}
{docstring Array.getMax?}
## Queries
{docstring Array.count}
{docstring Array.countP}
{docstring Array.idxOf}
{docstring Array.idxOf?}
{docstring Array.finIdxOf?}
## Conversions
{docstring Array.toList}
{docstring Array.toListRev}
{docstring Array.toListAppend}
{docstring Array.toVector}
{docstring Array.toSubarray}
{docstring Array.ofSubarray}
## Modification
{docstring Array.push}
{docstring Array.pop}
{docstring Array.popWhile}
{docstring Array.erase}
{docstring Array.eraseP}
{docstring Array.eraseIdx}
{docstring Array.eraseIdx!}
{docstring Array.eraseIdxIfInBounds}
{docstring Array.eraseReps}
{docstring Array.swap}
{docstring Array.swapIfInBounds}
{docstring Array.swapAt}
{docstring Array.swapAt!}
{docstring Array.replace}
{docstring Array.set}
{docstring Array.set!}
{docstring Array.setIfInBounds}
{docstring Array.uset}
{docstring Array.modify}
{docstring Array.modifyM}
{docstring Array.modifyOp}
{docstring Array.insertIdx}
{docstring Array.insertIdx!}
{docstring Array.insertIdxIfInBounds}
{docstring Array.reverse}
{docstring Array.take}
{docstring Array.takeWhile}
{docstring Array.drop}
{docstring Array.shrink}
{docstring Array.flatten}
{docstring Array.getEvenElems}
## Sorted Arrays
{docstring Array.qsort}
{docstring Array.qsortOrd}
{docstring Array.insertionSort}
{docstring Array.binInsert}
{docstring Array.binInsertM}
{docstring Array.binSearch}
{docstring Array.binSearchContains}
## Iteration
{docstring Array.iter}
{docstring Array.iterFromIdx}
{docstring Array.iterM}
{docstring Array.iterFromIdxM}
{docstring Array.foldr}
{docstring Array.foldrM}
{docstring Array.foldl}
{docstring Array.foldlM}
{docstring Array.forM}
{docstring Array.forRevM}
{docstring Array.firstM}
{docstring Array.sum}
## Transformation
{docstring Array.map}
{docstring Array.mapMono}
{docstring Array.mapM}
{docstring Array.mapM'}
{docstring Array.mapMonoM}
{docstring Array.mapIdx}
{docstring Array.mapIdxM}
{docstring Array.mapFinIdx}
{docstring Array.mapFinIdxM}
{docstring Array.flatMap}
{docstring Array.flatMapM}
{docstring Array.zip}
{docstring Array.zipWith}
{docstring Array.zipWithAll}
{docstring Array.zipIdx}
{docstring Array.unzip}
## Filtering
{docstring Array.filter}
{docstring Array.filterM}
{docstring Array.filterRevM}
{docstring Array.filterMap}
{docstring Array.filterMapM}
{docstring Array.filterSepElems}
{docstring Array.filterSepElemsM}
## Partitioning
{docstring Array.partition}
{docstring Array.groupByKey}
## Element Predicates
{docstring Array.contains}
{docstring Array.elem}
{docstring Array.find?}
{docstring Array.findRev?}
{docstring Array.findIdx}
{docstring Array.findIdx?}
{docstring Array.findIdxM?}
{docstring Array.findFinIdx?}
{docstring Array.findM?}
{docstring Array.findRevM?}
{docstring Array.findSome?}
{docstring Array.findSome!}
{docstring Array.findSomeM?}
{docstring Array.findSomeRev?}
{docstring Array.findSomeRevM?}
{docstring Array.all}
{docstring Array.allM}
{docstring Array.any}
{docstring Array.anyM}
{docstring Array.allDiff}
{docstring Array.isEqv}
## Comparisons
{docstring Array.isPrefixOf}
{docstring Array.lex}
## Termination Helpers
{docstring Array.attach}
{docstring Array.attachWith}
{docstring Array.unattach}
{docstring Array.pmap}
{include 1 Manual.BasicTypes.Array.Subarray}
{include 0 Manual.BasicTypes.Array.FFI} |
reference-manual/Manual/BasicTypes/UInt.lean | import VersoManual
import Manual.Meta
import Manual.BasicTypes.UInt.Comparisons
import Manual.BasicTypes.UInt.Arith
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
#doc (Manual) "Fixed-Precision Integers" =>
%%%
tag := "fixed-ints"
%%%
Lean's standard library includes the usual assortment of fixed-width integer types.
From the perspective of formalization and proofs, these types are wrappers around bitvectors of the appropriate size; the wrappers ensure that the correct implementations of e.g. arithmetic operations are applied.
In compiled code, they are represented efficiently: the compiler has special support for them, as it does for other fundamental types.
# Logical Model
Fixed-width integers may be unsigned or signed.
Furthermore, they are available in five sizes: 8, 16, 32, and 64 bits, along with the current architecture's word size.
In their logical models, the unsigned integers are structures that wrap a {name}`BitVec` of the appropriate width.
Signed integers wrap the corresponding unsigned integers, and use a twos-complement representation.
## Unsigned
{docstring USize}
{docstring UInt8}
{docstring UInt16}
{docstring UInt32}
{docstring UInt64}
## Signed
{docstring ISize}
{docstring Int8}
{docstring Int16}
{docstring Int32}
{docstring Int64}
# Run-Time Representation
%%%
tag := "fixed-int-runtime"
%%%
In compiled code in contexts that require {tech}[boxed] representations, fixed-width integer types that fit in one less bit than the platform's pointer size are always represented without additional allocations or indirections.
This always includes {lean}`Int8`, {lean}`UInt8`, {lean}`Int16`, and {lean}`UInt16`.
On 64-bit architectures, {lean}`Int32` and {lean}`UInt32` are also represented without pointers.
On 32-bit architectures, {lean}`Int32` and {lean}`UInt32` require a pointer to an object on the heap.
{lean}`ISize`, {lean}`USize`, {lean}`Int64` and {lean}`UInt64` may require pointers on all architectures.
Even though some fixed-with integer types require boxing in general, the compiler is able to represent them without boxing or pointer indirections in code paths that use only a specific fixed-width type rather than being polymorphic, potentially after a specialization pass.
This applies in most practical situations where these types are used: their values are represented using the corresponding unsigned fixed-width C type when a constructor parameter, function parameter, function return value, or intermediate result is known to be a fixed-width integer type.
The Lean run-time system includes primitives for storing fixed-width integers in constructors of {tech}[inductive types], and the primitive operations are defined on the corresponding C types, so boxing tends to happen at the “edges” of integer calculations rather than for each intermediate result.
In contexts where other types might occur, such as the contents of polymorphic containers like {name}`Array`, these types are boxed, even if an array is statically known to contain only a single fixed-width integer type.{margin}[The monomorphic array type {lean}`ByteArray` avoids boxing for arrays of {lean}`UInt8`.]
Lean does not specialize the representation of inductive types or arrays.
Inspecting a function's type in Lean is not sufficient to determine how fixed-width integer values will be represented, because boxed values are not eagerly unboxed—a function that projects an {name}`Int64` from an array returns a boxed integer value.
# Syntax
All the fixed-width integer types have {name}`OfNat` instances, which allow numerals to be used as literals, both in expression and in pattern contexts.
The signed types additionally have {lean}`Neg` instances, allowing negation to be applied.
:::example "Fixed-Width Literals"
Lean allows both decimal and hexadecimal literals to be used for types with {name}`OfNat` instances.
In this example, literal notation is used to define masks.
```lean
structure Permissions where
readable : Bool
writable : Bool
executable : Bool
def Permissions.encode (p : Permissions) : UInt8 :=
let r := if p.readable then 0x01 else 0
let w := if p.writable then 0x02 else 0
let x := if p.executable then 0x04 else 0
r ||| w ||| x
def Permissions.decode (i : UInt8) : Permissions :=
⟨i &&& 0x01 ≠ 0, i &&& 0x02 ≠ 0, i &&& 0x04 ≠ 0⟩
```
```lean -show
-- Check the above
theorem Permissions.decode_encode (p : Permissions) : p = .decode (p.encode) := by
let ⟨r, w, x⟩ := p
cases r <;> cases w <;> cases x <;>
simp +decide [decode]
```
:::
Literals that overflow their types' precision are interpreted modulus the precision.
Signed types, are interpreted according to the underlying twos-complement representation.
:::example "Overflowing Fixed-Width Literals"
The following statements are all true:
```lean
example : (255 : UInt8) = 255 := by rfl
example : (256 : UInt8) = 0 := by rfl
example : (257 : UInt8) = 1 := by rfl
example : (0x7f : Int8) = 127 := by rfl
example : (0x8f : Int8) = -113 := by rfl
example : (0xff : Int8) = -1 := by rfl
```
:::
# API Reference
## Sizes
Each fixed-width integer has a _size_, which is the number of distinct values that can be represented by the type.
This is not equivalent to C's `sizeof` operator, which instead determines how many bytes the type occupies.
{docstring USize.size}
{docstring ISize.size}
{docstring UInt8.size}
{docstring Int8.size}
{docstring UInt16.size}
{docstring Int16.size}
{docstring UInt32.size}
{docstring Int32.size}
{docstring UInt64.size}
{docstring Int64.size}
## Ranges
{docstring ISize.minValue}
{docstring ISize.maxValue}
{docstring Int8.minValue}
{docstring Int8.maxValue}
{docstring Int16.minValue}
{docstring Int16.maxValue}
{docstring Int32.minValue}
{docstring Int32.maxValue}
{docstring Int64.minValue}
{docstring Int64.maxValue}
## Conversions
### To and From `Int`
{docstring ISize.toInt}
{docstring Int8.toInt}
{docstring Int16.toInt}
{docstring Int32.toInt}
{docstring Int64.toInt}
{docstring ISize.ofInt}
{docstring Int8.ofInt}
{docstring Int16.ofInt}
{docstring Int32.ofInt}
{docstring Int64.ofInt}
{docstring ISize.ofIntTruncate}
{docstring Int8.ofIntTruncate}
{docstring Int16.ofIntTruncate}
{docstring Int32.ofIntTruncate}
{docstring Int64.ofIntTruncate}
{docstring ISize.ofIntLE}
{docstring Int8.ofIntLE}
{docstring Int16.ofIntLE}
{docstring Int32.ofIntLE}
{docstring Int64.ofIntLE}
### To and From `Nat`
{docstring USize.ofNat}
{docstring ISize.ofNat}
{docstring UInt8.ofNat}
{docstring Int8.ofNat}
{docstring UInt16.ofNat}
{docstring Int16.ofNat}
{docstring UInt32.ofNat}
{docstring Int32.ofNat}
{docstring UInt64.ofNat}
{docstring Int64.ofNat}
{docstring USize.ofNat32}
{docstring USize.ofNatLT}
{docstring UInt8.ofNatLT}
{docstring UInt16.ofNatLT}
{docstring UInt32.ofNatLT}
{docstring UInt64.ofNatLT}
{docstring USize.ofNatTruncate}
{docstring UInt8.ofNatTruncate}
{docstring UInt16.ofNatTruncate}
{docstring UInt32.ofNatTruncate}
{docstring UInt64.ofNatTruncate}
{docstring USize.toNat}
{docstring ISize.toNatClampNeg}
{docstring UInt8.toNat}
{docstring Int8.toNatClampNeg}
{docstring UInt16.toNat}
{docstring Int16.toNatClampNeg}
{docstring UInt32.toNat}
{docstring Int32.toNatClampNeg}
{docstring UInt64.toNat}
{docstring Int64.toNatClampNeg}
### To Other Fixed-Width Integers
{docstring USize.toUInt8}
{docstring USize.toUInt16}
{docstring USize.toUInt32}
{docstring USize.toUInt64}
{docstring USize.toISize}
{docstring UInt8.toInt8}
{docstring UInt8.toUInt16}
{docstring UInt8.toUInt32}
{docstring UInt8.toUInt64}
{docstring UInt8.toUSize}
{docstring UInt16.toUInt8}
{docstring UInt16.toInt16}
{docstring UInt16.toUInt32}
{docstring UInt16.toUInt64}
{docstring UInt16.toUSize}
{docstring UInt32.toUInt8}
{docstring UInt32.toUInt16}
{docstring UInt32.toInt32}
{docstring UInt32.toUInt64}
{docstring UInt32.toUSize}
{docstring UInt64.toUInt8}
{docstring UInt64.toUInt16}
{docstring UInt64.toUInt32}
{docstring UInt64.toInt64}
{docstring UInt64.toUSize}
{docstring ISize.toInt8}
{docstring ISize.toInt16}
{docstring ISize.toInt32}
{docstring ISize.toInt64}
{docstring Int8.toInt16}
{docstring Int8.toInt32}
{docstring Int8.toInt64}
{docstring Int8.toISize}
{docstring Int16.toInt8}
{docstring Int16.toInt32}
{docstring Int16.toInt64}
{docstring Int16.toISize}
{docstring Int32.toInt8}
{docstring Int32.toInt16}
{docstring Int32.toInt64}
{docstring Int32.toISize}
{docstring Int64.toInt8}
{docstring Int64.toInt16}
{docstring Int64.toInt32}
{docstring Int64.toISize}
### To Floating-Point Numbers
{docstring ISize.toFloat}
{docstring ISize.toFloat32}
{docstring Int8.toFloat}
{docstring Int8.toFloat32}
{docstring Int16.toFloat}
{docstring Int16.toFloat32}
{docstring Int32.toFloat}
{docstring Int32.toFloat32}
{docstring Int64.toFloat}
{docstring Int64.toFloat32}
{docstring USize.toFloat}
{docstring USize.toFloat32}
{docstring UInt8.toFloat}
{docstring UInt8.toFloat32}
{docstring UInt16.toFloat}
{docstring UInt16.toFloat32}
{docstring UInt32.toFloat}
{docstring UInt32.toFloat32}
{docstring UInt64.toFloat}
{docstring UInt64.toFloat32}
### To and From Bitvectors
{docstring ISize.toBitVec}
{docstring ISize.ofBitVec}
{docstring Int8.toBitVec}
{docstring Int8.ofBitVec}
{docstring Int16.toBitVec}
{docstring Int16.ofBitVec}
{docstring Int32.toBitVec}
{docstring Int32.ofBitVec}
{docstring Int64.toBitVec}
{docstring Int64.ofBitVec}
### To and From Finite Numbers
{docstring USize.toFin}
{docstring UInt8.toFin}
{docstring UInt16.toFin}
{docstring UInt32.toFin}
{docstring UInt64.toFin}
{docstring USize.ofFin}
{docstring UInt8.ofFin}
{docstring UInt16.ofFin}
{docstring UInt32.ofFin}
{docstring UInt64.ofFin}
{docstring USize.repr}
### To Characters
The {name}`Char` type is a wrapper around {name}`UInt32` that requires a proof that the wrapped integer represents a Unicode code point.
This predicate is part of the {name}`UInt32` API.
{docstring UInt32.isValidChar}
{include 2 Manual.BasicTypes.UInt.Comparisons}
{include 2 Manual.BasicTypes.UInt.Arith}
## Bitwise Operations
Typically, bitwise operations on fixed-width integers should be accessed using Lean's overloaded operators, particularly their instances of {name}`ShiftLeft`, {name}`ShiftRight`, {name}`AndOp`, {name}`OrOp`, and {name}`XorOp`.
```lean -show
-- Check that all those instances really exist
open Lean Elab Command in
#eval show CommandElabM Unit from do
let types := [`ISize, `Int8, `Int16, `Int32, `Int64, `USize, `UInt8, `UInt16, `UInt32, `UInt64]
let classes := [`ShiftLeft, `ShiftRight, `AndOp, `OrOp, `XorOp]
for t in types do
for c in classes do
elabCommand <| ← `(example : $(mkIdent c):ident $(mkIdent t) := inferInstance)
```
{docstring USize.land}
{docstring ISize.land}
{docstring UInt8.land}
{docstring Int8.land}
{docstring UInt16.land}
{docstring Int16.land}
{docstring UInt32.land}
{docstring Int32.land}
{docstring UInt64.land}
{docstring Int64.land}
{docstring USize.lor}
{docstring ISize.lor}
{docstring UInt8.lor}
{docstring Int8.lor}
{docstring UInt16.lor}
{docstring Int16.lor}
{docstring UInt32.lor}
{docstring Int32.lor}
{docstring UInt64.lor}
{docstring Int64.lor}
{docstring USize.xor}
{docstring ISize.xor}
{docstring UInt8.xor}
{docstring Int8.xor}
{docstring UInt16.xor}
{docstring Int16.xor}
{docstring UInt32.xor}
{docstring Int32.xor}
{docstring UInt64.xor}
{docstring Int64.xor}
{docstring USize.complement}
{docstring ISize.complement}
{docstring UInt8.complement}
{docstring Int8.complement}
{docstring UInt16.complement}
{docstring Int16.complement}
{docstring UInt32.complement}
{docstring Int32.complement}
{docstring UInt64.complement}
{docstring Int64.complement}
{docstring USize.shiftLeft}
{docstring ISize.shiftLeft}
{docstring UInt8.shiftLeft}
{docstring Int8.shiftLeft}
{docstring UInt16.shiftLeft}
{docstring Int16.shiftLeft}
{docstring UInt32.shiftLeft}
{docstring Int32.shiftLeft}
{docstring UInt64.shiftLeft}
{docstring Int64.shiftLeft}
{docstring USize.shiftRight}
{docstring ISize.shiftRight}
{docstring UInt8.shiftRight}
{docstring Int8.shiftRight}
{docstring UInt16.shiftRight}
{docstring Int16.shiftRight}
{docstring UInt32.shiftRight}
{docstring Int32.shiftRight}
{docstring UInt64.shiftRight}
{docstring Int64.shiftRight} |
reference-manual/Manual/BasicTypes/Maps/TreeMap.lean | import VersoManual
import Manual.Meta
import Std.Data.TreeMap
import Std.Data.TreeMap.Raw
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option maxHeartbeats 250000
#doc (Manual) "Tree-Based Maps" =>
%%%
tag := "TreeMap"
%%%
The declarations in this section should be imported using `import Std.TreeMap`.
{docstring Std.TreeMap +hideFields +hideStructureConstructor}
# Creation
{docstring Std.TreeMap.empty}
# Properties
{docstring Std.TreeMap.size}
{docstring Std.TreeMap.isEmpty}
# Queries
{docstring Std.TreeMap.contains}
{docstring Std.TreeMap.get}
{docstring Std.TreeMap.get!}
{docstring Std.TreeMap.get?}
{docstring Std.TreeMap.getD}
{docstring Std.TreeMap.getKey}
{docstring Std.TreeMap.getKey!}
{docstring Std.TreeMap.getKey?}
{docstring Std.TreeMap.getKeyD}
{docstring Std.TreeMap.keys}
{docstring Std.TreeMap.keysArray}
{docstring Std.TreeMap.values}
{docstring Std.TreeMap.valuesArray}
## Ordering-Based Queries
{docstring Std.TreeMap.entryAtIdx}
{docstring Std.TreeMap.entryAtIdx!}
{docstring Std.TreeMap.entryAtIdx?}
{docstring Std.TreeMap.entryAtIdxD}
{docstring Std.TreeMap.getEntryGE}
{docstring Std.TreeMap.getEntryGE!}
{docstring Std.TreeMap.getEntryGE?}
{docstring Std.TreeMap.getEntryGED}
{docstring Std.TreeMap.getEntryGT}
{docstring Std.TreeMap.getEntryGT!}
{docstring Std.TreeMap.getEntryGT?}
{docstring Std.TreeMap.getEntryGTD}
{docstring Std.TreeMap.getEntryLE}
{docstring Std.TreeMap.getEntryLE!}
{docstring Std.TreeMap.getEntryLE?}
{docstring Std.TreeMap.getEntryLED}
{docstring Std.TreeMap.getEntryLT}
{docstring Std.TreeMap.getEntryLT!}
{docstring Std.TreeMap.getEntryLT?}
{docstring Std.TreeMap.getEntryLTD}
{docstring Std.TreeMap.getKeyGE}
{docstring Std.TreeMap.getKeyGE!}
{docstring Std.TreeMap.getKeyGE?}
{docstring Std.TreeMap.getKeyGED}
{docstring Std.TreeMap.getKeyGT}
{docstring Std.TreeMap.getKeyGT!}
{docstring Std.TreeMap.getKeyGT?}
{docstring Std.TreeMap.getKeyGTD}
{docstring Std.TreeMap.getKeyLE}
{docstring Std.TreeMap.getKeyLE!}
{docstring Std.TreeMap.getKeyLE?}
{docstring Std.TreeMap.getKeyLED}
{docstring Std.TreeMap.getKeyLT}
{docstring Std.TreeMap.getKeyLT!}
{docstring Std.TreeMap.getKeyLT?}
{docstring Std.TreeMap.getKeyLTD}
{docstring Std.TreeMap.keyAtIdx}
{docstring Std.TreeMap.keyAtIdx!}
{docstring Std.TreeMap.keyAtIdx?}
{docstring Std.TreeMap.keyAtIdxD}
{docstring Std.TreeMap.minEntry}
{docstring Std.TreeMap.minEntry!}
{docstring Std.TreeMap.minEntry?}
{docstring Std.TreeMap.minEntryD}
{docstring Std.TreeMap.minKey}
{docstring Std.TreeMap.minKey!}
{docstring Std.TreeMap.minKey?}
{docstring Std.TreeMap.minKeyD}
{docstring Std.TreeMap.maxEntry}
{docstring Std.TreeMap.maxEntry!}
{docstring Std.TreeMap.maxEntry?}
{docstring Std.TreeMap.maxEntryD}
{docstring Std.TreeMap.maxKey}
{docstring Std.TreeMap.maxKey!}
{docstring Std.TreeMap.maxKey?}
{docstring Std.TreeMap.maxKeyD}
# Modification
{docstring Std.TreeMap.alter}
{docstring Std.TreeMap.modify}
{docstring Std.TreeMap.containsThenInsert}
{docstring Std.TreeMap.containsThenInsertIfNew}
{docstring Std.TreeMap.erase}
{docstring Std.TreeMap.eraseMany}
{docstring Std.TreeMap.filter}
{docstring Std.TreeMap.filterMap}
{docstring Std.TreeMap.insert}
{docstring Std.TreeMap.insertIfNew}
{docstring Std.TreeMap.getThenInsertIfNew?}
{docstring Std.TreeMap.insertMany}
{docstring Std.TreeMap.insertManyIfNewUnit}
{docstring Std.TreeMap.mergeWith}
{docstring Std.TreeMap.partition}
# Iteration
{docstring Std.TreeMap.iter}
{docstring Std.TreeMap.keysIter}
{docstring Std.TreeMap.valuesIter}
{docstring Std.TreeMap.map}
{docstring Std.TreeMap.all}
{docstring Std.TreeMap.any}
{docstring Std.TreeMap.foldl}
{docstring Std.TreeMap.foldlM}
{docstring Std.TreeMap.foldr}
{docstring Std.TreeMap.foldrM}
{docstring Std.TreeMap.forIn}
{docstring Std.TreeMap.forM}
# Conversion
{docstring Std.TreeMap.ofList}
{docstring Std.TreeMap.toList}
{docstring Std.TreeMap.ofArray}
{docstring Std.TreeMap.toArray}
{docstring Std.TreeMap.unitOfArray}
{docstring Std.TreeMap.unitOfList}
## Unbundled Variants
Unbundled maps separate well-formedness proofs from data.
This is primarily useful when defining {ref "raw-data"}[nested inductive types].
To use these variants, import the module `Std.TreeMap.Raw`.
{docstring Std.TreeMap.Raw}
{docstring Std.TreeMap.Raw.WF} |
reference-manual/Manual/BasicTypes/Maps/TreeSet.lean | import VersoManual
import Manual.Meta
import Std.Data.TreeSet
import Std.Data.TreeSet.Raw
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Tree-Based Sets" =>
%%%
tag := "TreeSet"
%%%
{docstring Std.TreeSet +hideStructureConstructor +hideFields}
# Creation
{docstring Std.TreeSet.empty}
# Properties
{docstring Std.TreeSet.isEmpty}
{docstring Std.TreeSet.size}
# Queries
{docstring Std.TreeSet.contains}
{docstring Std.TreeSet.get}
{docstring Std.TreeSet.get!}
{docstring Std.TreeSet.get?}
{docstring Std.TreeSet.getD}
## Ordering-Based Queries
{docstring Std.TreeSet.atIdx}
{docstring Std.TreeSet.atIdx!}
{docstring Std.TreeSet.atIdx?}
{docstring Std.TreeSet.atIdxD}
{docstring Std.TreeSet.getGE}
{docstring Std.TreeSet.getGE!}
{docstring Std.TreeSet.getGE?}
{docstring Std.TreeSet.getGED}
{docstring Std.TreeSet.getGT}
{docstring Std.TreeSet.getGT!}
{docstring Std.TreeSet.getGT?}
{docstring Std.TreeSet.getGTD}
{docstring Std.TreeSet.getLE}
{docstring Std.TreeSet.getLE!}
{docstring Std.TreeSet.getLE?}
{docstring Std.TreeSet.getLED}
{docstring Std.TreeSet.getLT}
{docstring Std.TreeSet.getLT!}
{docstring Std.TreeSet.getLT?}
{docstring Std.TreeSet.getLTD}
{docstring Std.TreeSet.min}
{docstring Std.TreeSet.min!}
{docstring Std.TreeSet.min?}
{docstring Std.TreeSet.minD}
{docstring Std.TreeSet.max}
{docstring Std.TreeSet.max!}
{docstring Std.TreeSet.max?}
{docstring Std.TreeSet.maxD}
# Modification
{docstring Std.TreeSet.insert}
{docstring Std.TreeSet.insertMany}
{docstring Std.TreeSet.containsThenInsert}
{docstring Std.TreeSet.erase}
{docstring Std.TreeSet.eraseMany}
{docstring Std.TreeSet.filter}
{docstring Std.TreeSet.merge}
{docstring Std.TreeSet.partition}
# Iteration
{docstring Std.TreeSet.iter}
{docstring Std.TreeSet.all}
{docstring Std.TreeSet.any}
{docstring Std.TreeSet.foldl}
{docstring Std.TreeSet.foldlM}
{docstring Std.TreeSet.foldr}
{docstring Std.TreeSet.foldrM}
{docstring Std.TreeSet.forIn}
{docstring Std.TreeSet.forM}
# Conversion
{docstring Std.TreeSet.toList}
{docstring Std.TreeSet.ofList}
{docstring Std.TreeSet.toArray}
{docstring Std.TreeSet.ofArray}
## Unbundled Variants
Unbundled sets separate well-formedness proofs from data.
This is primarily useful when defining {ref "raw-data"}[nested inductive types].
To use these variants, import the module `Std.TreeSet.Raw`.
{docstring Std.TreeSet.Raw}
{docstring Std.TreeSet.Raw.WF} |
reference-manual/Manual/BasicTypes/UInt/Arith.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
#doc (Manual) "Arithmetic" =>
%%%
tag := "fixed-int-arithmetic"
%%%
Typically, arithmetic operations on fixed-width integers should be accessed using Lean's overloaded arithmetic notation, particularly their instances of {name}`Add`, {name}`Sub`, {name}`Mul`, {name}`Div`, and {name}`Mod`, as well as {name}`Neg` for signed types.
```lean -show
-- Check that all those instances really exist
open Lean Elab Command in
#eval show CommandElabM Unit from do
let signed := [`ISize, `Int8, `Int16, `Int32, `Int64]
let unsigned := [`USize, `UInt8, `UInt16, `UInt32, `UInt64]
let types := signed ++ unsigned
let classes : List Name := [`Add, `Sub, `Mul, `Div, `Mod]
for t in types do
for c in classes do
elabCommand <| ← `(example : $(mkIdent c):ident $(mkIdent t) := inferInstance)
for t in signed do
elabCommand <| ← `(example : Neg $(mkIdent t) := inferInstance)
```
{docstring ISize.neg}
{docstring Int8.neg}
{docstring Int16.neg}
{docstring Int32.neg}
{docstring Int64.neg}
{docstring USize.neg}
{docstring UInt8.neg}
{docstring UInt16.neg}
{docstring UInt32.neg}
{docstring UInt64.neg}
{docstring USize.add}
{docstring ISize.add}
{docstring UInt8.add}
{docstring Int8.add}
{docstring UInt16.add}
{docstring Int16.add}
{docstring UInt32.add}
{docstring Int32.add}
{docstring UInt64.add}
{docstring Int64.add}
{docstring USize.sub}
{docstring ISize.sub}
{docstring UInt8.sub}
{docstring Int8.sub}
{docstring UInt16.sub}
{docstring Int16.sub}
{docstring UInt32.sub}
{docstring Int32.sub}
{docstring UInt64.sub}
{docstring Int64.sub}
{docstring USize.mul}
{docstring ISize.mul}
{docstring UInt8.mul}
{docstring Int8.mul}
{docstring UInt16.mul}
{docstring Int16.mul}
{docstring UInt32.mul}
{docstring Int32.mul}
{docstring UInt64.mul}
{docstring Int64.mul}
{docstring USize.div}
{docstring ISize.div}
{docstring UInt8.div}
{docstring Int8.div}
{docstring UInt16.div}
{docstring Int16.div}
{docstring UInt32.div}
{docstring Int32.div}
{docstring UInt64.div}
{docstring Int64.div}
{docstring USize.mod}
{docstring ISize.mod}
{docstring UInt8.mod}
{docstring Int8.mod}
{docstring UInt16.mod}
{docstring Int16.mod}
{docstring UInt32.mod}
{docstring Int32.mod}
{docstring UInt64.mod}
{docstring Int64.mod}
{docstring USize.log2}
{docstring UInt8.log2}
{docstring UInt16.log2}
{docstring UInt32.log2}
{docstring UInt64.log2}
{docstring ISize.abs}
{docstring Int8.abs}
{docstring Int16.abs}
{docstring Int32.abs}
{docstring Int64.abs} |
reference-manual/Manual/BasicTypes/UInt/Comparisons.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option verso.docstring.allowMissing true
#doc (Manual) "Comparisons" =>
%%%
tag := "fixed-int-comparisons"
%%%
The operators in this section are rarely invoked by name.
Typically, comparisons operations on fixed-width integers should use the decidability of the corresponding relations, which consist of the equality type {name}`Eq` and those implemented in instances of {name}`LE` and {name}`LT`.
```lean -show
-- Check that all those instances really exist
open Lean Elab Command in
#eval show CommandElabM Unit from do
let types := [`ISize, `Int8, `Int16, `Int32, `Int64, `USize, `UInt8, `UInt16, `UInt32, `UInt64]
for t in types do
elabCommand <| ← `(example : LE $(mkIdent t) := inferInstance)
elabCommand <| ← `(example : LT $(mkIdent t) := inferInstance)
```
```lean -show
-- Check that all those instances really exist
open Lean Elab Command in
#eval show CommandElabM Unit from do
let types := [`ISize, `Int8, `Int16, `Int32, `Int64, `USize, `UInt8, `UInt16, `UInt32, `UInt64]
for t in types do
elabCommand <| ← `(example (x y : $(mkIdent t):ident) : Decidable (x < y) := inferInstance)
elabCommand <| ← `(example (x y : $(mkIdent t):ident) : Decidable (x ≤ y) := inferInstance)
elabCommand <| ← `(example (x y : $(mkIdent t):ident) : Decidable (x = y) := inferInstance)
```
{docstring USize.le}
{docstring ISize.le}
{docstring UInt8.le}
{docstring Int8.le}
{docstring UInt16.le}
{docstring Int16.le}
{docstring UInt32.le}
{docstring Int32.le}
{docstring UInt64.le}
{docstring Int64.le}
{docstring USize.lt}
{docstring ISize.lt}
{docstring UInt8.lt}
{docstring Int8.lt}
{docstring UInt16.lt}
{docstring Int16.lt}
{docstring UInt32.lt}
{docstring Int32.lt}
{docstring UInt64.lt}
{docstring Int64.lt}
{docstring USize.decEq}
{docstring ISize.decEq}
{docstring UInt8.decEq}
{docstring Int8.decEq}
{docstring UInt16.decEq}
{docstring Int16.decEq}
{docstring UInt32.decEq}
{docstring Int32.decEq}
{docstring UInt64.decEq}
{docstring Int64.decEq}
{docstring USize.decLe}
{docstring ISize.decLe}
{docstring UInt8.decLe}
{docstring Int8.decLe}
{docstring UInt16.decLe}
{docstring Int16.decLe}
{docstring UInt32.decLe}
{docstring Int32.decLe}
{docstring UInt64.decLe}
{docstring Int64.decLe}
{docstring USize.decLt}
{docstring ISize.decLt}
{docstring UInt8.decLt}
{docstring Int8.decLt}
{docstring UInt16.decLt}
{docstring Int16.decLt}
{docstring UInt32.decLt}
{docstring Int32.decLt}
{docstring UInt64.decLt}
{docstring Int64.decLt} |
reference-manual/Manual/BasicTypes/Array/Subarray.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Sub-Arrays" =>
%%%
tag := "subarray"
%%%
{docstring Subarray}
{docstring Subarray.toArray}
{docstring Subarray.empty}
# Array Data
{docstring Subarray.array}
{docstring Subarray.start}
{docstring Subarray.stop}
{docstring Subarray.start_le_stop}
{docstring Subarray.stop_le_array_size}
# Size
{docstring Subarray.size}
# Resizing
{docstring Subarray.drop}
{docstring Subarray.take}
{docstring Subarray.popFront}
{docstring Subarray.split}
# Lookups
{docstring Subarray.get}
{docstring Subarray.get!}
{docstring Subarray.getD}
# Iteration
{docstring Subarray.foldl}
{docstring Subarray.foldlM}
{docstring Subarray.foldr}
{docstring Subarray.foldrM}
{docstring Subarray.forM}
{docstring Subarray.forRevM}
{docstring Subarray.forIn}
# Element Predicates
{docstring Subarray.findRev?}
{docstring Subarray.findRevM?}
{docstring Subarray.findSomeRevM?}
{docstring Subarray.all}
{docstring Subarray.allM}
{docstring Subarray.any}
{docstring Subarray.anyM} |
reference-manual/Manual/BasicTypes/Array/FFI.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "FFI" =>
%%%
tag := "array-ffi"
%%%
:::ffi "lean_string_object" (kind := type)
```
typedef struct {
lean_object m_header;
size_t m_size;
size_t m_capacity;
lean_object * m_data[];
} lean_array_object;
```
The representation of arrays in C. See {ref "array-runtime"}[the description of run-time {name}`Array`s] for more details.
:::
:::ffi "lean_is_array"
```
bool lean_is_array(lean_object * o)
```
Returns `true` if `o` is an array, or `false` otherwise.
:::
:::ffi "lean_to_array"
```
lean_array_object * lean_to_array(lean_object * o)
```
Performs a runtime check that `o` is indeed an array. If `o` is not an array, an assertion fails.
:::
::::draft
:::planned 158
* Complete C API for {lean}`Array`
:::
:::: |
reference-manual/Manual/BasicTypes/List/Transformation.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Transformation" =>
{docstring List.map}
{docstring List.mapTR}
{docstring List.mapM}
{docstring List.mapM'}
{docstring List.mapA}
{docstring List.mapFinIdx}
{docstring List.mapFinIdxM}
{docstring List.mapIdx}
{docstring List.mapIdxM}
{docstring List.mapMono}
{docstring List.mapMonoM}
{docstring List.flatMap}
{docstring List.flatMapTR}
{docstring List.flatMapM}
{docstring List.zip}
{docstring List.zipIdx}
{docstring List.zipIdxTR}
{docstring List.zipWith}
{docstring List.zipWithTR}
{docstring List.zipWithAll}
{docstring List.unzip}
{docstring List.unzipTR} |
reference-manual/Manual/BasicTypes/List/Modification.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Modification" =>
{docstring List.set}
{docstring List.setTR}
{docstring List.modify}
{docstring List.modifyTR}
{docstring List.modifyHead}
{docstring List.modifyTailIdx}
{docstring List.erase}
{docstring List.eraseTR}
{docstring List.eraseDups}
{docstring List.eraseIdx}
{docstring List.eraseIdxTR}
{docstring List.eraseP}
{docstring List.erasePTR}
{docstring List.eraseReps}
{docstring List.extract}
{docstring List.removeAll}
{docstring List.replace}
{docstring List.replaceTR}
{docstring List.reverse}
{docstring List.flatten}
{docstring List.flattenTR}
{docstring List.rotateLeft}
{docstring List.rotateRight}
{docstring List.leftpad}
{docstring List.leftpadTR}
{docstring List.rightpad}
# Insertion
{docstring List.insert}
{docstring List.insertIdx}
{docstring List.insertIdxTR}
{docstring List.intersperse}
{docstring List.intersperseTR}
{docstring List.intercalate}
{docstring List.intercalateTR} |
reference-manual/Manual/BasicTypes/List/Predicates.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Predicates and Relations" =>
{docstring List.IsPrefix}
:::syntax term (title := "List Prefix")
```grammar
$_ <+: $_
```
{includeDocstring List.«term_<+:_»}
:::
{docstring List.IsSuffix}
:::syntax term (title := "List Suffix")
```grammar
$_ <:+ $_
```
{includeDocstring List.«term_<:+_»}
:::
{docstring List.IsInfix}
:::syntax term (title := "List Infix")
```grammar
$_ <:+: $_
```
{includeDocstring List.«term_<:+:_»}
:::
{docstring List.Sublist}
::: syntax term (title := "Sublists") (namespace := List)
```grammar
$_ <+ $_
```
{includeDocstring List.«term_<+_»}
This syntax is only available when the `List` namespace is opened.
:::
{docstring List.Perm}
:::syntax term (title := "List Permutation") (namespace := List)
```grammar
$_ ~ $_
```
{includeDocstring List.«term_~_»}
This syntax is only available when the `List` namespace is opened.
:::
{docstring List.Pairwise}
{docstring List.Nodup}
{docstring List.Lex}
{docstring List.Mem} |
reference-manual/Manual/BasicTypes/List/Partitioning.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Partitioning" =>
{docstring List.take}
{docstring List.takeTR}
{docstring List.takeWhile}
{docstring List.takeWhileTR}
{docstring List.drop}
{docstring List.dropWhile}
{docstring List.dropLast}
{docstring List.dropLastTR}
{docstring List.splitAt}
{docstring List.span}
{docstring List.splitBy}
{docstring List.partition}
{docstring List.partitionM}
{docstring List.partitionMap}
{docstring List.groupByKey} |
reference-manual/Manual/BasicTypes/List/Comparisons.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Comparisons" =>
{docstring List.beq}
{docstring List.isEqv}
{docstring List.isPerm}
{docstring List.isPrefixOf}
{docstring List.isPrefixOf?}
{docstring List.isSublist}
{docstring List.isSuffixOf}
{docstring List.isSuffixOf?}
{docstring List.le}
{docstring List.lt}
{docstring List.lex} |
reference-manual/Manual/BasicTypes/String/Literals.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Syntax" =>
%%%
tag := "string-syntax"
%%%
Lean has three kinds of string literals: ordinary string literals, interpolated string literals, and raw string literals.
# String Literals
%%%
tag := "string-literals"
%%%
String literals begin and end with a double-quote character `"`. {index (subterm := "string")}[literal]
Between these characters, they may contain any other character, including newlines, which are included literally (with the caveat that all newlines in a Lean source file are interpreted as `'\n'`, regardless of file encoding and platform).
Special characters that cannot otherwise be written in string literals may be escaped with a backslash, so `"\"Quotes\""` is a string literal that begins and ends with double quotes.
The following forms of escape sequences are accepted:
: `\r`, `\n`, `\t`, `\\`, `\"`, `\'`
These escape sequences have the usual meaning, mapping to `CR`, `LF`, tab, backslash, double quote, and single quote, respectively.
: `\xNN`
When `NN` is a sequence of two hexadecimal digits, this escape denotes the character whose Unicode code point is indicated by the two-digit hexadecimal code.
: `\uNNNN`
When `NN` is a sequence of two hexadecimal digits, this escape denotes the character whose Unicode code point is indicated by the four-digit hexadecimal code.
String literals may contain {deftech}[_gaps_].
A gap is indicated by an escaped newline, with no intervening characters between the escaping backslash and the newline.
In this case, the string denoted by the literal is missing the newline and all leading whitespace from the next line.
String gaps may not precede lines that contain only whitespace.
Here, `str1` and `str2` are the same string:
```lean
def str1 := "String with \
a gap"
def str2 := "String with a gap"
example : str1 = str2 := rfl
```
If the line following the gap is empty, the string is rejected:
```syntaxError foo
def str3 := "String with \
a gap"
```
The parser error is:
```leanOutput foo
<example>:2:0-3:0: unexpected additional newline in string gap
```
# Interpolated Strings
%%%
tag := "string-interpolation"
%%%
Preceding a string literal with `s!` causes it to be processed as an {deftech}[_interpolated string_], in which regions of the string surrounded by `{` and `}` characters are parsed and interpreted as Lean expressions.
Interpolated strings are interpreted by appending the string that precedes the interpolation, the expression (with an added call to {name ToString.toString}`toString` surrounding it), and the string that follows the interpolation.
For example:
```lean
example :
s!"1 + 1 = {1 + 1}\n" =
"1 + 1 = " ++ toString (1 + 1) ++ "\n" :=
rfl
```
Preceding a literal with `m!` causes the interpolation to result in an instance of {name Lean.MessageData}`MessageData`, the compiler's internal data structure for messages to be shown to users.
# Raw String Literals
%%%
tag := "raw-string-literals"
%%%
In {deftech}[raw string literals], {index (subterm := "raw string")}[literal] there are no escape sequences or gaps, and each character denotes itself exactly.
Raw string literals are preceded by `r`, followed by zero or more hash characters (`#`) and a double quote `"`.
The string literal is completed at a double quote that is followed by _the same number_ of hash characters.
For example, they can be used to avoid the need to double-escape certain characters:
```lean (name := evalStr)
example : r"\t" = "\\t" := rfl
#eval r"Write backslash in a string using '\\\\'"
```
The `#eval` yields:
```leanOutput evalStr
"Write backslash in a string using '\\\\\\\\'"
```
Including hash marks allows the strings to contain unescaped quotes:
```lean
example :
r#"This is "literally" quoted"# =
"This is \"literally\" quoted" :=
rfl
```
Adding sufficiently many hash marks allows any raw literal to be written literally:
```lean
example :
r##"This is r#"literally"# quoted"## =
"This is r#\"literally\"# quoted" :=
rfl
``` |
reference-manual/Manual/BasicTypes/String/RawPos.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Raw Positions" =>
%%%
tag := "string-api-pos"
%%%
{docstring String.Pos.Raw}
# Validity
{docstring String.Pos.Raw.isValid}
{docstring String.Pos.Raw.isValidForSlice}
# Boundaries
{docstring String.endPos}
{docstring String.Pos.Raw.atEnd}
# Comparisons
{docstring String.Pos.Raw.min}
{docstring String.Pos.Raw.byteDistance}
{docstring String.Pos.Raw.substrEq}
# Adjustment
{docstring String.Pos.Raw.prev}
{docstring String.Pos.Raw.next}
{docstring String.Pos.Raw.next'}
{docstring String.Pos.Raw.nextUntil}
{docstring String.Pos.Raw.nextWhile}
{docstring String.Pos.Raw.inc}
{docstring String.Pos.Raw.increaseBy}
{docstring String.Pos.Raw.offsetBy}
{docstring String.Pos.Raw.dec}
{docstring String.Pos.Raw.decreaseBy}
{docstring String.Pos.Raw.unoffsetBy}
# String Lookups
{docstring String.Pos.Raw.extract}
{docstring String.Pos.Raw.get}
{docstring String.Pos.Raw.get!}
{docstring String.Pos.Raw.get'}
{docstring String.Pos.Raw.get?}
# String Modifications
{docstring String.Pos.Raw.set}
{docstring String.Pos.Raw.modify} |
reference-manual/Manual/BasicTypes/String/Logical.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Logical Model" =>
{docstring String}
:::paragraph
The logical model of strings in Lean is a structure that contains two fields:
* {name}`String.toByteArray` is a {name}`ByteArray`, which contains the UTF-8 encoding of the string.
* {name}`String.isValidUTF8` is a proof that the bytes are in fact a valid UTF-8 encoding of a string.
This model allows operations on byte arrays to be used to specify and prove properties about string operations at a low level while still building on the theory of byte arrays.
At the same time, it is close enough to the real run-time representation to avoid impedance mismatches between the logical model and the operations that make sense in the run-time representation.
:::
# Backwards Compatibility
In prior versions of Lean, the logical model of strings was a structure that contained a list of characters.
This model is still useful.
It is still accessible using {name}`String.ofList`, which converts a list of characters into a {name}`String`, and {name}`String.toList`, which converts a {name}`String` into a list of characters.
{docstring String.ofList}
{docstring String.toList} |
reference-manual/Manual/BasicTypes/String/FFI.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "FFI" =>
%%%
tag := "string-ffi"
%%%
:::ffi "lean_string_object" (kind := type)
```
typedef struct {
lean_object m_header;
/* byte length including '\0' terminator */
size_t m_size;
size_t m_capacity;
/* UTF8 length */
size_t m_length;
char m_data[0];
} lean_string_object;
```
The representation of strings in C. See {ref "string-runtime"}[the description of run-time {name}`String`s] for more details.
:::
:::ffi "lean_is_string"
```
bool lean_is_string(lean_object * o)
```
Returns `true` if `o` is a string, or `false` otherwise.
:::
:::ffi "lean_to_string"
```
lean_string_object * lean_to_string(lean_object * o)
```
Performs a runtime check that `o` is indeed a string. If `o` is not a string, an assertion fails.
:::
::::draft
:::planned 158
* Complete C API for {lean}`String`
:::
:::: |
reference-manual/Manual/BasicTypes/String/ValidPos.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Positions" =>
%%%
tag := "string-api-valid-pos"
%%%
{docstring String.ValidPos}
# In Strings
{docstring String.startValidPos}
{docstring String.endValidPos}
{docstring String.pos}
{docstring String.pos?}
{docstring String.pos!}
# Lookups
{docstring String.ValidPos.get}
{docstring String.ValidPos.get!}
{docstring String.ValidPos.get?}
{docstring String.ValidPos.set}
{docstring String.ValidPos.extract +allowMissing}
# Modifications
{docstring String.ValidPos.modify}
{docstring String.ValidPos.byte}
# Adjustment
{docstring String.ValidPos.prev}
{docstring String.ValidPos.prev!}
{docstring String.ValidPos.prev?}
{docstring String.ValidPos.next}
{docstring String.ValidPos.next!}
{docstring String.ValidPos.next?}
# Other Strings
{docstring String.ValidPos.cast}
{docstring String.ValidPos.ofCopy}
{docstring String.ValidPos.setOfLE}
{docstring String.ValidPos.modifyOfLE}
{docstring String.ValidPos.toSlice} |
reference-manual/Manual/BasicTypes/String/Slice.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "String Slices" =>
%%%
tag := "string-api-slice"
%%%
{docstring String.Slice}
{docstring String.toSlice}
{docstring String.sliceFrom}
{docstring String.sliceTo}
{docstring String.Slice.Pos}
# API Reference
## Copying
{docstring String.Slice.copy}
## Size
{docstring String.Slice.isEmpty}
{docstring String.Slice.utf8ByteSize}
## Boundaries
{docstring String.Slice.pos}
{docstring String.Slice.pos!}
{docstring String.Slice.pos?}
{docstring String.Slice.startPos}
{docstring String.Slice.endPos}
{docstring String.Slice.rawEndPos}
### Adjustment
{docstring String.Slice.sliceFrom}
{docstring String.Slice.sliceTo}
{docstring String.Slice.slice}
{docstring String.Slice.slice!}
{docstring String.Slice.drop}
{docstring String.Slice.dropEnd}
{docstring String.Slice.dropEndWhile}
{docstring String.Slice.dropPrefix}
{docstring String.Slice.dropPrefix?}
{docstring String.Slice.dropSuffix}
{docstring String.Slice.dropSuffix?}
{docstring String.Slice.dropWhile}
{docstring String.Slice.take}
{docstring String.Slice.takeEnd}
{docstring String.Slice.takeEndWhile}
{docstring String.Slice.takeWhile}
## Characters
{docstring String.Slice.front}
{docstring String.Slice.front?}
{docstring String.Slice.back}
{docstring String.Slice.back?}
## Bytes
{docstring String.Slice.getUTF8Byte}
{docstring String.Slice.getUTF8Byte!}
## Positions
{docstring String.Slice.findNextPos}
## Searching
{docstring String.Slice.contains}
{docstring String.Slice.startsWith}
{docstring String.Slice.endsWith}
{docstring String.Slice.all}
{docstring String.Slice.find?}
{docstring String.Slice.revFind?}
## Manipulation
{docstring String.Slice.split}
{docstring String.Slice.splitInclusive}
{docstring String.Slice.lines}
{docstring String.Slice.trimAscii}
{docstring String.Slice.trimAsciiEnd}
{docstring String.Slice.trimAsciiStart}
## Iteration
{docstring String.Slice.chars}
{docstring String.Slice.revChars}
{docstring String.Slice.positions}
{docstring String.Slice.revPositions}
{docstring String.Slice.bytes}
{docstring String.Slice.revBytes}
{docstring String.Slice.revSplit}
{docstring String.Slice.foldl}
{docstring String.Slice.foldr}
## Conversions
{docstring String.Slice.isNat}
{docstring String.Slice.toNat!}
{docstring String.Slice.toNat?}
## Equality
{docstring String.Slice.beq}
{docstring String.Slice.eqIgnoreAsciiCase}
# Patterns
String slices feature generalized search patterns.
Rather than being defined to work only for characters or for strings, many operations on slices accept arbitrary patterns.
New types can be made into patterns by defining instances of the classes in this section.
The Lean standard library provides instances that allow the following types to be used for both forward and backward searching:
:::table +header
* * Pattern Type
* Meaning
* * {name}`Char`
* Matches the provided character
*
* {lean}`Char → Bool`
* Matches any character that satisfies the predicate
* * {lean}`String`
* Matches occurrences of the given string
* * {lean}`String.Slice`
* Matches occurrences of the string represented by the slice
:::
{docstring String.Slice.Pattern.ToForwardSearcher}
{docstring String.Slice.Pattern.ForwardPattern}
{docstring String.Slice.Pattern.ToBackwardSearcher}
{docstring String.Slice.Pattern.BackwardPattern +allowMissing}
# Positions
## Lookups
Because they retain a reference to the slice from which they were drawn, slice positions allow individual characters or bytes to be looked up.
{docstring String.Slice.Pos.byte}
{docstring String.Slice.Pos.get}
{docstring String.Slice.Pos.get!}
{docstring String.Slice.Pos.get?}
## Incrementing and Decrementing
{docstring String.Slice.Pos.prev}
{docstring String.Slice.Pos.prev!}
{docstring String.Slice.Pos.prev?}
{docstring String.Slice.Pos.prevn}
{docstring String.Slice.Pos.next}
{docstring String.Slice.Pos.next!}
{docstring String.Slice.Pos.next?}
{docstring String.Slice.Pos.nextn}
## Other Strings or Slices
{docstring String.Slice.Pos.cast}
{docstring String.Slice.Pos.ofSlice}
{docstring String.Slice.Pos.str}
{docstring String.Slice.Pos.copy}
{docstring String.Slice.Pos.ofSliceFrom}
{docstring String.Slice.Pos.ofSliceTo} |
reference-manual/Manual/BasicTypes/String/Substrings.lean | import VersoManual
import Manual.Meta
open Manual.FFIDocType
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
#doc (Manual) "Raw Substrings" =>
%%%
tag := "string-api-substring"
%%%
Raw substrings are a low-level type that groups a string together with byte positions that delimit a region in the string.
Most code should use {ref "string-api-slice"}[slices] instead, because they are safer and more convenient.
{docstring String.toRawSubstring}
{docstring String.toRawSubstring'}
{docstring Substring.Raw}
# Properties
{docstring Substring.Raw.isEmpty}
{docstring Substring.Raw.bsize}
# Positions
{docstring Substring.Raw.atEnd}
{docstring Substring.Raw.posOf}
{docstring Substring.Raw.next}
{docstring Substring.Raw.nextn}
{docstring Substring.Raw.prev}
{docstring Substring.Raw.prevn}
# Folds and Aggregation
{docstring Substring.Raw.foldl}
{docstring Substring.Raw.foldr}
{docstring Substring.Raw.all}
{docstring Substring.Raw.any}
# Comparisons
{docstring Substring.Raw.beq}
{docstring Substring.Raw.sameAs}
# Prefix and Suffix
{docstring Substring.Raw.commonPrefix}
{docstring Substring.Raw.commonSuffix}
{docstring Substring.Raw.dropPrefix?}
{docstring Substring.Raw.dropSuffix?}
# Lookups
{docstring Substring.Raw.get}
{docstring Substring.Raw.contains}
{docstring Substring.Raw.front}
# Modifications
{docstring Substring.Raw.drop}
{docstring Substring.Raw.dropWhile}
{docstring Substring.Raw.dropRight}
{docstring Substring.Raw.dropRightWhile}
{docstring Substring.Raw.take}
{docstring Substring.Raw.takeWhile}
{docstring Substring.Raw.takeRight}
{docstring Substring.Raw.takeRightWhile}
{docstring Substring.Raw.extract}
{docstring Substring.Raw.trim}
{docstring Substring.Raw.trimLeft}
{docstring Substring.Raw.trimRight}
{docstring Substring.Raw.splitOn}
{docstring Substring.Raw.repair}
# Conversions
{docstring Substring.Raw.toString}
{docstring Substring.Raw.isNat}
{docstring Substring.Raw.toNat? +allowMissing}
{docstring Substring.Raw.toLegacyIterator}
{docstring Substring.Raw.toName} |
reference-manual/Manual/Classes/InstanceDecls.lean | import VersoManual
import Manual.Meta
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
#doc (Manual) "Instance Declarations" =>
%%%
tag := "instance-declarations"
%%%
The syntax of instance declarations is almost identical to that of definitions.
The only syntactic differences are that the keyword {keywordOf Lean.Parser.Command.declaration}`def` is replaced by {keywordOf Lean.Parser.Command.declaration}`instance` and the name is optional:
:::syntax Lean.Parser.Command.instance (title := "Instance Declarations")
Most instances define each method using {keywordOf Lean.Parser.Command.declaration}`where` syntax:
```grammar
instance $[(priority := $p:prio)]? $name? $_ where
$_*
```
However, type classes are inductive types, so instances can be constructed using any expression with an appropriate type:
```grammar
instance $[(priority := $p:prio)]? $_? $_ :=
$_
```
Instances may also be defined by cases; however, this feature is rarely used outside of {name}`Decidable` instances:
```grammar
instance $[(priority := $p:prio)]? $_? $_
$[| $_ => $_]*
```
:::
Instances defined with explicit terms often consist of either anonymous constructors ({keywordOf Lean.Parser.Term.anonymousCtor}`⟨...⟩`) wrapping method implementations or of invocations of {name}`inferInstanceAs` on definitionally equal types.
Elaboration of instances is almost identical to the elaboration of ordinary definitions, with the exception of the caveats documented below.
If no name is provided, then one is created automatically.
It is possible to refer to this generated name directly, but the algorithm used to generate the names has changed in the past and may change in the future.
It's better to explicitly name instances that will be referred to directly.
After elaboration, the new instance is registered as a candidate for instance search.
Adding the attribute {attr}`instance` to a name can be used to mark any other defined name as a candidate.
::::keepEnv
:::example "Instance Name Generation"
Following these declarations:
```lean
structure NatWrapper where
val : Nat
instance : BEq NatWrapper where
beq
| ⟨x⟩, ⟨y⟩ => x == y
```
the name {lean}`instBEqNatWrapper` refers to the new instance.
:::
::::
::::keepEnv
:::example "Variations in Instance Definitions"
Given this structure type:
```lean
structure NatWrapper where
val : Nat
```
all of the following ways of defining a {name}`BEq` instance are equivalent:
```lean
instance : BEq NatWrapper where
beq
| ⟨x⟩, ⟨y⟩ => x == y
instance : BEq NatWrapper :=
⟨fun x y => x.val == y.val⟩
instance : BEq NatWrapper :=
⟨fun ⟨x⟩ ⟨y⟩ => x == y⟩
```
Aside from introducing different names into the environment, the following are also equivalent:
```lean
@[instance]
def instBeqNatWrapper : BEq NatWrapper where
beq
| ⟨x⟩, ⟨y⟩ => x == y
instance : BEq NatWrapper :=
⟨fun x y => x.val == y.val⟩
instance : BEq NatWrapper :=
⟨fun ⟨x⟩ ⟨y⟩ => x == y⟩
```
:::
::::
# Recursive Instances
%%%
tag := "recursive-instances"
%%%
Functions defined in {keywordOf Lean.Parser.Command.declaration}`where` structure definition syntax are not recursive.
Because instance declaration is a version of structure definition, type class methods are also not recursive by default.
Instances for recursive inductive types are common, however.
There is a standard idiom to work around this limitation: define a recursive function independently of the instance, and then refer to it in the instance definition.
By convention, these recursive functions have the name of the corresponding method, but are defined in the type's namespace.
:::example "Instances are not recursive"
Given this definition of {lean}`NatTree`:
```lean
inductive NatTree where
| leaf
| branch (left : NatTree) (val : Nat) (right : NatTree)
```
the following {name}`BEq` instance fails:
```lean +error (name := beqNatTreeFail)
instance : BEq NatTree where
beq
| .leaf, .leaf =>
true
| .branch l1 v1 r1, .branch l2 v2 r2 =>
l1 == l2 && v1 == v2 && r1 == r2
| _, _ =>
false
```
with errors in both the left and right recursive calls that read:
```leanOutput beqNatTreeFail
failed to synthesize instance of type class
BEq NatTree
Hint: Adding the command `deriving instance BEq for NatTree` may allow Lean to derive the missing instance.
```
Given a suitable recursive function, such as {lean}`NatTree.beq`:
```lean
def NatTree.beq : NatTree → NatTree → Bool
| .leaf, .leaf =>
true
| .branch l1 v1 r1, .branch l2 v2 r2 =>
NatTree.beq l1 l2 && v1 == v2 && NatTree.beq r1 r2
| _, _ =>
false
```
the instance can be created in a second step:
```lean
instance : BEq NatTree where
beq := NatTree.beq
```
or, equivalently, using anonymous constructor syntax:
```lean
instance : BEq NatTree := ⟨NatTree.beq⟩
```
:::
Furthermore, instances are not available for instance synthesis during their own definitions.
They are first marked as being available for instance synthesis after they are defined.
Nested inductive types, in which the recursive occurrence of the type occurs as a parameter to some other inductive type, may require an instance to be available to write even the recursive function.
The standard idiom to work around this limitation is to create a local instance in a recursively-defined function that includes a reference to the function being defined, taking advantage of the fact that instance synthesis may use every binding in the local context with the right type.
::: example "Instances for nested types"
In this definition of {lean}`NatRoseTree`, the type being defined occurs nested under another inductive type constructor ({name}`Array`):
```lean
inductive NatRoseTree where
| node (val : Nat) (children : Array NatRoseTree)
```
Checking the equality of rose trees requires checking equality of arrays.
However, instances are not typically available for instance synthesis during their own definitions, so the following definition fails, even though {lean}`NatRoseTree.beq` is a recursive function and is in scope in its own definition.
```lean +error (name := natRoseTreeBEqFail) -keep
def NatRoseTree.beq : (tree1 tree2 : NatRoseTree) → Bool
| .node val1 children1, .node val2 children2 =>
val1 == val2 &&
children1 == children2
```
```leanOutput natRoseTreeBEqFail
failed to synthesize instance of type class
BEq (Array NatRoseTree)
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
To solve this, a local {lean}`BEq NatRoseTree` instance may be `let`-bound:
```lean
partial def NatRoseTree.beq : (tree1 tree2 : NatRoseTree) → Bool
| .node val1 children1, .node val2 children2 =>
let _ : BEq NatRoseTree := ⟨NatRoseTree.beq⟩
val1 == val2 &&
children1 == children2
```
The use of array equality on the children finds the let-bound instance during instance synthesis.
:::
# Instances of `class inductive`s
%%%
tag := "class-inductive-instances"
%%%
Many instances have function types: any instance that itself recursively invokes instance search is a function, as is any instance with implicit parameters.
While most instances only project method implementations from their own instance parameters, instances of class inductive types typically pattern-match one or more of their arguments, allowing the instance to select the appropriate constructor.
This is done using ordinary Lean function syntax.
Just as with other instances, the function in question is not available for instance synthesis in its own definition.
::::keepEnv
:::example "An instance for a sum class"
```lean -show
axiom α : Type
```
Because {lean}`DecidableEq α` is an abbreviation for {lean}`(a b : α) → Decidable (Eq a b)`, its arguments can be used directly, as in this example:
```lean
inductive ThreeChoices where
| yes | no | maybe
instance : DecidableEq ThreeChoices
| .yes, .yes =>
.isTrue rfl
| .no, .no =>
.isTrue rfl
| .maybe, .maybe =>
.isTrue rfl
| .yes, .maybe | .yes, .no
| .maybe, .yes | .maybe, .no
| .no, .yes | .no, .maybe =>
.isFalse nofun
```
:::
::::
::::keepEnv
:::example "A recursive instance for a sum class"
The type {lean}`StringList` represents monomorphic lists of strings:
```lean
inductive StringList where
| nil
| cons (hd : String) (tl : StringList)
```
In the following attempt at defining a {name}`DecidableEq` instance, instance synthesis invoked while elaborating the inner {keywordOf termIfThenElse}`if` fails because the instance is not available for instance synthesis in its own definition:
```lean +error (name := stringListNoRec) -keep
instance : DecidableEq StringList
| .nil, .nil => .isTrue rfl
| .cons h1 t1, .cons h2 t2 =>
if h : h1 = h2 then
if h' : t1 = t2 then
.isTrue (by simp [*])
else
.isFalse (by intro hEq; cases hEq; trivial)
else
.isFalse (by intro hEq; cases hEq; trivial)
| .nil, .cons _ _ | .cons _ _, .nil => .isFalse nofun
```
```leanOutput stringListNoRec
failed to synthesize instance of type class
Decidable (t1 = t2)
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
However, because it is an ordinary Lean function, it can recursively refer to its own explicitly-provided name:
```lean
instance instDecidableEqStringList : DecidableEq StringList
| .nil, .nil => .isTrue rfl
| .cons h1 t1, .cons h2 t2 =>
let _ : Decidable (t1 = t2) :=
instDecidableEqStringList t1 t2
if h : h1 = h2 then
if h' : t1 = t2 then
.isTrue (by simp [*])
else
.isFalse (by intro hEq; cases hEq; trivial)
else
.isFalse (by intro hEq; cases hEq; trivial)
| .nil, .cons _ _ | .cons _ _, .nil => .isFalse nofun
```
:::
::::
# Instance Priorities
%%%
tag := "instance-priorities"
%%%
Instances may be assigned {deftech}_priorities_.
During instance synthesis, higher-priority instances are preferred; see {ref "instance-synth"}[the section on instance synthesis] for details of instance synthesis.
:::syntax prio -open (title := "Instance Priorities")
Priorities may be numeric:
```grammar
$n:num
```
If no priority is specified, the default priority that corresponds to {evalPrio}`default` is used:
```grammar
default
```
Three named priorities are available when numeric values are too fine-grained, corresponding to {evalPrio}`low`, {evalPrio}`mid`, and {evalPrio}`high` respectively.
The {keywordOf prioMid}`mid` priority is lower than {keywordOf prioDefault}`default`.
```grammar
low
```
```grammar
mid
```
```grammar
high
```
Finally, priorities can be added and subtracted, so `default + 2` is a valid priority, corresponding to {evalPrio}`default + 2`:
```grammar
($_)
```
```grammar
$_ + $_
```
```grammar
$_ - $_
```
:::
# Default Instances
%%%
tag := "default-instances"
%%%
The {attr}`default_instance` attribute specifies that an instance {ref "default-instance-synth"}[should be used as a fallback in situations where there is not enough information to select it otherwise].
If no priority is specified, then the default priority `default` is used.
:::syntax attr (title := "The {keyword}`default_instance` Attribute")
```grammar
default_instance $p?
```
:::
:::::keepEnv
::::example "Default Instances"
A default instance of {lean}`OfNat Nat` is used to select {lean}`Nat` for natural number literals in the absence of other type information.
It is declared in the Lean standard library with priority 100.
Given this representation of even numbers, in which an even number is represented by half of it:
```lean
structure Even where
half : Nat
```
the following instances allow numeric literals to be used for small {lean}`Even` values (a limit on the depth of type class instance search prevents them from being used for arbitrarily large literals):
```lean (name := insts)
instance ofNatEven0 : OfNat Even 0 where
ofNat := ⟨0⟩
instance ofNatEvenPlusTwo [OfNat Even n] : OfNat Even (n + 2) where
ofNat := ⟨(OfNat.ofNat n : Even).half + 1⟩
#eval (0 : Even)
#eval (34 : Even)
#eval (254 : Even)
```
```leanOutput insts
{ half := 0 }
```
```leanOutput insts
{ half := 17 }
```
```leanOutput insts
{ half := 127 }
```
Specifying them as default instances with a priority greater than or equal to 100 causes them to be used instead of {lean}`Nat`:
```lean
attribute [default_instance 100] ofNatEven0
attribute [default_instance 100] ofNatEvenPlusTwo
```
```lean (name := withDefaults)
#eval 0
#eval 34
```
```leanOutput withDefaults
{ half := 0 }
```
```leanOutput withDefaults
{ half := 17 }
```
Non-even numerals still use the {lean}`OfNat Nat` instance:
```lean (name := stillNat)
#eval 5
```
```leanOutput stillNat
5
```
::::
:::::
# The Instance Attribute
%%%
tag := "instance-attribute"
%%%
The {attr}`instance` attribute declares a name to be an instance, with the specified priority.
Like other attributes, {attr}`instance` can be applied globally, locally, or only when the current namespace is opened.
The {keywordOf Lean.Parser.Command.declaration}`instance` declaration is a form of definition that automatically applies the {attr}`instance` attribute.
:::syntax attr (title := "The `instance` Attribute")
Declares the definition to which it is applied to be an instance.
If no priority is provided, then the default priority `default` is used.
```grammar
instance $p?
```
::: |
reference-manual/Manual/Classes/BasicClasses.lean | import VersoManual
import Manual.Meta
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
set_option maxHeartbeats 250000
#doc (Manual) "Basic Classes" =>
%%%
tag := "basic-classes"
%%%
Many Lean type classes exist in order to allow built-in notations such as addition or array indexing to be overloaded.
# Boolean Equality Tests
The Boolean equality operator `==` is overloaded by defining instances of {name}`BEq`.
The companion class {name}`Hashable` specifies a hashing procedure for a type.
When a type has both {name}`BEq` and {name}`Hashable` instances, then the hashes computed should respect the {name}`BEq` instance: two values equated by {name}`BEq.beq` should always have the same hash.
{docstring BEq}
{docstring Hashable}
{docstring mixHash}
{docstring LawfulBEq}
{docstring ReflBEq}
{docstring EquivBEq}
{docstring LawfulHashable}
{docstring hash_eq}
# Ordering
There are two primary ways to order the values of a type:
* The {name}`Ord` type class provides a three-way comparison operator, {name}`compare`, which can indicate that one value is less than, equal to, or greater than another. It returns an {name}`Ordering`.
* The {name}`LT` and {name}`LE` classes provide canonical {lean}`Prop`-valued ordering relations for a type that do not need to be decidable. These relations are used to overload the `<` and `≤` operators.
{docstring Ord}
The {name}`compare` method is exported, so no explicit `Ord` namespace is required to use it.
{docstring compareOn}
{docstring Ord.opposite}
{docstring Ordering}
{docstring Ordering.swap}
{docstring Ordering.then}
{docstring Ordering.isLT}
{docstring Ordering.isLE}
{docstring Ordering.isEq}
{docstring Ordering.isNe}
{docstring Ordering.isGE}
{docstring Ordering.isGT}
{docstring compareOfLessAndEq}
{docstring compareOfLessAndBEq}
{docstring compareLex}
:::syntax term (title := "Ordering Operators")
The less-than operator is overloaded in the {name}`LT` class:
```grammar
$_ < $_
```
The less-than-or-equal-to operator is overloaded in the {name}`LE` class:
```grammar
$_ ≤ $_
```
The greater-than and greater-than-or-equal-to operators are the reverse of the less-than and less-than-or-equal-to operators, and cannot be independently overloaded:
```grammar
$_ > $_
```
```grammar
$_ ≥ $_
```
:::
{docstring LT}
{docstring LE}
An {name}`Ord` can be used to construct {name}`BEq`, {name}`LT`, and {name}`LE` instances with the following helpers.
They are not automatically instances because many types are better served by custom relations.
{docstring ltOfOrd}
{docstring leOfOrd}
{docstring Ord.toBEq}
{docstring Ord.toLE}
{docstring Ord.toLT}
:::example "Using `Ord` Instances for `LT` and `LE` Instances"
Lean can automatically derive an {name}`Ord` instance.
In this case, the {inst}`Ord Vegetable` instance compares vegetables lexicographically:
```lean
structure Vegetable where
color : String
size : Fin 5
deriving Ord
```
```lean
def broccoli : Vegetable where
color := "green"
size := 2
def sweetPotato : Vegetable where
color := "orange"
size := 3
```
Using the helpers {name}`ltOfOrd` and {name}`leOfOrd`, {inst}`LT Vegetable` and {inst}`LE Vegetable` instances can be defined.
These instances compare the vegetables using {name}`compare` and logically assert that the result is as expected.
```lean
instance : LT Vegetable := ltOfOrd
instance : LE Vegetable := leOfOrd
```
The resulting relations are decidable because equality is decidable for {lean}`Ordering`:
```lean (name := brLtSw)
#eval broccoli < sweetPotato
```
```leanOutput brLtSw
true
```
```lean (name := brLeSw)
#eval broccoli ≤ sweetPotato
```
```leanOutput brLeSw
true
```
```lean (name := brLtBr)
#eval broccoli < broccoli
```
```leanOutput brLtBr
false
```
```lean (name := brLeBr)
#eval broccoli ≤ broccoli
```
```leanOutput brLeBr
true
```
:::
## Instance Construction
{docstring Ord.lex}
{docstring Ord.lex'}
{docstring Ord.on}
# Minimum and Maximum Values
The classes `Max` and `Min` provide overloaded operators for choosing the greater or lesser of two values.
These should be in agreement with `Ord`, `LT`, and `LE` instances, if they exist, but there is no mechanism to enforce this.
{docstring Min}
{docstring Max}
:::leanSection
```lean -show
variable {α : Type u} [LE α]
```
Given an {inst}`LE α` instance for which {name}`LE.le` is decidable, the helpers {name}`minOfLe` and {name}`maxOfLe` can be used to create suitable {lean}`Min α` and {lean}`Max α` instances.
They can be used as the right-hand side of an {keywordOf Lean.Parser.Command.declaration}`instance` declaration.
{docstring minOfLe}
{docstring maxOfLe}
:::
# Decidability
%%%
tag := "decidable-propositions"
%%%
A proposition is {deftech}_decidable_ if it can be checked algorithmically.{index}[decidable]{index (subterm := "decidable")}[proposition]
The Law of the Excluded Middle means that every proposition is true or false, but it provides no way to check which of the two cases holds, which can often be useful.
By default, only algorithmic {lean}`Decidable` instances for which code can be generated are in scope; opening the `Classical` namespace makes every proposition decidable.
{docstring Decidable}
{docstring DecidablePred}
{docstring DecidableRel}
{docstring DecidableEq}
{docstring DecidableLT}
{docstring DecidableLE}
{docstring Decidable.decide}
{docstring Decidable.byCases}
::::keepEnv
:::example "Excluded Middle and {lean}`Decidable`"
The equality of functions from {lean}`Nat` to {lean}`Nat` is not decidable:
```lean +error (name := NatFunNotDecEq)
example (f g : Nat → Nat) : Decidable (f = g) := inferInstance
```
```leanOutput NatFunNotDecEq
failed to synthesize instance of type class
Decidable (f = g)
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
Opening `Classical` makes every proposition decidable; however, declarations and examples that use this fact must be marked {keywordOf Lean.Parser.Command.declaration}`noncomputable` to indicate that code should not be generated for them.
```lean
open Classical
noncomputable example (f g : Nat → Nat) : Decidable (f = g) :=
inferInstance
```
:::
::::
# Inhabited Types
{docstring Inhabited}
{docstring Nonempty}
# Subsingleton Types
{docstring Subsingleton}
{docstring Subsingleton.elim}
{docstring Subsingleton.helim}
# Visible Representations
%%%
draft := true
%%%
:::planned 135
* ToString
* xref to Repr section
* When to use {name}`Repr` vs {name}`ToString`
:::
{docstring ToString +allowMissing}
# Arithmetic and Bitwise Operators
{docstring Zero}
{docstring NeZero}
{docstring HAdd}
{docstring Add}
{docstring HSub}
{docstring Sub}
{docstring HMul}
{docstring SMul}
{docstring Mul}
{docstring HDiv}
{docstring Div}
{docstring Dvd}
{docstring HMod}
{docstring Mod}
{docstring HPow}
{docstring Pow}
{docstring NatPow}
{docstring HomogeneousPow}
{docstring HShiftLeft}
{docstring ShiftLeft}
{docstring HShiftRight}
{docstring ShiftRight}
{docstring Neg}
{docstring HAnd}
{docstring AndOp}
{docstring HOr}
{docstring OrOp}
{docstring HXor}
{docstring XorOp}
# Append
{docstring HAppend}
{docstring Append}
# Data Lookups
{docstring GetElem}
{docstring GetElem?}
{docstring LawfulGetElem} |
reference-manual/Manual/Classes/InstanceSynth.lean | import VersoManual
import Manual.Meta
import Manual.Papers
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
#doc (Manual) "Instance Synthesis" =>
%%%
tag := "instance-synth"
%%%
Instance synthesis is a recursive search procedure that either finds an instance for a given type class or fails.
In other words, given a type that is registered as a type class, instance synthesis attempts to construct a term with said type.
It respects {tech}[reducibility]: {tech}[semireducible] or {tech}[irreducible] definitions are not unfolded, so instances for a definition are not automatically treated as instances for its unfolding unless it is {tech}[reducible].
There may be multiple possible instances for a given class; in this case, declared priorities and order of declaration are used as tiebreakers, in that order, with more recent instances taking precedence over earlier ones with the same priority.
This search procedure is efficient in the presence of diamonds and does not loop indefinitely when there are cycles.
{deftech}_Diamonds_ occur when there is more than one route to a given goal, and {deftech}_cycles_ are situations when two instances each could be solved if the other were solved.
Diamonds occur regularly in practice when encoding mathematical concepts using type classes, and Lean's coercion feature {TODO}[link] naturally leads to cycles, e.g. between finite sets and finite multisets.
Instance synthesis can be tested using the {keywordOf Lean.Parser.Command.synth}`#synth` command.
Additionally, {name}`inferInstance` and {name}`inferInstanceAs` can be used to synthesize an instance in a position where the instance itself is needed.
{docstring inferInstance}
{docstring inferInstanceAs}
# Instance Search Summary
Generally speaking, instance synthesis is a recursive search procedure that may, in general, backtrack arbitrarily.
Synthesis may _succeed_ with an instance term, _fail_ if no such term can be found, or get _stuck_ if there is insufficient information.
A detailed description of the instance synthesis algorithm is available in {citet tabledRes}[].
An instance search problem is given by a type class applied to concrete arguments; these argument values may or may not be known.
Instance search attempts every locally-bound variable whose type is a class, as well as each registered instance, in order of priority and definition.
When candidate instances themselves have instance-implicit parameters, they impose further synthesis tasks.
A problem is only attempted when all of the input parameters to the type class are known.
When a problem cannot yet be attempted, then that branch is stuck; progress in other subproblems may result in the problem becoming solvable.
Output or semi-output parameters may be either known or unknown at the start of instance search.
Output parameters are ignored when checking whether an instance matches the problem, while semi-output parameters are considered.
Every candidate solution for a given problem is saved in a table; this prevents infinite regress in case of cycles as well as exponential search overheads in the presence of diamonds (that is, multiple paths by which the same goal can be achieved).
A branch of the search fails when any of the following occur:
* All potential instances have been attempted, and the search space is exhausted.
* The instance size limit specified by the option {option}`synthInstance.maxSize` is reached.
* The synthesized value of an output parameter does not match the specified value in the search problem.
Failed branches are not retried.
If search would otherwise fail or get stuck, the search process attempts to use matching {tech}[default instances] in order of priority.
For default instances, the input parameters do not need to be fully known, and may be instantiated by the instances parameter values.
Default instances may take instance-implicit parameters, which induce further recursive search.
Successful branches in which the problem is fully known (that is, in which there are no unsolved metavariables) are pruned, and further potentially-successful instances are not attempted, because no later instance could cause the previously-succeeding branch to fail.
# Instance Search Problems
%%%
tag := "instance-search"
%%%
Instance search occurs during the elaboration of (potentially nullary) function applications.
Some of the implicit parameters' values are forced by others; for instance, an implicit type parameter may be solved using the type of a later value argument that is explicitly provided.
Implicit parameters may also be solved using information from the expected type at that point in the program.
The search for instance implicit arguments may make use of the implicit argument values that have been found, and may additionally solve others.
Instance synthesis begins with the type of the instance-implicit parameter.
This type must be the application of a type class to zero or more arguments; these argument values may be known or unknown when search begins.
If an argument to a class is unknown, the search process will not instantiate it unless the corresponding parameter is {ref "class-output-parameters"}[marked as an output parameter], explicitly making it an output of the instance synthesis routine.
Search may succeed, fail, or get stuck; a stuck search may occur when an unknown argument value becoming known might enable progress to be made.
Stuck searches may be re-invoked when the elaborator has discovered one of the previously-unknown implicit arguments.
If this does not occur, stuck searches become failures.
::::example "Tracing Instance Search"
Setting the {option}`trace.Meta.synthInstance` option to {lean}`true` causes Lean to emit a trace of the process for synthesizing an instance of a type class.
This trace can be used to understand how instance synthesis succeeds and why it fails.
:::paragraph
Here, we can see the steps Lean takes to conclude that there exists an element of the type {lean}`(Nat ⊕ Empty)` (specifically the element {lean}`Sum.inl 0`):
Clicking a `▶` symbol expands that branch of the trace, and clicking the `▼` collapses an expanded branch.
```lean (name := trace)
set_option pp.explicit true in
set_option trace.Meta.synthInstance true in
#synth Nonempty (Nat ⊕ Empty)
```
```comment
IF THE LEAN OUTPUT BELOW CHANGES, IT MAY ALSO BE NECESSARY TO UPDATE THE NARRATIVE VERSION OF THIS STORY THAT FOLLOWS
```
```leanOutput trace (expandTrace := Meta.synthInstance) (expandTrace := Meta.synthInstance.resume)
[Meta.synthInstance] ✅️ Nonempty (Sum Nat Empty)
[Meta.synthInstance] new goal Nonempty (Sum Nat Empty)
[Meta.synthInstance.instances] #[@instNonemptyOfInhabited, @instNonemptyOfMonad, @Sum.nonemptyLeft, @Sum.nonemptyRight]
[Meta.synthInstance] ✅️ apply @Sum.nonemptyRight to Nonempty (Sum Nat Empty)
[Meta.synthInstance.tryResolve] ✅️ Nonempty (Sum Nat Empty) ≟ Nonempty (Sum Nat Empty)
[Meta.synthInstance] new goal Nonempty Empty
[Meta.synthInstance.instances] #[@instNonemptyOfInhabited, @instNonemptyOfMonad]
[Meta.synthInstance] ❌️ apply @instNonemptyOfMonad to Nonempty Empty
[Meta.synthInstance.tryResolve] ❌️ Nonempty Empty ≟ Nonempty (?m.5 ?m.6)
[Meta.synthInstance] ✅️ apply @instNonemptyOfInhabited to Nonempty Empty
[Meta.synthInstance.tryResolve] ✅️ Nonempty Empty ≟ Nonempty Empty
[Meta.synthInstance] new goal Inhabited Empty
[Meta.synthInstance.instances] #[@instInhabitedOfMonad, @Lake.inhabitedOfNilTrace, @instInhabitedOfApplicative_manual]
[Meta.synthInstance] ❌️ apply @instInhabitedOfApplicative_manual to Inhabited Empty
[Meta.synthInstance.tryResolve] ❌️ Inhabited Empty ≟ Inhabited (?m.8 ?m.7)
[Meta.synthInstance] ✅️ apply @Lake.inhabitedOfNilTrace to Inhabited Empty
[Meta.synthInstance.tryResolve] ✅️ Inhabited Empty ≟ Inhabited Empty
[Meta.synthInstance] no instances for Lake.NilTrace Empty
[Meta.synthInstance.instances] #[]
[Meta.synthInstance] ❌️ apply @instInhabitedOfMonad to Inhabited Empty
[Meta.synthInstance.tryResolve] ❌️ Inhabited Empty ≟ Inhabited (?m.8 ?m.7)
[Meta.synthInstance] ✅️ apply @Sum.nonemptyLeft to Nonempty (Sum Nat Empty)
[Meta.synthInstance.tryResolve] ✅️ Nonempty (Sum Nat Empty) ≟ Nonempty (Sum Nat Empty)
[Meta.synthInstance] new goal Nonempty Nat
[Meta.synthInstance.instances] #[@instNonemptyOfInhabited, @instNonemptyOfMonad]
[Meta.synthInstance] ❌️ apply @instNonemptyOfMonad to Nonempty Nat
[Meta.synthInstance.tryResolve] ❌️ Nonempty Nat ≟ Nonempty (?m.5 ?m.6)
[Meta.synthInstance] ✅️ apply @instNonemptyOfInhabited to Nonempty Nat
[Meta.synthInstance.tryResolve] ✅️ Nonempty Nat ≟ Nonempty Nat
[Meta.synthInstance] new goal Inhabited Nat
[Meta.synthInstance.instances] #[@instInhabitedOfMonad, @Lake.inhabitedOfNilTrace, @instInhabitedOfApplicative_manual, instInhabitedNat]
[Meta.synthInstance] ✅️ apply instInhabitedNat to Inhabited Nat
[Meta.synthInstance.tryResolve] ✅️ Inhabited Nat ≟ Inhabited Nat
[Meta.synthInstance.answer] ✅️ Inhabited Nat
[Meta.synthInstance.resume] propagating Inhabited Nat to subgoal Inhabited Nat of Nonempty Nat
[Meta.synthInstance.resume] size: 1
[Meta.synthInstance.answer] ✅️ Nonempty Nat
[Meta.synthInstance.resume] propagating Nonempty Nat to subgoal Nonempty Nat of Nonempty (Sum Nat Empty)
[Meta.synthInstance.resume] size: 2
[Meta.synthInstance.answer] ✅️ Nonempty (Sum Nat Empty)
[Meta.synthInstance] result @Sum.nonemptyLeft Nat Empty (@instNonemptyOfInhabited Nat instInhabitedNat)
```
:::
:::paragraph
By exploring the trace, it is possible to follow the depth-first, backtracking search that Lean uses for type class instance search.
This can take a little practice to get used to!
In the example above, Lean follows these steps:
* Lean considers the first goal, {lean}`Nonempty (Sum Nat Empty)`. Lean sees four ways of possibly satisfying this goal:
- The {name}`Sum.nonemptyRight` instance, which would create a sub-goal {lean}`Nonempty Empty`.
- The {name}`Sum.nonemptyLeft` instance, which would create a sub-goal {lean}`Nonempty Nat`.
- The {name}`instNonemptyOfMonad` instance, which would create two sub-goals {lean}`Monad (Sum Nat)` and {lean}`Nonempty Nat`.
- The {name}`instNonemptyOfInhabited` instance, which would create a sub-goal {lean}`Inhabited (Sum Nat Empty)`.
* The first sub-goal, {lean}`Nonempty Empty`, is considered. Lean sees two ways of possibly satisfying this goal:
- The {name}`instNonemptyOfMonad` instance, which is rejected.
It can't be used because the type {lean}`Empty` is not the application of a monad to a type.
Lean describes this as a failure of {option}`trace.Meta.synthInstance.tryResolve` to solve the equation `Nonempty Empty ≟ Nonempty (?m.5 ?m.6)`.
- The {name}`instNonemptyOfInhabited` instance, which would create a sub-goal {lean}`Inhabited Empty`.
* The newly-generated sub-goal, {lean}`Inhabited Empty`, is considered.
Lean only sees one way of possibly satisfying this goal, {name}`instInhabitedOfMonad`, which is rejected.
As before, this is because the type {lean}`Empty` is not the application of a monad to a type.
* At this point, there are no remaining options for achieving the original first sub-goal.
The search backtracks to the second original sub-goal, {lean}`Nonempty Nat`.
This search eventually succeeds.
:::
The third and fourth original sub-goals are never considered.
Once the search for {lean}`Nonempty Nat` succeeds, the {keywordOf Lean.Parser.Command.synth}`#synth` command finishes and outputs the solution:
```leanOutput trace
@Sum.nonemptyLeft Nat Empty (@instNonemptyOfInhabited Nat instInhabitedNat)
```
::::
# Candidate Instances
Instance synthesis uses both local and global instances in its search.
{deftech}_Local instances_ are those available in the local context; they may be either parameters to a function or locally defined with `let`. {TODO}[xref to docs for `let`]
Local instances do not need to be indicated specially; any local variable whose type is a type class is a candidate for instance synthesis.
{deftech}_Global instances_ are those available in the global environment; every global instance is a defined name with the {attr}`instance` attribute applied.{margin}[{keywordOf Lean.Parser.Command.declaration}`instance` declarations automatically apply the {attr}`instance` attribute.]
::::keepEnv
:::example "Local Instances"
In this example, {lean}`addPairs` contains a locally-defined instance of {lean}`Add NatPair`:
```lean
structure NatPair where
x : Nat
y : Nat
def addPairs (p1 p2 : NatPair) : NatPair :=
let _ : Add NatPair :=
⟨fun ⟨x1, y1⟩ ⟨x2, y2⟩ => ⟨x1 + x2, y1 + y2⟩⟩
p1 + p2
```
The local instance is used for the addition, having been found by instance synthesis.
:::
::::
::::keepEnv
:::example "Local Instances Have Priority"
Here, {lean}`addPairs` contains a locally-defined instance of {lean}`Add NatPair`, even though there is a global instance:
```lean
structure NatPair where
x : Nat
y : Nat
instance : Add NatPair where
add
| ⟨x1, y1⟩, ⟨x2, y2⟩ => ⟨x1 + x2, y1 + y2⟩
def addPairs (p1 p2 : NatPair) : NatPair :=
let _ : Add NatPair :=
⟨fun _ _ => ⟨0, 0⟩⟩
p1 + p2
```
The local instance is selected instead of the global one:
```lean (name:=addPairsOut)
#eval addPairs ⟨1, 2⟩ ⟨5, 2⟩
```
```leanOutput addPairsOut
{ x := 0, y := 0 }
```
:::
::::
# Instance Parameters and Synthesis
%%%
tag := "instance-synth-parameters"
%%%
The search process for instances is largely governed by class parameters.
Type classes take a certain number of parameters, and instances are tried during the search when their choice of parameters is _compatible_ with those in the class type for which the instance is being synthesized.
Instances themselves may also take parameters, but the role of instances' parameters in instance synthesis is very different.
Instances' parameters represent either variables that may be instantiated by instance synthesis or further synthesis work to be done before the instance can be used.
In particular, parameters to instances may be explicit, implicit, or instance-implicit.
If they are instance implicit, then they induce further recursive instance searching, while explicit or implicit parameters must be solved by unification.
::::keepEnv
:::example "Implicit and Explicit Parameters to Instances"
While instances typically take parameters either implicitly or instance-implicitly, explicit parameters may be filled out as if they were implicit during instance synthesis.
In this example, {name}`aNonemptySumInstance` is found by synthesis, applied explicitly to {lean}`Nat`, which is needed to make it type-correct.
```lean
instance aNonemptySumInstance
(α : Type) {β : Type} [inst : Nonempty α] :
Nonempty (α ⊕ β) :=
let ⟨x⟩ := inst
⟨.inl x⟩
```
```lean (name := instSearch)
set_option pp.explicit true in
#synth Nonempty (Nat ⊕ Empty)
```
In the output, both the explicit argument {lean}`Nat` and the implicit argument {lean}`Empty` were found by unification with the search goal, while the {lean}`Nonempty Nat` instance was found via recursive instance synthesis.
```leanOutput instSearch
@aNonemptySumInstance Nat Empty (@instNonemptyOfInhabited Nat instInhabitedNat)
```
:::
::::
# Output Parameters
%%%
tag := "class-output-parameters"
%%%
By default, the parameters of a type class are considered to be _inputs_ to the search process.
If the parameters are not known, then the search process gets stuck, because choosing an instance would require the parameters to have values that match those in the instance, which cannot be determined on the basis of incomplete information.
In most cases, guessing instances would make instance synthesis unpredictable.
In some cases, however, the choice of one parameter should cause an automatic choice of another.
For example, the overloaded membership predicate type class {name}`Membership` treats the type of elements of a data structure as an output, so that the type of element can be determined by the type of data structure at a use site, instead of requiring that there be sufficient type annotations to determine _both_ types prior to starting instance synthesis.
An element of a {lean}`List Nat` can be concluded to be a {lean}`Nat` simply on the basis of its membership in the list.
```signature -show
-- Test the above claim
Membership.{u, v} (α : outParam (Type u)) (γ : Type v) : Type (max u v)
```
Type class parameters can be declared as outputs by wrapping their types in the {name}`outParam` {tech}[gadget].
When a class parameter is an {deftech}_output parameter_, instance synthesis will not require that it be known; in fact, any existing value is ignored completely.
The first instance that matches the input parameters is selected, and that instance's assignment of the output parameter becomes its value.
If there was a pre-existing value, then it is compared with the assignment after synthesis is complete, and it is an error if they do not match.
{docstring outParam}
::::example "Output Parameters and Stuck Search"
:::keepEnv
This serialization framework provides a way to convert values to some underlying storage type:
```lean
class Serialize (input output : Type) where
ser : input → output
export Serialize (ser)
instance : Serialize Nat String where
ser n := toString n
instance [Serialize α γ] [Serialize β γ] [Append γ] :
Serialize (α × β) γ where
ser
| (x, y) => ser x ++ ser y
```
In this example, the output type is unknown.
```lean +error (name := noOutputType)
example := ser (2, 3)
```
Instance synthesis can't select the {lean}`Serialize Nat String` instance, and thus the {lean}`Append String` instance, because that would require instantiating the output type as {lean}`String`, so the search gets stuck:
```leanOutput noOutputType
typeclass instance problem is stuck
Serialize (Nat × Nat) ?m.5
Note: Lean will not try to resolve this typeclass instance problem because the second type argument to `Serialize` is a metavariable. This argument must be fully determined before Lean will try to resolve the typeclass.
Hint: Adding type annotations and supplying implicit arguments to functions can give Lean more information for typeclass resolution. For example, if you have a variable `x` that you intend to be a `Nat`, but Lean reports it as having an unresolved type like `?m`, replacing `x` with `(x : Nat)` can get typeclass resolution un-stuck.
```
As the message indicates, one way to fix the problem is to supply an expected type:
```lean
example : String := ser (2, 3)
```
:::
:::keepEnv
The other is to make the output type into an output parameter:
```lean
class Serialize (input : Type) (output : outParam Type) where
ser : input → output
export Serialize (ser)
instance : Serialize Nat String where
ser n := toString n
instance [Serialize α γ] [Serialize β γ] [Append γ] :
Serialize (α × β) γ where
ser
| (x, y) => ser x ++ ser y
```
Now, instance synthesis is free to select the {lean}`Serialize Nat String` instance, which solves the unknown implicit `output` parameter of {name}`ser`:
```lean
example := ser (2, 3)
```
:::
::::
::::keepEnv
:::example "Output Parameters with Pre-Existing Values"
The class {name}`OneSmaller` represents a way to transform non-maximal elements of a type into elements of a type that has one fewer elements.
There are two separate instances that can match an input type {lean}`Option Bool`, with different outputs:
```lean
class OneSmaller (α : Type) (β : outParam Type) where
biggest : α
shrink : (x : α) → x ≠ biggest → β
instance : OneSmaller (Option α) α where
biggest := none
shrink
| some x, _ => x
instance : OneSmaller (Option Bool) (Option Unit) where
biggest := some true
shrink
| none, _ => none
| some false, _ => some ()
instance : OneSmaller Bool Unit where
biggest := true
shrink
| false, _ => ()
```
Because instance synthesis selects the most recently defined instance, the following code is an error:
```lean +error (name := nosmaller)
#check OneSmaller.shrink (β := Bool) (some false) sorry
```
```leanOutput nosmaller
failed to synthesize instance of type class
OneSmaller (Option Bool) Bool
Hint: Type class instance resolution failures can be inspected with the `set_option trace.Meta.synthInstance true` command.
```
The {lean}`OneSmaller (Option Bool) (Option Unit)` instance was selected during instance synthesis, without regard to the supplied value of `β`.
:::
::::
{deftech}_Semi-output parameters_ are like output parameters in that they are not required to be known prior to synthesis commencing; unlike output parameters, their values are taken into account when selecting instances.
{docstring semiOutParam}
Semi-output parameters impose a requirement on instances: each instance of a class with semi-output parameters should determine the values of its semi-output parameters.
:::TODO
What goes wrong if they can't?
:::
::::keepEnv
:::example "Semi-Output Parameters with Pre-Existing Values"
The class {name}`OneSmaller` represents a way to transform non-maximal elements of a type into elements of a type that one fewer elements.
It has two separate instances that can match an input type {lean}`Option Bool`, with different outputs:
```lean
class OneSmaller (α : Type) (β : semiOutParam Type) where
biggest : α
shrink : (x : α) → x ≠ biggest → β
instance : OneSmaller (Option α) α where
biggest := none
shrink
| some x, _ => x
instance : OneSmaller (Option Bool) (Option Unit) where
biggest := some true
shrink
| none, _ => none
| some false, _ => some ()
instance : OneSmaller Bool Unit where
biggest := true
shrink
| false, _ => ()
```
Because instance synthesis takes semi-output parameters into account when selecting instances, the {lean}`OneSmaller (Option Bool) (Option Unit)` instance is passed over due to the supplied value for `β`:
```lean (name := nosmaller2)
#check OneSmaller.shrink (β := Bool) (some false) sorry
```
```leanOutput nosmaller2
OneSmaller.shrink (some false) ⋯ : Bool
```
:::
::::
# Default Instances
%%%
tag := "default-instance-synth"
%%%
When instance synthesis would otherwise fail, having not selected an instance, the {deftech}_default instances_ specified using the {attr}`default_instance` attribute are attempted in order of priority.
When priorities are equal, more recently-defined default instances are chosen before earlier ones.
The first default instance that causes the search to succeed is chosen.
Default instances may induce further recursive instance search if the default instances themselves have instance-implicit parameters.
If the recursive search fails, the search process backtracks and the next default instance is tried.
# “Morally Canonical” Instances
During instance synthesis, if a goal is fully known (that is, contains no metavariables) and search succeeds, no further instances will be attempted for that same goal.
In other words, when search succeeds for a goal in a way that can't be refuted by a subsequent increase in information, the goal will not be attempted again, even if there are other instances that could potentially have been used.
This optimization can prevent a failure in a later branch of an instance synthesis search from causing spurious backtracking that replaces a fast solution from an earlier branch with a slow exploration of a large state space.
The optimization relies on the assumption that instances are {deftech}_morally canonical_.
Even if there is more than one potential implementation of a given type class's overloaded operations, or more than one way to synthesize an instance due to diamonds, _any discovered instance should be considered as good as any other_.
In other words, there's no need to consider _all_ potential instances so long as one of them has been guaranteed to work.
The optimization may be disabled with the backwards-compatibility option {option}`backward.synthInstance.canonInstances`, which may be removed in a future version of Lean.
Code that uses instance-implicit parameters should be prepared to consider all instances as equivalent.
In other words, it should be robust in the face of differences in synthesized instances.
When the code relies on instances _in fact_ being equivalent, it should either explicitly manipulate instances (e.g. via local definitions, by saving them in structure fields, or having a structure inherit from the appropriate class) or it should make this dependency explicit in the type, so that different choices of instance lead to incompatible types.
# Options
{optionDocs backward.synthInstance.canonInstances}
{optionDocs synthInstance.maxHeartbeats}
{optionDocs synthInstance.maxSize} |
reference-manual/Manual/Classes/DerivingHandlers.lean | import VersoManual
import Manual.Meta
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
section
open Lean Elab Command
/- Needed due to big infotree coming out of the instance quotation in the example here -/
set_option maxRecDepth 1024
set_option maxHeartbeats 650_000
/-- Classes that are part of the manual, not to be shown -/
-- TODO: When moving to v4.26.0-rc1, @kim-em removed `Plausible.Arbitrary` from this list.
-- Should it be restored?
private def hiddenDerivable : Array Name := #[``Manual.Toml.Test]
private def derivableClasses : IO (Array Name) := do
let handlers ← derivingHandlersRef.get
let derivable :=
handlers.toList.map (·.fst)
|>.toArray
|>.filter (fun x => !hiddenDerivable.contains x && !(`Lean).isPrefixOf x)
|>.qsort (·.toString < ·.toString)
pure derivable
private def checkDerivable (expected : Array Name) : CommandElabM Unit := do
let classes ← derivableClasses
let extra := classes.filter (· ∉ expected)
let missing := expected.filter (· ∉ classes)
if extra.isEmpty && missing.isEmpty then
Verso.Log.logSilentInfo m!"Derivable classes match!"
else
unless extra.isEmpty do
logError
m!"These classes were not expected. If they should appear in the list here, \
then add them to the call; otherwise, add them to `{.ofConstName ``hiddenDerivable}`: \
{.andList <| extra.toList.map (.ofConstName ·)}"
unless missing.isEmpty do
logError
m!"These classes were expected but not present. Check whether the text needs updating, then \
then remove them from the call."
end
#eval checkDerivable #[``BEq, ``DecidableEq, ``Hashable, ``Inhabited, ``Nonempty, ``Ord, ``Repr, ``SizeOf, ``TypeName, ``LawfulBEq, ``ReflBEq]
open Verso Doc Elab ArgParse in
open Lean in
open SubVerso Highlighting in
@[directive_expander derivableClassList]
def derivableClassList : DirectiveExpander
| args, contents => do
-- No arguments!
ArgParse.done.run args
if contents.size > 0 then throwError "Expected empty directive"
let classNames ← derivableClasses
let itemStx ← classNames.mapM fun n => do
let hl : Highlighted ← constTok n n.toString
`(Inline.other {Verso.Genre.Manual.InlineLean.Inline.name with data := ToJson.toJson $(quote hl)} #[Inline.code $(quote n.toString)])
let theList ← `(Verso.Doc.Block.ul #[$[⟨#[Verso.Doc.Block.para #[$itemStx]]⟩],*])
return #[theList]
open Lean Elab Command
#doc (Manual) "Deriving Handlers" =>
%%%
tag := "deriving-handlers"
%%%
Instance deriving uses a table of {deftech}_deriving handlers_ that maps type class names to metaprograms that derive instances for them.
Deriving handlers may be added to the table using {lean}`registerDerivingHandler`, which should be called in an {keywordOf Lean.Parser.Command.initialize}`initialize` block.
Each deriving handler should have the type {lean}`Array Name → CommandElabM Bool`.
When a user requests that an instance of a class be derived, its registered handlers are called one at a time.
They are provided with all of the names in the mutual block for which the instance is to be derived, and should either correctly derive an instance and return {lean}`true` or have no effect and return {lean}`false`.
When a handler returns {lean}`true`, no further handlers are called.
Lean includes deriving handlers for the following classes:
:::derivableClassList
:::
{docstring Lean.Elab.registerDerivingHandler}
::::keepEnv
:::example "Deriving Handlers"
```imports -show
import Lean.Elab
```
Instances of the {name}`IsEnum` class demonstrate that a type is a finite enumeration by providing a bijection between the type and a suitably-sized {name}`Fin`:
```lean
class IsEnum (α : Type) where
size : Nat
toIdx : α → Fin size
fromIdx : Fin size → α
to_from_id : ∀ (i : Fin size), toIdx (fromIdx i) = i
from_to_id : ∀ (x : α), fromIdx (toIdx x) = x
```
For inductive types that are trivial enumerations, where no constructor expects any parameters, instances of this class are quite repetitive.
The instance for `Bool` is typical:
```lean
instance : IsEnum Bool where
size := 2
toIdx
| false => 0
| true => 1
fromIdx
| 0 => false
| 1 => true
to_from_id
| 0 => rfl
| 1 => rfl
from_to_id
| false => rfl
| true => rfl
```
The deriving handler programmatically constructs each pattern case, by analogy to the {lean}`IsEnum Bool` implementation:
```lean
open Lean Elab Parser Term Command
def deriveIsEnum (declNames : Array Name) : CommandElabM Bool := do
if h : declNames.size = 1 then
let env ← getEnv
if let some (.inductInfo ind) := env.find? declNames[0] then
let mut tos : Array (TSyntax ``matchAlt) := #[]
let mut froms := #[]
let mut to_froms := #[]
let mut from_tos := #[]
let mut i := 0
for ctorName in ind.ctors do
let c := mkIdent ctorName
let n := Syntax.mkNumLit (toString i)
tos := tos.push (← `(matchAltExpr| | $c => $n))
from_tos := from_tos.push (← `(matchAltExpr| | $c => rfl))
froms := froms.push (← `(matchAltExpr| | $n => $c))
to_froms := to_froms.push (← `(matchAltExpr| | $n => rfl))
i := i + 1
let cmd ← `(instance : IsEnum $(mkIdent declNames[0]) where
size := $(quote ind.ctors.length)
toIdx $tos:matchAlt*
fromIdx $froms:matchAlt*
to_from_id $to_froms:matchAlt*
from_to_id $from_tos:matchAlt*)
elabCommand cmd
return true
return false
initialize
registerDerivingHandler ``IsEnum deriveIsEnum
```
:::
:::: |
reference-manual/Manual/Tactics/Reference.lean | import VersoManual
import Lean.Parser.Term
import Manual.Meta
import Manual.Papers
import Manual.Tactics.Reference.Simp
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.unusedVariables false
set_option maxHeartbeats 250000
#doc (Manual) "Tactic Reference" =>
%%%
tag := "tactic-ref"
%%%
# Classical Logic
%%%
tag := "tactic-ref-classical"
%%%
:::tactic "classical"
:::
# Assumptions
%%%
tag := "tactic-ref-assumptions"
%%%
:::tactic Lean.Parser.Tactic.assumption
:::
:::tactic "apply_assumption"
:::
# Quantifiers
%%%
tag := "tactic-ref-quantifiers"
%%%
:::tactic "exists"
:::
:::tactic "intro"
:::
:::tactic "intros"
:::
:::tactic "rintro"
:::
# Relations
%%%
tag := "tactic-ref-relations"
%%%
:::tactic "rfl"
:::
:::tactic "rfl'"
:::
:::tactic Lean.Parser.Tactic.applyRfl
:::
:::syntax attr (title := "Reflexive Relations")
The {attr}`refl` attribute marks a lemma as a proof of reflexivity for some relation.
These lemmas are used by the {tactic}`rfl`, {tactic}`rfl'`, and {tactic}`apply_rfl` tactics.
```grammar
refl
```
:::
:::tactic "symm"
:::
:::tactic "symm_saturate"
:::
:::syntax attr (title := "Symmetric Relations")
The {attr}`symm` attribute marks a lemma as a proof that a relation is symmetric.
These lemmas are used by the {tactic}`symm` and {tactic}`symm_saturate` tactics.
```grammar
symm
```
:::
:::tactic "calc"
:::
{docstring Trans}
## Equality
%%%
tag := "tactic-ref-equality"
%%%
:::tactic "subst"
:::
:::tactic "subst_eqs"
:::
:::tactic "subst_vars"
:::
:::tactic "congr"
:::
:::tactic "eq_refl"
:::
:::tactic "ac_rfl"
:::
# Associativity and Commutativity
%%%
tag := "tactic-ref-associativity-commutativity"
%%%
:::tactic "ac_nf"
:::
:::tactic "ac_nf0"
:::
# Lemmas
%%%
tag := "tactic-ref-lemmas"
%%%
:::tactic "exact"
:::
:::tactic "apply"
:::
:::tactic "refine"
:::
:::tactic "refine'"
:::
:::tactic "solve_by_elim"
:::
:::tactic "apply_rules"
:::
:::tactic "as_aux_lemma"
:::
# Falsehood
%%%
tag := "tactic-ref-false"
%%%
:::tactic "exfalso"
:::
:::tactic "contradiction"
:::
:::tactic "false_or_by_contra"
:::
# Goal Management
%%%
tag := "tactic-ref-goals"
%%%
:::tactic "suffices"
:::
:::tactic "change"
:::
:::tactic "generalize"
:::
:::tactic "specialize"
:::
:::tactic "obtain"
:::
:::tactic "show"
:::
:::tactic Lean.Parser.Tactic.showTerm
:::
# Cast Management
%%%
tag := "tactic-ref-casts"
%%%
The tactics in this section make it easier avoid getting stuck on {deftech}_casts_, which are functions that coerce data from one type to another, such as converting a natural number to the corresponding integer.
They are described in more detail by {citet castPaper}[].
:::tactic Lean.Parser.Tactic.tacticNorm_cast__
:::
:::tactic Lean.Parser.Tactic.pushCast
:::
:::tactic Lean.Parser.Tactic.tacticExact_mod_cast_
:::
:::tactic Lean.Parser.Tactic.tacticApply_mod_cast_
:::
:::tactic Lean.Parser.Tactic.tacticRw_mod_cast___
:::
:::tactic Lean.Parser.Tactic.tacticAssumption_mod_cast_
:::
# Managing `let` Expressions
:::tactic "extract_lets"
:::
:::tactic "lift_lets"
:::
:::tactic "let_to_have"
:::
:::tactic "clear_value"
:::
# Extensionality
%%%
tag := "tactic-ref-ext"
%%%
:::tactic "ext"
:::
:::tactic Lean.Elab.Tactic.Ext.tacticExt1___
:::
:::tactic Lean.Elab.Tactic.Ext.applyExtTheorem
:::
:::tactic "funext"
:::
# SMT-Inspired Automation
:::tactic "grind"
:::
:::tactic "grind?"
:::
:::tactic "lia"
:::
:::tactic "grobner"
:::
{include 0 Manual.Tactics.Reference.Simp}
# Rewriting
%%%
tag := "tactic-ref-rw"
%%%
:::tactic "rw"
:::
:::tactic "rewrite"
:::
:::tactic "erw"
:::
:::tactic Lean.Parser.Tactic.tacticRwa__
:::
{docstring Lean.Meta.Rewrite.Config +allowMissing}
{docstring Lean.Meta.Occurrences}
{docstring Lean.Meta.TransparencyMode +allowMissing}
{docstring Lean.Meta.Rewrite.NewGoals +allowMissing}
:::tactic "unfold"
Implemented by {name}`Lean.Elab.Tactic.evalUnfold`.
:::
:::tactic "replace"
:::
:::tactic "delta"
:::
# Inductive Types
%%%
tag := "tactic-ref-inductive"
%%%
## Introduction
%%%
tag := "tactic-ref-inductive-intro"
%%%
:::tactic "constructor"
:::
:::tactic "injection"
:::
:::tactic "injections"
:::
:::tactic "left"
:::
:::tactic "right"
:::
## Elimination
%%%
tag := "tactic-ref-inductive-elim"
%%%
Elimination tactics use {ref "recursors"}[recursors] and the automatically-derived {ref "recursor-elaboration-helpers"}[`casesOn` helper] to implement induction and case splitting.
The {tech}[subgoals] that result from these tactics are determined by the types of the minor premises of the eliminators, and using different eliminators with the {keyword}`using` option results in different subgoals.
:::::leanSection
```lean -show
variable {n : Nat}
```
::::example "Choosing Eliminators"
:::tacticExample
```setup
intro n i
```
{goal -show}`∀(n : Nat) (i : Fin (n + 1)), 0 + i = i`
```pre -show
n : Nat
i : Fin (n + 1)
⊢ 0 + i = i
```
When attempting to prove that {lean}`∀(i : Fin (n + 1)), 0 + i = i`, after introducing the hypotheses the tactic {tacticStep}`induction i` results in:
```post
case mk
n val✝ : Nat
isLt✝ : val✝ < n + 1
⊢ 0 + ⟨val✝, isLt✝⟩ = ⟨val✝, isLt✝⟩
```
This is because {name}`Fin` is a {tech}[structure] with a single non-recursive constructor.
Its recursor has a single minor premise for this constructor:
```signature
Fin.rec.{u} {n : Nat} {motive : Fin n → Sort u}
(mk : (val : Nat) →
(isLt : val < n) →
motive ⟨val, isLt⟩)
(t : Fin n) : motive t
```
:::
:::tacticExample
```setup
intro n i
```
{goal -show}`∀(n : Nat) (i : Fin (n + 1)), 0 + i = i`
```pre -show
n : Nat
i : Fin (n + 1)
⊢ 0 + i = i
```
Using the tactic {tacticStep}`induction i using Fin.induction` instead results in:
```post
case zero
n : Nat
⊢ 0 + 0 = 0
case succ
n : Nat
i✝ : Fin n
a✝ : 0 + i✝.castSucc = i✝.castSucc
⊢ 0 + i✝.succ = i✝.succ
```
{name}`Fin.induction` is an alternative eliminator that implements induction on the underlying {name}`Nat`:
```signature
Fin.induction.{u} {n : Nat}
{motive : Fin (n + 1) → Sort u}
(zero : motive 0)
(succ : (i : Fin n) →
motive i.castSucc →
motive i.succ)
(i : Fin (n + 1)) : motive i
```
:::
::::
:::::
{deftech}[Custom eliminators] can be registered using the {attr}`induction_eliminator` and {attr}`cases_eliminator` attributes.
The eliminator is registered for its explicit targets (i.e. those that are explicit, rather than implicit, parameters to the eliminator function) and will be applied when {tactic}`induction` or {tactic}`cases` is used on targets of those types.
When present, custom eliminators take precedence over recursors.
Setting {option}`tactic.customEliminators` to {lean}`false` disables the use of custom eliminators.
:::syntax attr (title := "Custom Eliminators")
The {attr}`induction_eliminator` attribute registers an eliminator for use by the {tactic}`induction` tactic.
```grammar
induction_eliminator
```
The {attr}`cases_eliminator` attribute registers an eliminator for use by the {tactic}`cases` tactic.
```grammar
cases_eliminator
```
:::
:::tactic "cases"
:::
:::tactic "rcases"
:::
:::tactic "fun_cases"
:::
:::tactic "induction"
:::
:::tactic "fun_induction"
:::
:::tactic "nofun"
:::
:::tactic "nomatch"
:::
# Library Search
%%%
tag := "tactic-ref-search"
%%%
The library search tactics are intended for interactive use.
When run, they search the Lean library for lemmas or rewrite rules that could be applicable in the current situation, and suggests a new tactic.
These tactics should not be left in a proof; rather, their suggestions should be incorporated.
:::tactic "exact?"
:::
:::tactic "apply?"
:::
:::tacticExample
{goal -show}`∀ (i j k : Nat), i < j → j < k → i < k`
```setup
intro i j k h1 h2
```
In this proof state:
```pre
i j k : Nat
h1 : i < j
h2 : j < k
⊢ i < k
```
invoking {tacticStep}`apply?` suggests:
```tacticOutput
Try this:
[apply] exact Nat.lt_trans h1 h2
```
```post -show
```
:::
:::tactic "rw?"
:::
# Case Analysis
%%%
tag := "tactic-ref-cases"
%%%
:::tactic "split"
:::
:::tactic "by_cases"
:::
# Decision Procedures
%%%
tag := "tactic-ref-decision"
%%%
:::tactic Lean.Parser.Tactic.decide (show := "decide")
:::
:::tactic Lean.Parser.Tactic.nativeDecide (show := "native_decide")
:::
:::tactic "omega"
:::
:::tactic "bv_omega"
:::
## SAT Solver Integration
%%%
tag := "tactic-ref-sat"
%%%
:::tactic "bv_decide"
:::
:::tactic "bv_normalize"
:::
:::tactic "bv_check"
:::
:::tactic Lean.Parser.Tactic.bvTraceMacro
:::
# Controlling Reduction
%%%
tag := "tactic-reducibility"
%%%
:::tactic Lean.Parser.Tactic.withReducible
:::
:::tactic Lean.Parser.Tactic.withReducibleAndInstances
:::
:::tactic "with_unfolding_all"
:::
:::tactic "with_unfolding_none"
:::
# Control Flow
%%%
tag := "tactic-ref-control"
%%%
:::tactic "skip"
:::
:::tactic Lean.Parser.Tactic.guardHyp
:::
:::tactic Lean.Parser.Tactic.guardTarget
:::
:::tactic Lean.Parser.Tactic.guardExpr
:::
:::tactic "done"
:::
:::tactic "sleep"
:::
:::tactic "stop"
:::
# Term Elaboration Backends
%%%
tag := "tactic-ref-term-helpers"
%%%
These tactics are used during elaboration of terms to satisfy obligations that arise.
:::tactic tacticDecreasing_with_
:::
:::tactic "get_elem_tactic"
:::
:::tactic "get_elem_tactic_trivial"
:::
# Debugging Utilities
%%%
tag := "tactic-ref-debug"
%%%
:::tactic "sorry"
:::
:::tactic "admit"
:::
:::tactic "dbg_trace"
:::
:::tactic Lean.Parser.Tactic.traceState
:::
:::tactic Lean.Parser.Tactic.traceMessage
:::
# Suggestions
:::tactic "∎"
:::
:::tactic "suggestions"
:::
# Other
%%%
tag := "tactic-ref-other"
%%%
:::tactic "trivial"
:::
:::tactic "solve"
:::
:::tactic "and_intros"
:::
:::tactic "infer_instance"
:::
:::tactic "expose_names"
:::
:::tactic Lean.Parser.Tactic.tacticUnhygienic_
:::
:::tactic Lean.Parser.Tactic.runTac
:::
# Verification Condition Generation
%%%
tag := "tactic-ref-mvcgen"
%%%
:::tactic "mvcgen"
:::
## Tactics for Stateful Goals in `Std.Do.SPred`
%%%
tag := "tactic-ref-spred"
%%%
### Starting and Stopping the Proof Mode
:::tactic "mstart"
:::
:::tactic "mstop"
:::
:::tactic "mleave"
:::
### Proving a Stateful Goal
:::tactic "mspec"
:::
:::tactic Lean.Parser.Tactic.mintroMacro
:::
:::tactic "mexact"
:::
:::tactic "massumption"
:::
:::tactic "mrefine"
:::
:::tactic "mconstructor"
:::
:::tactic "mleft"
:::
:::tactic "mright"
:::
:::tactic "mexists"
:::
:::tactic "mpure_intro"
:::
:::tactic "mexfalso"
:::
### Manipulating Stateful Hypotheses
:::tactic "mclear"
:::
:::tactic "mdup"
:::
:::tactic "mhave"
:::
:::tactic "mreplace"
:::
:::tactic "mspecialize"
:::
:::tactic "mspecialize_pure"
:::
:::tactic "mcases"
:::
:::tactic "mrename_i"
:::
:::tactic "mpure"
:::
:::tactic "mframe"
::: |
reference-manual/Manual/Tactics/Conv.lean | import VersoManual
import Lean.Parser.Term
import Manual.Meta
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.unusedVariables false
#doc (Manual) "Targeted Rewriting with {tactic}`conv`" =>
%%%
tag := "conv"
%%%
The {tactic}`conv`, or conversion, tactic allows targeted rewriting within a goal.
The argument to {tactic}`conv` is written in a separate language that interoperates with the main tactic language; it features commands to navigate to specific subterms within the goal along with commands that allow these subterms to be rewritten.
{tactic}`conv` is useful when rewrites should only be applied in part of a goal (e.g. only on one side of an equality), rather than across the board, or when rewrites should be applied underneath a binder that prevents tactics like {tactic}`rw` from accessing the term.
The conversion tactic language is very similar to the main tactic language: it uses the same proof states, tactics work primarily on the main goal and may either fail or succeed with a sequence of new goals, and macro expansion is interleaved with tactic execution.
Unlike the main tactic language, in which tactics are intended to eventually solve goals, the {tactic}`conv` tactic is used to _change_ a goal so that it becomes amenable to further processing in the main tactic language.
Goals that are intended to be rewritten with {tactic}`conv` are shown with a vertical bar instead of a turnstile.
:::tactic "conv"
:::
::::example "Navigation and Rewriting with {tactic}`conv`"
In this example, there are multiple instances of addition, and {tactic}`rw` would by default rewrite the first instance that it encounters.
Using {tactic}`conv` to navigate to the specific subterm before rewriting leaves {tactic}`rw` no choice but to rewrite the correct term.
```lean
example (x y z : Nat) : x + (y + z) = (x + z) + y := by
conv =>
lhs
arg 2
rw [Nat.add_comm]
rw [Nat.add_assoc]
```
::::
::::example "Rewriting Under Binders with {tactic}`conv`"
In this example, addition occurs under binders, so {tactic}`rw` can't be used.
However, after using {tactic}`conv` to navigate to the function body, it succeeds.
The nested use of {tactic}`conv` causes control to return to the current position in the term after performing further conversions on one of its subterms.
Because the goal is a reflexive equation after rewriting, {tactic}`conv` automatically closes it.
```lean
example :
(fun (x y z : Nat) =>
x + (y + z))
=
(fun x y z =>
(z + x) + y)
:= by
conv =>
lhs
intro x y z
conv =>
arg 2
rw [Nat.add_comm]
rw [← Nat.add_assoc]
arg 1
rw [Nat.add_comm]
```
::::
# Control Structures
%%%
tag := "conv-control"
%%%
:::conv first (show := "first")
:::
:::conv convTry_ (show := "try")
:::
:::conv «conv_<;>_» (show:="<;>") +allowMissing
:::
:::conv convRepeat_ (show := "repeat")
:::
:::conv skip (show := "skip")
:::
:::conv nestedConv (show := "{ ... }")
:::
:::conv paren (show := "( ... )")
:::
:::conv convDone (show := "done")
:::
# Goal Selection
%%%
tag := "conv-goals"
%%%
:::conv allGoals (show := "all_goals")
:::
:::conv anyGoals (show := "any_goals")
:::
:::conv case (show := "case ... => ...")
:::
:::conv case' (show := "case' ... => ...")
:::
:::conv «convNext__=>_» (show := "next ... => ...")
:::
:::conv focus (show := "focus")
:::
:::conv «conv·._» (show := ". ...")
:::
:::conv «conv·._» (show := "· ...")
:::
:::conv failIfSuccess (show := "fail_if_success")
:::
# Navigation
%%%
tag := "conv-nav"
%%%
:::conv lhs (show := "lhs")
:::
:::conv rhs (show := "rhs")
:::
:::conv fun (show := "fun")
:::
:::conv congr (show := "congr")
:::
:::conv arg (show := "arg [@]i")
:::
:::syntax Lean.Parser.Tactic.Conv.enterArg (title := "Arguments to {keyword}`enter`")
```grammar
$i:num
```
```grammar
@$i:num
```
```grammar
$x:ident
```
:::
:::conv enter (show := "enter")
:::
:::conv pattern (show := "pattern")
:::
:::conv ext (show := "ext")
:::
:::conv convArgs (show := "args")
:::
:::conv convLeft (show := "left")
:::
:::conv convRight (show := "right")
:::
:::conv convIntro___ (show := "intro")
:::
# Changing the Goal
%%%
tag := "conv-change"
%%%
## Reduction
%%%
tag := "conv-reduction"
%%%
:::conv whnf (show := "whnf")
:::
:::conv reduce (show := "reduce")
:::
:::conv zeta (show := "zeta")
:::
:::conv delta (show := "delta")
:::
:::conv unfold (show := "unfold")
:::
## Simplification
%%%
tag := "conv-simp"
%%%
:::conv simp (show := "simp")
:::
:::conv dsimp (show := "dsimp")
:::
:::conv simpMatch (show := "simp_match")
:::
## Rewriting
%%%
tag := "conv-rw"
%%%
:::conv change (show := "change")
:::
:::conv rewrite (show := "rewrite")
:::
:::conv convRw__ (show := "rw")
:::
:::conv convErw__ (show := "erw")
:::
:::conv convApply_ (show := "apply")
:::
# Nested Tactics
%%%
tag := "conv-nested"
%%%
:::tactic Lean.Parser.Tactic.Conv.convTactic
:::
:::conv nestedTactic (show := "tactic")
:::
:::conv nestedTacticCore (show := "tactic'")
:::
:::tactic Lean.Parser.Tactic.Conv.convTactic (show := "conv'")
:::
:::conv convConvSeq (show := "conv => ...")
:::
# Debugging Utilities
%%%
tag := "conv-debug"
%%%
:::conv convTrace_state (show := "trace_state")
:::
# Other
%%%
tag := "conv-other"
%%%
:::conv convRfl (show := "rfl")
:::
:::conv normCast (show := "norm_cast")
::: |
reference-manual/Manual/Tactics/Custom.lean | import VersoManual
import Lean.Parser.Term
import Manual.Meta
import Manual.Tactics.Reference
import Manual.Tactics.Conv
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.unusedVariables false
set_option verso.docstring.allowMissing true
open Lean.Elab.Tactic
#doc (Manual) "Custom Tactics" =>
%%%
tag := "custom-tactics"
%%%
```lean -show
open Lean
```
Tactics are productions in the syntax category `tactic`. {TODO}[xref macro for syntax\_cats]
Given the syntax of a tactic, the tactic interpreter is responsible for carrying out actions in the tactic monad {name}`TacticM`, which is a wrapper around Lean's term elaborator that keeps track of the additional state needed to execute tactics.
A custom tactic consists of an extension to the `tactic` category along with either:
* a {tech}[macro] that translates the new syntax into existing syntax, or
* an elaborator that carries out {name}`TacticM` actions to implement the tactic.
# Tactic Macros
%%%
tag := "tactic-macros"
%%%
The easiest way to define a new tactic is as a {tech}[macro] that expands into already-existing tactics.
Macro expansion is interleaved with tactic execution.
The tactic interpreter first expands tactic macros just before they are to be interpreted.
Because tactic macros are not fully expanded prior to running a tactic script, they can use recursion; as long as the recursive occurrence of the macro syntax is beneath a tactic that can be executed, there will not be an infinite chain of expansion.
::::keepEnv
:::example "Recursive tactic macro"
This recursive implementation of a tactic akin to {tactic}`repeat` is defined via macro expansion.
When the argument `$t` fails, the recursive occurrence of {tactic}`rep` is never invoked, and is thus never macro expanded.
```lean
syntax "rep" tactic : tactic
macro_rules
| `(tactic|rep $t) =>
`(tactic|
first
| $t; rep $t
| skip)
example : 0 ≤ 4 := by
rep (apply Nat.le.step)
apply Nat.le.refl
```
:::
::::
Like other Lean macros, tactic macros are {tech (key := "hygiene")}[hygienic].
References to global names are resolved when the macro is defined, and names introduced by the tactic macro cannot capture names from its invocation site.
When defining a tactic macro, it's important to specify that the syntax being matched or constructed is for the syntax category `tactic`.
Otherwise, the syntax will be interpreted as that of a term, which will match against or construct an incorrect AST for tactics.
## Extensible Tactic Macros
%%%
tag := "tactic-macro-extension"
%%%
Because macro expansion can fail, {TODO}[xref] multiple macros can match the same syntax, allowing backtracking.
Tactic macros take this further: even if a tactic macro expands successfully, if the expansion fails when interpreted, the tactic interpreter will attempt the next expansion.
This is used to make a number of Lean's built-in tactics extensible—new behavior can be added to a tactic by adding a {keywordOf Lean.Parser.Command.macro_rules}`macro_rules` declaration.
::::keepEnv
:::example "Extending {tactic}`trivial`"
The {tactic}`trivial`, which is used by many other tactics to quickly dispatch subgoals that are not worth bothering the user with, is designed to be extended through new macro expansions.
Lean's default {lean}`trivial` can't solve {lean}`IsEmpty []` goals:
```lean
def IsEmpty (xs : List α) : Prop :=
¬ xs ≠ []
```
```lean +error
example (α : Type u) : IsEmpty (α := α) [] := by trivial
```
The error message is an artifact of {tactic}`trivial` trying {tactic}`assumption` last.
Adding another expansion allows {tactic}`trivial` to take care of these goals:
```lean
def emptyIsEmpty : IsEmpty (α := α) [] := by simp [IsEmpty]
macro_rules | `(tactic|trivial) => `(tactic|exact emptyIsEmpty)
example (α : Type u) : IsEmpty (α := α) [] := by
trivial
```
:::
::::
::::keepEnv
:::example "Expansion Backtracking"
Macro expansion can induce backtracking when the failure arises from any part of the expanded syntax.
An infix version of {tactic}`first` can be defined by providing multiple expansions in separate {keywordOf Lean.Parser.Command.macro_rules}`macro_rules` declarations:
```lean
syntax tactic "<|||>" tactic : tactic
macro_rules
| `(tactic|$t1 <|||> $t2) => pure t1
macro_rules
| `(tactic|$t1 <|||> $t2) => pure t2
example : 2 = 2 := by
rfl <|||> apply And.intro
example : 2 = 2 := by
apply And.intro <|||> rfl
```
Multiple {keywordOf Lean.Parser.Command.macro_rules}`macro_rules` declarations are needed because each defines a pattern-matching function that will always take the first matching alternative.
Backtracking is at the granularity of {keywordOf Lean.Parser.Command.macro_rules}`macro_rules` declarations, not their individual cases.
:::
:::: |
reference-manual/Manual/Tactics/Reference/Simp.lean | import VersoManual
import Lean.Parser.Term
import Manual.Meta
open Verso.Genre Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.unusedVariables false
#doc (Manual) "Simplification" =>
%%%
tag := "simp-tactics"
%%%
The simplifier is described in greater detail in {ref "the-simplifier"}[its dedicated chapter].
:::tactic "simp"
:::
:::tactic "simp!"
:::
:::tactic "simp?"
:::
:::tactic "simp?!"
:::
:::tactic "simp_arith"
:::
:::tactic "simp_arith!"
:::
:::tactic "dsimp"
:::
:::tactic "dsimp!"
:::
:::tactic "dsimp?"
:::
:::tactic "dsimp?!"
:::
:::tactic "simp_all"
:::
:::tactic "simp_all!"
:::
:::tactic "simp_all?"
:::
:::tactic "simp_all?!"
:::
:::tactic "simp_all_arith"
:::
:::tactic "simp_all_arith!"
:::
:::tactic "simpa"
:::
:::tactic "simpa!"
:::
:::tactic "simpa?"
:::
:::tactic "simpa?!"
:::
:::tactic "simp_wf"
::: |
reference-manual/Manual/IO/Files.lean | import VersoManual
import Manual.Meta
import Lean.Parser.Command
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.unusedVariables false
#doc (Manual) "Files, File Handles, and Streams" =>
Lean provides a consistent filesystem API on all supported platforms.
These are the key concepts:
: {deftech}[Files]
Files are an abstraction provided by operating systems that provide random access to persistently-stored data, organized hierarchically into directories.
: {deftech}[Directories]
Directories, also known as _folders_, may contain files or other directories.
Fundamentally, a directory maps names to the files and/or directories that it contains.
: {deftech}[File Handles]
File handles ({name IO.FS.Handle}`Handle`) are abstract references to files that have been opened for reading and/or writing.
A file handle maintains a mode that determines whether reading and/or writing are allowed, along with a cursor that points at a specific location in the file.
Reading from or writing to a file handle advances the cursor.
File handles may be {deftech}[buffered], which means that reading from a file handle may not return the current contents of the persistent data, and writing to a file handle may not modify them immediately.
: Paths
Files are primarily accessed via {deftech}_paths_ ({name}`System.FilePath`).
A path is a sequence of directory names, potentially terminated by a file name.
They are represented by strings in which separator characters {margin}[The current platform's separator characters are listed in {name}`System.FilePath.pathSeparators`.] delimit the names.
The details of paths are platform-specific.
{deftech}[Absolute paths] begin in a {deftech}_root directory_; some operating systems have a single root, while others may have multiple root directories.
Relative paths do not begin in a root directory and require that some other directory be taken as a starting point.
In addition to directories, paths may contain the special directory names `.`, which refers to the directory in which it is found, and `..`, which refers to prior directory in the path.
Filenames, and thus paths, may end in one or more {deftech}_extensions_ that identify the file's type.
Extensions are delimited by the character {name}`System.FilePath.extSeparator`.
On some platforms, executable files have a special extension ({name}`System.FilePath.exeExtension`).
: {deftech}[Streams]
Streams are a higher-level abstraction over files, both providing additional functionality and hiding some details of files.
While {tech}[file handles] are essentially a thin wrapper around the operating system's representation, streams are implemented in Lean as a structure called {lean}`IO.FS.Stream`.
Because streams are implemented in Lean, user code can create additional streams, which can be used seamlessly together with those provided in the standard library.
# Low-Level File API
At the lowest level, files are explicitly opened using {name IO.FS.Handle.mk}`Handle.mk`.
When the last reference to the handle object is dropped, the file is closed.
There is no explicit way to close a file handle other than by ensuring that there are no references to it.
{docstring IO.FS.Handle}
{docstring IO.FS.Handle.mk}
{docstring IO.FS.Mode}
{docstring IO.FS.Handle.read}
{docstring IO.FS.Handle.readToEnd}
{docstring IO.FS.Handle.readBinToEnd}
{docstring IO.FS.Handle.readBinToEndInto}
{docstring IO.FS.Handle.getLine}
{docstring IO.FS.Handle.write}
{docstring IO.FS.Handle.putStr}
{docstring IO.FS.Handle.putStrLn}
{docstring IO.FS.Handle.flush}
{docstring IO.FS.Handle.rewind}
{docstring IO.FS.Handle.truncate}
{docstring IO.FS.Handle.isTty}
{docstring IO.FS.Handle.lock}
{docstring IO.FS.Handle.tryLock}
{docstring IO.FS.Handle.unlock}
::::example "One File, Multiple Handles"
This program has two handles to the same file.
Because file I/O may be buffered independently for each handle, {name IO.FS.Handle.flush}`Handle.flush` should be called when the buffers need to be synchronized with the file's actual contents.
Here, the two handles proceed in lock-step through the file, with one of them a single byte ahead of the other.
The first handle is used to count the number of occurrences of `'A'`, while the second is used to replace each `'A'` with `'!'`.
The second handle is opened in {name IO.FS.Mode.readWrite}`readWrite` mode rather than {name IO.FS.Mode.write}`write` mode because opening an existing file in {name IO.FS.Mode.write}`write` mode replaces it with an empty file.
In this case, the buffers don't need to be flushed during execution because modifications occur only to parts of the file that will not be read again, but the write handle should be flushed after the loop has completed.
:::ioExample
```ioLean
open IO.FS (Handle)
def main : IO Unit := do
IO.println s!"Starting contents: '{(← IO.FS.readFile "data").trimAscii}'"
let h ← Handle.mk "data" .read
let h' ← Handle.mk "data" .readWrite
h'.rewind
let mut count := 0
let mut buf : ByteArray ← h.read 1
while ok : buf.size = 1 do
if Char.ofUInt8 buf[0] == 'A' then
count := count + 1
h'.write (ByteArray.empty.push '!'.toUInt8)
else
h'.write buf
buf ← h.read 1
h'.flush
IO.println s!"Count: {count}"
IO.println s!"Contents: '{(← IO.FS.readFile "data").trimAscii}'"
```
When run on this file:
```inputFile "data"
AABAABCDAB
```
the program outputs:
```stdout
Starting contents: 'AABAABCDAB'
Count: 5
Contents: '!!B!!BCD!B'
```
```stderr -show
```
Afterwards, the file contains:
```outputFile "data"
!!B!!BCD!B
```
:::
::::
# Streams
{docstring IO.FS.Stream}
{docstring IO.FS.Stream.ofBuffer}
{docstring IO.FS.Stream.ofHandle}
{docstring IO.FS.Stream.putStrLn}
{docstring IO.FS.Stream.Buffer}
# Paths
Paths are represented by strings.
Different platforms have different conventions for paths: some use slashes (`/`) as directory separators, others use backslashes (`\`).
Some are case-sensitive, others are not.
Different Unicode encodings and normal forms may be used to represent filenames, and some platforms consider filenames to be byte sequences rather than strings.
A string that represents an {tech}[absolute path] on one system may not even be a valid path on another system.
To write Lean code that is as compatible as possible with multiple systems, it can be helpful to use Lean's path manipulation primitives instead of raw string manipulation.
Helpers such as {name}`System.FilePath.join` take platform-specific rules for absolute paths into account, {name}`System.FilePath.pathSeparator` contains the appropriate path separator for the current platform, and {name}`System.FilePath.exeExtension` contains any necessary extension for executable files.
Avoid hard-coding these rules.
There is an instance of the {lean}`Div` type class for {name System.FilePath}`FilePath` which allows the slash operator to be used to concatenate paths.
{docstring System.FilePath +allowMissing}
{docstring System.mkFilePath}
{docstring System.FilePath.join}
{docstring System.FilePath.normalize}
{docstring System.FilePath.isAbsolute}
{docstring System.FilePath.isRelative}
{docstring System.FilePath.parent}
{docstring System.FilePath.components}
{docstring System.FilePath.fileName}
{docstring System.FilePath.fileStem}
{docstring System.FilePath.extension}
{docstring System.FilePath.addExtension}
{docstring System.FilePath.withExtension}
{docstring System.FilePath.withFileName}
{docstring System.FilePath.pathSeparator}
{docstring System.FilePath.pathSeparators}
{docstring System.FilePath.extSeparator}
{docstring System.FilePath.exeExtension}
# Interacting with the Filesystem
Some operations on paths consult the filesystem.
{docstring IO.FS.Metadata}
{docstring System.FilePath.metadata}
{docstring System.FilePath.symlinkMetadata}
{docstring System.FilePath.pathExists}
{docstring System.FilePath.isDir}
{docstring IO.FS.DirEntry}
{docstring IO.FS.DirEntry.path}
{docstring System.FilePath.readDir}
{docstring System.FilePath.walkDir}
{docstring IO.AccessRight +allowMissing}
{docstring IO.AccessRight.flags}
{docstring IO.FileRight}
{docstring IO.FileRight.flags}
{docstring IO.setAccessRights}
{docstring IO.FS.removeFile}
{docstring IO.FS.rename}
{docstring IO.FS.removeDir}
{docstring IO.FS.lines}
{docstring IO.FS.withTempFile}
{docstring IO.FS.withTempDir}
{docstring IO.FS.createDirAll}
{docstring IO.FS.writeBinFile}
{docstring IO.FS.withFile}
{docstring IO.FS.removeDirAll}
{docstring IO.FS.createTempFile}
{docstring IO.FS.createTempDir}
{docstring IO.FS.readFile}
{docstring IO.FS.realPath}
{docstring IO.FS.writeFile}
{docstring IO.FS.readBinFile}
{docstring IO.FS.createDir}
# Standard I/O
%%%
tag := "stdio"
%%%
On operating systems that are derived from or inspired by Unix, {deftech}_standard input_, {deftech}_standard output_, and {deftech}_standard error_ are the names of three streams that are available in each process.
Generally, programs are expected to read from standard input, write ordinary output to the standard output, and error messages to the standard error.
By default, standard input receives input from the console, while standard output and standard error output to the console, but all three are often redirected to or from pipes or files.
Rather than providing direct access to the operating system's standard I/O facilities, Lean wraps them in {name IO.FS.Stream}`Stream`s.
Additionally, the {lean}`IO` monad contains special support for replacing or locally overriding them.
This extra level of indirection makes it possible to redirect input and output within a Lean program.
{docstring IO.getStdin}
::::example "Reading from Standard Input"
In this example, {lean}`IO.getStdin` and {lean}`IO.getStdout` are used to get the current standard input and output, respectively.
These can be read from and written to.
:::ioExample
```ioLean
def main : IO Unit := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
stdout.putStrLn "Who is it?"
let name ← stdin.getLine
stdout.putStr "Hello, "
stdout.putStrLn name
```
With this standard input:
```stdin
Lean user
```
the standard output is:
```stdout
Who is it?
Hello, Lean user
```
:::
::::
{docstring IO.setStdin}
{docstring IO.withStdin}
{docstring IO.getStdout}
{docstring IO.setStdout}
{docstring IO.withStdout}
{docstring IO.getStderr}
{docstring IO.setStderr}
{docstring IO.withStderr}
{docstring IO.FS.withIsolatedStreams}
::::keepEnv
:::example "Redirecting Standard I/O to Strings"
The {lean}`countdown` function counts down from a specified number, writing its progress to standard output.
Using `IO.FS.withIsolatedStreams`, this output can be redirected to a string.
```lean (name := countdown)
def countdown : Nat → IO Unit
| 0 =>
IO.println "Blastoff!"
| n + 1 => do
IO.println s!"{n + 1}"
countdown n
def runCountdown : IO String := do
let (output, ()) ← IO.FS.withIsolatedStreams (countdown 10)
return output
#eval runCountdown
```
Running {lean}`countdown` yields a string that contains the output:
```leanOutput countdown
"10\n9\n8\n7\n6\n5\n4\n3\n2\n1\nBlastoff!\n"
```
:::
::::
# Files and Directories
{docstring IO.currentDir}
{docstring IO.appPath}
{docstring IO.appDir} |
reference-manual/Manual/IO/Ref.lean | import VersoManual
import Manual.Meta
import Manual.Papers
import Lean.Parser.Command
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.unusedVariables false
#doc (Manual) "Mutable References" =>
While ordinary {tech}[state monads] encode stateful computations with tuples that track the contents of the state along with the computation's value, Lean's runtime system also provides mutable references that are always backed by mutable memory cells.
Mutable references have a type {lean}`IO.Ref` that indicates that a cell is mutable, and reads and writes must be explicit.
{lean}`IO.Ref` is implemented using {lean}`ST.Ref`, so the entire {ref "mutable-st-references"}[{lean}`ST.Ref` API] may also be used with {lean}`IO.Ref`.
{docstring IO.Ref}
{docstring IO.mkRef}
# State Transformers
%%%
tag := "mutable-st-references"
%%%
Mutable references are often useful in contexts where arbitrary side effects are undesired.
They can give a significant speedup when Lean is unable to optimize pure operations into mutation, and some algorithms are more easily expressed using mutable references than with state monads.
Additionally, it has a property that other side effects do not have: if all of the mutable references used by a piece of code are created during its execution, and no mutable references from the code escape to other code, then the result of evaluation is deterministic.
The {lean}`ST` monad is a restricted version of {lean}`IO` in which mutable state is the only side effect, and mutable references cannot escape.{margin}[{lean}`ST` was first described by {citehere launchbury94}[].]
{lean}`ST` takes a type parameter that is never used to classify any terms.
The {lean}`runST` function, which allow escape from {lean}`ST`, requires that the {lean}`ST` action that is passed to it can instantiate this type parameter with _any_ type.
This unknown type does not exist except as a parameter to a function, which means that values whose types are “marked” by it cannot escape its scope.
{docstring ST}
{docstring runST}
As with {lean}`IO` and {lean}`EIO`, there is also a variation of {lean}`ST` that takes a custom error type as a parameter.
Here, {lean}`ST` is analogous to {lean}`BaseIO` rather than {lean}`IO`, because {lean}`ST` cannot result in errors being thrown.
{docstring EST}
{docstring runEST}
{docstring ST.Ref +hideFields}
{docstring ST.mkRef}
## Reading and Writing
{docstring ST.Ref.get}
{docstring ST.Ref.set}
::::example "Data races with {name ST.Ref.get}`get` and {name ST.Ref.set}`set`"
:::ioExample
```ioLean
def main : IO Unit := do
let balance ← IO.mkRef (100 : Int)
let mut orders := #[]
IO.println "Sending out orders..."
for _ in [0:100] do
let o ← IO.asTask (prio := .dedicated) do
let cost ← IO.rand 1 100
IO.sleep (← IO.rand 10 100).toUInt32
if cost < (← balance.get) then
IO.sleep (← IO.rand 10 100).toUInt32
balance.set ((← balance.get) - cost)
orders := orders.push o
-- Wait until all orders are completed
for o in orders do
match o.get with
| .ok () => pure ()
| .error e => throw e
if (← balance.get) < 0 then
IO.eprintln "Final balance is negative!"
else
IO.println "Final balance is zero or positive."
```
```stdout
Sending out orders...
```
```stderr
Final balance is negative!
```
:::
::::
{docstring ST.Ref.modify}
::::example "Avoiding data races with {name ST.Ref.modify}`modify`"
This program launches 100 threads.
Each thread simulates a purchase attempt: it generates a random price, and if the account balance is sufficient, it decrements it by the price.
The balance check and the computation of the new value occur in an atomic call to {name}`ST.Ref.modify`.
:::ioExample
```ioLean
def main : IO Unit := do
let balance ← IO.mkRef (100 : Int)
let mut orders := #[]
IO.println "Sending out orders..."
for _ in [0:100] do
let o ← IO.asTask (prio := .dedicated) do
let cost ← IO.rand 1 100
IO.sleep (← IO.rand 10 100).toUInt32
balance.modify fun b =>
if cost < b then
b - cost
else b
orders := orders.push o
-- Wait until all orders are completed
for o in orders do
match o.get with
| .ok () => pure ()
| .error e => throw e
if (← balance.get) < 0 then
IO.eprintln "Final balance negative!"
else
IO.println "Final balance is zero or positive."
```
```stdout
Sending out orders...
Final balance is zero or positive.
```
```stderr
```
:::
::::
{docstring ST.Ref.modifyGet}
{docstring ST.Ref.swap}
## Comparisons
{docstring ST.Ref.ptrEq}
## `ST`-Backed State Monads
{docstring ST.Ref.toMonadStateOf}
# Concurrency
%%%
tag := "ref-locks"
%%%
Mutable references can be used as a locking mechanism.
_Taking_ the contents of the reference causes attempts to take it or to read from it to block until it is {name ST.Ref.set}`set` again.
This is a low-level feature that can be used to implement other synchronization mechanisms; it's usually better to rely on higher-level abstractions when possible.
{docstring ST.Ref.take}
::::example "Reference Cells as Locks"
This program launches 100 threads.
Each thread simulates a purchase attempt: it generates a random price, and if the account balance is sufficient, it decrements it by the price.
If the balance is not sufficient, then it is not decremented.
Because each thread {name ST.Ref.take}`take`s the balance cell prior to checking it and only returns it when it is finished, the cell acts as a lock.
Unlike using {name}`ST.Ref.modify`, which atomically modifies the contents of the cell using a pure function, other {name}`IO` actions may occur in the critical section
This program's `main` function is marked {keywordOf Lean.Parser.Command.declaration}`unsafe` because {name ST.Ref.take}`take` itself is unsafe.
:::ioExample
```ioLean
unsafe def main : IO Unit := do
let balance ← IO.mkRef (100 : Int)
let validationUsed ← IO.mkRef false
let mut orders := #[]
IO.println "Sending out orders..."
for _ in [0:100] do
let o ← IO.asTask (prio := .dedicated) do
let cost ← IO.rand 1 100
IO.sleep (← IO.rand 10 100).toUInt32
let b ← balance.take
if cost ≤ b then
balance.set (b - cost)
else
balance.set b
validationUsed.set true
orders := orders.push o
-- Wait until all orders are completed
for o in orders do
match o.get with
| .ok () => pure ()
| .error e => throw e
if (← validationUsed.get) then
IO.println "Validation prevented a negative balance."
if (← balance.get) < 0 then
IO.eprintln "Final balance negative!"
else
IO.println "Final balance is zero or positive."
```
The program's output is:
```stdout
Sending out orders...
Validation prevented a negative balance.
Final balance is zero or positive.
```
:::
:::: |
reference-manual/Manual/IO/Console.lean | import VersoManual
import Manual.Meta
import Lean.Parser.Command
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.unusedVariables false
#doc (Manual) "Console Output" =>
Lean includes convenience functions for writing to {tech}[standard output] and {tech}[standard error].
All make use of {lean}`ToString` instances, and the varieties whose names end in `-ln` add a newline after the output.
These convenience functions only expose a part of the functionality available {ref "stdio"}[using the standard I/O streams].
In particular, to read a line from standard input, use a combination of {lean}`IO.getStdin` and {lean}`IO.FS.Stream.getLine`.
{docstring IO.print}
{docstring IO.println}
{docstring IO.eprint}
{docstring IO.eprintln}
::::example "Printing"
This program demonstrates all four convenience functions for console I/O.
:::ioExample
```ioLean
def main : IO Unit := do
IO.print "This is the "
IO.print "Lean"
IO.println " language reference."
IO.println "Thank you for reading it!"
IO.eprint "Please report any "
IO.eprint "errors"
IO.eprintln " so they can be corrected."
```
It outputs the following to the standard output:
```stdout
This is the Lean language reference.
Thank you for reading it!
```
and the following to the standard error:
```stderr
Please report any errors so they can be corrected.
```
:::
:::: |
reference-manual/Manual/IO/Threads.lean | import VersoManual
import Manual.Meta
import Lean.Parser.Command
open Manual
open Verso.Genre
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean
set_option pp.rawOnError true
set_option linter.unusedVariables false
#doc (Manual) "Tasks and Threads" =>
%%%
tag := "concurrency"
%%%
:::leanSection
```lean -show
variable {α : Type u}
```
{deftech}_Tasks_ are the fundamental primitive for writing multi-threaded code.
A {lean}`Task α` represents a computation that, at some point, will {tech (key := "resolve promise")}_resolve_ to a value of type `α`; it may be computed on a separate thread.
When a task has resolved, its value can be read; attempting to get the value of a task before it resolves causes the current thread to block until the task has resolved.
Tasks are similar to promises in JavaScript, `JoinHandle` in Rust, and `Future` in Scala.
Tasks may either carry out pure computations or {name}`IO` actions.
The API of pure tasks resembles that of {tech}[thunks]: {name}`Task.spawn` creates a {lean}`Task α` from a function in {lean}`Unit → α`, and {name}`Task.get` waits until the function's value has been computed and then returns it.
The value is cached, so subsequent requests do not need to recompute it.
The key difference lies in when the computation occurs: while the values of thunks are not computed until they are forced, tasks execute opportunistically in a separate thread.
Tasks in {name}`IO` are created using {name}`IO.asTask`.
Similarly, {name}`BaseIO.asTask` and {name}`EIO.asTask` create tasks in other {name}`IO` monads.
These tasks may have side effects, and can communicate with other tasks.
:::
When the last reference to a task is dropped it is {deftech (key := "cancel")}_cancelled_.
Pure tasks created with {name}`Task.spawn` are terminated upon cancellation.
Tasks spawned with {name}`IO.asTask`, {name}`EIO.asTask`, or {name}`BaseIO.asTask` continue executing and must explicitly check for cancellation using {name}`IO.checkCanceled`.
Tasks may be explicitly cancelled using {name}`IO.cancel`.
The Lean runtime maintains a thread pool for running tasks.
The size of the thread pool is determined by the environment variable {envVar +def}`LEAN_NUM_THREADS` if it is set, or by the number of logical processors on the current machine otherwise.
The size of the thread pool is not a hard limit; in certain situations it may be exceeded to avoid deadlocks.
By default, these threads are used to run tasks; each task has a {deftech (key := "task priority")}_priority_ ({name}`Task.Priority`), and higher-priority tasks take precedence over lower-priority tasks.
Tasks may also be assigned to dedicated threads by spawning them with a sufficiently high priority.
{docstring Task (label := "type") +hideStructureConstructor +hideFields}
# Creating Tasks
Pure tasks should typically be created with {name}`Task.spawn`, as {name}`Task.pure` is a task that's already been resolved with the provided value.
Impure tasks are created by one of the {name BaseIO.asTask}`asTask` actions.
## Pure Tasks
Pure tasks may be created outside the {name}`IO` family of monads.
They are terminated when the last reference to them is dropped.
{docstring Task.spawn}
{docstring Task.pure}
## Impure Tasks
When spawning a task with side effects using one of the {name IO.asTask}`asTask` functions, it's important to actually execute the resulting {name}`IO` action.
A task is spawned each time the resulting action is executed, not when {name IO.asTask}`asTask` is called.
Impure tasks continue running even when there are no references to them, though this does result in cancellation being requested.
Cancellation may also be explicitly requested using {name}`IO.cancel`.
The impure task must check for cancellation using {name}`IO.checkCanceled`.
{docstring BaseIO.asTask}
{docstring EIO.asTask}
{docstring IO.asTask}
## Priorities
Task priorities are used by the thread scheduler to assign tasks to threads.
Within the priority range {name Task.Priority.default}`default`–{name Task.Priority.max}`max`, higher-priority tasks always take precedence over lower-priority tasks.
Tasks spawned with priority {name Task.Priority.dedicated}`dedicated` are assigned their own dedicated threads and do not contend with other tasks for the threads in the thread pool.
{docstring Task.Priority}
{docstring Task.Priority.default}
{docstring Task.Priority.max}
{docstring Task.Priority.dedicated}
# Task Results
{docstring Task.get}
{docstring IO.wait}
{docstring IO.waitAny}
# Sequencing Tasks
These operators create new tasks from old ones.
When possible, it's good to use {name}`Task.map` or {name}`Task.bind` instead of manually calling {name}`Task.get` in a new task because they don't temporarily increase the size of the thread pool.
{docstring Task.map}
{docstring Task.bind}
{docstring Task.mapList}
{docstring BaseIO.mapTask}
{docstring EIO.mapTask}
{docstring IO.mapTask}
{docstring BaseIO.mapTasks}
{docstring EIO.mapTasks}
{docstring IO.mapTasks}
{docstring BaseIO.bindTask}
{docstring EIO.bindTask}
{docstring IO.bindTask}
{docstring BaseIO.chainTask}
{docstring EIO.chainTask}
{docstring IO.chainTask}
# Cancellation and Status
Impure tasks should use `IO.checkCanceled` to react to cancellation, which occurs either as a result of `IO.cancel` or when the last reference to the task is dropped.
Pure tasks are terminated automatically upon cancellation.
{docstring IO.cancel}
{docstring IO.checkCanceled}
{docstring IO.hasFinished}
{docstring IO.getTaskState}
{docstring IO.TaskState}
{docstring IO.getTID}
# Promises
Promises represent a value that will be supplied in the future.
Supplying the value is called {deftech (key := "resolve promise")}_resolving_ the promise.
Once created, a promise can be stored in a data structure or passed around like any other value, and attempts to read from it will block until it is resolved.
{docstring IO.Promise}
{docstring IO.Promise.new}
{docstring IO.Promise.isResolved}
{docstring IO.Promise.result?}
{docstring IO.Promise.result!}
{docstring IO.Promise.resultD}
{docstring IO.Promise.resolve}
# Communication Between Tasks
In addition to the types and operations described in this section, {name}`IO.Ref` can be used as a lock.
Taking the reference (using {name ST.Ref.take}`take`) causes other threads to block when reading until the reference is {name ST.Ref.set}`set` again.
This pattern is described in {ref "ref-locks"}[the section on reference cells].
## Channels
The types and functions in this section are available after importing {module}`Std.Sync.Channel`.
{docstring Std.Channel}
{docstring Std.Channel.new}
{docstring Std.Channel.send}
{docstring Std.Channel.recv}
{docstring Std.Channel.forAsync}
{docstring Std.Channel.sync}
{docstring Std.Channel.Sync}
{docstring Std.CloseableChannel}
{docstring Std.CloseableChannel.new}
:::leanSection
```lean -show
variable {m : Type → Type v} {α : Type} [MonadLiftT BaseIO m] [Inhabited α] [Monad m]
```
Synchronous channels can also be read using {keywordOf Lean.Parser.Term.doFor}`for` loops.
In particular, there is an instance of type {inst}`ForIn m (Std.Channel.Sync α) α` for every monad {lean}`m` with a {inst}`MonadLiftT BaseIO m` instance and {lean}`α` with an {inst}`Inhabited α` instance.
:::
## Mutexes
The types and functions in this section are available after importing {module}`Std.Sync.Mutex`.
{docstring Std.Mutex (label := "type") +hideStructureConstructor +hideFields}
{docstring Std.Mutex.new}
{docstring Std.Mutex.atomically}
{docstring Std.Mutex.atomicallyOnce}
{docstring Std.AtomicT}
## Condition Variables
The types and functions in this section are available after importing {module}`Std.Sync.Mutex`.
{docstring Std.Condvar}
{docstring Std.Condvar.new}
{docstring Std.Condvar.wait}
{docstring Std.Condvar.notifyOne}
{docstring Std.Condvar.notifyAll}
{docstring Std.Condvar.waitUntil} |
reference-manual/Manual/Meta/ExpectString.lean | import Lean.Elab.Command
import Lean.Elab.InfoTree
import Verso
open Lean Elab
open Verso Doc
namespace Manual
variable {m : Type → Type} [Monad m] [MonadLog m] [AddMessageContext m] [MonadOptions m]
variable [MonadInfoTree m]
def abbreviateString (what : String) (maxLength : Nat := 30) : String :=
if what.length > maxLength then
(what.take maxLength).copy ++ "…"
else
what
/--
Expects that a string matches some expected form from the document.
If the strings don't match, then a diff is displayed as an error, and a code action to replace the
expected string with the actual one is offered. Strings are compared one line at a time, and only
strings that match `useLine` are considered (by default, all are considered). Lines are compared
modulo `preEq`. The parameter `what` is used in the error message header, in a context "Mismatched
`what`:".
Errors are logged, not thrown; the returned `Bool` indicates whether an error was logged.
-/
def expectString (what : String) (expected : StrLit) (actual : String)
(preEq : String → String := id)
(useLine : String → Bool := fun _ => true) : m Bool := do
let expectedLines := expected.getString.splitOn "\n" |>.filter useLine |>.toArray
let actualLines := actual.splitOn "\n" |>.filter useLine |>.toArray
unless expectedLines.map preEq == actualLines.map preEq do
let diff := Diff.diff expectedLines actualLines
logErrorAt expected m!"Mismatched {what}:\n{Diff.linesToString diff}"
Suggestion.saveSuggestion expected (abbreviateString actual) actual
return false
return true |
reference-manual/Manual/Meta/Instances.lean | module
public import Lean.ToExpr
public import SubVerso.Highlighting.Highlighted
open SubVerso.Highlighting
open Lean
namespace Manual
public section
deriving instance ToExpr for Token.Kind
deriving instance ToExpr for Token
deriving instance ToExpr for Highlighted.Hypothesis
deriving instance ToExpr for Highlighted.Goal
deriving instance ToExpr for Highlighted.MessageContents
deriving instance ToExpr for Highlighted.Span.Kind
deriving instance ToExpr for Highlighted |
reference-manual/Manual/Meta/ModuleExample.lean | import Lean.Elab.Term
import Lean.Elab.Tactic
import Verso.Code.Highlighted
import Verso.Doc.Elab
import Verso.Doc.ArgParse
import Verso.Doc.Suggestion
import SubVerso.Highlighting.Code
import SubVerso.Examples.Messages
import VersoManual
import Manual.Meta.Basic
import Manual.Meta.PPrint
open Verso.Doc.Elab
open Verso.ArgParse
open Verso.Log
open Lean
namespace Manual
structure ModuleConfig where
name : Option Ident := none
moduleName : Option Ident := none
error : Bool := false
«show» : Bool := true
section
variable [Monad m] [MonadError m]
instance : FromArgs ModuleConfig m where
fromArgs := ModuleConfig.mk <$> .named' `name true <*> .named' `moduleName true <*> .flag `error false <*> .flag `show true
end
section
open SubVerso.Highlighting
partial def getMessages (hl : Highlighted) : Array (Nat × Highlighted.Message) :=
let ((), _, out) := go hl (0, #[])
out
where
go : Highlighted → StateM (Nat × Array (Nat × Highlighted.Message)) Unit
| .text s | .unparsed s =>
for c in s.toSlice.chars do
if c == '\n' then modify fun (l, msgs) => (l + 1, msgs) else pure ()
| .token .. => pure ()
| .tactics _ _ _ hl' => go hl'
| .seq xs => xs.forM go
| .span msgs' hl' => do
modify fun (l, msgs) => (l, msgs ++ msgs'.map (fun (sev, m) => (l, ⟨sev, m⟩)))
go hl'
| .point sev contents =>
modify fun (l, msgs) => (l, msgs.push (l, ⟨sev, contents⟩))
def dropBlanks (hl : Highlighted) : Highlighted :=
match hl with
| .text s => .text s.trimAsciiStart.copy
| .seq xs => Id.run do
for h : i in 0...xs.size do
let x := dropBlanks xs[i]
if x.isEmpty then continue
return .seq <| #[x] ++ xs.extract (i + 1) xs.size
return .seq #[]
| _ => hl
end
def logBuild [Monad m] [MonadRef m] [MonadOptions m] [MonadLog m] [AddMessageContext m] (command : String) (out : IO.Process.Output) (blame : Option Syntax := none) : m Unit := do
let blame ←
if let some b := blame then pure b else getRef
let mut buildOut : Array MessageData := #[]
unless out.stdout.isEmpty do
buildOut := buildOut.push <| .trace {cls := `stdout} (toMessageData out.stdout) #[]
unless out.stderr.isEmpty do
buildOut := buildOut.push <| .trace {cls := `stderr} (toMessageData out.stderr) #[]
unless buildOut.isEmpty do
logSilentInfoAt blame <| .trace {cls := `build} m!"{command}" buildOut
def lineStx [Monad m] [MonadFileMap m] (l : Nat) : m Syntax := do
let text ← getFileMap
-- 0-indexed vs 1-indexed requires +1 and +2 here
let r := ⟨text.lineStart (l + 1), text.lineStart (l + 2)⟩
return .ofRange r
@[code_block]
def leanModule : CodeBlockExpanderOf ModuleConfig
| { name, moduleName, error, «show» }, str => do
let line := (← getFileMap).utf8PosToLspPos str.raw.getPos! |>.line
let leanCode := line.fold (fun _ _ s => s.push '\n') "" ++ str.getString ++ "\n"
let hl ← IO.FS.withTempDir fun dirname => do
let u := toString (← IO.monoMsNow)
let dirname := dirname / u
IO.FS.createDirAll dirname
let modName : Name := moduleName.map (·.getId) |>.getD `Main
let out ← IO.Process.output {cmd := "lake", args := #["env", "which", "subverso-extract-mod"]}
if out.exitCode != 0 then
throwError
m!"When running 'lake env which subverso-extract-mod', the exit code was {out.exitCode}\n" ++
m!"Stderr:\n{out.stderr}\n\nStdout:\n{out.stdout}\n\n"
let some «subverso-extract-mod» := out.stdout.splitOn "\n" |>.head?
| throwError "No executable path found"
let «subverso-extract-mod» ← IO.FS.realPath «subverso-extract-mod»
let leanFileName : System.FilePath := (modName.toString : System.FilePath).addExtension "lean"
IO.FS.writeFile (dirname / leanFileName) leanCode
let jsonFile := dirname / s!"{modName}.json"
let out ← IO.Process.output {
cmd := toString «subverso-extract-mod»,
args := #[modName.toString, jsonFile.toString],
cwd := some dirname,
env := #[("LEAN_SRC_PATH", dirname.toString ++ ((":" ++ ·) <$> (← IO.getEnv "LEAN_SRC_PATH")).getD "") ]
}
if out.exitCode != 0 then
throwError
m!"When running '{«subverso-extract-mod»} {modName} {jsonFile}' in {dirname}, the exit code was {out.exitCode}\n" ++
m!"Stderr:\n{out.stderr}\n\nStdout:\n{out.stdout}\n\n"
logBuild s!"subverso-extract-mod {modName} {jsonFile} (in {dirname})" out
let json ← IO.FS.readFile jsonFile
let json ← IO.ofExcept <| Json.parse json
let mod ← match SubVerso.Module.Module.fromJson? json with
| .ok v => pure v
| .error e => throwError m!"Failed to deserialized JSON output as highlighted Lean code. Error: {indentD e}\nJSON: {json}"
let code := mod.items.map (·.code)
pure <| code.foldl (init := .empty) fun hl v => hl ++ v
let msgs := getMessages hl
let hl := dropBlanks hl
if let some name := name then
Verso.Genre.Manual.InlineLean.saveOutputs name.getId (msgs.toList.map (·.2))
let hasError := msgs.any fun m => m.2.severity == .error
for (l, msg) in msgs do
match msg.severity with
| .info => logSilentInfoAt (← lineStx l) msg.toString
| .warning => logSilentAt (← lineStx l) .warning msg.toString
| .error =>
if error then logSilentInfoAt (← lineStx l) msg.toString
else logErrorAt (← lineStx l) msg.toString
if error && !hasError then
logError "Error expected in code block, but none detected."
if !error && hasError then
logError "No error expected in code block, but one occurred."
if «show» then
``(Verso.Doc.Block.other (Verso.Genre.Manual.InlineLean.Block.lean $(quote hl)) #[])
else
``(Verso.Doc.Block.empty)
structure IdentRefConfig where
name : Ident
section
variable [Monad m] [MonadError m]
instance : FromArgs IdentRefConfig m where
fromArgs := IdentRefConfig.mk <$> .positional' `name
end
@[code_block]
def identRef : CodeBlockExpanderOf IdentRefConfig
| { name := x }, _ => pure x
@[role identRef]
def identRefRole : RoleExpanderOf IdentRefConfig
| { name := x }, _ => pure x
structure ModulesConfig where
server : Bool
moduleRoots : List Ident
error : Bool
section
variable [Monad m] [MonadError m]
instance : FromArgs ModulesConfig m where
fromArgs := ModulesConfig.mk <$> .flag `server true <*> .many (.named' `moduleRoot false) <*> .flag `error false
end
open Lean.Doc.Syntax in
partial def getBlocks (block : Syntax) : StateT (NameMap (ModuleConfig × StrLit × Syntax)) DocElabM Syntax := do
if block.getKind == ``Lean.Doc.Syntax.codeblock then
if let `(Lean.Doc.Syntax.codeblock|```$x:ident $args* | $s:str ```) := block then
try
let x' ← Elab.realizeGlobalConstNoOverloadWithInfo x
if x' == ``leanModule then
let n ← mkFreshUserName `code
let blame := mkNullNode <| #[x] ++ args
let argVals ← parseArgs args
let cfg ← fromArgs.run argVals
modify (·.insert n (cfg, s, blame))
let x := mkIdentFrom block n
return ← `(Lean.Doc.Syntax.codeblock|```identRef $x:ident | $(quote "") ```)
catch
| _ => pure ()
match block with
| .node i k xs => do
let args ← xs.mapM getBlocks
return Syntax.node i k args
| _ => return block
open Lean.Doc.Syntax in
partial def getQuotes (stx : Syntax) : StateT (NameMap StrLit) DocElabM Syntax := do
if stx.getKind == ``Lean.Doc.Syntax.role then
if let `(Lean.Doc.Syntax.role|role{$x:ident $args*}[$inls*]) := stx then
try
let x' ← Elab.realizeGlobalConstNoOverloadWithInfo x
if x' == ``Verso.Genre.Manual.InlineLean.name then
unless args.isEmpty do logErrorAt (mkNullNode args) m!"No arguments expected here"
let some code ← oneCodeStr? inls
| return ((← `(.empty)) : Syntax)
let n ← mkFreshUserName `name
modify (·.insert n code)
let x := mkIdentFrom stx n
return ((← `(Lean.Doc.Syntax.role|role{identRef $x:ident}[])) : Syntax)
catch
| _ => pure ()
match stx with
| .node i k xs => do
let args ← xs.mapM getQuotes
return Syntax.node i k args
| _ => return stx
def getRoot (mods : NameMap (ModuleConfig × α)) : Option Name :=
mods.foldl (init := none) fun
| none, _, ({ moduleName, .. }, _) => moduleName.map (·.getId)
| some y, _, ({moduleName := some x, ..}, _) => prefix? y x.getId
| some y, _, ({moduleName := none, ..}, _) => some y
where
prefix? x y :=
if x.isPrefixOf y then some x
else if y.isPrefixOf x then some y
else none
@[directive]
def leanModules : DirectiveExpanderOf ModulesConfig
| { server, moduleRoots, error }, blocks => do
let (blocks, codeBlocks) ← blocks.mapM getBlocks {}
let moduleRoots ←
if !moduleRoots.isEmpty then pure <| moduleRoots.map (·.getId)
else if let some root := getRoot codeBlocks then pure [root]
else
if codeBlocks.isEmpty then throwError m!"No `{.ofConstName ``leanModule}` blocks in example"
else
let mods := codeBlocks.values.filterMap fun ({moduleName, ..}, _) => moduleName
if mods.isEmpty then
let msg := m!"No named modules in example." ++ (← m!"Use the named argument `moduleName` to specify a name.".hint #[])
throwError msg
let mods := mods.map (m!"`{·}`")
throwError m!"No root module found for {.andList mods}. Use the `moduleRoot` named argument to generate one."
let out ← IO.Process.output {cmd := "lake", args := #["env", "which", "subverso-extract-mod"]}
if out.exitCode != 0 then
throwError
m!"When running 'lake env which subverso-extract-mod', the exit code was {out.exitCode}\n" ++
m!"Stderr:\n{out.stderr}\n\nStdout:\n{out.stdout}\n\n"
let some «subverso-extract-mod» := out.stdout.splitOn "\n" |>.head?
| throwError "No executable path found"
IO.FS.withTempDir fun dirname => do
let u := toString (← IO.monoMsNow)
let dirname := dirname / u
IO.FS.createDirAll dirname
let mut mods := #[]
for (x, modConfig, s, blame) in codeBlocks do
let some modName := modConfig.moduleName
| logErrorAt blame "Explicit module name required"
let modName := modName.getId
let leanFileName : System.FilePath := (modName.toStringWithSep "/" false : System.FilePath).addExtension "lean"
leanFileName.parent.forM (IO.FS.createDirAll <| dirname / ·)
IO.FS.writeFile (dirname / leanFileName) (← parserInputString s)
mods := mods.push (modName, x, modConfig, blame)
let lakefile.toml := lakefile moduleRoots
logSilentInfo <| .trace { cls := `lakefile } m!"lakefile.toml" #[lakefile.toml]
IO.FS.writeFile (dirname / "lakefile.toml") lakefile.toml
let toolchain : String ← IO.FS.readFile "lean-toolchain"
IO.FS.writeFile (dirname / "lean-toolchain") toolchain
let rootsNotPresent := moduleRoots.filter (fun root => !mods.any (fun (x, _, _, _) => x == root))
for root in rootsNotPresent do
let leanFileName : System.FilePath := (root.toStringWithSep "/" false : System.FilePath).addExtension "lean"
leanFileName.parent.forM (IO.FS.createDirAll <| dirname / ·)
IO.FS.writeFile (dirname / leanFileName) <|
mkImports root <| mods.map fun (x, _, _, _) => x
let out ← IO.Process.output {cmd := "lake", args := #["build"], cwd := some dirname}
if !error && out.exitCode != 0 then
throwError
m!"When running 'lake build' in {dirname}, the exit code was {out.exitCode}\n" ++
m!"Stderr:\n{out.stderr}\n\nStdout:\n{out.stdout}\n\n"
else
logBuild "lake build" out
let mut addLets : Term → DocElabM Term := fun stx => pure stx
let mut hasError := false
let mut allHl := .empty
for (modName, x, modConfig, blame) in mods do
let jsonFile := dirname / (modName.toString : System.FilePath).addExtension "json"
let out ← IO.Process.output {
cmd := toString «subverso-extract-mod»,
args := (if server then #[] else #["--not-server"]) ++ #[modName.toString, jsonFile.toString],
cwd := some dirname
env := #[
("LEAN_SRC_PATH", dirname.toString ++ ((":" ++ ·) <$> (← IO.getEnv "LEAN_SRC_PATH")).getD ""),
("LEAN_PATH", (dirname / ".lake" / "build" / "lib" / "lean").toString ++ ((":" ++ ·) <$> (← IO.getEnv "LEAN_PATH")).getD "")
]
}
if out.exitCode != 0 then
throwError
m!"When running '{«subverso-extract-mod»} {modName} {jsonFile}' in {dirname}, the exit code was {out.exitCode}\n" ++
m!"Stderr:\n{out.stderr}\n\nStdout:\n{out.stdout}\n\n"
logBuild s!"subverso-extract-mod {modName} {jsonFile} (in {dirname}, exit code {out.exitCode})" out (some blame)
let json ← IO.FS.readFile (dirname / jsonFile)
let json ← IO.ofExcept <| Json.parse json
let code ← match SubVerso.Module.Module.fromJson? json with
| .ok v => pure (v.items.map (·.code))
| .error e => throwError m!"Failed to deserialized JSON output as highlighted Lean code. Error: {indentD e}\nJSON: {json}"
let hl := code.foldl (init := .empty) fun hl v => hl ++ v
let msgs := getMessages hl
let hl := dropBlanks hl
allHl := allHl ++ hl
if let some name := modConfig.name then
Verso.Genre.Manual.InlineLean.saveOutputs name.getId <| msgs.toList.map (·.2)
hasError := hasError || msgs.any fun m => m.2.severity == .error
for (l, msg) in msgs do
match msg.severity with
| .info => logSilentInfoAt (← lineStx l) msg.toString
| .warning => logSilentAt (← lineStx l) .warning msg.toString
| .error =>
if error then logSilentAt (← lineStx l) .warning msg.toString
else logErrorAt (← lineStx l) msg.toString
let filename : System.FilePath := (modName.toStringWithSep "/" false : System.FilePath).addExtension "lean"
let hlBlk ← ``(Verso.Doc.Block.other (Verso.Genre.Manual.InlineLean.Block.lean $(quote hl) $(quote filename)) #[])
let hlBlk ← ``(Verso.Doc.Block.other (Verso.Genre.Manual.InlineLean.Block.exampleLeanFile $(quote filename.toString)) #[$hlBlk])
addLets := addLets >=> fun stx => do
`(let $(mkIdent x) := $hlBlk; $stx)
if error && !hasError then
logError "Error expected in code block, but none detected."
if !error && hasError then
logError "No error expected in code block, but one occurred."
let (blocks, quotes) ← blocks.mapM getQuotes |>.run {}
for (x, q) in quotes do
if let some tok := allHl.matchingName? q.getString then
addLets := addLets >=> fun stx => do
let hl : SubVerso.Highlighting.Highlighted := .token tok
let hl : Term := quote hl
let name ← `(Verso.Doc.Inline.other {Verso.Genre.Manual.InlineLean.Inline.name with data := ToJson.toJson $hl} #[Verso.Doc.Inline.code $(quote q.getString)])
`(let $(mkIdent x) := $name; $stx)
else logErrorAt q m!"Not found: {q.getString.quote}"
let body ← blocks.mapM (elabBlock <| ⟨·⟩)
let body ← `(Verso.Doc.Block.concat #[$body,*])
addLets body
where
lakefile (roots : List Name) : String := Id.run do
let libNames := roots.map fun n => n.toString.quote
let namesList := ", ".intercalate libNames
let mut content := s!"name = \"example\"\ndefaultTargets = [{namesList}]\n"
content := content ++ "leanOptions = { experimental.module = true }\n"
for lib in libNames do
content := content ++ "\n[[lean_lib]]\nname = " ++ lib ++ "\n"
return content
mkImports (root : Name) (mods : Array Name) : String :=
"module\n" ++
String.join (mods |>.filter (root.isPrefixOf ·) |>.toList |>.map (s!"import {·}\n")) |
reference-manual/Manual/Meta/SectionNotes.lean | import VersoManual.Marginalia
open Verso.Genre.Manual
open Verso.Doc.Elab
namespace Manual
def sectionNote.css := r#"
.section-note .note {
position: relative;
padding: 0.5rem;
border: 1px solid #98B2C0;
border-radius: 0.5rem;
margin-bottom: var(--verso--box-vertical-margin);
padding: 0 var(--verso--box-padding) var(--verso--box-padding);
}
.section-note .note > h1 {
font-size: 1.25rem;
font-weight: bold;
margin-top: 0;
margin-bottom: 1rem;
}
.section-note .note > :first-child {
margin-top: 0;
padding-top: 0;
}
/* Wide viewport */
@media screen and (min-width: 1400px) {
.section-note .note {
float: right;
clear: right;
margin-right: -16rem;
width: 13rem;
}
}
/* Very wide viewport */
@media screen and (min-width: 1600px) {
.section-note .note {
margin-right: -19vw;
width: 15vw;
}
}
/* Medium viewport */
@media screen and (700px < width <= 1400px) {
.section-note .note {
float: right;
clear: right;
width: calc(50% - 2rem);
min-width: 12rem;
margin: 1rem 0;
margin-left: 10%;
}
}
/* Narrow viewport (e.g. phone) */
@media screen and (width <= 700px) {
.section-note .note {
float: left;
clear: left;
width: calc(100% - 2rem);
margin: 1rem 0;
}
}
"#
open Verso.Output Html in
def sectionNoteHtml (content : Html) : Html :=
{{<div class="section-note"><div class="note">{{content}}</div></div>}}
block_extension Block.sectionNote where
traverse _ _ _ := return none
toTeX := none
extraCss := [sectionNote.css]
toHtml :=
open Verso.Output.Html in
some <| fun _ goB _ _ content => do
sectionNoteHtml <$> content.mapM goB
@[directive]
def sectionNote : DirectiveExpanderOf Unit
| (), inlines => do
let content ← inlines.mapM elabBlock
``(Verso.Doc.Block.other Block.sectionNote #[$content,*])
open Verso.Doc.Html
block_extension Block.sectionNoteTitle where
traverse _ _ _ := return none
toTeX := none
toHtml :=
open Verso.Output.Html in
some <| fun goI _ _ _ content => do
match content with
| #[.para xs] =>
return {{<h1> {{← xs.mapM goI}} </h1>}}
| _ => HtmlT.logError "Malformed section note title"; return .empty
@[directive]
def tutorials : DirectiveExpanderOf Unit
| (), blocks => do
let content ← blocks.mapM elabBlock
``(Verso.Doc.Block.other Block.sectionNote #[Verso.Doc.Block.other Block.sectionNoteTitle #[Verso.Doc.Block.para #[Verso.Doc.Inline.text "Tutorials"]], $content,*])
@[directive]
def seeAlso : DirectiveExpanderOf Unit
| (), blocks => do
let content ← blocks.mapM elabBlock
``(Verso.Doc.Block.other Block.sectionNote #[Verso.Doc.Block.other Block.sectionNoteTitle #[Verso.Doc.Block.para #[Verso.Doc.Inline.text "See Also"]], $content,*]) |
reference-manual/Manual/Meta/LakeOpt.lean | import Lean.Elab.Command
import Lean.Elab.InfoTree
import Verso
import Verso.Doc.ArgParse
import Verso.Doc.Elab.Monad
import VersoManual
import Verso.Code
import Manual.Meta.Basic
open Verso ArgParse Doc Elab Genre.Manual Html Code Highlighted.WebAssets
open Lean.Doc.Syntax
open Lean Elab
namespace Manual
inductive LakeOptKind where
| flag
| option
deriving ToJson, FromJson, DecidableEq, Ord, Repr
def LakeOptKind.ns : LakeOptKind → String
| .flag => "lake-flag"
| .option => "lake-option"
open LakeOptKind in
instance : Quote LakeOptKind where
quote
| .flag => Syntax.mkCApp ``LakeOptKind.flag #[]
| .option => Syntax.mkCApp ``LakeOptKind.option #[]
def Inline.lakeOptDef (name : String) (kind : LakeOptKind) (argMeta : Option String) : Inline where
name := `Manual.lakeOptDef
data := .arr #[.str name, toJson kind, toJson argMeta]
def Inline.lakeOpt (name : String) (original : String) : Inline where
name := `Manual.lakeOpt
data := .arr #[.str name, .str original]
def lakeOptDomain := `Manual.lakeOpt
structure LakeOptDefOpts where
kind : LakeOptKind
def LakeOptDefOpts.parse [Monad m] [MonadError m] : ArgParse m LakeOptDefOpts :=
LakeOptDefOpts.mk <$> .positional `kind optKind
where
optKind : ValDesc m LakeOptKind := {
description := "'flag' or 'option'",
signature := .Ident,
get
| .name x =>
match x.getId with
| `flag => pure .flag
| `option => pure .option
| _ => throwErrorAt x "Expected 'flag' or 'option'"
| .num x | .str x => throwErrorAt x "Expected 'flag' or 'option'"
}
def lakeOptCss : String :=
r#"
.lake-opt a {
color: inherit;
text-decoration: currentcolor underline dotted;
}
.lake-opt a:hover {
text-decoration: currentcolor underline solid;
}
"#
@[role_expander lakeOptDef]
def lakeOptDef : RoleExpander
| args, inlines => do
let {kind} ← LakeOptDefOpts.parse.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $name:str )) := arg
| throwErrorAt arg "Expected code literal with the option or flag"
let origName := name.getString
let name := origName.takeWhile fun c => c == '-' || c.isAlphanum
let name := name.copy
let valMeta := origName.drop name.length |>.dropWhile fun (c : Char) => !c.isAlphanum
pure #[← `(show Verso.Doc.Inline Verso.Genre.Manual from .other (Manual.Inline.lakeOptDef $(quote name) $(quote kind) $(quote (if valMeta.isEmpty then none else some valMeta.copy : Option String))) #[Inline.code $(quote name)])]
open Verso.Search in
def lakeOptDomainMapper : DomainMapper :=
DomainMapper.withDefaultJs lakeOptDomain "Lake Command-Line Option" "lake-option-domain" |>.setFont { family := .code }
@[inline_extension lakeOptDef]
def lakeOptDef.descr : InlineDescr where
init s := s.addQuickJumpMapper lakeOptDomain lakeOptDomainMapper
traverse id data _ := do
let .arr #[.str name, jsonKind, _] := data
| logError s!"Failed to deserialize metadata for Lake option def: {data}"; return none
let .ok kind := fromJson? (α := LakeOptKind) jsonKind
| logError s!"Failed to deserialize metadata for Lake option def '{name}' kind: {jsonKind}"; return none
modify fun s =>
s |>.saveDomainObject lakeOptDomain name id |>.saveDomainObjectData lakeOptDomain name jsonKind
discard <| externalTag id (← read).path (kind.ns ++ name)
pure none
toTeX := none
toHtml :=
open Verso.Output.Html in
some <| fun goB id data content => do
let .arr #[.str name, _jsonKind, metadata] := data
| HtmlT.logError s!"Failed to deserialize metadata for Lake option def: {data}"; content.mapM goB
let idAttr := (← read).traverseState.htmlId id
let .ok metadata := FromJson.fromJson? (α := Option String) metadata
| HtmlT.logError s!"Failed to deserialize argument metadata for Lake option def: {metadata}"; content.mapM goB
if let some mv := metadata then
pure {{<code {{idAttr}} class="lake-opt">{{name}}"="{{mv}}</code>}}
else
pure {{<code {{idAttr}} class="lake-opt">{{name}}</code>}}
localContentItem _ info _ := open Verso.Output.Html in do
if let .arr #[.str name, _jsonKind, _meta] := info then
pure #[(name, {{<code>{{name}}</code>}})]
else throw s!"Expected three-element array with string first, got {info}"
@[role_expander lakeOpt]
def lakeOpt : RoleExpander
| args, inlines => do
let () ← ArgParse.done.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $name:str )) := arg
| throwErrorAt arg "Expected code literal with the option or flag"
let optName := name.getString.takeWhile fun c => c == '-' || c.isAlphanum
let optName := optName.copy
pure #[← `(show Verso.Doc.Inline Verso.Genre.Manual from .other (Manual.Inline.lakeOpt $(quote optName) $(quote name.getString)) #[Inline.code $(quote name.getString)])]
@[inline_extension lakeOpt]
def lakeOpt.descr : InlineDescr where
traverse _ _ _ := do
pure none
toTeX := none
extraCss := [lakeOptCss]
toHtml :=
open Verso.Output.Html in
some <| fun goB _ data content => do
let .arr #[.str name, .str original] := data
| HtmlT.logError s!"Failed to deserialize metadata for Lake option ref: {data}"; content.mapM goB
if let some obj := (← read).traverseState.getDomainObject? lakeOptDomain name then
for id in obj.ids do
if let some dest := (← read).traverseState.externalTags[id]? then
return {{<code class="lake-opt"><a href={{dest.link}} class="lake-command">{{name}}</a>{{original.drop name.length |>.copy}}</code>}}
pure {{<code class="lake-opt">{{original}}</code>}} |
reference-manual/Manual/Meta/ErrorExplanation.lean | import VersoManual
import Manual.Meta
import Manual.Meta.ErrorExplanation.Example
import Manual.Meta.ErrorExplanation.Header
open Lean
open Verso.Doc
open Verso.Genre.Manual
open Elab
namespace Manual
/--
Returns the suffix of `name` as a string containing soft-hyphen characters at reasonable split points.
-/
def getBreakableSuffix (name : Name) : Option String := do
let suffix ← match name with
| .str _ s => s
| .num _ n => toString n
| .anonymous => none
let breakableHtml := softHyphenateText false suffix
htmlText breakableHtml
where
htmlText : Verso.Output.Html → String
| .text _ txt => txt
| .seq elts => elts.foldl (· ++ htmlText ·) ""
| .tag _nm _attrs children => htmlText children |
reference-manual/Manual/Meta/LexedText.lean | import Verso
import VersoManual
-- TODO generalize upstream - this is based on the one in the blog genre.
namespace Manual
open Lean.Doc.Syntax
abbrev LexedText.Highlighted := Array (Option String × String)
structure LexedText where
name : String
content : LexedText.Highlighted
deriving Repr, Inhabited, BEq, DecidableEq, Lean.ToJson, Lean.FromJson
open Lean in
instance : Quote LexedText where
quote
| LexedText.mk n c => Syntax.mkCApp ``LexedText.mk #[quote n, quote c]
namespace LexedText
open Lean Parser
open Verso.Parser (ignoreFn)
-- In the absence of a proper regexp engine, abuse ParserFn here
structure Highlighter where
name : String
lexer : ParserFn
tokenClass : Syntax → Option String
def highlight (hl : Highlighter) (str : String) : IO LexedText := do
let mut out : Highlighted := #[]
let mut unHl : Option String := none
let env ← mkEmptyEnvironment
let ictx := mkInputContext str "<input>"
let pmctx : ParserModuleContext := {env := env, options := {}}
let mut s := mkParserState str
repeat
if s.pos.atEnd str then
if let some txt := unHl then
out := out.push (none, txt)
break
let s' := hl.lexer.run ictx pmctx {} s
if s'.hasError then
let c := s.pos.get! str
unHl := unHl.getD "" |>.push c
s := {s with pos := s.pos + c}
else
let stk := s'.stxStack.extract 0 s'.stxStack.size
if stk.size ≠ 1 then
unHl := unHl.getD "" ++ s.pos.extract str s'.pos
s := s'.restore 0 s'.pos
else
let stx := stk[0]!
match hl.tokenClass stx with
| none => unHl := unHl.getD "" ++ s.pos.extract str s'.pos
| some tok =>
if let some ws := unHl then
out := out.push (none, ws)
unHl := none
out := out.push (some tok, s.pos.extract str s'.pos)
s := s'.restore 0 s'.pos
pure ⟨hl.name, out⟩
def token (kind : Name) (p : ParserFn) : ParserFn :=
nodeFn kind <| ignoreFn p
open Verso.Output Html
def toHtml (text : LexedText) : Html :=
text.content.map fun
| (none, txt) => (txt : Html)
| (some cls, txt) => {{ <span class={{cls}}>{{txt}}</span>}}
--- Manual-specific parts
end LexedText
open Lean
open Verso.Genre.Manual
open Verso.Doc Elab
open Verso.ArgParse
section
open LexedText
open Verso.Parser
open Lean.Parser
def hlC : Highlighter where
name := "C"
lexer :=
token `type (andthenFn type (notFollowedByFn (satisfyFn (·.isAlphanum)) "")) <|>
token `kw (andthenFn kw (notFollowedByFn (satisfyFn (·.isAlphanum)) "")) <|>
token `comment comment <|>
token `name name <|>
token `op op <|>
token `brack brack
tokenClass stx := pure (toString stx.getKind)
where
kw := kws.foldl (init := strFn "if") (· <|> strFn ·)
kws := ["then", "else", "extern", "struct", "typedef", "return"]
type := andthenFn (types.foldl (init := strFn "void") (· <|> strFn ·))
(optionalFn (atomicFn (andthenFn (manyFn (chFn ' ')) (chFn '*'))))
types := ["lean_object", "lean_ctor_object", "lean_obj_arg", "b_lean_obj_arg", "size_t", "float", "double", "int", "char"] ++ sizes.map (s!"uint{·}_t")
sizes := [8, 16, 32, 64]
comment : ParserFn := andthenFn (strFn "//") (manyFn (satisfyFn (· ≠ '\n')))
name := atomicFn (andthenFn (satisfyFn (fun c => c.isAlpha || c == '_')) (manyFn (satisfyFn (fun c => c.isAlphanum || c == '_'))))
op := ops.foldl (init := strFn "++") (· <|> strFn ·)
ops := ["+", "*", "/", "--", "-"]
brack := chFn '{' <|> chFn '}' <|> chFn '[' <|> chFn ']' <|> chFn '(' <|> chFn ')'
end
private def c.css : String :=
r##"
.c .type { font-weight: 600; }
.c .kw { font-weight: 600; }
.c .comment { font-style: italic; }
"##
def Block.c (value : LexedText) : Block where
name := `Manual.c
data := toJson value
def Inline.c (value : LexedText) : Inline where
name := `Manual.c
data := toJson value
def lexedText := ()
@[code_block]
def c : CodeBlockExpanderOf Unit
| (), str => do
let codeStr := str.getString
let toks ← LexedText.highlight hlC codeStr
``(Block.other (Block.c $(quote toks)) #[Block.code $(quote codeStr)])
open Verso.Output Html in
open Verso.Doc.Html in
@[block_extension c]
def c.descr : BlockDescr where
traverse _ _ _ := pure none
toTeX := none
toHtml := some <| fun _ _ _ info _ => do
let .ok (v : LexedText) := fromJson? info
| HtmlT.logError s!"Failed to deserialize {info} as lexer-enhanced text"; pure .empty
pure {{<pre class="c">{{v.toHtml}}</pre>}}
extraCss := [c.css]
open Verso.Output Html in
open Verso.Doc.Html in
@[inline_extension c]
def c.idescr : InlineDescr where
traverse _ _ _ := pure none
toTeX := none
toHtml := some <| fun _ _ info _ => do
let .ok (v : LexedText) := fromJson? info
| HtmlT.logError s!"Failed to deserialize {info} as lexer-enhanced text"; pure .empty
pure {{<code class="c">{{v.toHtml}}</code>}}
extraCss := [c.css]
@[role c]
def cInline : RoleExpanderOf Unit
| (), contents => do
let #[x] := contents
| throwError "Expected exactly one parameter"
let `(inline|code($str)) := x
| throwError "Expected exactly one code item"
let codeStr := str.getString
let toks ← LexedText.highlight hlC codeStr
``(Inline.other (Inline.c $(quote toks)) #[Inline.code $(quote codeStr)]) |
reference-manual/Manual/Meta/Namespace.lean | import VersoManual
import Lean.Elab.InfoTree.Types
import SubVerso.Highlighting.Code
open scoped Lean.Doc.Syntax
open Verso Doc Elab
open Lean Elab
open Verso.Genre.Manual InlineLean Scopes
open Verso.SyntaxUtils
open SubVerso.Highlighting
@[role]
def «namespace» : RoleExpanderOf Unit
| (), #[arg] => do
let `(inline|code($s)) := arg
| throwErrorAt arg "Expected code"
-- TODO validate that namespace exists? Or is that too strict?
-- TODO namespace domain for documentation
``(Inline.code $(quote s.getString))
| _, more =>
if h : more.size > 0 then
throwErrorAt more[0] "Expected code literal with the namespace"
else
throwError "Expected code literal with the namespace" |
reference-manual/Manual/Meta/Lean.lean | import VersoManual
import Lean.Elab.InfoTree.Types
import SubVerso.Highlighting.Code
open scoped Lean.Doc.Syntax
open Verso Doc Elab
open Lean Elab
open Verso.Genre.Manual InlineLean Scopes
open Verso.SyntaxUtils
open SubVerso.Highlighting
/--
Elaborates the provided Lean term with a type annotation in the context of the current Verso module.
-/
@[role_expander typed]
def typed : RoleExpander
-- Async elab is turned off to make sure that info trees and messages are available when highlighting
| args, inlines => withoutAsync do
let config ← LeanInlineConfig.parse.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $term:str )) := arg
| throwErrorAt arg "Expected code literal with the example name"
let altStr ← parserInputString term
let leveller :=
if let some us := config.universes then
let us :=
us.getString.splitOn " " |>.filterMap fun (s : String) =>
if s.isEmpty then none else some s.toName
Elab.Term.withLevelNames us
else id
match Parser.runParserCategory (← getEnv) `doc_metavar altStr (← getFileName) with
| .error e => throw (.error (← getRef) e)
| .ok stx => do
let `(doc_metavar|$tm:term : $ty:term) := stx
| throwErrorAt term "Expected colon-separated terms"
let (newMsgs, type, tree) ← do
let initMsgs ← Core.getMessageLog
try
Core.resetMessageLog
let (tree', t) ← runWithOpenDecls <| runWithVariables fun _ => do
let expectedType ← do
let t ← leveller <| Elab.Term.elabType ty
Term.synthesizeSyntheticMVarsNoPostponing
let t ← instantiateMVars t
-- if t.hasExprMVar || t.hasLevelMVar then
-- throwErrorAt term "Type contains metavariables: {t}"
pure t
let e ← leveller <| Elab.Term.elabTerm (catchExPostpone := true) tm expectedType
Term.synthesizeSyntheticMVarsNoPostponing
let e ← Term.levelMVarToParam (← instantiateMVars e)
let t ← Meta.inferType e >>= instantiateMVars >>= (Meta.ppExpr ·)
let t := Std.Format.group <| (← Meta.ppExpr e) ++ (" :" ++ .line) ++ t
Term.synthesizeSyntheticMVarsNoPostponing
let ctx := PartialContextInfo.commandCtx {
env := ← getEnv, fileMap := ← getFileMap, mctx := ← getMCtx, currNamespace := ← getCurrNamespace,
openDecls := ← getOpenDecls, options := ← getOptions, ngen := ← getNGen
}
pure <| (InfoTree.context ctx (.node (Info.ofCommandInfo ⟨`Manual.leanInline, arg⟩) (← getInfoState).trees), t)
pure (← Core.getMessageLog, t, tree')
finally
Core.setMessageLog initMsgs
if let some name := config.name then
let msgs ← newMsgs.toList.mapM fun (msg : Message) => do
let head := if msg.caption != "" then msg.caption ++ ":\n" else ""
let msg ← highlightMessage msg
pure { msg with contents := .append #[.text head, msg.contents] }
saveOutputs name msgs
pushInfoTree tree
if let `(inline|role{%$s $f $_*}%$e[$_*]) ← getRef then
Hover.addCustomHover (mkNullNode #[s, e]) type
Hover.addCustomHover f type
if config.error then
if newMsgs.hasErrors then
for msg in newMsgs.errorsToWarnings.toArray do
logMessage {msg with isSilent := true}
else
throwErrorAt term "Error expected in code block, but none occurred"
else
for msg in newMsgs.toArray do
logMessage {msg with
isSilent := msg.isSilent || msg.severity != .error
}
reportMessages config.error term newMsgs
let hls := (← highlight stx #[] (PersistentArray.empty.push tree))
if config.show then
pure #[← ``(Inline.other (Verso.Genre.Manual.InlineLean.Inline.lean $(quote hls)) #[Inline.code $(quote term.getString)])]
else
pure #[]
where
withNewline (str : String) := if str == "" || str.back != '\n' then str ++ "\n" else str
modifyInfoTrees {m} [Monad m] [MonadInfoTree m] (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit :=
modifyInfoState fun s => { s with trees := f s.trees }
-- TODO - consider how to upstream this
withInfoTreeContext {m α} [Monad m] [MonadInfoTree m] [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m (α × InfoTree) := do
let treesSaved ← getResetInfoTrees
MonadFinally.tryFinally' x fun _ => do
let st ← getInfoState
let tree ← mkInfoTree st.trees
modifyInfoTrees fun _ => treesSaved.push tree
pure tree |
reference-manual/Manual/Meta/PPrint.lean | import Lean.Data.RBMap
import Lean.Data.Json
import Lean.Widget.TaggedText
namespace Manual.Meta.PPrint
open Lean (RBMap)
open Std (Format)
structure FormatWithTags (α : Type u) where
format : Format
tags : RBMap Nat α compare
structure TagFormatM.State (α) where
nextTag : Nat := 0
tags : RBMap Nat α compare := {}
def TagFormatT α m := StateT (TagFormatM.State α) m
instance [Monad m] : Monad (TagFormatT α m) := inferInstanceAs (Monad (StateT (TagFormatM.State α) m))
scoped instance [Monad m] : MonadStateOf (TagFormatM.State α) (TagFormatT α m) :=
inferInstanceAs (MonadStateOf (TagFormatM.State α) (StateT (TagFormatM.State α) m))
instance [Functor m] : MonadLift m (TagFormatT α m) where
monadLift act := fun σ => (·, σ) <$> act
abbrev TagFormatM α := TagFormatT α Id
def TagFormatT.run [Monad m] (act : TagFormatT α m Format) : m (FormatWithTags α) := do
let (value, ⟨_, tags⟩) ← StateT.run act {}
pure ⟨value, tags⟩
def TagFormatM.run (act : TagFormatM α Format) : FormatWithTags α := TagFormatT.run act
def fresh [Monad m] : TagFormatT α m Nat :=
modifyGet fun ⟨i, tags⟩ => (i, ⟨i+1, tags⟩)
def tag [Monad m] (val : α) (doc : Format) : TagFormatT α m Format := do
let i ← fresh
modify fun σ => {σ with tags := σ.tags.insert i val}
pure <| Format.tag i doc
open Lean.Widget
private structure TaggedState (α) where
out : TaggedText α := .text ""
tagStack : List (Nat × TaggedText α) := []
column : Nat := 0
deriving Inhabited
private abbrev RenderM α := (ReaderT (RBMap Nat α compare) (StateM (TaggedState α)))
instance inst [Inhabited α] : Format.MonadPrettyFormat (RenderM α) where
pushOutput s := modify fun ⟨out, ts, col⟩ => ⟨out.appendText s, ts, col + s.length⟩
pushNewline indent := modify fun ⟨out, ts, _⟩ => ⟨out.appendText ("\n".pushn ' ' indent), ts, indent⟩
currColumn := return (←get).column
startTag n := modify fun ⟨out, ts, col⟩ => ⟨TaggedText.text "", (n, out) :: ts, col⟩
endTags n := do
let tagVals ← read
modify fun ⟨out, ts, col⟩ =>
let (ended, left) := (ts.take n, ts.drop n)
let out' := ended.foldl (init := out) fun acc (tag, top) => top.appendTag (tagVals.find! tag) acc
⟨out', left, col⟩
def FormatWithTags.render [Inhabited α] (format : FormatWithTags α) (indent := 0) (w : Nat := Std.Format.defWidth) : TaggedText α :=
(format.format.prettyM w indent : RenderM α Unit) format.tags {} |>.2.out
deriving instance Lean.ToJson, Lean.FromJson for TaggedText
deriving instance Lean.ToJson, Lean.FromJson for PUnit
open Lean Syntax in
partial instance [Quote α] : Quote (TaggedText α) where
quote := go
where
go
| .text s => mkCApp ``TaggedText.text #[quote s]
| .tag x y => mkCApp ``TaggedText.tag #[quote x, go y]
| .append xs =>
mkCApp ``TaggedText.append #[arr xs]
goArr (xs : Array (TaggedText α)) (i : Nat) (args : Array Term) : Term :=
if h : i < xs.size then
goArr xs (i+1) (args.push (go xs[i]))
else
Syntax.mkCApp (Name.mkStr2 "Array" ("mkArray" ++ toString xs.size)) args
arr (xs : Array (TaggedText α)) : Term :=
if xs.size <= 8 then
goArr xs 0 #[]
else
Syntax.mkCApp ``List.toArray #[lst xs.toList]
lst : List (TaggedText α) → Term
| [] => mkCIdent ``List.nil
| (x::xs) => Syntax.mkCApp ``List.cons #[go x, lst xs] |
reference-manual/Manual/Meta/Figure.lean | import VersoManual
import Lean.Elab.InfoTree.Types
import Manual.Meta.Basic
open Verso Doc Elab
open Verso.Genre Manual
open Verso.ArgParse
open Lean Elab
namespace Manual
def Block.figure (captionString : String) (name : Option String) : Block where
name := `Manual.figure
data := ToJson.toJson (captionString, name, (none : Option Tag))
structure FigureConfig where
caption : FileMap × TSyntaxArray `inline
/-- Name for refs -/
tag : Option String := none
def FigureConfig.parse [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] [MonadFileMap m] : ArgParse m FigureConfig :=
FigureConfig.mk <$> .positional `caption .inlinesString <*> .named `tag .string true
@[directive_expander figure]
def figure : DirectiveExpander
| args, contents => do
let cfg ← FigureConfig.parse.run args
PointOfInterest.save (← getRef) (inlinesToString (← getEnv) cfg.caption.2)
(selectionRange := mkNullNode cfg.caption.2)
(kind := Lsp.SymbolKind.interface)
(detail? := some "Figure")
let caption ← DocElabM.withFileMap cfg.caption.1 <|
cfg.caption.2.mapM elabInline
let captionString := inlinesToString (← getEnv) cfg.caption.2
let blocks ← contents.mapM elabBlock
-- Figures are represented using the first block to hold the caption. Storing it in the JSON
-- entails repeated (de)serialization.
pure #[← ``(Block.other (Block.figure $(quote captionString) $(quote cfg.tag)) #[Block.para #[$caption,*], $blocks,*])]
@[block_extension figure]
def figure.descr : BlockDescr where
traverse id data contents := do
match FromJson.fromJson? data (α := String × Option String × Option Tag) with
| .error e => logError s!"Error deserializing figure tag: {e}"; pure none
| .ok (captionString, none, _) => pure none
| .ok (captionString, some x, none) =>
let path ← (·.path) <$> read
let tag ← Verso.Genre.Manual.externalTag id path x
pure <| some <| Block.other {Block.figure captionString none with id := some id, data := toJson (captionString, some x, some tag)} contents
| .ok (_, some _, some _) => pure none
toTeX :=
some <| fun _ go _ _ content => do
pure <| .seq <| ← content.mapM fun b => do
pure <| .seq #[← go b, .raw "\n"]
toHtml :=
open Verso.Doc.Html in
open Verso.Output.Html in
some <| fun goI goB id _data blocks => do
if h : blocks.size < 1 then
HtmlT.logError "Malformed figure"
pure .empty
else
let .para caption := blocks[0]
| HtmlT.logError "Malformed figure - caption not paragraph"; pure .empty
let xref ← HtmlT.state
let attrs := xref.htmlId id
pure {{
<figure {{attrs}}>
{{← blocks.extract 1 blocks.size |>.mapM goB}}
<figcaption>{{← caption.mapM goI}}</figcaption>
</figure>
}}
localContentItem _ info blocks := open Verso.Output.Html in do
let (captionString, _, _) ← FromJson.fromJson? info (α := String × Option String × Option Tag)
pure #[(captionString, {{<span class="figure">{{captionString}}</span>}})] |
reference-manual/Manual/Meta/ElanCmd.lean | import Manual.Meta.LakeCmd -- TODO: generalize the common parts into a library that can be upstreamed
open Verso ArgParse Doc Elab Genre.Manual Html Code Highlighted.WebAssets
open Lean Elab
open SubVerso.Highlighting Highlighted
open scoped Lean.Doc.Syntax
namespace Manual
structure ElanCommandOptions where
name : List Name
spec : StrLit
-- This only allows one level of subcommand, but it's sufficient for Elan as it is today
aliases : List Name
partial def ElanCommandOptions.parse [Monad m] [MonadError m] : ArgParse m ElanCommandOptions :=
ElanCommandOptions.mk <$>
many1 (.positional `name .name) <*>
(.positional `spec strLit <|>
(pure (Syntax.mkStrLit ""))) <*>
.many (.named `alias .name false)
where
many1 {α} (p : ArgParse m α) : ArgParse m (List α) :=
(· :: ·) <$> p <*> .many p
strLit : ValDesc m StrLit := {
description := "string literal containing a Elan command spec",
signature := .String,
get
| .str s => pure s
| other => throwError "Expected string, got {repr other}"
}
def Block.elanCommand (name : String) (aliases : List String) (spec : CommandSpec) : Block where
name := `Manual.Block.elanCommand
data := Json.arr #[Json.str name, toJson aliases, toJson spec]
def Inline.elanMeta : Inline where
name := `Manual.elanMeta
data := .arr #[.null, .null]
def Inline.elanArgs (hl : Highlighted) : Inline where
name := `Manual.elanArgs
data := .arr #[toJson hl, .null]
def Inline.elan : Inline where
name := `Manual.elan
data := .null
private partial def addElanMetaInline (name : String) : Doc.Inline Verso.Genre.Manual → Doc.Inline Verso.Genre.Manual
| .other i xs =>
if i.name == Inline.elanMeta.name || i.name == `Manual.elanArgs then
if let Json.arr #[mn, _] := i.data then
.other {i with data := .arr #[mn, .str <| name.replace " " "~~"]} <| xs.map (addElanMetaInline name)
else
.other i <| xs.map (addElanMetaInline name)
else
.other i <| xs.map (addElanMetaInline name)
| .concat xs => .concat <| xs.map (addElanMetaInline name)
| .emph xs => .emph <| xs.map (addElanMetaInline name)
| .bold xs => .bold <| xs.map (addElanMetaInline name)
| .image alt url => .image alt url
| .math t txt => .math t txt
| .footnote x xs => .footnote x (xs.map (addElanMetaInline name))
| .link xs url => .link (xs.map (addElanMetaInline name)) url
| .code s => .code s
| .linebreak str => .linebreak str
| .text str => .text str
private partial def addElanMetaBlock (name : String) : Doc.Block Verso.Genre.Manual → Doc.Block Verso.Genre.Manual
| .para xs => .para (xs.map (addElanMetaInline name))
| .other b xs => .other b (xs.map (addElanMetaBlock name))
| .concat xs => .concat (xs.map (addElanMetaBlock name))
| .blockquote xs => .blockquote (xs.map (addElanMetaBlock name))
| .code s => .code s
| .dl items => .dl (items.map fun ⟨xs, ys⟩ => ⟨xs.map (addElanMetaInline name), ys.map (addElanMetaBlock name)⟩)
| .ul items => .ul (items.map fun ⟨ys⟩ => ⟨ys.map (addElanMetaBlock name)⟩)
| .ol n items => .ol n (items.map fun ⟨ys⟩ => ⟨ys.map (addElanMetaBlock name)⟩)
@[directive_expander elan]
def elan : DirectiveExpander
| args, contents => do
let {name, spec, aliases} ← ElanCommandOptions.parse.run args
let spec ←
if spec.getString.trimAscii.isEmpty then
pure []
else
match Parser.runParserCategory (← getEnv) `lake_cmd_spec spec.getString (← getFileName) with
| .error e => throwErrorAt spec e
| .ok stx =>
match CommandSpec.ofSyntax stx with
| .error e => throwErrorAt spec e
| .ok spec => pure spec
let nameStr := String.intercalate " " (name.map (·.toString (escape := false)))
let contents ← contents.mapM fun b => do
``(addElanMetaBlock $(quote nameStr) $(← elabBlock b))
pure #[← ``(Verso.Doc.Block.other (Block.elanCommand $(quote nameStr) $(quote <| aliases.map (·.toString (escape := false))) $(quote spec)) #[$contents,*])]
def elanCommandDomain : Name := `Manual.elanCommand
open Verso.Search in
def elanCommandDomainMapper : DomainMapper := {
displayName := "Elan Command",
className := "elan-command-domain",
dataToSearchables := "(domainData) =>
Object.entries(domainData.contents).map(([key, value]) => ({
searchKey: `elan ${key}`,
address: `${value[0].address}#${value[0].id}`,
domainId: 'Manual.elanCommand',
ref: value,
}))"
: DomainMapper
}.setFont { family := .code }
open Verso.Genre.Manual.Markdown in
open Lean Elab Term Parser Tactic in
@[block_extension Block.elanCommand]
def elanCommand.descr : BlockDescr := withHighlighting {
init st := st
|>.setDomainTitle elanCommandDomain "Elan commands"
|>.setDomainDescription elanCommandDomain "Detailed descriptions of Elan commands"
|>.addQuickJumpMapper elanCommandDomain elanCommandDomainMapper
traverse id info _ := do
let Json.arr #[Json.str name, aliases, _] := info
| logError s!"Failed to deserialize data while traversing a Elan command, expected 3-element array starting with string but got {info}"
pure none
let aliases : List String ←
match fromJson? (α := List String) aliases with
| .ok v => pure v
| .error e =>
logError s!"Failed to deserialize aliases while traversing a Elan command: {e}"; pure []
let path ← (·.path) <$> read
let _ ← Verso.Genre.Manual.externalTag id path name
Index.addEntry id {term := Inline.concat #[.code name, .text " (Elan command)"]}
modify fun st => st.saveDomainObject elanCommandDomain name id
for a in aliases do
modify fun st => st.saveDomainObject elanCommandDomain a id
pure none
toHtml := some <| fun _goI goB id info contents =>
open Verso.Doc.Html in
open Verso.Output Html in do
let Json.arr #[ Json.str name, aliases, spec] := info
| do Verso.Doc.Html.HtmlT.logError s!"Failed to deserialize data while making HTML for Elan command, got {info}"; pure .empty
let .ok (aliases : List String) := FromJson.fromJson? aliases
| do Verso.Doc.Html.HtmlT.logError s!"Failed to deserialize aliases while making HTML for Elan command, got {spec}"; pure .empty
let .ok (spec : CommandSpec) := FromJson.fromJson? spec
| do Verso.Doc.Html.HtmlT.logError s!"Failed to deserialize spec while making HTML for Elan command, got {spec}"; pure .empty
let elanTok : Highlighted := .token ⟨.keyword none none none, "elan"⟩
let nameTok : Highlighted := .token ⟨.keyword none none none, name⟩
let spec : Highlighted := spec.toHighlighted
let xref ← HtmlT.state
let idAttr := xref.htmlId id
let aliasHtml : Html :=
match aliases with
| [] => .empty
| _::more => {{
<p>
<strong>{{if more.isEmpty then "Alias:" else "Aliases:"}}</strong>
" "
{{aliases.map (fun (a : String) => {{<code>s!"elan {a}"</code>}}) |>.intersperse {{", "}}}}
</p>
}}
return {{
<div class="namedocs" {{idAttr}}>
{{permalink id xref false}}
<span class="label">"Elan command"</span>
<pre class="signature hl lean block" data-lean-context={{name.replace " " "~~"}}>
{{← (Highlighted.seq #[elanTok, .text " ", nameTok, .text " ", spec]).toHtml (g := Verso.Genre.Manual)}}
</pre>
<div class="text">
{{aliasHtml}}
{{← contents.mapM goB}}
</div>
</div>
}}
toTeX := none
extraCss := [docstringStyle]
localContentItem _ info _ := open Verso.Output.Html in do
if let Json.arr #[ Json.str name, _, _] := info then
let str := s!"elan {name}"
pure #[(str, {{<code>{{str}}</code>}})]
else throw s!"Expected a three-element array with a string first, got {info}"
}
@[role_expander elanMeta]
def elanMeta : RoleExpander
| args, inlines => do
let () ← ArgParse.done.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $mName:str )) := arg
| throwErrorAt arg "Expected code literal with the metavariable"
let mName := mName.getString
pure #[← `(show Verso.Doc.Inline Verso.Genre.Manual from .other {Manual.Inline.elanMeta with data := Json.arr #[$(quote mName), .null]} #[Inline.code $(quote mName)])]
@[inline_extension elanMeta]
def elanMeta.descr : InlineDescr := withHighlighting {
traverse _ _ _ := do
pure none
toTeX :=
some <| fun go _ _ content => do
pure <| .seq <| ← content.mapM fun b => do
pure <| .seq #[← go b, .raw "\n"]
toHtml :=
open Verso.Output.Html in
some <| fun _ _ data _ => do
let (mName, ctx) :=
match data with
| .arr #[.str mName, .str cmdName] =>
(mName, some cmdName)
| .arr #[.str mName, _] =>
(mName, none)
| _ => ("", none)
let hl : Highlighted := .token ⟨.var ⟨mName.toName⟩ mName, mName⟩
hl.inlineHtml ctx (g := Verso.Genre.Manual)
}
@[role_expander elan]
def elanInline : RoleExpander
| args, inlines => do
let () ← ArgParse.done.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $cmdName:str )) := arg
| throwErrorAt arg "Expected code literal with the Elan command name"
let name := cmdName.getString
pure #[← `(show Verso.Doc.Inline Verso.Genre.Manual from .other {Manual.Inline.elan with data := $(quote name)} #[Inline.code $(quote name)])]
@[inline_extension elan]
def elan.descr : InlineDescr where
traverse _ _ _ := do
pure none
toTeX :=
some <| fun go _ _ content => do
pure <| .seq <| ← content.mapM fun b => do
pure <| .seq #[← go b, .raw "\n"]
extraCss := [
r#"
a.elan-command {
color: inherit;
text-decoration: currentcolor underline dotted;
}
a.elan-command:hover {
text-decoration: currentcolor underline solid;
}
"#
]
toHtml :=
open Verso.Output.Html in
some <| fun goI _ data is => do
let (name) :=
match data with
| .str x => some x
| _ => none
if let some n := name then
if let some dest := (← read).traverseState.getDomainObject? elanCommandDomain n then
for id in dest.ids do
if let some dest := (← read).traverseState.externalTags[id]? then
return {{<a href={{dest.link}} class="elan-command"><code>s!"elan {n}"</code></a>}}
HtmlT.logError s!"No name/dest for elan command {name}"
is.mapM goI
@[role_expander elanArgs]
def elanArgs : RoleExpander
| args, inlines => do
let () ← ArgParse.done.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $spec:str )) := arg
| throwErrorAt arg "Expected code literal with the Elan command name"
match Parser.runParserCategory (← getEnv) `lake_cmd_spec spec.getString (← getFileName) with
| .error e => throwErrorAt spec e
| .ok stx =>
match CommandSpec.ofSyntax stx with
| .error e => throwErrorAt spec e
| .ok spec =>
let hl := spec.toHighlighted
pure #[← ``(Verso.Doc.Inline.other (Inline.elanArgs $(quote hl)) #[])]
@[inline_extension elanArgs]
def elanArgs.descr : InlineDescr := withHighlighting {
traverse _ _ _ := do
pure none
toTeX := none
toHtml :=
open Verso.Output.Html in
some <| fun _ _ data _ => do
if let .arr #[hl, name] := data then
match fromJson? (α := Highlighted) hl with
| .error e => HtmlT.logError s!"Couldn't deserialize Elan args: {e}"; return .empty
| .ok hl =>
let name := if let Json.str n := name then some n else none
hl.inlineHtml name (g := Verso.Genre.Manual)
else HtmlT.logError s!"Expected two-element JSON array, got {data}"; return .empty
} |
reference-manual/Manual/Meta/Monotonicity.lean | import Verso
import Manual.Meta.Attribute
import Manual.Meta.Basic
import Manual.Meta.CustomStyle
import Manual.Meta.Instances
open scoped Lean.Doc.Syntax
open Verso Doc Elab Manual
open Verso.Genre.Manual
open Verso.Genre.Manual.InlineLean (constTok)
open SubVerso.Highlighting Highlighted
open Lean Meta Elab
namespace Manual
/--
A table for monotonicity lemmas. Likely some of this logic can be extracted to a helper
in `Manual/Meta/Table.lean`.
-/
private def mkInlineTable (rows : Array (Array Term)) (tag : Option String := none) : TermElabM Name := do
if h : rows.size = 0 then
throwError "Expected at least one row"
else
let columns := rows[0].size
if columns = 0 then
throwError "Expected at least one column"
if rows.any (·.size != columns) then
throwError s!"Expected all rows to have same number of columns, but got {rows.map (·.size)}"
let blocks : Array Term :=
#[ ← ``(Inline.text "Theorem"), ← ``(Inline.text "Pattern") ] ++
rows.flatten
-- The new compiler has a stack overflow when compiling the table unless we split it up. This
-- section is an elaborator to get good control over which parts of the table end up in their
-- own defs.
let arr1 ← mkFreshUserName `monoBlocks1
let arr2 ← mkFreshUserName `monoBlocks2
let blockName ← mkFreshUserName `block
let blockType : Expr := .app (.const ``Verso.Doc.Block []) (.const ``Verso.Genre.Manual [])
let listItemBlockType : Expr := .app (.const ``Verso.Doc.ListItem [0]) blockType
let inlineType : Expr := .app (.const ``Verso.Doc.Inline []) (.const ``Verso.Genre.Manual [])
let listItemInlineType : Expr := .app (.const ``Verso.Doc.ListItem [0]) inlineType
let arrListItemBlockType : Expr := .app (.const ``Array [0]) listItemBlockType
let elabCell (blk : Syntax) : TermElabM Expr := do
let blk ← Term.elabTerm blk (some inlineType)
let blk := mkApp2 (.const ``Verso.Doc.Block.para []) (.const ``Verso.Genre.Manual []) (← mkArrayLit inlineType [blk])
let blk := mkApp2 (.const ``Verso.Doc.ListItem.mk [0]) blockType (← mkArrayLit blockType [blk])
Term.synthesizeSyntheticMVarsNoPostponing
instantiateMVars blk
let blks1 ← blocks.take 70 |>.mapM elabCell
let blks2 ← blocks.drop 70 |>.mapM elabCell
let v1 ← mkArrayLit listItemBlockType blks1.toList
addAndCompile <| .defnDecl {
name := arr1, levelParams := [], type := arrListItemBlockType, value := v1, hints := .opaque, safety := .safe
}
let v1' ← mkArrayLit listItemBlockType blks2.toList
addAndCompile <| .defnDecl {
name := arr2, levelParams := [], type := arrListItemBlockType, value := v1', hints := .opaque, safety := .safe
}
-- The tag down here is relying on the coercion from `String` to `Tag`
let stx ← ``(Block.other (Block.table $(quote columns) (header := true) Option.none Option.none (tag := $(quote tag)))
#[Block.ul ($(mkIdent arr1) ++ $(mkIdent arr2))])
let v2 ← Term.elabTerm stx (some blockType)
Term.synthesizeSyntheticMVarsNoPostponing
let v2 ← instantiateMVars v2
addAndCompile <| .defnDecl {
name := blockName, levelParams := [], type := blockType, value := v2, hints := .opaque, safety := .safe
}
return blockName
section delabhelpers
/-!
To format the monotonicity lemma patterns, I’d like to clearly mark the monotone arguments from
the other arguments. So I define two gadgets with custom delaborators.
-/
def monoArg := @id
def otherArg := @id
open PrettyPrinter.Delaborator
@[app_delab monoArg] def delabMonoArg : Delab :=
PrettyPrinter.Delaborator.withOverApp 2 `(·)
@[app_delab otherArg] def delabOtherArg : Delab :=
PrettyPrinter.Delaborator.withOverApp 2 `(_)
end delabhelpers
open Lean Elab Command Term
def mkMonotonicityLemmas : TermElabM Name := do
let names := (Meta.Monotonicity.monotoneExt.getState (← getEnv)).values
let names := names.qsort (toString · < toString ·)
let mut rows := #[]
for name in names do
-- Extract the target pattern
let ci ← getConstInfo name
-- Omit the `Lean.Order` namespace, if present, to keep the table concise
let nameStr := (name.replacePrefix `Lean.Order .anonymous).getString!
let hl : Highlighted ← constTok name nameStr
let nameStx ← `(Inline.other {Verso.Genre.Manual.InlineLean.Inline.name with data := ToJson.toJson $(quote hl)}
#[Inline.code $(quote nameStr)])
let patternStx : TSyntax `term ←
forallTelescope ci.type fun _ concl => do
unless concl.isAppOfArity ``Lean.Order.monotone 5 do
throwError "Unexpected conclusion of {name}"
let f := concl.appArg!
unless f.isLambda do
throwError "Unexpected conclusion of {name}"
lambdaBoundedTelescope f 1 fun x call => do
-- Monotone arguments are the free variables applied to `x`,
-- Other arguments the other
-- This is an ad-hoc transformation and may fail in cases more complex
-- than we need right now (e.g. binders in the goal).
let call' ← Meta.transform call (pre := fun e => do
if e.isApp && e.appFn!.isFVar && e.appArg! == x[0]! then
.done <$> mkAppM ``monoArg #[e]
else if e.isFVar then
.done <$> mkAppM ``otherArg #[e]
else
pure .continue)
let hlCall ← withOptions (·.setBool `pp.tagAppFns true) do
let fmt ← Lean.Widget.ppExprTagged call'
renderTagged none fmt {ids := {}, definitionsPossible := false, includeUnparsed := false, suppressNamespaces := []}
let n ← mkFreshUserName `monotonicity.hl
-- This used to be a call to quote in the next quasiquotation, but that led to stack overflows in CI (but not locally)
addAndCompile <| .defnDecl {name := n, levelParams := [], type := mkConst ``Highlighted, value := toExpr hlCall, hints := .regular 0, safety := .safe}
``(Inline.other (Verso.Genre.Manual.InlineLean.Inline.lean $(mkIdent n)) #[(Inline.code $(quote hlCall.toString))])
rows := rows.push #[nameStx, patternStx]
mkInlineTable rows (tag := "--monotonicity-lemma-table")
run_cmd do
elabCommand <| ← `(def $(mkIdent `monoTable) := $(mkIdent (← runTermElabM <| fun _ => mkMonotonicityLemmas)))
@[block_command]
def monotonicityLemmas : BlockCommandOf Unit
| () => do
let extraCss ← `(Block.other (Block.customCSS $(quote css)) #[])
``(Block.concat #[$extraCss, monoTable])
where
css := r#"
table#--monotonicity-lemma-table {
border-collapse: collapse;
}
table#--monotonicity-lemma-table th {
text-align: center;
}
table#--monotonicity-lemma-table th, table#--monotonicity-lemma-table th p {
font-family: var(--verso-structure-font-family);
}
table#--monotonicity-lemma-table td:first-child {
padding-bottom: 0.25em;
padding-top: 0.25em;
padding-left: 0;
padding-right: 1.5em;
}
"#
-- #eval do
-- let (ss, _) ← (monotonicityLemmas #[] #[]).run {} (.init .missing)
-- logInfo (ss[0]!.raw.prettyPrint) |
reference-manual/Manual/Meta/Tactics.lean | import Lean.Elab.Term
import Lean.Elab.Tactic
import Verso.Code.Highlighted
import Verso.Doc.ArgParse
import Verso.Doc.Suggestion
import SubVerso.Highlighting.Code
import SubVerso.Examples.Messages
import VersoManual
import Manual.Meta.Basic
import Manual.Meta.PPrint
namespace Manual
open Verso ArgParse Doc Elab Genre.Manual Html Code Highlighted.WebAssets
open Lean Elab Term Tactic
open Verso.Genre.Manual.InlineLean.Scopes (runWithOpenDecls runWithVariables)
open SubVerso.Highlighting
open SubVerso.Examples.Messages
open Lean.Doc.Syntax
structure TacticOutputConfig where
«show» : Bool := true
severity : Option MessageSeverity
summarize : Bool
whitespace : GuardMsgs.WhitespaceMode
expandTraces : List Name
private partial def many (p : ArgParse m α) : ArgParse m (List α) :=
(· :: ·) <$> p <*> many p <|> pure []
def TacticOutputConfig.parser [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] : ArgParse m TacticOutputConfig :=
TacticOutputConfig.mk <$>
.flag `show true <*>
.named `severity .messageSeverity true <*>
.flag `summarize false <*>
((·.getD .exact) <$> .named `whitespace .whitespaceMode true) <*>
(many (.named `expandTrace .name false))
def checkTacticExample (goal : Term) (proofPrefix : Syntax) (tactic : Syntax) (pre : TSyntax `str) (post : TSyntax `str) : TermElabM Unit := do
let statement ← elabType goal
let mv ← Meta.mkFreshExprMVar (some statement)
let Expr.mvar mvarId := mv
| throwError "Not an mvar!"
-- `runTactic` is too specialized for this purpose - we need to capture the unsolved goals, not
-- throw them as an exception. This code is adapted from `runTactic`.
let remainingGoals ← withInfoHole mvarId <| Tactic.run mvarId do
withoutTacticIncrementality true <|
withTacticInfoContext proofPrefix do
-- also put an info node on the `by` keyword specifically -- the token may be `canonical` and thus shown in the info
-- view even though it is synthetic while a node like `tacticCode` never is (#1990)
evalTactic proofPrefix
synthesizeSyntheticMVars (postpone := .no)
-- `runTactic` extraction done. Now prettyprint the proof state.
let st1 := goalsToMessageData remainingGoals
--logInfoAt proofPrefix st1
let goodPre ← (← addMessageContext st1).toString
if pre.getString != goodPre then
logErrorAt pre m!"Mismatch. Expected {indentD goodPre}\n but got {indentD pre.getString}"
-- Run the example
let remainingGoals' ← Tactic.run mvarId do
withoutTacticIncrementality true <|
withTacticInfoContext tactic do
set (Tactic.State.mk remainingGoals)
evalTactic tactic
let st2 := goalsToMessageData remainingGoals'
--logInfoAt tactic st2
let goodPost ← (← addMessageContext st2).toString
if post.getString != goodPost then
logErrorAt post m!"Mismatch. Expected {indentD goodPost}\n but got {indentD post.getString}"
open Lean.Elab.Tactic.GuardMsgs in
def checkTacticExample'
(goal : Expr) (proofPrefix : Syntax) (tactic : Syntax)
(pre : TSyntax `str) (post : TSyntax `str)
(output : Option (TSyntax `str × TacticOutputConfig)) :
TermElabM
(Array (Highlighted.Goal Highlighted) ×
Array (Highlighted.Goal Highlighted) ×
Highlighted ×
MessageSeverity) := do
let mv ← Meta.mkFreshExprMVar (some goal)
let Expr.mvar mvarId := mv
| throwError "Not an mvar!"
-- `runTactic` is too specialized for this purpose - we need to capture the unsolved goals, not
-- throw them as an exception. This code is adapted from `runTactic`.
let ((remainingGoals, _setupMsgs), preTree) ← withInfoTreeContext (mkInfoTree := mkInfoTree `leanInline (← getRef)) do
let initMsgs ← Core.getMessageLog
try
Core.resetMessageLog
let remainingGoals ←
withInfoHole mvarId <| Tactic.run mvarId <|
withoutTacticIncrementality true <|
withTacticInfoContext proofPrefix do
-- also put an info node on the `by` keyword specifically -- the token may be `canonical` and thus shown in the info
-- view even though it is synthetic while a node like `tacticCode` never is (#1990)
evalTactic proofPrefix
synthesizeSyntheticMVars (postpone := .no)
let msgs ← Core.getMessageLog
pure (remainingGoals, msgs)
finally Core.setMessageLog initMsgs
-- `runTactic` extraction done. Now prettyprint the proof state.
let st1 := goalsToMessageData remainingGoals
--logInfoAt proofPrefix st1
let goodPre ← (← addMessageContext st1).toString
if pre.getString.trimAscii != goodPre.trimAscii then
Verso.Doc.Suggestion.saveSuggestion pre ((goodPre.take 30).copy ++ "…") (goodPre ++ "\n")
logErrorAt pre m!"Mismatch. Expected {indentD goodPre}\n but got {indentD pre.getString}"
let ci : ContextInfo := {
env := ← getEnv, fileMap := ← getFileMap, ngen := ← getNGen,
mctx := ← getMCtx, options := ← getOptions,
currNamespace := ← getCurrNamespace, openDecls := ← getOpenDecls
}
let hlPre ← highlightProofState ci remainingGoals (PersistentArray.empty.push preTree)
-- Run the example
let ((remainingGoals', msgs), postTree) ← withInfoTreeContext (mkInfoTree := mkInfoTree `leanInline (← getRef)) do
let initMsgs ← Core.getMessageLog
try
Core.resetMessageLog
let remainingGoals' ← Tactic.run mvarId <|
withoutTacticIncrementality true <|
withTacticInfoContext tactic do
set (Tactic.State.mk remainingGoals)
evalTactic tactic
let msgs ← Core.getMessageLog
pure (remainingGoals', msgs)
finally Core.setMessageLog initMsgs
let st2 := goalsToMessageData remainingGoals'
--logInfoAt tactic st2
let goodPost ← (← addMessageContext st2).toString
if post.getString.trimAscii != goodPost.trimAscii then
Verso.Doc.Suggestion.saveSuggestion post ((goodPost.take 30).copy ++ "…") (goodPost ++ "\n")
logErrorAt post m!"Mismatch. Expected {indentD goodPost}\n but got {indentD post.getString}"
let ci : ContextInfo := { ci with
mctx := ← getMCtx
}
let hlPost ← highlightProofState ci remainingGoals' (PersistentArray.empty.push postTree)
-- TODO suppress proof state bubbles here, at least as an option - `Inline.lean` needs to take that as an argument
let hlTac ← highlight tactic msgs.toArray (PersistentArray.empty.push postTree)
let outSev ← id <| do -- This 'id' is needed so that `return` in the `do` goes here
if let some (wantedOut, config) := output then
let processed ← msgs.toArray.mapM fun msg => do
let head := if msg.caption != "" then msg.caption ++ ":\n" else ""
let txt := withNewline <| head ++ (← msg.data.toString)
pure (msg.severity, txt)
for (sev, txt) in processed do
if mostlyEqual config.whitespace wantedOut.getString txt then
if let some s := config.severity then
if s != sev then
throwErrorAt wantedOut s!"Expected severity {sevStr s}, but got {sevStr sev}"
return sev
for (_, m) in processed do
Verso.Doc.Suggestion.saveSuggestion wantedOut ((m.take 30).copy ++ "…") m
throwErrorAt wantedOut "Didn't match - expected one of: {indentD (toMessageData <| processed.map (·.2))}\nbut got:{indentD (toMessageData wantedOut.getString)}"
else pure .information
return (hlPre, hlPost, hlTac, outSev)
where
withNewline (str : String) := if str == "" || str.back != '\n' then str ++ "\n" else str
sevStr : MessageSeverity → String
| .error => "error"
| .information => "information"
| .warning => "warning"
mostlyEqual (ws : WhitespaceMode) (s1 s2 : String) : Bool :=
ws.apply s1.trimAscii.copy == ws.apply s2.trimAscii.copy
mkInfoTree (elaborator : Name) (stx : Syntax) (trees : PersistentArray InfoTree) : TermElabM InfoTree := do
let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees
let ctx := PartialContextInfo.commandCtx {
env := ← getEnv, fileMap := ← getFileMap, mctx := {}, currNamespace := ← getCurrNamespace,
openDecls := ← getOpenDecls, options := ← getOptions, ngen := ← getNGen
}
return InfoTree.context ctx tree
modifyInfoTrees {m} [Monad m] [MonadInfoTree m] (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit :=
modifyInfoState fun s => { s with trees := f s.trees }
-- TODO - consider how to upstream this
withInfoTreeContext {m α} [Monad m] [MonadInfoTree m] [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m (α × InfoTree) := do
let treesSaved ← getResetInfoTrees
MonadFinally.tryFinally' x fun _ => do
let st ← getInfoState
let tree ← mkInfoTree st.trees
modifyInfoTrees fun _ => treesSaved.push tree
pure tree
open Command
-- TODO: This code would be much nicer if genres could impose custom elaboration contexts as well.
-- As things are, this seems to require hygiene-bending and environment mutation (basically the
-- fluid-let trick, in the absence of syntax parameters), which is icky and tricky and error-prone.
structure TacticExampleContext where
goal : Option Expr := none
setup : Option Syntax := none
pre : Option (TSyntax `str) := none
preName : Ident
tactic : Option Syntax := none
tacticName : Ident
post : Option (TSyntax `str) := none
postName : Ident
output : Option (TSyntax `str × TacticOutputConfig) := none
outputSeverityName : Ident
initialize tacticExampleCtx : Lean.EnvExtension (Option TacticExampleContext) ←
Lean.registerEnvExtension (pure none)
def startExample [Monad m] [MonadEnv m] [MonadError m] [MonadQuotation m] [MonadRef m] : m Unit := do
match tacticExampleCtx.getState (← getEnv) with
| some _ => throwError "Can't initialize - already in a context"
| none =>
let preName ← mkFreshIdent (← getRef)
let tacticName ← mkFreshIdent (← getRef)
let postName ← mkFreshIdent (← getRef)
let outputSeverityName ← mkFreshIdent (← getRef)
modifyEnv fun env =>
tacticExampleCtx.setState env (some {preName, tacticName, postName, outputSeverityName})
def saveGoal [Monad m] [MonadEnv m] [MonadError m] (goal : Expr) : m Unit := do
match tacticExampleCtx.getState (← getEnv) with
| none => throwError "Can't set goal - not in a tactic example"
| some st =>
match st.goal with
| none => modifyEnv fun env => tacticExampleCtx.setState env (some {st with goal := goal})
| some _ => throwError "Goal already specified"
def saveSetup [Monad m] [MonadEnv m] [MonadError m] (setup : Syntax) : m Unit := do
match tacticExampleCtx.getState (← getEnv) with
| none => throwError "Can't set setup - not in a tactic example"
| some st =>
match st.setup with
| none => modifyEnv fun env => tacticExampleCtx.setState env (some {st with setup := setup})
| some _ => throwError "Setup already specified"
def saveTactic [Monad m] [MonadEnv m] [MonadError m] (tactic : Syntax) : m Ident := do
match tacticExampleCtx.getState (← getEnv) with
| none => throwError "Can't set tactic step - not in a tactic example"
| some st =>
match st.tactic with
| some _ => throwError "Tactic step already specified"
| none =>
modifyEnv fun env => tacticExampleCtx.setState env (some {st with tactic := tactic})
return st.tacticName
def savePre [Monad m] [MonadEnv m] [MonadLog m] [MonadRef m] [MonadError m] [AddMessageContext m] [MonadOptions m] (pre : TSyntax `str) : m Ident := do
match tacticExampleCtx.getState (← getEnv) with
| none => throwError "Can't set pre-state - not in a tactic example"
| some st =>
match st.pre with
| none =>
modifyEnv fun env => tacticExampleCtx.setState env (some {st with pre := pre})
| some _ =>
logErrorAt (← getRef) "Pre-state already specified"
return st.preName
def saveOutput [Monad m] [MonadEnv m] [MonadLog m] [MonadRef m] [MonadError m] [AddMessageContext m] [MonadOptions m] (output : TSyntax `str) (options : TacticOutputConfig) : m Ident := do
match tacticExampleCtx.getState (← getEnv) with
| none => throwError "Can't set expected output - not in a tactic example"
| some st =>
match st.output with
| none =>
modifyEnv fun env => tacticExampleCtx.setState env (some {st with output := (output, options)})
| some _ =>
logErrorAt (← getRef) "Expected output already specified"
return st.outputSeverityName
def savePost [Monad m] [MonadEnv m] [MonadLog m] [MonadRef m] [MonadError m] [AddMessageContext m] [MonadOptions m] (post : TSyntax `str) : m Ident := do
match tacticExampleCtx.getState (← getEnv) with
| none => throwError "Can't set post-state - not in a tactic example"
| some st =>
match st.post with
| none =>
modifyEnv fun env => tacticExampleCtx.setState env (some {st with post := post})
| some _ =>
logErrorAt (← getRef) "Post-state already specified"
return st.postName
def endExample (body : TSyntax `term) : DocElabM (TSyntax `term) := do
match tacticExampleCtx.getState (← getEnv) with
| none => throwErrorAt body "Can't end examples - never started"
| some { goal, setup, pre, preName, tactic := tac, tacticName, post, postName, output, outputSeverityName } =>
modifyEnv fun env =>
tacticExampleCtx.setState env none
let some goal := goal
| throwErrorAt body "No goal specified"
let some setup := setup
| throwErrorAt body "No setup specified"
let some pre := pre
| throwErrorAt body "No pre-state specified"
let some tac := tac
| throwErrorAt body "No tactic specified"
let some post := post
| throwErrorAt body "No post-state specified"
let (hlPre, hlPost, hlTactic, outputSeverity) ← checkTacticExample' goal setup tac pre post output
`(let $preName : Array (Highlighted.Goal Highlighted) := $(quote hlPre)
let $postName : Array (Highlighted.Goal Highlighted) := $(quote hlPost)
let $tacticName : Highlighted := $(quote hlTactic)
let $outputSeverityName : MessageSeverity := $(quote outputSeverity)
$body)
@[directive_expander tacticExample]
def tacticExample : DirectiveExpander
| args, blocks => do
ArgParse.done.run args
startExample
let body ← blocks.mapM elabBlock
let body' ← `(Verso.Doc.Block.concat #[$body,*]) >>= endExample
pure #[body']
structure TacticGoalConfig where
«show» : Bool
def TacticGoalConfig.parse [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] : ArgParse m TacticGoalConfig :=
TacticGoalConfig.mk <$> (.flag `show true)
@[role_expander goal]
def goal : RoleExpander
| args, inlines => do
let config ← TacticGoalConfig.parse.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $term:str )) := arg
| throwErrorAt arg "Expected code literal with the example name"
let altStr ← parserInputString term
match Parser.runParserCategory (← getEnv) `term altStr (← getFileName) with
| .error e => throwErrorAt term e
| .ok stx =>
let (newMsgs, tree) ← withInfoTreeContext (mkInfoTree := mkInfoTree `leanInline (← getRef)) do
let initMsgs ← Core.getMessageLog
try
Core.resetMessageLog
let goalExpr ← runWithOpenDecls <| runWithVariables fun _ => Elab.Term.elabTerm stx none
saveGoal goalExpr
Core.getMessageLog
finally
Core.setMessageLog initMsgs
for msg in newMsgs.toArray do
logMessage msg
-- TODO msgs
let hls := (← highlight stx #[] (PersistentArray.empty.push tree))
if config.show then
-- Just emit a normal Lean node - no need to do anything special with the rendered result
pure #[← ``(Inline.other (Verso.Genre.Manual.InlineLean.Inline.lean $(quote hls)) #[Inline.code $(quote term.getString)])]
else
pure #[]
where
mkInfoTree (elaborator : Name) (stx : Syntax) (trees : PersistentArray InfoTree) : DocElabM InfoTree := do
let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees
let ctx := PartialContextInfo.commandCtx {
env := ← getEnv, fileMap := ← getFileMap, mctx := {}, currNamespace := ← getCurrNamespace,
openDecls := ← getOpenDecls, options := ← getOptions, ngen := ← getNGen
}
return InfoTree.context ctx tree
modifyInfoTrees {m} [Monad m] [MonadInfoTree m] (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit :=
modifyInfoState fun s => { s with trees := f s.trees }
-- TODO - consider how to upstream this
withInfoTreeContext {m α} [Monad m] [MonadInfoTree m] [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m (α × InfoTree) := do
let treesSaved ← getResetInfoTrees
MonadFinally.tryFinally' x fun _ => do
let st ← getInfoState
let tree ← mkInfoTree st.trees
modifyInfoTrees fun _ => treesSaved.push tree
pure tree
open Lean.Parser in
@[code_block_expander setup]
def setup : CodeBlockExpander
| args, str => do
let () ← ArgParse.done.run args
let altStr ← parserInputString str
let p := andthen ⟨{}, whitespace⟩ <| andthen {fn := (fun _ => (·.pushSyntax (mkIdent `tacticSeq)))} (parserOfStack 0)
match runParser (← getEnv) (← getOptions) p altStr (← getFileName) with
| .error es =>
for (pos, msg) in es do
log (severity := .error) (mkErrorStringWithPos "<setup>" pos msg)
throwErrorAt str "Failed to parse setup"
| .ok stx =>
saveSetup stx
pure #[]
open Lean.Parser in
@[code_block_expander tacticOutput]
def tacticOutput : CodeBlockExpander
| args, str => do
let opts ← TacticOutputConfig.parser.run args
let outputSeverityName ← saveOutput str opts
if opts.show then
return #[← `(Block.other {Verso.Genre.Manual.InlineLean.Block.leanOutput with data := ToJson.toJson (Highlighted.Message.ofSeverityString $outputSeverityName $(quote str.getString), $(quote opts.summarize), ($(quote opts.expandTraces) : List Lean.Name))} #[Block.code $(quote str.getString)])]
else
return #[]
open Lean.Parser in
@[code_block_expander tacticStep]
def tacticStep : CodeBlockExpander
| args, str => do
let () ← ArgParse.done.run args
let altStr ← parserInputString str
let p := andthen ⟨{}, whitespace⟩ <| andthen {fn := (fun _ => (·.pushSyntax (mkIdent `tacticSeq)))} (parserOfStack 0)
match runParser (← getEnv) (← getOptions) p altStr (← getFileName) with
| .error es =>
for (pos, msg) in es do
log (severity := .error) (mkErrorStringWithPos "<setup>" pos msg)
throwErrorAt str "Failed to parse tactic step"
| .ok stx =>
let hlTac ← saveTactic stx
pure #[← ``(Block.other (Verso.Genre.Manual.InlineLean.Block.lean $hlTac) #[Block.code $(quote str.getString)])]
open Lean.Parser in
@[role_expander tacticStep]
def tacticStepInline : RoleExpander
| args, inlines => do
let () ← ArgParse.done.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $tacStr:str )) := arg
| throwErrorAt arg "Expected code literal with the example name"
let altStr ← parserInputString tacStr
let p := andthen ⟨{}, whitespace⟩ <| andthen {fn := (fun _ => (·.pushSyntax (mkIdent `tacticSeq)))} (parserOfStack 0)
match runParser (← getEnv) (← getOptions) p altStr (← getFileName) with
| .error es =>
for (pos, msg) in es do
log (severity := .error) (mkErrorStringWithPos "<setup>" pos msg)
throwErrorAt arg "Failed to parse tactic step"
| .ok stx =>
let hlTac ← saveTactic stx
pure #[← ``(Inline.other (Verso.Genre.Manual.InlineLean.Inline.lean $hlTac) #[Inline.code $(quote tacStr.getString)])]
def Block.proofState : Block where
name := `Manual.proofState
structure ProofStateOptions where
tag : Option String := none
def ProofStateOptions.parse [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] : ArgParse m ProofStateOptions :=
ProofStateOptions.mk <$> .named `tag .string true
open Lean.Parser in
/--
Show a proof state in the text. The proof goal is expected as a documentation comment immediately
prior to tactics.
-/
@[code_block_expander proofState]
def proofState : CodeBlockExpander
| args, str => do
let opts ← ProofStateOptions.parse.run args
let altStr ← parserInputString str
let p :=
node nullKind <|
andthen ⟨{}, whitespace⟩ <|
andthen termParser <|
andthen ⟨{}, whitespace⟩ <|
andthen ":=" <| andthen ⟨{}, whitespace⟩ <| andthen "by" <|
andthen ⟨{}, whitespace⟩ <|
andthen (andthen {fn := (fun _ => (·.pushSyntax (mkIdent `tacticSeq)))} (parserOfStack 0)) <|
optional <|
andthen ⟨{}, whitespace⟩ <|
Command.docComment
match runParser (← getEnv) (← getOptions) p altStr (← getFileName) with
| .error es =>
for (pos, msg) in es do
log (severity := .error) (mkErrorStringWithPos "<setup>" pos msg)
throwErrorAt str "Failed to parse config (expected goal term, followed by ':=', 'by', and tactics, with optional docstring)"
| .ok stx =>
let goalStx := stx[0]
let tacticStx := stx[4]
let desired :=
match stx[5][0] with
| .missing => none
| other => some (⟨other⟩ : TSyntax `Lean.Parser.Command.docComment)
let goalExpr ← runWithOpenDecls <| runWithVariables fun _ => Elab.Term.elabTerm goalStx none
let mv ← Meta.mkFreshExprMVar (some goalExpr)
let Expr.mvar mvarId := mv
| throwError "Not an mvar!"
let (remainingGoals, infoTree) ← withInfoTreeContext (mkInfoTree := mkInfoTree `proofState (← getRef)) do
Tactic.run mvarId <|
withoutTacticIncrementality true <|
withTacticInfoContext tacticStx do
evalTactic tacticStx
synthesizeSyntheticMVars (postpone := .no)
let ci : ContextInfo := {
env := ← getEnv, fileMap := ← getFileMap, ngen := ← getNGen,
mctx := ← getMCtx, options := ← getOptions,
currNamespace := ← getCurrNamespace, openDecls := ← getOpenDecls
}
let hlState ← highlightProofState ci remainingGoals (PersistentArray.empty.push infoTree)
let st := goalsToMessageData remainingGoals
--logInfoAt proofPrefix st1
let stStr ← (← addMessageContext st).toString
if let some s := desired then
if normalizeMetavars stStr.trimAscii.copy != normalizeMetavars s.getDocString.trimAscii.copy then
logErrorAt s m!"Expected: {indentD stStr}\n\nGot: {indentD s.getDocString}"
Verso.Doc.Suggestion.saveSuggestion s ((stStr.take 30).copy ++ "…") ("/--\n" ++ stStr ++ "\n-/\n")
pure #[← `(Block.other {Block.proofState with data := ToJson.toJson (α := Option String × Array (Highlighted.Goal Highlighted)) ($(quote opts.tag), $(quote hlState))} #[Block.code $(quote stStr)])]
where
mkInfoTree (elaborator : Name) (stx : Syntax) (trees : PersistentArray InfoTree) : DocElabM InfoTree := do
let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees
let ctx := PartialContextInfo.commandCtx {
env := ← getEnv, fileMap := ← getFileMap, mctx := {}, currNamespace := ← getCurrNamespace,
openDecls := ← getOpenDecls, options := ← getOptions, ngen := ← getNGen
}
return InfoTree.context ctx tree
modifyInfoTrees {m} [Monad m] [MonadInfoTree m] (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit :=
modifyInfoState fun s => { s with trees := f s.trees }
-- TODO - consider how to upstream this
withInfoTreeContext {m α} [Monad m] [MonadInfoTree m] [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m (α × InfoTree) := do
let treesSaved ← getResetInfoTrees
MonadFinally.tryFinally' x fun _ => do
let st ← getInfoState
let tree ← mkInfoTree st.trees
modifyInfoTrees fun _ => treesSaved.push tree
pure tree
def proofStateStyle := r#"
.hl.lean.tactic-view {
white-space: collapse;
}
.hl.lean.tactic-view .tactic-state {
display: block;
left: 0;
padding: 0;
border: none;
}
.hl.lean.tactic-view .tactic-state .goal {
margin-top: 1em;
margin-bottom: 1em;
display: block;
}
.hl.lean.tactic-view .tactic-state .goal:first-child {
margin-top: 0.25em;
}
.hl.lean.tactic-view .tactic-state .goal:last-child {
margin-bottom: 0.25em;
}
"#
@[block_extension Manual.proofState]
def proofState.descr : BlockDescr := withHighlighting {
traverse id data content := do
match FromJson.fromJson? data (α := Option String × Array (Highlighted.Goal Highlighted)) with
| .error e => logError s!"Error deserializing proof state info: {e}"; pure none
| .ok (none, _) => pure none
| .ok (some t, v) =>
let path ← (·.path) <$> read
let _tag ← Verso.Genre.Manual.externalTag id path t
pure <| some <| Block.other {Block.proofState with id := some id, data := ToJson.toJson (α := (Option String × _)) (none, v)} content
toTeX := none
extraCss := [proofStateStyle]
toHtml :=
open Verso.Output.Html in
some <| fun _ _ id data _ => do
match FromJson.fromJson? (α := Option Tag × Array (Highlighted.Goal Highlighted)) data with
| .error err =>
HtmlT.logError <| "Couldn't deserialize proof state while rendering HTML: " ++ err
pure .empty
| .ok (_, goals) =>
let xref ← HtmlT.state
let idAttr := xref.htmlId id
pure {{
<div class="hl lean tactic-view">
<div class="tactic-state" {{idAttr}}>
{{← if goals.isEmpty then
pure {{"All goals completed! 🐙"}}
else
.seq <$> goals.mapIdxM fun i x => withCollapsedSubgoals (g := Verso.Genre.Manual) .never <| x.toHtml (·.toHtml) i}}
</div>
</div>
}}
}
structure StateConfig where
tag : Option String := none
«show» : Bool := true
def StateConfig.parse [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] : ArgParse m StateConfig :=
StateConfig.mk <$> .named `tag .string true <*> (.flag `show true)
@[code_block_expander pre]
def pre : CodeBlockExpander
| args, str => do
let opts ← StateConfig.parse.run args
let hlPre ← savePre str
-- The quote step here is to prevent the editor from showing document AST internals when the
-- cursor is on the code block
if opts.show then
pure #[← `(Block.other {Block.proofState with data := ToJson.toJson (α := Option String × Array (Highlighted.Goal Highlighted)) ($(quote opts.tag), $(hlPre))} #[Block.code $(quote str.getString)])]
else
pure #[]
@[code_block_expander post]
def post : CodeBlockExpander
| args, str => do
let opts ← StateConfig.parse.run args
let hlPost ← savePost str
-- The quote step here is to prevent the editor from showing document AST internals when the
-- cursor is on the code block
if opts.show then
pure #[← `(Block.other {Block.proofState with data := ToJson.toJson (α := Option String × Array (Highlighted.Goal Highlighted)) ($(quote opts.tag), $(hlPost))} #[Block.code $(quote str.getString)])]
else
pure #[] |
reference-manual/Manual/Meta/Syntax.lean | import VersoManual
import Verso.Code.Highlighted
import VersoManual.InlineLean
import Manual.Meta.Basic
import Manual.Meta.PPrint
open Verso Doc Elab
open Verso.Genre Manual
open Verso.ArgParse
open Verso.Code (highlightingJs)
open Verso.Code.Highlighted.WebAssets
open Lean.Doc.Syntax
open Verso.Genre.Manual.InlineLean.Scopes (getScopes)
open Lean Elab Parser
open Lean.Widget (TaggedText)
namespace Manual
set_option guard_msgs.diff true
@[role_expander evalPrio]
def evalPrio : RoleExpander
| args, inlines => do
ArgParse.done.run args
let #[inl] := inlines
| throwError "Expected a single code argument"
let `(inline|code( $s:str )) := inl
| throwErrorAt inl "Expected code literal with the priority"
let altStr ← parserInputString s
match runParser (← getEnv) (← getOptions) (andthen ⟨{}, whitespace⟩ priorityParser) altStr (← getFileName) with
| .ok stx =>
let n ← liftMacroM (Lean.evalPrio stx)
pure #[← `(Verso.Doc.Inline.text $(quote s!"{n}"))]
| .error es =>
for (pos, msg) in es do
log (severity := .error) (mkErrorStringWithPos "<example>" pos msg)
throwError s!"Failed to parse priority from '{s.getString}'"
@[role_expander evalPrec]
def evalPrec : RoleExpander
| args, inlines => do
ArgParse.done.run args
let #[inl] := inlines
| throwError "Expected a single code argument"
let `(inline|code( $s:str )) := inl
| throwErrorAt inl "Expected code literal with the precedence"
let altStr ← parserInputString s
match runParser (← getEnv) (← getOptions) (andthen ⟨{}, whitespace⟩ (categoryParser `prec 1024)) altStr (← getFileName) with
| .ok stx =>
let n ← liftMacroM (Lean.evalPrec stx)
pure #[← `(Verso.Doc.Inline.text $(quote s!"{n}"))]
| .error es =>
for (pos, msg) in es do
log (severity := .error) (mkErrorStringWithPos "<example>" pos msg)
throwError s!"Failed to parse precedence from '{s.getString}'"
def Block.syntax : Block where
name := `Manual.syntax
def Block.grammar : Block where
name := `Manual.grammar
def Inline.keywordOf : Inline where
name := `Manual.keywordOf
def Inline.keyword : Inline where
name := `Manual.keyword
structure FreeSyntaxConfig where
name : Name
«open» : Bool := true
label : Option String := none
title : (FileMap × TSyntaxArray `inline)
def FreeSyntaxConfig.getLabel (config : FreeSyntaxConfig) : String :=
config.label.getD <|
match config.name with
| `attr => "attribute"
| _ => "syntax"
structure SyntaxConfig extends FreeSyntaxConfig where
namespaces : List Name := []
aliases : List Name := []
def SyntaxConfig.getLabel (config : SyntaxConfig) : String :=
config.toFreeSyntaxConfig.getLabel
structure KeywordOfConfig where
ofSyntax : Ident
parser : Option Ident
def KeywordOfConfig.parse [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] : ArgParse m KeywordOfConfig :=
KeywordOfConfig.mk <$> .positional `ofSyntax .ident <*> .named `parser .ident true
@[role_expander keywordOf]
def keywordOf : RoleExpander
| args, inlines => do
let ⟨kind, parser⟩ ← KeywordOfConfig.parse.run args
let #[inl] := inlines
| throwError "Expected a single code argument"
let `(inline|code( $kw:str )) := inl
| throwErrorAt inl "Expected code literal with the keyword"
let kindName := kind.getId
let parserName ← parser.mapM (realizeGlobalConstNoOverloadWithInfo ·)
let env ← getEnv
let mut catName := none
for (cat, contents) in (Lean.Parser.parserExtension.getState env).categories do
for (k, ()) in contents.kinds do
if kindName == k then catName := some cat; break
if let some _ := catName then break
let kindDoc ← findDocString? (← getEnv) kindName
return #[← `(Inline.other {Inline.keywordOf with data := ToJson.toJson (α := (String × Option Name × Name × Option String)) $(quote (kw.getString, catName, parserName.getD kindName, kindDoc))} #[Inline.code $kw])]
@[inline_extension keywordOf]
def keywordOf.descr : InlineDescr := withHighlighting {
traverse _ _ _ := do
pure none
toTeX := none
toHtml :=
open Verso.Output Html in
some <| fun goI _ info content => do
match FromJson.fromJson? (α := (String × Option Name × Name × Option String)) info with
| .ok (kw, cat, kind, kindDoc) =>
-- TODO: use the presentation of the syntax in the manual to show the kind, rather than
-- leaking the kind name here, which is often horrible. But we need more data to test this
-- with first! Also TODO: we need docs for syntax categories, with human-readable names to
-- show here. Use tactic index data for inspiration.
-- For now, here's the underlying data so we don't have to fill in xrefs later and can debug.
let tgt := (← read).linkTargets.keyword kind none
let addLink (html : Html) : Html :=
match tgt[0]? with
| none => html
| some l =>
{{<a href={{l.href}}>{{html}}</a>}}
pure {{
<span class="hl lean keyword-of">
<code class="hover-info">
<code>{{kind.toString}} {{cat.map (" : " ++ toString ·) |>.getD ""}}</code>
{{if let some doc := kindDoc then
{{ <span class="sep"/> <code class="docstring">{{doc}}</code>}}
else
.empty
}}
</code>
{{addLink {{<code class="kw">{{kw}}</code>}} }}
</span>
}}
| .error e =>
Html.HtmlT.logError s!"Couldn't deserialized keywordOf data: {e}"
content.mapM goI
extraCss := [
r#".keyword-of .kw {
font-weight: 500;
}
.keyword-of .hover-info {
display: none;
}
.keyword-of .kw:hover {
background-color: #eee;
border-radius: 2px;
}
"#
]
extraJs := [
r#"
window.addEventListener("load", () => {
tippy('.keyword-of.hl.lean', {
allowHtml: true,
/* DEBUG -- remove the space: * /
onHide(any) { return false; },
trigger: "click",
// */
maxWidth: "none",
theme: "lean",
placement: 'bottom-start',
content (tgt) {
const content = document.createElement("span");
const state = tgt.querySelector(".hover-info").cloneNode(true);
state.style.display = "block";
content.appendChild(state);
/* Render docstrings - TODO server-side */
if ('undefined' !== typeof marked) {
for (const d of content.querySelectorAll("code.docstring, pre.docstring")) {
const str = d.innerText;
const html = marked.parse(str);
const rendered = document.createElement("div");
rendered.classList.add("docstring");
rendered.innerHTML = html;
d.parentNode.replaceChild(rendered, d);
}
}
content.style.display = "block";
content.className = "hl lean popup";
return content;
}
});
});
"#
]
}
@[role_expander keyword]
def keyword : RoleExpander
| args, inlines => do
let () ← ArgParse.done.run args
let #[inl] := inlines
| throwError "Expected a single code argument"
let `(inline|code( $kw:str )) := inl
| throwErrorAt inl "Expected code literal with the keyword"
return #[← `(Inline.other {Inline.keyword with data := Lean.Json.str $(quote kw.getString)} #[Inline.code $kw])]
@[inline_extension keyword]
def keyword.descr : InlineDescr where
traverse _ _ _ := do
pure none
toTeX := none
toHtml :=
open Verso.Output Html in
some <| fun goI _ info content => do
let .str kw := info
| Html.HtmlT.logError s!"Expected a JSON string for a plain keyword, got {info}"; content.mapM goI
pure {{<code class="plain-keyword">{{kw}}</code>}}
extraCss := [
r#".plain-keyword {
font-weight: 500;
}
"#
]
partial def many [Inhabited (f (List α))] [Applicative f] [Alternative f] (x : f α) : f (List α) :=
((· :: ·) <$> x <*> many x) <|> pure []
def FreeSyntaxConfig.parse [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] [MonadFileMap m] : ArgParse m FreeSyntaxConfig :=
FreeSyntaxConfig.mk <$>
.positional `name .name <*>
.flag `open true <*>
.named `label .string true <*>
.named `title .inlinesString false
def SyntaxConfig.parse [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] [MonadFileMap m] : ArgParse m SyntaxConfig :=
SyntaxConfig.mk <$> FreeSyntaxConfig.parse <*> (many (.named `namespace .name false)) <*> (many (.named `alias .resolvedName false) <* .done)
inductive GrammarTag where
| lhs
| rhs
| keyword
| literalIdent
| nonterminal (name : Name) (docstring? : Option String)
| fromNonterminal (name : Name) (docstring? : Option String)
| error
| bnf
| comment
| localName (name : Name) (which : Nat) (category : Name) (docstring? : Option String)
deriving Repr, FromJson, ToJson, Inhabited
open Lean.Syntax in
open GrammarTag in
instance : Quote GrammarTag where
quote
| .lhs => mkCApp ``GrammarTag.lhs #[]
| .rhs => mkCApp ``GrammarTag.rhs #[]
| .keyword => mkCApp ``GrammarTag.keyword #[]
| .literalIdent => mkCApp ``GrammarTag.literalIdent #[]
| nonterminal x d => mkCApp ``nonterminal #[quote x, quote d]
| fromNonterminal x d => mkCApp ``fromNonterminal #[quote x, quote d]
| GrammarTag.error => mkCApp ``GrammarTag.error #[]
| bnf => mkCApp ``bnf #[]
| comment => mkCApp ``comment #[]
| localName name which cat d => mkCApp ``localName #[quote name, quote which, quote cat, quote d]
structure GrammarConfig where
of : Option Name
prec : Nat := 0
def GrammarConfig.parse [Monad m] [MonadInfoTree m] [MonadEnv m] [MonadError m] : ArgParse m GrammarConfig :=
GrammarConfig.mk <$>
.named `of .name true <*>
((·.getD 0) <$> .named `prec .nat true)
namespace FreeSyntax
declare_syntax_cat free_syntax_item
scoped syntax (name := strItem) str : free_syntax_item
scoped syntax (name := docCommentItem) docComment : free_syntax_item
scoped syntax (name := identItem) ident : free_syntax_item
scoped syntax (name := namedIdentItem) ident noWs ":" noWs ident : free_syntax_item
scoped syntax (name := antiquoteItem) "$" noWs (ident <|> "_") noWs ":" noWs ident ("?" <|> "*" <|> "+")? : free_syntax_item
scoped syntax (name := modItem) "(" free_syntax_item+ ")" noWs ("?" <|> "*" <|> "+") : free_syntax_item
scoped syntax (name := checked) Term.dynamicQuot : free_syntax_item
declare_syntax_cat free_syntax
scoped syntax (name := rule) free_syntax_item* : free_syntax
scoped syntax (name := embed) "free{" free_syntax_item* "}" : term
declare_syntax_cat syntax_sep
open Lean Elab Command in
run_cmd do
for i in [5:40] do
let sep := Syntax.mkStrLit <| String.ofList (List.replicate i '*')
let cmd ← `(scoped syntax (name := $(mkIdent s!"sep{i}".toName)) $sep:str : syntax_sep)
elabCommand cmd
pure ()
declare_syntax_cat free_syntaxes
scoped syntax (name := done) free_syntax : free_syntaxes
scoped syntax (name := more) free_syntax syntax_sep free_syntaxes : free_syntaxes
/-- Translate freely specified syntax into what the output of the Lean parser would have been -/
partial def decodeMany (stx : Syntax) : List Syntax :=
match stx.getKind with
| ``done => [stx[0]]
| ``more => stx[0] :: decodeMany stx[2]
| _ => [stx]
mutual
/-- Translate freely specified syntax into what the output of the Lean parser would have been -/
partial def decode (stx : Syntax) : Syntax :=
(Syntax.copyHeadTailInfoFrom · stx) <|
Id.run <| stx.rewriteBottomUp fun stx' =>
match stx'.getKind with
| ``strItem =>
.atom .none (⟨stx'[0]⟩ : StrLit).getString
| ``embed =>
stx'[1]
| ``checked =>
let quote := stx'[0]
-- 0: `( ; 1: parser ; 2: | ; 3: content ; 4: )
quote[3]
| _ => stx'
/-- Find instances of freely specified syntax in the result of parsing checked syntax, and decode them -/
partial def decodeIn (stx : Syntax) : Syntax :=
Id.run <| stx.rewriteBottomUp fun
| `(term|free{$stxs*}) => .node .none `null (stxs.map decode)
| other => other
end
end FreeSyntax
namespace Meta.PPrint.Grammar
def antiquoteOf : Name → Option Name
| .str n "antiquot" => pure n
| _ => none
def nonTerm : Name → String
| .str x "pseudo" => nonTerm x
| .str _ x => x
| x => x.toString
def empty : Syntax → Bool
| .node _ _ #[] => true
| _ => false
def isEmpty : Format → Bool
| .nil => true
| .tag _ f => isEmpty f
| .append f1 f2 => isEmpty f1 && isEmpty f2
| .line => false
| .group f _ => isEmpty f
| .nest _ f => isEmpty f
| .align .. => false
| .text str => str.isEmpty
def isCompound [Monad m] (f : Format) : TagFormatT GrammarTag m Bool := do
if (← beginsWithBnfParen f <&&> endsWithBnfParen f) then return false
match f with
| .nil => pure false
| .tag _ f => isCompound f
| .append f1 f2 =>
isCompound f1 <||> isCompound f2
| .line => pure true
| .group f _ => isCompound f
| .nest _ f => isCompound f
| .align .. => pure false
| .text str =>
pure <| str.any fun c => c.isWhitespace || c ∈ ['"', ':', '+', '*', ',', '\'', '(', ')', '[', ']']
where
beginsWithBnfParen : Format → TagFormatT GrammarTag m Bool
| .nil => pure false
| .tag k (.text s) => do
if (← get).tags.find? k matches some .bnf then
return "(".isPrefixOf s
else pure false
| .tag _ f => beginsWithBnfParen f
| .append f1 f2 =>
if isEmpty f1 then beginsWithBnfParen f2 else beginsWithBnfParen f1
| .line => pure false
| .group f _ => beginsWithBnfParen f
| .nest _ f => beginsWithBnfParen f
| .align _ => pure false
| .text .. => pure false
endsWithBnfParen : Format → TagFormatT GrammarTag m Bool
| .nil => pure false
| .tag k (.text s) => do
if (← get).tags.find? k matches some .bnf then
return ")".isPrefixOf s
else pure false
| .tag _ f => endsWithBnfParen f
| .append f1 f2 =>
if isEmpty f2 then endsWithBnfParen f1 else endsWithBnfParen f2
| .line => pure false
| .group f _ => endsWithBnfParen f
| .nest _ f => endsWithBnfParen f
| .align _ => pure false
| .text .. => pure false
partial def kleeneLike (mod : String) (f : Format) : TagFormatT GrammarTag DocElabM Format := do
if (← isCompound f) then return (← tag .bnf "(") ++ f ++ (← tag .bnf s!"){mod}")
else return f ++ (← tag .bnf mod)
def kleene := kleeneLike "*"
def perhaps := kleeneLike "?"
def lined (ws : String) : Format :=
Format.line.joinSep (ws.splitOn "\n")
def noTrailing (info : SourceInfo) : Option SourceInfo :=
match info with
| .original leading p1 _ p2 => some <| .original leading p1 "".toRawSubstring p2
| .synthetic .. => some info
| .none => none
def removeTrailing? : Syntax → Option Syntax
| .node .none k children => do
for h : i in [0:children.size] do
have : children.size > 0 := by
let ⟨_, _, _⟩ := h
simp_all +zetaDelta
omega
if let some child' := removeTrailing? children[children.size - i - 1] then
return .node .none k (children.set (children.size - i - 1) child')
failure
| .node info k children =>
noTrailing info |>.map (.node · k children)
| .atom info str => noTrailing info |>.map (.atom · str)
| .ident info str x pre => noTrailing info |>.map (.ident · str x pre)
| .missing => failure
def removeTrailing (stx : Syntax) : Syntax := removeTrailing? stx |>.getD stx
def infoWrap (info : SourceInfo) (doc : Format) : Format :=
if let .original leading _ trailing _ := info then
lined leading.toString ++ doc ++ lined trailing.toString
else doc
def infoWrapTrailing (info : SourceInfo) (doc : Format) : Format :=
if let .original _ _ trailing _ := info then
doc ++ lined trailing.toString
else doc
def infoWrap2 (info1 : SourceInfo) (info2 : SourceInfo) (doc : Format) : Format :=
let pre := if let .original leading _ _ _ := info1 then lined leading.toString else .nil
let post := if let .original _ _ trailing _ := info2 then lined trailing.toString else .nil
pre ++ doc ++ post
def longestSuffix (strs : Array String) : String := Id.run do
if h : strs.size = 0 then ""
else
let mut suff := strs[0].toSlice
repeat
if suff.isEmpty then return ""
let suff' := suff
for s in strs do
unless s.dropSuffix? suff |>.isSome do
suff := suff.drop 1
if suff' == suff then return suff'.copy
return ""
/-- info: "abc" -/
#guard_msgs in
#eval longestSuffix #["abc", "abc"]
/-- info: "bc" -/
#guard_msgs in
#eval longestSuffix #["abc", "bc"]
/-- info: "abc" -/
#guard_msgs in
#eval longestSuffix #["abc"]
/-- info: "" -/
#guard_msgs in
#eval longestSuffix #[]
/-- info: "" -/
#guard_msgs in
#eval longestSuffix #["abc", "def"]
/-- info: "" -/
#guard_msgs in
#eval longestSuffix #["abc", "def", "abc"]
def longestPrefix (strs : Array String) : String := Id.run do
if h : strs.size = 0 then ""
else
let mut pref := strs[0].toSlice
repeat
if pref.isEmpty then return ""
let pref' := pref
for s in strs do
unless s.dropPrefix? pref |>.isSome do
pref := pref.dropEnd 1
if pref' == pref then return pref'.copy
return ""
/-- info: "abc" -/
#guard_msgs in
#eval longestPrefix #["abc", "abc"]
/-- info: "" -/
#guard_msgs in
#eval longestPrefix #["abc", "bc"]
/-- info: "ab" -/
#guard_msgs in
#eval longestPrefix #["abc", "ab"]
/-- info: "abc" -/
#guard_msgs in
#eval longestPrefix #["abc"]
/-- info: "" -/
#guard_msgs in
#eval longestPrefix #[]
/-- info: "" -/
#guard_msgs in
#eval longestPrefix #["abc", "def"]
/-- info: "" -/
#guard_msgs in
#eval longestPrefix #["abc", "def", "abc"]
/-- info: "a" -/
#guard_msgs in
#eval longestPrefix #["abc", "aaa"]
/-- Does this syntax take up zero source code? -/
partial def isEmptySyntax : Syntax → Bool
| .node info _ args => isEmptyInfo info && args.all isEmptySyntax
| .atom info s => isEmptyInfo info && s.isEmpty
| .ident .. => false
| .missing => false
where
isEmptyInfo
| .original leading _ trailing _ => leading.isEmpty && trailing.isEmpty
| _ => true
def removeLeadingString (string : String) : Syntax → Syntax
| .missing => .missing
| .atom info str => .atom (remove info).2 str
| .ident info x raw pre => .ident (remove info).2 x raw pre
| .node info k args => Id.run do
let (string', info') := remove info
let mut args' := #[]
for h : i in [0 : args.size] do
if isEmptySyntax args[i] then
args' := args'.push args[i]
else
let this := removeLeadingString string' args[i]
args' := args'.push this
args' := args' ++ args.extract (i + 1) args.size
break
.node info' k args'
where
remove : SourceInfo → String × SourceInfo
| .original leading pos trailing pos' =>
(string.take leading.toString.length |>.copy, .original (leading.drop string.length) pos trailing pos')
| other => (string, other)
partial def removeTrailingString (string : String) : Syntax → Syntax :=
fun stx =>
if string.isEmpty then stx else
match stx with
| .missing => .missing
| .atom info str => .atom (remove info).2 str
| .ident info x raw pre => .ident (remove info).2 x raw pre
| .node info k args => Id.run do
let (string', info') := remove info
let mut args' := #[]
for h : i in [0 : args.size] do
let j := args.size - (i + 1)
have : i < args.size := by get_elem_tactic
have : j < args.size := by omega
if isEmptySyntax args[j] then
-- The parser doesn't presently put source info here, so it's expedient to not check for
-- whitespace on this source info. If this ever changes, update this code.
args' := args'.push args[j]
else
let this := removeTrailingString string' args[j]
args' := args'.push this
args' := args.extract 0 j ++ args'.reverse
break
.node info' k args'
where
remove : SourceInfo → String × SourceInfo
| .original leading pos trailing pos' =>
(string.dropEnd trailing.toString.length |>.copy, .original leading pos (trailing.dropRight string.length) pos')
| other => (string, other)
/--
Extracts the common leading and trailing whitespaces from an array of syntaxes.
This is to be used when rendering choice nodes in a grammar, so they don't have redundant whitespace.
-/
def commonWs (stxs : Array Syntax) : String × Array Syntax × String :=
let allLeading := stxs.map Syntax.getHeadInfo |>.map fun
| .none => ""
| .synthetic .. => ""
| .original leading _ _ _ => leading.toString
let allTrailing := stxs.map Syntax.getTailInfo |>.map fun
| .none => ""
| .synthetic .. => ""
| .original _ _ trailing _ => trailing.toString
let pref := longestPrefix allLeading
let suff := longestSuffix allTrailing
let stxs := stxs.map fun stx =>
removeLeadingString pref (removeTrailingString suff stx)
(pref, stxs, suff)
open Lean.Parser.Command in
/--
A set of parsers that exist to wrap only a single keyword and should be rendered as the keyword
itself.
-/
-- TODO make this extensible in the manual itself
def keywordParsers : List (Name × String) :=
[(``«private», "private"), (``«protected», "protected"), (``«partial», "partial"), (``«nonrec», "nonrec")]
open StateT (lift) in
partial def production (which : Nat) (stx : Syntax) : StateT (Lean.NameMap (Name × Option String)) (TagFormatT GrammarTag DocElabM) Format := do
match stx with
| .atom info str => infoWrap info <$> lift (tag GrammarTag.keyword str)
| .missing => lift <| tag GrammarTag.error "<missing>"
| .ident info _ x _ =>
-- If the identifier is the name of something that works like a syntax category, then treat it as a nonterminal
if x ∈ [`ident, `atom, `num] || (Lean.Parser.parserExtension.getState (← getEnv)).categories.contains x then
let d? ← findDocString? (← getEnv) x
-- TODO render markdown
let tok ←
lift <| tag (.nonterminal x d?) <|
match x with
| .str x' "pseudo" => x'.toString
| _ => x.toString
return infoWrap info tok
else
-- If it's not a syntax category, treat it as the literal identifier (e.g. `config` before `:=` in tactic configurations)
let tok ←
lift <| tag .literalIdent x.toString
return infoWrap info tok
| .node info k args => do
infoWrap info <$>
match k, antiquoteOf k, args with
| `many.antiquot_suffix_splice, _, #[starred, star] =>
infoWrap2 starred.getHeadInfo star.getTailInfo <$> (production which starred >>= lift ∘ kleene)
| `optional.antiquot_suffix_splice, _, #[questioned, star] => -- See also the case for antiquoted identifiers below
infoWrap2 questioned.getHeadInfo star.getTailInfo <$> (production which questioned >>= lift ∘ perhaps)
| `sepBy.antiquot_suffix_splice, _, #[starred, star] =>
let starStr :=
match star with
| .atom _ s => s
| _ => ",*"
infoWrap2 starred.getHeadInfo star.getTailInfo <$> (production which starred >>= lift ∘ kleeneLike starStr)
| `many.antiquot_scope, _, #[dollar, _null, _brack, contents, _brack2, .atom info star] =>
infoWrap2 dollar.getHeadInfo info <$> (production which contents >>= lift ∘ kleene)
| `optional.antiquot_scope, _, #[dollar, _null, _brack, contents, _brack2, .atom info _star] =>
infoWrap2 dollar.getHeadInfo info <$> (production which contents >>= lift ∘ perhaps)
| `sepBy.antiquot_scope, _, #[dollar, _null, _brack, contents, _brack2, .atom info star] =>
infoWrap2 dollar.getHeadInfo info <$> (production which contents >>= lift ∘ kleeneLike star)
| `choice, _, opts => do
-- Extract the common whitespace here. Otherwise, something like `∀ $_ $_*, $_` might render as
-- `∀ (binder | thing )(binder | thing )*, term`
-- instead of
-- `∀ (binder | thing) (binder | thing)* , term`
let (pre, opts, post) := commonWs opts
return pre ++
(← lift <| tag .bnf "(") ++ (" " ++ (← lift <| tag .bnf "|") ++ " ").joinSep
(← opts.toList.mapM (production which)) ++ (← lift <| tag .bnf ")") ++
post
| ``Attr.simple, _, #[.ident kinfo _ name _, other] => do
return infoWrap info (infoWrap kinfo (← lift <| tag .keyword name.toString) ++ (← production which other))
| ``FreeSyntax.docCommentItem, _, _ =>
match stx[0][1] with
| .atom _ val => do
-- TODO: use a slice here. As of nightly-2025-10-20, the code panicked (reported)
let mut str := val.dropEnd 2
let mut contents : Format := .nil
let mut inVar : Bool := false
while !str.isEmpty do
if inVar then
let pre := str.takeWhile (· != '}')
str := str.dropPrefix pre |>.drop 1
let x := pre.trimAscii.toName
if let some (c, d?) := (← get).find? x then
contents := contents ++ (← lift <| tag (.localName x which c d?) x.toString)
else
contents := contents ++ x.toString
inVar := false
else
let pre := str.takeWhile (· != '{')
str := str.dropPrefix pre |>.drop 1
contents := contents ++ pre.copy
inVar := true
lift <| tag .comment contents
| _ => lift <| tag .comment "error extracting comment..."
| ``FreeSyntax.identItem, _, _ => do
let cat := stx[0]
if let .ident info' _ c _ := cat then
let d? ← findDocString? (← getEnv) c
-- TODO render markdown
let tok ←
lift <| tag (.nonterminal c d?) <|
match c with
| .str c' "pseudo" => c'.toString
| _ => c.toString
return infoWrap info <| infoWrap info' tok
return "_" ++ (← lift <| tag .bnf ":") ++ (← production which cat)
| ``FreeSyntax.namedIdentItem, _, _ => do
let name := stx[0]
let cat := stx[2]
if let .ident info _ x _ := name then
if let .ident info' _ c _ := cat then
let d? ← findDocString? (← getEnv) c
modify (·.insert x (c, d?))
return (← lift <| tag (.localName x which c d?) x.toString) ++ (← lift <| tag .bnf ":") ++ (← production which cat)
return "_" ++ (← lift <| tag .bnf ":") ++ (← production which cat)
| ``FreeSyntax.antiquoteItem, _, _ => do
let _name := stx[1]
let cat := stx[3]
let qual := stx[4].getOptional?
let content ← production which cat
match qual with
| some (.atom info op)
-- The parser creates token.«+» (etc) nodes for these, which should ideally be looked through
| some (.node _ _ #[.atom info op]) => infoWrapTrailing info <$> lift (kleeneLike op content)
| _ => pure content
| ``FreeSyntax.modItem, _, _ => do
let stxs := stx[1]
let mod := stx[3]
let content ← production which stxs
match mod with
| .atom info op
-- The parser creates token.«+» (etc) nodes for these, which should ideally be looked through
| .node _ _ #[.atom info op] => infoWrapTrailing info <$> lift (kleeneLike op content)
| _ => pure content
| _, some k', #[a, b, c, d] => do
--
let doc? ← findDocString? (← getEnv) k'
let last :=
if let .node _ _ #[] := d then c else d
if let some kw := keywordParsers.lookup k' then
return infoWrap2 a.getHeadInfo last.getTailInfo (← lift (tag .keyword kw))
-- Optional quasiquotes $NAME? where kind FOO is expected look like this:
-- k := FOO.antiquot
-- k' := FOO
-- args := #["$", [], `NAME?, []]
if let (.atom _ "$", .node _ nullKind #[], .ident _ _ x _) := (a, b, c) then
if x.toString.back == '?' then
return infoWrap2 a.getHeadInfo last.getTailInfo ((← lift <| tag (.nonterminal k' doc?) (nonTerm k')) ++ (← lift <| tag .bnf "?"))
infoWrap2 a.getHeadInfo last.getTailInfo <$> lift (tag (.nonterminal k' doc?) (nonTerm k'))
| _, _, _ => do
let mut out := Format.nil
for a in args do
out := out ++ (← production which a)
let doc? ← findDocString? (← getEnv) k
lift <| tag (.fromNonterminal k doc?) out
end Meta.PPrint.Grammar
def categoryOf (env : Environment) (kind : Name) : Option Name := do
for (catName, contents) in (Lean.Parser.parserExtension.getState env).categories do
for (k, ()) in contents.kinds do
if kind == k then return catName
failure
open Manual.Meta.PPrint Grammar in
def getBnf (config : FreeSyntaxConfig) (isFirst : Bool) (stxs : List Syntax) : DocElabM (TaggedText GrammarTag) := do
let bnf ← TagFormatT.run <| do
let lhs ← renderLhs config isFirst
let prods ←
match stxs with
| [] => pure []
| [p] => pure [(← renderProd config isFirst 0 p)]
| p::ps =>
let hd := indentIfNotOpen config.open (← renderProd config isFirst 0 p)
let tl ← ps.mapIdxM fun i s => renderProd config false i s
pure <| hd :: tl
pure <| lhs ++ (← tag .rhs (Format.nest 4 (.join (prods.map (.line ++ ·)))))
return bnf.render (w := 5)
where
indentIfNotOpen (isOpen : Bool) (f : Format) : Format :=
if isOpen then f else " " ++ f
renderLhs (config : FreeSyntaxConfig) (isFirst : Bool) : TagFormatT GrammarTag DocElabM Format := do
let cat := (categoryOf (← getEnv) config.name).getD config.name
let d? ← findDocString? (← getEnv) cat
let mut bnf : Format := (← tag (.nonterminal cat d?) s!"{nonTerm cat}") ++ " " ++ (← tag .bnf "::=")
if config.open || (!config.open && !isFirst) then
bnf := bnf ++ (" ..." : Format)
tag .lhs bnf
renderProd (config : FreeSyntaxConfig) (isFirst : Bool) (which : Nat) (stx : Syntax) : TagFormatT GrammarTag DocElabM Format := do
let stx := removeTrailing stx
let bar := (← tag .bnf "|") ++ " "
if !config.open && isFirst then
production which stx |>.run' {}
else
return bar ++ .nest 2 (← production which stx |>.run' {})
def testGetBnf (config : FreeSyntaxConfig) (isFirst : Bool) (stxs : List Syntax) : TermElabM String := do
let (tagged, _) ← getBnf config isFirst stxs |>.run ⟨default, default, default, default⟩ {} {partContext := ⟨⟨default, default, default, default, default⟩, default⟩}
pure tagged.stripTags
namespace Tests
open FreeSyntax
def selectedParser : Parser := leading_parser
ident >> "| " >> incQuotDepth (parserOfStack 1)
elab "#test_syntax" arg:selectedParser : command => do
let bnf ← Command.liftTermElabM (testGetBnf {name := (TSyntax.mk arg.raw[0]).getId, title := (FileMap.ofString "", #[])} true [arg.raw[2]])
logInfo bnf
/--
info: term ::= ...
| term < term
-/
#guard_msgs in
#test_syntax term | $x < $y
/--
info: term ::= ...
| term term*
-/
#guard_msgs in
#test_syntax term | $e $e*
/--
info: term ::= ...
| term [(term term),*]
-/
#guard_msgs in
#test_syntax term | $e [$[$e $e],*]
elab "#test_free_syntax" x:ident arg:free_syntaxes : command => do
let bnf ← Command.liftTermElabM (testGetBnf {name := x.getId, title := (FileMap.ofString "", #[])} true (FreeSyntax.decodeMany arg |>.map FreeSyntax.decode))
logInfo bnf
/--
info: go ::= ...
| thing term
| foo
-/
#guard_msgs in
#test_free_syntax go
"thing" term
*****
"foo"
example := () -- Keep it from eating the next doc comment
/--
info: antiquot ::= ...
| $ident(:ident)?suffix?
| $( term )(:ident)?suffix?
-/
#guard_msgs in
#test_free_syntax antiquot
"$"ident(":"ident)?(suffix)?
*******
"$(" term ")"(":"ident)?(suffix)?
end Tests
instance : MonadWithReaderOf Core.Context DocElabM := inferInstanceAs (MonadWithReaderOf Core.Context (ReaderT DocElabContext (ReaderT PartElabM.State (StateT DocElabM.State TermElabM))))
def withOpenedNamespace (ns : Name) (act : DocElabM α) : DocElabM α :=
try
pushScope
let mut openDecls := (← readThe Core.Context).openDecls
for n in (← resolveNamespaceCore ns) do
openDecls := .simple n [] :: openDecls
activateScoped n
withTheReader Core.Context ({· with openDecls := openDecls}) act
finally
popScope
def withOpenedNamespaces (nss : List Name) (act : DocElabM α) : DocElabM α :=
(nss.foldl (init := id) fun acc ns => withOpenedNamespace ns ∘ acc) act
inductive SearchableTag where
| metavar
| keyword
| literalIdent
| ws
deriving DecidableEq, Ord, Repr
open Lean.Syntax in
instance : Quote SearchableTag where
quote
| .metavar => mkCApp ``SearchableTag.metavar #[]
| .keyword => mkCApp ``SearchableTag.keyword #[]
| .literalIdent => mkCApp ``SearchableTag.literalIdent #[]
| .ws => mkCApp ``SearchableTag.ws #[]
def SearchableTag.toKey : SearchableTag → String
| .metavar => "meta"
| .keyword => "keyword"
| .literalIdent => "literalIdent"
| .ws => "ws"
def SearchableTag.toJson : SearchableTag → Json := Json.str ∘ SearchableTag.toKey
instance : ToJson SearchableTag where
toJson := SearchableTag.toJson
def SearchableTag.fromJson? : Json → Except String SearchableTag
| .str "meta" => pure .metavar
| .str "keyword" => pure .keyword
| .str "literalIdent" => pure .literalIdent
| .str "ws" => pure .ws
| other =>
let s :=
match other with
| .str s => s.quote
| .arr .. => "array"
| .obj .. => "object"
| .num .. => "number"
| .bool b => toString b
| .null => "null"
throw s!"Expected 'meta', 'keyword', 'literalIdent', or 'ws', got {s}"
instance : FromJson SearchableTag where
fromJson? := SearchableTag.fromJson?
def searchableJson (ss : Array (SearchableTag × String)) : Json :=
.arr <| ss.map fun (tag, str) =>
json%{"kind": $tag.toKey, "string": $str}
partial def searchable (cat : Name) (txt : TaggedText GrammarTag) : Array (SearchableTag × String) :=
(go txt *> get).run' #[] |> fixup
where
dots : SearchableTag × String := (.metavar, "…")
go : TaggedText GrammarTag → StateM (Array (SearchableTag × String)) String
| .text s => do
ws s
pure s
| .append xs => do
for ⟨x, _⟩ in xs.attach do
discard <| go x
pure ""
| .tag .keyword x => do
let x' ← go x
modify (·.push (.keyword, x'))
pure x'
| .tag .lhs _ => pure ""
| .tag (.nonterminal (.str (.str .anonymous "token") _) _) (.text txt) => do
let txt := txt.trimAscii.copy
modify (·.push (.keyword, txt))
pure txt
| .tag (.nonterminal ``Lean.Parser.Attr.simple ..) txt => do
let kw := txt.stripTags.trimAscii.copy
modify (·.push (.keyword, kw))
pure kw
| .tag (.nonterminal ..) _ => do
ellipsis
pure dots.2
| .tag .literalIdent (.text s) => do
modify (·.push (.literalIdent, s))
return s
| .tag .bnf (.text s) => do
let s := s.trimAscii.copy
modify fun st => Id.run do
match s with
-- Suppress leading |
| "|" => if st.isEmpty then return st
-- Don't add repetition modifiers after ... or to an empty output
| "*" | "?" | ",*" =>
if let some _ := suffixMatches #[(· == dots)] st then return st
if st.isEmpty then return st
-- Don't parenthesize just "..."
| ")" | ")?" | ")*" =>
if let some st' := suffixMatches #[(· == (.metavar, "(")) , (· == dots)] st then return st'.push dots
| _ => pure ()
return st.push (.metavar, s)
pure s
| .tag other txt => do
go txt
fixup (s : Array (SearchableTag × String)) : Array (SearchableTag × String) :=
let s := s.popWhile (·.1 == .ws) -- Remove trailing whitespace
match cat with
| `command => Id.run do
-- Drop leading ellipses from commands
for h : i in [0:s.size] do
if s[i] ∉ [dots, (.metavar, "?"), (.ws, " ")] then return s.extract i s.size
return s
| _ => s
ws (s : String) : StateM (Array (SearchableTag × String)) Unit := do
if !s.isEmpty && s.all Char.isWhitespace then
modify fun st =>
if st.isEmpty then st
else if st.back?.map (·.1 == .ws) |>.getD true then st
else st.push (.ws, " ")
suffixMatches (suffix : Array (SearchableTag × String → Bool)) (st : (Array (SearchableTag × String))) : Option (Array (SearchableTag × String)) := do
let mut suffix := suffix
for h : i in [0 : st.size] do
match suffix.back? with
| none => return st.extract 0 (st.size - i)
| some p =>
have : st.size > 0 := by
let ⟨_, h, _⟩ := h
simp_all +zetaDelta
omega
let curr := st[st.size - (i + 1)]
if curr.1 matches .ws then continue
if p curr then
suffix := suffix.pop
else throw ()
if suffix.isEmpty then some #[] else none
ellipsis : StateM (Array (SearchableTag × String)) Unit := do
modify fun st =>
-- Don't push ellipsis onto ellipsis
if let some _ := suffixMatches #[(· == dots)] st then st
-- Don't alternate ellipses
else if let some st' := suffixMatches #[(· == dots), (· == (.metavar, "|"))] st then st'.push dots
else st.push dots
/-- info: some #[] -/
#guard_msgs in
#eval searchable.suffixMatches #[] #[]
/-- info: some #[(Manual.SearchableTag.keyword, "aaa")] -/
#guard_msgs in
#eval searchable.suffixMatches #[(· == (.metavar, "(")), (· == searchable.dots)] #[(.keyword, "aaa"),(.metavar, "("), (.ws, " "),(.metavar, "…")]
/-- info: some #[(Manual.SearchableTag.keyword, "aaa")] -/
#guard_msgs in
#eval searchable.suffixMatches #[(· == searchable.dots)] #[(.keyword, "aaa"),(.metavar, "…"), (.ws, " ")]
/-- info: some #[] -/
#guard_msgs in
#eval searchable.suffixMatches #[(· == searchable.dots)] #[(.metavar, "…"), (.ws, " ")]
/-- info: some #[] -/
#guard_msgs in
#eval searchable.suffixMatches #[(· == searchable.dots)] #[(.metavar, "…")]
open Manual.Meta.PPrint Grammar in
/--
Display actual Lean syntax, validated by the parser.
-/
@[directive_expander «syntax»]
def «syntax» : DirectiveExpander
| args, blocks => do
let config ← SyntaxConfig.parse.run args
let title ← do
let (fm, t) := config.title
DocElabM.withFileMap fm <| t.mapM elabInline
let env ← getEnv
let titleString := inlinesToString env (config.title.snd)
let mut content := #[]
let mut firstGrammar := true
for b in blocks do
match isGrammar? b with
| some (nameStx, argsStx, contents) =>
let grm ← elabGrammar nameStx config firstGrammar argsStx contents
content := content.push grm
firstGrammar := false
| _ =>
content := content.push <| ← elabBlock b
Doc.PointOfInterest.save (← getRef) titleString
(selectionRange := (← getRef)[0])
pure #[← `(Block.other {Block.syntax with data := ToJson.toJson (α := Option String × Name × String × Option Tag × Array Name) ($(quote titleString), $(quote config.name), $(quote config.getLabel), none, $(quote config.aliases.toArray))} #[Block.para #[$(title),*], $content,*])]
where
isGrammar? : Syntax → Option (Syntax × Array Syntax × StrLit)
| `(block|``` $nameStx:ident $argsStx* | $contents ```) =>
if nameStx.getId == `grammar then some (nameStx, argsStx, contents) else none
| _ => none
elabGrammar nameStx config isFirst (argsStx : Array Syntax) (str : TSyntax `str) := do
let args ← parseArgs <| argsStx.map (⟨·⟩)
let {of, prec} ← GrammarConfig.parse.run args
let config : SyntaxConfig :=
if let some n := of then
{name := n, «open» := false, title := config.title}
else config
let altStr ← parserInputString str
let p := andthen ⟨{}, whitespace⟩ <| andthen {fn := (fun _ => (·.pushSyntax (mkIdent config.name)))} (parserOfStack 0)
let scope := (← Verso.Genre.Manual.InlineLean.Scopes.getScopes).head!
withOpenedNamespace `Manual.FreeSyntax <| withOpenedNamespaces config.namespaces <| do
match runParser (← getEnv) (← getOptions) p altStr (← getFileName) (prec := prec) (openDecls := scope.openDecls) with
| .ok stx =>
Doc.PointOfInterest.save stx stx.getKind.toString
let bnf ← getBnf config.toFreeSyntaxConfig isFirst [FreeSyntax.decode stx]
let searchTarget := searchable config.name bnf
Hover.addCustomHover nameStx s!"Kind: {stx.getKind}\n\n````````\n{bnf.stripTags}\n````````"
let blockStx ← `(Block.other {Block.grammar with data := ToJson.toJson (($(quote stx.getKind), $(quote bnf), searchableJson $(quote searchTarget)) : Name × TaggedText GrammarTag × Json)} #[])
pure (blockStx)
| .error es =>
for (pos, msg) in es do
log (severity := .error) (mkErrorStringWithPos "<example>" pos msg)
throwError "Parse errors prevented grammar from being processed."
open Manual.Meta.PPrint Grammar in
/--
Display free-form syntax that isn't validated by Lean's parser.
Here, the name is simply for reference, and should not exist as a syntax kind.
The grammar of free-form syntax items is:
* strings - atoms
* doc_comments - inline comments
* ident - instance of nonterminal
* $ident:ident('?'|'*'|'+')? - named quasiquote (the name is rendered, and can be referred to later)
* '(' ITEM+ ')'('?'|'*'|'+')? - grouped sequence (potentially modified/repeated)
* ` `( `ident|...) - embedding parsed Lean that matches the specified parser
They can be separated by a row of `**************`
-/
@[directive_expander freeSyntax]
def freeSyntax : DirectiveExpander
| args, blocks => do
let config ← FreeSyntaxConfig.parse.run args
let title ← do
let (fm, t) := config.title
DocElabM.withFileMap fm <| t.mapM elabInline
let env ← getEnv
let titleString := inlinesToString env config.title.snd
let mut content := #[]
let mut firstGrammar := true
for b in blocks do
match isGrammar? b with
| some (nameStx, argsStx, contents) =>
let grm ← elabGrammar nameStx config firstGrammar argsStx contents
content := content.push grm
firstGrammar := false
| _ =>
content := content.push <| ← elabBlock b
pure #[← `(Block.other {Block.syntax with data := ToJson.toJson (α := Option String × Name × String × Option Tag × Array Name) ($(quote titleString), $(quote config.name), $(quote config.getLabel), none, #[])} #[Block.para #[$(title),*], $content,*])]
where
isGrammar? : Syntax → Option (Syntax × Array Syntax × StrLit)
| `(block|```$nameStx:ident $argsStx* | $contents:str ```) =>
if nameStx.getId == `grammar then some (nameStx, argsStx, contents) else none
| _ => none
elabGrammar nameStx config isFirst (argsStx : Array Syntax) (str : TSyntax `str) := do
let args ← parseArgs <| argsStx.map (⟨·⟩)
let () ← ArgParse.done.run args
let altStr ← parserInputString str
let p := andthen ⟨{}, whitespace⟩ <| categoryParser `free_syntaxes 0
withOpenedNamespace `Manual.FreeSyntax do
match runParser (← getEnv) (← getOptions) p altStr (← getFileName) (prec := 0) with
| .ok stx =>
let bnf ← getBnf config isFirst (FreeSyntax.decodeMany stx |>.map FreeSyntax.decode)
Hover.addCustomHover nameStx s!"Kind: {stx.getKind}\n\n````````\n{bnf.stripTags}\n````````"
-- TODO: searchable instead of Json.arr #[]
`(Block.other {Block.grammar with data := ToJson.toJson (($(quote stx.getKind), $(quote bnf), Json.arr #[]) : Name × TaggedText GrammarTag × Json)} #[])
| .error es =>
for (pos, msg) in es do
log (severity := .error) (mkErrorStringWithPos "<example>" pos msg)
throwError "Parse errors prevented grammar from being processed."
@[block_extension «syntax»]
def syntax.descr : BlockDescr where
traverse id data contents := do
if let .ok (title, kind, label, tag, aliases) := FromJson.fromJson? (α := Option String × Name × String × Option Tag × Array Name) data then
if tag.isSome then
pure none
else
let path := (← read).path
let tag ← Verso.Genre.Manual.externalTag id path kind.toString
pure <| some <| Block.other {Block.syntax with id := some id, data := toJson (title, kind, label, some tag, aliases)} contents
else
logError "Couldn't deserialize kind name for syntax block"
pure none
toTeX := none
toHtml :=
open Verso.Output.Html Verso.Doc.Html in
some <| fun goI goB id data content => do
let (titleString, label) ←
match FromJson.fromJson? (α := Option String × Name × String × Option Tag × Array Name) data with
| .ok (titleString, _, label, _, _) => pure (titleString, label)
| .error e =>
HtmlT.logError s!"Failed to deserialize syntax docs: {e} from {data}"
pure (none, "syntax")
let xref ← HtmlT.state
let attrs := xref.htmlId id
let (descr, content) ←
if let some (Block.para titleInlines) := content[0]? then
pure (titleInlines, content.drop 1)
else
HtmlT.logError s!"Didn't get a paragraph for the title inlines in syntax description {titleString}"
pure (#[], content)
let titleHtml ← descr.mapM goI
let titleHtml := if titleHtml.isEmpty then .empty else {{<span class="title">{{titleHtml}}</span>}}
pure {{
<div class="namedocs" {{attrs}}>
<span class="label">{{label}}</span>
{{titleHtml}}
<div class="text">
{{← content.mapM goB}}
</div>
</div>
}}
extraCss := [
r#"
.namedocs .title {
font-family: var(--verso-structure-font-family);
font-size: 1.1rem;
margin-top: 0;
margin-left: 1rem;
margin-right: 1.5rem;
margin-bottom: 0.75rem;
display: inline-block;
}
"#
]
def grammar := ()
def grammarCss :=
r#".grammar .keyword {
font-weight: 500 !important;
}
.grammar {
padding-top: 0.25rem;
padding-bottom: 0.25rem;
}
.grammar .comment {
font-style: italic;
font-family: var(--verso-text-font-family);
/* TODO add background and text colors to Verso theme, then compute a background here */
background-color: #fafafa;
border: 1px solid #f0f0f0;
}
.grammar .local-name {
font-family: var(--verso-code-font-family);
font-style: italic;
}
.grammar .nonterminal {
font-style: italic;
}
.grammar .nonterminal > .hover-info, .grammar .from-nonterminal > .hover-info, .grammar .local-name > .hover-info {
display: none;
}
.grammar .active {
background-color: #eee;
border-radius: 2px;
}
.grammar a {
color: inherit;
text-decoration: currentcolor underline dotted;
}
"#
def grammarJs :=
r#"
window.addEventListener("load", () => {
const innerProps = {
onShow(inst) { console.log(inst); },
onHide(inst) { console.log(inst); },
content(tgt) {
const content = document.createElement("span");
const state = tgt.querySelector(".hover-info").cloneNode(true);
state.style.display = "block";
content.appendChild(state);
/* Render docstrings - TODO server-side */
if ('undefined' !== typeof marked) {
for (const d of content.querySelectorAll("code.docstring, pre.docstring")) {
const str = d.innerText;
const html = marked.parse(str);
const rendered = document.createElement("div");
rendered.classList.add("docstring");
rendered.innerHTML = html;
d.parentNode.replaceChild(rendered, d);
}
}
content.style.display = "block";
content.className = "hl lean popup";
return content;
}
};
const outerProps = {
allowHtml: true,
theme: "lean",
placement: 'bottom-start',
maxWidth: "none",
delay: 100,
moveTransition: 'transform 0.2s ease-out',
onTrigger(inst, event) {
const ref = event.currentTarget;
const block = ref.closest('.hl.lean');
block.querySelectorAll('.active').forEach((i) => i.classList.remove('active'));
ref.classList.add("active");
},
onUntrigger(inst, event) {
const ref = event.currentTarget;
const block = ref.closest('.hl.lean');
block.querySelectorAll('.active').forEach((i) => i.classList.remove('active'));
}
};
tippy.createSingleton(tippy('pre.grammar.hl.lean .nonterminal.documented, pre.grammar.hl.lean .from-nonterminal.documented, pre.grammar.hl.lean .local-name.documented', innerProps), outerProps);
});
"#
open Verso.Output Html HtmlT in
private def nonTermHtmlOf (kind : Name) (doc? : Option String) (rendered : Html) : HtmlT Manual (ReaderT Multi.AllRemotes (ReaderT ExtensionImpls IO)) Html := do
let xref ← match (← state).resolveDomainObject syntaxKindDomain kind.toString with
| .error _ =>
pure none
| .ok dest =>
pure (some dest.link)
let addXref := fun html =>
match xref with
| none => html
| some tgt => {{<a href={{tgt}}>{{html}}</a>}}
return addXref <|
match doc? with
| some doc => {{
<span class="nonterminal documented" {{#[("data-kind", kind.toString)]}}>
<code class="hover-info"><code class="docstring">{{doc}}</code></code>
{{rendered}}
</span>
}}
| none => {{
<span class="nonterminal" {{#[("data-kind", kind.toString)]}}>
{{rendered}}
</span>
}}
structure GrammarHtmlContext where
skipKinds : NameSet := NameSet.empty.insert nullKind
lookingAt : Option Name := none
namespace GrammarHtmlContext
def default : GrammarHtmlContext := {}
def skip (k : Name) (ctx : GrammarHtmlContext) : GrammarHtmlContext :=
{ctx with skipKinds := ctx.skipKinds.insert k}
def look (k : Name) (ctx : GrammarHtmlContext) : GrammarHtmlContext :=
if ctx.skipKinds.contains k then ctx else {ctx with lookingAt := some k}
def noLook (ctx : GrammarHtmlContext) : GrammarHtmlContext :=
{ctx with lookingAt := none}
end GrammarHtmlContext
open Verso.Output Html in
abbrev GrammarHtmlM := ReaderT GrammarHtmlContext (HtmlT Manual (ReaderT Multi.AllRemotes (ReaderT ExtensionImpls IO)))
private def lookingAt (k : Name) : GrammarHtmlM α → GrammarHtmlM α := withReader (·.look k)
private def notLooking : GrammarHtmlM α → GrammarHtmlM α := withReader (·.noLook)
def productionDomain : Name := `Manual.Syntax.production
open Verso.Search in
def productionDomainMapper : DomainMapper where
displayName := "Syntax"
className := "syntax-domain"
dataToSearchables :=
"(domainData) =>
Object.entries(domainData.contents).map(([key, value]) => ({
// TODO find a way to not include the “meta” parts of the string
// in the search key here, but still display them
searchKey: value[0].data.forms.map(v => v.string).join(''),
address: `${value[0].address}#${value[0].id}`,
domainId: 'Manual.Syntax.production',
ref: value,
}))"
open Verso.Output Html in
@[block_extension grammar]
partial def grammar.descr : BlockDescr := withHighlighting {
init s := s.addQuickJumpMapper productionDomain (productionDomainMapper.setFont { family := .code })
traverse id info _ := do
if let .ok (k, _, searchable) := FromJson.fromJson? (α := Name × TaggedText GrammarTag × Json) info then
let path ← (·.path) <$> read
let _ ← Verso.Genre.Manual.externalTag id path k.toString
modify fun st => st.saveDomainObject syntaxKindDomain k.toString id
let prodName := s!"{k} {searchable}"
modify fun st => st.saveDomainObject productionDomain prodName id
modify fun st => st.saveDomainObjectData productionDomain prodName (json%{"category": null, "kind": $k.toString, "forms": $searchable})
else
logError "Couldn't deserialize grammar info during traversal"
pure none
toTeX := none
toHtml :=
open Verso.Output.Html in
some <| fun _goI _goB id info _ => do
match FromJson.fromJson? (α := Name × TaggedText GrammarTag × Json) info with
| .ok (kind, bnf, _searchable) =>
let t ← match (← read).traverseState.externalTags.get? id with
| some dest => pure dest.htmlId.toString
| _ => Html.HtmlT.logError s!"Couldn't get HTML ID for grammar of {kind}" *> pure ""
pure {{
<pre class="grammar hl lean" data-lean-context="--grammar" id={{t}}>
{{← bnfHtml bnf |>.run (GrammarHtmlContext.default.skip kind) }}
</pre>
}}
| .error e =>
Html.HtmlT.logError s!"Couldn't deserialize BNF: {e}"
pure .empty
extraCss := [grammarCss, "#toc .split-toc > ol .syntax .keyword { font-family: var(--verso-code-font-family); font-weight: 600; }"]
extraJs := [grammarJs]
localContentItem _ json _ := open Verso.Output.Html in do
if let .arr #[_, .arr #[_, .arr toks]] := json then
let toks ← toks.mapM fun v => do
let Json.str str ← v.getObjVal? "string"
| throw "Not a string"
let .str k ← v.getObjVal? "kind"
| throw "Not a string"
pure (str, {{<span class={{k}}>{{str}}</span>}})
let (strs, toks) := toks.unzip
if strs == #["…"] || strs == #["..."] then
-- Don't add the item if it'd be useless for navigating the page
pure #[]
else
pure #[(String.join strs.toList, {{<span class="syntax">{{toks}}</span>}})]
else throw s!"Expected a Json array shaped like [_, [_, [tok, ...]]], got {json}"
}
where
bnfHtml : TaggedText GrammarTag → GrammarHtmlM Html
| .text str => pure <| .text true str
| .tag t txt => tagHtml t (bnfHtml txt)
| .append txts => .seq <$> txts.mapM bnfHtml
tagHtml (t : GrammarTag) (go : GrammarHtmlM Html) : GrammarHtmlM Html :=
match t with
| .lhs | .rhs => go
| .bnf => ({{<span class="bnf">{{·}}</span>}}) <$> notLooking go
| .comment => ({{<span class="comment">{{·}}</span>}}) <$> notLooking go
| .error => ({{<span class="err">{{·}}</span>}}) <$> notLooking go
| .literalIdent => ({{<span class="literal-ident">{{·}}</span>}}) <$> notLooking go
| .keyword => do
let inner ← go
if let some k := (← read).lookingAt then
unless k == nullKind do
if let some tgt := ((← HtmlT.state (genre := Manual) (m := ReaderT Multi.AllRemotes (ReaderT ExtensionImpls IO))).localTargets.keyword k none)[0]? then
return {{<a href={{tgt.href}}><span class="keyword">{{inner}}</span></a>}}
return {{<span class="keyword">{{inner}}</span>}}
| .nonterminal k doc? => do
let inner ← notLooking go
nonTermHtmlOf k doc? inner
| .fromNonterminal k none => do
let inner ← lookingAt k go
return {{<span class="from-nonterminal" {{#[("data-kind", k.toString)]}}>{{inner}}</span>}}
| .fromNonterminal k (some doc) => do
let inner ← lookingAt k go
return {{
<span class="from-nonterminal documented" {{#[("data-kind", k.toString)]}}>
<code class="hover-info"><code class="docstring">{{doc}}</code></code>
{{inner}}
</span>
}}
| .localName x n cat doc? => do
let doc :=
match doc? with
| none => .empty
| some d => {{<span class="sep"/><code class="docstring">{{d}}</code>}}
let inner ← notLooking go
-- The "token" class below triggers binding highlighting
return {{
<span class="local-name token documented" {{#[("data-kind", cat.toString)]}} data-binding=s!"grammar-var-{n}-{x}">
<code class="hover-info"><code>{{x.toString}} " : " {{cat.toString}}</code>{{doc}}</code>
{{inner}}
</span>
}}
def Inline.syntaxKind : Inline where
name := `Manual.syntaxKind
@[role_expander syntaxKind]
def syntaxKind : RoleExpander
| args, inlines => do
let () ← ArgParse.done.run args
let #[arg] := inlines
| throwError "Expected exactly one argument"
let `(inline|code( $syntaxKindName:str )) := arg
| throwErrorAt arg "Expected code literal with the syntax kind name"
let kName := syntaxKindName.getString.toName
let id : Ident := mkIdentFrom syntaxKindName kName
let k ← try realizeGlobalConstNoOverloadWithInfo id catch _ => pure kName
let doc? ← findDocString? (← getEnv) k
return #[← `(Inline.other {Inline.syntaxKind with data := ToJson.toJson (α := Name × String × Option String) ($(quote k), $(quote syntaxKindName.getString), $(quote doc?))} #[Inline.code $(quote k.toString)])]
@[inline_extension syntaxKind]
def syntaxKind.inlinedescr : InlineDescr := withHighlighting {
traverse _ _ _ := do
pure none
toTeX :=
some <| fun go _ _ content => do
pure <| .seq <| ← content.mapM fun b => do
pure <| .seq #[← go b, .raw "\n"]
extraCss := [grammarCss]
extraJs := [grammarJs]
toHtml :=
open Verso.Output.Html in
some <| fun goI _ data inls => do
match FromJson.fromJson? (α := Name × String × Option String) data with
| .error e =>
Html.HtmlT.logError s!"Couldn't deserialize syntax kind name: {e}"
return {{<code>{{← inls.mapM goI}}</code>}}
| .ok (k, showAs, doc?) =>
return {{
<code class="grammar">
{{← nonTermHtmlOf k doc? showAs}}
</code>
}}
} |
reference-manual/Manual/Meta/Basic.lean | module
public import Lean.Data.Position
public import Lean.Syntax
public import Lean.Environment
public import Lean.Parser.Types
public import Lean.Elab.Command
import Lean.Parser
import Verso.Parser
import Verso.Doc.ArgParse
import SubVerso.Highlighting
open Lean
namespace Manual
public def parserInputString [Monad m] [MonadFileMap m]
(str : TSyntax `str) :
m String := do
let text ← getFileMap
let preString := String.Pos.Raw.extract text.source 0 (str.raw.getPos?.getD 0)
let mut code := ""
for c in preString.toSlice.chars do
if c == '\n' then code := code.push '\n'
else
for _ in [0:c.utf8Size] do
code := code.push ' '
let strOriginal? : Option String := do
let ⟨start, stop⟩ ← str.raw.getRange?
start.extract text.source stop
code := code ++ strOriginal?.getD str.getString
return code
public structure SyntaxError where
pos : Position
endPos : Position
text : String
deriving ToJson, FromJson, BEq, Repr
open Lean.Syntax in
public instance : Quote Position where
quote
| .mk l c => mkCApp ``Position.mk #[quote l, quote c]
open Lean.Syntax in
public instance : Quote SyntaxError where
quote
| .mk pos endPos text => mkCApp ``SyntaxError.mk #[quote pos, quote endPos, quote text]
-- Based on mkErrorMessage used in Lean upstream - keep them in synch for best UX
open Lean.Parser in
private partial def mkSyntaxError (c : InputContext) (pos : String.Pos.Raw) (stk : SyntaxStack) (e : Parser.Error) : SyntaxError := Id.run do
let mut pos := pos
let mut endPos? := none
let mut e := e
unless e.unexpectedTk.isMissing do
-- calculate error parts too costly to do eagerly
if let some r := e.unexpectedTk.getRange? then
pos := r.start
endPos? := some r.stop
let unexpected := match e.unexpectedTk with
| .ident .. => "unexpected identifier"
| .atom _ v => s!"unexpected token '{v}'"
| _ => "unexpected token" -- TODO: categorize (custom?) literals as well?
e := { e with unexpected }
-- if there is an unexpected token, include preceding whitespace as well as the expected token could
-- be inserted at any of these places to fix the error; see tests/lean/1971.lean
if let some trailing := lastTrailing stk then
if trailing.stopPos == pos then
pos := trailing.startPos
return {
pos := c.fileMap.toPosition pos
endPos := (c.fileMap.toPosition <$> endPos?).getD (c.fileMap.toPosition (pos + c.get pos))
text := toString e
}
where
-- Error recovery might lead to there being some "junk" on the stack
lastTrailing (s : SyntaxStack) : Option Substring.Raw :=
s.toSubarray.findSomeRevM? (m := Id) fun stx =>
if let .original (trailing := trailing) .. := stx.getTailInfo then pure (some trailing)
else none
open Lean.Parser in
public def runParserCategory (env : Environment) (opts : Lean.Options) (catName : Name) (input : String) (fileName : String := "<example>") : Except (List (Position × String)) Syntax :=
let p := andthenFn whitespace (categoryParserFnImpl catName)
let ictx := mkInputContext input fileName
let s := p.run ictx { env, options := opts } (getTokenTable env) (mkParserState input)
if !s.allErrors.isEmpty then
Except.error (toErrorMsg ictx s)
else if ictx.atEnd s.pos then
Except.ok s.stxStack.back
else
Except.error (toErrorMsg ictx (s.mkError "end of input"))
where
toErrorMsg (ctx : InputContext) (s : ParserState) : List (Position × String) := Id.run do
let mut errs := []
for (pos, _stk, err) in s.allErrors do
let pos := ctx.fileMap.toPosition pos
errs := (pos, toString err) :: errs
errs.reverse
open Lean.Parser in
/--
A version of `Manual.runParserCategory` that returns syntax errors located the way Lean does.
-/
public def runParserCategory' (env : Environment) (opts : Lean.Options) (catName : Name) (input : String) (fileName : String := "<example>") : Except (Array SyntaxError) Syntax :=
let p := andthenFn whitespace (categoryParserFnImpl catName)
let ictx := mkInputContext input fileName
let s := p.run ictx { env, options := opts } (getTokenTable env) (mkParserState input)
if !s.allErrors.isEmpty then
Except.error <| toSyntaxErrors ictx s
else if ictx.atEnd s.pos then
Except.ok s.stxStack.back
else
Except.error (toSyntaxErrors ictx (s.mkError "end of input"))
where
toSyntaxErrors (ictx : InputContext) (s : ParserState) : Array SyntaxError :=
s.allErrors.map fun (pos, stk, e) => (mkSyntaxError ictx pos stk e)
open Lean.Parser in
public def runParser
(env : Environment) (opts : Lean.Options)
(p : Parser) (input : String) (fileName : String := "<example>")
(currNamespace : Name := .anonymous) (openDecls : List OpenDecl := [])
(prec : Nat := 0) :
Except (List (Position × String)) Syntax :=
let ictx := mkInputContext input fileName
let p' := adaptCacheableContext ({· with prec}) p
let s := p'.fn.run ictx { env, currNamespace, openDecls, options := opts } (getTokenTable env) (mkParserState input)
if !s.allErrors.isEmpty then
Except.error (toErrorMsg ictx s)
else if ictx.atEnd s.pos then
Except.ok s.stxStack.back
else
Except.error (toErrorMsg ictx (s.mkError "end of input"))
where
toErrorMsg (ctx : InputContext) (s : ParserState) : List (Position × String) := Id.run do
let mut errs := []
for (pos, _stk, err) in s.allErrors do
let pos := ctx.fileMap.toPosition pos
errs := (pos, toString err) :: errs
errs.reverse
open Lean Elab Command in
public def commandWithoutAsync : (act : CommandElabM α) → CommandElabM α :=
withScope fun sc =>
{sc with opts := Elab.async.set sc.opts false}
public def withoutAsync [Monad m] [MonadWithOptions m] : (act : m α) → m α :=
withOptions (Elab.async.set · false)
open scoped Lean.Doc.Syntax in
/--
If the array of inlines contains a single code element, it is returned. Otherwise, an error is
logged and `none` is returned.
-/
public def oneCodeStr? [Monad m] [MonadError m] [MonadLog m] [AddMessageContext m] [MonadOptions m]
(inlines : Array (TSyntax `inline)) : m (Option StrLit) := do
let #[code] := inlines
| if inlines.size == 0 then
Lean.logError "Expected a code element"
else
logErrorAt (mkNullNode inlines) "Expected one code element"
return none
let `(inline|code($code)) := code
| logErrorAt code "Expected a code element"
return none
return some code |
reference-manual/Manual/Meta/ParserAlias.lean | import Lean.Elab.Term
import Lean.Elab.Tactic
import Verso.Code.Highlighted
import Verso.Doc.ArgParse
import Verso.Doc.Suggestion
import SubVerso.Highlighting.Code
import VersoManual
import Manual.Meta.Basic
import Manual.Meta.PPrint
namespace Manual
open Verso ArgParse Doc Elab Genre.Manual Html Code Highlighted.WebAssets
open Lean Elab Term Tactic
open SubVerso.Highlighting
def parserAliasDomain := `Manual.parserAlias
def Block.parserAlias (name : Name) (declName : Name) («show» : Option String) (stackSz? : Option Nat) (autoGroupArgs : Bool) (docs? : Option String) (argCount : Nat) : Block where
name := `Manual.Block.parserAlias
-- These are represented as an array, rather than using the ToJson instance for a tuple, because
-- the traversal pass only needs two fields and it's wasteful to deserialize the whole thing.
data := Json.arr #[
ToJson.toJson name,
ToJson.toJson declName,
ToJson.toJson «show»,
ToJson.toJson stackSz?,
ToJson.toJson autoGroupArgs,
ToJson.toJson docs?,
ToJson.toJson argCount
]
structure ParserAliasOptions where
name : Name
«show» : Option String
def ParserAliasOptions.parse [Monad m] [MonadError m] : ArgParse m ParserAliasOptions :=
ParserAliasOptions.mk <$> .positional `name .name <*> .named `show .string true
@[directive_expander parserAlias]
def parserAlias : DirectiveExpander
| args, more => do
let opts ← ParserAliasOptions.parse.run args
let {declName, stackSz?, autoGroupArgs} ← Parser.getParserAliasInfo opts.name
let docs? ← findDocString? (← getEnv) declName
let some mdAst := MD4Lean.parse (docs?.getD "")
| throwError "Failed to parse docstring as Markdown"
let contents ← mdAst.blocks.mapM (Markdown.blockFromMarkdown · Markdown.strongEmphHeaders)
let userContents ← more.mapM elabBlock
let argCount :=
match (← Lean.Parser.getAlias Lean.Parser.parserAliasesRef opts.name) with
| some (.unary ..) => 1
| some (.binary ..) => 2
| _ => 0
pure #[← ``(Verso.Doc.Block.other (Block.parserAlias $(quote opts.name) $(quote declName) $(quote opts.show) $(quote stackSz?) $(quote autoGroupArgs) $(quote docs?) $(quote argCount)) #[$(contents ++ userContents),*])]
@[inline]
private def getFromJson {α} [Inhabited α] [FromJson α] [Monad m] (v : Json) : HtmlT Genre.Manual m α:=
match FromJson.fromJson? (α := α) v with
| .error e => do
Verso.Doc.Html.HtmlT.logError
s!"Failed to deserialize parser alias data while generating HTML for a parser alias docstring.\nError: {e}\nJSON: {v}\n\n"
pure default
| .ok v => pure v
open Verso.Genre.Manual.Markdown in
open Lean Elab Term Parser Tactic in
@[block_extension Block.parserAlias]
def parserAlias.descr : BlockDescr where
init st := st
|>.setDomainTitle parserAliasDomain "Parser Alias Documentation"
|>.setDomainDescription parserAliasDomain "Detailed descriptions of parser aliases"
traverse id info _ := do
let Json.arr #[ name, _, «show», _, _, _, _] := info
| do logError s!"Failed to deserialize docstring data while traversing a parser alias, expected array but got {info}"; pure none
let .ok (name, «show») := do return (← FromJson.fromJson? (α := Name) name, ← FromJson.fromJson? (α := Option String) «show»)
| do logError "Failed to deserialize docstring data while traversing a parser alias"; pure none
let path ← (·.path) <$> read
let _ ← Verso.Genre.Manual.externalTag id path <| show.getD name.toString
Index.addEntry id {term := Inline.code <| show.getD name.toString}
modify fun st => st.saveDomainObject parserAliasDomain name.toString id
pure none
toHtml := some <| fun _goI goB id info contents =>
open Verso.Doc.Html in
open Verso.Output Html in do
let Json.arr #[ name, declName, «show», stackSz?, autoGroupArgs, docs?, argCount] := info
| do Verso.Doc.Html.HtmlT.logError s!"Failed to deserialize docstring data while making HTML for parser alias, expected array but got {info}"; pure .empty
let name ← getFromJson (α := Name) name
let declName ← getFromJson (α := Name) declName
let «show» ← getFromJson (α := Option String) «show»
let stackSz? ← getFromJson (α := Option Nat) stackSz?
let autoGroupArgs ← getFromJson (α := Bool) autoGroupArgs
let docs? ← getFromJson (α := Option String) docs?
let argCount ← getFromJson (α := Nat) argCount
let x : Highlighted := .token ⟨.keyword declName none docs?, show.getD name.toString⟩
let args : Highlighted :=
match argCount with
| 1 => .seq <|
#[.token ⟨.unknown, "("⟩, .token ⟨.unknown, "p"⟩, .token ⟨.unknown, ")"⟩]
| 2 => .seq <|
#[.token ⟨.unknown, "("⟩, .token ⟨.unknown, "p1"⟩, .token ⟨.unknown, ", "⟩, .token ⟨.unknown, "p2"⟩, .token ⟨.unknown, ")"⟩]
| _ => .empty
let xref ← HtmlT.state
let idAttr := xref.htmlId id
let arity : Html :=
match stackSz? with
| some n => {{s!"Arity: {n}"}}
| none => {{"Arity is sum of arguments' arities"}}
let grp :=
if autoGroupArgs then
some {{"Automatically wraps arguments in a " <code>"null"</code> " node unless there's exactly one"}}
else none
let metadata :=
match grp with
| none => {{<p>{{arity}}</p>}}
| some g => {{<ul><li>{{arity}}</li><li>{{g}}</li></ul>}}
return {{
<div class="namedocs" {{idAttr}}>
{{permalink id xref false}}
<span class="label">"parser alias"</span>
<pre class="signature hl lean block">{{← (Highlighted.seq #[x, args]).toHtml (g := Verso.Genre.Manual)}}</pre>
<div class="text">
{{metadata}}
{{← contents.mapM goB}}
</div>
</div>
}}
toTeX := none
extraCss := [highlightingStyle, docstringStyle]
extraJs := [highlightingJs] |
reference-manual/Manual/Meta/LakeCheck.lean | import Lean.Elab.Command
import Lean.Elab.InfoTree
import Verso
import Verso.Doc.ArgParse
import Verso.Doc.Elab.Monad
import VersoManual
import Verso.Code
import SubVerso.Highlighting
import SubVerso.Examples
import Manual.Meta.Basic
import Manual.Meta.ExpectString
open Lean Elab
open Verso ArgParse Doc Elab Genre.Manual Html Code Highlighted.WebAssets
open SubVerso.Highlighting Highlighted
open Lean.Elab.Tactic.GuardMsgs
namespace Manual
private partial def parseOpts [Monad m] [MonadInfoTree m] [MonadLiftT CoreM m] [MonadEnv m] [MonadError m] : ArgParse m (List String) :=
(.many (.positional `subcommand stringOrIdent))
where
stringOrIdent : ValDesc m String := {
get
| .name x => pure <| x.getId.toString (escape := false)
| .str x => pure x.getString
| .num n => throwErrorAt n "Expected string or identifier"
signature := .Ident ∪ .String
description := "Subcommand"
}
/--
Check that the output of `lake --help` has not changed unexpectedly
-/
@[code_block_expander lakeHelp]
def lakeHelp : CodeBlockExpander
| args, str => do
let sub ← parseOpts.run args
let args := #["--help"] ++ sub.toArray
let out ← IO.Process.output {cmd := "lake", args}
if out.exitCode != 0 then
throwError
m!"When running 'lake --help', the exit code was {out.exitCode}\n" ++
m!"Stderr:\n{out.stderr}\n\nStdout:\n{out.stdout}\n\n"
let lakeOutput := out.stdout
discard <| expectString "'lake --help' output" str lakeOutput (useLine := useLine)
return #[]
where
-- Ignore the version spec or empty lines to reduce false positives
useLine (l : String) : Bool :=
!l.isEmpty && !"Lake version ".isPrefixOf l
/--
Check that the output of `lake CMD help` has not changed unexpectedly.
This was introduced to get CI unstuck when `lake --help cache` was broken temporarily, but `lake cache help` worked.
-/
@[code_block_expander lakeCacheHelp]
def lakeCacheHelp : CodeBlockExpander
| args, str => do
let sub ← parseOpts.run args
let args := #["cache", "help"] ++ sub
let out ← IO.Process.output {cmd := "lake", args}
if out.exitCode != 0 then
throwError
m!"When running 'lake --help', the exit code was {out.exitCode}\n" ++
m!"Stderr:\n{out.stderr}\n\nStdout:\n{out.stdout}\n\n"
let lakeOutput := out.stdout
discard <| expectString s!"'lake {sub} help' output" str lakeOutput (useLine := useLine)
return #[]
where
-- Ignore the version spec or empty lines to reduce false positives
useLine (l : String) : Bool :=
!l.isEmpty && !"Lake version ".isPrefixOf l |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.