]> git.lizzy.rs Git - rust.git/blob - src/librustc_trait_selection/traits/mod.rs
make `to_predicate` take a `tcx` argument
[rust.git] / src / librustc_trait_selection / 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 #[allow(dead_code)]
6 pub mod auto_trait;
7 mod chalk_fulfill;
8 pub mod codegen;
9 mod coherence;
10 mod engine;
11 pub mod error_reporting;
12 mod fulfill;
13 pub mod misc;
14 mod object_safety;
15 mod on_unimplemented;
16 mod project;
17 pub mod query;
18 mod select;
19 mod specialize;
20 mod structural_match;
21 mod util;
22 pub mod wf;
23
24 use crate::infer::outlives::env::OutlivesEnvironment;
25 use crate::infer::{InferCtxt, RegionckMode, TyCtxtInferExt};
26 use crate::traits::error_reporting::InferCtxtExt as _;
27 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
28 use rustc_errors::ErrorReported;
29 use rustc_hir as hir;
30 use rustc_hir::def_id::DefId;
31 use rustc_middle::middle::region;
32 use rustc_middle::ty::fold::TypeFoldable;
33 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
34 use rustc_middle::ty::{
35     self, GenericParamDefKind, ParamEnv, ToPredicate, Ty, TyCtxt, WithConstness,
36 };
37 use rustc_span::Span;
38
39 use std::fmt::Debug;
40
41 pub use self::FulfillmentErrorCode::*;
42 pub use self::ObligationCauseCode::*;
43 pub use self::SelectionError::*;
44 pub use self::Vtable::*;
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::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::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
55 pub use self::project::{
56     normalize, normalize_projection_type, normalize_to, poly_project_and_unify_type,
57 };
58 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
59 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
60 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
61 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
62 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
63 pub use self::structural_match::search_for_structural_match_violation;
64 pub use self::structural_match::type_marked_structural;
65 pub use self::structural_match::NonStructuralMatchTy;
66 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
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, 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 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
81 pub enum SkipLeakCheck {
82     Yes,
83     No,
84 }
85
86 impl SkipLeakCheck {
87     fn is_yes(self) -> bool {
88         self == SkipLeakCheck::Yes
89     }
90 }
91
92 /// The "default" for skip-leak-check corresponds to the current
93 /// behavior (do not skip the leak check) -- not the behavior we are
94 /// transitioning into.
95 impl Default for SkipLeakCheck {
96     fn default() -> Self {
97         SkipLeakCheck::No
98     }
99 }
100
101 /// The mode that trait queries run in.
102 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
103 pub enum TraitQueryMode {
104     // Standard/un-canonicalized queries get accurate
105     // spans etc. passed in and hence can do reasonable
106     // error reporting on their own.
107     Standard,
108     // Canonicalized queries get dummy spans and hence
109     // must generally propagate errors to
110     // pre-canonicalization callsites.
111     Canonical,
112 }
113
114 /// Creates predicate obligations from the generic bounds.
115 pub fn predicates_for_generics<'tcx>(
116     cause: ObligationCause<'tcx>,
117     param_env: ty::ParamEnv<'tcx>,
118     generic_bounds: ty::InstantiatedPredicates<'tcx>,
119 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
120     util::predicates_for_generics(cause, 0, param_env, generic_bounds)
121 }
122
123 /// Determines whether the type `ty` is known to meet `bound` and
124 /// returns true if so. Returns false if `ty` either does not meet
125 /// `bound` or is not known to meet bound (note that this is
126 /// conservative towards *no impl*, which is the opposite of the
127 /// `evaluate` methods).
128 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
129     infcx: &InferCtxt<'a, 'tcx>,
130     param_env: ty::ParamEnv<'tcx>,
131     ty: Ty<'tcx>,
132     def_id: DefId,
133     span: Span,
134 ) -> bool {
135     debug!(
136         "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
137         ty,
138         infcx.tcx.def_path_str(def_id)
139     );
140
141     let trait_ref = ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) };
142     let obligation = Obligation {
143         param_env,
144         cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
145         recursion_depth: 0,
146         predicate: trait_ref.without_const().to_predicate(infcx.tcx),
147     };
148
149     let result = infcx.predicate_must_hold_modulo_regions(&obligation);
150     debug!(
151         "type_known_to_meet_ty={:?} bound={} => {:?}",
152         ty,
153         infcx.tcx.def_path_str(def_id),
154         result
155     );
156
157     if result && ty.has_infer_types_or_consts() {
158         // Because of inference "guessing", selection can sometimes claim
159         // to succeed while the success requires a guess. To ensure
160         // this function's result remains infallible, we must confirm
161         // that guess. While imperfect, I believe this is sound.
162
163         // The handling of regions in this area of the code is terrible,
164         // see issue #29149. We should be able to improve on this with
165         // NLL.
166         let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
167
168         // We can use a dummy node-id here because we won't pay any mind
169         // to region obligations that arise (there shouldn't really be any
170         // anyhow).
171         let cause = ObligationCause::misc(span, hir::CRATE_HIR_ID);
172
173         fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
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 fulfill_cx.select_all_or_error(infcx) {
179             Ok(()) => {
180                 debug!(
181                     "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
182                     ty,
183                     infcx.tcx.def_path_str(def_id)
184                 );
185                 true
186             }
187             Err(e) => {
188                 debug!(
189                     "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
190                     ty,
191                     infcx.tcx.def_path_str(def_id),
192                     e
193                 );
194                 false
195             }
196         }
197     } else {
198         result
199     }
200 }
201
202 fn do_normalize_predicates<'tcx>(
203     tcx: TyCtxt<'tcx>,
204     region_context: DefId,
205     cause: ObligationCause<'tcx>,
206     elaborated_env: ty::ParamEnv<'tcx>,
207     predicates: Vec<ty::Predicate<'tcx>>,
208 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
209     debug!(
210         "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
211         predicates, region_context, cause,
212     );
213     let span = cause.span;
214     tcx.infer_ctxt().enter(|infcx| {
215         // FIXME. We should really... do something with these region
216         // obligations. But this call just continues the older
217         // behavior (i.e., doesn't cause any new bugs), and it would
218         // take some further refactoring to actually solve them. In
219         // particular, we would have to handle implied bounds
220         // properly, and that code is currently largely confined to
221         // regionck (though I made some efforts to extract it
222         // out). -nmatsakis
223         //
224         // @arielby: In any case, these obligations are checked
225         // by wfcheck anyway, so I'm not sure we have to check
226         // them here too, and we will remove this function when
227         // we move over to lazy normalization *anyway*.
228         let fulfill_cx = FulfillmentContext::new_ignoring_regions();
229         let predicates =
230             match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, &predicates) {
231                 Ok(predicates) => predicates,
232                 Err(errors) => {
233                     infcx.report_fulfillment_errors(&errors, None, false);
234                     return Err(ErrorReported);
235                 }
236             };
237
238         debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
239
240         let region_scope_tree = region::ScopeTree::default();
241
242         // We can use the `elaborated_env` here; the region code only
243         // cares about declarations like `'a: 'b`.
244         let outlives_env = OutlivesEnvironment::new(elaborated_env);
245
246         infcx.resolve_regions_and_report_errors(
247             region_context,
248             &region_scope_tree,
249             &outlives_env,
250             RegionckMode::default(),
251         );
252
253         let predicates = match infcx.fully_resolve(&predicates) {
254             Ok(predicates) => predicates,
255             Err(fixup_err) => {
256                 // If we encounter a fixup error, it means that some type
257                 // variable wound up unconstrained. I actually don't know
258                 // if this can happen, and I certainly don't expect it to
259                 // happen often, but if it did happen it probably
260                 // represents a legitimate failure due to some kind of
261                 // unconstrained variable, and it seems better not to ICE,
262                 // all things considered.
263                 tcx.sess.span_err(span, &fixup_err.to_string());
264                 return Err(ErrorReported);
265             }
266         };
267         if predicates.needs_infer() {
268             tcx.sess.delay_span_bug(span, "encountered inference variables after `fully_resolve`");
269             Err(ErrorReported)
270         } else {
271             Ok(predicates)
272         }
273     })
274 }
275
276 // FIXME: this is gonna need to be removed ...
277 /// Normalizes the parameter environment, reporting errors if they occur.
278 pub fn normalize_param_env_or_error<'tcx>(
279     tcx: TyCtxt<'tcx>,
280     region_context: DefId,
281     unnormalized_env: ty::ParamEnv<'tcx>,
282     cause: ObligationCause<'tcx>,
283 ) -> ty::ParamEnv<'tcx> {
284     // I'm not wild about reporting errors here; I'd prefer to
285     // have the errors get reported at a defined place (e.g.,
286     // during typeck). Instead I have all parameter
287     // environments, in effect, going through this function
288     // and hence potentially reporting errors. This ensures of
289     // course that we never forget to normalize (the
290     // alternative seemed like it would involve a lot of
291     // manual invocations of this fn -- and then we'd have to
292     // deal with the errors at each of those sites).
293     //
294     // In any case, in practice, typeck constructs all the
295     // parameter environments once for every fn as it goes,
296     // and errors will get reported then; so after typeck we
297     // can be sure that no errors should occur.
298
299     debug!(
300         "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
301         region_context, unnormalized_env, cause
302     );
303
304     let mut predicates: Vec<_> =
305         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.into_iter().cloned())
306             .map(|obligation| obligation.predicate)
307             .collect();
308
309     debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
310
311     let elaborated_env = ty::ParamEnv::new(
312         tcx.intern_predicates(&predicates),
313         unnormalized_env.reveal,
314         unnormalized_env.def_id,
315     );
316
317     // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
318     // normalization expects its param-env to be already normalized, which means we have
319     // a circularity.
320     //
321     // The way we handle this is by normalizing the param-env inside an unnormalized version
322     // of the param-env, which means that if the param-env contains unnormalized projections,
323     // we'll have some normalization failures. This is unfortunate.
324     //
325     // Lazy normalization would basically handle this by treating just the
326     // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
327     //
328     // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
329     // types, so to make the situation less bad, we normalize all the predicates *but*
330     // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
331     // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
332     //
333     // This works fairly well because trait matching  does not actually care about param-env
334     // TypeOutlives predicates - these are normally used by regionck.
335     let outlives_predicates: Vec<_> = predicates
336         .drain_filter(|predicate| match predicate {
337             ty::PredicateKind::TypeOutlives(..) => true,
338             _ => false,
339         })
340         .collect();
341
342     debug!(
343         "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
344         predicates, outlives_predicates
345     );
346     let non_outlives_predicates = match do_normalize_predicates(
347         tcx,
348         region_context,
349         cause.clone(),
350         elaborated_env,
351         predicates,
352     ) {
353         Ok(predicates) => predicates,
354         // An unnormalized env is better than nothing.
355         Err(ErrorReported) => {
356             debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
357             return elaborated_env;
358         }
359     };
360
361     debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
362
363     // Not sure whether it is better to include the unnormalized TypeOutlives predicates
364     // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
365     // predicates here anyway. Keeping them here anyway because it seems safer.
366     let outlives_env: Vec<_> =
367         non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
368     let outlives_env =
369         ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal, None);
370     let outlives_predicates = match do_normalize_predicates(
371         tcx,
372         region_context,
373         cause,
374         outlives_env,
375         outlives_predicates,
376     ) {
377         Ok(predicates) => predicates,
378         // An unnormalized env is better than nothing.
379         Err(ErrorReported) => {
380             debug!("normalize_param_env_or_error: errored resolving outlives predicates");
381             return elaborated_env;
382         }
383     };
384     debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
385
386     let mut predicates = non_outlives_predicates;
387     predicates.extend(outlives_predicates);
388     debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
389     ty::ParamEnv::new(
390         tcx.intern_predicates(&predicates),
391         unnormalized_env.reveal,
392         unnormalized_env.def_id,
393     )
394 }
395
396 pub fn fully_normalize<'a, 'tcx, T>(
397     infcx: &InferCtxt<'a, 'tcx>,
398     mut fulfill_cx: FulfillmentContext<'tcx>,
399     cause: ObligationCause<'tcx>,
400     param_env: ty::ParamEnv<'tcx>,
401     value: &T,
402 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
403 where
404     T: TypeFoldable<'tcx>,
405 {
406     debug!("fully_normalize_with_fulfillcx(value={:?})", value);
407     let selcx = &mut SelectionContext::new(infcx);
408     let Normalized { value: normalized_value, obligations } =
409         project::normalize(selcx, param_env, cause, value);
410     debug!(
411         "fully_normalize: normalized_value={:?} obligations={:?}",
412         normalized_value, obligations
413     );
414     for obligation in obligations {
415         fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
416     }
417
418     debug!("fully_normalize: select_all_or_error start");
419     fulfill_cx.select_all_or_error(infcx)?;
420     debug!("fully_normalize: select_all_or_error complete");
421     let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
422     debug!("fully_normalize: resolved_value={:?}", resolved_value);
423     Ok(resolved_value)
424 }
425
426 /// Normalizes the predicates and checks whether they hold in an empty
427 /// environment. If this returns false, then either normalize
428 /// encountered an error or one of the predicates did not hold. Used
429 /// when creating vtables to check for unsatisfiable methods.
430 pub fn normalize_and_test_predicates<'tcx>(
431     tcx: TyCtxt<'tcx>,
432     predicates: Vec<ty::Predicate<'tcx>>,
433 ) -> bool {
434     debug!("normalize_and_test_predicates(predicates={:?})", predicates);
435
436     let result = tcx.infer_ctxt().enter(|infcx| {
437         let param_env = ty::ParamEnv::reveal_all();
438         let mut selcx = SelectionContext::new(&infcx);
439         let mut fulfill_cx = FulfillmentContext::new();
440         let cause = ObligationCause::dummy();
441         let Normalized { value: predicates, obligations } =
442             normalize(&mut selcx, param_env, cause.clone(), &predicates);
443         for obligation in obligations {
444             fulfill_cx.register_predicate_obligation(&infcx, obligation);
445         }
446         for predicate in predicates {
447             let obligation = Obligation::new(cause.clone(), param_env, predicate);
448             fulfill_cx.register_predicate_obligation(&infcx, obligation);
449         }
450
451         fulfill_cx.select_all_or_error(&infcx).is_ok()
452     });
453     debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", predicates, result);
454     result
455 }
456
457 fn substitute_normalize_and_test_predicates<'tcx>(
458     tcx: TyCtxt<'tcx>,
459     key: (DefId, SubstsRef<'tcx>),
460 ) -> bool {
461     debug!("substitute_normalize_and_test_predicates(key={:?})", key);
462
463     let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
464     let result = normalize_and_test_predicates(tcx, predicates);
465
466     debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", key, result);
467     result
468 }
469
470 /// Given a trait `trait_ref`, iterates the vtable entries
471 /// that come from `trait_ref`, including its supertraits.
472 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
473 fn vtable_methods<'tcx>(
474     tcx: TyCtxt<'tcx>,
475     trait_ref: ty::PolyTraitRef<'tcx>,
476 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
477     debug!("vtable_methods({:?})", trait_ref);
478
479     tcx.arena.alloc_from_iter(supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
480         let trait_methods = tcx
481             .associated_items(trait_ref.def_id())
482             .in_definition_order()
483             .filter(|item| item.kind == ty::AssocKind::Fn);
484
485         // Now list each method's DefId and InternalSubsts (for within its trait).
486         // If the method can never be called from this object, produce None.
487         trait_methods.map(move |trait_method| {
488             debug!("vtable_methods: trait_method={:?}", trait_method);
489             let def_id = trait_method.def_id;
490
491             // Some methods cannot be called on an object; skip those.
492             if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
493                 debug!("vtable_methods: not vtable safe");
494                 return None;
495             }
496
497             // The method may have some early-bound lifetimes; add regions for those.
498             let substs = trait_ref.map_bound(|trait_ref| {
499                 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
500                     GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
501                     GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
502                         trait_ref.substs[param.index as usize]
503                     }
504                 })
505             });
506
507             // The trait type may have higher-ranked lifetimes in it;
508             // erase them if they appear, so that we get the type
509             // at some particular call site.
510             let substs =
511                 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &substs);
512
513             // It's possible that the method relies on where-clauses that
514             // do not hold for this particular set of type parameters.
515             // Note that this method could then never be called, so we
516             // do not want to try and codegen it, in that case (see #23435).
517             let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
518             if !normalize_and_test_predicates(tcx, predicates.predicates) {
519                 debug!("vtable_methods: predicates do not hold");
520                 return None;
521             }
522
523             Some((def_id, substs))
524         })
525     }))
526 }
527
528 /// Check whether a `ty` implements given trait(trait_def_id).
529 ///
530 /// NOTE: Always return `false` for a type which needs inference.
531 fn type_implements_trait<'tcx>(
532     tcx: TyCtxt<'tcx>,
533     key: (
534         DefId,    // trait_def_id,
535         Ty<'tcx>, // type
536         SubstsRef<'tcx>,
537         ParamEnv<'tcx>,
538     ),
539 ) -> bool {
540     let (trait_def_id, ty, params, param_env) = key;
541
542     debug!(
543         "type_implements_trait: trait_def_id={:?}, type={:?}, params={:?}, param_env={:?}",
544         trait_def_id, ty, params, param_env
545     );
546
547     // Do not check on infer_types to avoid panic in evaluate_obligation.
548     if ty.has_infer_types() {
549         return false;
550     }
551
552     let ty = tcx.erase_regions(&ty);
553
554     let trait_ref = ty::TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(ty, params) };
555
556     let obligation = Obligation {
557         cause: ObligationCause::dummy(),
558         param_env,
559         recursion_depth: 0,
560         predicate: trait_ref.without_const().to_predicate(tcx),
561     };
562     tcx.infer_ctxt().enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
563 }
564
565 pub fn provide(providers: &mut ty::query::Providers<'_>) {
566     object_safety::provide(providers);
567     *providers = ty::query::Providers {
568         specialization_graph_of: specialize::specialization_graph_provider,
569         specializes: specialize::specializes,
570         codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
571         vtable_methods,
572         substitute_normalize_and_test_predicates,
573         type_implements_trait,
574         ..*providers
575     };
576 }