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