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