1use core::ops::ControlFlow;
23use rustc_abi::{FieldIdx, VariantIdx};
4use rustc_apfloat::Float;
5use rustc_data_structures::fx::FxHashSet;
6use rustc_errors::{Diag, msg};
7use rustc_hiras hir;
8use rustc_hir::find_attr;
9use rustc_index::Idx;
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_infer::traits::Obligation;
12use rustc_middle::mir::interpret::ErrorHandled;
13use rustc_middle::span_bug;
14use rustc_middle::thir::{FieldPat, Pat, PatKind};
15use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitableExt, TypeVisitor};
16use rustc_span::def_id::DefId;
17use rustc_span::{DUMMY_SP, Span};
18use rustc_trait_selection::traits::ObligationCause;
19use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
20use tracing::{debug, instrument, trace};
2122use super::PatCtxt;
23use crate::errors::{
24ConstPatternDependsOnGenericParameter, CouldNotEvalConstPattern, InvalidPattern, NaNPattern,
25PointerPattern, TypeNotPartialEq, TypeNotStructural, UnionPattern, UnsizedPattern,
26};
2728impl<'tcx> PatCtxt<'tcx> {
29/// Converts a constant to a pattern (if possible).
30 /// This means aggregate values (like structs and enums) are converted
31 /// to a pattern that matches the value (as if you'd compared via structural equality).
32 ///
33 /// Only type system constants are supported, as we are using valtrees
34 /// as an intermediate step. Unfortunately those don't carry a type
35 /// so we have to carry one ourselves.
36x;#[instrument(level = "debug", skip(self), ret)]37pub(super) fn const_to_pat(
38&self,
39 c: ty::Const<'tcx>,
40 ty: Ty<'tcx>,
41 id: hir::HirId,
42 span: Span,
43 ) -> Box<Pat<'tcx>> {
44let mut convert = ConstToPat::new(self, id, span, c);
4546match c.kind() {
47 ty::ConstKind::Unevaluated(uv) => convert.unevaluated_to_pat(uv, ty),
48 ty::ConstKind::Value(value) => convert.valtree_to_pat(value),
49_ => span_bug!(span, "Invalid `ConstKind` for `const_to_pat`: {:?}", c),
50 }
51 }
52}
5354struct ConstToPat<'tcx> {
55 tcx: TyCtxt<'tcx>,
56 typing_env: ty::TypingEnv<'tcx>,
57 span: Span,
58 id: hir::HirId,
5960 c: ty::Const<'tcx>,
61}
6263impl<'tcx> ConstToPat<'tcx> {
64fn new(pat_ctxt: &PatCtxt<'tcx>, id: hir::HirId, span: Span, c: ty::Const<'tcx>) -> Self {
65{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs:65",
"rustc_mir_build::thir::pattern::const_to_pat",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs"),
::tracing_core::__macro_support::Option::Some(65u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
::tracing_core::field::FieldSet::new(&["pat_ctxt.typeck_results.hir_owner"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&pat_ctxt.typeck_results.hir_owner)
as &dyn Value))])
});
} else { ; }
};trace!(?pat_ctxt.typeck_results.hir_owner);
66ConstToPat { tcx: pat_ctxt.tcx, typing_env: pat_ctxt.typing_env, span, id, c }
67 }
6869fn type_marked_structural(&self, ty: Ty<'tcx>) -> bool {
70ty.is_structural_eq_shallow(self.tcx)
71 }
7273/// We errored. Signal that in the pattern, so that follow up errors can be silenced.
74fn mk_err(&self, mut err: Diag<'_>, ty: Ty<'tcx>) -> Box<Pat<'tcx>> {
75if let ty::ConstKind::Unevaluated(uv) = self.c.kind() {
76let def_kind = self.tcx.def_kind(uv.def);
77if let hir::def::DefKind::AssocConst = def_kind78 && let Some(def_id) = uv.def.as_local()
79 {
80// Include the container item in the output.
81err.span_label(self.tcx.def_span(self.tcx.local_parent(def_id)), "");
82 }
83if let hir::def::DefKind::Const | hir::def::DefKind::AssocConst = def_kind {
84err.span_label(self.tcx.def_span(uv.def), rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("constant defined here"))msg!("constant defined here"));
85 }
86 }
87Box::new(Pat { span: self.span, ty, kind: PatKind::Error(err.emit()), extra: None })
88 }
8990fn unevaluated_to_pat(
91&mut self,
92 uv: ty::UnevaluatedConst<'tcx>,
93 ty: Ty<'tcx>,
94 ) -> Box<Pat<'tcx>> {
95// It's not *technically* correct to be revealing opaque types here as borrowcheck has
96 // not run yet. However, CTFE itself uses `TypingMode::PostAnalysis` unconditionally even
97 // during typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
98 // As a result we always use a revealed env when resolving the instance to evaluate.
99 //
100 // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
101 // instead of having this logic here
102let typing_env = self103 .tcx
104 .erase_and_anonymize_regions(self.typing_env)
105 .with_post_analysis_normalized(self.tcx);
106let uv = self.tcx.erase_and_anonymize_regions(uv);
107108// try to resolve e.g. associated constants to their definition on an impl, and then
109 // evaluate the const.
110let valtree = match self.tcx.const_eval_resolve_for_typeck(typing_env, uv, self.span) {
111Ok(Ok(c)) => c,
112Err(ErrorHandled::Reported(_, _)) => {
113// Let's tell the use where this failing const occurs.
114let mut err =
115self.tcx.dcx().create_err(CouldNotEvalConstPattern { span: self.span });
116// We've emitted an error on the original const, it would be redundant to complain
117 // on its use as well.
118if let ty::ConstKind::Unevaluated(uv) = self.c.kind()
119 && let hir::def::DefKind::Const | hir::def::DefKind::AssocConst =
120self.tcx.def_kind(uv.def)
121 {
122err.downgrade_to_delayed_bug();
123 }
124return self.mk_err(err, ty);
125 }
126Err(ErrorHandled::TooGeneric(_)) => {
127let mut e = self128 .tcx
129 .dcx()
130 .create_err(ConstPatternDependsOnGenericParameter { span: self.span });
131for arg in uv.args {
132if let ty::GenericArgKind::Type(ty) = arg.kind()
133 && let ty::Param(param_ty) = ty.kind()
134 {
135let def_id = self.tcx.hir_enclosing_body_owner(self.id);
136let generics = self.tcx.generics_of(def_id);
137let param = generics.type_param(*param_ty, self.tcx);
138let span = self.tcx.def_span(param.def_id);
139 e.span_label(span, "constant depends on this generic parameter");
140if let Some(ident) = self.tcx.def_ident_span(def_id)
141 && self.tcx.sess.source_map().is_multiline(ident.between(span))
142 {
143// Display the `fn` name as well in the diagnostic, as the generic isn't
144 // in the same line and it could be confusing otherwise.
145e.span_label(ident, "");
146 }
147 }
148 }
149return self.mk_err(e, ty);
150 }
151Ok(Err(bad_ty)) => {
152// The pattern cannot be turned into a valtree.
153let e = match bad_ty.kind() {
154 ty::Adt(def, ..) => {
155if !def.is_union() {
::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
156self.tcx.dcx().create_err(UnionPattern { span: self.span })
157 }
158 ty::FnPtr(..) | ty::RawPtr(..) => {
159self.tcx.dcx().create_err(PointerPattern { span: self.span })
160 }
161_ => self.tcx.dcx().create_err(InvalidPattern {
162 span: self.span,
163 non_sm_ty: bad_ty,
164 prefix: bad_ty.prefix_string(self.tcx).to_string(),
165 }),
166 };
167return self.mk_err(e, ty);
168 }
169 };
170171// Lower the valtree to a THIR pattern.
172let mut thir_pat = self.valtree_to_pat(ty::Value { ty, valtree });
173174if !thir_pat.references_error() {
175// Always check for `PartialEq` if we had no other errors yet.
176if !type_has_partial_eq_impl(self.tcx, typing_env, ty).has_impl {
177let mut err = self.tcx.dcx().create_err(TypeNotPartialEq { span: self.span, ty });
178extend_type_not_partial_eq(self.tcx, typing_env, ty, &mut err);
179return self.mk_err(err, ty);
180 }
181 }
182183// Mark the pattern to indicate that it is the result of lowering a named
184 // constant. This is used for diagnostics.
185thir_pat.extra.get_or_insert_default().expanded_const = Some(uv.def);
186thir_pat187 }
188189fn lower_field_values_to_fieldpats(
190&self,
191 values: impl Iterator<Item = ty::Value<'tcx>>,
192 ) -> Vec<FieldPat<'tcx>> {
193values194 .enumerate()
195 .map(|(index, value)| FieldPat {
196 field: FieldIdx::new(index),
197 pattern: *self.valtree_to_pat(value),
198 })
199 .collect()
200 }
201202// Recursive helper for `to_pat`; invoke that (instead of calling this directly).
203#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("valtree_to_pat",
"rustc_mir_build::thir::pattern::const_to_pat",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs"),
::tracing_core::__macro_support::Option::Some(203u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
::tracing_core::field::FieldSet::new(&["value"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Box<Pat<'tcx>> = loop {};
return __tracing_attr_fake_return;
}
{
let span = self.span;
let tcx = self.tcx;
let ty::Value { ty, valtree } = value;
let kind =
match ty.kind() {
ty::Adt(adt_def, _) if !self.type_marked_structural(ty) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs:214",
"rustc_mir_build::thir::pattern::const_to_pat",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs"),
::tracing_core::__macro_support::Option::Some(214u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
::tracing_core::field::FieldSet::new(&["message", "adt_def",
"value.ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ADT type in pattern is not `type_marked_structural`")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&adt_def) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&value.ty)
as &dyn Value))])
});
} else { ; }
};
let PartialEqImplStatus {
is_derived, structural_partial_eq, non_blanket_impl, .. } =
type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
let (manual_partialeq_impl_span,
manual_partialeq_impl_note) =
match (structural_partial_eq, non_blanket_impl) {
(true, _) => (None, false),
(_, Some(def_id)) if def_id.is_local() && !is_derived => {
(Some(tcx.def_span(def_id)), false)
}
_ => (None, true),
};
let ty_def_span = tcx.def_span(adt_def.did());
let err =
TypeNotStructural {
span,
ty,
ty_def_span,
manual_partialeq_impl_span,
manual_partialeq_impl_note,
};
return self.mk_err(tcx.dcx().create_err(err), ty);
}
ty::Adt(adt_def, args) if adt_def.is_enum() => {
let (&variant_index, fields) =
valtree.to_branch().split_first().unwrap();
let variant_index =
VariantIdx::from_u32(variant_index.to_leaf().to_u32());
PatKind::Variant {
adt_def: *adt_def,
args,
variant_index,
subpatterns: self.lower_field_values_to_fieldpats(fields.iter().map(|ct|
ct.to_value())),
}
}
ty::Adt(def, _) => {
if !!def.is_union() {
::core::panicking::panic("assertion failed: !def.is_union()")
};
PatKind::Leaf {
subpatterns: self.lower_field_values_to_fieldpats(valtree.to_branch().iter().map(|ct|
ct.to_value())),
}
}
ty::Tuple(_) =>
PatKind::Leaf {
subpatterns: self.lower_field_values_to_fieldpats(valtree.to_branch().iter().map(|ct|
ct.to_value())),
},
ty::Slice(_) =>
PatKind::Slice {
prefix: valtree.to_branch().iter().map(|val|
*self.valtree_to_pat(val.to_value())).collect(),
slice: None,
suffix: Box::new([]),
},
ty::Array(_, _) =>
PatKind::Array {
prefix: valtree.to_branch().iter().map(|val|
*self.valtree_to_pat(val.to_value())).collect(),
slice: None,
suffix: Box::new([]),
},
ty::Str => { PatKind::Constant { value } }
ty::Ref(_, pointee_ty, ..) => {
if pointee_ty.is_str() || pointee_ty.is_slice() ||
pointee_ty.is_sized(tcx, self.typing_env) {
PatKind::Deref {
pin: hir::Pinnedness::Not,
subpattern: self.valtree_to_pat(ty::Value {
ty: *pointee_ty,
valtree,
}),
}
} else {
return self.mk_err(tcx.dcx().create_err(UnsizedPattern {
span,
non_sm_ty: *pointee_ty,
}), ty);
}
}
ty::Float(flt) => {
let v = valtree.to_leaf();
let is_nan =
match flt {
ty::FloatTy::F16 => v.to_f16().is_nan(),
ty::FloatTy::F32 => v.to_f32().is_nan(),
ty::FloatTy::F64 => v.to_f64().is_nan(),
ty::FloatTy::F128 => v.to_f128().is_nan(),
};
if is_nan {
return self.mk_err(tcx.dcx().create_err(NaNPattern {
span,
}), ty);
} else { PatKind::Constant { value } }
}
ty::Pat(..) | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_)
| ty::RawPtr(..) => {
PatKind::Constant { value }
}
ty::FnPtr(..) => {
{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("Valtree construction would never succeed for FnPtr, so this is unreachable.")));
}
}
_ => {
let err =
InvalidPattern {
span,
non_sm_ty: ty,
prefix: ty.prefix_string(tcx).to_string(),
};
return self.mk_err(tcx.dcx().create_err(err), ty);
}
};
Box::new(Pat { span, ty, kind, extra: None })
}
}
}#[instrument(skip(self), level = "debug")]204fn valtree_to_pat(&self, value: ty::Value<'tcx>) -> Box<Pat<'tcx>> {
205let span = self.span;
206let tcx = self.tcx;
207let ty::Value { ty, valtree } = value;
208209let kind = match ty.kind() {
210// Extremely important check for all ADTs!
211 // Make sure they are eligible to be used in patterns, and if not, emit an error.
212ty::Adt(adt_def, _) if !self.type_marked_structural(ty) => {
213// This ADT cannot be used as a constant in patterns.
214debug!(?adt_def, ?value.ty, "ADT type in pattern is not `type_marked_structural`");
215let PartialEqImplStatus {
216 is_derived, structural_partial_eq, non_blanket_impl, ..
217 } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
218let (manual_partialeq_impl_span, manual_partialeq_impl_note) =
219match (structural_partial_eq, non_blanket_impl) {
220 (true, _) => (None, false),
221 (_, Some(def_id)) if def_id.is_local() && !is_derived => {
222 (Some(tcx.def_span(def_id)), false)
223 }
224_ => (None, true),
225 };
226let ty_def_span = tcx.def_span(adt_def.did());
227let err = TypeNotStructural {
228 span,
229 ty,
230 ty_def_span,
231 manual_partialeq_impl_span,
232 manual_partialeq_impl_note,
233 };
234return self.mk_err(tcx.dcx().create_err(err), ty);
235 }
236 ty::Adt(adt_def, args) if adt_def.is_enum() => {
237let (&variant_index, fields) = valtree.to_branch().split_first().unwrap();
238let variant_index = VariantIdx::from_u32(variant_index.to_leaf().to_u32());
239 PatKind::Variant {
240 adt_def: *adt_def,
241 args,
242 variant_index,
243 subpatterns: self
244.lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())),
245 }
246 }
247 ty::Adt(def, _) => {
248assert!(!def.is_union()); // Valtree construction would never succeed for unions.
249PatKind::Leaf {
250 subpatterns: self.lower_field_values_to_fieldpats(
251 valtree.to_branch().iter().map(|ct| ct.to_value()),
252 ),
253 }
254 }
255 ty::Tuple(_) => PatKind::Leaf {
256 subpatterns: self.lower_field_values_to_fieldpats(
257 valtree.to_branch().iter().map(|ct| ct.to_value()),
258 ),
259 },
260 ty::Slice(_) => PatKind::Slice {
261 prefix: valtree
262 .to_branch()
263 .iter()
264 .map(|val| *self.valtree_to_pat(val.to_value()))
265 .collect(),
266 slice: None,
267 suffix: Box::new([]),
268 },
269 ty::Array(_, _) => PatKind::Array {
270 prefix: valtree
271 .to_branch()
272 .iter()
273 .map(|val| *self.valtree_to_pat(val.to_value()))
274 .collect(),
275 slice: None,
276 suffix: Box::new([]),
277 },
278 ty::Str => {
279// Constant/literal patterns of type `&str` are lowered to a
280 // `PatKind::Deref` wrapping a `PatKind::Constant` of type `str`.
281 // This pattern node is the `str` constant part.
282 //
283 // Under `feature(deref_patterns)`, string literal patterns can also
284 // have type `str` directly, without the `&`, in order to allow things
285 // like `deref!("...")` to work when the scrutinee is `String`.
286PatKind::Constant { value }
287 }
288 ty::Ref(_, pointee_ty, ..) => {
289if pointee_ty.is_str()
290 || pointee_ty.is_slice()
291 || pointee_ty.is_sized(tcx, self.typing_env)
292 {
293 PatKind::Deref {
294// This node has type `ty::Ref`, so it's not a pin-deref.
295pin: hir::Pinnedness::Not,
296// Lower the valtree to a pattern as the pointee type.
297 // This works because references have the same valtree
298 // representation as their pointee.
299subpattern: self.valtree_to_pat(ty::Value { ty: *pointee_ty, valtree }),
300 }
301 } else {
302return self.mk_err(
303 tcx.dcx().create_err(UnsizedPattern { span, non_sm_ty: *pointee_ty }),
304 ty,
305 );
306 }
307 }
308 ty::Float(flt) => {
309let v = valtree.to_leaf();
310let is_nan = match flt {
311 ty::FloatTy::F16 => v.to_f16().is_nan(),
312 ty::FloatTy::F32 => v.to_f32().is_nan(),
313 ty::FloatTy::F64 => v.to_f64().is_nan(),
314 ty::FloatTy::F128 => v.to_f128().is_nan(),
315 };
316if is_nan {
317// NaNs are not ever equal to anything so they make no sense as patterns.
318 // Also see <https://github.com/rust-lang/rfcs/pull/3535>.
319return self.mk_err(tcx.dcx().create_err(NaNPattern { span }), ty);
320 } else {
321 PatKind::Constant { value }
322 }
323 }
324 ty::Pat(..) | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) => {
325// The raw pointers we see here have been "vetted" by valtree construction to be
326 // just integers, so we simply allow them.
327PatKind::Constant { value }
328 }
329 ty::FnPtr(..) => {
330unreachable!(
331"Valtree construction would never succeed for FnPtr, so this is unreachable."
332)
333 }
334_ => {
335let err = InvalidPattern {
336 span,
337 non_sm_ty: ty,
338 prefix: ty.prefix_string(tcx).to_string(),
339 };
340return self.mk_err(tcx.dcx().create_err(err), ty);
341 }
342 };
343344 Box::new(Pat { span, ty, kind, extra: None })
345 }
346}
347348/// Given a type with type parameters, visit every ADT looking for types that need to
349/// `#[derive(PartialEq)]` for it to be a structural type.
350fn extend_type_not_partial_eq<'tcx>(
351 tcx: TyCtxt<'tcx>,
352 typing_env: ty::TypingEnv<'tcx>,
353 ty: Ty<'tcx>,
354 err: &mut Diag<'_>,
355) {
356/// Collect all types that need to be `StructuralPartialEq`.
357struct UsedParamsNeedInstantiationVisitor<'tcx> {
358 tcx: TyCtxt<'tcx>,
359 typing_env: ty::TypingEnv<'tcx>,
360/// The user has written `impl PartialEq for Ty` which means it's non-structural.
361adts_with_manual_partialeq: FxHashSet<Span>,
362/// The type has no `PartialEq` implementation, neither manual or derived.
363adts_without_partialeq: FxHashSet<Span>,
364/// The user has written `impl PartialEq for Ty` which means it's non-structural,
365 /// but we don't have a span to point at, so we'll just add them as a `note`.
366manual: FxHashSet<Ty<'tcx>>,
367/// The type has no `PartialEq` implementation, neither manual or derived, but
368 /// we don't have a span to point at, so we'll just add them as a `note`.
369without: FxHashSet<Ty<'tcx>>,
370 }
371372impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for UsedParamsNeedInstantiationVisitor<'tcx> {
373type Result = ControlFlow<()>;
374fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
375match ty.kind() {
376 ty::Dynamic(..) => return ControlFlow::Break(()),
377// Unsafe binders never implement `PartialEq`, so avoid walking into them
378 // which would require instantiating its binder with placeholders too.
379ty::UnsafeBinder(..) => return ControlFlow::Break(()),
380 ty::FnPtr(..) => return ControlFlow::Continue(()),
381 ty::Adt(def, _args) => {
382let ty_def_id = def.did();
383let ty_def_span = self.tcx.def_span(ty_def_id);
384let PartialEqImplStatus {
385 has_impl,
386 is_derived,
387 structural_partial_eq,
388 non_blanket_impl,
389 } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
390match (has_impl, is_derived, structural_partial_eq, non_blanket_impl) {
391 (_, _, true, _) => {}
392 (true, false, _, Some(def_id)) if def_id.is_local() => {
393self.adts_with_manual_partialeq.insert(self.tcx.def_span(def_id));
394 }
395 (true, false, _, _) if ty_def_id.is_local() => {
396self.adts_with_manual_partialeq.insert(ty_def_span);
397 }
398 (false, _, _, _) if ty_def_id.is_local() => {
399self.adts_without_partialeq.insert(ty_def_span);
400 }
401 (true, false, _, _) => {
402self.manual.insert(ty);
403 }
404 (false, _, _, _) => {
405self.without.insert(ty);
406 }
407_ => {}
408 };
409ty.super_visit_with(self)
410 }
411_ => ty.super_visit_with(self),
412 }
413 }
414 }
415let mut v = UsedParamsNeedInstantiationVisitor {
416tcx,
417typing_env,
418 adts_with_manual_partialeq: FxHashSet::default(),
419 adts_without_partialeq: FxHashSet::default(),
420 manual: FxHashSet::default(),
421 without: FxHashSet::default(),
422 };
423if v.visit_ty(ty).is_break() {
424return;
425 }
426#[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
427for span in v.adts_with_manual_partialeq {
428 err.span_note(span, "the `PartialEq` trait must be derived, manual `impl`s are not sufficient; see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details");
429 }
430#[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
431for span in v.adts_without_partialeq {
432 err.span_label(
433 span,
434"must be annotated with `#[derive(PartialEq)]` to be usable in patterns",
435 );
436 }
437#[allow(rustc::potential_query_instability)]
438let mut manual: Vec<_> = v.manual.into_iter().map(|t| t.to_string()).collect();
439manual.sort();
440for ty in manual {
441 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns, manual `impl`s are not sufficient; see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details",
ty))
})format!(
442"`{ty}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns, manual `impl`s are not sufficient; see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details"
443));
444 }
445#[allow(rustc::potential_query_instability)]
446let mut without: Vec<_> = v.without.into_iter().map(|t| t.to_string()).collect();
447without.sort();
448for ty in without {
449 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns",
ty))
})format!(
450"`{ty}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns"
451));
452 }
453}
454455#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PartialEqImplStatus {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"PartialEqImplStatus", "has_impl", &self.has_impl, "is_derived",
&self.is_derived, "structural_partial_eq",
&self.structural_partial_eq, "non_blanket_impl",
&&self.non_blanket_impl)
}
}Debug)]
456struct PartialEqImplStatus {
457 has_impl: bool,
458 is_derived: bool,
459 structural_partial_eq: bool,
460 non_blanket_impl: Option<DefId>,
461}
462463x;#[instrument(level = "trace", skip(tcx), ret)]464fn type_has_partial_eq_impl<'tcx>(
465 tcx: TyCtxt<'tcx>,
466 typing_env: ty::TypingEnv<'tcx>,
467 ty: Ty<'tcx>,
468) -> PartialEqImplStatus {
469let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
470// double-check there even *is* a semantic `PartialEq` to dispatch to.
471 //
472 // (If there isn't, then we can safely issue a hard
473 // error, because that's never worked, due to compiler
474 // using `PartialEq::eq` in this scenario in the past.)
475let partial_eq_trait_id = tcx.require_lang_item(hir::LangItem::PartialEq, DUMMY_SP);
476let structural_partial_eq_trait_id =
477 tcx.require_lang_item(hir::LangItem::StructuralPeq, DUMMY_SP);
478479let partial_eq_obligation = Obligation::new(
480 tcx,
481 ObligationCause::dummy(),
482 param_env,
483 ty::TraitRef::new(tcx, partial_eq_trait_id, [ty, ty]),
484 );
485486let mut automatically_derived = false;
487let mut structural_peq = false;
488let mut impl_def_id = None;
489for def_id in tcx.non_blanket_impls_for_ty(partial_eq_trait_id, ty) {
490 automatically_derived = find_attr!(tcx, def_id, AutomaticallyDerived(..));
491 impl_def_id = Some(def_id);
492 }
493for _ in tcx.non_blanket_impls_for_ty(structural_partial_eq_trait_id, ty) {
494 structural_peq = true;
495 }
496// This *could* accept a type that isn't actually `PartialEq`, because region bounds get
497 // ignored. However that should be pretty much impossible since consts that do not depend on
498 // generics can only mention the `'static` lifetime, and how would one have a type that's
499 // `PartialEq` for some lifetime but *not* for `'static`? If this ever becomes a problem
500 // we'll need to leave some sort of trace of this requirement in the MIR so that borrowck
501 // can ensure that the type really implements `PartialEq`.
502 // We also do *not* require `const PartialEq`, not even in `const fn`. This violates the model
503 // that patterns can only do things that the code could also do without patterns, but it is
504 // needed for backwards compatibility. The actual pattern matching compares primitive values,
505 // `PartialEq::eq` never gets invoked, so there's no risk of us running non-const code.
506PartialEqImplStatus {
507 has_impl: infcx.predicate_must_hold_modulo_regions(&partial_eq_obligation),
508 is_derived: automatically_derived,
509 structural_partial_eq: structural_peq,
510 non_blanket_impl: impl_def_id,
511 }
512}