1 //! Logic and data structures related to impl specialization, explained in
2 //! greater detail below.
3 //!
4 //! At the moment, this implementation support only the simple "chain" rule:
5 //! If any two impls overlap, one must be a strict subset of the other.
6 //!
7 //! See the [rustc dev guide] for a bit more detail on how specialization
8 //! fits together with the rest of the trait machinery.
9 //!
10 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
11
12 pub mod specialization_graph;
13 use rustc_infer::infer::DefineOpaqueTypes;
14 use specialization_graph::GraphExt;
15
16 use crate::errors::NegativePositiveConflict;
17 use crate::infer::{InferCtxt, InferOk, TyCtxtInferExt};
18 use crate::traits::select::IntercrateAmbiguityCause;
19 use crate::traits::{
20 self, coherence, FutureCompatOverlapErrorKind, ObligationCause, ObligationCtxt,
21 };
22 use rustc_data_structures::fx::FxIndexSet;
23 use rustc_errors::{error_code, DelayDm, Diagnostic};
24 use rustc_hir::def_id::{DefId, LocalDefId};
25 use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt, TypeVisitableExt};
26 use rustc_middle::ty::{InternalSubsts, SubstsRef};
27 use rustc_session::lint::builtin::COHERENCE_LEAK_CHECK;
28 use rustc_session::lint::builtin::ORDER_DEPENDENT_TRAIT_OBJECTS;
29 use rustc_span::{Span, DUMMY_SP};
30
31 use super::util;
32 use super::SelectionContext;
33
34 /// Information pertinent to an overlapping impl error.
35 #[derive(Debug)]
36 pub struct OverlapError<'tcx> {
37 pub with_impl: DefId,
38 pub trait_ref: ty::TraitRef<'tcx>,
39 pub self_ty: Option<Ty<'tcx>>,
40 pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause>,
41 pub involves_placeholder: bool,
42 }
43
44 /// Given a subst for the requested impl, translate it to a subst
45 /// appropriate for the actual item definition (whether it be in that impl,
46 /// a parent impl, or the trait).
47 ///
48 /// When we have selected one impl, but are actually using item definitions from
49 /// a parent impl providing a default, we need a way to translate between the
50 /// type parameters of the two impls. Here the `source_impl` is the one we've
51 /// selected, and `source_substs` is a substitution of its generics.
52 /// And `target_node` is the impl/trait we're actually going to get the
53 /// definition from. The resulting substitution will map from `target_node`'s
54 /// generics to `source_impl`'s generics as instantiated by `source_subst`.
55 ///
56 /// For example, consider the following scenario:
57 ///
58 /// ```ignore (illustrative)
59 /// trait Foo { ... }
60 /// impl<T, U> Foo for (T, U) { ... } // target impl
61 /// impl<V> Foo for (V, V) { ... } // source impl
62 /// ```
63 ///
64 /// Suppose we have selected "source impl" with `V` instantiated with `u32`.
65 /// This function will produce a substitution with `T` and `U` both mapping to `u32`.
66 ///
67 /// where-clauses add some trickiness here, because they can be used to "define"
68 /// an argument indirectly:
69 ///
70 /// ```ignore (illustrative)
71 /// impl<'a, I, T: 'a> Iterator for Cloned<I>
72 /// where I: Iterator<Item = &'a T>, T: Clone
73 /// ```
74 ///
75 /// In a case like this, the substitution for `T` is determined indirectly,
76 /// through associated type projection. We deal with such cases by using
77 /// *fulfillment* to relate the two impls, requiring that all projections are
78 /// resolved.
translate_substs<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, source_impl: DefId, source_substs: SubstsRef<'tcx>, target_node: specialization_graph::Node, ) -> SubstsRef<'tcx>79 pub fn translate_substs<'tcx>(
80 infcx: &InferCtxt<'tcx>,
81 param_env: ty::ParamEnv<'tcx>,
82 source_impl: DefId,
83 source_substs: SubstsRef<'tcx>,
84 target_node: specialization_graph::Node,
85 ) -> SubstsRef<'tcx> {
86 translate_substs_with_cause(
87 infcx,
88 param_env,
89 source_impl,
90 source_substs,
91 target_node,
92 |_, _| ObligationCause::dummy(),
93 )
94 }
95
96 /// Like [translate_substs], but obligations from the parent implementation
97 /// are registered with the provided `ObligationCause`.
98 ///
99 /// This is for reporting *region* errors from those bounds. Type errors should
100 /// not happen because the specialization graph already checks for those, and
101 /// will result in an ICE.
translate_substs_with_cause<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, source_impl: DefId, source_substs: SubstsRef<'tcx>, target_node: specialization_graph::Node, cause: impl Fn(usize, Span) -> ObligationCause<'tcx>, ) -> SubstsRef<'tcx>102 pub fn translate_substs_with_cause<'tcx>(
103 infcx: &InferCtxt<'tcx>,
104 param_env: ty::ParamEnv<'tcx>,
105 source_impl: DefId,
106 source_substs: SubstsRef<'tcx>,
107 target_node: specialization_graph::Node,
108 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
109 ) -> SubstsRef<'tcx> {
110 debug!(
111 "translate_substs({:?}, {:?}, {:?}, {:?})",
112 param_env, source_impl, source_substs, target_node
113 );
114 let source_trait_ref =
115 infcx.tcx.impl_trait_ref(source_impl).unwrap().subst(infcx.tcx, &source_substs);
116
117 // translate the Self and Param parts of the substitution, since those
118 // vary across impls
119 let target_substs = match target_node {
120 specialization_graph::Node::Impl(target_impl) => {
121 // no need to translate if we're targeting the impl we started with
122 if source_impl == target_impl {
123 return source_substs;
124 }
125
126 fulfill_implication(infcx, param_env, source_trait_ref, source_impl, target_impl, cause)
127 .unwrap_or_else(|()| {
128 bug!(
129 "When translating substitutions from {source_impl:?} to {target_impl:?}, \
130 the expected specialization failed to hold"
131 )
132 })
133 }
134 specialization_graph::Node::Trait(..) => source_trait_ref.substs,
135 };
136
137 // directly inherent the method generics, since those do not vary across impls
138 source_substs.rebase_onto(infcx.tcx, source_impl, target_substs)
139 }
140
141 /// Is `impl1` a specialization of `impl2`?
142 ///
143 /// Specialization is determined by the sets of types to which the impls apply;
144 /// `impl1` specializes `impl2` if it applies to a subset of the types `impl2` applies
145 /// to.
146 #[instrument(skip(tcx), level = "debug")]
specializes(tcx: TyCtxt<'_>, (impl1_def_id, impl2_def_id): (DefId, DefId)) -> bool147 pub(super) fn specializes(tcx: TyCtxt<'_>, (impl1_def_id, impl2_def_id): (DefId, DefId)) -> bool {
148 // The feature gate should prevent introducing new specializations, but not
149 // taking advantage of upstream ones.
150 let features = tcx.features();
151 let specialization_enabled = features.specialization || features.min_specialization;
152 if !specialization_enabled && (impl1_def_id.is_local() || impl2_def_id.is_local()) {
153 return false;
154 }
155
156 // We determine whether there's a subset relationship by:
157 //
158 // - replacing bound vars with placeholders in impl1,
159 // - assuming the where clauses for impl1,
160 // - instantiating impl2 with fresh inference variables,
161 // - unifying,
162 // - attempting to prove the where clauses for impl2
163 //
164 // The last three steps are encapsulated in `fulfill_implication`.
165 //
166 // See RFC 1210 for more details and justification.
167
168 // Currently we do not allow e.g., a negative impl to specialize a positive one
169 if tcx.impl_polarity(impl1_def_id) != tcx.impl_polarity(impl2_def_id) {
170 return false;
171 }
172
173 // create a parameter environment corresponding to a (placeholder) instantiation of impl1
174 let penv = tcx.param_env(impl1_def_id);
175 let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id).unwrap().subst_identity();
176
177 // Create an infcx, taking the predicates of impl1 as assumptions:
178 let infcx = tcx.infer_ctxt().build();
179
180 // Attempt to prove that impl2 applies, given all of the above.
181 fulfill_implication(&infcx, penv, impl1_trait_ref, impl1_def_id, impl2_def_id, |_, _| {
182 ObligationCause::dummy()
183 })
184 .is_ok()
185 }
186
187 /// Attempt to fulfill all obligations of `target_impl` after unification with
188 /// `source_trait_ref`. If successful, returns a substitution for *all* the
189 /// generics of `target_impl`, including both those needed to unify with
190 /// `source_trait_ref` and those whose identity is determined via a where
191 /// clause in the impl.
fulfill_implication<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, source_trait_ref: ty::TraitRef<'tcx>, source_impl: DefId, target_impl: DefId, error_cause: impl Fn(usize, Span) -> ObligationCause<'tcx>, ) -> Result<SubstsRef<'tcx>, ()>192 fn fulfill_implication<'tcx>(
193 infcx: &InferCtxt<'tcx>,
194 param_env: ty::ParamEnv<'tcx>,
195 source_trait_ref: ty::TraitRef<'tcx>,
196 source_impl: DefId,
197 target_impl: DefId,
198 error_cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
199 ) -> Result<SubstsRef<'tcx>, ()> {
200 debug!(
201 "fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
202 param_env, source_trait_ref, target_impl
203 );
204
205 let source_trait_ref = match traits::fully_normalize(
206 &infcx,
207 ObligationCause::dummy(),
208 param_env,
209 source_trait_ref,
210 ) {
211 Ok(source_trait_ref) => source_trait_ref,
212 Err(_errors) => {
213 infcx.tcx.sess.delay_span_bug(
214 infcx.tcx.def_span(source_impl),
215 format!("failed to fully normalize {source_trait_ref}"),
216 );
217 source_trait_ref
218 }
219 };
220
221 let source_trait = ImplSubject::Trait(source_trait_ref);
222
223 let selcx = &mut SelectionContext::new(&infcx);
224 let target_substs = infcx.fresh_substs_for_item(DUMMY_SP, target_impl);
225 let (target_trait, obligations) =
226 util::impl_subject_and_oblig(selcx, param_env, target_impl, target_substs, error_cause);
227
228 // do the impls unify? If not, no specialization.
229 let Ok(InferOk { obligations: more_obligations, .. }) =
230 infcx.at(&ObligationCause::dummy(), param_env).eq(DefineOpaqueTypes::No, source_trait, target_trait)
231 else {
232 debug!(
233 "fulfill_implication: {:?} does not unify with {:?}",
234 source_trait, target_trait
235 );
236 return Err(());
237 };
238
239 // Needs to be `in_snapshot` because this function is used to rebase
240 // substitutions, which may happen inside of a select within a probe.
241 let ocx = ObligationCtxt::new(infcx);
242 // attempt to prove all of the predicates for impl2 given those for impl1
243 // (which are packed up in penv)
244 ocx.register_obligations(obligations.chain(more_obligations));
245
246 let errors = ocx.select_all_or_error();
247 if !errors.is_empty() {
248 // no dice!
249 debug!(
250 "fulfill_implication: for impls on {:?} and {:?}, \
251 could not fulfill: {:?} given {:?}",
252 source_trait,
253 target_trait,
254 errors,
255 param_env.caller_bounds()
256 );
257 return Err(());
258 }
259
260 debug!("fulfill_implication: an impl for {:?} specializes {:?}", source_trait, target_trait);
261
262 // Now resolve the *substitution* we built for the target earlier, replacing
263 // the inference variables inside with whatever we got from fulfillment.
264 Ok(infcx.resolve_vars_if_possible(target_substs))
265 }
266
267 /// Query provider for `specialization_graph_of`.
specialization_graph_provider( tcx: TyCtxt<'_>, trait_id: DefId, ) -> specialization_graph::Graph268 pub(super) fn specialization_graph_provider(
269 tcx: TyCtxt<'_>,
270 trait_id: DefId,
271 ) -> specialization_graph::Graph {
272 let mut sg = specialization_graph::Graph::new();
273 let overlap_mode = specialization_graph::OverlapMode::get(tcx, trait_id);
274
275 let mut trait_impls: Vec<_> = tcx.all_impls(trait_id).collect();
276
277 // The coherence checking implementation seems to rely on impls being
278 // iterated over (roughly) in definition order, so we are sorting by
279 // negated `CrateNum` (so remote definitions are visited first) and then
280 // by a flattened version of the `DefIndex`.
281 trait_impls
282 .sort_unstable_by_key(|def_id| (-(def_id.krate.as_u32() as i64), def_id.index.index()));
283
284 for impl_def_id in trait_impls {
285 if let Some(impl_def_id) = impl_def_id.as_local() {
286 // This is where impl overlap checking happens:
287 let insert_result = sg.insert(tcx, impl_def_id.to_def_id(), overlap_mode);
288 // Report error if there was one.
289 let (overlap, used_to_be_allowed) = match insert_result {
290 Err(overlap) => (Some(overlap), None),
291 Ok(Some(overlap)) => (Some(overlap.error), Some(overlap.kind)),
292 Ok(None) => (None, None),
293 };
294
295 if let Some(overlap) = overlap {
296 report_overlap_conflict(tcx, overlap, impl_def_id, used_to_be_allowed, &mut sg);
297 }
298 } else {
299 let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
300 sg.record_impl_from_cstore(tcx, parent, impl_def_id)
301 }
302 }
303
304 sg
305 }
306
307 // This function is only used when
308 // encountering errors and inlining
309 // it negatively impacts perf.
310 #[cold]
311 #[inline(never)]
report_overlap_conflict<'tcx>( tcx: TyCtxt<'tcx>, overlap: OverlapError<'tcx>, impl_def_id: LocalDefId, used_to_be_allowed: Option<FutureCompatOverlapErrorKind>, sg: &mut specialization_graph::Graph, )312 fn report_overlap_conflict<'tcx>(
313 tcx: TyCtxt<'tcx>,
314 overlap: OverlapError<'tcx>,
315 impl_def_id: LocalDefId,
316 used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
317 sg: &mut specialization_graph::Graph,
318 ) {
319 let impl_polarity = tcx.impl_polarity(impl_def_id.to_def_id());
320 let other_polarity = tcx.impl_polarity(overlap.with_impl);
321 match (impl_polarity, other_polarity) {
322 (ty::ImplPolarity::Negative, ty::ImplPolarity::Positive) => {
323 report_negative_positive_conflict(
324 tcx,
325 &overlap,
326 impl_def_id,
327 impl_def_id.to_def_id(),
328 overlap.with_impl,
329 sg,
330 );
331 }
332
333 (ty::ImplPolarity::Positive, ty::ImplPolarity::Negative) => {
334 report_negative_positive_conflict(
335 tcx,
336 &overlap,
337 impl_def_id,
338 overlap.with_impl,
339 impl_def_id.to_def_id(),
340 sg,
341 );
342 }
343
344 _ => {
345 report_conflicting_impls(tcx, overlap, impl_def_id, used_to_be_allowed, sg);
346 }
347 }
348 }
349
report_negative_positive_conflict<'tcx>( tcx: TyCtxt<'tcx>, overlap: &OverlapError<'tcx>, local_impl_def_id: LocalDefId, negative_impl_def_id: DefId, positive_impl_def_id: DefId, sg: &mut specialization_graph::Graph, )350 fn report_negative_positive_conflict<'tcx>(
351 tcx: TyCtxt<'tcx>,
352 overlap: &OverlapError<'tcx>,
353 local_impl_def_id: LocalDefId,
354 negative_impl_def_id: DefId,
355 positive_impl_def_id: DefId,
356 sg: &mut specialization_graph::Graph,
357 ) {
358 let mut err = tcx.sess.create_err(NegativePositiveConflict {
359 impl_span: tcx.def_span(local_impl_def_id),
360 trait_desc: overlap.trait_ref,
361 self_ty: overlap.self_ty,
362 negative_impl_span: tcx.span_of_impl(negative_impl_def_id),
363 positive_impl_span: tcx.span_of_impl(positive_impl_def_id),
364 });
365 sg.has_errored = Some(err.emit());
366 }
367
report_conflicting_impls<'tcx>( tcx: TyCtxt<'tcx>, overlap: OverlapError<'tcx>, impl_def_id: LocalDefId, used_to_be_allowed: Option<FutureCompatOverlapErrorKind>, sg: &mut specialization_graph::Graph, )368 fn report_conflicting_impls<'tcx>(
369 tcx: TyCtxt<'tcx>,
370 overlap: OverlapError<'tcx>,
371 impl_def_id: LocalDefId,
372 used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
373 sg: &mut specialization_graph::Graph,
374 ) {
375 let impl_span = tcx.def_span(impl_def_id);
376
377 // Work to be done after we've built the DiagnosticBuilder. We have to define it
378 // now because the struct_lint methods don't return back the DiagnosticBuilder
379 // that's passed in.
380 fn decorate<'tcx>(
381 tcx: TyCtxt<'tcx>,
382 overlap: &OverlapError<'tcx>,
383 impl_span: Span,
384 err: &mut Diagnostic,
385 ) {
386 if (overlap.trait_ref, overlap.self_ty).references_error() {
387 err.downgrade_to_delayed_bug();
388 }
389
390 match tcx.span_of_impl(overlap.with_impl) {
391 Ok(span) => {
392 err.span_label(span, "first implementation here");
393
394 err.span_label(
395 impl_span,
396 format!(
397 "conflicting implementation{}",
398 overlap.self_ty.map_or_else(String::new, |ty| format!(" for `{}`", ty))
399 ),
400 );
401 }
402 Err(cname) => {
403 let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
404 Some(s) => {
405 format!("conflicting implementation in crate `{}`:\n- {}", cname, s)
406 }
407 None => format!("conflicting implementation in crate `{}`", cname),
408 };
409 err.note(msg);
410 }
411 }
412
413 for cause in &overlap.intercrate_ambiguity_causes {
414 cause.add_intercrate_ambiguity_hint(err);
415 }
416
417 if overlap.involves_placeholder {
418 coherence::add_placeholder_note(err);
419 }
420 }
421
422 let msg = DelayDm(|| {
423 format!(
424 "conflicting implementations of trait `{}`{}{}",
425 overlap.trait_ref.print_only_trait_path(),
426 overlap.self_ty.map_or_else(String::new, |ty| format!(" for type `{ty}`")),
427 match used_to_be_allowed {
428 Some(FutureCompatOverlapErrorKind::Issue33140) => ": (E0119)",
429 _ => "",
430 }
431 )
432 });
433
434 match used_to_be_allowed {
435 None => {
436 let reported = if overlap.with_impl.is_local()
437 || tcx.orphan_check_impl(impl_def_id).is_ok()
438 {
439 let mut err = tcx.sess.struct_span_err(impl_span, msg);
440 err.code(error_code!(E0119));
441 decorate(tcx, &overlap, impl_span, &mut err);
442 Some(err.emit())
443 } else {
444 Some(tcx.sess.delay_span_bug(impl_span, "impl should have failed the orphan check"))
445 };
446 sg.has_errored = reported;
447 }
448 Some(kind) => {
449 let lint = match kind {
450 FutureCompatOverlapErrorKind::Issue33140 => ORDER_DEPENDENT_TRAIT_OBJECTS,
451 FutureCompatOverlapErrorKind::LeakCheck => COHERENCE_LEAK_CHECK,
452 };
453 tcx.struct_span_lint_hir(
454 lint,
455 tcx.hir().local_def_id_to_hir_id(impl_def_id),
456 impl_span,
457 msg,
458 |err| {
459 decorate(tcx, &overlap, impl_span, err);
460 err
461 },
462 );
463 }
464 };
465 }
466
467 /// Recovers the "impl X for Y" signature from `impl_def_id` and returns it as a
468 /// string.
to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String>469 pub(crate) fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String> {
470 use std::fmt::Write;
471
472 let trait_ref = tcx.impl_trait_ref(impl_def_id)?.subst_identity();
473 let mut w = "impl".to_owned();
474
475 let substs = InternalSubsts::identity_for_item(tcx, impl_def_id);
476
477 // FIXME: Currently only handles ?Sized.
478 // Needs to support ?Move and ?DynSized when they are implemented.
479 let mut types_without_default_bounds = FxIndexSet::default();
480 let sized_trait = tcx.lang_items().sized_trait();
481
482 if !substs.is_empty() {
483 types_without_default_bounds.extend(substs.types());
484 w.push('<');
485 w.push_str(
486 &substs
487 .iter()
488 .map(|k| k.to_string())
489 .filter(|k| k != "'_")
490 .collect::<Vec<_>>()
491 .join(", "),
492 );
493 w.push('>');
494 }
495
496 write!(
497 w,
498 " {} for {}",
499 trait_ref.print_only_trait_path(),
500 tcx.type_of(impl_def_id).subst_identity()
501 )
502 .unwrap();
503
504 // The predicates will contain default bounds like `T: Sized`. We need to
505 // remove these bounds, and add `T: ?Sized` to any untouched type parameters.
506 let predicates = tcx.predicates_of(impl_def_id).predicates;
507 let mut pretty_predicates =
508 Vec::with_capacity(predicates.len() + types_without_default_bounds.len());
509
510 for (mut p, _) in predicates {
511 if let Some(poly_trait_ref) = p.as_trait_clause() {
512 if Some(poly_trait_ref.def_id()) == sized_trait {
513 types_without_default_bounds.remove(&poly_trait_ref.self_ty().skip_binder());
514 continue;
515 }
516
517 if ty::BoundConstness::ConstIfConst == poly_trait_ref.skip_binder().constness {
518 p = p.without_const(tcx);
519 }
520 }
521 pretty_predicates.push(p.to_string());
522 }
523
524 pretty_predicates
525 .extend(types_without_default_bounds.iter().map(|ty| format!("{}: ?Sized", ty)));
526
527 if !pretty_predicates.is_empty() {
528 write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap();
529 }
530
531 w.push(';');
532 Some(w)
533 }
534