rust/compiler/rustc_hir_analysis/src/coherence/mod.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

198 lines
6.8 KiB
Rust
Raw Normal View History

// Coherence phase
//
// The job of the coherence phase of typechecking is to ensure that
// each trait has at most one implementation for each type. This is
// done by the orphan and overlap modules. Then we build up various
// mappings. That mapping code resides here.
2023-04-10 16:04:14 +01:00
use crate::errors;
use rustc_errors::{error_code, struct_span_code_err};
2021-05-11 13:39:19 +02:00
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_middle::query::Providers;
2023-02-22 02:18:40 +00:00
use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
2020-02-11 21:19:40 +01:00
use rustc_trait_selection::traits;
mod builtin;
mod inherent_impls;
mod inherent_impls_overlap;
mod orphan;
2014-12-10 10:59:20 -05:00
mod unsafety;
fn check_impl(tcx: TyCtxt<'_>, impl_def_id: LocalDefId, trait_ref: ty::TraitRef<'_>) {
debug!(
"(checking implementation) adding impl for trait '{:?}', item '{}'",
trait_ref,
tcx.def_path_str(impl_def_id)
);
// Skip impls where one of the self type is an error type.
// This occurs with e.g., resolve failures (#30589).
if trait_ref.references_error() {
return;
}
enforce_trait_manually_implementable(tcx, impl_def_id, trait_ref.def_id);
enforce_empty_impls_for_marker_traits(tcx, impl_def_id, trait_ref.def_id);
}
fn enforce_trait_manually_implementable(
tcx: TyCtxt<'_>,
impl_def_id: LocalDefId,
trait_def_id: DefId,
) {
let impl_header_span = tcx.def_span(impl_def_id);
2022-11-12 23:37:52 +00:00
// Disallow *all* explicit impls of traits marked `#[rustc_deny_explicit_impl]`
if tcx.trait_def(trait_def_id).deny_explicit_impl {
2022-11-12 23:37:52 +00:00
let trait_name = tcx.item_name(trait_def_id);
let mut err = struct_span_code_err!(
tcx.dcx(),
impl_header_span,
E0322,
2022-11-12 23:37:52 +00:00
"explicit impls for the `{trait_name}` trait are not permitted"
);
err.span_label(impl_header_span, format!("impl of `{trait_name}` not allowed"));
2022-11-12 23:37:52 +00:00
// Maintain explicit error code for `Unsize`, since it has a useful
// explanation about using `CoerceUnsized` instead.
if Some(trait_def_id) == tcx.lang_items().unsize_trait() {
err.code(error_code!(E0328));
}
2022-11-12 23:37:52 +00:00
err.emit();
return;
}
if let ty::trait_def::TraitSpecializationKind::AlwaysApplicable =
tcx.trait_def(trait_def_id).specialization_kind
{
if !tcx.features().specialization && !tcx.features().min_specialization {
tcx.dcx().emit_err(errors::SpecializationTrait { span: impl_header_span });
return;
}
}
}
/// We allow impls of marker traits to overlap, so they can't override impls
/// as that could make it ambiguous which associated item to use.
fn enforce_empty_impls_for_marker_traits(
tcx: TyCtxt<'_>,
impl_def_id: LocalDefId,
trait_def_id: DefId,
) {
if !tcx.trait_def(trait_def_id).is_marker {
return;
}
if tcx.associated_item_def_ids(trait_def_id).is_empty() {
return;
}
struct_span_code_err!(
tcx.dcx(),
tcx.def_span(impl_def_id),
E0715,
"impls for marker traits cannot contain items"
)
.emit();
}
pub fn provide(providers: &mut Providers) {
use self::builtin::coerce_unsized_info;
use self::inherent_impls::{crate_incoherent_impls, crate_inherent_impls, inherent_impls};
use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
2021-05-09 20:53:13 +02:00
use self::orphan::orphan_check_impl;
*providers = Providers {
coherent_trait,
crate_inherent_impls,
crate_incoherent_impls,
inherent_impls,
crate_inherent_impls_overlap_check,
coerce_unsized_info,
2021-05-09 20:53:13 +02:00
orphan_check_impl,
..*providers
};
}
2019-06-21 20:05:14 +02:00
fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) {
// Trigger building the specialization graph for the trait. This will detect and report any
// overlap errors.
2020-05-01 11:32:20 +02:00
tcx.ensure().specialization_graph_of(def_id);
let impls = tcx.hir().trait_impls(def_id);
for &impl_def_id in impls {
let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity();
check_impl(tcx, impl_def_id, trait_ref);
check_object_overlap(tcx, impl_def_id, trait_ref);
2023-02-06 08:31:19 +01:00
unsafety::check_item(tcx, impl_def_id);
tcx.ensure().orphan_check_impl(impl_def_id);
}
2021-05-09 20:53:13 +02:00
builtin::check_trait(tcx, def_id);
}
/// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
fn check_object_overlap<'tcx>(
tcx: TyCtxt<'tcx>,
impl_def_id: LocalDefId,
trait_ref: ty::TraitRef<'tcx>,
) {
let trait_def_id = trait_ref.def_id;
if trait_ref.references_error() {
debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
return;
}
// check for overlap with the automatic `impl Trait for dyn Trait`
2021-09-30 19:38:50 +02:00
if let ty::Dynamic(data, ..) = trait_ref.self_ty().kind() {
// This is something like impl Trait1 for Trait2. Illegal
// if Trait1 is a supertrait of Trait2 or Trait2 is not object safe.
let component_def_ids = data.iter().flat_map(|predicate| {
match predicate.skip_binder() {
ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
2020-06-24 23:40:33 +02:00
ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
// An associated type projection necessarily comes with
// an additional `Trait` requirement.
ty::ExistentialPredicate::Projection(..) => None,
}
});
for component_def_id in component_def_ids {
if !tcx.check_is_object_safe(component_def_id) {
// Without the 'object_safe_for_dispatch' feature this is an error
// which will be reported by wfcheck. Ignore it here.
// This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
// With the feature enabled, the trait is not implemented automatically,
// so this is valid.
} else {
let mut supertrait_def_ids = traits::supertrait_def_ids(tcx, component_def_id);
if supertrait_def_ids.any(|d| d == trait_def_id) {
let span = tcx.def_span(impl_def_id);
struct_span_code_err!(
tcx.dcx(),
span,
E0371,
"the object type `{}` automatically implements the trait `{}`",
trait_ref.self_ty(),
tcx.def_path_str(trait_def_id)
2019-12-22 17:42:04 -05:00
)
Make `DiagnosticBuilder::emit` consuming. This works for most of its call sites. This is nice, because `emit` very much makes sense as a consuming operation -- indeed, `DiagnosticBuilderState` exists to ensure no diagnostic is emitted twice, but it uses runtime checks. For the small number of call sites where a consuming emit doesn't work, the commit adds `DiagnosticBuilder::emit_without_consuming`. (This will be removed in subsequent commits.) Likewise, `emit_unless` becomes consuming. And `delay_as_bug` becomes consuming, while `delay_as_bug_without_consuming` is added (which will also be removed in subsequent commits.) All this requires significant changes to `DiagnosticBuilder`'s chaining methods. Currently `DiagnosticBuilder` method chaining uses a non-consuming `&mut self -> &mut Self` style, which allows chaining to be used when the chain ends in `emit()`, like so: ``` struct_err(msg).span(span).emit(); ``` But it doesn't work when producing a `DiagnosticBuilder` value, requiring this: ``` let mut err = self.struct_err(msg); err.span(span); err ``` This style of chaining won't work with consuming `emit` though. For that, we need to use to a `self -> Self` style. That also would allow `DiagnosticBuilder` production to be chained, e.g.: ``` self.struct_err(msg).span(span) ``` However, removing the `&mut self -> &mut Self` style would require that individual modifications of a `DiagnosticBuilder` go from this: ``` err.span(span); ``` to this: ``` err = err.span(span); ``` There are *many* such places. I have a high tolerance for tedious refactorings, but even I gave up after a long time trying to convert them all. Instead, this commit has it both ways: the existing `&mut self -> Self` chaining methods are kept, and new `self -> Self` chaining methods are added, all of which have a `_mv` suffix (short for "move"). Changes to the existing `forward!` macro lets this happen with very little additional boilerplate code. I chose to add the suffix to the new chaining methods rather than the existing ones, because the number of changes required is much smaller that way. This doubled chainging is a bit clumsy, but I think it is worthwhile because it allows a *lot* of good things to subsequently happen. In this commit, there are many `mut` qualifiers removed in places where diagnostics are emitted without being modified. In subsequent commits: - chaining can be used more, making the code more concise; - more use of chaining also permits the removal of redundant diagnostic APIs like `struct_err_with_code`, which can be replaced easily with `struct_err` + `code_mv`; - `emit_without_diagnostic` can be removed, which simplifies a lot of machinery, removing the need for `DiagnosticBuilderState`.
2024-01-03 12:17:35 +11:00
.span_label_mv(
span,
format!(
"`{}` automatically implements trait `{}`",
trait_ref.self_ty(),
tcx.def_path_str(trait_def_id)
2019-12-22 17:42:04 -05:00
),
)
.emit();
}
}
}
}
}