Skip to content

Commit a1cdf72

Browse files
committed
Fix exhaustiveness in case a byte string literal is used at slice type
1 parent 30e49a9 commit a1cdf72

File tree

7 files changed

+113
-12
lines changed

7 files changed

+113
-12
lines changed

compiler/rustc_middle/src/ty/context.rs

+9
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,12 @@ pub struct TypeckResults<'tcx> {
418418
/// Stores the type, expression, span and optional scope span of all types
419419
/// that are live across the yield of this generator (if a generator).
420420
pub generator_interior_types: Vec<GeneratorInteriorTypeCause<'tcx>>,
421+
422+
/// We sometimes treat byte string literals (which are of type `&[u8; N]`)
423+
/// as `&[u8]`, depending on the pattern in which they are used.
424+
/// This hashset records all instances where we behave
425+
/// like this to allow `const_to_pat` to reliably handle this situation.
426+
pub treat_byte_string_as_slice: ItemLocalSet,
421427
}
422428

423429
impl<'tcx> TypeckResults<'tcx> {
@@ -443,6 +449,7 @@ impl<'tcx> TypeckResults<'tcx> {
443449
concrete_opaque_types: Default::default(),
444450
closure_captures: Default::default(),
445451
generator_interior_types: Default::default(),
452+
treat_byte_string_as_slice: Default::default(),
446453
}
447454
}
448455

@@ -677,6 +684,7 @@ impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckResults<'tcx> {
677684
ref concrete_opaque_types,
678685
ref closure_captures,
679686
ref generator_interior_types,
687+
ref treat_byte_string_as_slice,
680688
} = *self;
681689

682690
hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
@@ -710,6 +718,7 @@ impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckResults<'tcx> {
710718
concrete_opaque_types.hash_stable(hcx, hasher);
711719
closure_captures.hash_stable(hcx, hasher);
712720
generator_interior_types.hash_stable(hcx, hasher);
721+
treat_byte_string_as_slice.hash_stable(hcx, hasher);
713722
})
714723
}
715724
}

compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs

+36-8
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,20 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
1818
/// Converts an evaluated constant to a pattern (if possible).
1919
/// This means aggregate values (like structs and enums) are converted
2020
/// to a pattern that matches the value (as if you'd compared via structural equality).
21+
#[instrument(skip(self))]
2122
pub(super) fn const_to_pat(
2223
&self,
2324
cv: &'tcx ty::Const<'tcx>,
2425
id: hir::HirId,
2526
span: Span,
2627
mir_structural_match_violation: bool,
2728
) -> Pat<'tcx> {
28-
debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
29-
debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
30-
3129
let pat = self.tcx.infer_ctxt().enter(|infcx| {
3230
let mut convert = ConstToPat::new(self, id, span, infcx);
3331
convert.to_pat(cv, mir_structural_match_violation)
3432
});
3533

36-
debug!("const_to_pat: pat={:?}", pat);
34+
debug!(?pat);
3735
pat
3836
}
3937
}
@@ -61,6 +59,8 @@ struct ConstToPat<'a, 'tcx> {
6159
infcx: InferCtxt<'a, 'tcx>,
6260

6361
include_lint_checks: bool,
62+
63+
treat_byte_string_as_slice: bool,
6464
}
6565

6666
mod fallback_to_const_ref {
@@ -88,6 +88,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
8888
span: Span,
8989
infcx: InferCtxt<'a, 'tcx>,
9090
) -> Self {
91+
trace!(?pat_ctxt.typeck_results.hir_owner);
9192
ConstToPat {
9293
id,
9394
span,
@@ -97,6 +98,10 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
9798
saw_const_match_error: Cell::new(false),
9899
saw_const_match_lint: Cell::new(false),
99100
behind_reference: Cell::new(false),
101+
treat_byte_string_as_slice: pat_ctxt
102+
.typeck_results
103+
.treat_byte_string_as_slice
104+
.contains(&id.local_id),
100105
}
101106
}
102107

@@ -153,6 +158,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
153158
cv: &'tcx ty::Const<'tcx>,
154159
mir_structural_match_violation: bool,
155160
) -> Pat<'tcx> {
161+
trace!(self.treat_byte_string_as_slice);
156162
// This method is just a wrapper handling a validity check; the heavy lifting is
157163
// performed by the recursive `recur` method, which is not meant to be
158164
// invoked except by this method.
@@ -384,7 +390,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
384390
}
385391
PatKind::Wild
386392
}
387-
// `&str` and `&[u8]` are represented as `ConstValue::Slice`, let's keep using this
393+
// `&str` is represented as `ConstValue::Slice`, let's keep using this
388394
// optimization for now.
389395
ty::Str => PatKind::Constant { value: cv },
390396
// `b"foo"` produces a `&[u8; 3]`, but you can't use constants of array type when
@@ -393,11 +399,33 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
393399
// as slices. This means we turn `&[T; N]` constants into slice patterns, which
394400
// has no negative effects on pattern matching, even if we're actually matching on
395401
// arrays.
396-
ty::Array(..) |
402+
ty::Array(..) if !self.treat_byte_string_as_slice => {
403+
let old = self.behind_reference.replace(true);
404+
let array = tcx.deref_const(self.param_env.and(cv));
405+
let val = PatKind::Deref {
406+
subpattern: Pat {
407+
kind: Box::new(PatKind::Array {
408+
prefix: tcx
409+
.destructure_const(param_env.and(array))
410+
.fields
411+
.iter()
412+
.map(|val| self.recur(val, false))
413+
.collect::<Result<_, _>>()?,
414+
slice: None,
415+
suffix: vec![],
416+
}),
417+
span,
418+
ty: pointee_ty,
419+
},
420+
};
421+
self.behind_reference.set(old);
422+
val
423+
}
424+
ty::Array(elem_ty, _) |
397425
// Cannot merge this with the catch all branch below, because the `const_deref`
398426
// changes the type from slice to array, we need to keep the original type in the
399427
// pattern.
400-
ty::Slice(..) => {
428+
ty::Slice(elem_ty) => {
401429
let old = self.behind_reference.replace(true);
402430
let array = tcx.deref_const(self.param_env.and(cv));
403431
let val = PatKind::Deref {
@@ -413,7 +441,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
413441
suffix: vec![],
414442
}),
415443
span,
416-
ty: pointee_ty,
444+
ty: tcx.mk_slice(elem_ty),
417445
},
418446
};
419447
self.behind_reference.set(old);

