Michael Goulet
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Async Closures (and "coroutine-closures" in general) For the purposes of keeping the implementation mostly future-compatible (i.e. with `gen || {}` and `async gen || {}`), most of this document calls async closures "coroutine-closures". Coroutine-closures are a generalization of async closures, being special syntax for closure expressions which return a coroutine, notably one that is allowed to capture from the closure's upvars. **For now**, the only usable kind of coroutine-closure is the async closure, and supporting async closures is the extent of this PR. We may eventually support `gen ||`, etc., and all of the problems and curiosities described in this document apply to all coroutine-closures in general. ## `TyKind::CoroutineClosure` The main thing that this PR introduces is a new `TyKind` called `CoroutineClosure` and corresponding variants on other relevant enums in typeck and borrowck (`UpvarArgs`, `DefiningTy`, `AggregateKind`). #### Signature A traditional closure has a `fn_sig_as_fn_ptr_ty` which it uses to represent the signature of the closure. The problem with this sig type is that it doesn't actually reference the closure input: e.g., for a closure like `|| -> i32 { 0 }`, the ptr type is `fn(()) -> i32`. This is the first problem with a coroutine-closure, which returns a coroutine that is allowed to borrow from the closure's upvars, since there's no way to link the input lifetime (of the closure borrow) with the output lifetimes (in the coroutine's upvars). The second problem is that coroutine-closures actually have several different signatures depending on if they're called with `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`. For a general coroutine-closure which returns a coroutine that borrows from the closure's upvars... ```rust let s = String::new(); let c = async move || { call_service(&s).await; }; ``` ...the output coroutine returned by `AsyncFn::call(& /* borrow for '1 */ c)` captures the `&'1 String` for the input lifetime `'1`. Conversely, the coroutine returned by `AsyncFnOnce::call_once(c)` *cannot* borrow from the `c` closure since it is consumed as part of the call, so it must capture `String` by move, since the coroutine is now responsible for dropping the coroutine-closure's upvars after the coroutine-closure is dropped. Conceptually, the coroutine-closure may be thought as containing several different signature types depending on whether it is being called by-ref or by-move. Instead of doing this, we store the common parts of the different coroutines in the `CoroutineClosureSignature`, and compute the relevant coroutine output type on demand. This `CoroutineClosureSignature` is stored in a compressed form in the `signature_parts_ty`. See the docs on that type for more explanation. ## Delaying the computation of the returned coroutine's upvars We introduce a new `AsyncFnKindHelper` trait to enforce that the `ClosureKind` of a goal is within the capabilities of a `CoroutineClosure`, and which allows us to delay the projection of the tupled upvar types until after upvar analysis is complete. This is because the upvars of the coroutine returned by the coroutine-closure should be the appended tuple of the input tys and the coroutine-closure's upvars. However, since the coroutine-closure's tupled upvars ty is an infer var until after closure analysis, we can't compute this eagerly. We have two options therefore: 1. We could mark all `AsyncFn*` goals as ambiguous until upvar analysis. However, this is really detrimental to inference in the program, since it means that programs like this would not type check: ```rust! let c = async || -> String { .. }; let s = c().await; // ^ If we can't project `<{ c } as AsyncFn>::call()` to a coroutine type, then the `IntoFuture::into_future` call inside of the `.await` stalls out, and the type of `s` is left as an infer var. s.as_bytes(); // ^ That means we can't call any methods on it! ``` 2. So *instead*, we can use an alias type (in this case, a projection: `AsyncFnKindHelper::Upvars<'env, ...>`) to delay the computation of the tupled upvars and give us something to put in its place. ## Modifications to capture mode Async closures are peculiar since they must move all the closure's arguments into the returned coroutine, but prefer not to move the coroutine-closure's upvars unless needed (otherwise they'd always be forced to only implement `AsyncFnOnce`) and instead capture them by ref. Right now, the deusgaring that is shared between async closures and async functions ([#119978]) always generates a by-move async block. [#119978]: https://github.com/rust-lang/rust/pull/119978 In order to support this, I've modified the desugaring of these generated `async` blocks so that they always capture by-ref, and then modified the upvar analysis in hir_typeck to additionally force any *argument* types from the parent signature to be captured by move. This seems to work quite successfully. **NOTE**: Since this is essentially a second copy of the coroutine body stored within the first, we must make sure to apply all the same MIR passes to this one. This functionality is implemented in `run_passes`, but other ad-hoc calls to `visit_body` will need to be audited for correctness. ## Coroutine kind ty The coroutines returned by `AsyncFnOnce`/`AsyncFnMut`/`AsyncFn` have the same def id, since they originate from the same HIR, but correspond to different bodies during codegen. To distinguish which body to associate with each implementation, I added a `kind_ty` to the coroutine args. For coroutines that do not originate from coroutine-closures, this `kind_ty` is always `()`. For coroutines that *do*, this kind ty will match the `ClosureTy` of the call trait that produced it. ## By move shims This PR introduces the `ByMoveBody` MIR pass which is run right after MIR is built. When it finds the body of a coroutine from a coroutine-closure, and that coroutine-closure's closure kind is *greater* than `FnOnce`, it clones the body and adjusts all of the upvars to be taken by-move. We call this the `by_move_body`, and store it into the `CoroutineInfo` in the original coroutine's MIR body. Later on, when `Instance::resolve` tries to resolve `Future::poll_next` for a coroutine type that is returned by `AsyncFnOnce::call_once` (and that coroutine-closure's closure kind is *greater* than `FnOnce`), we can use this by-move body instead. We also generate a shim for `AsyncFnOnce::call_once` for these coroutine-closures, which constructs a coroutine by moving the coroutine-closure's upvars rather than borrows them. **FOLLOW-UP**: The `fn_sig_for_fn_abi`/`Instance::ty` implementation for these shims is a bit sketchy. This shouldn't cause issues for codegen_llvm, but may cause issues for stricter backends like clif. ## Wins #### Higher-ranked async closures We support coroutine-closures with binders in their signature, both implicit and explicit. ```rust let c = async |s: &str| { do_service(s).await; }; ``` While the the future coroutine returned by the closure may reference late-bound lifetimes, the coroutine still is not "lending". See `async-await/async-closures/not-lending.rs` for an example. It is however not currently possible for the *return type* of the coroutine to reference the higher-ranked lifetimes of the closure: ```rust let c = async |s: &str| -> &str { s }; ``` **FOLLOW-UP**: Figure out why this code doesn't work. ## Limitations #### The "double move" case The coroutine returned by coroutine-closures will always opportunistically borrow from the parent coroutine. There's essentially no way to express `move || async move { .. }`. #### Async closures don't currently implement the regular `Fn` traits The `AsyncFn` hierarchy of traits is not currently unified with the `Fn` hierarchy of traits. In the future, we could make coroutine-closures implement `FnOnce` always (since it's always possible to implement `FnOnce`) and then opportunistically implement `FnMut`/`Fn` as long as the don't borrow anything from the closure upvars. EDIT: this was fixed https://github.com/rust-lang/rust/pull/120712 #### Closure signature inference isn't implemented This PR does not implement closure signature inference that comes from passing async closures as arguments. This could be implemented if needed, but it may put the new trait solver in a worse position w.r.t. its inability to do closure signature inference.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully