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_kind84 {
85err.span_label(self.tcx.def_span(uv.def), rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("constant defined here"))msg!("constant defined here"));
86 }
87 }
88Box::new(Pat { span: self.span, ty, kind: PatKind::Error(err.emit()), extra: None })
89 }
9091fn unevaluated_to_pat(
92&mut self,
93 uv: ty::UnevaluatedConst<'tcx>,
94 ty: Ty<'tcx>,
95 ) -> Box<Pat<'tcx>> {
96// It's not *technically* correct to be revealing opaque types here as borrowcheck has
97 // not run yet. However, CTFE itself uses `TypingMode::PostAnalysis` unconditionally even
98 // during typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
99 // As a result we always use a revealed env when resolving the instance to evaluate.
100 //
101 // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
102 // instead of having this logic here
103let typing_env = self104 .tcx
105 .erase_and_anonymize_regions(self.typing_env)
106 .with_post_analysis_normalized(self.tcx);
107let uv = self.tcx.erase_and_anonymize_regions(uv);
108109// try to resolve e.g. associated constants to their definition on an impl, and then
110 // evaluate the const.
111let valtree = match self.tcx.const_eval_resolve_for_typeck(typing_env, uv, self.span) {
112Ok(Ok(c)) => c,
113Err(ErrorHandled::Reported(_, _)) => {
114// Let's tell the use where this failing const occurs.
115let mut err =
116self.tcx.dcx().create_err(CouldNotEvalConstPattern { span: self.span });
117// We've emitted an error on the original const, it would be redundant to complain
118 // on its use as well.
119if let ty::ConstKind::Unevaluated(uv) = self.c.kind()
120 && let hir::def::DefKind::Const { .. } | hir::def::DefKind::AssocConst { .. } =
121self.tcx.def_kind(uv.def)
122 {
123err.downgrade_to_delayed_bug();
124 }
125return self.mk_err(err, ty);
126 }
127Err(ErrorHandled::TooGeneric(_)) => {
128let mut e = self129 .tcx
130 .dcx()
131 .create_err(ConstPatternDependsOnGenericParameter { span: self.span });
132for arg in uv.args {
133if let ty::GenericArgKind::Type(ty) = arg.kind()
134 && let ty::Param(param_ty) = ty.kind()
135 {
136let def_id = self.tcx.hir_enclosing_body_owner(self.id);
137let generics = self.tcx.generics_of(def_id);
138let param = generics.type_param(*param_ty, self.tcx);
139let span = self.tcx.def_span(param.def_id);
140 e.span_label(span, "constant depends on this generic parameter");
141if let Some(ident) = self.tcx.def_ident_span(def_id)
142 && self.tcx.sess.source_map().is_multiline(ident.between(span))
143 {
144// Display the `fn` name as well in the diagnostic, as the generic isn't
145 // in the same line and it could be confusing otherwise.
146e.span_label(ident, "");
147 }
148 }
149 }
150return self.mk_err(e, ty);
151 }
152Ok(Err(bad_ty)) => {
153// The pattern cannot be turned into a valtree.
154let e = match bad_ty.kind() {
155 ty::Adt(def, ..) => {
156if !def.is_union() {
::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
157self.tcx.dcx().create_err(UnionPattern { span: self.span })
158 }
159 ty::FnPtr(..) | ty::RawPtr(..) => {
160self.tcx.dcx().create_err(PointerPattern { span: self.span })
161 }
162_ => self.tcx.dcx().create_err(InvalidPattern {
163 span: self.span,
164 non_sm_ty: bad_ty,
165 prefix: bad_ty.prefix_string(self.tcx).to_string(),
166 }),
167 };
168return self.mk_err(e, ty);
169 }
170 };
171172// Lower the valtree to a THIR pattern.
173let mut thir_pat = self.valtree_to_pat(ty::Value { ty, valtree });
174175if !thir_pat.references_error() {
176// Always check for `PartialEq` if we had no other errors yet.
177if !type_has_partial_eq_impl(self.tcx, typing_env, ty).has_impl {
178let mut err = self.tcx.dcx().create_err(TypeNotPartialEq { span: self.span, ty });
179extend_type_not_partial_eq(self.tcx, typing_env, ty, &mut err);
180return self.mk_err(err, ty);
181 }
182 }
183184// Mark the pattern to indicate that it is the result of lowering a named
185 // constant. This is used for diagnostics.
186thir_pat.extra.get_or_insert_default().expanded_const = Some(uv.def);
187thir_pat188 }
189190fn lower_field_values_to_fieldpats(
191&self,
192 values: impl Iterator<Item = ty::Value<'tcx>>,
193 ) -> Vec<FieldPat<'tcx>> {
194values195 .enumerate()
196 .map(|(index, value)| FieldPat {
197 field: FieldIdx::new(index),
198 pattern: *self.valtree_to_pat(value),
199 })
200 .collect()
201 }
202203// Recursive helper for `to_pat`; invoke that (instead of calling this directly).
204#[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(204u32),
::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:215",
"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(215u32),
::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")]205fn valtree_to_pat(&self, value: ty::Value<'tcx>) -> Box<Pat<'tcx>> {
206let span = self.span;
207let tcx = self.tcx;
208let ty::Value { ty, valtree } = value;
209210let kind = match ty.kind() {
211// Extremely important check for all ADTs!
212 // Make sure they are eligible to be used in patterns, and if not, emit an error.
213ty::Adt(adt_def, _) if !self.type_marked_structural(ty) => {
214// This ADT cannot be used as a constant in patterns.
215debug!(?adt_def, ?value.ty, "ADT type in pattern is not `type_marked_structural`");
216let PartialEqImplStatus {
217 is_derived, structural_partial_eq, non_blanket_impl, ..
218 } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
219let (manual_partialeq_impl_span, manual_partialeq_impl_note) =
220match (structural_partial_eq, non_blanket_impl) {
221 (true, _) => (None, false),
222 (_, Some(def_id)) if def_id.is_local() && !is_derived => {
223 (Some(tcx.def_span(def_id)), false)
224 }
225_ => (None, true),
226 };
227let ty_def_span = tcx.def_span(adt_def.did());
228let err = TypeNotStructural {
229 span,
230 ty,
231 ty_def_span,
232 manual_partialeq_impl_span,
233 manual_partialeq_impl_note,
234 };
235return self.mk_err(tcx.dcx().create_err(err), ty);
236 }
237 ty::Adt(adt_def, args) if adt_def.is_enum() => {
238let (&variant_index, fields) = valtree.to_branch().split_first().unwrap();
239let variant_index = VariantIdx::from_u32(variant_index.to_leaf().to_u32());
240 PatKind::Variant {
241 adt_def: *adt_def,
242 args,
243 variant_index,
244 subpatterns: self
245.lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())),
246 }
247 }
248 ty::Adt(def, _) => {
249assert!(!def.is_union()); // Valtree construction would never succeed for unions.
250PatKind::Leaf {
251 subpatterns: self.lower_field_values_to_fieldpats(
252 valtree.to_branch().iter().map(|ct| ct.to_value()),
253 ),
254 }
255 }
256 ty::Tuple(_) => PatKind::Leaf {
257 subpatterns: self.lower_field_values_to_fieldpats(
258 valtree.to_branch().iter().map(|ct| ct.to_value()),
259 ),
260 },
261 ty::Slice(_) => PatKind::Slice {
262 prefix: valtree
263 .to_branch()
264 .iter()
265 .map(|val| *self.valtree_to_pat(val.to_value()))
266 .collect(),
267 slice: None,
268 suffix: Box::new([]),
269 },
270 ty::Array(_, _) => PatKind::Array {
271 prefix: valtree
272 .to_branch()
273 .iter()
274 .map(|val| *self.valtree_to_pat(val.to_value()))
275 .collect(),
276 slice: None,
277 suffix: Box::new([]),
278 },
279 ty::Str => {
280// Constant/literal patterns of type `&str` are lowered to a
281 // `PatKind::Deref` wrapping a `PatKind::Constant` of type `str`.
282 // This pattern node is the `str` constant part.
283 //
284 // Under `feature(deref_patterns)`, string literal patterns can also
285 // have type `str` directly, without the `&`, in order to allow things
286 // like `deref!("...")` to work when the scrutinee is `String`.
287PatKind::Constant { value }
288 }
289 ty::Ref(_, pointee_ty, ..) => {
290if pointee_ty.is_str()
291 || pointee_ty.is_slice()
292 || pointee_ty.is_sized(tcx, self.typing_env)
293 {
294 PatKind::Deref {
295// This node has type `ty::Ref`, so it's not a pin-deref.
296pin: hir::Pinnedness::Not,
297// Lower the valtree to a pattern as the pointee type.
298 // This works because references have the same valtree
299 // representation as their pointee.
300subpattern: self.valtree_to_pat(ty::Value { ty: *pointee_ty, valtree }),
301 }
302 } else {
303return self.mk_err(
304 tcx.dcx().create_err(UnsizedPattern { span, non_sm_ty: *pointee_ty }),
305 ty,
306 );
307 }
308 }
309 ty::Float(flt) => {
310let v = valtree.to_leaf();
311let is_nan = match flt {
312 ty::FloatTy::F16 => v.to_f16().is_nan(),
313 ty::FloatTy::F32 => v.to_f32().is_nan(),
314 ty::FloatTy::F64 => v.to_f64().is_nan(),
315 ty::FloatTy::F128 => v.to_f128().is_nan(),
316 };
317if is_nan {
318// NaNs are not ever equal to anything so they make no sense as patterns.
319 // Also see <https://github.com/rust-lang/rfcs/pull/3535>.
320return self.mk_err(tcx.dcx().create_err(NaNPattern { span }), ty);
321 } else {
322 PatKind::Constant { value }
323 }
324 }
325 ty::Pat(..) | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) => {
326// The raw pointers we see here have been "vetted" by valtree construction to be
327 // just integers, so we simply allow them.
328PatKind::Constant { value }
329 }
330 ty::FnPtr(..) => {
331unreachable!(
332"Valtree construction would never succeed for FnPtr, so this is unreachable."
333)
334 }
335_ => {
336let err = InvalidPattern {
337 span,
338 non_sm_ty: ty,
339 prefix: ty.prefix_string(tcx).to_string(),
340 };
341return self.mk_err(tcx.dcx().create_err(err), ty);
342 }
343 };
344345 Box::new(Pat { span, ty, kind, extra: None })
346 }
347}
348349/// Given a type with type parameters, visit every ADT looking for types that need to
350/// `#[derive(PartialEq)]` for it to be a structural type.
351fn extend_type_not_partial_eq<'tcx>(
352 tcx: TyCtxt<'tcx>,
353 typing_env: ty::TypingEnv<'tcx>,
354 ty: Ty<'tcx>,
355 err: &mut Diag<'_>,
356) {
357/// Collect all types that need to be `StructuralPartialEq`.
358struct UsedParamsNeedInstantiationVisitor<'tcx> {
359 tcx: TyCtxt<'tcx>,
360 typing_env: ty::TypingEnv<'tcx>,
361/// The user has written `impl PartialEq for Ty` which means it's non-structural.
362adts_with_manual_partialeq: FxHashSet<Span>,
363/// The type has no `PartialEq` implementation, neither manual or derived.
364adts_without_partialeq: FxHashSet<Span>,
365/// The user has written `impl PartialEq for Ty` which means it's non-structural,
366 /// but we don't have a span to point at, so we'll just add them as a `note`.
367manual: FxHashSet<Ty<'tcx>>,
368/// The type has no `PartialEq` implementation, neither manual or derived, but
369 /// we don't have a span to point at, so we'll just add them as a `note`.
370without: FxHashSet<Ty<'tcx>>,
371 }
372373impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for UsedParamsNeedInstantiationVisitor<'tcx> {
374type Result = ControlFlow<()>;
375fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
376match ty.kind() {
377 ty::Dynamic(..) => return ControlFlow::Break(()),
378// Unsafe binders never implement `PartialEq`, so avoid walking into them
379 // which would require instantiating its binder with placeholders too.
380ty::UnsafeBinder(..) => return ControlFlow::Break(()),
381 ty::FnPtr(..) => return ControlFlow::Continue(()),
382 ty::Adt(def, _args) => {
383let ty_def_id = def.did();
384let ty_def_span = self.tcx.def_span(ty_def_id);
385let PartialEqImplStatus {
386 has_impl,
387 is_derived,
388 structural_partial_eq,
389 non_blanket_impl,
390 } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
391match (has_impl, is_derived, structural_partial_eq, non_blanket_impl) {
392 (_, _, true, _) => {}
393 (true, false, _, Some(def_id)) if def_id.is_local() => {
394self.adts_with_manual_partialeq.insert(self.tcx.def_span(def_id));
395 }
396 (true, false, _, _) if ty_def_id.is_local() => {
397self.adts_with_manual_partialeq.insert(ty_def_span);
398 }
399 (false, _, _, _) if ty_def_id.is_local() => {
400self.adts_without_partialeq.insert(ty_def_span);
401 }
402 (true, false, _, _) => {
403self.manual.insert(ty);
404 }
405 (false, _, _, _) => {
406self.without.insert(ty);
407 }
408_ => {}
409 };
410ty.super_visit_with(self)
411 }
412_ => ty.super_visit_with(self),
413 }
414 }
415 }
416let mut v = UsedParamsNeedInstantiationVisitor {
417tcx,
418typing_env,
419 adts_with_manual_partialeq: FxHashSet::default(),
420 adts_without_partialeq: FxHashSet::default(),
421 manual: FxHashSet::default(),
422 without: FxHashSet::default(),
423 };
424if v.visit_ty(ty).is_break() {
425return;
426 }
427#[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
428for span in v.adts_with_manual_partialeq {
429 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");
430 }
431#[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
432for span in v.adts_without_partialeq {
433 err.span_label(
434 span,
435"must be annotated with `#[derive(PartialEq)]` to be usable in patterns",
436 );
437 }
438#[allow(rustc::potential_query_instability)]
439let mut manual: Vec<_> = v.manual.into_iter().map(|t| t.to_string()).collect();
440manual.sort();
441for ty in manual {
442 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!(
443"`{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"
444));
445 }
446#[allow(rustc::potential_query_instability)]
447let mut without: Vec<_> = v.without.into_iter().map(|t| t.to_string()).collect();
448without.sort();
449for ty in without {
450 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!(
451"`{ty}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns"
452));
453 }
454}
455456#[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)]
457struct PartialEqImplStatus {
458 has_impl: bool,
459 is_derived: bool,
460 structural_partial_eq: bool,
461 non_blanket_impl: Option<DefId>,
462}
463464x;#[instrument(level = "trace", skip(tcx), ret)]465fn type_has_partial_eq_impl<'tcx>(
466 tcx: TyCtxt<'tcx>,
467 typing_env: ty::TypingEnv<'tcx>,
468 ty: Ty<'tcx>,
469) -> PartialEqImplStatus {
470let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
471// double-check there even *is* a semantic `PartialEq` to dispatch to.
472 //
473 // (If there isn't, then we can safely issue a hard
474 // error, because that's never worked, due to compiler
475 // using `PartialEq::eq` in this scenario in the past.)
476let partial_eq_trait_id = tcx.require_lang_item(hir::LangItem::PartialEq, DUMMY_SP);
477let structural_partial_eq_trait_id =
478 tcx.require_lang_item(hir::LangItem::StructuralPeq, DUMMY_SP);
479480let partial_eq_obligation = Obligation::new(
481 tcx,
482 ObligationCause::dummy(),
483 param_env,
484 ty::TraitRef::new(tcx, partial_eq_trait_id, [ty, ty]),
485 );
486487let mut automatically_derived = false;
488let mut structural_peq = false;
489let mut impl_def_id = None;
490for def_id in tcx.non_blanket_impls_for_ty(partial_eq_trait_id, ty) {
491 automatically_derived = find_attr!(tcx, def_id, AutomaticallyDerived(..));
492 impl_def_id = Some(def_id);
493 }
494for _ in tcx.non_blanket_impls_for_ty(structural_partial_eq_trait_id, ty) {
495 structural_peq = true;
496 }
497// This *could* accept a type that isn't actually `PartialEq`, because region bounds get
498 // ignored. However that should be pretty much impossible since consts that do not depend on
499 // generics can only mention the `'static` lifetime, and how would one have a type that's
500 // `PartialEq` for some lifetime but *not* for `'static`? If this ever becomes a problem
501 // we'll need to leave some sort of trace of this requirement in the MIR so that borrowck
502 // can ensure that the type really implements `PartialEq`.
503 // We also do *not* require `const PartialEq`, not even in `const fn`. This violates the model
504 // that patterns can only do things that the code could also do without patterns, but it is
505 // needed for backwards compatibility. The actual pattern matching compares primitive values,
506 // `PartialEq::eq` never gets invoked, so there's no risk of us running non-const code.
507PartialEqImplStatus {
508 has_impl: infcx.predicate_must_hold_modulo_regions(&partial_eq_obligation),
509 is_derived: automatically_derived,
510 structural_partial_eq: structural_peq,
511 non_blanket_impl: impl_def_id,
512 }
513}