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