]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/mod.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_typeck / check / method / mod.rs
1 //! Method lookup: the secret sauce of Rust. See the [rustc dev guide] for more information.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/method-lookup.html
4
5 mod confirm;
6 pub mod probe;
7 mod suggest;
8
9 pub use self::suggest::{SelfSource, TraitInfo};
10 pub use self::CandidateSource::*;
11 pub use self::MethodError::*;
12
13 use crate::check::FnCtxt;
14 use rustc::ty::subst::Subst;
15 use rustc::ty::subst::{InternalSubsts, SubstsRef};
16 use rustc::ty::GenericParamDefKind;
17 use rustc::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TypeFoldable, WithConstness};
18 use rustc_ast::ast;
19 use rustc_data_structures::sync::Lrc;
20 use rustc_errors::{Applicability, DiagnosticBuilder};
21 use rustc_hir as hir;
22 use rustc_hir::def::{CtorOf, DefKind, Namespace};
23 use rustc_hir::def_id::DefId;
24 use rustc_infer::infer::{self, InferOk};
25 use rustc_span::Span;
26 use rustc_trait_selection::traits;
27 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
28
29 use self::probe::{IsSuggestion, ProbeScope};
30
31 pub fn provide(providers: &mut ty::query::Providers<'_>) {
32     suggest::provide(providers);
33     probe::provide(providers);
34 }
35
36 #[derive(Clone, Copy, Debug)]
37 pub struct MethodCallee<'tcx> {
38     /// Impl method ID, for inherent methods, or trait method ID, otherwise.
39     pub def_id: DefId,
40     pub substs: SubstsRef<'tcx>,
41
42     /// Instantiated method signature, i.e., it has been
43     /// substituted, normalized, and has had late-bound
44     /// lifetimes replaced with inference variables.
45     pub sig: ty::FnSig<'tcx>,
46 }
47
48 pub enum MethodError<'tcx> {
49     // Did not find an applicable method, but we did find various near-misses that may work.
50     NoMatch(NoMatchData<'tcx>),
51
52     // Multiple methods might apply.
53     Ambiguity(Vec<CandidateSource>),
54
55     // Found an applicable method, but it is not visible. The third argument contains a list of
56     // not-in-scope traits which may work.
57     PrivateMatch(DefKind, DefId, Vec<DefId>),
58
59     // Found a `Self: Sized` bound where `Self` is a trait object, also the caller may have
60     // forgotten to import a trait.
61     IllegalSizedBound(Vec<DefId>, bool, Span),
62
63     // Found a match, but the return type is wrong
64     BadReturnType,
65 }
66
67 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
68 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
69 pub struct NoMatchData<'tcx> {
70     pub static_candidates: Vec<CandidateSource>,
71     pub unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
72     pub out_of_scope_traits: Vec<DefId>,
73     pub lev_candidate: Option<ty::AssocItem>,
74     pub mode: probe::Mode,
75 }
76
77 impl<'tcx> NoMatchData<'tcx> {
78     pub fn new(
79         static_candidates: Vec<CandidateSource>,
80         unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
81         out_of_scope_traits: Vec<DefId>,
82         lev_candidate: Option<ty::AssocItem>,
83         mode: probe::Mode,
84     ) -> Self {
85         NoMatchData {
86             static_candidates,
87             unsatisfied_predicates,
88             out_of_scope_traits,
89             lev_candidate,
90             mode,
91         }
92     }
93 }
94
95 // A pared down enum describing just the places from which a method
96 // candidate can arise. Used for error reporting only.
97 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
98 pub enum CandidateSource {
99     ImplSource(DefId),
100     TraitSource(DefId /* trait id */),
101 }
102
103 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
104     /// Determines whether the type `self_ty` supports a method name `method_name` or not.
105     pub fn method_exists(
106         &self,
107         method_name: ast::Ident,
108         self_ty: Ty<'tcx>,
109         call_expr_id: hir::HirId,
110         allow_private: bool,
111     ) -> bool {
112         let mode = probe::Mode::MethodCall;
113         match self.probe_for_name(
114             method_name.span,
115             mode,
116             method_name,
117             IsSuggestion(false),
118             self_ty,
119             call_expr_id,
120             ProbeScope::TraitsInScope,
121         ) {
122             Ok(..) => true,
123             Err(NoMatch(..)) => false,
124             Err(Ambiguity(..)) => true,
125             Err(PrivateMatch(..)) => allow_private,
126             Err(IllegalSizedBound(..)) => true,
127             Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
128         }
129     }
130
131     /// Adds a suggestion to call the given method to the provided diagnostic.
132     crate fn suggest_method_call(
133         &self,
134         err: &mut DiagnosticBuilder<'a>,
135         msg: &str,
136         method_name: ast::Ident,
137         self_ty: Ty<'tcx>,
138         call_expr: &hir::Expr<'_>,
139     ) {
140         let has_params = self
141             .probe_for_name(
142                 method_name.span,
143                 probe::Mode::MethodCall,
144                 method_name,
145                 IsSuggestion(false),
146                 self_ty,
147                 call_expr.hir_id,
148                 ProbeScope::TraitsInScope,
149             )
150             .and_then(|pick| {
151                 let sig = self.tcx.fn_sig(pick.item.def_id);
152                 Ok(sig.inputs().skip_binder().len() > 1)
153             });
154
155         // Account for `foo.bar<T>`;
156         let sugg_span = method_name.span.with_hi(call_expr.span.hi());
157         let snippet = self
158             .tcx
159             .sess
160             .source_map()
161             .span_to_snippet(sugg_span)
162             .unwrap_or_else(|_| method_name.to_string());
163         let (suggestion, applicability) = if has_params.unwrap_or_default() {
164             (format!("{}(...)", snippet), Applicability::HasPlaceholders)
165         } else {
166             (format!("{}()", snippet), Applicability::MaybeIncorrect)
167         };
168
169         err.span_suggestion(sugg_span, msg, suggestion, applicability);
170     }
171
172     /// Performs method lookup. If lookup is successful, it will return the callee
173     /// and store an appropriate adjustment for the self-expr. In some cases it may
174     /// report an error (e.g., invoking the `drop` method).
175     ///
176     /// # Arguments
177     ///
178     /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
179     ///
180     /// * `fcx`:                   the surrounding `FnCtxt` (!)
181     /// * `span`:                  the span for the method call
182     /// * `method_name`:           the name of the method being called (`bar`)
183     /// * `self_ty`:               the (unadjusted) type of the self expression (`foo`)
184     /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
185     /// * `self_expr`:             the self expression (`foo`)
186     pub fn lookup_method(
187         &self,
188         self_ty: Ty<'tcx>,
189         segment: &hir::PathSegment<'_>,
190         span: Span,
191         call_expr: &'tcx hir::Expr<'tcx>,
192         self_expr: &'tcx hir::Expr<'tcx>,
193     ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
194         debug!(
195             "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
196             segment.ident, self_ty, call_expr, self_expr
197         );
198
199         let pick =
200             self.lookup_probe(span, segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
201
202         for import_id in &pick.import_ids {
203             let import_def_id = self.tcx.hir().local_def_id(*import_id);
204             debug!("used_trait_import: {:?}", import_def_id);
205             Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports)
206                 .unwrap()
207                 .insert(import_def_id);
208         }
209
210         self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span);
211
212         let result =
213             self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment);
214
215         if let Some(span) = result.illegal_sized_bound {
216             let mut needs_mut = false;
217             if let ty::Ref(region, t_type, mutability) = self_ty.kind {
218                 let trait_type = self
219                     .tcx
220                     .mk_ref(region, ty::TypeAndMut { ty: t_type, mutbl: mutability.invert() });
221                 // We probe again to see if there might be a borrow mutability discrepancy.
222                 match self.lookup_probe(
223                     span,
224                     segment.ident,
225                     trait_type,
226                     call_expr,
227                     ProbeScope::TraitsInScope,
228                 ) {
229                     Ok(ref new_pick) if *new_pick != pick => {
230                         needs_mut = true;
231                     }
232                     _ => {}
233                 }
234             }
235
236             // We probe again, taking all traits into account (not only those in scope).
237             let candidates = match self.lookup_probe(
238                 span,
239                 segment.ident,
240                 self_ty,
241                 call_expr,
242                 ProbeScope::AllTraits,
243             ) {
244                 // If we find a different result the caller probably forgot to import a trait.
245                 Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
246                 Err(Ambiguity(ref sources)) => sources
247                     .iter()
248                     .filter_map(|source| {
249                         match *source {
250                             // Note: this cannot come from an inherent impl,
251                             // because the first probing succeeded.
252                             ImplSource(def) => self.tcx.trait_id_of_impl(def),
253                             TraitSource(_) => None,
254                         }
255                     })
256                     .collect(),
257                 _ => Vec::new(),
258             };
259
260             return Err(IllegalSizedBound(candidates, needs_mut, span));
261         }
262
263         Ok(result.callee)
264     }
265
266     pub fn lookup_probe(
267         &self,
268         span: Span,
269         method_name: ast::Ident,
270         self_ty: Ty<'tcx>,
271         call_expr: &'tcx hir::Expr<'tcx>,
272         scope: ProbeScope,
273     ) -> probe::PickResult<'tcx> {
274         let mode = probe::Mode::MethodCall;
275         let self_ty = self.resolve_vars_if_possible(&self_ty);
276         self.probe_for_name(
277             span,
278             mode,
279             method_name,
280             IsSuggestion(false),
281             self_ty,
282             call_expr.hir_id,
283             scope,
284         )
285     }
286
287     /// `lookup_method_in_trait` is used for overloaded operators.
288     /// It does a very narrow slice of what the normal probe/confirm path does.
289     /// In particular, it doesn't really do any probing: it simply constructs
290     /// an obligation for a particular trait with the given self type and checks
291     /// whether that trait is implemented.
292     //
293     // FIXME(#18741): it seems likely that we can consolidate some of this
294     // code with the other method-lookup code. In particular, the second half
295     // of this method is basically the same as confirmation.
296     pub fn lookup_method_in_trait(
297         &self,
298         span: Span,
299         m_name: ast::Ident,
300         trait_def_id: DefId,
301         self_ty: Ty<'tcx>,
302         opt_input_types: Option<&[Ty<'tcx>]>,
303     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
304         debug!(
305             "lookup_in_trait_adjusted(self_ty={:?}, \
306                 m_name={}, trait_def_id={:?})",
307             self_ty, m_name, trait_def_id
308         );
309
310         // Construct a trait-reference `self_ty : Trait<input_tys>`
311         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
312             match param.kind {
313                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => {}
314                 GenericParamDefKind::Type { .. } => {
315                     if param.index == 0 {
316                         return self_ty.into();
317                     } else if let Some(ref input_types) = opt_input_types {
318                         return input_types[param.index as usize - 1].into();
319                     }
320                 }
321             }
322             self.var_for_def(span, param)
323         });
324
325         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
326
327         // Construct an obligation
328         let poly_trait_ref = trait_ref.to_poly_trait_ref();
329         let obligation = traits::Obligation::misc(
330             span,
331             self.body_id,
332             self.param_env,
333             poly_trait_ref.without_const().to_predicate(),
334         );
335
336         // Now we want to know if this can be matched
337         if !self.predicate_may_hold(&obligation) {
338             debug!("--> Cannot match obligation");
339             return None; // Cannot be matched, no such method resolution is possible.
340         }
341
342         // Trait must have a method named `m_name` and it should not have
343         // type parameters or early-bound regions.
344         let tcx = self.tcx;
345         let method_item = match self.associated_item(trait_def_id, m_name, Namespace::ValueNS) {
346             Some(method_item) => method_item,
347             None => {
348                 tcx.sess.delay_span_bug(
349                     span,
350                     "operator trait does not have corresponding operator method",
351                 );
352                 return None;
353             }
354         };
355         let def_id = method_item.def_id;
356         let generics = tcx.generics_of(def_id);
357         assert_eq!(generics.params.len(), 0);
358
359         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
360         let mut obligations = vec![];
361
362         // Instantiate late-bound regions and substitute the trait
363         // parameters into the method type to get the actual method type.
364         //
365         // N.B., instantiate late-bound regions first so that
366         // `instantiate_type_scheme` can normalize associated types that
367         // may reference those regions.
368         let fn_sig = tcx.fn_sig(def_id);
369         let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, &fn_sig).0;
370         let fn_sig = fn_sig.subst(self.tcx, substs);
371         let fn_sig = match self.normalize_associated_types_in_as_infer_ok(span, &fn_sig) {
372             InferOk { value, obligations: o } => {
373                 obligations.extend(o);
374                 value
375             }
376         };
377
378         // Register obligations for the parameters. This will include the
379         // `Self` parameter, which in turn has a bound of the main trait,
380         // so this also effectively registers `obligation` as well.  (We
381         // used to register `obligation` explicitly, but that resulted in
382         // double error messages being reported.)
383         //
384         // Note that as the method comes from a trait, it should not have
385         // any late-bound regions appearing in its bounds.
386         let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
387         let bounds = match self.normalize_associated_types_in_as_infer_ok(span, &bounds) {
388             InferOk { value, obligations: o } => {
389                 obligations.extend(o);
390                 value
391             }
392         };
393         assert!(!bounds.has_escaping_bound_vars());
394
395         let cause = traits::ObligationCause::misc(span, self.body_id);
396         obligations.extend(traits::predicates_for_generics(cause.clone(), self.param_env, &bounds));
397
398         // Also add an obligation for the method type being well-formed.
399         let method_ty = tcx.mk_fn_ptr(ty::Binder::bind(fn_sig));
400         debug!(
401             "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
402             method_ty, obligation
403         );
404         obligations.push(traits::Obligation::new(
405             cause,
406             self.param_env,
407             ty::Predicate::WellFormed(method_ty),
408         ));
409
410         let callee = MethodCallee { def_id, substs: trait_ref.substs, sig: fn_sig };
411
412         debug!("callee = {:?}", callee);
413
414         Some(InferOk { obligations, value: callee })
415     }
416
417     pub fn resolve_ufcs(
418         &self,
419         span: Span,
420         method_name: ast::Ident,
421         self_ty: Ty<'tcx>,
422         expr_id: hir::HirId,
423     ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
424         debug!(
425             "resolve_ufcs: method_name={:?} self_ty={:?} expr_id={:?}",
426             method_name, self_ty, expr_id,
427         );
428
429         let tcx = self.tcx;
430
431         // Check if we have an enum variant.
432         if let ty::Adt(adt_def, _) = self_ty.kind {
433             if adt_def.is_enum() {
434                 let variant_def = adt_def
435                     .variants
436                     .iter()
437                     .find(|vd| tcx.hygienic_eq(method_name, vd.ident, adt_def.did));
438                 if let Some(variant_def) = variant_def {
439                     // Braced variants generate unusable names in value namespace (reserved for
440                     // possible future use), so variants resolved as associated items may refer to
441                     // them as well. It's ok to use the variant's id as a ctor id since an
442                     // error will be reported on any use of such resolution anyway.
443                     let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id);
444                     tcx.check_stability(ctor_def_id, Some(expr_id), span);
445                     return Ok((
446                         DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind),
447                         ctor_def_id,
448                     ));
449                 }
450             }
451         }
452
453         let pick = self.probe_for_name(
454             span,
455             probe::Mode::Path,
456             method_name,
457             IsSuggestion(false),
458             self_ty,
459             expr_id,
460             ProbeScope::TraitsInScope,
461         )?;
462         debug!("resolve_ufcs: pick={:?}", pick);
463         {
464             let mut tables = self.tables.borrow_mut();
465             let used_trait_imports = Lrc::get_mut(&mut tables.used_trait_imports).unwrap();
466             for import_id in pick.import_ids {
467                 let import_def_id = tcx.hir().local_def_id(import_id);
468                 debug!("resolve_ufcs: used_trait_import: {:?}", import_def_id);
469                 used_trait_imports.insert(import_def_id);
470             }
471         }
472
473         let def_kind = pick.item.def_kind();
474         debug!("resolve_ufcs: def_kind={:?}, def_id={:?}", def_kind, pick.item.def_id);
475         tcx.check_stability(pick.item.def_id, Some(expr_id), span);
476         Ok((def_kind, pick.item.def_id))
477     }
478
479     /// Finds item with name `item_name` defined in impl/trait `def_id`
480     /// and return it, or `None`, if no such item was defined there.
481     pub fn associated_item(
482         &self,
483         def_id: DefId,
484         item_name: ast::Ident,
485         ns: Namespace,
486     ) -> Option<ty::AssocItem> {
487         self.tcx
488             .associated_items(def_id)
489             .find_by_name_and_namespace(self.tcx, item_name, ns, def_id)
490             .copied()
491     }
492 }