]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/method/mod.rs
Auto merge of #82127 - tgnottingham:tune-ahead-of-time-codegen, r=varkor
[rust.git] / compiler / rustc_typeck / src / 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_data_structures::sync::Lrc;
15 use rustc_errors::{Applicability, DiagnosticBuilder};
16 use rustc_hir as hir;
17 use rustc_hir::def::{CtorOf, DefKind, Namespace};
18 use rustc_hir::def_id::DefId;
19 use rustc_infer::infer::{self, InferOk};
20 use rustc_middle::ty::subst::Subst;
21 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
22 use rustc_middle::ty::GenericParamDefKind;
23 use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TypeFoldable, WithConstness};
24 use rustc_span::symbol::Ident;
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     #[instrument(level = "debug", skip(self))]
106     pub fn method_exists(
107         &self,
108         method_name: Ident,
109         self_ty: Ty<'tcx>,
110         call_expr_id: hir::HirId,
111         allow_private: bool,
112     ) -> bool {
113         let mode = probe::Mode::MethodCall;
114         match self.probe_for_name(
115             method_name.span,
116             mode,
117             method_name,
118             IsSuggestion(false),
119             self_ty,
120             call_expr_id,
121             ProbeScope::TraitsInScope,
122         ) {
123             Ok(..) => true,
124             Err(NoMatch(..)) => false,
125             Err(Ambiguity(..)) => true,
126             Err(PrivateMatch(..)) => allow_private,
127             Err(IllegalSizedBound(..)) => true,
128             Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
129         }
130     }
131
132     /// Adds a suggestion to call the given method to the provided diagnostic.
133     #[instrument(level = "debug", skip(self, err, call_expr))]
134     crate fn suggest_method_call(
135         &self,
136         err: &mut DiagnosticBuilder<'a>,
137         msg: &str,
138         method_name: Ident,
139         self_ty: Ty<'tcx>,
140         call_expr: &hir::Expr<'_>,
141     ) {
142         let params = self
143             .probe_for_name(
144                 method_name.span,
145                 probe::Mode::MethodCall,
146                 method_name,
147                 IsSuggestion(false),
148                 self_ty,
149                 call_expr.hir_id,
150                 ProbeScope::TraitsInScope,
151             )
152             .map(|pick| {
153                 let sig = self.tcx.fn_sig(pick.item.def_id);
154                 sig.inputs().skip_binder().len().saturating_sub(1)
155             })
156             .unwrap_or(0);
157
158         // Account for `foo.bar<T>`;
159         let sugg_span = call_expr.span.shrink_to_hi();
160         let (suggestion, applicability) = (
161             format!("({})", (0..params).map(|_| "_").collect::<Vec<_>>().join(", ")),
162             if params > 0 { Applicability::HasPlaceholders } else { Applicability::MaybeIncorrect },
163         );
164
165         err.span_suggestion_verbose(sugg_span, msg, suggestion, applicability);
166     }
167
168     /// Performs method lookup. If lookup is successful, it will return the callee
169     /// and store an appropriate adjustment for the self-expr. In some cases it may
170     /// report an error (e.g., invoking the `drop` method).
171     ///
172     /// # Arguments
173     ///
174     /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
175     ///
176     /// * `self`:                  the surrounding `FnCtxt` (!)
177     /// * `self_ty`:               the (unadjusted) type of the self expression (`foo`)
178     /// * `segment`:               the name and generic arguments of the method (`bar::<T1, ...Tn>`)
179     /// * `span`:                  the span for the method call
180     /// * `call_expr`:             the complete method call: (`foo.bar::<T1,...Tn>(...)`)
181     /// * `self_expr`:             the self expression (`foo`)
182     #[instrument(level = "debug", skip(self, call_expr, self_expr))]
183     pub fn lookup_method(
184         &self,
185         self_ty: Ty<'tcx>,
186         segment: &hir::PathSegment<'_>,
187         span: Span,
188         call_expr: &'tcx hir::Expr<'tcx>,
189         self_expr: &'tcx hir::Expr<'tcx>,
190     ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
191         debug!(
192             "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
193             segment.ident, self_ty, call_expr, self_expr
194         );
195
196         let pick =
197             self.lookup_probe(span, segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
198
199         for import_id in &pick.import_ids {
200             debug!("used_trait_import: {:?}", import_id);
201             Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports)
202                 .unwrap()
203                 .insert(*import_id);
204         }
205
206         self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span);
207
208         let result =
209             self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment);
210         debug!("result = {:?}", result);
211
212         if let Some(span) = result.illegal_sized_bound {
213             let mut needs_mut = false;
214             if let ty::Ref(region, t_type, mutability) = self_ty.kind() {
215                 let trait_type = self
216                     .tcx
217                     .mk_ref(region, ty::TypeAndMut { ty: t_type, mutbl: mutability.invert() });
218                 // We probe again to see if there might be a borrow mutability discrepancy.
219                 match self.lookup_probe(
220                     span,
221                     segment.ident,
222                     trait_type,
223                     call_expr,
224                     ProbeScope::TraitsInScope,
225                 ) {
226                     Ok(ref new_pick) if *new_pick != pick => {
227                         needs_mut = true;
228                     }
229                     _ => {}
230                 }
231             }
232
233             // We probe again, taking all traits into account (not only those in scope).
234             let candidates = match self.lookup_probe(
235                 span,
236                 segment.ident,
237                 self_ty,
238                 call_expr,
239                 ProbeScope::AllTraits,
240             ) {
241                 // If we find a different result the caller probably forgot to import a trait.
242                 Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
243                 Err(Ambiguity(ref sources)) => sources
244                     .iter()
245                     .filter_map(|source| {
246                         match *source {
247                             // Note: this cannot come from an inherent impl,
248                             // because the first probing succeeded.
249                             ImplSource(def) => self.tcx.trait_id_of_impl(def),
250                             TraitSource(_) => None,
251                         }
252                     })
253                     .collect(),
254                 _ => Vec::new(),
255             };
256
257             return Err(IllegalSizedBound(candidates, needs_mut, span));
258         }
259
260         Ok(result.callee)
261     }
262
263     #[instrument(level = "debug", skip(self, call_expr))]
264     pub fn lookup_probe(
265         &self,
266         span: Span,
267         method_name: Ident,
268         self_ty: Ty<'tcx>,
269         call_expr: &'tcx hir::Expr<'tcx>,
270         scope: ProbeScope,
271     ) -> probe::PickResult<'tcx> {
272         let mode = probe::Mode::MethodCall;
273         let self_ty = self.resolve_vars_if_possible(self_ty);
274         self.probe_for_name(
275             span,
276             mode,
277             method_name,
278             IsSuggestion(false),
279             self_ty,
280             call_expr.hir_id,
281             scope,
282         )
283     }
284
285     /// `lookup_method_in_trait` is used for overloaded operators.
286     /// It does a very narrow slice of what the normal probe/confirm path does.
287     /// In particular, it doesn't really do any probing: it simply constructs
288     /// an obligation for a particular trait with the given self type and checks
289     /// whether that trait is implemented.
290     //
291     // FIXME(#18741): it seems likely that we can consolidate some of this
292     // code with the other method-lookup code. In particular, the second half
293     // of this method is basically the same as confirmation.
294     #[instrument(level = "debug", skip(self, span, opt_input_types))]
295     pub fn lookup_method_in_trait(
296         &self,
297         span: Span,
298         m_name: Ident,
299         trait_def_id: DefId,
300         self_ty: Ty<'tcx>,
301         opt_input_types: Option<&[Ty<'tcx>]>,
302     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
303         debug!(
304             "lookup_in_trait_adjusted(self_ty={:?}, m_name={}, trait_def_id={:?})",
305             self_ty, m_name, trait_def_id
306         );
307
308         // Construct a trait-reference `self_ty : Trait<input_tys>`
309         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
310             match param.kind {
311                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => {}
312                 GenericParamDefKind::Type { .. } => {
313                     if param.index == 0 {
314                         return self_ty.into();
315                     } else if let Some(ref input_types) = opt_input_types {
316                         return input_types[param.index as usize - 1].into();
317                     }
318                 }
319             }
320             self.var_for_def(span, param)
321         });
322
323         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
324
325         // Construct an obligation
326         let poly_trait_ref = trait_ref.to_poly_trait_ref();
327         let obligation = traits::Obligation::misc(
328             span,
329             self.body_id,
330             self.param_env,
331             poly_trait_ref.without_const().to_predicate(self.tcx),
332         );
333
334         // Now we want to know if this can be matched
335         if !self.predicate_may_hold(&obligation) {
336             debug!("--> Cannot match obligation");
337             return None; // Cannot be matched, no such method resolution is possible.
338         }
339
340         // Trait must have a method named `m_name` and it should not have
341         // type parameters or early-bound regions.
342         let tcx = self.tcx;
343         let method_item = match self.associated_item(trait_def_id, m_name, Namespace::ValueNS) {
344             Some(method_item) => method_item,
345             None => {
346                 tcx.sess.delay_span_bug(
347                     span,
348                     "operator trait does not have corresponding operator method",
349                 );
350                 return None;
351             }
352         };
353         let def_id = method_item.def_id;
354         let generics = tcx.generics_of(def_id);
355         assert_eq!(generics.params.len(), 0);
356
357         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
358         let mut obligations = vec![];
359
360         // Instantiate late-bound regions and substitute the trait
361         // parameters into the method type to get the actual method type.
362         //
363         // N.B., instantiate late-bound regions first so that
364         // `instantiate_type_scheme` can normalize associated types that
365         // may reference those regions.
366         let fn_sig = tcx.fn_sig(def_id);
367         let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, fn_sig).0;
368         let fn_sig = fn_sig.subst(self.tcx, substs);
369
370         let InferOk { value, obligations: o } =
371             self.normalize_associated_types_in_as_infer_ok(span, fn_sig);
372         let fn_sig = {
373             obligations.extend(o);
374             value
375         };
376
377         // Register obligations for the parameters. This will include the
378         // `Self` parameter, which in turn has a bound of the main trait,
379         // so this also effectively registers `obligation` as well.  (We
380         // used to register `obligation` explicitly, but that resulted in
381         // double error messages being reported.)
382         //
383         // Note that as the method comes from a trait, it should not have
384         // any late-bound regions appearing in its bounds.
385         let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
386
387         let InferOk { value, obligations: o } =
388             self.normalize_associated_types_in_as_infer_ok(span, bounds);
389         let bounds = {
390             obligations.extend(o);
391             value
392         };
393
394         assert!(!bounds.has_escaping_bound_vars());
395
396         let cause = traits::ObligationCause::misc(span, self.body_id);
397         obligations.extend(traits::predicates_for_generics(cause.clone(), self.param_env, bounds));
398
399         // Also add an obligation for the method type being well-formed.
400         let method_ty = tcx.mk_fn_ptr(ty::Binder::bind(fn_sig));
401         debug!(
402             "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
403             method_ty, obligation
404         );
405         obligations.push(traits::Obligation::new(
406             cause,
407             self.param_env,
408             ty::PredicateKind::WellFormed(method_ty.into()).to_predicate(tcx),
409         ));
410
411         let callee = MethodCallee { def_id, substs: trait_ref.substs, sig: fn_sig };
412
413         debug!("callee = {:?}", callee);
414
415         Some(InferOk { obligations, value: callee })
416     }
417
418     #[instrument(level = "debug", skip(self))]
419     pub fn resolve_ufcs(
420         &self,
421         span: Span,
422         method_name: Ident,
423         self_ty: Ty<'tcx>,
424         expr_id: hir::HirId,
425     ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
426         debug!(
427             "resolve_ufcs: method_name={:?} self_ty={:?} expr_id={:?}",
428             method_name, self_ty, expr_id,
429         );
430
431         let tcx = self.tcx;
432
433         // Check if we have an enum variant.
434         if let ty::Adt(adt_def, _) = self_ty.kind() {
435             if adt_def.is_enum() {
436                 let variant_def = adt_def
437                     .variants
438                     .iter()
439                     .find(|vd| tcx.hygienic_eq(method_name, vd.ident, adt_def.did));
440                 if let Some(variant_def) = variant_def {
441                     // Braced variants generate unusable names in value namespace (reserved for
442                     // possible future use), so variants resolved as associated items may refer to
443                     // them as well. It's ok to use the variant's id as a ctor id since an
444                     // error will be reported on any use of such resolution anyway.
445                     let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id);
446                     tcx.check_stability(ctor_def_id, Some(expr_id), span);
447                     return Ok((
448                         DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind),
449                         ctor_def_id,
450                     ));
451                 }
452             }
453         }
454
455         let pick = self.probe_for_name(
456             span,
457             probe::Mode::Path,
458             method_name,
459             IsSuggestion(false),
460             self_ty,
461             expr_id,
462             ProbeScope::TraitsInScope,
463         )?;
464         debug!("resolve_ufcs: pick={:?}", pick);
465         {
466             let mut typeck_results = self.typeck_results.borrow_mut();
467             let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
468             for import_id in pick.import_ids {
469                 debug!("resolve_ufcs: used_trait_import: {:?}", import_id);
470                 used_trait_imports.insert(import_id);
471             }
472         }
473
474         let def_kind = pick.item.kind.as_def_kind();
475         debug!("resolve_ufcs: def_kind={:?}, def_id={:?}", def_kind, pick.item.def_id);
476         tcx.check_stability(pick.item.def_id, Some(expr_id), span);
477         Ok((def_kind, pick.item.def_id))
478     }
479
480     /// Finds item with name `item_name` defined in impl/trait `def_id`
481     /// and return it, or `None`, if no such item was defined there.
482     pub fn associated_item(
483         &self,
484         def_id: DefId,
485         item_name: Ident,
486         ns: Namespace,
487     ) -> Option<ty::AssocItem> {
488         self.tcx
489             .associated_items(def_id)
490             .find_by_name_and_namespace(self.tcx, item_name, ns, def_id)
491             .copied()
492     }
493 }