rustc_hir_analysis/coherence/
mod.rs

1// Coherence phase
2//
3// The job of the coherence phase of typechecking is to ensure that
4// each trait has at most one implementation for each type. This is
5// done by the orphan and overlap modules. Then we build up various
6// mappings. That mapping code resides here.
7
8use rustc_errors::codes::*;
9use rustc_errors::struct_span_code_err;
10use rustc_hir::LangItem;
11use rustc_hir::def_id::{DefId, LocalDefId};
12use rustc_middle::query::Providers;
13use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt, elaborate};
14use rustc_session::parse::feature_err;
15use rustc_span::{ErrorGuaranteed, sym};
16use tracing::debug;
17
18use crate::check::always_applicable;
19use crate::errors;
20
21mod builtin;
22mod inherent_impls;
23mod inherent_impls_overlap;
24mod orphan;
25mod unsafety;
26
27fn check_impl<'tcx>(
28    tcx: TyCtxt<'tcx>,
29    impl_def_id: LocalDefId,
30    trait_ref: ty::TraitRef<'tcx>,
31    trait_def: &'tcx ty::TraitDef,
32    polarity: ty::ImplPolarity,
33) -> Result<(), ErrorGuaranteed> {
34    debug!(
35        "(checking implementation) adding impl for trait '{:?}', item '{}'",
36        trait_ref,
37        tcx.def_path_str(impl_def_id)
38    );
39
40    // Skip impls where one of the self type is an error type.
41    // This occurs with e.g., resolve failures (#30589).
42    if trait_ref.references_error() {
43        return Ok(());
44    }
45
46    enforce_trait_manually_implementable(tcx, impl_def_id, trait_ref.def_id, trait_def)
47        .and(enforce_empty_impls_for_marker_traits(tcx, impl_def_id, trait_ref.def_id, trait_def))
48        .and(always_applicable::check_negative_auto_trait_impl(
49            tcx,
50            impl_def_id,
51            trait_ref,
52            polarity,
53        ))
54}
55
56fn enforce_trait_manually_implementable(
57    tcx: TyCtxt<'_>,
58    impl_def_id: LocalDefId,
59    trait_def_id: DefId,
60    trait_def: &ty::TraitDef,
61) -> Result<(), ErrorGuaranteed> {
62    let impl_header_span = tcx.def_span(impl_def_id);
63
64    if tcx.is_lang_item(trait_def_id, LangItem::Freeze) && !tcx.features().freeze_impls() {
65        feature_err(
66            &tcx.sess,
67            sym::freeze_impls,
68            impl_header_span,
69            "explicit impls for the `Freeze` trait are not permitted",
70        )
71        .with_span_label(impl_header_span, format!("impl of `Freeze` not allowed"))
72        .emit();
73    }
74
75    // Disallow *all* explicit impls of traits marked `#[rustc_deny_explicit_impl]`
76    if trait_def.deny_explicit_impl {
77        let trait_name = tcx.item_name(trait_def_id);
78        let mut err = struct_span_code_err!(
79            tcx.dcx(),
80            impl_header_span,
81            E0322,
82            "explicit impls for the `{trait_name}` trait are not permitted"
83        );
84        err.span_label(impl_header_span, format!("impl of `{trait_name}` not allowed"));
85
86        // Maintain explicit error code for `Unsize`, since it has a useful
87        // explanation about using `CoerceUnsized` instead.
88        if tcx.is_lang_item(trait_def_id, LangItem::Unsize) {
89            err.code(E0328);
90        }
91
92        return Err(err.emit());
93    }
94
95    if let ty::trait_def::TraitSpecializationKind::AlwaysApplicable = trait_def.specialization_kind
96    {
97        if !tcx.features().specialization()
98            && !tcx.features().min_specialization()
99            && !impl_header_span.allows_unstable(sym::specialization)
100            && !impl_header_span.allows_unstable(sym::min_specialization)
101        {
102            return Err(tcx.dcx().emit_err(errors::SpecializationTrait { span: impl_header_span }));
103        }
104    }
105    Ok(())
106}
107
108/// We allow impls of marker traits to overlap, so they can't override impls
109/// as that could make it ambiguous which associated item to use.
110fn enforce_empty_impls_for_marker_traits(
111    tcx: TyCtxt<'_>,
112    impl_def_id: LocalDefId,
113    trait_def_id: DefId,
114    trait_def: &ty::TraitDef,
115) -> Result<(), ErrorGuaranteed> {
116    if !trait_def.is_marker {
117        return Ok(());
118    }
119
120    if tcx.associated_item_def_ids(trait_def_id).is_empty() {
121        return Ok(());
122    }
123
124    Err(struct_span_code_err!(
125        tcx.dcx(),
126        tcx.def_span(impl_def_id),
127        E0715,
128        "impls for marker traits cannot contain items"
129    )
130    .emit())
131}
132
133pub(crate) fn provide(providers: &mut Providers) {
134    use self::builtin::coerce_unsized_info;
135    use self::inherent_impls::{
136        crate_incoherent_impls, crate_inherent_impls, crate_inherent_impls_validity_check,
137        inherent_impls,
138    };
139    use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
140    use self::orphan::orphan_check_impl;
141
142    *providers = Providers {
143        coherent_trait,
144        crate_inherent_impls,
145        crate_incoherent_impls,
146        inherent_impls,
147        crate_inherent_impls_validity_check,
148        crate_inherent_impls_overlap_check,
149        coerce_unsized_info,
150        orphan_check_impl,
151        ..*providers
152    };
153}
154
155fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) -> Result<(), ErrorGuaranteed> {
156    // If there are no impls for the trait, then "all impls" are trivially coherent and we won't check anything
157    // anyway. Thus we bail out even before the specialization graph, avoiding the dep_graph edge.
158    let Some(impls) = tcx.all_local_trait_impls(()).get(&def_id) else { return Ok(()) };
159    // Trigger building the specialization graph for the trait. This will detect and report any
160    // overlap errors.
161    let mut res = tcx.ensure_ok().specialization_graph_of(def_id);
162
163    for &impl_def_id in impls {
164        let impl_header = tcx.impl_trait_header(impl_def_id).unwrap();
165        let trait_ref = impl_header.trait_ref.instantiate_identity();
166        let trait_def = tcx.trait_def(trait_ref.def_id);
167
168        res = res
169            .and(check_impl(tcx, impl_def_id, trait_ref, trait_def, impl_header.polarity))
170            .and(check_object_overlap(tcx, impl_def_id, trait_ref))
171            .and(unsafety::check_item(tcx, impl_def_id, impl_header, trait_def))
172            .and(tcx.ensure_ok().orphan_check_impl(impl_def_id))
173            .and(builtin::check_trait(tcx, def_id, impl_def_id, impl_header));
174    }
175
176    res
177}
178
179/// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
180fn check_object_overlap<'tcx>(
181    tcx: TyCtxt<'tcx>,
182    impl_def_id: LocalDefId,
183    trait_ref: ty::TraitRef<'tcx>,
184) -> Result<(), ErrorGuaranteed> {
185    let trait_def_id = trait_ref.def_id;
186
187    if trait_ref.references_error() {
188        debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
189        return Ok(());
190    }
191
192    // check for overlap with the automatic `impl Trait for dyn Trait`
193    if let ty::Dynamic(data, ..) = trait_ref.self_ty().kind() {
194        // This is something like `impl Trait1 for Trait2`. Illegal if
195        // Trait1 is a supertrait of Trait2 or Trait2 is not dyn compatible.
196
197        let component_def_ids = data.iter().flat_map(|predicate| {
198            match predicate.skip_binder() {
199                ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
200                ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
201                // An associated type projection necessarily comes with
202                // an additional `Trait` requirement.
203                ty::ExistentialPredicate::Projection(..) => None,
204            }
205        });
206
207        for component_def_id in component_def_ids {
208            if !tcx.is_dyn_compatible(component_def_id) {
209                // This is a WF error tested by `coherence-impl-trait-for-trait-dyn-compatible.rs`.
210            } else {
211                let mut supertrait_def_ids = elaborate::supertrait_def_ids(tcx, component_def_id);
212                if supertrait_def_ids
213                    .any(|d| d == trait_def_id && tcx.trait_def(d).implement_via_object)
214                {
215                    let span = tcx.def_span(impl_def_id);
216                    return Err(struct_span_code_err!(
217                        tcx.dcx(),
218                        span,
219                        E0371,
220                        "the object type `{}` automatically implements the trait `{}`",
221                        trait_ref.self_ty(),
222                        tcx.def_path_str(trait_def_id)
223                    )
224                    .with_span_label(
225                        span,
226                        format!(
227                            "`{}` automatically implements trait `{}`",
228                            trait_ref.self_ty(),
229                            tcx.def_path_str(trait_def_id)
230                        ),
231                    )
232                    .emit());
233                }
234            }
235        }
236    }
237    Ok(())
238}