2 use rustc_index::vec::Idx;
3 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
4 use rustc_middle::mir::Field;
5 use rustc_middle::thir::{FieldPat, Pat, PatKind};
6 use rustc_middle::ty::print::with_no_trimmed_paths;
7 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
8 use rustc_session::lint;
10 use rustc_trait_selection::traits::predicate_for_trait_def;
11 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
12 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligation};
18 impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
19 /// Converts an evaluated constant to a pattern (if possible).
20 /// This means aggregate values (like structs and enums) are converted
21 /// to a pattern that matches the value (as if you'd compared via structural equality).
22 #[instrument(level = "debug", skip(self))]
23 pub(super) fn const_to_pat(
25 cv: &'tcx ty::Const<'tcx>,
28 mir_structural_match_violation: bool,
30 let pat = self.tcx.infer_ctxt().enter(|infcx| {
31 let mut convert = ConstToPat::new(self, id, span, infcx);
32 convert.to_pat(cv, mir_structural_match_violation)
40 struct ConstToPat<'a, 'tcx> {
43 param_env: ty::ParamEnv<'tcx>,
45 // This tracks if we emitted some hard error for a given const value, so that
46 // we will not subsequently issue an irrelevant lint for the same const
48 saw_const_match_error: Cell<bool>,
50 // This tracks if we emitted some diagnostic for a given const value, so that
51 // we will not subsequently issue an irrelevant lint for the same const
53 saw_const_match_lint: Cell<bool>,
55 // For backcompat we need to keep allowing non-structurally-eq types behind references.
56 // See also all the `cant-hide-behind` tests.
57 behind_reference: Cell<bool>,
59 // inference context used for checking `T: Structural` bounds.
60 infcx: InferCtxt<'a, 'tcx>,
62 include_lint_checks: bool,
64 treat_byte_string_as_slice: bool,
67 mod fallback_to_const_ref {
69 /// This error type signals that we encountered a non-struct-eq situation behind a reference.
70 /// We bubble this up in order to get back to the reference destructuring and make that emit
71 /// a const pattern instead of a deref pattern. This allows us to simply call `PartialEq::eq`
72 /// on such patterns (since that function takes a reference) and not have to jump through any
73 /// hoops to get a reference to the value.
74 pub(super) struct FallbackToConstRef(());
76 pub(super) fn fallback_to_const_ref<'a, 'tcx>(
77 c2p: &super::ConstToPat<'a, 'tcx>,
78 ) -> FallbackToConstRef {
79 assert!(c2p.behind_reference.get());
80 FallbackToConstRef(())
83 use fallback_to_const_ref::{fallback_to_const_ref, FallbackToConstRef};
85 impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
87 pat_ctxt: &PatCtxt<'_, 'tcx>,
90 infcx: InferCtxt<'a, 'tcx>,
92 trace!(?pat_ctxt.typeck_results.hir_owner);
97 param_env: pat_ctxt.param_env,
98 include_lint_checks: pat_ctxt.include_lint_checks,
99 saw_const_match_error: Cell::new(false),
100 saw_const_match_lint: Cell::new(false),
101 behind_reference: Cell::new(false),
102 treat_byte_string_as_slice: pat_ctxt
104 .treat_byte_string_as_slice
105 .contains(&id.local_id),
109 fn tcx(&self) -> TyCtxt<'tcx> {
113 fn adt_derive_msg(&self, adt_def: &AdtDef) -> String {
114 let path = self.tcx().def_path_str(adt_def.did);
116 "to use a constant of type `{}` in a pattern, \
117 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
122 fn search_for_structural_match_violation(&self, ty: Ty<'tcx>) -> Option<String> {
123 traits::search_for_structural_match_violation(self.span, self.tcx(), ty).map(|non_sm_ty| {
124 with_no_trimmed_paths(|| match non_sm_ty {
125 traits::NonStructuralMatchTy::Adt(adt) => self.adt_derive_msg(adt),
126 traits::NonStructuralMatchTy::Dynamic => {
127 "trait objects cannot be used in patterns".to_string()
129 traits::NonStructuralMatchTy::Opaque => {
130 "opaque types cannot be used in patterns".to_string()
132 traits::NonStructuralMatchTy::Closure => {
133 "closures cannot be used in patterns".to_string()
135 traits::NonStructuralMatchTy::Generator => {
136 "generators cannot be used in patterns".to_string()
138 traits::NonStructuralMatchTy::Param => {
139 bug!("use of a constant whose type is a parameter inside a pattern")
141 traits::NonStructuralMatchTy::Projection => {
142 bug!("use of a constant whose type is a projection inside a pattern")
144 traits::NonStructuralMatchTy::Foreign => {
145 bug!("use of a value of a foreign type inside a pattern")
151 fn type_marked_structural(&self, ty: Ty<'tcx>) -> bool {
152 ty.is_structural_eq_shallow(self.infcx.tcx)
157 cv: &'tcx ty::Const<'tcx>,
158 mir_structural_match_violation: bool,
160 trace!(self.treat_byte_string_as_slice);
161 // This method is just a wrapper handling a validity check; the heavy lifting is
162 // performed by the recursive `recur` method, which is not meant to be
163 // invoked except by this method.
165 // once indirect_structural_match is a full fledged error, this
166 // level of indirection can be eliminated
168 let inlined_const_as_pat = self.recur(cv, mir_structural_match_violation).unwrap();
170 if self.include_lint_checks && !self.saw_const_match_error.get() {
171 // If we were able to successfully convert the const to some pat,
172 // double-check that all types in the const implement `Structural`.
174 let structural = self.search_for_structural_match_violation(cv.ty);
176 "search_for_structural_match_violation cv.ty: {:?} returned: {:?}",
180 // This can occur because const qualification treats all associated constants as
181 // opaque, whereas `search_for_structural_match_violation` tries to monomorphize them
184 // FIXME(#73448): Find a way to bring const qualification into parity with
185 // `search_for_structural_match_violation`.
186 if structural.is_none() && mir_structural_match_violation {
187 warn!("MIR const-checker found novel structural match violation. See #73448.");
188 return inlined_const_as_pat;
191 if let Some(msg) = structural {
192 if !self.type_may_have_partial_eq_impl(cv.ty) {
193 // span_fatal avoids ICE from resolution of non-existent method (rare case).
194 self.tcx().sess.span_fatal(self.span, &msg);
195 } else if mir_structural_match_violation && !self.saw_const_match_lint.get() {
196 self.tcx().struct_span_lint_hir(
197 lint::builtin::INDIRECT_STRUCTURAL_MATCH,
200 |lint| lint.build(&msg).emit(),
204 "`search_for_structural_match_violation` found one, but `CustomEq` was \
205 not in the qualifs for that `const`"
214 fn type_may_have_partial_eq_impl(&self, ty: Ty<'tcx>) -> bool {
215 // double-check there even *is* a semantic `PartialEq` to dispatch to.
217 // (If there isn't, then we can safely issue a hard
218 // error, because that's never worked, due to compiler
219 // using `PartialEq::eq` in this scenario in the past.)
220 let partial_eq_trait_id =
221 self.tcx().require_lang_item(hir::LangItem::PartialEq, Some(self.span));
222 let obligation: PredicateObligation<'_> = predicate_for_trait_def(
225 ObligationCause::misc(self.span, self.id),
231 // FIXME: should this call a `predicate_must_hold` variant instead?
233 let has_impl = self.infcx.predicate_may_hold(&obligation);
235 // Note: To fix rust-lang/rust#65466, we could just remove this type
236 // walk hack for function pointers, and unconditionally error
237 // if `PartialEq` is not implemented. However, that breaks stable
238 // code at the moment, because types like `for <'a> fn(&'a ())` do
239 // not *yet* implement `PartialEq`. So for now we leave this here.
241 || ty.walk().any(|t| match t.unpack() {
242 ty::subst::GenericArgKind::Lifetime(_) => false,
243 ty::subst::GenericArgKind::Type(t) => t.is_fn_ptr(),
244 ty::subst::GenericArgKind::Const(_) => false,
250 vals: impl Iterator<Item = &'tcx ty::Const<'tcx>>,
251 ) -> Result<Vec<FieldPat<'tcx>>, FallbackToConstRef> {
254 let field = Field::new(idx);
255 Ok(FieldPat { field, pattern: self.recur(val, false)? })
260 // Recursive helper for `to_pat`; invoke that (instead of calling this directly).
263 cv: &'tcx ty::Const<'tcx>,
264 mir_structural_match_violation: bool,
265 ) -> Result<Pat<'tcx>, FallbackToConstRef> {
267 let span = self.span;
268 let tcx = self.tcx();
269 let param_env = self.param_env;
271 let kind = match cv.ty.kind() {
273 if self.include_lint_checks {
274 tcx.struct_span_lint_hir(
275 lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
278 |lint| lint.build("floating-point types cannot be used in patterns").emit(),
281 PatKind::Constant { value: cv }
283 ty::Adt(adt_def, _) if adt_def.is_union() => {
284 // Matching on union fields is unsafe, we can't hide it in constants
285 self.saw_const_match_error.set(true);
286 let msg = "cannot use unions in constant patterns";
287 if self.include_lint_checks {
288 tcx.sess.span_err(span, msg);
290 tcx.sess.delay_span_bug(span, msg)
295 if !self.type_may_have_partial_eq_impl(cv.ty)
296 // FIXME(#73448): Find a way to bring const qualification into parity with
297 // `search_for_structural_match_violation` and then remove this condition.
298 && self.search_for_structural_match_violation(cv.ty).is_some() =>
300 // Obtain the actual type that isn't annotated. If we just looked at `cv.ty` we
301 // could get `Option<NonStructEq>`, even though `Option` is annotated with derive.
302 let msg = self.search_for_structural_match_violation(cv.ty).unwrap();
303 self.saw_const_match_error.set(true);
304 if self.include_lint_checks {
305 tcx.sess.span_err(self.span, &msg);
307 tcx.sess.delay_span_bug(self.span, &msg)
311 // If the type is not structurally comparable, just emit the constant directly,
312 // causing the pattern match code to treat it opaquely.
313 // FIXME: This code doesn't emit errors itself, the caller emits the errors.
314 // So instead of specific errors, you just get blanket errors about the whole
316 // https://github.com/rust-lang/rust/pull/70743#discussion_r404701963 for
318 // Backwards compatibility hack because we can't cause hard errors on these
319 // types, so we compare them via `PartialEq::eq` at runtime.
320 ty::Adt(..) if !self.type_marked_structural(cv.ty) && self.behind_reference.get() => {
321 if self.include_lint_checks
322 && !self.saw_const_match_error.get()
323 && !self.saw_const_match_lint.get()
325 self.saw_const_match_lint.set(true);
326 tcx.struct_span_lint_hir(
327 lint::builtin::INDIRECT_STRUCTURAL_MATCH,
332 "to use a constant of type `{}` in a pattern, \
333 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
336 lint.build(&msg).emit()
340 // Since we are behind a reference, we can just bubble the error up so we get a
341 // constant at reference type, making it easy to let the fallback call
342 // `PartialEq::eq` on it.
343 return Err(fallback_to_const_ref(self));
345 ty::Adt(adt_def, _) if !self.type_marked_structural(cv.ty) => {
346 debug!("adt_def {:?} has !type_marked_structural for cv.ty: {:?}", adt_def, cv.ty);
347 let path = tcx.def_path_str(adt_def.did);
349 "to use a constant of type `{}` in a pattern, \
350 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
353 self.saw_const_match_error.set(true);
354 if self.include_lint_checks {
355 tcx.sess.span_err(span, &msg);
357 tcx.sess.delay_span_bug(span, &msg)
361 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
362 let destructured = tcx.destructure_const(param_env.and(cv));
366 variant_index: destructured
368 .expect("destructed const of adt without variant id"),
369 subpatterns: self.field_pats(destructured.fields.iter().copied())?,
372 ty::Tuple(_) | ty::Adt(_, _) => {
373 let destructured = tcx.destructure_const(param_env.and(cv));
374 PatKind::Leaf { subpatterns: self.field_pats(destructured.fields.iter().copied())? }
376 ty::Array(..) => PatKind::Array {
378 .destructure_const(param_env.and(cv))
381 .map(|val| self.recur(val, false))
382 .collect::<Result<_, _>>()?,
386 ty::Ref(_, pointee_ty, ..) => match *pointee_ty.kind() {
387 // These are not allowed and will error elsewhere anyway.
389 self.saw_const_match_error.set(true);
390 let msg = format!("`{}` cannot be used in patterns", cv.ty);
391 if self.include_lint_checks {
392 tcx.sess.span_err(span, &msg);
394 tcx.sess.delay_span_bug(span, &msg)
398 // `&str` is represented as `ConstValue::Slice`, let's keep using this
399 // optimization for now.
400 ty::Str => PatKind::Constant { value: cv },
401 // `b"foo"` produces a `&[u8; 3]`, but you can't use constants of array type when
402 // matching against references, you can only use byte string literals.
403 // The typechecker has a special case for byte string literals, by treating them
404 // as slices. This means we turn `&[T; N]` constants into slice patterns, which
405 // has no negative effects on pattern matching, even if we're actually matching on
407 ty::Array(..) if !self.treat_byte_string_as_slice => {
408 let old = self.behind_reference.replace(true);
409 let array = tcx.deref_const(self.param_env.and(cv));
410 let val = PatKind::Deref {
412 kind: Box::new(PatKind::Array {
414 .destructure_const(param_env.and(array))
417 .map(|val| self.recur(val, false))
418 .collect::<Result<_, _>>()?,
426 self.behind_reference.set(old);
429 ty::Array(elem_ty, _) |
430 // Cannot merge this with the catch all branch below, because the `const_deref`
431 // changes the type from slice to array, we need to keep the original type in the
433 ty::Slice(elem_ty) => {
434 let old = self.behind_reference.replace(true);
435 let array = tcx.deref_const(self.param_env.and(cv));
436 let val = PatKind::Deref {
438 kind: Box::new(PatKind::Slice {
440 .destructure_const(param_env.and(array))
443 .map(|val| self.recur(val, false))
444 .collect::<Result<_, _>>()?,
449 ty: tcx.mk_slice(elem_ty),
452 self.behind_reference.set(old);
455 // Backwards compatibility hack: support references to non-structural types.
457 // this pattern to a `PartialEq::eq` comparison and `PartialEq::eq` takes a
458 // reference. This makes the rest of the matching logic simpler as it doesn't have
459 // to figure out how to get a reference again.
460 ty::Adt(adt_def, _) if !self.type_marked_structural(pointee_ty) => {
461 if self.behind_reference.get() {
462 if self.include_lint_checks
463 && !self.saw_const_match_error.get()
464 && !self.saw_const_match_lint.get()
466 self.saw_const_match_lint.set(true);
467 let msg = self.adt_derive_msg(adt_def);
468 self.tcx().struct_span_lint_hir(
469 lint::builtin::INDIRECT_STRUCTURAL_MATCH,
472 |lint| lint.build(&msg).emit(),
475 PatKind::Constant { value: cv }
477 if !self.saw_const_match_error.get() {
478 self.saw_const_match_error.set(true);
479 let msg = self.adt_derive_msg(adt_def);
480 if self.include_lint_checks {
481 tcx.sess.span_err(span, &msg);
483 tcx.sess.delay_span_bug(span, &msg)
489 // All other references are converted into deref patterns and then recursively
490 // convert the dereferenced constant to a pattern that is the sub-pattern of the
493 if !pointee_ty.is_sized(tcx.at(span), param_env) {
494 // `tcx.deref_const()` below will ICE with an unsized type
495 // (except slices, which are handled in a separate arm above).
496 let msg = format!("cannot use unsized non-slice type `{}` in constant patterns", pointee_ty);
497 if self.include_lint_checks {
498 tcx.sess.span_err(span, &msg);
500 tcx.sess.delay_span_bug(span, &msg);
504 let old = self.behind_reference.replace(true);
505 // In case there are structural-match violations somewhere in this subpattern,
506 // we fall back to a const pattern. If we do not do this, we may end up with
507 // a !structural-match constant that is not of reference type, which makes it
508 // very hard to invoke `PartialEq::eq` on it as a fallback.
509 let val = match self.recur(tcx.deref_const(self.param_env.and(cv)), false) {
510 Ok(subpattern) => PatKind::Deref { subpattern },
511 Err(_) => PatKind::Constant { value: cv },
513 self.behind_reference.set(old);
518 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::FnDef(..) => {
519 PatKind::Constant { value: cv }
521 ty::RawPtr(pointee) if pointee.ty.is_sized(tcx.at(span), param_env) => {
522 PatKind::Constant { value: cv }
524 // FIXME: these can have very suprising behaviour where optimization levels or other
525 // compilation choices change the runtime behaviour of the match.
526 // See https://github.com/rust-lang/rust/issues/70861 for examples.
527 ty::FnPtr(..) | ty::RawPtr(..) => {
528 if self.include_lint_checks
529 && !self.saw_const_match_error.get()
530 && !self.saw_const_match_lint.get()
532 self.saw_const_match_lint.set(true);
533 let msg = "function pointers and unsized pointers in patterns behave \
534 unpredictably and should not be relied upon. \
535 See https://github.com/rust-lang/rust/issues/70861 for details.";
536 tcx.struct_span_lint_hir(
537 lint::builtin::POINTER_STRUCTURAL_MATCH,
540 |lint| lint.build(&msg).emit(),
543 PatKind::Constant { value: cv }
546 self.saw_const_match_error.set(true);
547 let msg = format!("`{}` cannot be used in patterns", cv.ty);
548 if self.include_lint_checks {
549 tcx.sess.span_err(span, &msg);
551 tcx.sess.delay_span_bug(span, &msg)
557 if self.include_lint_checks
558 && !self.saw_const_match_error.get()
559 && !self.saw_const_match_lint.get()
560 && mir_structural_match_violation
561 // FIXME(#73448): Find a way to bring const qualification into parity with
562 // `search_for_structural_match_violation` and then remove this condition.
563 && self.search_for_structural_match_violation(cv.ty).is_some()
565 self.saw_const_match_lint.set(true);
566 // Obtain the actual type that isn't annotated. If we just looked at `cv.ty` we
567 // could get `Option<NonStructEq>`, even though `Option` is annotated with derive.
568 let msg = self.search_for_structural_match_violation(cv.ty).unwrap().replace(
570 "in a pattern, the constant's initializer must be trivial or",
572 tcx.struct_span_lint_hir(
573 lint::builtin::NONTRIVIAL_STRUCTURAL_MATCH,
576 |lint| lint.build(&msg).emit(),
580 Ok(Pat { span, ty: cv.ty, kind: Box::new(kind) })