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