Tracking Issue for the use of ? in constants

73b5fee
Opened by Oli Scherer at 2022-03-01 07:43:16

The ? operator expands to invoking Try::into_result for the argument and Into::into for the error of the result. In order to support these, we need to

  • stabilize impl const Trait for Type items https://github.com/rust-lang/rust/issues/67792
  • implement const Try for Result and Option in libstd
  • users need to implement const Into for their error types
    • Since we have an impl<T> From<T> for T, we have to make this a const impl, too, as well as the impl<T: From<U>, U> Into<T> for U impl
  1. The ? operator expands to invoking Try::into_result for the argument and Into::into for the error of the result. In order to support these, we need to

    • Figure out traits-in-const: https://github.com/rust-lang/rust/issues/110395
    • stabilize impl const Trait for Type items https://github.com/rust-lang/rust/issues/67792
    • implement const Try for Result and Option in libstd
    • users need to implement const Into for their error types
      • Since we have an impl<T> From<T> for T, we have to make this a const impl, too, as well as the impl<T: From<U>, U> Into<T> for U impl

    Ralf Jung at 2024-09-08 07:06:15

  2. #60964 also needs to be resolved to be able to implement const Try. See https://play.rust-lang.org/?version=nightly&gist=bdf8f8e2774f54c084e2cb25624ce193

    Alphyr at 2020-07-30 13:35:37

  3. Would it be reasonable to permit ? in const fn only for Option<T> for now? The only thing would have to change is the desugaring, I think.

    Jacob Pratt at 2022-03-01 04:23:58

  4. You mean to make the desugaring different if we're in a const fn?

    Oli Scherer at 2022-03-01 06:26:23

  5. I don't see any reason we couldn't desugar to this unconditionally for Option<T>:

    match opt {
        Some(val) => val,
        None => return None,
    }
    

    Sure, the Try trait was designed with this in mind, but ultimately it is just a matter of desugaring the syntax. There's no semantic difference. Result<T, E> is more complicated due to the E::from(err) call, which can't be stable const fn right now anyways.

    If it's possible to stabilize it on Option<T> without changing the desugar, that would be great. But I don't think it is possible until we stabilize both Try and const_trait_impl, which seems a ways off still.

    Plus, who knows. There might be a small performance benefit to changing the desugaring to something simpler.

    Jacob Pratt at 2022-03-01 06:40:44

  6. The reason we can't do this is that during desugaring we don't know what the type is. We compute types after desugaring.

    Oli Scherer at 2022-03-01 07:39:03

  7. Ah, dang. For some reason I thought the order was the other way around.

    Jacob Pratt at 2022-03-01 07:43:16