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