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