1use rustc_attr_ir::lang_items::LangItem;
2use rustc_errors::ErrorGuaranteed;
3use rustc_hir as hir;
4use rustc_hir::ItemKind;
5use rustc_hir::def_id::{DefId, LocalDefId};
6use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
7use rustc_infer::traits::{Obligation, TraitErrors};
8use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized};
9use rustc_span::Span;
10use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
11use rustc_trait_selection::traits::{self, ObligationCtxt};
12use tracing::debug;
13
14use super::{
15 ReborrowDataField, assert_field_type_is_copy, collect_reborrow_data_fields, field_type_is_copy,
16 field_type_is_reborrow, trait_impl_lifetime_params_count,
17};
18use crate::diagnostics;
19
20#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CoerceSharedDiagnosticContext { }
#[automatically_derived]
impl ::core::clone::Clone for CoerceSharedDiagnosticContext {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<Option<Span>>;
let _: ::core::clone::AssertParamIsClone<Option<Span>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CoerceSharedDiagnosticContext { }Copy)]
21struct CoerceSharedDiagnosticContext {
22 impl_span: Span,
23 trait_span: Span,
24 source_ty_span: Span,
25 target_ty_span: Span,
26 source_lifetime_span: Option<Span>,
27 target_lifetime_span: Option<Span>,
28}
29
30#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CoerceSharedTypeRole { }
#[automatically_derived]
impl ::core::clone::Clone for CoerceSharedTypeRole {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CoerceSharedTypeRole { }Copy)]
31enum CoerceSharedTypeRole {
32 Source,
33 Target,
34}
35
36impl CoerceSharedTypeRole {
37 fn as_str(self) -> &'static str {
38 match self {
39 CoerceSharedTypeRole::Source => "source",
40 CoerceSharedTypeRole::Target => "target",
41 }
42 }
43
44 fn type_span(self, diagnostic_context: CoerceSharedDiagnosticContext) -> Span {
45 match self {
46 CoerceSharedTypeRole::Source => diagnostic_context.source_ty_span,
47 CoerceSharedTypeRole::Target => diagnostic_context.target_ty_span,
48 }
49 }
50}
51
52fn coerce_shared_diagnostic_context(
53 tcx: TyCtxt<'_>,
54 impl_did: LocalDefId,
55) -> CoerceSharedDiagnosticContext {
56 let item = tcx.hir_expect_item(impl_did);
57 let fallback_span = tcx.def_span(impl_did);
58 let mut diagnostic_context = CoerceSharedDiagnosticContext {
59 impl_span: item.span,
60 trait_span: fallback_span,
61 source_ty_span: fallback_span,
62 target_ty_span: fallback_span,
63 source_lifetime_span: None,
64 target_lifetime_span: None,
65 };
66
67 let ItemKind::Impl(impl_) = &item.kind else {
68 return diagnostic_context;
69 };
70 let Some(of_trait) = impl_.of_trait else {
71 return diagnostic_context;
72 };
73
74 diagnostic_context.trait_span = of_trait.trait_ref.path.span;
75 diagnostic_context.source_ty_span = impl_.self_ty.span;
76 diagnostic_context.source_lifetime_span = first_explicit_lifetime_span_in_ty(impl_.self_ty)
77 .or_else(|| first_explicit_impl_lifetime_param_span(impl_.generics));
78
79 if let Some(target_ty) = coerce_shared_target_ty_from_path(of_trait.trait_ref.path) {
80 diagnostic_context.target_ty_span = target_ty.span;
81 diagnostic_context.target_lifetime_span =
82 first_explicit_lifetime_span_in_ambig_ty(target_ty);
83 } else {
84 diagnostic_context.target_ty_span = diagnostic_context.trait_span;
85 }
86
87 diagnostic_context
88}
89
90fn coerce_shared_target_ty_from_path<'hir>(
91 path: &'hir hir::Path<'hir>,
92) -> Option<&'hir hir::Ty<'hir, hir::AmbigArg>> {
93 path.segments.last()?.args().args.iter().find_map(|arg| match arg {
94 hir::GenericArg::Type(ty) => Some(*ty),
95 hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) | hir::GenericArg::Infer(_) => {
96 None
97 }
98 })
99}
100
101fn first_explicit_impl_lifetime_param_span(generics: &hir::Generics<'_>) -> Option<Span> {
102 generics.params.iter().find_map(|param| match param.kind {
103 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit } => {
104 Some(param.span)
105 }
106 hir::GenericParamKind::Lifetime { .. }
107 | hir::GenericParamKind::Type { .. }
108 | hir::GenericParamKind::Const { .. } => None,
109 })
110}
111
112fn first_explicit_lifetime_span(lifetime: &hir::Lifetime) -> Option<Span> {
113 match lifetime.kind {
114 hir::LifetimeKind::Param(_) | hir::LifetimeKind::Static
115 if !lifetime.ident.span.is_dummy() =>
116 {
117 Some(lifetime.ident.span)
118 }
119 hir::LifetimeKind::Param(_)
120 | hir::LifetimeKind::Static
121 | hir::LifetimeKind::ImplicitObjectLifetimeDefault
122 | hir::LifetimeKind::Error(_)
123 | hir::LifetimeKind::Infer => None,
124 }
125}
126
127fn first_explicit_lifetime_span_in_ambig_ty(ty: &hir::Ty<'_, hir::AmbigArg>) -> Option<Span> {
128 first_explicit_lifetime_span_in_ty(ty.as_unambig_ty())
129}
130
131fn first_explicit_lifetime_span_in_ty(ty: &hir::Ty<'_>) -> Option<Span> {
132 match ty.kind {
133 hir::TyKind::Ref(lifetime, ty, _) => first_explicit_lifetime_span(lifetime)
134 .or_else(|| first_explicit_lifetime_span_in_ty(ty)),
135 hir::TyKind::Slice(ty)
136 | hir::TyKind::Array(ty, _)
137 | hir::TyKind::Pat(ty, _)
138 | hir::TyKind::FieldOf(ty, _)
139 | hir::TyKind::View(ty, _) => first_explicit_lifetime_span_in_ty(ty),
140 hir::TyKind::Ptr(ty, _) => first_explicit_lifetime_span_in_ty(ty),
141 hir::TyKind::Tup(tys) => tys.iter().find_map(first_explicit_lifetime_span_in_ty),
142 hir::TyKind::Path(qpath) => first_explicit_lifetime_span_in_qpath(qpath),
143 hir::TyKind::TraitObject(bounds, lifetime) => bounds
144 .iter()
145 .find_map(|bound| first_explicit_lifetime_span_in_path(bound.trait_ref.path))
146 .or_else(|| first_explicit_lifetime_span(&lifetime)),
147 hir::TyKind::OpaqueDef(opaque) => first_explicit_lifetime_span_in_bounds(opaque.bounds),
148 hir::TyKind::TraitAscription(bounds) => first_explicit_lifetime_span_in_bounds(bounds),
149 hir::TyKind::FnPtr(fn_ptr) => {
150 fn_ptr.generic_params.iter().find_map(|param| match param.kind {
151 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit } => {
152 Some(param.span)
153 }
154 hir::GenericParamKind::Lifetime { .. }
155 | hir::GenericParamKind::Type { .. }
156 | hir::GenericParamKind::Const { .. } => None,
157 })
158 }
159 hir::TyKind::UnsafeBinder(binder) => binder
160 .generic_params
161 .iter()
162 .find_map(|param| match param.kind {
163 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit } => {
164 Some(param.span)
165 }
166 hir::GenericParamKind::Lifetime { .. }
167 | hir::GenericParamKind::Type { .. }
168 | hir::GenericParamKind::Const { .. } => None,
169 })
170 .or_else(|| first_explicit_lifetime_span_in_ty(binder.inner_ty)),
171 hir::TyKind::InferDelegation(_)
172 | hir::TyKind::Never
173 | hir::TyKind::Infer(())
174 | hir::TyKind::Err(_) => None,
175 }
176}
177
178fn first_explicit_lifetime_span_in_bounds(bounds: hir::GenericBounds<'_>) -> Option<Span> {
179 bounds.iter().find_map(|bound| match bound {
180 hir::GenericBound::Trait(poly_trait_ref) => {
181 first_explicit_lifetime_span_in_path(poly_trait_ref.trait_ref.path)
182 }
183 hir::GenericBound::Outlives(lifetime) => first_explicit_lifetime_span(lifetime),
184 hir::GenericBound::Use(args, _) => args.iter().find_map(|arg| match arg {
185 hir::PreciseCapturingArgKind::Lifetime(lifetime) => {
186 first_explicit_lifetime_span(lifetime)
187 }
188 hir::PreciseCapturingArgKind::Param(_) => None,
189 }),
190 })
191}
192
193fn first_explicit_lifetime_span_in_qpath(qpath: hir::QPath<'_>) -> Option<Span> {
194 match qpath {
195 hir::QPath::Resolved(qself, path) => qself
196 .and_then(first_explicit_lifetime_span_in_ty)
197 .or_else(|| first_explicit_lifetime_span_in_path(path)),
198 hir::QPath::TypeRelative(qself, segment) => first_explicit_lifetime_span_in_ty(qself)
199 .or_else(|| first_explicit_lifetime_span_in_path_segment(segment)),
200 }
201}
202
203fn first_explicit_lifetime_span_in_path(path: &hir::Path<'_>) -> Option<Span> {
204 path.segments.iter().find_map(first_explicit_lifetime_span_in_path_segment)
205}
206
207fn first_explicit_lifetime_span_in_path_segment(segment: &hir::PathSegment<'_>) -> Option<Span> {
208 first_explicit_lifetime_span_in_generic_args(segment.args())
209}
210
211fn first_explicit_lifetime_span_in_generic_args(args: &hir::GenericArgs<'_>) -> Option<Span> {
212 args.args
213 .iter()
214 .find_map(|arg| match arg {
215 hir::GenericArg::Lifetime(lifetime) => first_explicit_lifetime_span(lifetime),
216 hir::GenericArg::Type(ty) => first_explicit_lifetime_span_in_ambig_ty(ty),
217 hir::GenericArg::Const(_) | hir::GenericArg::Infer(_) => None,
218 })
219 .or_else(|| {
220 args.constraints.iter().find_map(|constraint| {
221 first_explicit_lifetime_span_in_generic_args(constraint.gen_args)
222 .or_else(|| constraint.ty().and_then(first_explicit_lifetime_span_in_ty))
223 })
224 })
225}
226
227pub(super) fn coerce_shared_info<'tcx>(
228 tcx: TyCtxt<'tcx>,
229 impl_did: LocalDefId,
230) -> Result<(), ErrorGuaranteed> {
231 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/coherence/builtin/coerce_shared.rs:231",
"rustc_hir_analysis::coherence::builtin::coerce_shared",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/coherence/builtin/coerce_shared.rs"),
::tracing_core::__macro_support::Option::Some(231u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin::coerce_shared"),
::tracing_core::field::FieldSet::new(&["message"],
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("compute_coerce_shared_info(impl_did={0:?})",
impl_did) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("compute_coerce_shared_info(impl_did={:?})", impl_did);
232 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
233 let span = tcx.def_span(impl_did);
234 let diagnostic_context = coerce_shared_diagnostic_context(tcx, impl_did);
235 let trait_name = "CoerceShared";
236
237 let coerce_shared_trait = tcx.require_lang_item(LangItem::CoerceShared, span);
238
239 let source = tcx.type_of(impl_did).instantiate_identity().skip_norm_wip();
240 let trait_ref = tcx.impl_trait_ref(impl_did).instantiate_identity().skip_norm_wip();
241
242 if trait_impl_lifetime_params_count(tcx, impl_did) != 1 {
243 return Err(tcx
244 .dcx()
245 .emit_err(diagnostics::CoerceSharedNotSingleLifetimeParam { span, trait_name }));
246 }
247
248 {
match (&trait_ref.def_id, &coerce_shared_trait) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(trait_ref.def_id, coerce_shared_trait);
249 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
250 let param_env = tcx.param_env(impl_did);
251 let (source, target) = ocx
252 .deeply_normalize(
253 &traits::ObligationCause::misc(span, impl_did),
254 param_env,
255 Unnormalized::new_wip((source, trait_ref.args.type_at(1))),
256 )
257 .map_err(|errors| infcx.err_ctxt().report_fulfillment_errors(errors))?;
258 let errors = ocx.evaluate_obligations_error_on_ambiguity();
259 if let TraitErrors::HasErrors(errors) = errors {
260 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
261 }
262
263 if !!source.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !source.has_escaping_bound_vars()")
};assert!(!source.has_escaping_bound_vars());
264
265 match (source.kind(), target.kind()) {
266 (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
267 if def_a.is_struct() && def_b.is_struct() =>
268 {
269 let a_lifetime = single_region_arg(args_a);
270 let b_lifetime = single_region_arg(args_b);
271
272 if a_lifetime.is_none() || b_lifetime.is_none() {
273 return Err(tcx.dcx().emit_err(diagnostics::CoerceSharedMulti {
274 span: diagnostic_context.trait_span,
275 trait_name,
276 }));
277 }
278
279 if a_lifetime != b_lifetime {
280 return Err(tcx.dcx().emit_err(diagnostics::CoerceSharedLifetimeMismatch {
281 span: diagnostic_context.trait_span,
282 source_lifetime_span: diagnostic_context.source_lifetime_span,
283 target_lifetime_span: diagnostic_context.target_lifetime_span,
284 trait_name,
285 }));
286 }
287
288 validate_reborrow_field_access(
289 tcx,
290 impl_did,
291 def_a,
292 trait_name,
293 diagnostic_context,
294 CoerceSharedTypeRole::Source,
295 )?;
296 validate_reborrow_field_access(
297 tcx,
298 impl_did,
299 def_b,
300 trait_name,
301 diagnostic_context,
302 CoerceSharedTypeRole::Target,
303 )?;
304
305 validate_coerce_shared_fields(
306 &infcx,
307 impl_did,
308 param_env,
309 coerce_shared_trait,
310 trait_name,
311 span,
312 diagnostic_context,
313 def_a,
314 args_a,
315 def_b,
316 args_b,
317 )
318 }
319
320 _ => {
321 Err(tcx.dcx().emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name }))
323 }
324 }
325}
326
327#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for CoerceSharedFieldPair<'tcx>
{
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for CoerceSharedFieldPair<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<ReborrowDataField<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ReborrowDataField<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for CoerceSharedFieldPair<'tcx> { }Copy)]
328struct CoerceSharedFieldPair<'tcx> {
329 source: ReborrowDataField<'tcx>,
330 target: ReborrowDataField<'tcx>,
331}
332
333struct CoerceSharedFields<'tcx> {
334 pairs: Vec<CoerceSharedFieldPair<'tcx>>,
335 unpaired_sources: Vec<ReborrowDataField<'tcx>>,
336}
337
338#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for
CoerceSharedFieldPairError<'tcx> {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for CoerceSharedFieldPairError<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<ReborrowDataField<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for CoerceSharedFieldPairError<'tcx> { }Copy)]
339enum CoerceSharedFieldPairError<'tcx> {
340 FieldStyleMismatch,
341 MissingSourceField { target: ReborrowDataField<'tcx> },
342}
343
344fn single_region_arg<'tcx>(args: ty::GenericArgsRef<'tcx>) -> Option<ty::Region<'tcx>> {
345 let mut lifetimes = args.iter().filter_map(|arg| arg.as_region());
346 let lifetime = lifetimes.next()?;
347 lifetimes.next().is_none().then_some(lifetime)
348}
349
350fn collect_coerce_shared_field_pairs<'tcx>(
354 tcx: TyCtxt<'tcx>,
355 source_def: ty::AdtDef<'tcx>,
356 source_args: ty::GenericArgsRef<'tcx>,
357 target_def: ty::AdtDef<'tcx>,
358 target_args: ty::GenericArgsRef<'tcx>,
359) -> Result<CoerceSharedFields<'tcx>, CoerceSharedFieldPairError<'tcx>> {
360 let source_variant = source_def.non_enum_variant();
361 let target_variant = target_def.non_enum_variant();
362 if source_variant.ctor_kind() != target_variant.ctor_kind() {
363 return Err(CoerceSharedFieldPairError::FieldStyleMismatch);
364 }
365
366 let source_fields = collect_reborrow_data_fields(tcx, source_def, source_args);
367 let target_fields = collect_reborrow_data_fields(tcx, target_def, target_args);
368
369 let mut pairs = Vec::with_capacity(target_fields.len());
370
371 for target in &target_fields {
372 let source = source_fields
373 .iter()
374 .find(|source| tcx.hygienic_eq(target.ident, source.ident, source_variant.def_id))
375 .ok_or(CoerceSharedFieldPairError::MissingSourceField { target: *target })?;
376
377 pairs.push(CoerceSharedFieldPair { source: *source, target: *target });
378 }
379
380 let unpaired_sources = source_fields
381 .into_iter()
382 .filter(|source| {
383 !target_fields
384 .iter()
385 .any(|target| tcx.hygienic_eq(target.ident, source.ident, source_variant.def_id))
386 })
387 .collect();
388
389 Ok(CoerceSharedFields { pairs, unpaired_sources })
390}
391
392fn validate_reborrow_field_access(
393 tcx: TyCtxt<'_>,
394 impl_did: LocalDefId,
395 def: ty::AdtDef<'_>,
396 trait_name: &'static str,
397 diagnostic_context: CoerceSharedDiagnosticContext,
398 role: CoerceSharedTypeRole,
399) -> Result<(), ErrorGuaranteed> {
400 let module = tcx.parent_module_from_def_id(impl_did);
401 let variant = def.non_enum_variant();
402
403 if variant.field_list_has_applicable_non_exhaustive()
404 || variant.fields.iter().any(|f| !f.vis.is_accessible_from(module, tcx))
405 {
406 Err(tcx.dcx().emit_err(diagnostics::CoerceSharedInaccessibleField {
407 span: diagnostic_context.impl_span,
408 type_span: role.type_span(diagnostic_context),
409 trait_name,
410 role: role.as_str(),
411 type_name: tcx.item_name(def.did()),
412 }))
413 } else {
414 Ok(())
415 }
416}
417
418fn validate_coerce_shared_fields<'tcx>(
419 infcx: &InferCtxt<'tcx>,
420 impl_did: LocalDefId,
421 param_env: ty::ParamEnv<'tcx>,
422 coerce_shared_trait: DefId,
423 trait_name: &'static str,
424 span: Span,
425 diagnostic_context: CoerceSharedDiagnosticContext,
426 source_def: ty::AdtDef<'tcx>,
427 source_args: ty::GenericArgsRef<'tcx>,
428 target_def: ty::AdtDef<'tcx>,
429 target_args: ty::GenericArgsRef<'tcx>,
430) -> Result<(), ErrorGuaranteed> {
431 let tcx = infcx.tcx;
432 let fields = match collect_coerce_shared_field_pairs(
433 tcx,
434 source_def,
435 source_args,
436 target_def,
437 target_args,
438 ) {
439 Ok(fields) => fields,
440 Err(CoerceSharedFieldPairError::FieldStyleMismatch) => {
441 return Err(tcx
442 .dcx()
443 .emit_err(diagnostics::CoerceSharedFieldStyleMismatch { span, trait_name }));
444 }
445 Err(CoerceSharedFieldPairError::MissingSourceField { target }) => {
446 return Err(tcx.dcx().emit_err(diagnostics::CoerceSharedMissingField {
447 span: target.span,
448 source_ty_span: diagnostic_context.source_ty_span,
449 trait_name,
450 source_ty_name: tcx.item_name(source_def.did()),
451 field_name: target.name,
452 }));
453 }
454 };
455
456 for field_pair in fields.pairs {
457 validate_coerce_shared_field(
458 infcx,
459 impl_did,
460 param_env,
461 coerce_shared_trait,
462 trait_name,
463 span,
464 diagnostic_context,
465 field_pair.source,
466 field_pair.target,
467 )?;
468 }
469
470 let reborrow_trait = tcx.require_lang_item(LangItem::Reborrow, span);
471 for source in fields.unpaired_sources {
472 validate_coerce_shared_unpaired_source_field(
473 infcx,
474 impl_did,
475 param_env,
476 reborrow_trait,
477 trait_name,
478 diagnostic_context,
479 source,
480 )?;
481 }
482
483 validate_coerce_shared_fields_are_memcpy_compatible(
487 infcx,
488 impl_did,
489 param_env,
490 coerce_shared_trait,
491 trait_name,
492 span,
493 diagnostic_context,
494 source_def,
495 source_args,
496 target_def,
497 target_args,
498 )?;
499
500 Ok(())
501}
502
503fn validate_coerce_shared_fields_are_memcpy_compatible<'tcx>(
504 infcx: &InferCtxt<'tcx>,
505 impl_did: LocalDefId,
506 param_env: ty::ParamEnv<'tcx>,
507 coerce_shared_trait: DefId,
508 trait_name: &'static str,
509 span: Span,
510 diagnostic_context: CoerceSharedDiagnosticContext,
511 source_def: ty::AdtDef<'tcx>,
512 source_args: ty::GenericArgsRef<'tcx>,
513 target_def: ty::AdtDef<'tcx>,
514 target_args: ty::GenericArgsRef<'tcx>,
515) -> Result<(), ErrorGuaranteed> {
516 let tcx = infcx.tcx;
517 let source_non_zst_fields =
518 non_zst_reborrow_data_fields(infcx, param_env, source_def, source_args);
519 let target_non_zst_fields =
520 non_zst_reborrow_data_fields(infcx, param_env, target_def, target_args);
521
522 match (&source_non_zst_fields[..], &target_non_zst_fields[..]) {
523 ([], []) => Ok(()),
524 ([source], [target]) => {
525 if field_tys_satisfy_relation_after_normalization_and_resolution(
526 tcx,
527 impl_did,
528 param_env,
529 source.ty,
530 target.ty,
531 source.span,
532 FieldRelation::Equal,
533 ) {
534 return Ok(());
535 }
536
537 if #[allow(non_exhaustive_omitted_patterns)] match (source.ty.kind(),
target.ty.kind()) {
(&ty::Ref(_, _, ty::Mutability::Mut), &ty::Ref(_, _, ty::Mutability::Not))
| (&ty::Alias(..), _) | (_, &ty::Alias(..)) => true,
_ => false,
}matches!(
538 (source.ty.kind(), target.ty.kind()),
539 (&ty::Ref(_, _, ty::Mutability::Mut), &ty::Ref(_, _, ty::Mutability::Not))
540 | (&ty::Alias(..), _)
541 | (_, &ty::Alias(..))
542 ) && field_tys_satisfy_relation_after_normalization_and_resolution(
543 tcx,
544 impl_did,
545 param_env,
546 source.ty,
547 target.ty,
548 source.span,
549 FieldRelation::MutRefToSharedRef,
550 ) {
551 return Ok(());
552 }
553
554 validate_field_tys_satisfy_coerce_shared_relation(
555 infcx,
556 impl_did,
557 param_env,
558 coerce_shared_trait,
559 trait_name,
560 span,
561 diagnostic_context,
562 *source,
563 *target,
564 )
565 }
566 _ => Err(tcx.dcx().emit_err(diagnostics::CoerceSharedMultipleNonZstFields {
567 span: diagnostic_context.impl_span,
568 source_ty_span: diagnostic_context.source_ty_span,
569 target_ty_span: diagnostic_context.target_ty_span,
570 trait_name,
571 source_count: source_non_zst_fields.len(),
572 target_count: target_non_zst_fields.len(),
573 })),
574 }
575}
576
577fn non_zst_reborrow_data_fields<'tcx>(
578 infcx: &InferCtxt<'tcx>,
579 param_env: ty::ParamEnv<'tcx>,
580 def: ty::AdtDef<'tcx>,
581 args: ty::GenericArgsRef<'tcx>,
582) -> Vec<ReborrowDataField<'tcx>> {
583 let tcx = infcx.tcx;
584 collect_reborrow_data_fields(tcx, def, args)
585 .into_iter()
586 .filter(|field| {
587 !#[allow(non_exhaustive_omitted_patterns)] match tcx.layout_of(infcx.typing_env(param_env).as_query_input(field.ty))
{
Ok(layout) if layout.is_zst() => true,
_ => false,
}matches!(
588 tcx.layout_of(infcx.typing_env(param_env).as_query_input(field.ty)),
589 Ok(layout) if layout.is_zst()
590 )
591 })
592 .collect()
593}
594
595fn validate_coerce_shared_field<'tcx>(
596 infcx: &InferCtxt<'tcx>,
597 impl_did: LocalDefId,
598 param_env: ty::ParamEnv<'tcx>,
599 coerce_shared_trait: DefId,
600 trait_name: &'static str,
601 span: Span,
602 diagnostic_context: CoerceSharedDiagnosticContext,
603 source: ReborrowDataField<'tcx>,
604 target: ReborrowDataField<'tcx>,
605) -> Result<(), ErrorGuaranteed> {
606 let tcx = infcx.tcx;
607 if #[allow(non_exhaustive_omitted_patterns)] match (source.ty.kind(),
target.ty.kind()) {
(&ty::Ref(_, _, ty::Mutability::Mut), &ty::Ref(_, _, ty::Mutability::Not))
| (&ty::Alias(..), _) | (_, &ty::Alias(..)) => true,
_ => false,
}matches!(
608 (source.ty.kind(), target.ty.kind()),
609 (&ty::Ref(_, _, ty::Mutability::Mut), &ty::Ref(_, _, ty::Mutability::Not))
610 | (&ty::Alias(..), _)
611 | (_, &ty::Alias(..))
612 ) && field_tys_satisfy_relation_after_normalization_and_resolution(
613 tcx,
614 impl_did,
615 param_env,
616 source.ty,
617 target.ty,
618 source.span,
619 FieldRelation::MutRefToSharedRef,
620 ) {
621 return Ok(());
622 }
623
624 if field_tys_satisfy_relation_after_normalization_and_resolution(
625 tcx,
626 impl_did,
627 param_env,
628 source.ty,
629 target.ty,
630 source.span,
631 FieldRelation::Equal,
632 ) {
633 return assert_field_type_is_copy(tcx, infcx, impl_did, param_env, source.ty, source.span);
634 }
635
636 validate_field_tys_satisfy_coerce_shared_relation(
637 infcx,
638 impl_did,
639 param_env,
640 coerce_shared_trait,
641 trait_name,
642 span,
643 diagnostic_context,
644 source,
645 target,
646 )
647}
648
649fn validate_coerce_shared_unpaired_source_field<'tcx>(
650 infcx: &InferCtxt<'tcx>,
651 impl_did: LocalDefId,
652 param_env: ty::ParamEnv<'tcx>,
653 reborrow_trait: DefId,
654 trait_name: &'static str,
655 diagnostic_context: CoerceSharedDiagnosticContext,
656 mut source: ReborrowDataField<'tcx>,
657) -> Result<(), ErrorGuaranteed> {
658 let tcx = infcx.tcx;
659 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
660 source.ty = ocx
661 .deeply_normalize(
662 &traits::ObligationCause::misc(source.span, impl_did),
663 param_env,
664 Unnormalized::new_wip(source.ty),
665 )
666 .map_err(|errors| infcx.err_ctxt().report_fulfillment_errors(errors))?;
667
668 if field_type_is_reborrow(
669 tcx,
670 infcx,
671 reborrow_trait,
672 impl_did,
673 param_env,
674 source.ty,
675 source.span,
676 ) || field_type_is_copy(tcx, infcx, impl_did, param_env, source.ty, source.span)
677 {
678 return Ok(());
679 }
680
681 Err(tcx.dcx().emit_err(diagnostics::CoerceSharedOmittedSourceFieldNotCopyOrReborrow {
682 span: source.span,
683 impl_span: diagnostic_context.impl_span,
684 trait_name,
685 field_name: source.name,
686 field_ty: source.ty,
687 }))
688}
689
690fn validate_field_tys_satisfy_coerce_shared_relation<'tcx>(
691 infcx: &InferCtxt<'tcx>,
692 impl_did: LocalDefId,
693 param_env: ty::ParamEnv<'tcx>,
694 coerce_shared_trait: DefId,
695 trait_name: &'static str,
696 span: Span,
697 diagnostic_context: CoerceSharedDiagnosticContext,
698 source: ReborrowDataField<'tcx>,
699 target: ReborrowDataField<'tcx>,
700) -> Result<(), ErrorGuaranteed> {
701 let tcx = infcx.tcx;
702 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
703 let cause = traits::ObligationCause::misc(span, impl_did);
704 ocx.register_obligation(Obligation::new(
705 tcx,
706 cause,
707 param_env,
708 ty::TraitRef::new(tcx, coerce_shared_trait, [source.ty, target.ty]),
709 ));
710 let errors = ocx.evaluate_obligations_error_on_ambiguity();
711
712 if errors.has_errors() {
713 return Err(emit_coerce_shared_field_mismatch(
714 tcx,
715 trait_name,
716 diagnostic_context,
717 source,
718 target,
719 ));
720 }
721
722 ocx.resolve_regions_and_report_errors(impl_did, param_env, [])
723}
724
725fn emit_coerce_shared_field_mismatch<'tcx>(
726 tcx: TyCtxt<'tcx>,
727 trait_name: &'static str,
728 diagnostic_context: CoerceSharedDiagnosticContext,
729 source: ReborrowDataField<'tcx>,
730 target: ReborrowDataField<'tcx>,
731) -> ErrorGuaranteed {
732 tcx.dcx().emit_err(diagnostics::CoerceSharedFieldMismatch {
733 span: target.span,
734 source_span: source.span,
735 impl_span: diagnostic_context.impl_span,
736 source_name: source.name,
737 source_ty: source.ty,
738 target_name: target.name,
739 target_ty: target.ty,
740 trait_name,
741 })
742}
743
744enum FieldRelation {
745 Equal,
746 MutRefToSharedRef,
747}
748
749fn field_tys_satisfy_relation_after_normalization_and_resolution<'tcx>(
757 tcx: TyCtxt<'tcx>,
758 impl_did: LocalDefId,
759 param_env: ty::ParamEnv<'tcx>,
760 source_ty: Ty<'tcx>,
761 target_ty: Ty<'tcx>,
762 span: Span,
763 relation: FieldRelation,
764) -> bool {
765 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
766 let cause = traits::ObligationCause::misc(span, impl_did);
767 let ocx = ObligationCtxt::new(&infcx);
768
769 let Ok((source_ty, target_ty)) =
770 ocx.deeply_normalize(&cause, param_env, Unnormalized::new_wip((source_ty, target_ty)))
771 else {
772 return false;
773 };
774
775 if ocx.evaluate_obligations_error_on_ambiguity().has_errors() {
776 return false;
777 }
778
779 match relation {
780 FieldRelation::Equal => {
781 if infcx
782 .at(&cause, param_env)
783 .relate(DefineOpaqueTypes::Yes, source_ty, ty::Variance::Invariant, target_ty)
784 .is_err()
785 {
786 return false;
787 }
788 }
789 FieldRelation::MutRefToSharedRef => {
790 let (
791 &ty::Ref(source_region, source_referent_ty, ty::Mutability::Mut),
792 &ty::Ref(target_region, target_referent_ty, ty::Mutability::Not),
793 ) = (source_ty.kind(), target_ty.kind())
794 else {
795 return false;
796 };
797 if source_region != target_region {
798 return false;
799 }
800 if ocx.sup(&cause, param_env, target_referent_ty, source_referent_ty).is_err() {
801 return false;
802 }
803 }
804 };
805
806 ocx.evaluate_obligations_error_on_ambiguity().no_errors()
807 && ocx.resolve_regions(impl_did, param_env, []).is_empty()
808}