Skip to content
This repository was archived by the owner on Oct 30, 2019. It is now read-only.
This repository was archived by the owner on Oct 30, 2019. It is now read-only.

Async Closures With Borrowed Arguments #19

Closed
@cramertj

Description

@cramertj

Async closures with borrowed arguments are a messy thing. Since the output type of the closure (impl Future + 'a) depends upon the input lifetime of the argument, these closures are always higher-ranked. Eventually I think we'd like to support this through syntax like this:

fn higher_order_fn(
    async_fn: impl for<'a> FnOnce(&'a Foo) -> impl Future<Output = ()> + 'a`
) { ... }

// and someday

fn higher_order_fn(
    async_fn: impl async FnOnce(&Foo),
) { ... }

Unfortunately, the current impl Trait-in-args implementation doesn't support these sorts of higher-ranked use cases. Luckily it's not backwards incompatible to add support for them, since we've currently banned impl Trait inside of Fn syntax.

Until we get one of these nicer solutions, however, we need a way to type these sorts of functions. I made an attempt at one of them that looks like this:

pub trait PinnedFnLt<'a, Data: 'a, Output> {
    type Future: Future<Output = Output> + 'a;
    fn apply(self, data: PinMut<'a, Data>) -> Self::Future;
}

pub trait PinnedFn<Data, Output>: for<'a> PinnedFnLt<'a, Data, Output> + 'static {}
impl<Data, Output, T> PinnedFn<Data, Output> for T
    where T: for<'a> PinnedFnLt<'a, Data, Output> + 'static {}

impl<'a, Data, Output, Fut, T> PinnedFnLt<'a, Data, Output> for T
where
    Data: 'a,
    T: FnOnce(PinMut<'a, Data>) -> Fut,
    Fut: Future<Output = Output> + 'a,
{
    type Future = Fut;
    fn apply(self, data: PinMut<'a, Data>) -> Self::Future {
        (self)(data)
    }
}

pub fn pinned<Data, Output, F>(data: Data, f: F) -> PinnedFut<Data, Output, F>
    where F: PinnedFn<Data, Output>,
{ ... }

Unfortunately, this fails because of rust-lang/rust#51004. Even if this worked, though, this is an awful lot of code to write for each of these functions-- we'd likely want some sort of macro.

Until progress is made on this issue, it's impossible to make a function which accepts an asynchronous closure with an argument borrowed for a non-fixed lifetime (precise named lifetimes like impl FnOnce(&'tcx Foo) -> F are possible).

Metadata

Metadata

Assignees

No one assigned

    Labels

    WG async/awaitIssues relevant to the async subgroup

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions