]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/mod.rs
Auto merge of #105176 - klensy:docker-smol, r=Mark-Simulacrum
[rust.git] / compiler / rustc_trait_selection / src / traits / mod.rs
1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
4
5 pub mod auto_trait;
6 mod chalk_fulfill;
7 pub mod codegen;
8 mod coherence;
9 pub mod const_evaluatable;
10 mod engine;
11 pub mod error_reporting;
12 mod fulfill;
13 pub mod misc;
14 mod object_safety;
15 pub mod outlives_bounds;
16 mod project;
17 pub mod query;
18 pub(crate) mod relationships;
19 mod select;
20 mod specialize;
21 mod structural_match;
22 mod util;
23 pub mod wf;
24
25 use crate::errors::DumpVTableEntries;
26 use crate::infer::outlives::env::OutlivesEnvironment;
27 use crate::infer::{InferCtxt, TyCtxtInferExt};
28 use crate::traits::error_reporting::TypeErrCtxtExt as _;
29 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
30 use rustc_errors::ErrorGuaranteed;
31 use rustc_hir as hir;
32 use rustc_hir::def_id::DefId;
33 use rustc_hir::lang_items::LangItem;
34 use rustc_middle::ty::fold::TypeFoldable;
35 use rustc_middle::ty::visit::TypeVisitable;
36 use rustc_middle::ty::{
37     self, DefIdTree, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeSuperVisitable, VtblEntry,
38 };
39 use rustc_middle::ty::{InternalSubsts, SubstsRef};
40 use rustc_span::{sym, Span};
41 use smallvec::SmallVec;
42
43 use std::fmt::Debug;
44 use std::ops::ControlFlow;
45
46 pub use self::FulfillmentErrorCode::*;
47 pub use self::ImplSource::*;
48 pub use self::ObligationCauseCode::*;
49 pub use self::SelectionError::*;
50
51 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
52 pub use self::coherence::{OrphanCheckErr, OverlapResult};
53 pub use self::engine::{ObligationCtxt, TraitEngineExt};
54 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
55 pub use self::object_safety::astconv_object_safety_violations;
56 pub use self::object_safety::is_vtable_safe_method;
57 pub use self::object_safety::MethodViolationCode;
58 pub use self::object_safety::ObjectSafetyViolation;
59 pub use self::project::{normalize_projection_type, NormalizeExt};
60 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
61 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
62 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
63 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
64 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
65 pub use self::structural_match::{
66     search_for_adt_const_param_violation, search_for_structural_match_violation,
67 };
68 pub use self::util::{
69     elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
70     elaborate_trait_ref, elaborate_trait_refs,
71 };
72 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
73 pub use self::util::{
74     get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
75 };
76 pub use self::util::{
77     supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
78     SupertraitDefIds, Supertraits,
79 };
80
81 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
82
83 pub use rustc_infer::traits::*;
84
85 /// Whether to skip the leak check, as part of a future compatibility warning step.
86 ///
87 /// The "default" for skip-leak-check corresponds to the current
88 /// behavior (do not skip the leak check) -- not the behavior we are
89 /// transitioning into.
90 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
91 pub enum SkipLeakCheck {
92     Yes,
93     #[default]
94     No,
95 }
96
97 impl SkipLeakCheck {
98     fn is_yes(self) -> bool {
99         self == SkipLeakCheck::Yes
100     }
101 }
102
103 /// The mode that trait queries run in.
104 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
105 pub enum TraitQueryMode {
106     /// Standard/un-canonicalized queries get accurate
107     /// spans etc. passed in and hence can do reasonable
108     /// error reporting on their own.
109     Standard,
110     /// Canonicalized queries get dummy spans and hence
111     /// must generally propagate errors to
112     /// pre-canonicalization callsites.
113     Canonical,
114 }
115
116 /// Creates predicate obligations from the generic bounds.
117 #[instrument(level = "debug", skip(cause, param_env))]
118 pub fn predicates_for_generics<'tcx>(
119     cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
120     param_env: ty::ParamEnv<'tcx>,
121     generic_bounds: ty::InstantiatedPredicates<'tcx>,
122 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
123     std::iter::zip(generic_bounds.predicates, generic_bounds.spans).enumerate().map(
124         move |(idx, (predicate, span))| Obligation {
125             cause: cause(idx, span),
126             recursion_depth: 0,
127             param_env,
128             predicate,
129         },
130     )
131 }
132
133 /// Determines whether the type `ty` is known to meet `bound` and
134 /// returns true if so. Returns false if `ty` either does not meet
135 /// `bound` or is not known to meet bound (note that this is
136 /// conservative towards *no impl*, which is the opposite of the
137 /// `evaluate` methods).
138 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
139     infcx: &InferCtxt<'tcx>,
140     param_env: ty::ParamEnv<'tcx>,
141     ty: Ty<'tcx>,
142     def_id: DefId,
143     span: Span,
144 ) -> bool {
145     let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
146     pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
147 }
148
149 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
150 fn pred_known_to_hold_modulo_regions<'tcx>(
151     infcx: &InferCtxt<'tcx>,
152     param_env: ty::ParamEnv<'tcx>,
153     pred: impl ToPredicate<'tcx, ty::Predicate<'tcx>> + TypeVisitable<'tcx>,
154     span: Span,
155 ) -> bool {
156     let has_non_region_infer = pred.has_non_region_infer();
157     let obligation = Obligation {
158         param_env,
159         // We can use a dummy node-id here because we won't pay any mind
160         // to region obligations that arise (there shouldn't really be any
161         // anyhow).
162         cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
163         recursion_depth: 0,
164         predicate: pred.to_predicate(infcx.tcx),
165     };
166
167     let result = infcx.predicate_must_hold_modulo_regions(&obligation);
168     debug!(?result);
169
170     if result && has_non_region_infer {
171         // Because of inference "guessing", selection can sometimes claim
172         // to succeed while the success requires a guess. To ensure
173         // this function's result remains infallible, we must confirm
174         // that guess. While imperfect, I believe this is sound.
175
176         // FIXME(@lcnr): this function doesn't seem right.
177         // The handling of regions in this area of the code is terrible,
178         // see issue #29149. We should be able to improve on this with
179         // NLL.
180         let errors = fully_solve_obligation(infcx, obligation);
181
182         // Note: we only assume something is `Copy` if we can
183         // *definitively* show that it implements `Copy`. Otherwise,
184         // assume it is move; linear is always ok.
185         match &errors[..] {
186             [] => true,
187             errors => {
188                 debug!(?errors);
189                 false
190             }
191         }
192     } else {
193         result
194     }
195 }
196
197 #[instrument(level = "debug", skip(tcx, elaborated_env))]
198 fn do_normalize_predicates<'tcx>(
199     tcx: TyCtxt<'tcx>,
200     cause: ObligationCause<'tcx>,
201     elaborated_env: ty::ParamEnv<'tcx>,
202     predicates: Vec<ty::Predicate<'tcx>>,
203 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
204     let span = cause.span;
205     // FIXME. We should really... do something with these region
206     // obligations. But this call just continues the older
207     // behavior (i.e., doesn't cause any new bugs), and it would
208     // take some further refactoring to actually solve them. In
209     // particular, we would have to handle implied bounds
210     // properly, and that code is currently largely confined to
211     // regionck (though I made some efforts to extract it
212     // out). -nmatsakis
213     //
214     // @arielby: In any case, these obligations are checked
215     // by wfcheck anyway, so I'm not sure we have to check
216     // them here too, and we will remove this function when
217     // we move over to lazy normalization *anyway*.
218     let infcx = tcx.infer_ctxt().ignoring_regions().build();
219     let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
220         Ok(predicates) => predicates,
221         Err(errors) => {
222             let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
223             return Err(reported);
224         }
225     };
226
227     debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
228
229     // We can use the `elaborated_env` here; the region code only
230     // cares about declarations like `'a: 'b`.
231     let outlives_env = OutlivesEnvironment::new(elaborated_env);
232
233     // FIXME: It's very weird that we ignore region obligations but apparently
234     // still need to use `resolve_regions` as we need the resolved regions in
235     // the normalized predicates.
236     let errors = infcx.resolve_regions(&outlives_env);
237     if !errors.is_empty() {
238         tcx.sess.delay_span_bug(
239             span,
240             format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
241         );
242     }
243
244     match infcx.fully_resolve(predicates) {
245         Ok(predicates) => Ok(predicates),
246         Err(fixup_err) => {
247             // If we encounter a fixup error, it means that some type
248             // variable wound up unconstrained. I actually don't know
249             // if this can happen, and I certainly don't expect it to
250             // happen often, but if it did happen it probably
251             // represents a legitimate failure due to some kind of
252             // unconstrained variable.
253             //
254             // @lcnr: Let's still ICE here for now. I want a test case
255             // for that.
256             span_bug!(
257                 span,
258                 "inference variables in normalized parameter environment: {}",
259                 fixup_err
260             );
261         }
262     }
263 }
264
265 // FIXME: this is gonna need to be removed ...
266 /// Normalizes the parameter environment, reporting errors if they occur.
267 #[instrument(level = "debug", skip(tcx))]
268 pub fn normalize_param_env_or_error<'tcx>(
269     tcx: TyCtxt<'tcx>,
270     unnormalized_env: ty::ParamEnv<'tcx>,
271     cause: ObligationCause<'tcx>,
272 ) -> ty::ParamEnv<'tcx> {
273     // I'm not wild about reporting errors here; I'd prefer to
274     // have the errors get reported at a defined place (e.g.,
275     // during typeck). Instead I have all parameter
276     // environments, in effect, going through this function
277     // and hence potentially reporting errors. This ensures of
278     // course that we never forget to normalize (the
279     // alternative seemed like it would involve a lot of
280     // manual invocations of this fn -- and then we'd have to
281     // deal with the errors at each of those sites).
282     //
283     // In any case, in practice, typeck constructs all the
284     // parameter environments once for every fn as it goes,
285     // and errors will get reported then; so outside of type inference we
286     // can be sure that no errors should occur.
287     let mut predicates: Vec<_> =
288         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
289             .map(|obligation| obligation.predicate)
290             .collect();
291
292     debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
293
294     let elaborated_env = ty::ParamEnv::new(
295         tcx.intern_predicates(&predicates),
296         unnormalized_env.reveal(),
297         unnormalized_env.constness(),
298     );
299
300     // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
301     // normalization expects its param-env to be already normalized, which means we have
302     // a circularity.
303     //
304     // The way we handle this is by normalizing the param-env inside an unnormalized version
305     // of the param-env, which means that if the param-env contains unnormalized projections,
306     // we'll have some normalization failures. This is unfortunate.
307     //
308     // Lazy normalization would basically handle this by treating just the
309     // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
310     //
311     // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
312     // types, so to make the situation less bad, we normalize all the predicates *but*
313     // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
314     // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
315     //
316     // This works fairly well because trait matching  does not actually care about param-env
317     // TypeOutlives predicates - these are normally used by regionck.
318     let outlives_predicates: Vec<_> = predicates
319         .drain_filter(|predicate| {
320             matches!(
321                 predicate.kind().skip_binder(),
322                 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
323             )
324         })
325         .collect();
326
327     debug!(
328         "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
329         predicates, outlives_predicates
330     );
331     let Ok(non_outlives_predicates) = do_normalize_predicates(
332         tcx,
333         cause.clone(),
334         elaborated_env,
335         predicates,
336     ) else {
337         // An unnormalized env is better than nothing.
338         debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
339         return elaborated_env;
340     };
341
342     debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
343
344     // Not sure whether it is better to include the unnormalized TypeOutlives predicates
345     // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
346     // predicates here anyway. Keeping them here anyway because it seems safer.
347     let outlives_env: Vec<_> =
348         non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
349     let outlives_env = ty::ParamEnv::new(
350         tcx.intern_predicates(&outlives_env),
351         unnormalized_env.reveal(),
352         unnormalized_env.constness(),
353     );
354     let Ok(outlives_predicates) = do_normalize_predicates(
355         tcx,
356         cause,
357         outlives_env,
358         outlives_predicates,
359     ) else {
360         // An unnormalized env is better than nothing.
361         debug!("normalize_param_env_or_error: errored resolving outlives predicates");
362         return elaborated_env;
363     };
364     debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
365
366     let mut predicates = non_outlives_predicates;
367     predicates.extend(outlives_predicates);
368     debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
369     ty::ParamEnv::new(
370         tcx.intern_predicates(&predicates),
371         unnormalized_env.reveal(),
372         unnormalized_env.constness(),
373     )
374 }
375
376 /// Normalize a type and process all resulting obligations, returning any errors
377 #[instrument(skip_all)]
378 pub fn fully_normalize<'tcx, T>(
379     infcx: &InferCtxt<'tcx>,
380     cause: ObligationCause<'tcx>,
381     param_env: ty::ParamEnv<'tcx>,
382     value: T,
383 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
384 where
385     T: TypeFoldable<'tcx>,
386 {
387     let ocx = ObligationCtxt::new(infcx);
388     debug!(?value);
389     let normalized_value = ocx.normalize(&cause, param_env, value);
390     debug!(?normalized_value);
391     debug!("select_all_or_error start");
392     let errors = ocx.select_all_or_error();
393     if !errors.is_empty() {
394         return Err(errors);
395     }
396     debug!("select_all_or_error complete");
397     let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
398     debug!(?resolved_value);
399     Ok(resolved_value)
400 }
401
402 /// Process an obligation (and any nested obligations that come from it) to
403 /// completion, returning any errors
404 pub fn fully_solve_obligation<'tcx>(
405     infcx: &InferCtxt<'tcx>,
406     obligation: PredicateObligation<'tcx>,
407 ) -> Vec<FulfillmentError<'tcx>> {
408     fully_solve_obligations(infcx, [obligation])
409 }
410
411 /// Process a set of obligations (and any nested obligations that come from them)
412 /// to completion
413 pub fn fully_solve_obligations<'tcx>(
414     infcx: &InferCtxt<'tcx>,
415     obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
416 ) -> Vec<FulfillmentError<'tcx>> {
417     let ocx = ObligationCtxt::new(infcx);
418     ocx.register_obligations(obligations);
419     ocx.select_all_or_error()
420 }
421
422 /// Process a bound (and any nested obligations that come from it) to completion.
423 /// This is a convenience function for traits that have no generic arguments, such
424 /// as auto traits, and builtin traits like Copy or Sized.
425 pub fn fully_solve_bound<'tcx>(
426     infcx: &InferCtxt<'tcx>,
427     cause: ObligationCause<'tcx>,
428     param_env: ty::ParamEnv<'tcx>,
429     ty: Ty<'tcx>,
430     bound: DefId,
431 ) -> Vec<FulfillmentError<'tcx>> {
432     let tcx = infcx.tcx;
433     let trait_ref = ty::TraitRef { def_id: bound, substs: tcx.mk_substs_trait(ty, []) };
434     let obligation = Obligation {
435         cause,
436         recursion_depth: 0,
437         param_env,
438         predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
439     };
440
441     fully_solve_obligation(infcx, obligation)
442 }
443
444 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
445 /// returns true, then either normalize encountered an error or one of the predicates did not
446 /// hold. Used when creating vtables to check for unsatisfiable methods.
447 pub fn impossible_predicates<'tcx>(
448     tcx: TyCtxt<'tcx>,
449     predicates: Vec<ty::Predicate<'tcx>>,
450 ) -> bool {
451     debug!("impossible_predicates(predicates={:?})", predicates);
452
453     let infcx = tcx.infer_ctxt().build();
454     let param_env = ty::ParamEnv::reveal_all();
455     let ocx = ObligationCtxt::new(&infcx);
456     let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
457     for predicate in predicates {
458         let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
459         ocx.register_obligation(obligation);
460     }
461     let errors = ocx.select_all_or_error();
462
463     // Clean up after ourselves
464     let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
465
466     let result = !errors.is_empty();
467     debug!("impossible_predicates = {:?}", result);
468     result
469 }
470
471 fn subst_and_check_impossible_predicates<'tcx>(
472     tcx: TyCtxt<'tcx>,
473     key: (DefId, SubstsRef<'tcx>),
474 ) -> bool {
475     debug!("subst_and_check_impossible_predicates(key={:?})", key);
476
477     let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
478
479     // Specifically check trait fulfillment to avoid an error when trying to resolve
480     // associated items.
481     if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
482         let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
483         predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
484     }
485
486     predicates.retain(|predicate| !predicate.needs_subst());
487     let result = impossible_predicates(tcx, predicates);
488
489     debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
490     result
491 }
492
493 /// Checks whether a trait's method is impossible to call on a given impl.
494 ///
495 /// This only considers predicates that reference the impl's generics, and not
496 /// those that reference the method's generics.
497 fn is_impossible_method<'tcx>(
498     tcx: TyCtxt<'tcx>,
499     (impl_def_id, trait_item_def_id): (DefId, DefId),
500 ) -> bool {
501     struct ReferencesOnlyParentGenerics<'tcx> {
502         tcx: TyCtxt<'tcx>,
503         generics: &'tcx ty::Generics,
504         trait_item_def_id: DefId,
505     }
506     impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
507         type BreakTy = ();
508         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
509             // If this is a parameter from the trait item's own generics, then bail
510             if let ty::Param(param) = t.kind()
511                 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
512                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
513             {
514                 return ControlFlow::BREAK;
515             }
516             t.super_visit_with(self)
517         }
518         fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
519             if let ty::ReEarlyBound(param) = r.kind()
520                 && let param_def_id = self.generics.region_param(&param, self.tcx).def_id
521                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
522             {
523                 return ControlFlow::BREAK;
524             }
525             r.super_visit_with(self)
526         }
527         fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
528             if let ty::ConstKind::Param(param) = ct.kind()
529                 && let param_def_id = self.generics.const_param(&param, self.tcx).def_id
530                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
531             {
532                 return ControlFlow::BREAK;
533             }
534             ct.super_visit_with(self)
535         }
536     }
537
538     let generics = tcx.generics_of(trait_item_def_id);
539     let predicates = tcx.predicates_of(trait_item_def_id);
540     let impl_trait_ref =
541         tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
542     let param_env = tcx.param_env(impl_def_id);
543
544     let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
545     let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
546         if pred.visit_with(&mut visitor).is_continue() {
547             Some(Obligation::new(
548                 tcx,
549                 ObligationCause::dummy_with_span(*span),
550                 param_env,
551                 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
552             ))
553         } else {
554             None
555         }
556     });
557
558     let infcx = tcx.infer_ctxt().ignoring_regions().build();
559     for obligation in predicates_for_trait {
560         // Ignore overflow error, to be conservative.
561         if let Ok(result) = infcx.evaluate_obligation(&obligation)
562             && !result.may_apply()
563         {
564             return true;
565         }
566     }
567     false
568 }
569
570 #[derive(Clone, Debug)]
571 enum VtblSegment<'tcx> {
572     MetadataDSA,
573     TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
574 }
575
576 /// Prepare the segments for a vtable
577 fn prepare_vtable_segments<'tcx, T>(
578     tcx: TyCtxt<'tcx>,
579     trait_ref: ty::PolyTraitRef<'tcx>,
580     mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
581 ) -> Option<T> {
582     // The following constraints holds for the final arrangement.
583     // 1. The whole virtual table of the first direct super trait is included as the
584     //    the prefix. If this trait doesn't have any super traits, then this step
585     //    consists of the dsa metadata.
586     // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
587     //    other super traits except those already included as part of the first
588     //    direct super trait virtual table.
589     // 3. finally, the own methods of this trait.
590
591     // This has the advantage that trait upcasting to the first direct super trait on each level
592     // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
593     // while not using too much extra memory.
594
595     // For a single inheritance relationship like this,
596     //   D --> C --> B --> A
597     // The resulting vtable will consists of these segments:
598     //  DSA, A, B, C, D
599
600     // For a multiple inheritance relationship like this,
601     //   D --> C --> A
602     //           \-> B
603     // The resulting vtable will consists of these segments:
604     //  DSA, A, B, B-vptr, C, D
605
606     // For a diamond inheritance relationship like this,
607     //   D --> B --> A
608     //     \-> C -/
609     // The resulting vtable will consists of these segments:
610     //  DSA, A, B, C, C-vptr, D
611
612     // For a more complex inheritance relationship like this:
613     //   O --> G --> C --> A
614     //     \     \     \-> B
615     //     |     |-> F --> D
616     //     |           \-> E
617     //     |-> N --> J --> H
618     //           \     \-> I
619     //           |-> M --> K
620     //                 \-> L
621     // The resulting vtable will consists of these segments:
622     //  DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
623     //  H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
624     //  N, N-vptr, O
625
626     // emit dsa segment first.
627     if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
628         return Some(v);
629     }
630
631     let mut emit_vptr_on_new_entry = false;
632     let mut visited = util::PredicateSet::new(tcx);
633     let predicate = trait_ref.without_const().to_predicate(tcx);
634     let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
635         smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
636     visited.insert(predicate);
637
638     // the main traversal loop:
639     // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
640     // that each node is emitted after all its descendents have been emitted.
641     // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
642     // this is done on the fly.
643     // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
644     // stops after it finds a node that has a next-sibling node.
645     // This next-sibling node will used as the starting point of next slice.
646
647     // Example:
648     // For a diamond inheritance relationship like this,
649     //   D#1 --> B#0 --> A#0
650     //     \-> C#1 -/
651
652     // Starting point 0 stack [D]
653     // Loop run #0: Stack after diving in is [D B A], A is "childless"
654     // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
655     // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
656     // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
657     // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
658     // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
659     // Loop run #1: Stack after exiting out is []. Now the function exits.
660
661     loop {
662         // dive deeper into the stack, recording the path
663         'diving_in: loop {
664             if let Some((inner_most_trait_ref, _, _)) = stack.last() {
665                 let inner_most_trait_ref = *inner_most_trait_ref;
666                 let mut direct_super_traits_iter = tcx
667                     .super_predicates_of(inner_most_trait_ref.def_id())
668                     .predicates
669                     .into_iter()
670                     .filter_map(move |(pred, _)| {
671                         pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
672                     });
673
674                 'diving_in_skip_visited_traits: loop {
675                     if let Some(next_super_trait) = direct_super_traits_iter.next() {
676                         if visited.insert(next_super_trait.to_predicate(tcx)) {
677                             // We're throwing away potential constness of super traits here.
678                             // FIXME: handle ~const super traits
679                             let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
680                             stack.push((
681                                 next_super_trait,
682                                 emit_vptr_on_new_entry,
683                                 Some(direct_super_traits_iter),
684                             ));
685                             break 'diving_in_skip_visited_traits;
686                         } else {
687                             continue 'diving_in_skip_visited_traits;
688                         }
689                     } else {
690                         break 'diving_in;
691                     }
692                 }
693             }
694         }
695
696         // Other than the left-most path, vptr should be emitted for each trait.
697         emit_vptr_on_new_entry = true;
698
699         // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
700         'exiting_out: loop {
701             if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
702                 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
703                     trait_ref: *inner_most_trait_ref,
704                     emit_vptr: *emit_vptr,
705                 }) {
706                     return Some(v);
707                 }
708
709                 'exiting_out_skip_visited_traits: loop {
710                     if let Some(siblings) = siblings_opt {
711                         if let Some(next_inner_most_trait_ref) = siblings.next() {
712                             if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
713                                 // We're throwing away potential constness of super traits here.
714                                 // FIXME: handle ~const super traits
715                                 let next_inner_most_trait_ref =
716                                     next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
717                                 *inner_most_trait_ref = next_inner_most_trait_ref;
718                                 *emit_vptr = emit_vptr_on_new_entry;
719                                 break 'exiting_out;
720                             } else {
721                                 continue 'exiting_out_skip_visited_traits;
722                             }
723                         }
724                     }
725                     stack.pop();
726                     continue 'exiting_out;
727                 }
728             }
729             // all done
730             return None;
731         }
732     }
733 }
734
735 fn dump_vtable_entries<'tcx>(
736     tcx: TyCtxt<'tcx>,
737     sp: Span,
738     trait_ref: ty::PolyTraitRef<'tcx>,
739     entries: &[VtblEntry<'tcx>],
740 ) {
741     tcx.sess.emit_err(DumpVTableEntries {
742         span: sp,
743         trait_ref,
744         entries: format!("{:#?}", entries),
745     });
746 }
747
748 fn own_existential_vtable_entries<'tcx>(tcx: TyCtxt<'tcx>, trait_def_id: DefId) -> &'tcx [DefId] {
749     let trait_methods = tcx
750         .associated_items(trait_def_id)
751         .in_definition_order()
752         .filter(|item| item.kind == ty::AssocKind::Fn);
753     // Now list each method's DefId (for within its trait).
754     let own_entries = trait_methods.filter_map(move |trait_method| {
755         debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
756         let def_id = trait_method.def_id;
757
758         // Some methods cannot be called on an object; skip those.
759         if !is_vtable_safe_method(tcx, trait_def_id, &trait_method) {
760             debug!("own_existential_vtable_entry: not vtable safe");
761             return None;
762         }
763
764         Some(def_id)
765     });
766
767     tcx.arena.alloc_from_iter(own_entries.into_iter())
768 }
769
770 /// Given a trait `trait_ref`, iterates the vtable entries
771 /// that come from `trait_ref`, including its supertraits.
772 fn vtable_entries<'tcx>(
773     tcx: TyCtxt<'tcx>,
774     trait_ref: ty::PolyTraitRef<'tcx>,
775 ) -> &'tcx [VtblEntry<'tcx>] {
776     debug!("vtable_entries({:?})", trait_ref);
777
778     let mut entries = vec![];
779
780     let vtable_segment_callback = |segment| -> ControlFlow<()> {
781         match segment {
782             VtblSegment::MetadataDSA => {
783                 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
784             }
785             VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
786                 let existential_trait_ref = trait_ref
787                     .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
788
789                 // Lookup the shape of vtable for the trait.
790                 let own_existential_entries =
791                     tcx.own_existential_vtable_entries(existential_trait_ref.def_id());
792
793                 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
794                     debug!("vtable_entries: trait_method={:?}", def_id);
795
796                     // The method may have some early-bound lifetimes; add regions for those.
797                     let substs = trait_ref.map_bound(|trait_ref| {
798                         InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
799                             GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
800                             GenericParamDefKind::Type { .. }
801                             | GenericParamDefKind::Const { .. } => {
802                                 trait_ref.substs[param.index as usize]
803                             }
804                         })
805                     });
806
807                     // The trait type may have higher-ranked lifetimes in it;
808                     // erase them if they appear, so that we get the type
809                     // at some particular call site.
810                     let substs = tcx
811                         .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
812
813                     // It's possible that the method relies on where-clauses that
814                     // do not hold for this particular set of type parameters.
815                     // Note that this method could then never be called, so we
816                     // do not want to try and codegen it, in that case (see #23435).
817                     let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
818                     if impossible_predicates(tcx, predicates.predicates) {
819                         debug!("vtable_entries: predicates do not hold");
820                         return VtblEntry::Vacant;
821                     }
822
823                     let instance = ty::Instance::resolve_for_vtable(
824                         tcx,
825                         ty::ParamEnv::reveal_all(),
826                         def_id,
827                         substs,
828                     )
829                     .expect("resolution failed during building vtable representation");
830                     VtblEntry::Method(instance)
831                 });
832
833                 entries.extend(own_entries);
834
835                 if emit_vptr {
836                     entries.push(VtblEntry::TraitVPtr(trait_ref));
837                 }
838             }
839         }
840
841         ControlFlow::Continue(())
842     };
843
844     let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
845
846     if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
847         let sp = tcx.def_span(trait_ref.def_id());
848         dump_vtable_entries(tcx, sp, trait_ref, &entries);
849     }
850
851     tcx.arena.alloc_from_iter(entries.into_iter())
852 }
853
854 /// Find slot base for trait methods within vtable entries of another trait
855 fn vtable_trait_first_method_offset<'tcx>(
856     tcx: TyCtxt<'tcx>,
857     key: (
858         ty::PolyTraitRef<'tcx>, // trait_to_be_found
859         ty::PolyTraitRef<'tcx>, // trait_owning_vtable
860     ),
861 ) -> usize {
862     let (trait_to_be_found, trait_owning_vtable) = key;
863
864     // #90177
865     let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
866
867     let vtable_segment_callback = {
868         let mut vtable_base = 0;
869
870         move |segment| {
871             match segment {
872                 VtblSegment::MetadataDSA => {
873                     vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
874                 }
875                 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
876                     if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
877                         return ControlFlow::Break(vtable_base);
878                     }
879                     vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
880                     if emit_vptr {
881                         vtable_base += 1;
882                     }
883                 }
884             }
885             ControlFlow::Continue(())
886         }
887     };
888
889     if let Some(vtable_base) =
890         prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
891     {
892         vtable_base
893     } else {
894         bug!("Failed to find info for expected trait in vtable");
895     }
896 }
897
898 /// Find slot offset for trait vptr within vtable entries of another trait
899 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
900     tcx: TyCtxt<'tcx>,
901     key: (
902         Ty<'tcx>, // trait object type whose trait owning vtable
903         Ty<'tcx>, // trait object for supertrait
904     ),
905 ) -> Option<usize> {
906     let (source, target) = key;
907     assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
908     assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
909
910     // this has been typecked-before, so diagnostics is not really needed.
911     let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
912
913     let trait_ref = tcx.mk_trait_ref(unsize_trait_did, [source, target]);
914
915     match tcx.codegen_select_candidate((ty::ParamEnv::reveal_all(), ty::Binder::dummy(trait_ref))) {
916         Ok(ImplSource::TraitUpcasting(implsrc_traitcasting)) => {
917             implsrc_traitcasting.vtable_vptr_slot
918         }
919         otherwise => bug!("expected TraitUpcasting candidate, got {otherwise:?}"),
920     }
921 }
922
923 pub fn provide(providers: &mut ty::query::Providers) {
924     object_safety::provide(providers);
925     structural_match::provide(providers);
926     *providers = ty::query::Providers {
927         specialization_graph_of: specialize::specialization_graph_provider,
928         specializes: specialize::specializes,
929         codegen_select_candidate: codegen::codegen_select_candidate,
930         own_existential_vtable_entries,
931         vtable_entries,
932         vtable_trait_upcasting_coercion_new_vptr_slot,
933         subst_and_check_impossible_predicates,
934         is_impossible_method,
935         ..*providers
936     };
937 }