]> git.proxmox.com Git - rustc.git/blobdiff - src/librustc_typeck/check/method/probe.rs
New upstream version 1.24.1+dfsg1
[rustc.git] / src / librustc_typeck / check / method / probe.rs
index 0f28be90abfbedb87d7562f4eac8f9c466ba03c7..53bb0e577a4b68405b95b9318cf1197e0af24e30 100644 (file)
@@ -16,38 +16,49 @@ use super::suggest;
 use check::FnCtxt;
 use hir::def_id::DefId;
 use hir::def::Def;
-use rustc::infer::InferOk;
+use namespace::Namespace;
 use rustc::ty::subst::{Subst, Substs};
 use rustc::traits::{self, ObligationCause};
-use rustc::ty::{self, Ty, ToPolyTraitRef, TraitRef, TypeFoldable};
+use rustc::ty::{self, Ty, ToPolyTraitRef, ToPredicate, TraitRef, TypeFoldable};
 use rustc::infer::type_variable::TypeVariableOrigin;
 use rustc::util::nodemap::FxHashSet;
+use rustc::infer::{self, InferOk};
 use syntax::ast;
+use syntax::util::lev_distance::{lev_distance, find_best_match_for_name};
 use syntax_pos::Span;
 use rustc::hir;
+use rustc::lint;
 use std::mem;
 use std::ops::Deref;
 use std::rc::Rc;
+use std::cmp::max;
 
 use self::CandidateKind::*;
 pub use self::PickKind::*;
 
+/// Boolean flag used to indicate if this search is for a suggestion
+/// or not.  If true, we can allow ambiguity and so forth.
+pub struct IsSuggestion(pub bool);
+
 struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
     fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
     span: Span,
     mode: Mode,
-    item_name: ast::Name,
+    method_name: Option<ast::Name>,
+    return_type: Option<Ty<'tcx>>,
     steps: Rc<Vec<CandidateStep<'tcx>>>,
-    opt_simplified_steps: Option<Vec<ty::fast_reject::SimplifiedType>>,
     inherent_candidates: Vec<Candidate<'tcx>>,
     extension_candidates: Vec<Candidate<'tcx>>,
     impl_dups: FxHashSet<DefId>,
-    import_id: Option<ast::NodeId>,
 
     /// Collects near misses when the candidate functions are missing a `self` keyword and is only
     /// used for error reporting
     static_candidates: Vec<CandidateSource>,
 
+    /// When probing for names, include names that are close to the
+    /// requested name (by Levensthein distance)
+    allow_similar_names: bool,
+
     /// Some(candidate) if there is a private candidate
     private_candidate: Option<Def>,
 
@@ -67,12 +78,19 @@ impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
 struct CandidateStep<'tcx> {
     self_ty: Ty<'tcx>,
     autoderefs: usize,
+    // true if the type results from a dereference of a raw pointer.
+    // when assembling candidates, we include these steps, but not when
+    // picking methods. This so that if we have `foo: *const Foo` and `Foo` has methods
+    // `fn by_raw_ptr(self: *const Self)` and `fn by_ref(&self)`, then
+    // `foo.by_raw_ptr()` will work and `foo.by_ref()` won't.
+    from_unsafe_deref: bool,
     unsize: bool,
 }
 
 #[derive(Debug)]
 struct Candidate<'tcx> {
     xform_self_ty: Ty<'tcx>,
+    xform_ret_ty: Option<Ty<'tcx>>,
     item: ty::AssociatedItem,
     kind: CandidateKind<'tcx>,
     import_id: Option<ast::NodeId>,
@@ -83,18 +101,20 @@ enum CandidateKind<'tcx> {
     InherentImplCandidate(&'tcx Substs<'tcx>,
                           // Normalize obligations
                           Vec<traits::PredicateObligation<'tcx>>),
-    ExtensionImplCandidate(// Impl
-                           DefId,
-                           &'tcx Substs<'tcx>,
-                           // Normalize obligations
-                           Vec<traits::PredicateObligation<'tcx>>),
     ObjectCandidate,
-    TraitCandidate,
+    TraitCandidate(ty::TraitRef<'tcx>),
     WhereClauseCandidate(// Trait
                          ty::PolyTraitRef<'tcx>),
 }
 
-#[derive(Debug)]
+#[derive(Debug, PartialEq, Eq, Copy, Clone)]
+enum ProbeResult {
+    NoMatch,
+    BadReturnType,
+    Match,
+}
+
+#[derive(Debug, PartialEq, Eq, Clone)]
 pub struct Pick<'tcx> {
     pub item: ty::AssociatedItem,
     pub kind: PickKind<'tcx>,
@@ -118,11 +138,9 @@ pub struct Pick<'tcx> {
     pub unsize: Option<Ty<'tcx>>,
 }
 
-#[derive(Clone,Debug)]
+#[derive(Clone, Debug, PartialEq, Eq)]
 pub enum PickKind<'tcx> {
     InherentImplPick,
-    ExtensionImplPick(// Impl
-                      DefId),
     ObjectPick,
     TraitPick,
     WhereClausePick(// Trait
@@ -143,19 +161,87 @@ pub enum Mode {
     Path,
 }
 
+#[derive(PartialEq, Eq, Copy, Clone, Debug)]
+pub enum ProbeScope {
+    // Assemble candidates coming only from traits in scope.
+    TraitsInScope,
+
+    // Assemble candidates coming from all traits.
+    AllTraits,
+}
+
 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
-    pub fn probe_method(&self,
-                        span: Span,
-                        mode: Mode,
-                        item_name: ast::Name,
-                        self_ty: Ty<'tcx>,
-                        scope_expr_id: ast::NodeId)
-                        -> PickResult<'tcx> {
+    /// This is used to offer suggestions to users. It returns methods
+    /// that could have been called which have the desired return
+    /// type. Some effort is made to rule out methods that, if called,
+    /// would result in an error (basically, the same criteria we
+    /// would use to decide if a method is a plausible fit for
+    /// ambiguity purposes).
+    pub fn probe_for_return_type(&self,
+                                 span: Span,
+                                 mode: Mode,
+                                 return_type: Ty<'tcx>,
+                                 self_ty: Ty<'tcx>,
+                                 scope_expr_id: ast::NodeId)
+                                 -> Vec<ty::AssociatedItem> {
+        debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
+               self_ty,
+               return_type,
+               scope_expr_id);
+        let method_names =
+            self.probe_op(span, mode, None, Some(return_type), IsSuggestion(true),
+                          self_ty, scope_expr_id, ProbeScope::TraitsInScope,
+                          |probe_cx| Ok(probe_cx.candidate_method_names()))
+                .unwrap_or(vec![]);
+         method_names
+             .iter()
+             .flat_map(|&method_name| {
+                 self.probe_op(
+                     span, mode, Some(method_name), Some(return_type),
+                     IsSuggestion(true), self_ty, scope_expr_id,
+                     ProbeScope::TraitsInScope, |probe_cx| probe_cx.pick()
+                 ).ok().map(|pick| pick.item)
+             })
+            .collect()
+    }
+
+    pub fn probe_for_name(&self,
+                          span: Span,
+                          mode: Mode,
+                          item_name: ast::Name,
+                          is_suggestion: IsSuggestion,
+                          self_ty: Ty<'tcx>,
+                          scope_expr_id: ast::NodeId,
+                          scope: ProbeScope)
+                          -> PickResult<'tcx> {
         debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
                self_ty,
                item_name,
                scope_expr_id);
+        self.probe_op(span,
+                      mode,
+                      Some(item_name),
+                      None,
+                      is_suggestion,
+                      self_ty,
+                      scope_expr_id,
+                      scope,
+                      |probe_cx| probe_cx.pick())
+    }
 
