1 // Copyright 2014 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.
11 //! Method lookup: the secret sauce of Rust. See `README.md`.
15 use hir
::def_id
::DefId
;
16 use namespace
::Namespace
;
17 use rustc
::ty
::subst
::Substs
;
19 use rustc
::ty
::{self, Ty, ToPredicate, ToPolyTraitRef, TraitRef, TypeFoldable}
;
20 use rustc
::ty
::subst
::Subst
;
21 use rustc
::infer
::{self, InferOk}
;
30 pub use self::MethodError
::*;
31 pub use self::CandidateSource
::*;
37 use self::probe
::{IsSuggestion, ProbeScope}
;
39 #[derive(Clone, Copy, Debug)]
40 pub struct MethodCallee
<'tcx
> {
41 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
43 pub substs
: &'tcx Substs
<'tcx
>,
45 /// Instantiated method signature, i.e. it has been
46 /// substituted, normalized, and has had late-bound
47 /// lifetimes replaced with inference variables.
48 pub sig
: ty
::FnSig
<'tcx
>,
51 pub enum MethodError
<'tcx
> {
52 // Did not find an applicable method, but we did find various near-misses that may work.
53 NoMatch(NoMatchData
<'tcx
>),
55 // Multiple methods might apply.
56 Ambiguity(Vec
<CandidateSource
>),
58 // Found an applicable method, but it is not visible. The second argument contains a list of
59 // not-in-scope traits which may work.
60 PrivateMatch(Def
, Vec
<DefId
>),
62 // Found a `Self: Sized` bound where `Self` is a trait object, also the caller may have
63 // forgotten to import a trait.
64 IllegalSizedBound(Vec
<DefId
>),
66 // Found a match, but the return type is wrong
70 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
71 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
72 pub struct NoMatchData
<'tcx
> {
73 pub static_candidates
: Vec
<CandidateSource
>,
74 pub unsatisfied_predicates
: Vec
<TraitRef
<'tcx
>>,
75 pub out_of_scope_traits
: Vec
<DefId
>,
76 pub lev_candidate
: Option
<ty
::AssociatedItem
>,
77 pub mode
: probe
::Mode
,
80 impl<'tcx
> NoMatchData
<'tcx
> {
81 pub fn new(static_candidates
: Vec
<CandidateSource
>,
82 unsatisfied_predicates
: Vec
<TraitRef
<'tcx
>>,
83 out_of_scope_traits
: Vec
<DefId
>,
84 lev_candidate
: Option
<ty
::AssociatedItem
>,
89 unsatisfied_predicates
,
97 // A pared down enum describing just the places from which a method
98 // candidate can arise. Used for error reporting only.
99 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
100 pub enum CandidateSource
{
102 TraitSource(// trait id
106 impl<'a
, 'gcx
, 'tcx
> FnCtxt
<'a
, 'gcx
, 'tcx
> {
107 /// Determines whether the type `self_ty` supports a method name `method_name` or not.
108 pub fn method_exists(&self,
110 method_name
: ast
::Name
,
112 call_expr_id
: ast
::NodeId
,
115 let mode
= probe
::Mode
::MethodCall
;
116 match self.probe_for_name(span
, mode
, method_name
, IsSuggestion(false),
117 self_ty
, call_expr_id
, ProbeScope
::TraitsInScope
) {
119 Err(NoMatch(..)) => false,
120 Err(Ambiguity(..)) => true,
121 Err(PrivateMatch(..)) => allow_private
,
122 Err(IllegalSizedBound(..)) => true,
123 Err(BadReturnType
) => {
124 bug
!("no return type expectations but got BadReturnType")
130 /// Performs method lookup. If lookup is successful, it will return the callee
131 /// and store an appropriate adjustment for the self-expr. In some cases it may
132 /// report an error (e.g., invoking the `drop` method).
136 /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
138 /// * `fcx`: the surrounding `FnCtxt` (!)
139 /// * `span`: the span for the method call
140 /// * `method_name`: the name of the method being called (`bar`)
141 /// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
142 /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
143 /// * `self_expr`: the self expression (`foo`)
144 pub fn lookup_method(&self,
146 segment
: &hir
::PathSegment
,
148 call_expr
: &'gcx hir
::Expr
,
149 self_expr
: &'gcx hir
::Expr
)
150 -> Result
<MethodCallee
<'tcx
>, MethodError
<'tcx
>> {
151 debug
!("lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
157 let pick
= self.lookup_probe(
162 ProbeScope
::TraitsInScope
165 if let Some(import_id
) = pick
.import_id
{
166 let import_def_id
= self.tcx
.hir
.local_def_id(import_id
);
167 debug
!("used_trait_import: {:?}", import_def_id
);
168 Rc
::get_mut(&mut self.tables
.borrow_mut().used_trait_imports
)
169 .unwrap().insert(import_def_id
);
172 self.tcx
.check_stability(pick
.item
.def_id
, call_expr
.id
, span
);
174 let result
= self.confirm_method(span
,
181 if result
.illegal_sized_bound
{
182 // We probe again, taking all traits into account (not only those in scope).
184 match self.lookup_probe(span
,
188 ProbeScope
::AllTraits
) {
190 // If we find a different result the caller probably forgot to import a trait.
191 Ok(ref new_pick
) if *new_pick
!= pick
=> vec
![new_pick
.item
.container
.id()],
192 Err(Ambiguity(ref sources
)) => {
194 .filter_map(|source
| {
196 // Note: this cannot come from an inherent impl,
197 // because the first probing succeeded.
198 ImplSource(def
) => self.tcx
.trait_id_of_impl(def
),
199 TraitSource(_
) => None
,
207 return Err(IllegalSizedBound(candidates
));
213 fn lookup_probe(&self,
215 method_name
: ast
::Name
,
217 call_expr
: &'gcx hir
::Expr
,
219 -> probe
::PickResult
<'tcx
> {
220 let mode
= probe
::Mode
::MethodCall
;
221 let self_ty
= self.resolve_type_vars_if_possible(&self_ty
);
222 self.probe_for_name(span
, mode
, method_name
, IsSuggestion(false),
223 self_ty
, call_expr
.id
, scope
)
226 /// `lookup_method_in_trait` is used for overloaded operators.
227 /// It does a very narrow slice of what the normal probe/confirm path does.
228 /// In particular, it doesn't really do any probing: it simply constructs
229 /// an obligation for a particular trait with the given self-type and checks
230 /// whether that trait is implemented.
232 /// FIXME(#18741) -- It seems likely that we can consolidate some of this
233 /// code with the other method-lookup code. In particular, the second half
234 /// of this method is basically the same as confirmation.
235 pub fn lookup_method_in_trait(&self,
240 opt_input_types
: Option
<&[Ty
<'tcx
>]>)
241 -> Option
<InferOk
<'tcx
, MethodCallee
<'tcx
>>> {
242 debug
!("lookup_in_trait_adjusted(self_ty={:?}, \
243 m_name={}, trait_def_id={:?})",
248 // Construct a trait-reference `self_ty : Trait<input_tys>`
249 let substs
= Substs
::for_item(self.tcx
,
251 |def
, _
| self.region_var_for_def(span
, def
),
255 } else if let Some(ref input_types
) = opt_input_types
{
256 input_types
[def
.index
as usize - 1]
258 self.type_var_for_def(span
, def
, substs
)
262 let trait_ref
= ty
::TraitRef
::new(trait_def_id
, substs
);
264 // Construct an obligation
265 let poly_trait_ref
= trait_ref
.to_poly_trait_ref();
267 traits
::Obligation
::misc(span
,
270 poly_trait_ref
.to_predicate());
272 // Now we want to know if this can be matched
273 let mut selcx
= traits
::SelectionContext
::new(self);
274 if !selcx
.evaluate_obligation(&obligation
) {
275 debug
!("--> Cannot match obligation");
276 return None
; // Cannot be matched, no such method resolution is possible.
279 // Trait must have a method named `m_name` and it should not have
280 // type parameters or early-bound regions.
282 let method_item
= self.associated_item(trait_def_id
, m_name
, Namespace
::Value
).unwrap();
283 let def_id
= method_item
.def_id
;
284 let generics
= tcx
.generics_of(def_id
);
285 assert_eq
!(generics
.types
.len(), 0);
286 assert_eq
!(generics
.regions
.len(), 0);
288 debug
!("lookup_in_trait_adjusted: method_item={:?}", method_item
);
289 let mut obligations
= vec
![];
291 // Instantiate late-bound regions and substitute the trait
292 // parameters into the method type to get the actual method type.
294 // NB: Instantiate late-bound regions first so that
295 // `instantiate_type_scheme` can normalize associated types that
296 // may reference those regions.
297 let fn_sig
= tcx
.fn_sig(def_id
);
298 let fn_sig
= self.replace_late_bound_regions_with_fresh_var(span
,
301 let fn_sig
= fn_sig
.subst(self.tcx
, substs
);
302 let fn_sig
= match self.normalize_associated_types_in_as_infer_ok(span
, &fn_sig
) {
303 InferOk { value, obligations: o }
=> {
304 obligations
.extend(o
);
309 // Register obligations for the parameters. This will include the
310 // `Self` parameter, which in turn has a bound of the main trait,
311 // so this also effectively registers `obligation` as well. (We
312 // used to register `obligation` explicitly, but that resulted in
313 // double error messages being reported.)
315 // Note that as the method comes from a trait, it should not have
316 // any late-bound regions appearing in its bounds.
317 let bounds
= self.tcx
.predicates_of(def_id
).instantiate(self.tcx
, substs
);
318 let bounds
= match self.normalize_associated_types_in_as_infer_ok(span
, &bounds
) {
319 InferOk { value, obligations: o }
=> {
320 obligations
.extend(o
);
324 assert
!(!bounds
.has_escaping_regions());
326 let cause
= traits
::ObligationCause
::misc(span
, self.body_id
);
327 obligations
.extend(traits
::predicates_for_generics(cause
.clone(),
331 // Also add an obligation for the method type being well-formed.
332 let method_ty
= tcx
.mk_fn_ptr(ty
::Binder(fn_sig
));
333 debug
!("lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
336 obligations
.push(traits
::Obligation
::new(cause
,
338 ty
::Predicate
::WellFormed(method_ty
)));
340 let callee
= MethodCallee
{
342 substs
: trait_ref
.substs
,
346 debug
!("callee = {:?}", callee
);
354 pub fn resolve_ufcs(&self,
356 method_name
: ast
::Name
,
358 expr_id
: ast
::NodeId
)
359 -> Result
<Def
, MethodError
<'tcx
>> {
360 let mode
= probe
::Mode
::Path
;
361 let pick
= self.probe_for_name(span
, mode
, method_name
, IsSuggestion(false),
362 self_ty
, expr_id
, ProbeScope
::TraitsInScope
)?
;
364 if let Some(import_id
) = pick
.import_id
{
365 let import_def_id
= self.tcx
.hir
.local_def_id(import_id
);
366 debug
!("used_trait_import: {:?}", import_def_id
);
367 Rc
::get_mut(&mut self.tables
.borrow_mut().used_trait_imports
)
368 .unwrap().insert(import_def_id
);
371 let def
= pick
.item
.def();
372 self.tcx
.check_stability(def
.def_id(), expr_id
, span
);
377 /// Find item with name `item_name` defined in impl/trait `def_id`
378 /// and return it, or `None`, if no such item was defined there.
379 pub fn associated_item(&self, def_id
: DefId
, item_name
: ast
::Name
, ns
: Namespace
)
380 -> Option
<ty
::AssociatedItem
> {
381 self.tcx
.associated_items(def_id
)
382 .find(|item
| Namespace
::from(item
.kind
) == ns
&&
383 self.tcx
.hygienic_eq(item_name
, item
.name
, def_id
))