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