]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/method/mod.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / librustc_typeck / check / method / mod.rs
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.
4 //
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.
10
11 //! Method lookup: the secret sauce of Rust. See `README.md`.
12
13 use check::FnCtxt;
14 use hir::def::Def;
15 use hir::def_id::DefId;
16 use namespace::Namespace;
17 use rustc::ty::subst::Substs;
18 use rustc::traits;
19 use rustc::ty::{self, Ty, ToPredicate, ToPolyTraitRef, TraitRef, TypeFoldable};
20 use rustc::ty::subst::Subst;
21 use rustc::infer::{self, InferOk};
22
23 use syntax::ast;
24 use syntax_pos::Span;
25
26 use rustc::hir;
27
28 use std::rc::Rc;
29
30 pub use self::MethodError::*;
31 pub use self::CandidateSource::*;
32
33 mod confirm;
34 pub mod probe;
35 mod suggest;
36
37 use self::probe::{IsSuggestion, ProbeScope};
38
39 #[derive(Clone, Copy, Debug)]
40 pub struct MethodCallee<'tcx> {
41 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
42 pub def_id: DefId,
43 pub substs: &'tcx Substs<'tcx>,
44
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>,
49 }
50
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>),
54
55 // Multiple methods might apply.
56 Ambiguity(Vec<CandidateSource>),
57
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>),
61
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>),
65
66 // Found a match, but the return type is wrong
67 BadReturnType,
68 }
69
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,
78 }
79
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>,
85 mode: probe::Mode)
86 -> Self {
87 NoMatchData {
88 static_candidates,
89 unsatisfied_predicates,
90 out_of_scope_traits,
91 lev_candidate,
92 mode,
93 }
94 }
95 }
96
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 {
101 ImplSource(DefId),
102 TraitSource(// trait id
103 DefId),
104 }
105
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,
109 span: Span,
110 method_name: ast::Name,
111 self_ty: Ty<'tcx>,
112 call_expr_id: ast::NodeId,
113 allow_private: bool)
114 -> bool {
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) {
118 Ok(..) => true,
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")
125 }
126
127 }
128 }
129
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).
133 ///
134 /// # Arguments
135 ///
136 /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
137 ///
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,
145 self_ty: Ty<'tcx>,
146 segment: &hir::PathSegment,
147 span: Span,
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={:?})",
152 segment.name,
153 self_ty,
154 call_expr,
155 self_expr);
156
157 let pick = self.lookup_probe(
158 span,
159 segment.name,
160 self_ty,
161 call_expr,
162 ProbeScope::TraitsInScope
163 )?;
164
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);
170 }
171
172 self.tcx.check_stability(pick.item.def_id, call_expr.id, span);
173
174 let result = self.confirm_method(span,
175 self_expr,
176 call_expr,
177 self_ty,
178 pick.clone(),
179 segment);
180
181 if result.illegal_sized_bound {
182 // We probe again, taking all traits into account (not only those in scope).
183 let candidates =
184 match self.lookup_probe(span,
185 segment.name,
186 self_ty,
187 call_expr,
188 ProbeScope::AllTraits) {
189
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)) => {
193 sources.iter()
194 .filter_map(|source| {
195 match *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,
200 }
201 })
202 .collect()
203 }
204 _ => Vec::new(),
205 };
206
207 return Err(IllegalSizedBound(candidates));
208 }
209
210 Ok(result.callee)
211 }
212
213 fn lookup_probe(&self,
214 span: Span,
215 method_name: ast::Name,
216 self_ty: Ty<'tcx>,
217 call_expr: &'gcx hir::Expr,
218 scope: ProbeScope)
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)
224 }
225
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.
231 ///
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,
236 span: Span,
237 m_name: ast::Name,
238 trait_def_id: DefId,
239 self_ty: Ty<'tcx>,
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={:?})",
244 self_ty,
245 m_name,
246 trait_def_id);
247
248 // Construct a trait-reference `self_ty : Trait<input_tys>`
249 let substs = Substs::for_item(self.tcx,
250 trait_def_id,
251 |def, _| self.region_var_for_def(span, def),
252 |def, substs| {
253 if def.index == 0 {
254 self_ty
255 } else if let Some(ref input_types) = opt_input_types {
256 input_types[def.index as usize - 1]
257 } else {
258 self.type_var_for_def(span, def, substs)
259 }
260 });
261
262 let trait_ref = ty::TraitRef::new(trait_def_id, substs);
263
264 // Construct an obligation
265 let poly_trait_ref = trait_ref.to_poly_trait_ref();
266 let obligation =
267 traits::Obligation::misc(span,
268 self.body_id,
269 self.param_env,
270 poly_trait_ref.to_predicate());
271
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.
277 }
278
279 // Trait must have a method named `m_name` and it should not have
280 // type parameters or early-bound regions.
281 let tcx = self.tcx;
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);
287
288 debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
289 let mut obligations = vec![];
290
291 // Instantiate late-bound regions and substitute the trait
292 // parameters into the method type to get the actual method type.
293 //
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,
299 infer::FnCall,
300 &fn_sig).0;
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);
305 value
306 }
307 };
308
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.)
314 //
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);
321 value
322 }
323 };
324 assert!(!bounds.has_escaping_regions());
325
326 let cause = traits::ObligationCause::misc(span, self.body_id);
327 obligations.extend(traits::predicates_for_generics(cause.clone(),
328 self.param_env,
329 &bounds));
330
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={:?}",
334 method_ty,
335 obligation);
336 obligations.push(traits::Obligation::new(cause,
337 self.param_env,
338 ty::Predicate::WellFormed(method_ty)));
339
340 let callee = MethodCallee {
341 def_id,
342 substs: trait_ref.substs,
343 sig: fn_sig,
344 };
345
346 debug!("callee = {:?}", callee);
347
348 Some(InferOk {
349 obligations,
350 value: callee
351 })
352 }
353
354 pub fn resolve_ufcs(&self,
355 span: Span,
356 method_name: ast::Name,
357 self_ty: Ty<'tcx>,
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)?;
363
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);
369 }
370
371 let def = pick.item.def();
372 self.tcx.check_stability(def.def_id(), expr_id, span);
373
374 Ok(def)
375 }
376
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))
384 }
385 }