]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/autoderef.rs
Rollup merge of #63416 - RalfJung:apfloat, r=eddyb
[rust.git] / src / librustc_typeck / check / autoderef.rs
1 use super::{FnCtxt, PlaceOp, Needs};
2 use super::method::MethodCallee;
3
4 use rustc::hir;
5 use rustc::infer::{InferCtxt, InferOk};
6 use rustc::session::DiagnosticMessageId;
7 use rustc::traits::{self, TraitEngine};
8 use rustc::ty::{self, Ty, TyCtxt, TraitRef};
9 use rustc::ty::{ToPredicate, TypeFoldable};
10 use rustc::ty::adjustment::{Adjustment, Adjust, OverloadedDeref};
11
12 use syntax_pos::Span;
13 use syntax::ast::Ident;
14
15 use std::iter;
16
17 #[derive(Copy, Clone, Debug)]
18 enum AutoderefKind {
19     Builtin,
20     Overloaded,
21 }
22
23 pub struct Autoderef<'a, 'tcx> {
24     infcx: &'a InferCtxt<'a, 'tcx>,
25     body_id: hir::HirId,
26     param_env: ty::ParamEnv<'tcx>,
27     steps: Vec<(Ty<'tcx>, AutoderefKind)>,
28     cur_ty: Ty<'tcx>,
29     obligations: Vec<traits::PredicateObligation<'tcx>>,
30     at_start: bool,
31     include_raw_pointers: bool,
32     span: Span,
33     silence_errors: bool,
34     reached_recursion_limit: bool,
35 }
36
37 impl<'a, 'tcx> Iterator for Autoderef<'a, 'tcx> {
38     type Item = (Ty<'tcx>, usize);
39
40     fn next(&mut self) -> Option<Self::Item> {
41         let tcx = self.infcx.tcx;
42
43         debug!("autoderef: steps={:?}, cur_ty={:?}",
44                self.steps,
45                self.cur_ty);
46         if self.at_start {
47             self.at_start = false;
48             debug!("autoderef stage #0 is {:?}", self.cur_ty);
49             return Some((self.cur_ty, 0));
50         }
51
52         if self.steps.len() >= *tcx.sess.recursion_limit.get() {
53             if !self.silence_errors {
54                 report_autoderef_recursion_limit_error(tcx, self.span, self.cur_ty);
55             }
56             self.reached_recursion_limit = true;
57             return None;
58         }
59
60         if self.cur_ty.is_ty_var() {
61             return None;
62         }
63
64         // Otherwise, deref if type is derefable:
65         let (kind, new_ty) =
66             if let Some(mt) = self.cur_ty.builtin_deref(self.include_raw_pointers) {
67                 (AutoderefKind::Builtin, mt.ty)
68             } else {
69                 let ty = self.overloaded_deref_ty(self.cur_ty)?;
70                 (AutoderefKind::Overloaded, ty)
71             };
72
73         if new_ty.references_error() {
74             return None;
75         }
76
77         self.steps.push((self.cur_ty, kind));
78         debug!("autoderef stage #{:?} is {:?} from {:?}",
79                self.steps.len(),
80                new_ty,
81                (self.cur_ty, kind));
82         self.cur_ty = new_ty;
83
84         Some((self.cur_ty, self.steps.len()))
85     }
86 }
87
88 impl<'a, 'tcx> Autoderef<'a, 'tcx> {
89     pub fn new(
90         infcx: &'a InferCtxt<'a, 'tcx>,
91         param_env: ty::ParamEnv<'tcx>,
92         body_id: hir::HirId,
93         span: Span,
94         base_ty: Ty<'tcx>,
95     ) -> Autoderef<'a, 'tcx> {
96         Autoderef {
97             infcx,
98             body_id,
99             param_env,
100             steps: vec![],
101             cur_ty: infcx.resolve_vars_if_possible(&base_ty),
102             obligations: vec![],
103             at_start: true,
104             include_raw_pointers: false,
105             silence_errors: false,
106             reached_recursion_limit: false,
107             span,
108         }
109     }
110
111     fn overloaded_deref_ty(&mut self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
112         debug!("overloaded_deref_ty({:?})", ty);
113
114         let tcx = self.infcx.tcx;
115
116         // <cur_ty as Deref>
117         let trait_ref = TraitRef {
118             def_id: tcx.lang_items().deref_trait()?,
119             substs: tcx.mk_substs_trait(self.cur_ty, &[]),
120         };
121
122         let cause = traits::ObligationCause::misc(self.span, self.body_id);
123
124         let obligation = traits::Obligation::new(cause.clone(),
125                                                  self.param_env,
126                                                  trait_ref.to_predicate());
127         if !self.infcx.predicate_may_hold(&obligation) {
128             debug!("overloaded_deref_ty: cannot match obligation");
129             return None;
130         }
131
132         let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
133         let normalized_ty = fulfillcx.normalize_projection_type(
134             &self.infcx,
135             self.param_env,
136             ty::ProjectionTy::from_ref_and_name(
137                 tcx,
138                 trait_ref,
139                 Ident::from_str("Target"),
140             ),
141             cause);
142         if let Err(e) = fulfillcx.select_where_possible(&self.infcx) {
143             // This shouldn't happen, except for evaluate/fulfill mismatches,
144             // but that's not a reason for an ICE (`predicate_may_hold` is conservative
145             // by design).
146             debug!("overloaded_deref_ty: encountered errors {:?} while fulfilling",
147                    e);
148             return None;
149         }
150         let obligations = fulfillcx.pending_obligations();
151         debug!("overloaded_deref_ty({:?}) = ({:?}, {:?})",
152                ty, normalized_ty, obligations);
153         self.obligations.extend(obligations);
154
155         Some(self.infcx.resolve_vars_if_possible(&normalized_ty))
156     }
157
158     /// Returns the final type, generating an error if it is an
159     /// unresolved inference variable.
160     pub fn unambiguous_final_ty(&self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
161         fcx.structurally_resolved_type(self.span, self.cur_ty)
162     }
163
164     /// Returns the final type we ended up with, which may well be an
165     /// inference variable (we will resolve it first, if possible).
166     pub fn maybe_ambiguous_final_ty(&self) -> Ty<'tcx> {
167         self.infcx.resolve_vars_if_possible(&self.cur_ty)
168     }
169
170     pub fn step_count(&self) -> usize {
171         self.steps.len()
172     }
173
174     /// Returns the adjustment steps.
175     pub fn adjust_steps(&self, fcx: &FnCtxt<'a, 'tcx>, needs: Needs) -> Vec<Adjustment<'tcx>> {
176         fcx.register_infer_ok_obligations(self.adjust_steps_as_infer_ok(fcx, needs))
177     }
178
179     pub fn adjust_steps_as_infer_ok(
180         &self,
181         fcx: &FnCtxt<'a, 'tcx>,
182         needs: Needs,
183     ) -> InferOk<'tcx, Vec<Adjustment<'tcx>>> {
184         let mut obligations = vec![];
185         let targets = self.steps.iter().skip(1).map(|&(ty, _)| ty)
186             .chain(iter::once(self.cur_ty));
187         let steps: Vec<_> = self.steps.iter().map(|&(source, kind)| {
188             if let AutoderefKind::Overloaded = kind {
189                 fcx.try_overloaded_deref(self.span, source, needs)
190                     .and_then(|InferOk { value: method, obligations: o }| {
191                         obligations.extend(o);
192                         if let ty::Ref(region, _, mutbl) = method.sig.output().kind {
193                             Some(OverloadedDeref {
194                                 region,
195                                 mutbl,
196                             })
197                         } else {
198                             None
199                         }
200                     })
201             } else {
202                 None
203             }
204         }).zip(targets).map(|(autoderef, target)| {
205             Adjustment {
206                 kind: Adjust::Deref(autoderef),
207                 target
208             }
209         }).collect();
210
211         InferOk {
212             obligations,
213             value: steps
214         }
215     }
216
217     /// also dereference through raw pointer types
218     /// e.g., assuming ptr_to_Foo is the type `*const Foo`
219     /// fcx.autoderef(span, ptr_to_Foo)  => [*const Foo]
220     /// fcx.autoderef(span, ptr_to_Foo).include_raw_ptrs() => [*const Foo, Foo]
221     pub fn include_raw_pointers(mut self) -> Self {
222         self.include_raw_pointers = true;
223         self
224     }
225
226     pub fn silence_errors(mut self) -> Self {
227         self.silence_errors = true;
228         self
229     }
230
231     pub fn reached_recursion_limit(&self) -> bool {
232         self.reached_recursion_limit
233     }
234
235     pub fn finalize(self, fcx: &FnCtxt<'a, 'tcx>) {
236         fcx.register_predicates(self.into_obligations());
237     }
238
239     pub fn into_obligations(self) -> Vec<traits::PredicateObligation<'tcx>> {
240         self.obligations
241     }
242 }
243
244 pub fn report_autoderef_recursion_limit_error<'tcx>(tcx: TyCtxt<'tcx>, span: Span, ty: Ty<'tcx>) {
245     // We've reached the recursion limit, error gracefully.
246     let suggested_limit = *tcx.sess.recursion_limit.get() * 2;
247     let msg = format!("reached the recursion limit while auto-dereferencing `{:?}`",
248                       ty);
249     let error_id = (DiagnosticMessageId::ErrorId(55), Some(span), msg);
250     let fresh = tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
251     if fresh {
252         struct_span_err!(tcx.sess,
253                          span,
254                          E0055,
255                          "reached the recursion limit while auto-dereferencing `{:?}`",
256                          ty)
257             .span_label(span, "deref recursion limit reached")
258             .help(&format!(
259                 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
260                 suggested_limit))
261             .emit();
262     }
263 }
264
265 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
266     pub fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'tcx> {
267         Autoderef::new(self, self.param_env, self.body_id, span, base_ty)
268     }
269
270     pub fn try_overloaded_deref(&self,
271                                 span: Span,
272                                 base_ty: Ty<'tcx>,
273                                 needs: Needs)
274                                 -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
275         self.try_overloaded_place_op(span, base_ty, &[], needs, PlaceOp::Deref)
276     }
277 }