+    fn probe_op<OP,R>(&'a self,
+                      span: Span,
+                      mode: Mode,
+                      method_name: Option<ast::Name>,
+                      return_type: Option<Ty<'tcx>>,
+                      is_suggestion: IsSuggestion,
+                      self_ty: Ty<'tcx>,
+                      scope_expr_id: ast::NodeId,
+                      scope: ProbeScope,
+                      op: OP)
+                      -> Result<R, MethodError<'tcx>>
+        where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
+    {
         // FIXME(#18741) -- right now, creating the steps involves evaluating the
         // `*` operator, which registers obligations that then escape into
         // the global fulfillment context and thus has global
@@ -164,41 +250,25 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
         // think cause spurious errors. Really though this part should
         // take place in the `self.probe` below.
         let steps = if mode == Mode::MethodCall {
-            match self.create_steps(span, self_ty) {
+            match self.create_steps(span, scope_expr_id, self_ty, is_suggestion) {
                 Some(steps) => steps,
                 None => {
                     return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
                                                                      Vec::new(),
                                                                      Vec::new(),
+                                                                     None,
                                                                      mode)))
                 }
             }
         } else {
             vec![CandidateStep {
-                     self_ty: self_ty,
+                     self_ty,
                      autoderefs: 0,
+                     from_unsafe_deref: false,
                      unsize: false,
                  }]
         };
 
-        // Create a list of simplified self types, if we can.
-        let mut simplified_steps = Vec::new();
-        for step in &steps {
-            match ty::fast_reject::simplify_type(self.tcx, step.self_ty, true) {
-                None => {
-                    break;
-                }
-                Some(simplified_type) => {
-                    simplified_steps.push(simplified_type);
-                }
-            }
-        }
-        let opt_simplified_steps = if simplified_steps.len() < steps.len() {
-            None // failed to convert at least one of the steps
-        } else {
-            Some(simplified_steps)
-        };
-
         debug!("ProbeContext: steps for self_ty={:?} are {:?}",
                self_ty,
                steps);
@@ -207,35 +277,82 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
         // that we create during the probe process are removed later
         self.probe(|_| {
             let mut probe_cx =
-                ProbeContext::new(self, span, mode, item_name, steps, opt_simplified_steps);
+                ProbeContext::new(self, span, mode, method_name, return_type, Rc::new(steps));
+
             probe_cx.assemble_inherent_candidates();
-            probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?;
-            probe_cx.pick()
+            match scope {
+                ProbeScope::TraitsInScope =>
+                    probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
+                ProbeScope::AllTraits =>
+                    probe_cx.assemble_extension_candidates_for_all_traits()?,
+            };
+            op(probe_cx)
         })
     }
 
