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