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