compiler/rustc_typeck/src/check/pat.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -149,15 +149,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
149149
///
150150
/// Outside of this module, `check_pat_top` should always be used.
151151
/// Conversely, inside this module, `check_pat_top` should never be used.
152+
#[instrument(skip(self, ti))]
152153
fn check_pat(
153154
&self,
154155
pat: &'tcx Pat<'tcx>,
155156
expected: Ty<'tcx>,
156157
def_bm: BindingMode,
157158
ti: TopInfo<'tcx>,
158159
) {
159-
debug!("check_pat(pat={:?},expected={:?},def_bm={:?})", pat, expected, def_bm);
160-
161160
let path_res = match &pat.kind {
162161
PatKind::Path(qpath) => Some(self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span)),
163162
_ => None,
@@ -398,6 +397,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
398397
if let ty::Ref(_, inner_ty, _) = expected.kind() {
399398
if matches!(inner_ty.kind(), ty::Slice(_)) {
400399
let tcx = self.tcx;
400+
trace!(?lt.hir_id.local_id, "polymorphic byte string lit");
401+
self.typeck_results
402+
.borrow_mut()
403+
.treat_byte_string_as_slice
404+
.insert(lt.hir_id.local_id);
401405
pat_ty = tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_slice(tcx.types.u8));
402406
}
403407
}

compiler/rustc_typeck/src/check/writeback.rs

+3
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
7070
debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
7171
wbcx.typeck_results.used_trait_imports = used_trait_imports;
7272

73+
wbcx.typeck_results.treat_byte_string_as_slice =
74+
mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice);
75+
7376
wbcx.typeck_results.closure_captures =
7477
mem::take(&mut self.typeck_results.borrow_mut().closure_captures);
7578

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#[deny(unreachable_patterns)]
2+
3+
fn parse_data1(data: &[u8]) -> u32 {
4+
match data {
5+
b"" => 1,
6+
_ => 2,
7+
}
8+
}
9+
10+
fn parse_data2(data: &[u8]) -> u32 {
11+
match data { //~ ERROR non-exhaustive patterns: `&[_, ..]` not covered
12+
b"" => 1,
13+
}
14+
}
15+
16+
fn parse_data3(data: &[u8; 0]) -> u8 {
17+
match data {
18+
b"" => 1,
19+
}
20+
}
21+
22+
fn parse_data4(data: &[u8]) -> u8 {
23+
match data { //~ ERROR non-exhaustive patterns
24+
b"aaa" => 0,
25+
[_, _, _] => 1,
26+
}
27+
}
28+
29+
fn parse_data5(data: &[u8; 3]) -> u8 {
30+
match data {
31+
b"aaa" => 0,
32+
[_, _, _] => 1,
33+
}
34+
}
35+
36+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
error[E0004]: non-exhaustive patterns: `&[_, ..]` not covered
2+
--> $DIR/type_polymorphic_byte_str_literals.rs:11:11
3+
|
4+
LL | match data {
5+
| ^^^^ pattern `&[_, ..]` not covered
6+
|
7+
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
8+
= note: the matched value is of type `&[u8]`
9+
10+
error[E0004]: non-exhaustive patterns: `&[]`, `&[_]`, `&[_, _]` and 1 more not covered
11+
--> $DIR/type_polymorphic_byte_str_literals.rs:23:11
12+
|
13+
LL | match data {
14+
| ^^^^ patterns `&[]`, `&[_]`, `&[_, _]` and 1 more not covered
15+
|
16+
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
17+
= note: the matched value is of type `&[u8]`
18+
19+
error: aborting due to 2 previous errors
20+
21+
For more information about this error, try `rustc --explain E0004`.

src/test/ui/pattern/usefulness/match-byte-array-patterns-2.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ LL | match buf {
77
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
88
= note: the matched value is of type `&[u8; 4]`
99

10-
error[E0004]: non-exhaustive patterns: `&[0_u8..=64_u8, _, _, _]` and `&[66_u8..=u8::MAX, _, _, _]` not covered
10+
error[E0004]: non-exhaustive patterns: `&[]`, `&[_]`, `&[_, _]` and 2 more not covered
1111
--> $DIR/match-byte-array-patterns-2.rs:10:11
1212
|
1313
LL | match buf {
14-
| ^^^ patterns `&[0_u8..=64_u8, _, _, _]` and `&[66_u8..=u8::MAX, _, _, _]` not covered
14+
| ^^^ patterns `&[]`, `&[_]`, `&[_, _]` and 2 more not covered
1515
|
1616
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
1717
= note: the matched value is of type `&[u8]`

0 commit comments

Comments
 (0)