1 use super::{FnCtxt, PlaceOp, Needs};
2 use super::method::MethodCallee;
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};
13 use syntax::ast::Ident;
17 #[derive(Copy, Clone, Debug)]
23 pub struct Autoderef<'a, 'gcx: 'tcx, 'tcx: 'a> {
24 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
26 param_env: ty::ParamEnv<'tcx>,
27 steps: Vec<(Ty<'tcx>, AutoderefKind)>,
29 obligations: Vec<traits::PredicateObligation<'tcx>>,
31 include_raw_pointers: bool,
34 reached_recursion_limit: bool
37 impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> {
38 type Item = (Ty<'tcx>, usize);
40 fn next(&mut self) -> Option<Self::Item> {
41 let tcx = self.infcx.tcx;
43 debug!("autoderef: steps={:?}, cur_ty={:?}",
47 self.at_start = false;
48 debug!("autoderef stage #0 is {:?}", self.cur_ty);
49 return Some((self.cur_ty, 0));
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);
56 self.reached_recursion_limit = true;
60 if self.cur_ty.is_ty_var() {
64 // Otherwise, deref if type is derefable:
66 if let Some(mt) = self.cur_ty.builtin_deref(self.include_raw_pointers) {
67 (AutoderefKind::Builtin, mt.ty)
69 let ty = self.overloaded_deref_ty(self.cur_ty)?;
70 (AutoderefKind::Overloaded, ty)
73 if new_ty.references_error() {
77 self.steps.push((self.cur_ty, kind));
78 debug!("autoderef stage #{:?} is {:?} from {:?}",
84 Some((self.cur_ty, self.steps.len()))
88 impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> {
89 pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
90 param_env: ty::ParamEnv<'tcx>,
94 -> Autoderef<'a, 'gcx, 'tcx>
101 cur_ty: infcx.resolve_vars_if_possible(&base_ty),
104 include_raw_pointers: false,
105 silence_errors: false,
106 reached_recursion_limit: false,
111 fn overloaded_deref_ty(&mut self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
112 debug!("overloaded_deref_ty({:?})", ty);
114 let tcx = self.infcx.tcx;
117 let trait_ref = TraitRef {
118 def_id: tcx.lang_items().deref_trait()?,
119 substs: tcx.mk_substs_trait(self.cur_ty, &[]),
122 let cause = traits::ObligationCause::misc(self.span, self.body_id);
124 let obligation = traits::Obligation::new(cause.clone(),
126 trait_ref.to_predicate());
127 if !self.infcx.predicate_may_hold(&obligation) {
128 debug!("overloaded_deref_ty: cannot match obligation");
132 let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
133 let normalized_ty = fulfillcx.normalize_projection_type(
136 ty::ProjectionTy::from_ref_and_name(
139 Ident::from_str("Target"),
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
146 debug!("overloaded_deref_ty: encountered errors {:?} while fulfilling",
150 let obligations = fulfillcx.pending_obligations();
151 debug!("overloaded_deref_ty({:?}) = ({:?}, {:?})",
152 ty, normalized_ty, obligations);
153 self.obligations.extend(obligations);
155 Some(self.infcx.resolve_vars_if_possible(&normalized_ty))
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, 'gcx, 'tcx>) -> Ty<'tcx> {
161 fcx.structurally_resolved_type(self.span, self.cur_ty)
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)
170 pub fn step_count(&self) -> usize {
174 /// Returns the adjustment steps.
175 pub fn adjust_steps(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, needs: Needs)
176 -> Vec<Adjustment<'tcx>> {
177 fcx.register_infer_ok_obligations(self.adjust_steps_as_infer_ok(fcx, needs))
180 pub fn adjust_steps_as_infer_ok(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, needs: Needs)
181 -> InferOk<'tcx, Vec<Adjustment<'tcx>>> {
182 let mut obligations = vec![];
183 let targets = self.steps.iter().skip(1).map(|&(ty, _)| ty)
184 .chain(iter::once(self.cur_ty));
185 let steps: Vec<_> = self.steps.iter().map(|&(source, kind)| {
186 if let AutoderefKind::Overloaded = kind {
187 fcx.try_overloaded_deref(self.span, source, needs)
188 .and_then(|InferOk { value: method, obligations: o }| {
189 obligations.extend(o);
190 if let ty::Ref(region, _, mutbl) = method.sig.output().sty {
191 Some(OverloadedDeref {
202 }).zip(targets).map(|(autoderef, target)| {
204 kind: Adjust::Deref(autoderef),
215 /// also dereference through raw pointer types
216 /// e.g., assuming ptr_to_Foo is the type `*const Foo`
217 /// fcx.autoderef(span, ptr_to_Foo) => [*const Foo]
218 /// fcx.autoderef(span, ptr_to_Foo).include_raw_ptrs() => [*const Foo, Foo]
219 pub fn include_raw_pointers(mut self) -> Self {
220 self.include_raw_pointers = true;
224 pub fn silence_errors(mut self) -> Self {
225 self.silence_errors = true;
229 pub fn reached_recursion_limit(&self) -> bool {
230 self.reached_recursion_limit
233 pub fn finalize(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
234 fcx.register_predicates(self.into_obligations());
237 pub fn into_obligations(self) -> Vec<traits::PredicateObligation<'tcx>> {
242 pub fn report_autoderef_recursion_limit_error<'a, 'gcx, 'tcx>(
243 tcx: TyCtxt<'a, 'gcx, '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 `{:?}`",
249 let error_id = (DiagnosticMessageId::ErrorId(55), Some(span), msg);
250 let fresh = tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
252 struct_span_err!(tcx.sess,
255 "reached the recursion limit while auto-dereferencing `{:?}`",
257 .span_label(span, "deref recursion limit reached")
259 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
265 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
266 pub fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'gcx, 'tcx> {
267 Autoderef::new(self, self.param_env, self.body_id, span, base_ty)
270 pub fn try_overloaded_deref(&self,
274 -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
275 self.try_overloaded_place_op(span, base_ty, &[], needs, PlaceOp::Deref)