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