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