1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use super::{FnCtxt, LvalueOp};
15 use rustc::infer::InferOk;
17 use rustc::ty::{self, Ty, TraitRef};
18 use rustc::ty::{ToPredicate, TypeFoldable};
19 use rustc::ty::{LvaluePreference, NoPreference};
20 use rustc::ty::adjustment::AutoBorrow;
23 use syntax::symbol::Symbol;
25 #[derive(Copy, Clone, Debug)]
31 pub struct Autoderef<'a, 'gcx: 'tcx, 'tcx: 'a> {
32 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
33 steps: Vec<(Ty<'tcx>, AutoderefKind)>,
35 obligations: Vec<traits::PredicateObligation<'tcx>>,
40 impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> {
41 type Item = (Ty<'tcx>, usize);
43 fn next(&mut self) -> Option<Self::Item> {
44 let tcx = self.fcx.tcx;
46 debug!("autoderef: steps={:?}, cur_ty={:?}",
50 self.at_start = false;
51 debug!("autoderef stage #0 is {:?}", self.cur_ty);
52 return Some((self.cur_ty, 0));
55 if self.steps.len() == tcx.sess.recursion_limit.get() {
56 // We've reached the recursion limit, error gracefully.
57 let suggested_limit = tcx.sess.recursion_limit.get() * 2;
58 struct_span_err!(tcx.sess,
61 "reached the recursion limit while auto-dereferencing {:?}",
63 .span_label(self.span, "deref recursion limit reached")
65 "consider adding a `#[recursion_limit=\"{}\"]` attribute to your crate",
71 if self.cur_ty.is_ty_var() {
75 // Otherwise, deref if type is derefable:
76 let (kind, new_ty) = if let Some(mt) = self.cur_ty.builtin_deref(false, NoPreference) {
77 (AutoderefKind::Builtin, mt.ty)
79 match self.overloaded_deref_ty(self.cur_ty) {
80 Some(ty) => (AutoderefKind::Overloaded, ty),
85 if new_ty.references_error() {
89 self.steps.push((self.cur_ty, kind));
90 debug!("autoderef stage #{:?} is {:?} from {:?}",
96 Some((self.cur_ty, self.steps.len()))
100 impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> {
101 fn overloaded_deref_ty(&mut self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
102 debug!("overloaded_deref_ty({:?})", ty);
104 let tcx = self.fcx.tcx();
107 let trait_ref = TraitRef {
108 def_id: match tcx.lang_items.deref_trait() {
112 substs: tcx.mk_substs_trait(self.cur_ty, &[]),
115 let cause = traits::ObligationCause::misc(self.span, self.fcx.body_id);
117 let mut selcx = traits::SelectionContext::new(self.fcx);
118 let obligation = traits::Obligation::new(cause.clone(), trait_ref.to_predicate());
119 if !selcx.evaluate_obligation(&obligation) {
120 debug!("overloaded_deref_ty: cannot match obligation");
124 let normalized = traits::normalize_projection_type(&mut selcx,
126 trait_ref: trait_ref,
127 item_name: Symbol::intern("Target"),
132 debug!("overloaded_deref_ty({:?}) = {:?}", ty, normalized);
133 self.obligations.extend(normalized.obligations);
135 Some(self.fcx.resolve_type_vars_if_possible(&normalized.value))
138 /// Returns the final type, generating an error if it is an
139 /// unresolved inference variable.
140 pub fn unambiguous_final_ty(&self) -> Ty<'tcx> {
141 self.fcx.structurally_resolved_type(self.span, self.cur_ty)
144 /// Returns the final type we ended up with, which may well be an
145 /// inference variable (we will resolve it first, if possible).
146 pub fn maybe_ambiguous_final_ty(&self) -> Ty<'tcx> {
147 self.fcx.resolve_type_vars_if_possible(&self.cur_ty)
150 pub fn step_count(&self) -> usize {
154 /// Returns the steps required in adjustments (overloaded deref calls).
155 pub fn adjust_steps(&self, pref: LvaluePreference)
156 -> Vec<Option<ty::MethodCallee<'tcx>>> {
157 self.fcx.register_infer_ok_obligations(self.adjust_steps_as_infer_ok(pref))
160 pub fn adjust_steps_as_infer_ok(&self, pref: LvaluePreference)
161 -> InferOk<'tcx, Vec<Option<ty::MethodCallee<'tcx>>>> {
162 let mut obligations = vec![];
163 let steps: Vec<_> = self.steps.iter().map(|&(ty, kind)| {
164 if let AutoderefKind::Overloaded = kind {
165 self.fcx.try_overloaded_deref(self.span, ty, pref)
166 .map(|InferOk { value: (_, method), obligations: o }| {
167 obligations.extend(o);
181 pub fn finalize(self) {
183 fcx.register_predicates(self.into_obligations());
186 pub fn into_obligations(self) -> Vec<traits::PredicateObligation<'tcx>> {
191 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
192 pub fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'gcx, 'tcx> {
196 cur_ty: self.resolve_type_vars_if_possible(&base_ty),
203 pub fn try_overloaded_deref(&self,
206 pref: LvaluePreference)
207 -> Option<InferOk<'tcx,
208 (Option<AutoBorrow<'tcx>>,
209 ty::MethodCallee<'tcx>)>> {
210 self.try_overloaded_lvalue_op(span, base_ty, &[], pref, LvalueOp::Deref)