]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/mod.rs
Auto merge of #106976 - tmiasko:borrowck-lazy-dominators, r=cjgillot
[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     /// Canonical 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     generic_bounds.into_iter().enumerate().map(move |(idx, (predicate, span))| Obligation {
119         cause: cause(idx, span),
120         recursion_depth: 0,
121         param_env,
122         predicate,
123     })
124 }
125
126 /// Determines whether the type `ty` is known to meet `bound` and
127 /// returns true if so. Returns false if `ty` either does not meet
128 /// `bound` or is not known to meet bound (note that this is
129 /// conservative towards *no impl*, which is the opposite of the
130 /// `evaluate` methods).
131 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
132     infcx: &InferCtxt<'tcx>,
133     param_env: ty::ParamEnv<'tcx>,
134     ty: Ty<'tcx>,
135     def_id: DefId,
136     span: Span,
137 ) -> bool {
138     let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
139     pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
140 }
141
142 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
143 fn pred_known_to_hold_modulo_regions<'tcx>(
144     infcx: &InferCtxt<'tcx>,
145     param_env: ty::ParamEnv<'tcx>,
146     pred: impl ToPredicate<'tcx> + TypeVisitable<'tcx>,
147     span: Span,
148 ) -> bool {
149     let has_non_region_infer = pred.has_non_region_infer();
150     let obligation = Obligation {
151         param_env,
152         // We can use a dummy node-id here because we won't pay any mind
153         // to region obligations that arise (there shouldn't really be any
154         // anyhow).
155         cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
156         recursion_depth: 0,
157         predicate: pred.to_predicate(infcx.tcx),
158     };
159
160     let result = infcx.predicate_must_hold_modulo_regions(&obligation);
161     debug!(?result);
162
163     if result && has_non_region_infer {
164         // Because of inference "guessing", selection can sometimes claim
165         // to succeed while the success requires a guess. To ensure
166         // this function's result remains infallible, we must confirm
167         // that guess. While imperfect, I believe this is sound.
168
169         // FIXME(@lcnr): this function doesn't seem right.
170         // The handling of regions in this area of the code is terrible,
171         // see issue #29149. We should be able to improve on this with
172         // NLL.
173         let errors = fully_solve_obligation(infcx, obligation);
174
175         // Note: we only assume something is `Copy` if we can
176         // *definitively* show that it implements `Copy`. Otherwise,
177         // assume it is move; linear is always ok.
178         match &errors[..] {
179             [] => true,
180             errors => {
181                 debug!(?errors);
182                 false
183             }
184         }
185     } else {
186         result
187     }
188 }
189
190 #[instrument(level = "debug", skip(tcx, elaborated_env))]
191 fn do_normalize_predicates<'tcx>(
192     tcx: TyCtxt<'tcx>,
193     cause: ObligationCause<'tcx>,
194     elaborated_env: ty::ParamEnv<'tcx>,
195     predicates: Vec<ty::Predicate<'tcx>>,
196 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
197     let span = cause.span;
198     // FIXME. We should really... do something with these region
199     // obligations. But this call just continues the older
200     // behavior (i.e., doesn't cause any new bugs), and it would
201     // take some further refactoring to actually solve them. In
202     // particular, we would have to handle implied bounds
203     // properly, and that code is currently largely confined to
204     // regionck (though I made some efforts to extract it
205     // out). -nmatsakis
206     //
207     // @arielby: In any case, these obligations are checked
208     // by wfcheck anyway, so I'm not sure we have to check
209     // them here too, and we will remove this function when
210     // we move over to lazy normalization *anyway*.
211     let infcx = tcx.infer_ctxt().ignoring_regions().build();
212     let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
213         Ok(predicates) => predicates,
214         Err(errors) => {
215             let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
216             return Err(reported);
217         }
218     };
219
220     debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
221
222     // We can use the `elaborated_env` here; the region code only
223     // cares about declarations like `'a: 'b`.
224     let outlives_env = OutlivesEnvironment::new(elaborated_env);
225
226     // FIXME: It's very weird that we ignore region obligations but apparently
227     // still need to use `resolve_regions` as we need the resolved regions in
228     // the normalized predicates.
229     let errors = infcx.resolve_regions(&outlives_env);
230     if !errors.is_empty() {
231         tcx.sess.delay_span_bug(
232             span,
233             format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
234         );
235     }
236
237     match infcx.fully_resolve(predicates) {
238         Ok(predicates) => Ok(predicates),
239         Err(fixup_err) => {
240             // If we encounter a fixup error, it means that some type
241             // variable wound up unconstrained. I actually don't know
242             // if this can happen, and I certainly don't expect it to
243             // happen often, but if it did happen it probably
244             // represents a legitimate failure due to some kind of
245             // unconstrained variable.
246             //
247             // @lcnr: Let's still ICE here for now. I want a test case
248             // for that.
249             span_bug!(
250                 span,
251                 "inference variables in normalized parameter environment: {}",
252                 fixup_err
253             );
254         }
255     }
256 }
257
258 // FIXME: this is gonna need to be removed ...
259 /// Normalizes the parameter environment, reporting errors if they occur.
260 #[instrument(level = "debug", skip(tcx))]
261 pub fn normalize_param_env_or_error<'tcx>(
262     tcx: TyCtxt<'tcx>,
263     unnormalized_env: ty::ParamEnv<'tcx>,
264     cause: ObligationCause<'tcx>,
265 ) -> ty::ParamEnv<'tcx> {
266     // I'm not wild about reporting errors here; I'd prefer to
267     // have the errors get reported at a defined place (e.g.,
268     // during typeck). Instead I have all parameter
269     // environments, in effect, going through this function
270     // and hence potentially reporting errors. This ensures of
271     // course that we never forget to normalize (the
272     // alternative seemed like it would involve a lot of
273     // manual invocations of this fn -- and then we'd have to
274     // deal with the errors at each of those sites).
275     //
276     // In any case, in practice, typeck constructs all the
277     // parameter environments once for every fn as it goes,
278     // and errors will get reported then; so outside of type inference we
279     // can be sure that no errors should occur.
280     let mut predicates: Vec<_> =
281         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
282             .map(|obligation| obligation.predicate)
283             .collect();
284
285     debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
286
287     let elaborated_env = ty::ParamEnv::new(
288         tcx.intern_predicates(&predicates),
289         unnormalized_env.reveal(),
290         unnormalized_env.constness(),
291     );
292
293     // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
294     // normalization expects its param-env to be already normalized, which means we have
295     // a circularity.
296     //
297     // The way we handle this is by normalizing the param-env inside an unnormalized version
298     // of the param-env, which means that if the param-env contains unnormalized projections,
299     // we'll have some normalization failures. This is unfortunate.
300     //
301     // Lazy normalization would basically handle this by treating just the
302     // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
303     //
304     // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
305     // types, so to make the situation less bad, we normalize all the predicates *but*
306     // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
307     // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
308     //
309     // This works fairly well because trait matching does not actually care about param-env
310     // TypeOutlives predicates - these are normally used by regionck.
311     let outlives_predicates: Vec<_> = predicates
312         .drain_filter(|predicate| {
313             matches!(
314                 predicate.kind().skip_binder(),
315                 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
316             )
317         })
318         .collect();
319
320     debug!(
321         "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
322         predicates, outlives_predicates
323     );
324     let Ok(non_outlives_predicates) = do_normalize_predicates(
325         tcx,
326         cause.clone(),
327         elaborated_env,
328         predicates,
329     ) else {
330         // An unnormalized env is better than nothing.
331         debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
332         return elaborated_env;
333     };
334
335     debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
336
337     // Not sure whether it is better to include the unnormalized TypeOutlives predicates
338     // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
339     // predicates here anyway. Keeping them here anyway because it seems safer.
340     let outlives_env: Vec<_> =
341         non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
342     let outlives_env = ty::ParamEnv::new(
343         tcx.intern_predicates(&outlives_env),
344         unnormalized_env.reveal(),
345         unnormalized_env.constness(),
346     );
347     let Ok(outlives_predicates) = do_normalize_predicates(
348         tcx,
349         cause,
350         outlives_env,
351         outlives_predicates,
352     ) else {
353         // An unnormalized env is better than nothing.
354         debug!("normalize_param_env_or_error: errored resolving outlives predicates");
355         return elaborated_env;
356     };
357     debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
358
359     let mut predicates = non_outlives_predicates;
360     predicates.extend(outlives_predicates);
361     debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
362     ty::ParamEnv::new(
363         tcx.intern_predicates(&predicates),
364         unnormalized_env.reveal(),
365         unnormalized_env.constness(),
366     )
367 }
368
369 /// Normalize a type and process all resulting obligations, returning any errors
370 #[instrument(skip_all)]
371 pub fn fully_normalize<'tcx, T>(
372     infcx: &InferCtxt<'tcx>,
373     cause: ObligationCause<'tcx>,
374     param_env: ty::ParamEnv<'tcx>,
375     value: T,
376 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
377 where
378     T: TypeFoldable<'tcx>,
379 {
380     let ocx = ObligationCtxt::new(infcx);
381     debug!(?value);
382     let normalized_value = ocx.normalize(&cause, param_env, value);
383     debug!(?normalized_value);
384     debug!("select_all_or_error start");
385     let errors = ocx.select_all_or_error();
386     if !errors.is_empty() {
387         return Err(errors);
388     }
389     debug!("select_all_or_error complete");
390     let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
391     debug!(?resolved_value);
392     Ok(resolved_value)
393 }
394
395 /// Process an obligation (and any nested obligations that come from it) to
396 /// completion, returning any errors
397 pub fn fully_solve_obligation<'tcx>(
398     infcx: &InferCtxt<'tcx>,
399     obligation: PredicateObligation<'tcx>,
400 ) -> Vec<FulfillmentError<'tcx>> {
401     fully_solve_obligations(infcx, [obligation])
402 }
403
404 /// Process a set of obligations (and any nested obligations that come from them)
405 /// to completion
406 pub fn fully_solve_obligations<'tcx>(
407     infcx: &InferCtxt<'tcx>,
408     obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
409 ) -> Vec<FulfillmentError<'tcx>> {
410     let ocx = ObligationCtxt::new(infcx);
411     ocx.register_obligations(obligations);
412     ocx.select_all_or_error()
413 }
414
415 /// Process a bound (and any nested obligations that come from it) to completion.
416 /// This is a convenience function for traits that have no generic arguments, such
417 /// as auto traits, and builtin traits like Copy or Sized.
418 pub fn fully_solve_bound<'tcx>(
419     infcx: &InferCtxt<'tcx>,
420     cause: ObligationCause<'tcx>,
421     param_env: ty::ParamEnv<'tcx>,
422     ty: Ty<'tcx>,
423     bound: DefId,
424 ) -> Vec<FulfillmentError<'tcx>> {
425     let tcx = infcx.tcx;
426     let trait_ref = tcx.mk_trait_ref(bound, [ty]);
427     let obligation = Obligation::new(tcx, cause, param_env, ty::Binder::dummy(trait_ref));
428
429     fully_solve_obligation(infcx, obligation)
430 }
431
432 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
433 /// returns true, then either normalize encountered an error or one of the predicates did not
434 /// hold. Used when creating vtables to check for unsatisfiable methods.
435 pub fn impossible_predicates<'tcx>(
436     tcx: TyCtxt<'tcx>,
437     predicates: Vec<ty::Predicate<'tcx>>,
438 ) -> bool {
439     debug!("impossible_predicates(predicates={:?})", predicates);
440
441     let infcx = tcx.infer_ctxt().build();
442     let param_env = ty::ParamEnv::reveal_all();
443     let ocx = ObligationCtxt::new(&infcx);
444     let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
445     for predicate in predicates {
446         let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
447         ocx.register_obligation(obligation);
448     }
449     let errors = ocx.select_all_or_error();
450
451     let result = !errors.is_empty();
452     debug!("impossible_predicates = {:?}", result);
453     result
454 }
455
456 fn subst_and_check_impossible_predicates<'tcx>(
457     tcx: TyCtxt<'tcx>,
458     key: (DefId, SubstsRef<'tcx>),
459 ) -> bool {
460     debug!("subst_and_check_impossible_predicates(key={:?})", key);
461
462     let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
463
464     // Specifically check trait fulfillment to avoid an error when trying to resolve
465     // associated items.
466     if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
467         let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
468         predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
469     }
470
471     predicates.retain(|predicate| !predicate.needs_subst());
472     let result = impossible_predicates(tcx, predicates);
473
474     debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
475     result
476 }
477
478 /// Checks whether a trait's method is impossible to call on a given impl.
479 ///
480 /// This only considers predicates that reference the impl's generics, and not
481 /// those that reference the method's generics.
482 fn is_impossible_method(tcx: TyCtxt<'_>, (impl_def_id, trait_item_def_id): (DefId, DefId)) -> bool {
483     struct ReferencesOnlyParentGenerics<'tcx> {
484         tcx: TyCtxt<'tcx>,
485         generics: &'tcx ty::Generics,
486         trait_item_def_id: DefId,
487     }
488     impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
489         type BreakTy = ();
490         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
491             // If this is a parameter from the trait item's own generics, then bail
492             if let ty::Param(param) = t.kind()
493                 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
494                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
495             {
496                 return ControlFlow::Break(());
497             }
498             t.super_visit_with(self)
499         }
500         fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
501             if let ty::ReEarlyBound(param) = r.kind()
502                 && let param_def_id = self.generics.region_param(&param, self.tcx).def_id
503                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
504             {
505                 return ControlFlow::Break(());
506             }
507             r.super_visit_with(self)
508         }
509         fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
510             if let ty::ConstKind::Param(param) = ct.kind()
511                 && let param_def_id = self.generics.const_param(&param, self.tcx).def_id
512                 && self.tcx.parent(param_def_id) == self.trait_item_def_id
513             {
514                 return ControlFlow::Break(());
515             }
516             ct.super_visit_with(self)
517         }
518     }
519
520     let generics = tcx.generics_of(trait_item_def_id);
521     let predicates = tcx.predicates_of(trait_item_def_id);
522     let impl_trait_ref = tcx
523         .impl_trait_ref(impl_def_id)
524         .expect("expected impl to correspond to trait")
525         .subst_identity();
526     let param_env = tcx.param_env(impl_def_id);
527
528     let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
529     let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
530         if pred.visit_with(&mut visitor).is_continue() {
531             Some(Obligation::new(
532                 tcx,
533                 ObligationCause::dummy_with_span(*span),
534                 param_env,
535                 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
536             ))
537         } else {
538             None
539         }
540     });
541
542     let infcx = tcx.infer_ctxt().ignoring_regions().build();
543     for obligation in predicates_for_trait {
544         // Ignore overflow error, to be conservative.
545         if let Ok(result) = infcx.evaluate_obligation(&obligation)
546             && !result.may_apply()
547         {
548             return true;
549         }
550     }
551     false
552 }
553
554 pub fn provide(providers: &mut ty::query::Providers) {
555     object_safety::provide(providers);
556     vtable::provide(providers);
557     *providers = ty::query::Providers {
558         specialization_graph_of: specialize::specialization_graph_provider,
559         specializes: specialize::specializes,
560         subst_and_check_impossible_predicates,
561         is_impossible_method,
562         ..*providers
563     };
564 }