]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/mod.rs
Auto merge of #98457 - japaric:gh98378, r=m-ou-se
[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::InferCtxtExt 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<'a, 'tcx>(
144     infcx: &InferCtxt<'a, '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_infer_types_or_consts() {
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     tcx.infer_ctxt().ignoring_regions().enter(|infcx| {
238         let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
239             Ok(predicates) => predicates,
240             Err(errors) => {
241                 let reported = infcx.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!(
260                     "failed region resolution while normalizing {elaborated_env:?}: {errors:?}"
261                 ),
262             );
263         }
264
265         match infcx.fully_resolve(predicates) {
266             Ok(predicates) => Ok(predicates),
267             Err(fixup_err) => {
268                 // If we encounter a fixup error, it means that some type
269                 // variable wound up unconstrained. I actually don't know
270                 // if this can happen, and I certainly don't expect it to
271                 // happen often, but if it did happen it probably
272                 // represents a legitimate failure due to some kind of
273                 // unconstrained variable.
274                 //
275                 // @lcnr: Let's still ICE here for now. I want a test case
276                 // for that.
277                 span_bug!(
278                     span,
279                     "inference variables in normalized parameter environment: {}",
280                     fixup_err
281                 );
282             }
283         }
284     })
285 }
286
287 // FIXME: this is gonna need to be removed ...
288 /// Normalizes the parameter environment, reporting errors if they occur.
289 #[instrument(level = "debug", skip(tcx))]
290 pub fn normalize_param_env_or_error<'tcx>(
291     tcx: TyCtxt<'tcx>,
292     unnormalized_env: ty::ParamEnv<'tcx>,
293     cause: ObligationCause<'tcx>,
294 ) -> ty::ParamEnv<'tcx> {
295     // I'm not wild about reporting errors here; I'd prefer to
296     // have the errors get reported at a defined place (e.g.,
297     // during typeck). Instead I have all parameter
298     // environments, in effect, going through this function
299     // and hence potentially reporting errors. This ensures of
300     // course that we never forget to normalize (the
301     // alternative seemed like it would involve a lot of
302     // manual invocations of this fn -- and then we'd have to
303     // deal with the errors at each of those sites).
304     //
305     // In any case, in practice, typeck constructs all the
306     // parameter environments once for every fn as it goes,
307     // and errors will get reported then; so outside of type inference we
308     // can be sure that no errors should occur.
309     let mut predicates: Vec<_> =
310         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
311             .map(|obligation| obligation.predicate)
312             .collect();
313
314     debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
315
316     let elaborated_env = ty::ParamEnv::new(
317         tcx.intern_predicates(&predicates),
318         unnormalized_env.reveal(),
319         unnormalized_env.constness(),
320     );
321
322     // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
323     // normalization expects its param-env to be already normalized, which means we have
324     // a circularity.
325     //
326     // The way we handle this is by normalizing the param-env inside an unnormalized version
327     // of the param-env, which means that if the param-env contains unnormalized projections,
328     // we'll have some normalization failures. This is unfortunate.
329     //
330     // Lazy normalization would basically handle this by treating just the
331     // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
332     //
333     // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
334     // types, so to make the situation less bad, we normalize all the predicates *but*
335     // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
336     // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
337     //
338     // This works fairly well because trait matching  does not actually care about param-env
339     // TypeOutlives predicates - these are normally used by regionck.
340     let outlives_predicates: Vec<_> = predicates
341         .drain_filter(|predicate| {
342             matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..))
343         })
344         .collect();
345
346     debug!(
347         "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
348         predicates, outlives_predicates
349     );
350     let Ok(non_outlives_predicates) = do_normalize_predicates(
351         tcx,
352         cause.clone(),
353         elaborated_env,
354         predicates,
355     ) else {
356         // An unnormalized env is better than nothing.
357         debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
358         return elaborated_env;
359     };
360
361     debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
362
363     // Not sure whether it is better to include the unnormalized TypeOutlives predicates
364     // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
365     // predicates here anyway. Keeping them here anyway because it seems safer.
366     let outlives_env: Vec<_> =
367         non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
368     let outlives_env = ty::ParamEnv::new(
369         tcx.intern_predicates(&outlives_env),
370         unnormalized_env.reveal(),
371         unnormalized_env.constness(),
372     );
373     let Ok(outlives_predicates) = do_normalize_predicates(
374         tcx,
375         cause,
376         outlives_env,
377         outlives_predicates,
378     ) else {
379         // An unnormalized env is better than nothing.
380         debug!("normalize_param_env_or_error: errored resolving outlives predicates");
381         return elaborated_env;
382     };
383     debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
384
385     let mut predicates = non_outlives_predicates;
386     predicates.extend(outlives_predicates);
387     debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
388     ty::ParamEnv::new(
389         tcx.intern_predicates(&predicates),
390         unnormalized_env.reveal(),
391         unnormalized_env.constness(),
392     )
393 }
394
395 /// Normalize a type and process all resulting obligations, returning any errors
396 pub fn fully_normalize<'a, 'tcx, T>(
397     infcx: &InferCtxt<'a, 'tcx>,
398     cause: ObligationCause<'tcx>,
399     param_env: ty::ParamEnv<'tcx>,
400     value: T,
401 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
402 where
403     T: TypeFoldable<'tcx>,
404 {
405     debug!("fully_normalize_with_fulfillcx(value={:?})", value);
406     let selcx = &mut SelectionContext::new(infcx);
407     let Normalized { value: normalized_value, obligations } =
408         project::normalize(selcx, param_env, cause, value);
409     debug!(
410         "fully_normalize: normalized_value={:?} obligations={:?}",
411         normalized_value, obligations
412     );
413
414     let mut fulfill_cx = FulfillmentContext::new();
415     for obligation in obligations {
416         fulfill_cx.register_predicate_obligation(infcx, obligation);
417     }
418
419     debug!("fully_normalize: select_all_or_error start");
420     let errors = fulfill_cx.select_all_or_error(infcx);
421     if !errors.is_empty() {
422         return Err(errors);
423     }
424     debug!("fully_normalize: select_all_or_error complete");
425     let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
426     debug!("fully_normalize: resolved_value={:?}", resolved_value);
427     Ok(resolved_value)
428 }
429
430 /// Process an obligation (and any nested obligations that come from it) to
431 /// completion, returning any errors
432 pub fn fully_solve_obligation<'a, 'tcx>(
433     infcx: &InferCtxt<'a, 'tcx>,
434     obligation: PredicateObligation<'tcx>,
435 ) -> Vec<FulfillmentError<'tcx>> {
436     let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
437     engine.register_predicate_obligation(infcx, obligation);
438     engine.select_all_or_error(infcx)
439 }
440
441 /// Process a set of obligations (and any nested obligations that come from them)
442 /// to completion
443 pub fn fully_solve_obligations<'a, 'tcx>(
444     infcx: &InferCtxt<'a, 'tcx>,
445     obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
446 ) -> Vec<FulfillmentError<'tcx>> {
447     let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
448     engine.register_predicate_obligations(infcx, obligations);
449     engine.select_all_or_error(infcx)
450 }
451
452 /// Process a bound (and any nested obligations that come from it) to completion.
453 /// This is a convenience function for traits that have no generic arguments, such
454 /// as auto traits, and builtin traits like Copy or Sized.
455 pub fn fully_solve_bound<'a, 'tcx>(
456     infcx: &InferCtxt<'a, 'tcx>,
457     cause: ObligationCause<'tcx>,
458     param_env: ty::ParamEnv<'tcx>,
459     ty: Ty<'tcx>,
460     bound: DefId,
461 ) -> Vec<FulfillmentError<'tcx>> {
462     let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
463     engine.register_bound(infcx, param_env, ty, bound, cause);
464     engine.select_all_or_error(infcx)
465 }
466
467 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
468 /// returns true, then either normalize encountered an error or one of the predicates did not
469 /// hold. Used when creating vtables to check for unsatisfiable methods.
470 pub fn impossible_predicates<'tcx>(
471     tcx: TyCtxt<'tcx>,
472     predicates: Vec<ty::Predicate<'tcx>>,
473 ) -> bool {
474     debug!("impossible_predicates(predicates={:?})", predicates);
475
476     let result = tcx.infer_ctxt().enter(|infcx| {
477         let param_env = ty::ParamEnv::reveal_all();
478         let ocx = ObligationCtxt::new(&infcx);
479         let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);
480         for predicate in predicates {
481             let obligation = Obligation::new(ObligationCause::dummy(), param_env, predicate);
482             ocx.register_obligation(obligation);
483         }
484         let errors = ocx.select_all_or_error();
485
486         // Clean up after ourselves
487         let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
488
489         !errors.is_empty()
490     });
491     debug!("impossible_predicates = {:?}", result);
492     result
493 }
494
495 fn subst_and_check_impossible_predicates<'tcx>(
496     tcx: TyCtxt<'tcx>,
497     key: (DefId, SubstsRef<'tcx>),
498 ) -> bool {
499     debug!("subst_and_check_impossible_predicates(key={:?})", key);
500
501     let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
502
503     // Specifically check trait fulfillment to avoid an error when trying to resolve
504     // associated items.
505     if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
506         let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
507         predicates.push(ty::Binder::dummy(trait_ref).to_poly_trait_predicate().to_predicate(tcx));
508     }
509
510     predicates.retain(|predicate| !predicate.needs_subst());
511     let result = impossible_predicates(tcx, predicates);
512
513     debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
514     result
515 }
516
517 /// Checks whether a trait's method is impossible to call on a given impl.
518 ///
519 /// This only considers predicates that reference the impl's generics, and not
520 /// those that reference the method's generics.
521 fn is_impossible_method<'tcx>(
522     tcx: TyCtxt<'tcx>,
523     (impl_def_id, trait_item_def_id): (DefId, DefId),
524 ) -> bool {
525     struct ReferencesOnlyParentGenerics<'tcx> {
526         tcx: TyCtxt<'tcx>,
527         generics: &'tcx ty::Generics,
528         trait_item_def_id: DefId,
529     }
530     impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
531         type BreakTy = ();
532         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
533             // If this is a parameter from the trait item's own generics, then bail
534             if let ty::Param(param) = t.kind()
535                 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
536                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
537             {
538                 return ControlFlow::BREAK;
539             }
540             t.super_visit_with(self)
541         }
542         fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
543             if let ty::ReEarlyBound(param) = r.kind()
544                 && let param_def_id = self.generics.region_param(&param, self.tcx).def_id
545                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
546             {
547                 return ControlFlow::BREAK;
548             }
549             r.super_visit_with(self)
550         }
551         fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
552             if let ty::ConstKind::Param(param) = ct.kind()
553                 && let param_def_id = self.generics.const_param(&param, self.tcx).def_id
554                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
555             {
556                 return ControlFlow::BREAK;
557             }
558             ct.super_visit_with(self)
559         }
560     }
561
562     let generics = tcx.generics_of(trait_item_def_id);
563     let predicates = tcx.predicates_of(trait_item_def_id);
564     let impl_trait_ref =
565         tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
566     let param_env = tcx.param_env(impl_def_id);
567
568     let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
569     let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
570         if pred.visit_with(&mut visitor).is_continue() {
571             Some(Obligation::new(
572                 ObligationCause::dummy_with_span(*span),
573                 param_env,
574                 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
575             ))
576         } else {
577             None
578         }
579     });
580
581     tcx.infer_ctxt().ignoring_regions().enter(|ref infcx| {
582         for obligation in predicates_for_trait {
583             // Ignore overflow error, to be conservative.
584             if let Ok(result) = infcx.evaluate_obligation(&obligation)
585                 && !result.may_apply()
586             {
587                 return true;
588             }
589         }
590
591         false
592     })
593 }
594
595 #[derive(Clone, Debug)]
596 enum VtblSegment<'tcx> {
597     MetadataDSA,
598     TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
599 }
600
601 /// Prepare the segments for a vtable
602 fn prepare_vtable_segments<'tcx, T>(
603     tcx: TyCtxt<'tcx>,
604     trait_ref: ty::PolyTraitRef<'tcx>,
605     mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
606 ) -> Option<T> {
607     // The following constraints holds for the final arrangement.
608     // 1. The whole virtual table of the first direct super trait is included as the
609     //    the prefix. If this trait doesn't have any super traits, then this step
610     //    consists of the dsa metadata.
611     // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
612     //    other super traits except those already included as part of the first
613     //    direct super trait virtual table.
614     // 3. finally, the own methods of this trait.
615
616     // This has the advantage that trait upcasting to the first direct super trait on each level
617     // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
618     // while not using too much extra memory.
619
620     // For a single inheritance relationship like this,
621     //   D --> C --> B --> A
622     // The resulting vtable will consists of these segments:
623     //  DSA, A, B, C, D
624
625     // For a multiple inheritance relationship like this,
626     //   D --> C --> A
627     //           \-> B
628     // The resulting vtable will consists of these segments:
629     //  DSA, A, B, B-vptr, C, D
630
631     // For a diamond inheritance relationship like this,
632     //   D --> B --> A
633     //     \-> C -/
634     // The resulting vtable will consists of these segments:
635     //  DSA, A, B, C, C-vptr, D
636
637     // For a more complex inheritance relationship like this:
638     //   O --> G --> C --> A
639     //     \     \     \-> B
640     //     |     |-> F --> D
641     //     |           \-> E
642     //     |-> N --> J --> H
643     //           \     \-> I
644     //           |-> M --> K
645     //                 \-> L
646     // The resulting vtable will consists of these segments:
647     //  DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
648     //  H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
649     //  N, N-vptr, O
650
651     // emit dsa segment first.
652     if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
653         return Some(v);
654     }
655
656     let mut emit_vptr_on_new_entry = false;
657     let mut visited = util::PredicateSet::new(tcx);
658     let predicate = trait_ref.without_const().to_predicate(tcx);
659     let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
660         smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
661     visited.insert(predicate);
662
663     // the main traversal loop:
664     // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
665     // that each node is emitted after all its descendents have been emitted.
666     // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
667     // this is done on the fly.
668     // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
669     // stops after it finds a node that has a next-sibling node.
670     // This next-sibling node will used as the starting point of next slice.
671
672     // Example:
673     // For a diamond inheritance relationship like this,
674     //   D#1 --> B#0 --> A#0
675     //     \-> C#1 -/
676
677     // Starting point 0 stack [D]
678     // Loop run #0: Stack after diving in is [D B A], A is "childless"
679     // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
680     // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
681     // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
682     // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
683     // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
684     // Loop run #1: Stack after exiting out is []. Now the function exits.
685
686     loop {
687         // dive deeper into the stack, recording the path
688         'diving_in: loop {
689             if let Some((inner_most_trait_ref, _, _)) = stack.last() {
690                 let inner_most_trait_ref = *inner_most_trait_ref;
691                 let mut direct_super_traits_iter = tcx
692                     .super_predicates_of(inner_most_trait_ref.def_id())
693                     .predicates
694                     .into_iter()
695                     .filter_map(move |(pred, _)| {
696                         pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
697                     });
698
699                 'diving_in_skip_visited_traits: loop {
700                     if let Some(next_super_trait) = direct_super_traits_iter.next() {
701                         if visited.insert(next_super_trait.to_predicate(tcx)) {
702                             // We're throwing away potential constness of super traits here.
703                             // FIXME: handle ~const super traits
704                             let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
705                             stack.push((
706                                 next_super_trait,
707                                 emit_vptr_on_new_entry,
708                                 Some(direct_super_traits_iter),
709                             ));
710                             break 'diving_in_skip_visited_traits;
711                         } else {
712                             continue 'diving_in_skip_visited_traits;
713                         }
714                     } else {
715                         break 'diving_in;
716                     }
717                 }
718             }
719         }
720
721         // Other than the left-most path, vptr should be emitted for each trait.
722         emit_vptr_on_new_entry = true;
723
724         // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
725         'exiting_out: loop {
726             if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
727                 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
728                     trait_ref: *inner_most_trait_ref,
729                     emit_vptr: *emit_vptr,
730                 }) {
731                     return Some(v);
732                 }
733
734                 'exiting_out_skip_visited_traits: loop {
735                     if let Some(siblings) = siblings_opt {
736                         if let Some(next_inner_most_trait_ref) = siblings.next() {
737                             if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
738                                 // We're throwing away potential constness of super traits here.
739                                 // FIXME: handle ~const super traits
740                                 let next_inner_most_trait_ref =
741                                     next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
742                                 *inner_most_trait_ref = next_inner_most_trait_ref;
743                                 *emit_vptr = emit_vptr_on_new_entry;
744                                 break 'exiting_out;
745                             } else {
746                                 continue 'exiting_out_skip_visited_traits;
747                             }
748                         }
749                     }
750                     stack.pop();
751                     continue 'exiting_out;
752                 }
753             }
754             // all done
755             return None;
756         }
757     }
758 }
759
760 fn dump_vtable_entries<'tcx>(
761     tcx: TyCtxt<'tcx>,
762     sp: Span,
763     trait_ref: ty::PolyTraitRef<'tcx>,
764     entries: &[VtblEntry<'tcx>],
765 ) {
766     tcx.sess.emit_err(DumpVTableEntries {
767         span: sp,
768         trait_ref,
769         entries: format!("{:#?}", entries),
770     });
771 }
772
773 fn own_existential_vtable_entries<'tcx>(
774     tcx: TyCtxt<'tcx>,
775     trait_ref: ty::PolyExistentialTraitRef<'tcx>,
776 ) -> &'tcx [DefId] {
777     let trait_methods = tcx
778         .associated_items(trait_ref.def_id())
779         .in_definition_order()
780         .filter(|item| item.kind == ty::AssocKind::Fn);
781     // Now list each method's DefId (for within its trait).
782     let own_entries = trait_methods.filter_map(move |trait_method| {
783         debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
784         let def_id = trait_method.def_id;
785
786         // Some methods cannot be called on an object; skip those.
787         if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
788             debug!("own_existential_vtable_entry: not vtable safe");
789             return None;
790         }
791
792         Some(def_id)
793     });
794
795     tcx.arena.alloc_from_iter(own_entries.into_iter())
796 }
797
798 /// Given a trait `trait_ref`, iterates the vtable entries
799 /// that come from `trait_ref`, including its supertraits.
800 fn vtable_entries<'tcx>(
801     tcx: TyCtxt<'tcx>,
802     trait_ref: ty::PolyTraitRef<'tcx>,
803 ) -> &'tcx [VtblEntry<'tcx>] {
804     debug!("vtable_entries({:?})", trait_ref);
805
806     let mut entries = vec![];
807
808     let vtable_segment_callback = |segment| -> ControlFlow<()> {
809         match segment {
810             VtblSegment::MetadataDSA => {
811                 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
812             }
813             VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
814                 let existential_trait_ref = trait_ref
815                     .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
816
817                 // Lookup the shape of vtable for the trait.
818                 let own_existential_entries =
819                     tcx.own_existential_vtable_entries(existential_trait_ref);
820
821                 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
822                     debug!("vtable_entries: trait_method={:?}", def_id);
823
824                     // The method may have some early-bound lifetimes; add regions for those.
825                     let substs = trait_ref.map_bound(|trait_ref| {
826                         InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
827                             GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
828                             GenericParamDefKind::Type { .. }
829                             | GenericParamDefKind::Const { .. } => {
830                                 trait_ref.substs[param.index as usize]
831                             }
832                         })
833                     });
834
835                     // The trait type may have higher-ranked lifetimes in it;
836                     // erase them if they appear, so that we get the type
837                     // at some particular call site.
838                     let substs = tcx
839                         .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
840
841                     // It's possible that the method relies on where-clauses that
842                     // do not hold for this particular set of type parameters.
843                     // Note that this method could then never be called, so we
844                     // do not want to try and codegen it, in that case (see #23435).
845                     let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
846                     if impossible_predicates(tcx, predicates.predicates) {
847                         debug!("vtable_entries: predicates do not hold");
848                         return VtblEntry::Vacant;
849                     }
850
851                     let instance = ty::Instance::resolve_for_vtable(
852                         tcx,
853                         ty::ParamEnv::reveal_all(),
854                         def_id,
855                         substs,
856                     )
857                     .expect("resolution failed during building vtable representation");
858                     VtblEntry::Method(instance)
859                 });
860
861                 entries.extend(own_entries);
862
863                 if emit_vptr {
864                     entries.push(VtblEntry::TraitVPtr(trait_ref));
865                 }
866             }
867         }
868
869         ControlFlow::Continue(())
870     };
871
872     let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
873
874     if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
875         let sp = tcx.def_span(trait_ref.def_id());
876         dump_vtable_entries(tcx, sp, trait_ref, &entries);
877     }
878
879     tcx.arena.alloc_from_iter(entries.into_iter())
880 }
881
882 /// Find slot base for trait methods within vtable entries of another trait
883 fn vtable_trait_first_method_offset<'tcx>(
884     tcx: TyCtxt<'tcx>,
885     key: (
886         ty::PolyTraitRef<'tcx>, // trait_to_be_found
887         ty::PolyTraitRef<'tcx>, // trait_owning_vtable
888     ),
889 ) -> usize {
890     let (trait_to_be_found, trait_owning_vtable) = key;
891
892     // #90177
893     let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
894
895     let vtable_segment_callback = {
896         let mut vtable_base = 0;
897
898         move |segment| {
899             match segment {
900                 VtblSegment::MetadataDSA => {
901                     vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
902                 }
903                 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
904                     if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
905                         return ControlFlow::Break(vtable_base);
906                     }
907                     vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
908                     if emit_vptr {
909                         vtable_base += 1;
910                     }
911                 }
912             }
913             ControlFlow::Continue(())
914         }
915     };
916
917     if let Some(vtable_base) =
918         prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
919     {
920         vtable_base
921     } else {
922         bug!("Failed to find info for expected trait in vtable");
923     }
924 }
925
926 /// Find slot offset for trait vptr within vtable entries of another trait
927 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
928     tcx: TyCtxt<'tcx>,
929     key: (
930         Ty<'tcx>, // trait object type whose trait owning vtable
931         Ty<'tcx>, // trait object for supertrait
932     ),
933 ) -> Option<usize> {
934     let (source, target) = key;
935     assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
936     assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
937
938     // this has been typecked-before, so diagnostics is not really needed.
939     let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
940
941     let trait_ref = ty::TraitRef {
942         def_id: unsize_trait_did,
943         substs: tcx.mk_substs_trait(source, &[target.into()]),
944     };
945     let obligation = Obligation::new(
946         ObligationCause::dummy(),
947         ty::ParamEnv::reveal_all(),
948         ty::Binder::dummy(ty::TraitPredicate {
949             trait_ref,
950             constness: ty::BoundConstness::NotConst,
951             polarity: ty::ImplPolarity::Positive,
952         }),
953     );
954
955     let implsrc = tcx.infer_ctxt().enter(|infcx| {
956         let mut selcx = SelectionContext::new(&infcx);
957         selcx.select(&obligation).unwrap()
958     });
959
960     let Some(ImplSource::TraitUpcasting(implsrc_traitcasting)) = implsrc else {
961         bug!();
962     };
963
964     implsrc_traitcasting.vtable_vptr_slot
965 }
966
967 pub fn provide(providers: &mut ty::query::Providers) {
968     object_safety::provide(providers);
969     structural_match::provide(providers);
970     *providers = ty::query::Providers {
971         specialization_graph_of: specialize::specialization_graph_provider,
972         specializes: specialize::specializes,
973         codegen_select_candidate: codegen::codegen_select_candidate,
974         own_existential_vtable_entries,
975         vtable_entries,
976         vtable_trait_upcasting_coercion_new_vptr_slot,
977         subst_and_check_impossible_predicates,
978         is_impossible_method,
979         try_unify_abstract_consts: |tcx, param_env_and| {
980             let (param_env, (a, b)) = param_env_and.into_parts();
981             const_evaluatable::try_unify_abstract_consts(tcx, (a, b), param_env)
982         },
983         ..*providers
984     };
985 }