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
133/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`].
134pub(crate) fn provide(providers: &mut Providers) {
135    use self::builtin::coerce_unsized_info;
136    use self::inherent_impls::{
137        crate_incoherent_impls, crate_inherent_impls, crate_inherent_impls_validity_check,
138        inherent_impls,
139    };
140    use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
141    use self::orphan::orphan_check_impl;
142
143    *providers = Providers {
144        coherent_trait,
145        crate_inherent_impls,
146        crate_incoherent_impls,
147        inherent_impls,
148        crate_inherent_impls_validity_check,
149        crate_inherent_impls_overlap_check,
150        coerce_unsized_info,
151        orphan_check_impl,
152        ..*providers
153    };
154}
155
156fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) -> Result<(), ErrorGuaranteed> {
157    let impls = tcx.local_trait_impls(def_id);
158    // If there are no impls for the trait, then "all impls" are trivially coherent and we won't check anything
159    // anyway. Thus we bail out even before the specialization graph, avoiding the dep_graph edge.
160    if impls.is_empty() {
161        return Ok(());
162    }
163    // Trigger building the specialization graph for the trait. This will detect and report any
164    // overlap errors.
165    let mut res = tcx.ensure_ok().specialization_graph_of(def_id);
166
167    for &impl_def_id in impls {
168        let impl_header = tcx.impl_trait_header(impl_def_id).unwrap();
169        let trait_ref = impl_header.trait_ref.instantiate_identity();
170        let trait_def = tcx.trait_def(trait_ref.def_id);
171
172        res = res
173            .and(check_impl(tcx, impl_def_id, trait_ref, trait_def, impl_header.polarity))
174            .and(check_object_overlap(tcx, impl_def_id, trait_ref))
175            .and(unsafety::check_item(tcx, impl_def_id, impl_header, trait_def))
176            .and(tcx.ensure_ok().orphan_check_impl(impl_def_id))
177            .and(builtin::check_trait(tcx, def_id, impl_def_id, impl_header));
178    }
179
180    res
181}
182
183/// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
184fn check_object_overlap<'tcx>(
185    tcx: TyCtxt<'tcx>,
186    impl_def_id: LocalDefId,
187    trait_ref: ty::TraitRef<'tcx>,
188) -> Result<(), ErrorGuaranteed> {
189    let trait_def_id = trait_ref.def_id;
190
191    if trait_ref.references_error() {
192        debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
193        return Ok(());
194    }
195
196    // check for overlap with the automatic `impl Trait for dyn Trait`
197    if let ty::Dynamic(data, ..) = trait_ref.self_ty().kind() {
198        // This is something like `impl Trait1 for Trait2`. Illegal if
199        // Trait1 is a supertrait of Trait2 or Trait2 is not dyn compatible.
200
201        let component_def_ids = data.iter().flat_map(|predicate| {
202            match predicate.skip_binder() {
203                ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
204                ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
205                // An associated type projection necessarily comes with
206                // an additional `Trait` requirement.
207                ty::ExistentialPredicate::Projection(..) => None,
208            }
209        });
210
211        for component_def_id in component_def_ids {
212            if !tcx.is_dyn_compatible(component_def_id) {
213                // This is a WF error tested by `coherence-impl-trait-for-trait-dyn-compatible.rs`.
214            } else {
215                let mut supertrait_def_ids = elaborate::supertrait_def_ids(tcx, component_def_id);
216                if supertrait_def_ids
217                    .any(|d| d == trait_def_id && tcx.trait_def(d).implement_via_object)
218                {
219                    let span = tcx.def_span(impl_def_id);
220                    return Err(struct_span_code_err!(
221                        tcx.dcx(),
222                        span,
223                        E0371,
224                        "the object type `{}` automatically implements the trait `{}`",
225                        trait_ref.self_ty(),
226                        tcx.def_path_str(trait_def_id)
227                    )
228                    .with_span_label(
229                        span,
230                        format!(
231                            "`{}` automatically implements trait `{}`",
232                            trait_ref.self_ty(),
233                            tcx.def_path_str(trait_def_id)
234                        ),
235                    )
236                    .emit());
237                }
238            }
239        }
240    }
241    Ok(())
242}