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