Fix ICE with unsized type in const pattern

This commit is contained in:
Fabian Wolff 2021-07-11 19:16:26 +02:00
parent 81053b912f
commit 79f0743b6f
3 changed files with 65 additions and 11 deletions

View File

@ -490,6 +490,17 @@ fn recur(
// convert the dereferenced constant to a pattern that is the sub-pattern of the
// deref pattern.
_ => {
if !pointee_ty.is_sized(tcx.at(span), param_env) {
// `tcx.deref_const()` below will ICE with an unsized type
// (except slices, which are handled in a separate arm above).
let msg = format!("cannot use unsized non-slice type `{}` in constant patterns", pointee_ty);
if self.include_lint_checks {
tcx.sess.span_err(span, &msg);
} else {
tcx.sess.delay_span_bug(span, &msg);
}
PatKind::Wild
} else {
let old = self.behind_reference.replace(true);
// In case there are structural-match violations somewhere in this subpattern,
// we fall back to a const pattern. If we do not do this, we may end up with
@ -502,6 +513,7 @@ fn recur(
self.behind_reference.set(old);
val
}
}
},
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::FnDef(..) => {
PatKind::Constant { value: cv }

View File

@ -0,0 +1,34 @@
// Regression test for the ICE described in #87046.
#![crate_type="lib"]
#![allow(unreachable_patterns)]
#![feature(const_fn_union)]
#[derive(PartialEq, Eq)]
#[repr(transparent)]
pub struct Username(str);
pub const ROOT_USER: &Username = Username::from_str("root");
impl Username {
pub const fn from_str(raw: &str) -> &Self {
union Transmute<'a> {
raw: &'a str,
typed: &'a Username,
}
unsafe { Transmute { raw }.typed }
}
pub const fn as_str(&self) -> &str {
&self.0
}
pub fn is_root(&self) -> bool {
match self {
ROOT_USER => true,
//~^ ERROR: cannot use unsized non-slice type `Username` in constant patterns
_ => false,
}
}
}

View File

@ -0,0 +1,8 @@
error: cannot use unsized non-slice type `Username` in constant patterns
--> $DIR/issue-87046.rs:29:13
|
LL | ROOT_USER => true,
| ^^^^^^^^^
error: aborting due to previous error