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