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