• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
8 use crate::errors;
9 use rustc_errors::{error_code, struct_span_err};
10 use rustc_hir::def_id::{DefId, LocalDefId};
11 use rustc_middle::query::Providers;
12 use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
13 use rustc_trait_selection::traits;
14 
15 mod builtin;
16 mod inherent_impls;
17 mod inherent_impls_overlap;
18 mod orphan;
19 mod unsafety;
20 
check_impl(tcx: TyCtxt<'_>, impl_def_id: LocalDefId, trait_ref: ty::TraitRef<'_>)21 fn check_impl(tcx: TyCtxt<'_>, impl_def_id: LocalDefId, trait_ref: ty::TraitRef<'_>) {
22     debug!(
23         "(checking implementation) adding impl for trait '{:?}', item '{}'",
24         trait_ref,
25         tcx.def_path_str(impl_def_id)
26     );
27 
28     // Skip impls where one of the self type is an error type.
29     // This occurs with e.g., resolve failures (#30589).
30     if trait_ref.references_error() {
31         return;
32     }
33 
34     enforce_trait_manually_implementable(tcx, impl_def_id, trait_ref.def_id);
35     enforce_empty_impls_for_marker_traits(tcx, impl_def_id, trait_ref.def_id);
36 }
37 
enforce_trait_manually_implementable( tcx: TyCtxt<'_>, impl_def_id: LocalDefId, trait_def_id: DefId, )38 fn enforce_trait_manually_implementable(
39     tcx: TyCtxt<'_>,
40     impl_def_id: LocalDefId,
41     trait_def_id: DefId,
42 ) {
43     let impl_header_span = tcx.def_span(impl_def_id);
44 
45     // Disallow *all* explicit impls of traits marked `#[rustc_deny_explicit_impl]`
46     if tcx.trait_def(trait_def_id).deny_explicit_impl {
47         let trait_name = tcx.item_name(trait_def_id);
48         let mut err = struct_span_err!(
49             tcx.sess,
50             impl_header_span,
51             E0322,
52             "explicit impls for the `{trait_name}` trait are not permitted"
53         );
54         err.span_label(impl_header_span, format!("impl of `{trait_name}` not allowed"));
55 
56         // Maintain explicit error code for `Unsize`, since it has a useful
57         // explanation about using `CoerceUnsized` instead.
58         if Some(trait_def_id) == tcx.lang_items().unsize_trait() {
59             err.code(error_code!(E0328));
60         }
61 
62         err.emit();
63         return;
64     }
65 
66     if let ty::trait_def::TraitSpecializationKind::AlwaysApplicable =
67         tcx.trait_def(trait_def_id).specialization_kind
68     {
69         if !tcx.features().specialization && !tcx.features().min_specialization {
70             tcx.sess.emit_err(errors::SpecializationTrait { span: impl_header_span });
71             return;
72         }
73     }
74 }
75 
76 /// We allow impls of marker traits to overlap, so they can't override impls
77 /// as that could make it ambiguous which associated item to use.
enforce_empty_impls_for_marker_traits( tcx: TyCtxt<'_>, impl_def_id: LocalDefId, trait_def_id: DefId, )78 fn enforce_empty_impls_for_marker_traits(
79     tcx: TyCtxt<'_>,
80     impl_def_id: LocalDefId,
81     trait_def_id: DefId,
82 ) {
83     if !tcx.trait_def(trait_def_id).is_marker {
84         return;
85     }
86 
87     if tcx.associated_item_def_ids(trait_def_id).is_empty() {
88         return;
89     }
90 
91     struct_span_err!(
92         tcx.sess,
93         tcx.def_span(impl_def_id),
94         E0715,
95         "impls for marker traits cannot contain items"
96     )
97     .emit();
98 }
99 
provide(providers: &mut Providers)100 pub fn provide(providers: &mut Providers) {
101     use self::builtin::coerce_unsized_info;
102     use self::inherent_impls::{crate_incoherent_impls, crate_inherent_impls, inherent_impls};
103     use self::inherent_impls_overlap::crate_inherent_impls_overlap_check;
104     use self::orphan::orphan_check_impl;
105 
106     *providers = Providers {
107         coherent_trait,
108         crate_inherent_impls,
109         crate_incoherent_impls,
110         inherent_impls,
111         crate_inherent_impls_overlap_check,
112         coerce_unsized_info,
113         orphan_check_impl,
114         ..*providers
115     };
116 }
117 
coherent_trait(tcx: TyCtxt<'_>, def_id: DefId)118 fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) {
119     // Trigger building the specialization graph for the trait. This will detect and report any
120     // overlap errors.
121     tcx.ensure().specialization_graph_of(def_id);
122 
123     let impls = tcx.hir().trait_impls(def_id);
124     for &impl_def_id in impls {
125         let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().subst_identity();
126 
127         check_impl(tcx, impl_def_id, trait_ref);
128         check_object_overlap(tcx, impl_def_id, trait_ref);
129 
130         unsafety::check_item(tcx, impl_def_id);
131         tcx.ensure().orphan_check_impl(impl_def_id);
132     }
133 
134     builtin::check_trait(tcx, def_id);
135 }
136 
137 /// Checks whether an impl overlaps with the automatic `impl Trait for dyn Trait`.
check_object_overlap<'tcx>( tcx: TyCtxt<'tcx>, impl_def_id: LocalDefId, trait_ref: ty::TraitRef<'tcx>, )138 fn check_object_overlap<'tcx>(
139     tcx: TyCtxt<'tcx>,
140     impl_def_id: LocalDefId,
141     trait_ref: ty::TraitRef<'tcx>,
142 ) {
143     let trait_def_id = trait_ref.def_id;
144 
145     if trait_ref.references_error() {
146         debug!("coherence: skipping impl {:?} with error {:?}", impl_def_id, trait_ref);
147         return;
148     }
149 
150     // check for overlap with the automatic `impl Trait for dyn Trait`
151     if let ty::Dynamic(data, ..) = trait_ref.self_ty().kind() {
152         // This is something like impl Trait1 for Trait2. Illegal
153         // if Trait1 is a supertrait of Trait2 or Trait2 is not object safe.
154 
155         let component_def_ids = data.iter().flat_map(|predicate| {
156             match predicate.skip_binder() {
157                 ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
158                 ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
159                 // An associated type projection necessarily comes with
160                 // an additional `Trait` requirement.
161                 ty::ExistentialPredicate::Projection(..) => None,
162             }
163         });
164 
165         for component_def_id in component_def_ids {
166             if !tcx.check_is_object_safe(component_def_id) {
167                 // Without the 'object_safe_for_dispatch' feature this is an error
168                 // which will be reported by wfcheck. Ignore it here.
169                 // This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
170                 // With the feature enabled, the trait is not implemented automatically,
171                 // so this is valid.
172             } else {
173                 let mut supertrait_def_ids = traits::supertrait_def_ids(tcx, component_def_id);
174                 if supertrait_def_ids.any(|d| d == trait_def_id) {
175                     let span = tcx.def_span(impl_def_id);
176                     struct_span_err!(
177                         tcx.sess,
178                         span,
179                         E0371,
180                         "the object type `{}` automatically implements the trait `{}`",
181                         trait_ref.self_ty(),
182                         tcx.def_path_str(trait_def_id)
183                     )
184                     .span_label(
185                         span,
186                         format!(
187                             "`{}` automatically implements trait `{}`",
188                             trait_ref.self_ty(),
189                             tcx.def_path_str(trait_def_id)
190                         ),
191                     )
192                     .emit();
193                 }
194             }
195         }
196     }
197 }
198