Auto merge of #74956 - ecstatic-morse:const-option-unwrap, r=oli-obk

Make `Option::unwrap` unstably const

This is lumped into the `const_option` feature gate (#67441), which enables a potpourri of `Option` methods.

cc @rust-lang/wg-const-eval

r? @oli-obk
This commit is contained in:
bors 2020-07-31 08:26:33 +00:00
commit 3a92b9987a
4 changed files with 37 additions and 1 deletions

View file

@ -81,6 +81,7 @@
#![feature(const_fn_union)]
#![feature(const_generics)]
#![feature(const_option)]
#![feature(const_precise_live_drops)]
#![feature(const_ptr_offset)]
#![feature(const_ptr_offset_from)]
#![feature(const_raw_ptr_comparison)]

View file

@ -380,7 +380,8 @@ impl<T> Option<T> {
#[inline]
#[track_caller]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unwrap(self) -> T {
#[rustc_const_unstable(feature = "const_option", issue = "67441")]
pub const fn unwrap(self) -> T {
match self {
Some(val) => val,
None => panic!("called `Option::unwrap()` on a `None` value"),

View file

@ -0,0 +1,14 @@
// check-fail
#![feature(const_option)]
const FOO: i32 = Some(42i32).unwrap();
// This causes an error, but it is attributed to the `panic` *inside* `Option::unwrap` (maybe due
// to `track_caller`?). A note points to the originating `const`.
const BAR: i32 = Option::<i32>::None.unwrap(); //~ NOTE
fn main() {
println!("{}", FOO);
println!("{}", BAR);
}

View file

@ -0,0 +1,20 @@
error: any use of this value will cause an error
--> $SRC_DIR/core/src/option.rs:LL:COL
|
LL | None => panic!("called `Option::unwrap()` on a `None` value"),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| the evaluated program panicked at 'called `Option::unwrap()` on a `None` value', $DIR/const-unwrap.rs:9:38
| inside `std::option::Option::<i32>::unwrap` at $SRC_DIR/core/src/macros/mod.rs:LL:COL
| inside `BAR` at $DIR/const-unwrap.rs:9:18
|
::: $DIR/const-unwrap.rs:9:1
|
LL | const BAR: i32 = Option::<i32>::None.unwrap();
| ----------------------------------------------
|
= note: `#[deny(const_err)]` on by default
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error