]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/mod.rs
c2104a98cea78e9f5c07721c796884e662b30327
[rust.git] / compiler / rustc_trait_selection / src / traits / mod.rs
1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
4
5 pub mod auto_trait;
6 mod chalk_fulfill;
7 pub mod codegen;
8 mod coherence;
9 pub mod const_evaluatable;
10 mod engine;
11 pub mod error_reporting;
12 mod fulfill;
13 pub mod misc;
14 mod object_safety;
15 pub mod outlives_bounds;
16 mod project;
17 pub mod query;
18 pub(crate) mod relationships;
19 mod select;
20 mod specialize;
21 mod structural_match;
22 mod util;
23 mod vtable;
24 pub mod wf;
25
26 use crate::infer::outlives::env::OutlivesEnvironment;
27 use crate::infer::{InferCtxt, TyCtxtInferExt};
28 use crate::traits::error_reporting::TypeErrCtxtExt as _;
29 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
30 use rustc_errors::ErrorGuaranteed;
31 use rustc_hir as hir;
32 use rustc_hir::def_id::DefId;
33 use rustc_middle::ty::fold::TypeFoldable;
34 use rustc_middle::ty::visit::TypeVisitable;
35 use rustc_middle::ty::{self, DefIdTree, ToPredicate, Ty, TyCtxt, TypeSuperVisitable};
36 use rustc_middle::ty::{InternalSubsts, SubstsRef};
37 use rustc_span::Span;
38
39 use std::fmt::Debug;
40 use std::ops::ControlFlow;
41
42 pub use self::FulfillmentErrorCode::*;
43 pub use self::ImplSource::*;
44 pub use self::ObligationCauseCode::*;
45 pub use self::SelectionError::*;
46
47 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
48 pub use self::coherence::{OrphanCheckErr, OverlapResult};
49 pub use self::engine::{ObligationCtxt, TraitEngineExt};
50 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
51 pub use self::object_safety::astconv_object_safety_violations;
52 pub use self::object_safety::is_vtable_safe_method;
53 pub use self::object_safety::MethodViolationCode;
54 pub use self::object_safety::ObjectSafetyViolation;
55 pub use self::project::{normalize_projection_type, NormalizeExt};
56 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
57 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
58 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
59 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
60 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
61 pub use self::structural_match::{
62     search_for_adt_const_param_violation, search_for_structural_match_violation,
63 };
64 pub use self::util::{
65     elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
66     elaborate_trait_ref, elaborate_trait_refs,
67 };
68 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
69 pub use self::util::{
70     get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
71 };
72 pub use self::util::{
73     supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
74     SupertraitDefIds, Supertraits,
75 };
76
77 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
78
79 pub use rustc_infer::traits::*;
80
81 /// Whether to skip the leak check, as part of a future compatibility warning step.
82 ///
83 /// The "default" for skip-leak-check corresponds to the current
84 /// behavior (do not skip the leak check) -- not the behavior we are
85 /// transitioning into.
86 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
87 pub enum SkipLeakCheck {
88     Yes,
89     #[default]
90     No,
91 }
92
93 impl SkipLeakCheck {
94     fn is_yes(self) -> bool {
95         self == SkipLeakCheck::Yes
96     }
97 }
98
99 /// The mode that trait queries run in.
100 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
101 pub enum TraitQueryMode {
102     /// Standard/un-canonicalized queries get accurate
103     /// spans etc. passed in and hence can do reasonable
104     /// error reporting on their own.
105     Standard,
106     /// Canonicalized queries get dummy spans and hence
107     /// must generally propagate errors to
108     /// pre-canonicalization callsites.
109     Canonical,
110 }
111
112 /// Creates predicate obligations from the generic bounds.
113 #[instrument(level = "debug", skip(cause, param_env))]
114 pub fn predicates_for_generics<'tcx>(
115     cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
116     param_env: ty::ParamEnv<'tcx>,
117     generic_bounds: ty::InstantiatedPredicates<'tcx>,
118 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
119     std::iter::zip(generic_bounds.predicates, generic_bounds.spans).enumerate().map(
120         move |(idx, (predicate, span))| Obligation {
121             cause: cause(idx, span),
122             recursion_depth: 0,
123             param_env,
124             predicate,
125         },
126     )
127 }
128
129 /// Determines whether the type `ty` is known to meet `bound` and
130 /// returns true if so. Returns false if `ty` either does not meet
131 /// `bound` or is not known to meet bound (note that this is
132 /// conservative towards *no impl*, which is the opposite of the
133 /// `evaluate` methods).
134 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
135     infcx: &InferCtxt<'tcx>,
136     param_env: ty::ParamEnv<'tcx>,
137     ty: Ty<'tcx>,
138     def_id: DefId,
139     span: Span,
140 ) -> bool {
141     let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
142     pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
143 }
144
145 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
146 fn pred_known_to_hold_modulo_regions<'tcx>(
147     infcx: &InferCtxt<'tcx>,
148     param_env: ty::ParamEnv<'tcx>,
149     pred: impl ToPredicate<'tcx> + TypeVisitable<'tcx>,
150     span: Span,
151 ) -> bool {
152     let has_non_region_infer = pred.has_non_region_infer();
153     let obligation = Obligation {
154         param_env,
155         // We can use a dummy node-id here because we won't pay any mind
156         // to region obligations that arise (there shouldn't really be any
157         // anyhow).
158         cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
159         recursion_depth: 0,
160         predicate: pred.to_predicate(infcx.tcx),
161     };
162
163     let result = infcx.predicate_must_hold_modulo_regions(&obligation);
164     debug!(?result);
165
166     if result && has_non_region_infer {
167         // Because of inference "guessing", selection can sometimes claim
168         // to succeed while the success requires a guess. To ensure
169         // this function's result remains infallible, we must confirm
170         // that guess. While imperfect, I believe this is sound.
171
172         // FIXME(@lcnr): this function doesn't seem right.
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_obligation(infcx, obligation);
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             [] => true,
183             errors => {
184                 debug!(?errors);
185                 false
186             }
187         }
188     } else {
189         result
190     }
191 }
192
193 #[instrument(level = "debug", skip(tcx, elaborated_env))]
194 fn do_normalize_predicates<'tcx>(
195     tcx: TyCtxt<'tcx>,
196     cause: ObligationCause<'tcx>,
197     elaborated_env: ty::ParamEnv<'tcx>,
198     predicates: Vec<ty::Predicate<'tcx>>,
199 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
200     let span = cause.span;
201     // FIXME. We should really... do something with these region
202     // obligations. But this call just continues the older
203     // behavior (i.e., doesn't cause any new bugs), and it would
204     // take some further refactoring to actually solve them. In
205     // particular, we would have to handle implied bounds
206     // properly, and that code is currently largely confined to
207     // regionck (though I made some efforts to extract it
208     // out). -nmatsakis
209     //
210     // @arielby: In any case, these obligations are checked
211     // by wfcheck anyway, so I'm not sure we have to check
212     // them here too, and we will remove this function when
213     // we move over to lazy normalization *anyway*.
214     let infcx = tcx.infer_ctxt().ignoring_regions().build();
215     let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
216         Ok(predicates) => predicates,
217         Err(errors) => {
218             let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
219             return Err(reported);
220         }
221     };
222
223     debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
224
225     // We can use the `elaborated_env` here; the region code only
226     // cares about declarations like `'a: 'b`.
227     let outlives_env = OutlivesEnvironment::new(elaborated_env);
228
229     // FIXME: It's very weird that we ignore region obligations but apparently
230     // still need to use `resolve_regions` as we need the resolved regions in
231     // the normalized predicates.
232     let errors = infcx.resolve_regions(&outlives_env);
233     if !errors.is_empty() {
234         tcx.sess.delay_span_bug(
235             span,
236             format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
237         );
238     }
239
240     match infcx.fully_resolve(predicates) {
241         Ok(predicates) => Ok(predicates),
242         Err(fixup_err) => {
243             // If we encounter a fixup error, it means that some type
244             // variable wound up unconstrained. I actually don't know
245             // if this can happen, and I certainly don't expect it to
246             // happen often, but if it did happen it probably
247             // represents a legitimate failure due to some kind of
248             // unconstrained variable.
249             //
250             // @lcnr: Let's still ICE here for now. I want a test case
251             // for that.
252             span_bug!(
253                 span,
254                 "inference variables in normalized parameter environment: {}",
255                 fixup_err
256             );
257         }
258     }
259 }
260
261 // FIXME: this is gonna need to be removed ...
262 /// Normalizes the parameter environment, reporting errors if they occur.
263 #[instrument(level = "debug", skip(tcx))]
264 pub fn normalize_param_env_or_error<'tcx>(
265     tcx: TyCtxt<'tcx>,
266     unnormalized_env: ty::ParamEnv<'tcx>,
267     cause: ObligationCause<'tcx>,
268 ) -> ty::ParamEnv<'tcx> {
269     // I'm not wild about reporting errors here; I'd prefer to
270     // have the errors get reported at a defined place (e.g.,
271     // during typeck). Instead I have all parameter
272     // environments, in effect, going through this function
273     // and hence potentially reporting errors. This ensures of
274     // course that we never forget to normalize (the
275     // alternative seemed like it would involve a lot of
276     // manual invocations of this fn -- and then we'd have to
277     // deal with the errors at each of those sites).
278     //
279     // In any case, in practice, typeck constructs all the
280     // parameter environments once for every fn as it goes,
281     // and errors will get reported then; so outside of type inference we
282     // can be sure that no errors should occur.
283     let mut predicates: Vec<_> =
284         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
285             .map(|obligation| obligation.predicate)
286             .collect();
287
288     debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
289
290     let elaborated_env = ty::ParamEnv::new(
291         tcx.intern_predicates(&predicates),
292         unnormalized_env.reveal(),
293         unnormalized_env.constness(),
294     );
295
296     // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
297     // normalization expects its param-env to be already normalized, which means we have
298     // a circularity.
299     //
300     // The way we handle this is by normalizing the param-env inside an unnormalized version
301     // of the param-env, which means that if the param-env contains unnormalized projections,
302     // we'll have some normalization failures. This is unfortunate.
303     //
304     // Lazy normalization would basically handle this by treating just the
305     // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
306     //
307     // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
308     // types, so to make the situation less bad, we normalize all the predicates *but*
309     // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
310     // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
311     //
312     // This works fairly well because trait matching  does not actually care about param-env
313     // TypeOutlives predicates - these are normally used by regionck.
314     let outlives_predicates: Vec<_> = predicates
315         .drain_filter(|predicate| {
316             matches!(
317                 predicate.kind().skip_binder(),
318                 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
319             )
320         })
321         .collect();
322
323     debug!(
324         "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
325         predicates, outlives_predicates
326     );
327     let Ok(non_outlives_predicates) = do_normalize_predicates(
328         tcx,
329         cause.clone(),
330         elaborated_env,
331         predicates,
332     ) else {
333         // An unnormalized env is better than nothing.
334         debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
335         return elaborated_env;
336     };
337
338     debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
339
340     // Not sure whether it is better to include the unnormalized TypeOutlives predicates
341     // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
342     // predicates here anyway. Keeping them here anyway because it seems safer.
343     let outlives_env: Vec<_> =
344         non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
345     let outlives_env = ty::ParamEnv::new(
346         tcx.intern_predicates(&outlives_env),
347         unnormalized_env.reveal(),
348         unnormalized_env.constness(),
349     );
350     let Ok(outlives_predicates) = do_normalize_predicates(
351         tcx,
352         cause,
353         outlives_env,
354         outlives_predicates,
355     ) else {
356         // An unnormalized env is better than nothing.
357         debug!("normalize_param_env_or_error: errored resolving outlives predicates");
358         return elaborated_env;
359     };
360     debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
361
362     let mut predicates = non_outlives_predicates;
363     predicates.extend(outlives_predicates);
364     debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
365     ty::ParamEnv::new(
366         tcx.intern_predicates(&predicates),
367         unnormalized_env.reveal(),
368         unnormalized_env.constness(),
369     )
370 }
371
372 /// Normalize a type and process all resulting obligations, returning any errors
373 #[instrument(skip_all)]
374 pub fn fully_normalize<'tcx, T>(
375     infcx: &InferCtxt<'tcx>,
376     cause: ObligationCause<'tcx>,
377     param_env: ty::ParamEnv<'tcx>,
378     value: T,
379 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
380 where
381     T: TypeFoldable<'tcx>,
382 {
383     let ocx = ObligationCtxt::new(infcx);
384     debug!(?value);
385     let normalized_value = ocx.normalize(&cause, param_env, value);
386     debug!(?normalized_value);
387     debug!("select_all_or_error start");
388     let errors = ocx.select_all_or_error();
389     if !errors.is_empty() {
390         return Err(errors);
391     }
392     debug!("select_all_or_error complete");
393     let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
394     debug!(?resolved_value);
395     Ok(resolved_value)
396 }
397
398 /// Process an obligation (and any nested obligations that come from it) to
399 /// completion, returning any errors
400 pub fn fully_solve_obligation<'tcx>(
401     infcx: &InferCtxt<'tcx>,
402     obligation: PredicateObligation<'tcx>,
403 ) -> Vec<FulfillmentError<'tcx>> {
404     fully_solve_obligations(infcx, [obligation])
405 }
406
407 /// Process a set of obligations (and any nested obligations that come from them)
408 /// to completion
409 pub fn fully_solve_obligations<'tcx>(
410     infcx: &InferCtxt<'tcx>,
411     obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
412 ) -> Vec<FulfillmentError<'tcx>> {
413     let ocx = ObligationCtxt::new(infcx);
414     ocx.register_obligations(obligations);
415     ocx.select_all_or_error()
416 }
417
418 /// Process a bound (and any nested obligations that come from it) to completion.
419 /// This is a convenience function for traits that have no generic arguments, such
420 /// as auto traits, and builtin traits like Copy or Sized.
421 pub fn fully_solve_bound<'tcx>(
422     infcx: &InferCtxt<'tcx>,
423     cause: ObligationCause<'tcx>,
424     param_env: ty::ParamEnv<'tcx>,
425     ty: Ty<'tcx>,
426     bound: DefId,
427 ) -> Vec<FulfillmentError<'tcx>> {
428     let tcx = infcx.tcx;
429     let trait_ref = ty::TraitRef { def_id: bound, substs: tcx.mk_substs_trait(ty, []) };
430     let obligation = Obligation {
431         cause,
432         recursion_depth: 0,
433         param_env,
434         predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
435     };
436
437     fully_solve_obligation(infcx, obligation)
438 }
439
440 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
441 /// returns true, then either normalize encountered an error or one of the predicates did not
442 /// hold. Used when creating vtables to check for unsatisfiable methods.
443 pub fn impossible_predicates<'tcx>(
444     tcx: TyCtxt<'tcx>,
445     predicates: Vec<ty::Predicate<'tcx>>,
446 ) -> bool {
447     debug!("impossible_predicates(predicates={:?})", predicates);
448
449     let infcx = tcx.infer_ctxt().build();
450     let param_env = ty::ParamEnv::reveal_all();
451     let ocx = ObligationCtxt::new(&infcx);
452     let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
453     for predicate in predicates {
454         let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
455         ocx.register_obligation(obligation);
456     }
457     let errors = ocx.select_all_or_error();
458
459     // Clean up after ourselves
460     let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
461
462     let result = !errors.is_empty();
463     debug!("impossible_predicates = {:?}", result);
464     result
465 }
466
467 fn subst_and_check_impossible_predicates<'tcx>(
468     tcx: TyCtxt<'tcx>,
469     key: (DefId, SubstsRef<'tcx>),
470 ) -> bool {
471     debug!("subst_and_check_impossible_predicates(key={:?})", key);
472
473     let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
474
475     // Specifically check trait fulfillment to avoid an error when trying to resolve
476     // associated items.
477     if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
478         let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
479         predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
480     }
481
482     predicates.retain(|predicate| !predicate.needs_subst());
483     let result = impossible_predicates(tcx, predicates);
484
485     debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
486     result
487 }
488
489 /// Checks whether a trait's method is impossible to call on a given impl.
490 ///
491 /// This only considers predicates that reference the impl's generics, and not
492 /// those that reference the method's generics.
493 fn is_impossible_method<'tcx>(
494     tcx: TyCtxt<'tcx>,
495     (impl_def_id, trait_item_def_id): (DefId, DefId),
496 ) -> bool {
497     struct ReferencesOnlyParentGenerics<'tcx> {
498         tcx: TyCtxt<'tcx>,
499         generics: &'tcx ty::Generics,
500         trait_item_def_id: DefId,
501     }
502     impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
503         type BreakTy = ();
504         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
505             // If this is a parameter from the trait item's own generics, then bail
506             if let ty::Param(param) = t.kind()
507                 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
508                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
509             {
510                 return ControlFlow::BREAK;
511             }
512             t.super_visit_with(self)
513         }
514         fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
515             if let ty::ReEarlyBound(param) = r.kind()
516                 && let param_def_id = self.generics.region_param(&param, self.tcx).def_id
517                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
518             {
519                 return ControlFlow::BREAK;
520             }
521             r.super_visit_with(self)
522         }
523         fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
524             if let ty::ConstKind::Param(param) = ct.kind()
525                 && let param_def_id = self.generics.const_param(&param, self.tcx).def_id
526                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
527             {
528                 return ControlFlow::BREAK;
529             }
530             ct.super_visit_with(self)
531         }
532     }
533
534     let generics = tcx.generics_of(trait_item_def_id);
535     let predicates = tcx.predicates_of(trait_item_def_id);
536     let impl_trait_ref =
537         tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
538     let param_env = tcx.param_env(impl_def_id);
539
540     let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
541     let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
542         if pred.visit_with(&mut visitor).is_continue() {
543             Some(Obligation::new(
544                 tcx,
545                 ObligationCause::dummy_with_span(*span),
546                 param_env,
547                 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
548             ))
549         } else {
550             None
551         }
552     });
553
554     let infcx = tcx.infer_ctxt().ignoring_regions().build();
555     for obligation in predicates_for_trait {
556         // Ignore overflow error, to be conservative.
557         if let Ok(result) = infcx.evaluate_obligation(&obligation)
558             && !result.may_apply()
559         {
560             return true;
561         }
562     }
563     false
564 }
565
566 pub fn provide(providers: &mut ty::query::Providers) {
567     object_safety::provide(providers);
568     vtable::provide(providers);
569     *providers = ty::query::Providers {
570         specialization_graph_of: specialize::specialization_graph_provider,
571         specializes: specialize::specializes,
572         codegen_select_candidate: codegen::codegen_select_candidate,
573         subst_and_check_impossible_predicates,
574         is_impossible_method,
575         ..*providers
576     };
577 }