-    fn create_steps(&self, span: Span, self_ty: Ty<'tcx>) -> Option<Vec<CandidateStep<'tcx>>> {
+    fn create_steps(&self,
+                    span: Span,
+                    scope_expr_id: ast::NodeId,
+                    self_ty: Ty<'tcx>,
+                    is_suggestion: IsSuggestion)
+                    -> Option<Vec<CandidateStep<'tcx>>> {
         // FIXME: we don't need to create the entire steps in one pass
 
-        let mut autoderef = self.autoderef(span, self_ty);
+        let mut autoderef = self.autoderef(span, self_ty).include_raw_pointers();
+        let mut reached_raw_pointer = false;
         let mut steps: Vec<_> = autoderef.by_ref()
             .map(|(ty, d)| {
-                CandidateStep {
+                let step = CandidateStep {
                     self_ty: ty,
                     autoderefs: d,
+                    from_unsafe_deref: reached_raw_pointer,
                     unsize: false,
+                };
+                if let ty::TyRawPtr(_) = ty.sty {
+                    // all the subsequent steps will be from_unsafe_deref
+                    reached_raw_pointer = true;
                 }
+                step
             })
             .collect();
 
-        let final_ty = autoderef.unambiguous_final_ty();
+        let final_ty = autoderef.maybe_ambiguous_final_ty();
         match final_ty.sty {
+            ty::TyInfer(ty::TyVar(_)) => {
+                // Ended in an inference variable. If we are doing
+                // a real method lookup, this is a hard error because it's
+                // possible that there will be multiple applicable methods.
+                if !is_suggestion.0 {
+                    if reached_raw_pointer
+                    && !self.tcx.sess.features.borrow().arbitrary_self_types {
+                        // this case used to be allowed by the compiler,
+                        // so we do a future-compat lint here
+                        // (see https://github.com/rust-lang/rust/issues/46906)
+                        self.tcx.lint_node(
+                            lint::builtin::TYVAR_BEHIND_RAW_POINTER,
+                            scope_expr_id,
+                            span,
+                            &format!("the type of this value must be known in this context"));
+                    } else {
+                        let t = self.structurally_resolved_type(span, final_ty);
+                        assert_eq!(t, self.tcx.types.err);
+                        return None
+                    }
+                } else {
+                    // If we're just looking for suggestions,
+                    // though, ambiguity is no big thing, we can
+                    // just ignore it.
+                }
+            }
             ty::TyArray(elem_ty, _) => {
                 let dereferences = steps.len() - 1;
 
                 steps.push(CandidateStep {
                     self_ty: self.tcx.mk_slice(elem_ty),
                     autoderefs: dereferences,
+                    // this could be from an unsafe deref if we had
+                    // a *mut/const [T; N]
+                    from_unsafe_deref: reached_raw_pointer,
                     unsize: true,
                 });
             }
@@ -253,22 +370,22 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
     fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
            span: Span,
            mode: Mode,
-           item_name: ast::Name,
-           steps: Vec<CandidateStep<'tcx>>,
-           opt_simplified_steps: Option<Vec<ty::fast_reject::SimplifiedType>>)
+           method_name: Option<ast::Name>,
+           return_type: Option<Ty<'tcx>>,
+           steps: Rc<Vec<CandidateStep<'tcx>>>)
            -> ProbeContext<'a, 'gcx, 'tcx> {
         ProbeContext {
-            fcx: fcx,
-            span: span,
-            mode: mode,
-            item_name: item_name,
+            fcx,
+            span,
+            mode,
+            method_name,
+            return_type,
             inherent_candidates: Vec::new(),
             extension_candidates: Vec::new(),
             impl_dups: FxHashSet(),
-            import_id: None,
-            steps: Rc::new(steps),
-            opt_simplified_steps: opt_simplified_steps,
+            steps: steps,
             static_candidates: Vec::new(),
+            allow_similar_names: false,
             private_candidate: None,
             unsatisfied_predicates: Vec::new(),
         }
@@ -285,6 +402,28 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
     ///////////////////////////////////////////////////////////////////////////
     // CANDIDATE ASSEMBLY
 
+    fn push_candidate(&mut self,
+                      candidate: Candidate<'tcx>,
+                      is_inherent: bool)
+    {
+        let is_accessible = if let Some(name) = self.method_name {
+            let item = candidate.item;
+            let def_scope = self.tcx.adjust(name, item.container.id(), self.body_id).1;
+            item.vis.is_accessible_from(def_scope, self.tcx)
+        } else {
+            true
+        };
+        if is_accessible {
+            if is_inherent {
+                self.inherent_candidates.push(candidate);
+            } else {
+                self.extension_candidates.push(candidate);
+            }
+        } else if self.private_candidate.is_none() {
+            self.private_candidate = Some(candidate.item.def());
+        }
+    }
+
     fn assemble_inherent_candidates(&mut self) {
         let steps = self.steps.clone();
         for step in steps.iter() {
@@ -294,6 +433,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
 
     fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
         debug!("assemble_probe: self_ty={:?}", self_ty);
+        let lang_items = self.tcx.lang_items();
 
         match self_ty.sty {
             ty::TyDynamic(ref data, ..) => {
@@ -305,80 +445,89 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
             ty::TyAdt(def, _) => {
                 self.assemble_inherent_impl_candidates_for_type(def.did);
             }
-            ty::TyBox(_) => {
-                if let Some(box_did) = self.tcx.lang_items.owned_box() {
-                    self.assemble_inherent_impl_candidates_for_type(box_did);
-                }
+            ty::TyForeign(did) => {
+                self.assemble_inherent_impl_candidates_for_type(did);
             }
             ty::TyParam(p) => {
                 self.assemble_inherent_candidates_from_param(self_ty, p);
             }
             ty::TyChar => {
-                let lang_def_id = self.tcx.lang_items.char_impl();
+                let lang_def_id = lang_items.char_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyStr => {
-                let lang_def_id = self.tcx.lang_items.str_impl();
+                let lang_def_id = lang_items.str_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TySlice(_) => {
-                let lang_def_id = self.tcx.lang_items.slice_impl();
+                let lang_def_id = lang_items.slice_impl();
+                self.assemble_inherent_impl_for_primitive(lang_def_id);
+
+                let lang_def_id = lang_items.slice_u8_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
-                let lang_def_id = self.tcx.lang_items.const_ptr_impl();
+                let lang_def_id = lang_items.const_ptr_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
-                let lang_def_id = self.tcx.lang_items.mut_ptr_impl();
+                let lang_def_id = lang_items.mut_ptr_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyInt(ast::IntTy::I8) => {
-                let lang_def_id = self.tcx.lang_items.i8_impl();
+                let lang_def_id = lang_items.i8_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyInt(ast::IntTy::I16) => {
-                let lang_def_id = self.tcx.lang_items.i16_impl();
+                let lang_def_id = lang_items.i16_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyInt(ast::IntTy::I32) => {
-                let lang_def_id = self.tcx.lang_items.i32_impl();
+                let lang_def_id = lang_items.i32_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyInt(ast::IntTy::I64) => {
-                let lang_def_id = self.tcx.lang_items.i64_impl();
+                let lang_def_id = lang_items.i64_impl();
+                self.assemble_inherent_impl_for_primitive(lang_def_id);
+            }
+            ty::TyInt(ast::IntTy::I128) => {
+                let lang_def_id = lang_items.i128_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyInt(ast::IntTy::Is) => {
-                let lang_def_id = self.tcx.lang_items.isize_impl();
+                let lang_def_id = lang_items.isize_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyUint(ast::UintTy::U8) => {
-                let lang_def_id = self.tcx.lang_items.u8_impl();
+                let lang_def_id = lang_items.u8_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyUint(ast::UintTy::U16) => {
-                let lang_def_id = self.tcx.lang_items.u16_impl();
+                let lang_def_id = lang_items.u16_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyUint(ast::UintTy::U32) => {
-                let lang_def_id = self.tcx.lang_items.u32_impl();
+                let lang_def_id = lang_items.u32_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyUint(ast::UintTy::U64) => {
-                let lang_def_id = self.tcx.lang_items.u64_impl();
+                let lang_def_id = lang_items.u64_impl();
+                self.assemble_inherent_impl_for_primitive(lang_def_id);
+            }
+            ty::TyUint(ast::UintTy::U128) => {
+                let lang_def_id = lang_items.u128_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyUint(ast::UintTy::Us) => {
-                let lang_def_id = self.tcx.lang_items.usize_impl();
+                let lang_def_id = lang_items.usize_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyFloat(ast::FloatTy::F32) => {
-                let lang_def_id = self.tcx.lang_items.f32_impl();
+                let lang_def_id = lang_items.f32_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             ty::TyFloat(ast::FloatTy::F64) => {
-                let lang_def_id = self.tcx.lang_items.f64_impl();
+                let lang_def_id = lang_items.f64_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
             _ => {}
@@ -392,14 +541,9 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
     }
 
     fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
-        // Read the inherent implementation candidates for this type from the
-        // metadata if necessary.
-        self.tcx.populate_inherent_implementations_for_type_if_necessary(def_id);
-
-        if let Some(impl_infos) = self.tcx.inherent_impls.borrow().get(&def_id) {
-            for &impl_def_id in impl_infos.iter() {
-                self.assemble_inherent_impl_probe(impl_def_id);
-            }
+        let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
+        for &impl_def_id in impl_def_ids.iter() {
+            self.assemble_inherent_impl_probe(impl_def_id);
         }
     }
 
@@ -410,44 +554,34 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
 
         debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
 
-        let item = match self.associated_item(impl_def_id) {
-            Some(m) => m,
-            None => {
-                return;
-            } // No method with correct name on this impl
-        };
-
-        if !self.has_applicable_self(&item) {
-            // No receiver declared. Not a candidate.
-            return self.record_static_candidate(ImplSource(impl_def_id));
-        }
-
-        if !item.vis.is_accessible_from(self.body_id, &self.tcx.map) {
-            self.private_candidate = Some(item.def());
-            return;
-        }
+        for item in self.impl_or_trait_item(impl_def_id) {
+            if !self.has_applicable_self(&item) {
+                // No receiver declared. Not a candidate.
+                self.record_static_candidate(ImplSource(impl_def_id));
+                continue
+            }
 
-        let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
-        let impl_ty = impl_ty.subst(self.tcx, impl_substs);
+            let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
+            let impl_ty = impl_ty.subst(self.tcx, impl_substs);
 
-        // Determine the receiver type that the method itself expects.
-        let xform_self_ty = self.xform_self_ty(&item, impl_ty, impl_substs);
+            // Determine the receiver type that the method itself expects.
+            let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
 
-        // We can't use normalize_associated_types_in as it will pollute the
-        // fcx's fulfillment context after this probe is over.
-        let cause = traits::ObligationCause::misc(self.span, self.body_id);
-        let mut selcx = &mut traits::SelectionContext::new(self.fcx);
-        let traits::Normalized { value: xform_self_ty, obligations } =
-            traits::normalize(selcx, cause, &xform_self_ty);
-        debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}",
-               xform_self_ty);
-
-        self.inherent_candidates.push(Candidate {
-            xform_self_ty: xform_self_ty,
-            item: item,
-            kind: InherentImplCandidate(impl_substs, obligations),
-            import_id: self.import_id,
-        });
+            // We can't use normalize_associated_types_in as it will pollute the
+            // fcx's fulfillment context after this probe is over.
+            let cause = traits::ObligationCause::misc(self.span, self.body_id);
+            let selcx = &mut traits::SelectionContext::new(self.fcx);
+            let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
+                traits::normalize(selcx, self.param_env, cause, &xform_tys);
+            debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
+                   xform_self_ty, xform_ret_ty);
+
+            self.push_candidate(Candidate {
+                xform_self_ty, xform_ret_ty, item,
+                kind: InherentImplCandidate(impl_substs, obligations),
+                import_id: None
+            }, true);
+        }
     }
 
     fn assemble_inherent_candidates_from_object(&mut self,
@@ -467,15 +601,13 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
         self.elaborate_bounds(&[trait_ref], |this, new_trait_ref, item| {
             let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
 
-            let xform_self_ty =
+            let (xform_self_ty, xform_ret_ty) =
                 this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
-
-            this.inherent_candidates.push(Candidate {
-                xform_self_ty: xform_self_ty,
-                item: item,
+            this.push_candidate(Candidate {
+                xform_self_ty, xform_ret_ty, item,
                 kind: ObjectCandidate,
-                import_id: this.import_id,
-            });
+                import_id: None
+            }, true);
         });
     }
 
@@ -484,7 +616,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
                                                param_ty: ty::ParamTy) {
         // FIXME -- Do we want to commit to this behavior for param bounds?
 
-        let bounds: Vec<_> = self.parameter_environment
+        let bounds: Vec<_> = self.param_env
             .caller_bounds
             .iter()
             .filter_map(|predicate| {
@@ -498,12 +630,14 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
                         }
                     }
                     ty::Predicate::Equate(..) |
+                    ty::Predicate::Subtype(..) |
                     ty::Predicate::Projection(..) |
                     ty::Predicate::RegionOutlives(..) |
                     ty::Predicate::WellFormed(..) |
                     ty::Predicate::ObjectSafe(..) |
                     ty::Predicate::ClosureKind(..) |
-                    ty::Predicate::TypeOutlives(..) => None,
+                    ty::Predicate::TypeOutlives(..) |
+                    ty::Predicate::ConstEvaluatable(..) => None,
                 }
             })
             .collect();
@@ -511,7 +645,8 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
         self.elaborate_bounds(&bounds, |this, poly_trait_ref, item| {
             let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
 
-            let xform_self_ty = this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
+            let (xform_self_ty, xform_ret_ty) =
+                this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
 
             // Because this trait derives from a where-clause, it
             // should not contain any inference variables or other
@@ -520,12 +655,11 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
             // `WhereClausePick`.
             assert!(!trait_ref.substs.needs_infer());
 
-            this.inherent_candidates.push(Candidate {
-                xform_self_ty: xform_self_ty,
-                item: item,
+            this.push_candidate(Candidate {
+                xform_self_ty, xform_ret_ty, item,
                 kind: WhereClauseCandidate(poly_trait_ref),
-                import_id: this.import_id,
-            });
+                import_id: None
+            }, true);
         });
     }
 
@@ -540,17 +674,12 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
 
         let tcx = self.tcx;
         for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
-            let item = match self.associated_item(bound_trait_ref.def_id()) {
-                Some(v) => v,
-                None => {
-                    continue;
+            for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
+                if !self.has_applicable_self(&item) {
+                    self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
+                } else {
+                    mk_cand(self, bound_trait_ref, item);
                 }
-            };
-
-            if !self.has_applicable_self(&item) {
-                self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
-            } else {
-                mk_cand(self, bound_trait_ref, item);
             }
         }
     }
@@ -558,15 +687,18 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
     fn assemble_extension_candidates_for_traits_in_scope(&mut self,
                                                          expr_id: ast::NodeId)
                                                          -> Result<(), MethodError<'tcx>> {
+        if expr_id == ast::DUMMY_NODE_ID {
+            return Ok(())
+        }
         let mut duplicates = FxHashSet();
-        let opt_applicable_traits = self.tcx.trait_map.get(&expr_id);
+        let expr_hir_id = self.tcx.hir.node_to_hir_id(expr_id);
+        let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
         if let Some(applicable_traits) = opt_applicable_traits {
-            for trait_candidate in applicable_traits {
+            for trait_candidate in applicable_traits.iter() {
                 let trait_did = trait_candidate.def_id;
                 if duplicates.insert(trait_did) {
-                    self.import_id = trait_candidate.import_id;
-                    let result = self.assemble_extension_candidates_for_trait(trait_did);
-                    self.import_id = None;
+                    let import_id = trait_candidate.import_id;
+                    let result = self.assemble_extension_candidates_for_trait(import_id, trait_did);
                     result?;
                 }
             }
@@ -576,267 +708,95 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
 
     fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
         let mut duplicates = FxHashSet();
-        for trait_info in suggest::all_traits(self.ccx) {
+        for trait_info in suggest::all_traits(self.tcx) {
             if duplicates.insert(trait_info.def_id) {
-                self.assemble_extension_candidates_for_trait(trait_info.def_id)?;
+                self.assemble_extension_candidates_for_trait(None, trait_info.def_id)?;
             }
         }
         Ok(())
     }
 
+    pub fn matches_return_type(&self,
+                               method: &ty::AssociatedItem,
+                               self_ty: Option<Ty<'tcx>>,
+                               expected: Ty<'tcx>) -> bool {
+        match method.def() {
+            Def::Method(def_id) => {
+                let fty = self.tcx.fn_sig(def_id);
+                self.probe(|_| {
+                    let substs = self.fresh_substs_for_item(self.span, method.def_id);
+                    let fty = fty.subst(self.tcx, substs);
+                    let (fty, _) = self.replace_late_bound_regions_with_fresh_var(
+                        self.span, infer::FnCall, &fty);
+
+                    if let Some(self_ty) = self_ty {
+                        if let Err(_) = self.at(&ObligationCause::dummy(), self.param_env)
+                            .sup(fty.inputs()[0], self_ty)
+                        {
+                            return false
+                        }
+                    }
+                    self.can_sub(self.param_env, fty.output(), expected).is_ok()
+                })
+            }
+            _ => false,
+        }
+    }
+
     fn assemble_extension_candidates_for_trait(&mut self,
+                                               import_id: Option<ast::NodeId>,
                                                trait_def_id: DefId)
                                                -> Result<(), MethodError<'tcx>> {
         debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
                trait_def_id);
+        let trait_substs = self.fresh_item_substs(trait_def_id);
+        let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
 
-        // Check whether `trait_def_id` defines a method with suitable name:
-        let maybe_item = self.tcx.associated_items(trait_def_id)
-                             .find(|item| item.name == self.item_name);
-        let item = match maybe_item {
-            Some(i) => i,
-            None => {
-                return Ok(());
-            }
-        };
-
-        // Check whether `trait_def_id` defines a method with suitable name:
-        if !self.has_applicable_self(&item) {
-            debug!("method has inapplicable self");
-            self.record_static_candidate(TraitSource(trait_def_id));
-            return Ok(());
-        }
-
-        self.assemble_extension_candidates_for_trait_impls(trait_def_id, item.clone());
-
-        self.assemble_closure_candidates(trait_def_id, item.clone())?;
-
-        self.assemble_projection_candidates(trait_def_id, item.clone());
-
-        self.assemble_where_clause_candidates(trait_def_id, item.clone());
-
-        Ok(())
-    }
-
-    fn assemble_extension_candidates_for_trait_impls(&mut self,
-                                                     trait_def_id: DefId,
-                                                     item: ty::AssociatedItem) {
-        let trait_def = self.tcx.lookup_trait_def(trait_def_id);
-
-        // FIXME(arielb1): can we use for_each_relevant_impl here?
-        trait_def.for_each_impl(self.tcx, |impl_def_id| {
-            debug!("assemble_extension_candidates_for_trait_impl: trait_def_id={:?} \
-                                                                  impl_def_id={:?}",
-                   trait_def_id,
-                   impl_def_id);
-
-            if !self.impl_can_possibly_match(impl_def_id) {
-                return;
-            }
-
-            let (_, impl_substs) = self.impl_ty_and_substs(impl_def_id);
-
-            debug!("impl_substs={:?}", impl_substs);
-
-            let impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id)
-                .unwrap() // we know this is a trait impl
-                .subst(self.tcx, impl_substs);
-
-            debug!("impl_trait_ref={:?}", impl_trait_ref);
-
-            // Determine the receiver type that the method itself expects.
-            let xform_self_ty =
-                self.xform_self_ty(&item, impl_trait_ref.self_ty(), impl_trait_ref.substs);
-
-            // Normalize the receiver. We can't use normalize_associated_types_in
-            // as it will pollute the fcx's fulfillment context after this probe
-            // is over.
-            let cause = traits::ObligationCause::misc(self.span, self.body_id);
-            let mut selcx = &mut traits::SelectionContext::new(self.fcx);
-            let traits::Normalized { value: xform_self_ty, obligations } =
-                traits::normalize(selcx, cause, &xform_self_ty);
-
-            debug!("xform_self_ty={:?}", xform_self_ty);
-
-            self.extension_candidates.push(Candidate {
-                xform_self_ty: xform_self_ty,
-                item: item.clone(),
-                kind: ExtensionImplCandidate(impl_def_id, impl_substs, obligations),
-                import_id: self.import_id,
-            });
-        });
-    }
-
-    fn impl_can_possibly_match(&self, impl_def_id: DefId) -> bool {
-        let simplified_steps = match self.opt_simplified_steps {
-            Some(ref simplified_steps) => simplified_steps,
-            None => {
-                return true;
-            }
-        };
-
-        let impl_type = self.tcx.item_type(impl_def_id);
-        let impl_simplified_type =
-            match ty::fast_reject::simplify_type(self.tcx, impl_type, false) {
-                Some(simplified_type) => simplified_type,
-                None => {
-                    return true;
-                }
-            };
-
-        simplified_steps.contains(&impl_simplified_type)
-    }
-
-    fn assemble_closure_candidates(&mut self,
-                                   trait_def_id: DefId,
-                                   item: ty::AssociatedItem)
-                                   -> Result<(), MethodError<'tcx>> {
-        // Check if this is one of the Fn,FnMut,FnOnce traits.
-        let tcx = self.tcx;
-        let kind = if Some(trait_def_id) == tcx.lang_items.fn_trait() {
-            ty::ClosureKind::Fn
-        } else if Some(trait_def_id) == tcx.lang_items.fn_mut_trait() {
-            ty::ClosureKind::FnMut
-        } else if Some(trait_def_id) == tcx.lang_items.fn_once_trait() {
-            ty::ClosureKind::FnOnce
-        } else {
-            return Ok(());
-        };
-
-        // Check if there is an unboxed-closure self-type in the list of receivers.
-        // If so, add "synthetic impls".
-        let steps = self.steps.clone();
-        for step in steps.iter() {
-            let closure_def_id = match step.self_ty.sty {
-                ty::TyClosure(a, _) => a,
-                _ => continue,
-            };
-
-            let closure_kinds = &self.tables.borrow().closure_kinds;
-            let closure_kind = match closure_kinds.get(&closure_def_id) {
-                Some(&k) => k,
-                None => {
-                    return Err(MethodError::ClosureAmbiguity(trait_def_id));
-                }
-            };
-
-            // this closure doesn't implement the right kind of `Fn` trait
-            if !closure_kind.extends(kind) {
+        for item in self.impl_or_trait_item(trait_def_id) {
+            // Check whether `trait_def_id` defines a method with suitable name:
+            if !self.has_applicable_self(&item) {
+                debug!("method has inapplicable self");
+                self.record_static_candidate(TraitSource(trait_def_id));
                 continue;
             }
 
-            // create some substitutions for the argument/return type;
-            // for the purposes of our method lookup, we only take
-            // receiver type into account, so we can just substitute
-            // fresh types here to use during substitution and subtyping.
-            let substs = Substs::for_item(self.tcx,
-                                          trait_def_id,
-                                          |def, _| self.region_var_for_def(self.span, def),
-                                          |def, substs| {
-                if def.index == 0 {
-                    step.self_ty
-                } else {
-                    self.type_var_for_def(self.span, def, substs)
-                }
-            });
-
-            let xform_self_ty = self.xform_self_ty(&item, step.self_ty, substs);
-            self.inherent_candidates.push(Candidate {
-                xform_self_ty: xform_self_ty,
-                item: item.clone(),
-                kind: TraitCandidate,
-                import_id: self.import_id,
-            });
+            let (xform_self_ty, xform_ret_ty) =
+                self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
+            self.push_candidate(Candidate {
+                xform_self_ty, xform_ret_ty, item, import_id,
+                kind: TraitCandidate(trait_ref),
+            }, false);
         }
-
         Ok(())
     }
 
-    fn assemble_projection_candidates(&mut self,
-                                      trait_def_id: DefId,
-                                      item: ty::AssociatedItem) {
-        debug!("assemble_projection_candidates(\
-               trait_def_id={:?}, \
-               item={:?})",
-               trait_def_id,
-               item);
-
-        for step in self.steps.iter() {
-            debug!("assemble_projection_candidates: step={:?}", step);
-
-            let (def_id, substs) = match step.self_ty.sty {
-                ty::TyProjection(ref data) => (data.trait_ref.def_id, data.trait_ref.substs),
-                ty::TyAnon(def_id, substs) => (def_id, substs),
-                _ => continue,
-            };
-
-            debug!("assemble_projection_candidates: def_id={:?} substs={:?}",
-                   def_id,
-                   substs);
-
-            let trait_predicates = self.tcx.item_predicates(def_id);
-            let bounds = trait_predicates.instantiate(self.tcx, substs);
-            let predicates = bounds.predicates;
-            debug!("assemble_projection_candidates: predicates={:?}",
-                   predicates);
-            for poly_bound in traits::elaborate_predicates(self.tcx, predicates)
-                .filter_map(|p| p.to_opt_poly_trait_ref())
-                .filter(|b| b.def_id() == trait_def_id) {
-                let bound = self.erase_late_bound_regions(&poly_bound);
-
-                debug!("assemble_projection_candidates: def_id={:?} substs={:?} bound={:?}",
-                       def_id,
-                       substs,
-                       bound);
-
-                if self.can_equate(&step.self_ty, &bound.self_ty()).is_ok() {
-                    let xform_self_ty = self.xform_self_ty(&item, bound.self_ty(), bound.substs);
-
-                    debug!("assemble_projection_candidates: bound={:?} xform_self_ty={:?}",
-                           bound,
-                           xform_self_ty);
-
-                    self.extension_candidates.push(Candidate {
-                        xform_self_ty: xform_self_ty,
-                        item: item.clone(),
-                        kind: TraitCandidate,
-                        import_id: self.import_id,
-                    });
+    fn candidate_method_names(&self) -> Vec<ast::Name> {
+        let mut set = FxHashSet();
+        let mut names: Vec<_> = self.inherent_candidates
+            .iter()
+            .chain(&self.extension_candidates)
+            .filter(|candidate| {
+                if let Some(return_ty) = self.return_type {
+                    self.matches_return_type(&candidate.item, None, return_ty)
+                } else {
+                    true
                 }
-            }
-        }
-    }
-
-    fn assemble_where_clause_candidates(&mut self,
-                                        trait_def_id: DefId,
-                                        item: ty::AssociatedItem) {
-        debug!("assemble_where_clause_candidates(trait_def_id={:?})",
-               trait_def_id);
+            })
+            .map(|candidate| candidate.item.name)
+            .filter(|&name| set.insert(name))
+            .collect();
 
-        let caller_predicates = self.parameter_environment.caller_bounds.clone();
-        for poly_bound in traits::elaborate_predicates(self.tcx, caller_predicates)
-            .filter_map(|p| p.to_opt_poly_trait_ref())
-            .filter(|b| b.def_id() == trait_def_id) {
-            let bound = self.erase_late_bound_regions(&poly_bound);
-            let xform_self_ty = self.xform_self_ty(&item, bound.self_ty(), bound.substs);
-
-            debug!("assemble_where_clause_candidates: bound={:?} xform_self_ty={:?}",
-                   bound,
-                   xform_self_ty);
-
-            self.extension_candidates.push(Candidate {
-                xform_self_ty: xform_self_ty,
-                item: item.clone(),
-                kind: WhereClauseCandidate(poly_bound),
-                import_id: self.import_id,
-            });
-        }
+        // sort them by the name so we have a stable result
+        names.sort_by_key(|n| n.as_str());
+        names
     }
 
     ///////////////////////////////////////////////////////////////////////////
     // THE ACTUAL SEARCH
 
     fn pick(mut self) -> PickResult<'tcx> {
+        assert!(self.method_name.is_some());
+
         if let Some(r) = self.pick_core() {
             return r;
         }
@@ -855,6 +815,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
 
         let out_of_scope_traits = match self.pick_core() {
             Some(Ok(p)) => vec![p.item.container.id()],
+            //Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
             Some(Err(MethodError::Ambiguity(v))) => {
                 v.into_iter()
                     .map(|source| {
@@ -877,20 +838,18 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
                 assert!(others.is_empty());
                 vec![]
             }
-            Some(Err(MethodError::ClosureAmbiguity(..))) => {
-                // this error only occurs when assembling candidates
-                span_bug!(span, "encountered ClosureAmbiguity from pick_core");
-            }
             _ => vec![],
         };
 
         if let Some(def) = private_candidate {
-            return Err(MethodError::PrivateMatch(def));
+            return Err(MethodError::PrivateMatch(def, out_of_scope_traits));
         }
+        let lev_candidate = self.probe_for_lev_candidate()?;
 
         Err(MethodError::NoMatch(NoMatchData::new(static_candidates,
                                                   unsatisfied_predicates,
                                                   out_of_scope_traits,
+                                                  lev_candidate,
                                                   self.mode)))
     }
 
@@ -898,21 +857,19 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
         let steps = self.steps.clone();
 
         // find the first step that works
-        steps.iter().filter_map(|step| self.pick_step(step)).next()
-    }
-
-    fn pick_step(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
-        debug!("pick_step: step={:?}", step);
-
-        if step.self_ty.references_error() {
-            return None;
-        }
-
-        if let Some(result) = self.pick_by_value_method(step) {
-            return Some(result);
-        }
-
-        self.pick_autorefd_method(step)
+        steps
+            .iter()
+            .filter(|step| {
+                debug!("pick_core: step={:?}", step);
+                // skip types that are from a type error or that would require dereferencing
+                // a raw pointer
+                !step.self_ty.references_error() && !step.from_unsafe_deref
+            }).flat_map(|step| {
+                self.pick_by_value_method(step).or_else(|| {
+                self.pick_autorefd_method(step, hir::MutImmutable).or_else(|| {
+                self.pick_autorefd_method(step, hir::MutMutable)
+            })})})
+            .next()
     }
 
     fn pick_by_value_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
@@ -943,36 +900,30 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
         })
     }
 
-    fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>) -> Option<PickResult<'tcx>> {
+    fn pick_autorefd_method(&mut self, step: &CandidateStep<'tcx>, mutbl: hir::Mutability)
+                            -> Option<PickResult<'tcx>> {
         let tcx = self.tcx;
 
         // In general, during probing we erase regions. See
         // `impl_self_ty()` for an explanation.
-        let region = tcx.mk_region(ty::ReErased);
+        let region = tcx.types.re_erased;
 
-        // Search through mutabilities in order to find one where pick works:
-        [hir::MutImmutable, hir::MutMutable]
-            .iter()
-            .filter_map(|&m| {
-                let autoref_ty = tcx.mk_ref(region,
-                                            ty::TypeAndMut {
-                                                ty: step.self_ty,
-                                                mutbl: m,
-                                            });
-                self.pick_method(autoref_ty).map(|r| {
-                    r.map(|mut pick| {
-                        pick.autoderefs = step.autoderefs;
-                        pick.autoref = Some(m);
-                        pick.unsize = if step.unsize {
-                            Some(step.self_ty)
-                        } else {
-                            None
-                        };
-                        pick
-                    })
-                })
+        let autoref_ty = tcx.mk_ref(region,
+                                    ty::TypeAndMut {
+                                        ty: step.self_ty, mutbl
+                                    });
+        self.pick_method(autoref_ty).map(|r| {
+            r.map(|mut pick| {
+                pick.autoderefs = step.autoderefs;
+                pick.autoref = Some(mutbl);
+                pick.unsize = if step.unsize {
+                    Some(step.self_ty)
+                } else {
+                    None
+                };
+                pick
             })
-            .nth(0)
+        })
     }
 
     fn pick_method(&mut self, self_ty: Ty<'tcx>) -> Option<PickResult<'tcx>> {
@@ -1003,98 +954,180 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
                            possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
                            -> Option<PickResult<'tcx>> {
         let mut applicable_candidates: Vec<_> = probes.iter()
-            .filter(|&probe| self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
+            .map(|probe| {
+                (probe, self.consider_probe(self_ty, probe, possibly_unsatisfied_predicates))
+            })
+            .filter(|&(_, status)| status != ProbeResult::NoMatch)
             .collect();
 
         debug!("applicable_candidates: {:?}", applicable_candidates);
 
         if applicable_candidates.len() > 1 {
-            match self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
-                Some(pick) => {
-                    return Some(Ok(pick));
-                }
-                None => {}
+            if let Some(pick) = self.collapse_candidates_to_trait_pick(&applicable_candidates[..]) {
+                return Some(Ok(pick));
             }
         }
 
         if applicable_candidates.len() > 1 {
-            let sources = probes.iter().map(|p| p.to_source()).collect();
+            let sources = probes.iter()
+                .map(|p| self.candidate_source(p, self_ty))
+                .collect();
             return Some(Err(MethodError::Ambiguity(sources)));
         }
 
-        applicable_candidates.pop().map(|probe| Ok(probe.to_unadjusted_pick()))
+        applicable_candidates.pop().map(|(probe, status)| {
+            if status == ProbeResult::Match {
+                Ok(probe.to_unadjusted_pick())
+            } else {
+                Err(MethodError::BadReturnType)
+            }
+        })
+    }
+
+    fn select_trait_candidate(&self, trait_ref: ty::TraitRef<'tcx>)
+                              -> traits::SelectionResult<'tcx, traits::Selection<'tcx>>
+    {
+        let cause = traits::ObligationCause::misc(self.span, self.body_id);
+        let predicate =
+            trait_ref.to_poly_trait_ref().to_poly_trait_predicate();
+        let obligation = traits::Obligation::new(cause, self.param_env, predicate);
+        traits::SelectionContext::new(self).select(&obligation)
+    }
+
+    fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>)
+                        -> CandidateSource
+    {
+        match candidate.kind {
+            InherentImplCandidate(..) => ImplSource(candidate.item.container.id()),
+            ObjectCandidate |
+            WhereClauseCandidate(_) => TraitSource(candidate.item.container.id()),
+            TraitCandidate(trait_ref) => self.probe(|_| {
+                let _ = self.at(&ObligationCause::dummy(), self.param_env)
+                    .sup(candidate.xform_self_ty, self_ty);
+                match self.select_trait_candidate(trait_ref) {
+                    Ok(Some(traits::Vtable::VtableImpl(ref impl_data))) => {
+                        // If only a single impl matches, make the error message point
+                        // to that impl.
+                        ImplSource(impl_data.impl_def_id)
+                    }
+                    _ => {
+                        TraitSource(candidate.item.container.id())
+                    }
+                }
+            })
+        }
     }
 
     fn consider_probe(&self,
                       self_ty: Ty<'tcx>,
                       probe: &Candidate<'tcx>,
                       possibly_unsatisfied_predicates: &mut Vec<TraitRef<'tcx>>)
-                      -> bool {
+                      -> ProbeResult {
         debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
 
         self.probe(|_| {
             // First check that the self type can be related.
-            match self.sub_types(false,
-                                 &ObligationCause::dummy(),
-                                 self_ty,
-                                 probe.xform_self_ty) {
-                Ok(InferOk { obligations, value: () }) => {
-                    // FIXME(#32730) propagate obligations
-                    assert!(obligations.is_empty())
-                }
+            let sub_obligations = match self.at(&ObligationCause::dummy(), self.param_env)
+                                            .sup(probe.xform_self_ty, self_ty) {
+                Ok(InferOk { obligations, value: () }) => obligations,
                 Err(_) => {
                     debug!("--> cannot relate self-types");
-                    return false;
+                    return ProbeResult::NoMatch;
                 }
-            }
+            };
+
+            let mut result = ProbeResult::Match;
+            let selcx = &mut traits::SelectionContext::new(self);
+            let cause = traits::ObligationCause::misc(self.span, self.body_id);
 
             // If so, impls may carry other conditions (e.g., where
             // clauses) that must be considered. Make sure that those
             // match as well (or at least may match, sometimes we
             // don't have enough information to fully evaluate).
-            let (impl_def_id, substs, ref_obligations) = match probe.kind {
+            let candidate_obligations : Vec<_> = match probe.kind {
                 InherentImplCandidate(ref substs, ref ref_obligations) => {
-                    (probe.item.container.id(), substs, ref_obligations)
-                }
-
-                ExtensionImplCandidate(impl_def_id, ref substs, ref ref_obligations) => {
-                    (impl_def_id, substs, ref_obligations)
+                    // Check whether the impl imposes obligations we have to worry about.
+                    let impl_def_id = probe.item.container.id();
+                    let impl_bounds = self.tcx.predicates_of(impl_def_id);
+                    let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
+                    let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
+                        traits::normalize(selcx, self.param_env, cause.clone(), &impl_bounds);
+
+                    // Convert the bounds into obligations.
+                    let impl_obligations = traits::predicates_for_generics(
+                        cause.clone(), self.param_env, &impl_bounds);
+
+                    debug!("impl_obligations={:?}", impl_obligations);
+                    impl_obligations.into_iter()
+                        .chain(norm_obligations.into_iter())
+                        .chain(ref_obligations.iter().cloned())
+                        .collect()
                 }
 
                 ObjectCandidate |
-                TraitCandidate |
                 WhereClauseCandidate(..) => {
                     // These have no additional conditions to check.
-                    return true;
+                    vec![]
                 }
-            };
-
-            let selcx = &mut traits::SelectionContext::new(self);
-            let cause = traits::ObligationCause::misc(self.span, self.body_id);
 
-            // Check whether the impl imposes obligations we have to worry about.
-            let impl_bounds = self.tcx.item_predicates(impl_def_id);
-            let impl_bounds = impl_bounds.instantiate(self.tcx, substs);
-            let traits::Normalized { value: impl_bounds, obligations: norm_obligations } =
-                traits::normalize(selcx, cause.clone(), &impl_bounds);
+                TraitCandidate(trait_ref) => {
+                    let predicate = trait_ref.to_predicate();
+                    let obligation =
+                        traits::Obligation::new(cause.clone(), self.param_env, predicate);
+                    if !selcx.evaluate_obligation(&obligation) {
+                        if self.probe(|_| self.select_trait_candidate(trait_ref).is_err()) {
+                            // This candidate's primary obligation doesn't even
+                            // select - don't bother registering anything in
+                            // `potentially_unsatisfied_predicates`.
+                            return ProbeResult::NoMatch;
+                        } else {
+                            // Some nested subobligation of this predicate
+                            // failed.
+                            //
+                            // FIXME: try to find the exact nested subobligation
+                            // and point at it rather than reporting the entire
+                            // trait-ref?
+                            result = ProbeResult::NoMatch;
+                            let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
+                            possibly_unsatisfied_predicates.push(trait_ref);
+                        }
+                    }
+                    vec![]
+                }
+            };
 
-            // Convert the bounds into obligations.
-            let obligations = traits::predicates_for_generics(cause.clone(), &impl_bounds);
-            debug!("impl_obligations={:?}", obligations);
+            debug!("consider_probe - candidate_obligations={:?} sub_obligations={:?}",
+                   candidate_obligations, sub_obligations);
 
             // Evaluate those obligations to see if they might possibly hold.
-            let mut all_true = true;
-            for o in obligations.iter()
-                .chain(norm_obligations.iter())
-                .chain(ref_obligations.iter()) {
-                if !selcx.evaluate_obligation(o) {
-                    all_true = false;
+            for o in candidate_obligations.into_iter().chain(sub_obligations) {
+                let o = self.resolve_type_vars_if_possible(&o);
+                if !selcx.evaluate_obligation(&o) {
+                    result = ProbeResult::NoMatch;
                     if let &ty::Predicate::Trait(ref pred) = &o.predicate {
                         possibly_unsatisfied_predicates.push(pred.0.trait_ref);
                     }
                 }
             }
-            all_true
+
+            if let ProbeResult::Match = result {
+                if let (Some(return_ty), Some(xform_ret_ty)) =
+                    (self.return_type, probe.xform_ret_ty)
+                {
+                    let xform_ret_ty = self.resolve_type_vars_if_possible(&xform_ret_ty);
+                    debug!("comparing return_ty {:?} with xform ret ty {:?}",
+                           return_ty,
+                           probe.xform_ret_ty);
+                    if self.at(&ObligationCause::dummy(), self.param_env)
+                        .sup(return_ty, xform_ret_ty)
+                        .is_err()
+                    {
+                        return ProbeResult::BadReturnType;
+                    }
+                }
+            }
+
+            result
         })
     }
 
@@ -1115,28 +1148,79 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
     ///
     /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
     /// use, so it's ok to just commit to "using the method from the trait Foo".
-    fn collapse_candidates_to_trait_pick(&self, probes: &[&Candidate<'tcx>]) -> Option<Pick<'tcx>> {
+    fn collapse_candidates_to_trait_pick(&self, probes: &[(&Candidate<'tcx>, ProbeResult)])
+                                         -> Option<Pick<'tcx>>
+    {
         // Do all probes correspond to the same trait?
-        let container = probes[0].item.container;
+        let container = probes[0].0.item.container;
         match container {
             ty::TraitContainer(_) => {}
             ty::ImplContainer(_) => return None,
         }
-        if probes[1..].iter().any(|p| p.item.container != container) {
+        if probes[1..].iter().any(|&(p, _)| p.item.container != container) {
             return None;
         }
 
+        // FIXME: check the return type here somehow.
         // If so, just use this trait and call it a day.
         Some(Pick {
-            item: probes[0].item.clone(),
+            item: probes[0].0.item.clone(),
             kind: TraitPick,
-            import_id: probes[0].import_id,
+            import_id: probes[0].0.import_id,
             autoderefs: 0,
             autoref: None,
             unsize: None,
         })
     }
 
+    /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
+    /// candidate method where the method name may have been misspelt. Similarly to other
+    /// Levenshtein based suggestions, we provide at most one such suggestion.
+    fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssociatedItem>, MethodError<'tcx>> {
+        debug!("Probing for method names similar to {:?}",
+               self.method_name);
+
+        let steps = self.steps.clone();
+        self.probe(|_| {
+            let mut pcx = ProbeContext::new(self.fcx, self.span, self.mode, self.method_name,
+                                            self.return_type, steps);
+            pcx.allow_similar_names = true;
+            pcx.assemble_inherent_candidates();
+            pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)?;
+
+            let method_names = pcx.candidate_method_names();
+            pcx.allow_similar_names = false;
+            let applicable_close_candidates: Vec<ty::AssociatedItem> = method_names
+                .iter()
+                .filter_map(|&method_name| {
+                    pcx.reset();
+                    pcx.method_name = Some(method_name);
+                    pcx.assemble_inherent_candidates();
+                    pcx.assemble_extension_candidates_for_traits_in_scope(ast::DUMMY_NODE_ID)
+                        .ok().map_or(None, |_| {
+                            pcx.pick_core()
+                                .and_then(|pick| pick.ok())
+                                .and_then(|pick| Some(pick.item))
+                        })
+                })
+               .collect();
+
+            if applicable_close_candidates.is_empty() {
+                Ok(None)
+            } else {
+                let best_name = {
+                    let names = applicable_close_candidates.iter().map(|cand| &cand.name);
+                    find_best_match_for_name(names,
+                                             &self.method_name.unwrap().as_str(),
+                                             None)
+                }.unwrap();
+                Ok(applicable_close_candidates
+                   .into_iter()
+                   .find(|method| method.name == best_name))
+            }
+        })
+    }
+
     ///////////////////////////////////////////////////////////////////////////
     // MISCELLANY
     fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool {
@@ -1168,23 +1252,23 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
                      item: &ty::AssociatedItem,
                      impl_ty: Ty<'tcx>,
                      substs: &Substs<'tcx>)
-                     -> Ty<'tcx> {
+                     -> (Ty<'tcx>, Option<Ty<'tcx>>) {
         if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall {
-            self.xform_method_self_ty(item.def_id, impl_ty, substs)
+            let sig = self.xform_method_sig(item.def_id, substs);
+            (sig.inputs()[0], Some(sig.output()))
         } else {
-            impl_ty
+            (impl_ty, None)
         }
     }
 
-    fn xform_method_self_ty(&self,
-                            method: DefId,
-                            impl_ty: Ty<'tcx>,
-                            substs: &Substs<'tcx>)
-                            -> Ty<'tcx> {
-        let self_ty = self.tcx.item_type(method).fn_sig().input(0);
-        debug!("xform_self_ty(impl_ty={:?}, self_ty={:?}, substs={:?})",
-               impl_ty,
-               self_ty,
+    fn xform_method_sig(&self,
+                        method: DefId,
+                        substs: &Substs<'tcx>)
+                        -> ty::FnSig<'tcx>
+    {
+        let fn_sig = self.tcx.fn_sig(method);
+        debug!("xform_self_ty(fn_sig={:?}, substs={:?})",
+               fn_sig,
                substs);
 
         assert!(!substs.has_escaping_regions());
@@ -1194,50 +1278,50 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
         // are given do not include type/lifetime parameters for the
         // method yet. So create fresh variables here for those too,
         // if there are any.
-        let generics = self.tcx.item_generics(method);
+        let generics = self.tcx.generics_of(method);
         assert_eq!(substs.types().count(), generics.parent_types as usize);
         assert_eq!(substs.regions().count(), generics.parent_regions as usize);
 
         // Erase any late-bound regions from the method and substitute
         // in the values from the substitution.
-        let xform_self_ty = self.erase_late_bound_regions(&self_ty);
+        let xform_fn_sig = self.erase_late_bound_regions(&fn_sig);
 
         if generics.types.is_empty() && generics.regions.is_empty() {
-            xform_self_ty.subst(self.tcx, substs)
+            xform_fn_sig.subst(self.tcx, substs)
         } else {
             let substs = Substs::for_item(self.tcx, method, |def, _| {
                 let i = def.index as usize;
-                if i < substs.params().len() {
+                if i < substs.len() {
                     substs.region_at(i)
                 } else {
                     // In general, during probe we erase regions. See
                     // `impl_self_ty()` for an explanation.
-                    self.tcx.mk_region(ty::ReErased)
+                    self.tcx.types.re_erased
                 }
             }, |def, cur_substs| {
                 let i = def.index as usize;
-                if i < substs.params().len() {
+                if i < substs.len() {
                     substs.type_at(i)
                 } else {
                     self.type_var_for_def(self.span, def, cur_substs)
                 }
             });
-            xform_self_ty.subst(self.tcx, substs)
+            xform_fn_sig.subst(self.tcx, substs)
         }
     }
 
     /// Get the type of an impl and generate substitutions with placeholders.
     fn impl_ty_and_substs(&self, impl_def_id: DefId) -> (Ty<'tcx>, &'tcx Substs<'tcx>) {
-        let impl_ty = self.tcx.item_type(impl_def_id);
-
-        let substs = Substs::for_item(self.tcx,
-                                      impl_def_id,
-                                      |_, _| self.tcx.mk_region(ty::ReErased),
-                                      |_, _| self.next_ty_var(
-                                        TypeVariableOrigin::SubstitutionPlaceholder(
-                                            self.tcx.def_span(impl_def_id))));
+        (self.tcx.type_of(impl_def_id), self.fresh_item_substs(impl_def_id))
+    }
 
-        (impl_ty, substs)
+    fn fresh_item_substs(&self, def_id: DefId) -> &'tcx Substs<'tcx> {
+        Substs::for_item(self.tcx,
+                         def_id,
+                         |_, _| self.tcx.types.re_erased,
+                         |_, _| self.next_ty_var(
+                             TypeVariableOrigin::SubstitutionPlaceholder(
+                                 self.tcx.def_span(def_id))))
     }
 
     /// Replace late-bound-regions bound by `value` with `'static` using
@@ -1264,10 +1348,27 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
         self.tcx.erase_late_bound_regions(value)
     }
 
-    /// Find item with name `item_name` defined in impl/trait `def_id`
-    /// and return it, or `None`, if no such item was defined there.
-    fn associated_item(&self, def_id: DefId) -> Option<ty::AssociatedItem> {
-        self.fcx.associated_item(def_id, self.item_name)
+    /// Find the method with the appropriate name (or return type, as the case may be). If
+    /// `allow_similar_names` is set, find methods with close-matching names.
+    fn impl_or_trait_item(&self, def_id: DefId) -> Vec<ty::AssociatedItem> {
+        if let Some(name) = self.method_name {
+            if self.allow_similar_names {
+                let max_dist = max(name.as_str().len(), 3) / 3;
+                self.tcx.associated_items(def_id)
+                    .filter(|x| {
+                        let dist = lev_distance(&*name.as_str(), &x.name.as_str());
+                        Namespace::from(x.kind) == Namespace::Value && dist > 0
+                        && dist <= max_dist
+                    })
+                    .collect()
+            } else {
+                self.fcx
+                    .associated_item(def_id, name, Namespace::Value)
+                    .map_or(Vec::new(), |x| vec![x])
+            }
+        } else {
+            self.tcx.associated_items(def_id).collect()
+        }
     }
 }
 
@@ -1277,9 +1378,8 @@ impl<'tcx> Candidate<'tcx> {
             item: self.item.clone(),
             kind: match self.kind {
                 InherentImplCandidate(..) => InherentImplPick,
-                ExtensionImplCandidate(def_id, ..) => ExtensionImplPick(def_id),
                 ObjectCandidate => ObjectPick,
-                TraitCandidate => TraitPick,
+                TraitCandidate(_) => TraitPick,
                 WhereClauseCandidate(ref trait_ref) => {
                     // Only trait derived from where-clauses should
                     // appear here, so they should not contain any
@@ -1297,14 +1397,4 @@ impl<'tcx> Candidate<'tcx> {
             unsize: None,
         }
     }
-
-    fn to_source(&self) -> CandidateSource {
-        match self.kind {
-            InherentImplCandidate(..) => ImplSource(self.item.container.id()),
-            ExtensionImplCandidate(def_id, ..) => ImplSource(def_id),
-            ObjectCandidate |
-            TraitCandidate |
-            WhereClauseCandidate(_) => TraitSource(self.item.container.id()),
-        }
-    }
 }