]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/engine.rs
21516c93efb53aa8b33e681938a61c1701f54d35
[rust.git] / compiler / rustc_trait_selection / src / traits / engine.rs
1 use std::cell::RefCell;
2 use std::fmt::Debug;
3
4 use super::TraitEngine;
5 use super::{ChalkFulfillmentContext, FulfillmentContext};
6 use crate::infer::InferCtxtExt;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def_id::{DefId, LocalDefId};
9 use rustc_infer::infer::at::ToTrace;
10 use rustc_infer::infer::canonical::{
11     Canonical, CanonicalVarValues, CanonicalizedQueryResponse, QueryResponse,
12 };
13 use rustc_infer::infer::{InferCtxt, InferOk};
14 use rustc_infer::traits::query::Fallible;
15 use rustc_infer::traits::{
16     FulfillmentError, Obligation, ObligationCause, PredicateObligation, TraitEngineExt as _,
17 };
18 use rustc_middle::arena::ArenaAllocatable;
19 use rustc_middle::ty::error::TypeError;
20 use rustc_middle::ty::ToPredicate;
21 use rustc_middle::ty::TypeFoldable;
22 use rustc_middle::ty::{self, Ty, TyCtxt};
23 use rustc_span::Span;
24
25 pub trait TraitEngineExt<'tcx> {
26     fn new(tcx: TyCtxt<'tcx>) -> Box<Self>;
27     fn new_in_snapshot(tcx: TyCtxt<'tcx>) -> Box<Self>;
28 }
29
30 impl<'tcx> TraitEngineExt<'tcx> for dyn TraitEngine<'tcx> {
31     fn new(tcx: TyCtxt<'tcx>) -> Box<Self> {
32         if tcx.sess.opts.unstable_opts.chalk {
33             Box::new(ChalkFulfillmentContext::new())
34         } else {
35             Box::new(FulfillmentContext::new())
36         }
37     }
38
39     fn new_in_snapshot(tcx: TyCtxt<'tcx>) -> Box<Self> {
40         if tcx.sess.opts.unstable_opts.chalk {
41             Box::new(ChalkFulfillmentContext::new())
42         } else {
43             Box::new(FulfillmentContext::new_in_snapshot())
44         }
45     }
46 }
47
48 /// Used if you want to have pleasant experience when dealing
49 /// with obligations outside of hir or mir typeck.
50 pub struct ObligationCtxt<'a, 'tcx> {
51     pub infcx: &'a InferCtxt<'tcx>,
52     engine: RefCell<Box<dyn TraitEngine<'tcx>>>,
53 }
54
55 impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> {
56     pub fn new(infcx: &'a InferCtxt<'tcx>) -> Self {
57         Self { infcx, engine: RefCell::new(<dyn TraitEngine<'_>>::new(infcx.tcx)) }
58     }
59
60     pub fn new_in_snapshot(infcx: &'a InferCtxt<'tcx>) -> Self {
61         Self { infcx, engine: RefCell::new(<dyn TraitEngine<'_>>::new_in_snapshot(infcx.tcx)) }
62     }
63
64     pub fn register_obligation(&self, obligation: PredicateObligation<'tcx>) {
65         self.engine.borrow_mut().register_predicate_obligation(self.infcx, obligation);
66     }
67
68     pub fn register_obligations(
69         &self,
70         obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
71     ) {
72         // Can't use `register_predicate_obligations` because the iterator
73         // may also use this `ObligationCtxt`.
74         for obligation in obligations {
75             self.engine.borrow_mut().register_predicate_obligation(self.infcx, obligation)
76         }
77     }
78
79     pub fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
80         let InferOk { value, obligations } = infer_ok;
81         self.engine.borrow_mut().register_predicate_obligations(self.infcx, obligations);
82         value
83     }
84
85     /// Requires that `ty` must implement the trait with `def_id` in
86     /// the given environment. This trait must not have any type
87     /// parameters (except for `Self`).
88     pub fn register_bound(
89         &self,
90         cause: ObligationCause<'tcx>,
91         param_env: ty::ParamEnv<'tcx>,
92         ty: Ty<'tcx>,
93         def_id: DefId,
94     ) {
95         let tcx = self.infcx.tcx;
96         let trait_ref = ty::TraitRef { def_id, substs: tcx.mk_substs_trait(ty, &[]) };
97         self.register_obligation(Obligation {
98             cause,
99             recursion_depth: 0,
100             param_env,
101             predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
102         });
103     }
104
105     pub fn normalize<T: TypeFoldable<'tcx>>(
106         &self,
107         cause: ObligationCause<'tcx>,
108         param_env: ty::ParamEnv<'tcx>,
109         value: T,
110     ) -> T {
111         let infer_ok = self.infcx.partially_normalize_associated_types_in(cause, param_env, value);
112         self.register_infer_ok_obligations(infer_ok)
113     }
114
115     pub fn eq<T: ToTrace<'tcx>>(
116         &self,
117         cause: &ObligationCause<'tcx>,
118         param_env: ty::ParamEnv<'tcx>,
119         expected: T,
120         actual: T,
121     ) -> Result<(), TypeError<'tcx>> {
122         match self.infcx.at(cause, param_env).eq(expected, actual) {
123             Ok(InferOk { obligations, value: () }) => {
124                 self.register_obligations(obligations);
125                 Ok(())
126             }
127             Err(e) => Err(e),
128         }
129     }
130
131     pub fn sup<T: ToTrace<'tcx>>(
132         &self,
133         cause: &ObligationCause<'tcx>,
134         param_env: ty::ParamEnv<'tcx>,
135         expected: T,
136         actual: T,
137     ) -> Result<(), TypeError<'tcx>> {
138         match self.infcx.at(cause, param_env).sup(expected, actual) {
139             Ok(InferOk { obligations, value: () }) => {
140                 self.register_obligations(obligations);
141                 Ok(())
142             }
143             Err(e) => Err(e),
144         }
145     }
146
147     pub fn select_all_or_error(&self) -> Vec<FulfillmentError<'tcx>> {
148         self.engine.borrow_mut().select_all_or_error(self.infcx)
149     }
150
151     pub fn assumed_wf_types(
152         &self,
153         param_env: ty::ParamEnv<'tcx>,
154         span: Span,
155         def_id: LocalDefId,
156     ) -> FxHashSet<Ty<'tcx>> {
157         let tcx = self.infcx.tcx;
158         let assumed_wf_types = tcx.assumed_wf_types(def_id);
159         let mut implied_bounds = FxHashSet::default();
160         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
161         let cause = ObligationCause::misc(span, hir_id);
162         for ty in assumed_wf_types {
163             // FIXME(@lcnr): rustc currently does not check wf for types
164             // pre-normalization, meaning that implied bounds are sometimes
165             // incorrect. See #100910 for more details.
166             //
167             // Not adding the unnormalized types here mostly fixes that, except
168             // that there are projections which are still ambiguous in the item definition
169             // but do normalize successfully when using the item, see #98543.
170             //
171             // Anyways, I will hopefully soon change implied bounds to make all of this
172             // sound and then uncomment this line again.
173
174             // implied_bounds.insert(ty);
175             let normalized = self.normalize(cause.clone(), param_env, ty);
176             implied_bounds.insert(normalized);
177         }
178         implied_bounds
179     }
180
181     pub fn make_canonicalized_query_response<T>(
182         &self,
183         inference_vars: CanonicalVarValues<'tcx>,
184         answer: T,
185     ) -> Fallible<CanonicalizedQueryResponse<'tcx, T>>
186     where
187         T: Debug + TypeFoldable<'tcx>,
188         Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable<'tcx>,
189     {
190         self.infcx.make_canonicalized_query_response(
191             inference_vars,
192             answer,
193             &mut **self.engine.borrow_mut(),
194         )
195     }
196 }