1use rustc_data_structures::fx::FxIndexSet;
5use rustc_errors::ErrorGuaranteed;
6use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
7use rustc_lint_defs::builtin::UNCOVERED_PARAM_IN_PROJECTION;
8use rustc_middle::ty::{
9 self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
10 Unnormalized,
11};
12use rustc_middle::{bug, span_bug};
13use rustc_span::def_id::{DefId, LocalDefId};
14use rustc_trait_selection::traits::{
15 self, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, UncoveredTyParams,
16};
17use tracing::{debug, instrument};
18
19use crate::diagnostics;
20
21#[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("orphan_check_impl",
"rustc_hir_analysis::coherence::orphan",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/orphan.rs"),
::tracing_core::__macro_support::Option::Some(21u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::orphan"),
::tracing_core::field::FieldSet::new(&["impl_def_id"],
::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(&impl_def_id)
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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let trait_ref =
tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip();
trait_ref.error_reported()?;
match orphan_check(tcx, impl_def_id, OrphanCheckMode::Proper) {
Ok(()) => {}
Err(err) =>
match orphan_check(tcx, impl_def_id,
OrphanCheckMode::Compat) {
Ok(()) =>
match err {
OrphanCheckErr::UncoveredTyParams(uncovered_ty_params) => {
let hir_id = tcx.local_def_id_to_hir_id(impl_def_id);
for param_def_id in uncovered_ty_params.uncovered {
let ident = tcx.item_ident(param_def_id);
tcx.emit_node_span_lint(UNCOVERED_PARAM_IN_PROJECTION,
hir_id, ident.span,
diagnostics::UncoveredTyParam {
param: ident,
local_ty: uncovered_ty_params.local_ty,
});
}
}
OrphanCheckErr::NonLocalInputType(_) => {
::rustc_middle::util::bug::bug_fmt(format_args!("orphanck: shouldn\'t\'ve gotten non-local input tys in compat mode"))
}
},
Err(err) =>
return Err(emit_orphan_check_error(tcx, trait_ref,
impl_def_id, err)),
},
}
let trait_def_id = trait_ref.def_id;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/orphan.rs:92",
"rustc_hir_analysis::coherence::orphan",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/orphan.rs"),
::tracing_core::__macro_support::Option::Some(92u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::orphan"),
::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};
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!("trait_ref={0:?} trait_def_id={1:?} trait_is_auto={2}",
trait_ref, trait_def_id, tcx.trait_is_auto(trait_def_id)) as
&dyn Value))])
});
} else { ; }
};
if tcx.trait_is_auto(trait_def_id) {
let self_ty = trait_ref.self_ty();
enum LocalImpl {
Allow,
Disallow {
problematic_kind: &'static str,
},
}
enum NonlocalImpl {
Allow,
DisallowBecauseNonlocal,
DisallowOther,
}
let (local_impl, nonlocal_impl) =
match self_ty.kind() {
ty::Adt(self_def, _) =>
(LocalImpl::Allow,
if self_def.did().is_local() {
NonlocalImpl::Allow
} else { NonlocalImpl::DisallowBecauseNonlocal }),
ty::Foreign(did) =>
(LocalImpl::Allow,
if did.is_local() {
NonlocalImpl::Allow
} else { NonlocalImpl::DisallowBecauseNonlocal }),
ty::Dynamic(..) =>
(LocalImpl::Disallow { problematic_kind: "trait object" },
NonlocalImpl::DisallowOther),
ty::Param(..) =>
(if self_ty.is_sized(tcx,
ty::TypingEnv::non_body_analysis(tcx, impl_def_id)) {
LocalImpl::Allow
} else {
LocalImpl::Disallow { problematic_kind: "generic type" }
}, NonlocalImpl::DisallowOther),
ty::Alias(ty::AliasTy { kind, .. }) => {
let problematic_kind =
match kind {
ty::Projection { .. } => "associated type",
ty::Free { .. } => "type alias",
ty::Opaque { .. } => "opaque type",
ty::Inherent { .. } => "associated type",
};
(LocalImpl::Disallow { problematic_kind },
NonlocalImpl::DisallowOther)
}
ty::Bool | ty::Pat(..) | ty::Char | ty::Int(..) |
ty::Uint(..) | ty::Float(..) | ty::Str | ty::Array(..) |
ty::Slice(..) | ty::RawPtr(..) | ty::Ref(..) | ty::FnPtr(..)
| ty::Never | ty::Tuple(..) | ty::UnsafeBinder(_) =>
(LocalImpl::Allow, NonlocalImpl::DisallowOther),
ty::FnDef(..) | ty::Closure(..) | ty::CoroutineClosure(..) |
ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::Bound(..)
| ty::Placeholder(..) | ty::Infer(..) => {
let sp = tcx.def_span(impl_def_id);
::rustc_middle::util::bug::span_bug_fmt(sp,
format_args!("weird self type for autotrait impl"))
}
ty::Error(..) => (LocalImpl::Allow, NonlocalImpl::Allow),
};
if trait_def_id.is_local() {
match local_impl {
LocalImpl::Allow => {}
LocalImpl::Disallow { problematic_kind } => {
return Err(tcx.dcx().emit_err(diagnostics::TraitsWithDefaultImpl {
span: tcx.def_span(impl_def_id),
traits: tcx.def_path_str(trait_def_id),
problematic_kind,
self_ty,
}));
}
}
} else {
match nonlocal_impl {
NonlocalImpl::Allow => {}
NonlocalImpl::DisallowBecauseNonlocal => {
return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraitsDefined {
span: tcx.def_span(impl_def_id),
traits: tcx.def_path_str(trait_def_id),
}));
}
NonlocalImpl::DisallowOther => {
return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraits {
span: tcx.def_span(impl_def_id),
traits: tcx.def_path_str(trait_def_id),
self_ty,
}));
}
}
}
}
Ok(())
}
}
}#[instrument(level = "debug", skip(tcx))]
22pub(crate) fn orphan_check_impl(
23 tcx: TyCtxt<'_>,
24 impl_def_id: LocalDefId,
25) -> Result<(), ErrorGuaranteed> {
26 let trait_ref = tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip();
27 trait_ref.error_reported()?;
28
29 match orphan_check(tcx, impl_def_id, OrphanCheckMode::Proper) {
30 Ok(()) => {}
31 Err(err) => match orphan_check(tcx, impl_def_id, OrphanCheckMode::Compat) {
32 Ok(()) => match err {
33 OrphanCheckErr::UncoveredTyParams(uncovered_ty_params) => {
34 let hir_id = tcx.local_def_id_to_hir_id(impl_def_id);
35
36 for param_def_id in uncovered_ty_params.uncovered {
37 let ident = tcx.item_ident(param_def_id);
38
39 tcx.emit_node_span_lint(
40 UNCOVERED_PARAM_IN_PROJECTION,
41 hir_id,
42 ident.span,
43 diagnostics::UncoveredTyParam {
44 param: ident,
45 local_ty: uncovered_ty_params.local_ty,
46 },
47 );
48 }
49 }
50 OrphanCheckErr::NonLocalInputType(_) => {
51 bug!("orphanck: shouldn't've gotten non-local input tys in compat mode")
52 }
53 },
54 Err(err) => return Err(emit_orphan_check_error(tcx, trait_ref, impl_def_id, err)),
55 },
56 }
57
58 let trait_def_id = trait_ref.def_id;
59
60 debug!(
93 "trait_ref={:?} trait_def_id={:?} trait_is_auto={}",
94 trait_ref,
95 trait_def_id,
96 tcx.trait_is_auto(trait_def_id)
97 );
98
99 if tcx.trait_is_auto(trait_def_id) {
100 let self_ty = trait_ref.self_ty();
101
102 enum LocalImpl {
138 Allow,
139 Disallow { problematic_kind: &'static str },
140 }
141
142 enum NonlocalImpl {
150 Allow,
151 DisallowBecauseNonlocal,
152 DisallowOther,
153 }
154
155 let (local_impl, nonlocal_impl) = match self_ty.kind() {
158 ty::Adt(self_def, _) => (
161 LocalImpl::Allow,
162 if self_def.did().is_local() {
163 NonlocalImpl::Allow
164 } else {
165 NonlocalImpl::DisallowBecauseNonlocal
166 },
167 ),
168
169 ty::Foreign(did) => (
172 LocalImpl::Allow,
173 if did.is_local() {
174 NonlocalImpl::Allow
175 } else {
176 NonlocalImpl::DisallowBecauseNonlocal
177 },
178 ),
179
180 ty::Dynamic(..) => (
182 LocalImpl::Disallow { problematic_kind: "trait object" },
183 NonlocalImpl::DisallowOther,
184 ),
185
186 ty::Param(..) => (
189 if self_ty.is_sized(tcx, ty::TypingEnv::non_body_analysis(tcx, impl_def_id)) {
190 LocalImpl::Allow
191 } else {
192 LocalImpl::Disallow { problematic_kind: "generic type" }
193 },
194 NonlocalImpl::DisallowOther,
195 ),
196
197 ty::Alias(ty::AliasTy { kind, .. }) => {
198 let problematic_kind = match kind {
199 ty::Projection { .. } => "associated type",
205 ty::Free { .. } => "type alias",
208 ty::Opaque { .. } => "opaque type",
211 ty::Inherent { .. } => "associated type",
220 };
221 (LocalImpl::Disallow { problematic_kind }, NonlocalImpl::DisallowOther)
222 }
223
224 ty::Bool
225 | ty::Pat(..)
226 | ty::Char
227 | ty::Int(..)
228 | ty::Uint(..)
229 | ty::Float(..)
230 | ty::Str
231 | ty::Array(..)
232 | ty::Slice(..)
233 | ty::RawPtr(..)
234 | ty::Ref(..)
235 | ty::FnPtr(..)
236 | ty::Never
237 | ty::Tuple(..)
238 | ty::UnsafeBinder(_) => (LocalImpl::Allow, NonlocalImpl::DisallowOther),
239
240 ty::FnDef(..)
241 | ty::Closure(..)
242 | ty::CoroutineClosure(..)
243 | ty::Coroutine(..)
244 | ty::CoroutineWitness(..)
245 | ty::Bound(..)
246 | ty::Placeholder(..)
247 | ty::Infer(..) => {
248 let sp = tcx.def_span(impl_def_id);
249 span_bug!(sp, "weird self type for autotrait impl")
250 }
251
252 ty::Error(..) => (LocalImpl::Allow, NonlocalImpl::Allow),
253 };
254
255 if trait_def_id.is_local() {
256 match local_impl {
257 LocalImpl::Allow => {}
258 LocalImpl::Disallow { problematic_kind } => {
259 return Err(tcx.dcx().emit_err(diagnostics::TraitsWithDefaultImpl {
260 span: tcx.def_span(impl_def_id),
261 traits: tcx.def_path_str(trait_def_id),
262 problematic_kind,
263 self_ty,
264 }));
265 }
266 }
267 } else {
268 match nonlocal_impl {
269 NonlocalImpl::Allow => {}
270 NonlocalImpl::DisallowBecauseNonlocal => {
271 return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraitsDefined {
272 span: tcx.def_span(impl_def_id),
273 traits: tcx.def_path_str(trait_def_id),
274 }));
275 }
276 NonlocalImpl::DisallowOther => {
277 return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraits {
278 span: tcx.def_span(impl_def_id),
279 traits: tcx.def_path_str(trait_def_id),
280 self_ty,
281 }));
282 }
283 }
284 }
285 }
286
287 Ok(())
288}
289
290x;#[instrument(level = "debug", skip(tcx), ret)]
299fn orphan_check<'tcx>(
300 tcx: TyCtxt<'tcx>,
301 impl_def_id: LocalDefId,
302 mode: OrphanCheckMode,
303) -> Result<(), OrphanCheckErr<TyCtxt<'tcx>, FxIndexSet<DefId>>> {
304 let trait_ref = tcx.impl_trait_ref(impl_def_id);
307 debug!(trait_ref = ?trait_ref.skip_binder());
308
309 if let Some(def_id) = trait_ref.skip_binder().def_id.as_local() {
311 debug!("trait {def_id:?} is local to current crate");
312 return Ok(());
313 }
314
315 let infcx = tcx.infer_ctxt().build(TypingMode::Coherence);
317 let cause = traits::ObligationCause::dummy();
318 let args = infcx.fresh_args_for_item(cause.span, impl_def_id.to_def_id());
319 let trait_ref = trait_ref.instantiate(tcx, args).skip_norm_wip();
320
321 let lazily_normalize_ty = |user_ty: Ty<'tcx>| {
322 let ty::Alias(..) = user_ty.kind() else { return Ok(user_ty) };
323
324 let ocx = traits::ObligationCtxt::new(&infcx);
325 let ty = ocx.normalize(&cause, ty::ParamEnv::empty(), Unnormalized::new_wip(user_ty));
326 let ty = infcx.resolve_vars_if_possible(ty);
327 let errors = ocx.try_evaluate_obligations();
328 if !errors.is_empty() {
329 return Ok(user_ty);
330 }
331
332 Ok::<_, !>(ty)
333 };
334
335 let result = traits::orphan_check_trait_ref(
336 &infcx,
337 trait_ref,
338 traits::InCrate::Local { mode },
339 lazily_normalize_ty,
340 )
341 .into_ok();
342
343 result.map_err(|err| match err {
345 OrphanCheckErr::UncoveredTyParams(UncoveredTyParams { uncovered, local_ty }) => {
346 let mut collector =
347 UncoveredTyParamCollector { infcx: &infcx, uncovered_params: Default::default() };
348 uncovered.visit_with(&mut collector);
349 debug_assert!(!collector.uncovered_params.is_empty());
351
352 OrphanCheckErr::UncoveredTyParams(UncoveredTyParams {
353 uncovered: collector.uncovered_params,
354 local_ty,
355 })
356 }
357 OrphanCheckErr::NonLocalInputType(tys) => {
358 let tys = infcx.probe(|_| {
359 for (arg, id_arg) in
362 std::iter::zip(args, ty::GenericArgs::identity_for_item(tcx, impl_def_id))
363 {
364 let _ = infcx.at(&cause, ty::ParamEnv::empty()).eq(
365 DefineOpaqueTypes::No,
366 arg,
367 id_arg,
368 );
369 }
370 infcx.resolve_vars_if_possible(tys)
371 });
372 OrphanCheckErr::NonLocalInputType(tys)
373 }
374 })
375}
376
377fn emit_orphan_check_error<'tcx>(
378 tcx: TyCtxt<'tcx>,
379 trait_ref: ty::TraitRef<'tcx>,
380 impl_def_id: LocalDefId,
381 err: traits::OrphanCheckErr<TyCtxt<'tcx>, FxIndexSet<DefId>>,
382) -> ErrorGuaranteed {
383 match err {
384 traits::OrphanCheckErr::NonLocalInputType(tys) => {
385 let item = tcx.hir_expect_item(impl_def_id);
386 let impl_ = item.expect_impl();
387 let of_trait = impl_.of_trait.unwrap();
388
389 let span = tcx.def_span(impl_def_id);
390 let mut diag = tcx.dcx().create_err(match trait_ref.self_ty().kind() {
391 ty::Adt(..) => diagnostics::OnlyCurrentTraits::Outside { span, note: () },
392 _ if trait_ref.self_ty().is_primitive() => {
393 diagnostics::OnlyCurrentTraits::Primitive { span, note: () }
394 }
395 _ => diagnostics::OnlyCurrentTraits::Arbitrary { span, note: () },
396 });
397
398 for &(mut ty, is_target_ty) in &tys {
399 let span = if #[allow(non_exhaustive_omitted_patterns)] match is_target_ty {
IsFirstInputType::Yes => true,
_ => false,
}matches!(is_target_ty, IsFirstInputType::Yes) {
400 impl_.self_ty.span
402 } else {
403 of_trait.trait_ref.path.span
405 };
406
407 ty = tcx.erase_and_anonymize_regions(ty);
408
409 let is_foreign =
410 !trait_ref.def_id.is_local() && #[allow(non_exhaustive_omitted_patterns)] match is_target_ty {
IsFirstInputType::No => true,
_ => false,
}matches!(is_target_ty, IsFirstInputType::No);
411
412 match *ty.kind() {
413 ty::Slice(_) => {
414 if is_foreign {
415 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span });
416 } else {
417 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName {
418 span,
419 name: "slices",
420 });
421 }
422 }
423 ty::Array(..) => {
424 if is_foreign {
425 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span });
426 } else {
427 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName {
428 span,
429 name: "arrays",
430 });
431 }
432 }
433 ty::Tuple(..) => {
434 if is_foreign {
435 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span });
436 } else {
437 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName {
438 span,
439 name: "tuples",
440 });
441 }
442 }
443 ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
444 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsOpaque { span });
445 }
446 ty::RawPtr(ptr_ty, mutbl) => {
447 if !trait_ref.self_ty().has_param() {
448 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsPointerSugg {
449 wrapper_span: impl_.self_ty.span,
450 struct_span: item.span.shrink_to_lo(),
451 mut_key: mutbl.prefix_str(),
452 ptr_ty,
453 });
454 }
455 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsPointer {
456 span,
457 pointer: ty,
458 });
459 }
460 ty::Adt(adt_def, _) => {
461 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsAdt {
462 span,
463 name: tcx.def_path_str(adt_def.did()),
464 });
465 }
466 _ => {
467 diag.subdiagnostic(diagnostics::OnlyCurrentTraitsTy { span, ty });
468 }
469 }
470 }
471
472 diag.emit()
473 }
474 traits::OrphanCheckErr::UncoveredTyParams(UncoveredTyParams { uncovered, local_ty }) => {
475 let mut guar = None;
476 for param_def_id in uncovered {
477 guar.get_or_insert(tcx.dcx().emit_err(diagnostics::UncoveredTyParam {
478 param: tcx.item_ident(param_def_id),
479 local_ty,
480 }));
481 }
482 guar.unwrap()
483 }
484 }
485}
486
487struct UncoveredTyParamCollector<'cx, 'tcx> {
488 infcx: &'cx InferCtxt<'tcx>,
489 uncovered_params: FxIndexSet<DefId>,
490}
491
492impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for UncoveredTyParamCollector<'_, 'tcx> {
493 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
494 if !ty.has_type_flags(ty::TypeFlags::HAS_TY_INFER) {
495 return;
496 }
497 let ty::Infer(ty::TyVar(vid)) = *ty.kind() else {
498 return ty.super_visit_with(self);
499 };
500 let origin = self.infcx.type_var_origin(vid);
501 if let Some(def_id) = origin.param_def_id {
502 self.uncovered_params.insert(def_id);
503 }
504 }
505
506 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
507 if ct.has_type_flags(ty::TypeFlags::HAS_TY_INFER) {
508 ct.super_visit_with(self)
509 }
510 }
511}