Charles Lew
    • 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Stabilization report for dyn upcasting coercion tags: stabilization-report date: 2023-08-11 url: https://hackmd.io/QggP6SJVTa2jb7DjGq0vrQ --- # Stabilization report for dyn upcasting coercion This report proposes the stabilization of the `dyn` trait upcasting coercion feature, which is a long-desired feature ([since 2013](https://github.com/rust-lang/rfcs/issues/2765)). It is tracked as part of the [Dyn upcasting coercion initiative](https://github.com/rust-lang/dyn-upcasting-coercion-initiative). The associated PR to update the Reference is https://github.com/rust-lang/reference/pull/1259. We are stabilizing a new kind of coercion, which "upcasts" from a `dyn Trait` to its supertraits: <!-- to all supertraits or to just one? --> ```rust trait Foo { fn foo_method(&self); } trait Bar: Foo { fn bar_method(&self); } let x: &dyn Bar = /* ... */; let y: &dyn Foo = x; // compiles ``` The key factor for these upcasts is that they require adjusting the vtable. The current implementation strategy <!-- for dyn traits?--> is that the vtables for a `Bar` trait will embed pointers to the supertrait `Foo`'s vtable within them: ``` +----------------------------+ | Bar vtable for some type T | |----------------------------| | Foo vtable | ----------> +------------------+ | foo_method | -----+ | Foo vtable for T | | bar_method | --+ | |------------------| +----------------------------+ | | | foo_method | ---+ | | +------------------+ | | | | | +---> <T as Foo>::foo_method <-+ v <T as Bar>::bar_method (this diagram is only meant to convey the general idea of the vtable layout, and doesn't represent the exact offsets we would use, etc.; in fact, with the current implementation, the first supertrait is stored 'inline' and hence no load is required) ``` This way, given a `&dyn Bar` object, we convert its `Bar` vtable to the appropriate `Foo` vtable by loading the appropriate field. For some examples of code patterns that this feature enables, see [Integration with `Any`: You can give any trait object `downcast` ability by using `Any` as its supertrait](https://github.com/rust-lang/dyn-upcasting-coercion-initiative/issues/2) and [Aligning type-erased closure bounds: You can use `&mut dyn Fn` as if it's a `&mut dyn FnMut`](https://github.com/rust-lang/dyn-upcasting-coercion-initiative/issues/3). ---- ### Interaction with existing language features, and other implementation-level considerations There are some related topics tangentially affected with the implementation of this feature: #### Raw pointers safety rules During dyn upcasting coercion, it is possible that we need to access the contents of the actual vtable to retrieve the new replaced pointer. This brings up the topic of raw pointer safety. The agreement reached at [rust-lang/rust#101336] is as follows: * Vtable-adjusting upcasts are safe operations. The upcast is UB if performed on a value without a valid vtable * As such, the "safety invariant" requires a fully valid vtable. * The "validity invariant" requires `*dyn metadata` to be word-aligned and non-null. <!-- *dyn metadata? the pointer to the metadata, or? this notation is not one I recognize. --> The rules for vtable-adjusting upcasting are as follows: * Trait upcasts that alter the set of methods. These methods can be invoked on the resulting value at runtime (e.g., `dyn Bar` to `dyn Foo` from the example in the introduction). * Upcasts that simply add or remove auto-traits are not vtable-adjusting (e.g., dyn Debug + Send to dyn Debug). #### Potential minor behavior change There is one small potential behavior change. This is currently already linted against via `deref_into_dyn_supertrait`. * `dyn` upcasting coercion has a higher priority than user defined `Deref`-based coercions (from a user's perspective). * A specific setup will cause trait upcasting to shadow `deref` coercion. This is described in [`rust-lang/rust#89190`] * Users can leverage this to mimick upcasting. After this feature is stabilized, mimicking will no longer be required. * **If there are side effect within such `Deref` impls, they will be lost after this stabilization.** This is of low concern because these implementations are unlikely and have been under future-compat warnings for almost three years now (Triggering `deref_into_dyn_supertrait` lint). #### Binary-size considerations Trait objects have been critiqued by people due to their impact on binary size. Normally this shouldn't be too much concern, except on extremely resource limited environments, like embedded devices. Previously we surveyed standard libraries APIs and community crates to collect impacts. <!-- you can afford to take a moment to explain why trait objects have negative impacts on binary size sometimes, I think. in other cases they have positive impacts. --> For the standard libraries: * There will be 11 stable API traits that are now dyn upcastable, but only one of them (the `Error` trait) has multiple supertraits and would hence result in a larger vtable. <!-- that's pretty bad, given the error trait's importance... --> * There are 6 unstable traits that become upcastable (purple background), but none of them have multiple supertraits. * 21 traits are now upcastable to a "Sealed" supertrait. T-libs-api thinks this result is acceptable. For ecosystem crates: We gathered data in [rust-lang/rust#112355] and T-lang decided that this size cost was acceptable. T-lang think the size cost of this will be limited. Further, if size cost does prove to be a concern, an opt-out mechanism can be added after stabilization (so this mechanism does not block stabilization). This is preferred over providing an opt-in mechanism at this time because opt-in would be thought to be too disruptive to Rust developers. However, the downside of this approach is that opting out of upcasting in a public trait would be a breaking change. We may also see an ecosystem split between upcastable and non-upcastable traits, similar to how we have separate implementations of popular crates for use in embedded systems. Regarding implementation, there are still open issues about missed chances of further optimization such as [rust-lang/rust#114007]. This also does not block stabilization. [rust-lang/rust#101336]: https://github.com/rust-lang/rust/issues/101336 [`rust-lang/rust#89190`]: https://github.com/rust-lang/rust/issues/89190 [rust-lang/rust#112355]: https://github.com/rust-lang/rust/issues/112355 [rust-lang/rust#114007]: https://github.com/rust-lang/rust/issues/114007 #### Interactions with trait selection and inference Implementation of the `Unsize` trait, which powers dyn-upcasting, is documented in [the rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/traits/unsize.html#upcasting-implementations). # Resolutions to other unresolved questions - [x] Exponential (?) blowup in size (raised @ https://github.com/rust-lang/rfcs/pull/3324#issuecomment-1305015681) - Conclusion: We put out a request for data in [#112355](https://github.com/rust-lang/rust/issues/112355). The data gathered did not suggest major impact (e.g., nbdd0121 found <0.2% overhead in the size of text sections). Furthermore, the vtables in practice have included upcast support for a long time and so this is not making anything *larger*. - [x] Whatever we are fine with making creating `*const dyn Tr` with invalid metadata invalid, to support safe coercions (resolved by https://github.com/rust-lang/rust/issues/101336#issuecomment-1250356226) - [x] Should we make upcasting opt-in in some form to limit vtable size by default? The current inclination of the lang-team is "no", but it would be useful to gather data on how much supporting upcasting contributors to overall binary size. - Answer: no. This would create complexity for all Rust users with very little practical benefit (size impact, as measured above, is very little). - [x] Should we add an opt-out mechanism, and extend library stabilization checklist with "do we want to opt-out for now"? - Answer: we are not adding a mechanism but we can do it later. We wouldn't be able to apply it to the standard library traits but we did an analysis (in the stabilization report) and found that we would not want that anyway. - [x] Whatever there are concerns with traits in the ecosystem outside of the standard library (raised @ https://github.com/rust-lang/rust/issues/65991#issuecomment-1369970129) - Answer: No, based on our data, we are not concetrned. - [x] While `trait A: B` is upcastable, should `trait A where Self: B` be? (raised @ https://github.com/rust-lang/rust/issues/65991#issuecomment-1294081137) - Answer: Yes, and it is, because all other places in Rust treat `trait A: B` as equivalent to `trait A where Self: B` ([play](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=60b586c26727f642102cc1c867fee13e)).

    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