Re: [PATCH v5 22/24] rust: types: add `ForLt` trait for higher-ranked lifetime support
From: Alexandre Courbot
Date: Tue May 26 2026 - 01:45:38 EST
On Tue May 26, 2026 at 5:21 AM JST, Danilo Krummrich wrote:
> From: Gary Guo <gary@xxxxxxxxxxx>
>
> There are a few cases, e.g. when dealing with data referencing each
> other, one might want to write code that is generic over lifetimes. For
> example, if you want to take a function that takes `&'a Foo` and gives
> `Bar<'a>`, you can write:
>
> f: impl for<'a> FnOnce(&'a Foo) -> Bar<'a>,
>
> However, it becomes tricky when you want that function to not have a
> fixed `Bar`, but have it be generic again. In this case, one needs
> something that is generic over types that are themselves generic over
> lifetimes.
>
> `ForLt` provides such support. It provides a trait `ForLt` which
> describes a type generic over a lifetime. One may use `ForLt::Of<'a>` to
> get an instance of a type for a specific lifetime.
>
> For the case of cross referencing, one would almost always want the
> lifetime to be covariant. Therefore this is also made a requirement for
> the `ForLt` trait, so functions with `ForLt` trait bound can assume
> covariance.
>
> A macro `ForLt!()` is provided to be able to obtain a type that
> implements `ForLt`. For example, `ForLt!(for<'a> Bar<'a>)` would yield a
> type that `<TheType as ForLt>::Of<'a>` is `Bar<'a>`. This also works
> with lifetime elision, e.g. `ForLt!(Bar<'_>)` or for types without
> lifetime at all, e.g. `ForLt!(u32)`.
>
> The API design draws inspiration from the higher-kinded-types [1] crate,
> however a different design decision has been taken (e.g. covariance
> requirement) and the implementation is independent.
>
> License headers use "Apache-2.0 OR MIT" because I anticipate this to be
> used in pin-init crate too which is licensed as such.
>
> Link: https://docs.rs/higher-kinded-types/ [1]
>
> Reviewed-by: Greg Kroah-Hartman <gregkh@xxxxxxxxxxxxxxxxxxx>
> Reviewed-by: Eliot Courtney <ecourtney@xxxxxxxxxx>
> Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
> [ Handle macro_rules! invocations in the ForLt! proc macro's covariance
> and WF checks. Since proc macros cannot expand macro_rules!, add a
> visit_macro() implementation to conservatively assume macro
> invocations may contain lifetimes, forcing them through the
> compiler-assisted covariance proof.
>
> While at it, fix a few typos in the documentation and in the commit
> message. - Danilo ]
> Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>
For everything but the proc macro,
Reviewed-by: Alexandre Courbot <acourbot@xxxxxxxxxx>