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