]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_trait_selection/src/traits/codegen.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_trait_selection / src / traits / codegen.rs
1 // This file contains various trait resolution methods used by codegen.
2 // They all assume regions can be erased and monomorphic types. It
3 // seems likely that they should eventually be merged into more
4 // general routines.
5
6 use crate::infer::{InferCtxt, TyCtxtInferExt};
7 use crate::traits::{
8 FulfillmentContext, ImplSource, Obligation, ObligationCause, SelectionContext, TraitEngine,
9 Unimplemented,
10 };
11 use rustc_errors::ErrorReported;
12 use rustc_middle::ty::fold::TypeFoldable;
13 use rustc_middle::ty::{self, TyCtxt};
14
15 /// Attempts to resolve an obligation to an `ImplSource`. The result is
16 /// a shallow `ImplSource` resolution, meaning that we do not
17 /// (necessarily) resolve all nested obligations on the impl. Note
18 /// that type check should guarantee to us that all nested
19 /// obligations *could be* resolved if we wanted to.
20 ///
21 /// Assumes that this is run after the entire crate has been successfully type-checked.
22 /// This also expects that `trait_ref` is fully normalized.
23 pub fn codegen_fulfill_obligation<'tcx>(
24 tcx: TyCtxt<'tcx>,
25 (param_env, trait_ref): (ty::ParamEnv<'tcx>, ty::PolyTraitRef<'tcx>),
26 ) -> Result<ImplSource<'tcx, ()>, ErrorReported> {
27 // Remove any references to regions; this helps improve caching.
28 let trait_ref = tcx.erase_regions(trait_ref);
29 // We expect the input to be fully normalized.
30 debug_assert_eq!(trait_ref, tcx.normalize_erasing_regions(param_env, trait_ref));
31 debug!(
32 "codegen_fulfill_obligation(trait_ref={:?}, def_id={:?})",
33 (param_env, trait_ref),
34 trait_ref.def_id()
35 );
36
37 // Do the initial selection for the obligation. This yields the
38 // shallow result we are looking for -- that is, what specific impl.
39 tcx.infer_ctxt().enter(|infcx| {
40 let mut selcx = SelectionContext::new(&infcx);
41
42 let obligation_cause = ObligationCause::dummy();
43 let obligation =
44 Obligation::new(obligation_cause, param_env, trait_ref.to_poly_trait_predicate());
45
46 let selection = match selcx.select(&obligation) {
47 Ok(Some(selection)) => selection,
48 Ok(None) => {
49 // Ambiguity can happen when monomorphizing during trans
50 // expands to some humongo type that never occurred
51 // statically -- this humongo type can then overflow,
52 // leading to an ambiguous result. So report this as an
53 // overflow bug, since I believe this is the only case
54 // where ambiguity can result.
55 infcx.tcx.sess.delay_span_bug(
56 rustc_span::DUMMY_SP,
57 &format!(
58 "encountered ambiguity selecting `{:?}` during codegen, presuming due to \
59 overflow or prior type error",
60 trait_ref
61 ),
62 );
63 return Err(ErrorReported);
64 }
65 Err(Unimplemented) => {
66 // This can trigger when we probe for the source of a `'static` lifetime requirement
67 // on a trait object: `impl Foo for dyn Trait {}` has an implicit `'static` bound.
68 infcx.tcx.sess.delay_span_bug(
69 rustc_span::DUMMY_SP,
70 &format!(
71 "Encountered error `Unimplemented` selecting `{:?}` during codegen",
72 trait_ref
73 ),
74 );
75 return Err(ErrorReported);
76 }
77 Err(e) => {
78 bug!("Encountered error `{:?}` selecting `{:?}` during codegen", e, trait_ref)
79 }
80 };
81
82 debug!("fulfill_obligation: selection={:?}", selection);
83
84 // Currently, we use a fulfillment context to completely resolve
85 // all nested obligations. This is because they can inform the
86 // inference of the impl's type parameters.
87 let mut fulfill_cx = FulfillmentContext::new();
88 let impl_source = selection.map(|predicate| {
89 debug!("fulfill_obligation: register_predicate_obligation {:?}", predicate);
90 fulfill_cx.register_predicate_obligation(&infcx, predicate);
91 });
92 let impl_source = drain_fulfillment_cx_or_panic(&infcx, &mut fulfill_cx, impl_source);
93
94 debug!("Cache miss: {:?} => {:?}", trait_ref, impl_source);
95 Ok(impl_source)
96 })
97 }
98
99 // # Global Cache
100
101 /// Finishes processes any obligations that remain in the
102 /// fulfillment context, and then returns the result with all type
103 /// variables removed and regions erased. Because this is intended
104 /// for use after type-check has completed, if any errors occur,
105 /// it will panic. It is used during normalization and other cases
106 /// where processing the obligations in `fulfill_cx` may cause
107 /// type inference variables that appear in `result` to be
108 /// unified, and hence we need to process those obligations to get
109 /// the complete picture of the type.
110 fn drain_fulfillment_cx_or_panic<T>(
111 infcx: &InferCtxt<'_, 'tcx>,
112 fulfill_cx: &mut FulfillmentContext<'tcx>,
113 result: T,
114 ) -> T
115 where
116 T: TypeFoldable<'tcx>,
117 {
118 debug!("drain_fulfillment_cx_or_panic()");
119
120 // In principle, we only need to do this so long as `result`
121 // contains unbound type parameters. It could be a slight
122 // optimization to stop iterating early.
123 if let Err(errors) = fulfill_cx.select_all_or_error(infcx) {
124 infcx.tcx.sess.delay_span_bug(
125 rustc_span::DUMMY_SP,
126 &format!("Encountered errors `{:?}` resolving bounds after type-checking", errors),
127 );
128 }
129
130 let result = infcx.resolve_vars_if_possible(result);
131 infcx.tcx.erase_regions(result)
132 }