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