Repository navigation
Description
Proposal
Add an attribute that allows overriding the representation of an inductive type. All projections, constructors and casesOn should then become noncomputable by default; this should be overridable by @[implemented_by] and friends though. However, @[implemented_by] and friends should not work when the inductive type wasn't declared with @[override_repr].
Motivation:
In some cases there are two representations of a type: one that works well for proofs and another that works well at runtime but doesn't allow for proofs. Infinite lists are an example of this:
-- works well for proofs but inefficient
def InfiniteList (α : Type u) := Nat → α
-- works well at runtime but is formally an empty type
inductive InfiniteList (α : Type u) where
| cons (x : α) (l : Thunk (InfiniteList α))The @[override_repr] attribute would then allow specifying a "model implementation" of a type for proofs and using another type for runtime:
inductive InfiniteListImpl (α : Type u) where
| cons (x : α) (l : Thunk (InfiniteList α))
@[override_repr InfiniteListImpl]
structure InfiniteList (α : Type u) where
get : Nat → αSince InfiniteListImpl is now used as the representation of InfiniteList, the usual implementation of InfiniteList.mk and InfiniteList.get doesn't make any sense anymore (since it relied on the representation being the one of InfiniteList). Thus they should become noncomputable by default. However, you should then be able to override this by specifying your own implementation:
def InfiniteListImpl.get {α : Type u} (l : InfiniteListImpl α) (n : Nat) : α :=
match n, l with
| 0, .cons x t => x
| k + 1, .cons x t => t.get.get k
unsafe def InfiniteList.getImpl {α : Type u} (l : InfiniteList α) (n : Nat) : α := (unsafeCast l : InfiniteListImpl α).get n
attribute [implemented_by InfiniteList.getImpl] InfiniteList.getOverriding projections (and constructors) only makes sense with @[override_repr] though; as such it should be forbidden for regular inductives and point to @[override_repr]:
structure InfiniteList (α : Type u) where
get : Nat → α
unsafe def InfiniteList.getImpl {α : Type u} (l : InfiniteList α) (n : Nat) : α := (unsafeCast l : InfiniteListImpl α).get n
/-
invalid implemented_by: target is a projection of InfiniteList but InfiniteList doesn't have an `@[override_repr]` attribute.
-/
attribute [implemented_by InfiniteList.getImpl] InfiniteList.getAnother use case is a simpler definition of Erased that has good reduction properties:
@[override_repr True]
structure Erased (α : Sort u) where
out : αSpecifying True here should make the representation into the same of True: ◾ (erased). The behavior should then also match what you'd expect from Erased: Erased.out is noncomputable and Erased.mk would be noncomputable but is erased anyways so works similarly to proofs.
Community Feedback
Impact
Add 👍 to issues you consider important. If others benefit from the changes in this proposal being added, please ask them to add 👍 to it.
Activity
nomeata commentedon Jul 24, 2025
Thanks for the RFC! Something like this is on my wishlist as well.
I wonder if we can do without unsafe here; an equivalent to
csimpwould be nice. What if you first register the whole type as noncomputable, then define an equivalence to another type (back and forth with proofs, likeEquiv), and then tell the compiler to make these conversation functions casts. Then one can addcsimplemmas for the existing noncomputable functions on the model type. Would that work for your use cases?Rob23oba commentedon Jul 24, 2025
For these use cases, mathlib could perhaps define:
But there are cases where this doesn't work (the examples I've provided above) that need to be supported directly.
datokrat commentedon Jul 24, 2025
@nomeata's suggestion could be generalized to use cases such as
Erasedif instead of an equivalence, only an arbitrary map from the kernel's representation to the internal representation is required.Worked example for `Erased`
@nomeata's extension would also make it possible to safely create a version of Mathlib's
Shrink, which "shrinks" a type into a lower universe given a nonconstructive proof that the type is small enough, where the shrinking and unshrinking operations are both computable (and compiled toid).Rob23oba commentedon Jul 24, 2025
Hmm that's also an interesting idea; I guess the idea is similar to the
WithReprexcept theofRepr/toReprpart is handled for you (that you then usecsimplater to implement constructors and projections). Kinda funny since @zwarich questioned whethercsimpshould even be supported (I guess the answer is yes?)Some questions:
no_reprandoverride_repr? Should this simply be rejected in the sense of "Erased doesn't have a representation"?InfiniteList? There, you can't really write atoImplfunction that isn't unsafe (sinceInfiniteListImplisn't inhabited).@[override_repr]in a different module? Should this be prohibited? (probably)Otherwise, this idea is quite nice because you don't need to
unsafeCastyourself (and in particular often don't needunsafeat all) and it's simpler to specify the override than with myWithReprImplabove.zwarich commentedon Jul 24, 2025
This is implicitly assuming that the compiler can't exploit a type (or individual constructor) being uninhabited in its representation choices. Edit: I guess the assumption is technically being made by the
unsafecode, not theoverride_repritself.Rob23oba commentedon Jul 24, 2025
You're right; but Lean doesn't have support for coinductive types and you certainly want to be able to use such a representation. I guess if it would exploit this then either:
Thunkor a function wouldn't be consideredInfiniteList) to make such judgments.sgraf812 commentedon Jul 24, 2025
FWIW, I think a "safe" implementation could be achieved by axiomatizing a wrapper around
ThunkcalledLatertogether with the "usual" applicative instance and the Löb induction/guarded fixpoint operatorgfix : (Later α -> α) -> α: https://github.com/sgraf812/abs-den.lean/blob/3afc0c5532ef85f5056da8437dfdd30722224937/igdtt/IGDTT/Axioms.leanI don't think the compiler would be prone to peeking into the definition of
Lateras it would be prone to reasoning aboutThunk.My axiomatization is often enough for simple guarded recursive programs. Plus, you could justify every such axiom by providing a proof in the model of guarded domain theory. (Eliminating the later modality in a finite way is still a safety issue, though; every use of
unsafeForcein a function such asStream.takemust be audited.)Unfortunately last time I tried I encountered some strange segfaults. Perhaps it's better with the new compiler.
datokrat commentedon Jul 24, 2025
Responding to #9508 (comment):
In my opinion yes, because this behavior feels consistent with the fact that I can't use a
noncomputablefunction in computable code even if I later usedcsimp/implemented_by. I suppose this helps that things are compiled in order.Sadly, the
inductive-based implementation doesn't fit nicely into this approach. However, we can get (at least asymptotically) efficientInfiniteLists with a different implementation:an attempt at `InfiniteList`
Given that
override_reprworks as proposed, nounsafeCast/implemented_byis necessary at all, so all the "unsafety" is encapsulated in the proposed language feature. I haven't tested whether this comes with a performance penalty, though.Yes, I think I'd forbid that. Personally, I even find it questionable that
implemented_byworks beyond module boundaries because it makes it really hard to find the actual implementation of a type/def.Rob23oba commentedon Jul 25, 2025
Maybe to address 1 and 3 we can use a design similar to computed fields? The
withclause currently only supports computed fields but what about:Computed fields need a rework anyways so why not combine it with a similar feature :-)
(computed fields + override_repr would obviously not be allowed since computed fields already assume something like an override_repr)
nomeata commentedon Jul 25, 2025
(Small note for when this discussion eventually converges: we should probably look for a different name for the attribute that does not sounds like you are changing the
Reprinstance.)cppio commentedon Jul 26, 2025
I had an idea similar to
WithReprin https://leanprover.zulipchat.com/#narrow/channel/341532-lean4-dev/topic/Proposal.3A.20Customizable.20runtime.20representations/near/525950357 (I called itEncoded). As I mentioned there, you could use anopaqueequivalence for unsafe/external representations:Similarly, you could use the existing noncomputable equivalence
Erased.equivto implement the betterErased.A downside with this approach is that it does not support the case where only one of the constructor and projection is computable, though I'm not sure of a situation where you would want that.
Rob23oba commentedon Jul 27, 2025
Yeah, I believe something like this could be useful tool but shouldn't be "the main feature". In other words, you should be able to write this (mathlib should probably have this) and also use it to simplify the procedure for other types but other variants should also be allowed.
12 remaining items
digama0 commentedon Aug 21, 2025
This RFC doesn't mention the prior work #2292, which I think is all that is needed here. To recap that approach:
repandabs.implemented_byand/orcsimpfor:casesOnfunctionThis is a more low-level approach than
def_type_with_rep, but it covers situations which cannot be handled in that way, for example if the underlying repr can't be itself expressed as a lean type (e.g.String,ByteArray,Array,Nat). Indeed I think the best examples of use of@[override_repr]are in lean core itself. You could of course definedef_type_with_repas a macro on top, by defining a wrapper type, and overriding the constructor / projections etc.datokrat commentedon Aug 21, 2025
Agreed that it's nice that
opaque_reprallows for more use cases theoretically. Having an optional safe wrapper around it would be nice, too.However: If
opaque_reprsimply tells the compiler to make less assumptions, it seems that the compiler would have a hard time to apply optimizations based on the compiled representation, right? In contrast,def_type_with_repseems to give the compiler enough information about the representation to apply vital optimizations.So for example,
Erasedwould technically work withopaque_repr, but the compiler wouldn't be able to realize that its representation does not carry any data. This is only one desirable optimization that we would be miss out. Also, wrapping any type into computableShrinkwould prevent the compiler from unboxing (I expect the impact from that to be severe if we decide to make the iterator library more universe-polymorphic usingShrink).All in all, I would say that although these approaches look similar, they are quite orthogonal when it comes to performance-critical use cases:
opaque_reprwould allow for highly efficient Lean-external representations in a safe way whiledef_type_with_repwould allow for Lean-internal representations that lend themselves better to important compiler optimizations.digama0 commentedon Aug 21, 2025
I don't think
Erasedis / should be a use of@[override_repr]. That should be a separate thing (anddef_type_with_repcould also hook into that). Erasure (and ABI type more generally) works at the type level, representations work at the function level (at least currently).Shrinkwould work just fine with this.It can still inline the projection function once it's been overridden, although this may be at odds with whatever typing system the compiler is working with.
datokrat commentedon Aug 21, 2025
It can, but would the compiler be able to apply an unboxing optimization in a case like this (which seems to me like a perfectly plausible situation)?
I believe: No. At least I do not see how inlining the projection functions or the constructor would help us here. The compiler effectively has no explicit type information on which to rely and can only use whatever it can infer from a dataflow analysis; and I'm not yet convinced that would be equally efficient and/or effective as without
Shrink(I'm assuming that the compiler generally supports the unboxing optimizations @zwarich is working on).And I do think that the ABI of
fshould be the same asdef f (x : α × β) : Nat. How else would the snippet above be unboxable? But perhaps I'm asking for too much?digama0 commentedon Aug 21, 2025
That is, again, about ABI type, which I would say is a different (orthogonal) feature. You would need some way of talking about ABI types, or alternatively, provide only a few presets: transparent (use the ABI of a field), erased, opaque. But importantly, ABI types are a weaker type system from lean, so there need not be actual formal agreement between the ABI type and the effective type from the overridden projection and other functions. That's why I'm suspicious of an approach where the target type is an actual lean type and you can write actual lean functions implementing everything, because this doesn't really make sense for e.g. a type wrapping an external handle from C.
Rob23oba commentedon Aug 21, 2025
You're right, I forgot to mention that here; this RFC generally expands upon #2292 with the following points:
@[opaque_repr]doesn't work well with unboxing. Because it is opaque, the compiler can't do anything with it and needs to assign the "any" type (tobj). However, when we're going to get unboxed types, we'd wantShrink (UInt8 × UInt16)to be represented the same way asUInt8 × UInt16and not astobj(the same argument applies toShrink UInt8etc. at the current moment)@[override_repr](or@[opaque_repr]or whatever) should make the constructors and projections noncomputable. When the representation is overridden / no longer the default one, the usual implementation of projections and constructors doesn't make sense anymore.@[implemented_by]and all variants should be forbidden on projections and constructors unless@[override_repr](or@[opaque_repr]or whatever) is presentWhat's the problem? I'd expect the compiler to just pseudo-delta-reduce to the overridden type while it converts regular Lean types into compiler types.
digama0 commentedon Aug 23, 2025
The problem is that it's insufficiently general. I think it would be nice to have good specialization to the case where the replacement type is another lean type, e.g. with special syntax and/or enough low-level annotations that something like
def_type_with_repcan be written in user code, but there are cases that are not covered by this, and I would want to ensure that these work too.nomeata commentedon Aug 23, 2025
One reason I'm hesitant about the more basic approach of an attribute to tell the compiler to not assume anything about the type, and then separate
implemented_byon the constructor and cases is: what happens with definitions that are compiled between the attribute and the implemented_by? Also, do we get more possible combinations of which definition is overriden where?By exposing a slightly higher level primitive that does it all in one go with clear semantics, I expect less complexity, more reliability and more wiggle room for the compiler to optimize.
Rob23oba commentedon Aug 23, 2025
I'm not opposed to having something like
@[opaque_repr]in addition to@[override_repr]/def_type_with_rep/whatever (which we might put onUInt8, etc.) but the point is that we also should allow using another Lean type as replacement (I could imagine them being frontend to the same kind of thing in the compiler, as aParametricAttribute (Option Expr)or theEnvExtensionequivalent or whatever)cppio commentedon Aug 23, 2025
I don't understand how
def_type_with_repis insufficiently general. Why can'tArraycan't be implemented like:zwarich commentedon Sep 5, 2025
The other more general thing here is that it's usually a bad idea to add a feature defined by telling the compiler not to do something. Inevitably, the compiler will later do something else that also happens to be unacceptable to the user who requested the earlier feature, yet seems completely orthogonal to the compiler implementor.
zwarich commentedon Sep 5, 2025
This actually raises an interesting question (related to the points @Rob23oba made earlier). Can the compiler assume that every
opaquetype declared like this is actually arefand can't ever be a scalar in a tagged pointer? This would mean that types likeNat/Intwould remain compiler builtins forever, but the rest of our builtins could use the same mechanism as users.cppio commentedon Sep 5, 2025
Perhaps this should be controlled by an attribute?
Equilibris commentedon Sep 28, 2025
Hi this would be super useful to have. Do we know when this might be added?
Rob23oba commentedon Aug 1, 2026
I'd like to propose a new idea: Essentially, we let the compiler have its own notion of inductives that can be distinct from what the kernel thinks of as inductives. You'd then be able to control these "compiler inductives" using two new attributes:
@[override_runtime_type ident?]on an inductive prevents the compiler from seeing it as an inductive type. You can also optionally provide a specific compiler type that it should instead have. This is essentially a generalized@[opaque_repr]that allows you to specify the compiler type (the type parameter is mostly useful for implementing the runtime built-in types).@[compiled_cases]on an eliminator that's shaped like acasesOncauses the compiler to make that the "canonicalcasesOn" of the inductive, that is, it sets the constructors of the inductive based off of the eliminator (all from the compiler's perspective). It also checks that the eliminator laws hold usingrflorsimp(maybesimpis not the best option though, not sure).The reason I think this is such a nice idea is that we can mostly keep the compiler code the same except that the compiler now e.g. uses its own
getConstInfoCtorOverrideinstead ofgetConstInfoCtor(the reality is obviously a bit more complicated but this is the gist). Also I believe it can handle everything we've talked about here, including coinductives, in a safe way; I have a test here that shows how this can work.I have a prototype for this at #14626; don't expect this to get merged any time soon though. But, anyone curious can try out the PR toolchain
leanprover/lean4-pr-releases:pr-release-14626.Anyways, I'd like to know if that sounds like a good idea and if there are maybe some problems with this idea that would make it unsafe; I tried to add enough checks including proving the eliminator laws to make sure this is safe (in the same way as
csimp) but I could well have missed something.