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