Niko Matsakis
    • 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 New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # fallback and `!` ## Background * We introduced the `!` type in RFC XXX * Currently, for "abrupt" expressions like `return` and `break`, result is a type inference variable that (if otherwise unconstrained) falls back to `()` * RFC proposed to change that to `!` * However, it was found that this change caused a certain amount of breakage in practice * some of this manifested as failed compilations * but other cases (notably the `objc` crate) resulted in silent crashes ## When does the fallback mechanism apply * the type of an expression like `panic!()` is an inference variable * if that variable winds up being unconstrianed, it will "fallback" to either `()` (today) or `!` (proposed) * it is unusual for variables to be fully unconstrained but certainly possible, especially around dead code Example: ```rust fn foo() { let x: _ = panic!(); bar(&x); } fn bar<T: Debug>(t: T) { } ``` The type of `x` here is an unconstrained inference variable `?X` -- the only *constraint* is that whatever `?X` winds up being, it must implement `Debug`. ## Arguments in favor of changing the fallback The `!` type is more likely to be implemented and to integrate with `impl Trait`, [as scottmcm pointed out here][mcm]: [mcm]: https://github.com/rust-lang/rust/pull/65355#issuecomment-550000330 ```rust pub fn demo() -> impl std::error::Error { unimplemented!() } ``` ## Examples where problems arise ### Compilation failures I'm not sure if we saw in the wild, but it's possible to have a compilation failure if you have fallback and pending trait obligations that `!` cannot satisfy: ```rust ``` ### Runtime errors Code that uses `mem::zeroed` or `mem::uninitializd` can sometimes be "tricked" into synthesizing a `!` value. This presently results in a lint and a runtime panic, as [Centril notes here][Centril1]: [Centril1]: https://github.com/rust-lang/rust/pull/65355#issuecomment-550193109 > The former might not result in an error. It does however result in a warning (`invalid_value`) as well as a run-time panic ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=d0f73397e2d819d97cbc5f88fc7eed43)): > > ``` > warning: the type `!` does not permit zero-initialization > --> src/main.rs:8:13 > | > 8 | std::mem::zeroed() > | ^^^^^^^^^^^^^^^^^^ > | | > | this code causes undefined behavior when executed > | help: use `MaybeUninit<T>` instead > | > = note: `#[warn(invalid_value)]` on by default > = note: The never type (`!`) has no valid value > > Finished dev [unoptimized + debuginfo] target(s) in 1.12s > Running `target/debug/playground` > thread 'main' panicked at 'Attempted to instantiate uninhabited type !', /rustc/1423bec54cf2db283b614e527cfd602b481485d1/src/libcore/mem/mod.rs:461:5 > note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. > ``` > > As you can see from ^, there's no UB in sight. ### The "Deserialize" pattern (XXX rust issue number ([issue 39297?](https://github.com/rust-lang/rust/issues/39297)) One pattern that was found worked like this: ```rust fn foo() -> Result<(), ()> { let x = try!(Deserialize::deserialize())? println!("{:?}", x); Ok(()) } ``` when `try!` is expanded, the result is ```rust let x = match Deserialize::deserialize() { Ok(v) => v, // Ok match arm has type `?OK` Err(err) => return err.into(), // Err match arm has type `?ERR` } ``` The problem here is that the type of the both match arms are inference variables, let's call them `?OK` and `?ERR`. Those two variables are constrained to be the same, but neither of them are constrained to anything in particular. At fallback point, `?ERR` falls back to `!`, and hence `?OK` also falls back to `!`. Therefore, the final type of `x` is inferred to `!` -- but deserializing a `!` value doesn't make sense -- in particular, the deserialize trait was not (at the time) implemented for `!`, so we got an error. Had deserialize been implemented for `!`, the only possible behavior would be to panic, and hence this code would go from deserializing a `Result<(), ()>` (which could well succeed) to deserializing a `Result<!, ()>` (which panics). (In the particular case where this code was found, though, the value was known to be the `Err` variant so that would not in fact have happened.) Nonetheless, it was surprising that code which is **not obviously dead** winds up with the type `!` (that is, the variable `x`). ### objc crate The core of the objc crate error is the same pattern as the `Deserialize` error, as [SSheldon noted here][ss1]. [ss1]: https://github.com/rust-lang/rust/pull/65355#issuecomment-550117628 ```rust let _ = if false { panic!("panic") } else { mem::zeroed() }; ``` However, the specific case involved a `fn() -> !` value, [as SimonSapin clarified here][ss2]: [ss2]: https://github.com/rust-lang/rust/pull/65355#issuecomment-550214930 > \[objc\] [transmutes](https://github.com/SSheldon/rust-objc/blob/735816219676ad2b569163315cd23b002d1492ea/src/message/mod.rs#L126-L128) a pointer to `fn(…) -> R` and calls it. `R` is a generic type parameter that is inferred, and in the cases discussed here affected by the fallback change. ## Data on expected breakage XXX links to old crater runs and summaries of their results XXX objc fallout results from thread ## Mitigation options One thing to consider is whether we can **mitigate** the fallout through a warning period. The question is how one would design a suitable lint and how precise it would be. If the lint is overly coarse, we might make it **opt-in** (i.e., allow by default). Option 1: use "taint tracking" on the `()` value that results from fallback. This is what we attempted at first. It was complex and we are not keen to attempt it again. Option 2: when falling back a variable `?X` to `()`, search the outstanding trait obligations and see whether any of them reference `?X`. If so, issue a lint warning -- or perhaps get more precise, for example by "evaluating" the trait obligation with `()` and `!` to see if the result differ. (To check: Would this actually capture the "semantic" violations from cases like objc?) ## Options * Stabilize `!` type but leave fallback *temporarily* unresolved * this doesn't resolve the question, so it's really rather orthogonal to the document, but it may be worth considering regardless * the [main concern](https://github.com/rust-lang/rust/issues/58184#issuecomment-460697760) when this was [previously proposed](https://github.com/rust-lang/rust/issues/58184) was that we would have insufficient motivation to pursue a change to fallback (which does seem plausible, unless someone commits to seeing it through) * Leave the fallback as `()`. * Transition to `!`: * Can we do some sort of warning period? * How much do we have to prepare the ecosystem? * Edition boundary * no code breaks: good! * but it is complex for us to manage and may result in surprising interactions * presumably the edition of the `return` or `break` statement would be used to determine the fallback * depending how precise we are, we may see code breakage anyway

    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