]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/method/mod.rs
Rollup merge of #105120 - solid-rs:patch/kmc-solid/maintainance, r=thomcc
[rust.git] / compiler / rustc_hir_typeck / src / 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 mod prelude2021;
7 pub mod probe;
8 mod suggest;
9
10 pub use self::suggest::SelfSource;
11 pub use self::MethodError::*;
12
13 use crate::errors::OpMethodGenericParams;
14 use crate::{Expectation, FnCtxt};
15 use rustc_data_structures::sync::Lrc;
16 use rustc_errors::{Applicability, Diagnostic};
17 use rustc_hir as hir;
18 use rustc_hir::def::{CtorOf, DefKind, Namespace};
19 use rustc_hir::def_id::DefId;
20 use rustc_infer::infer::{self, InferOk};
21 use rustc_middle::traits::ObligationCause;
22 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
23 use rustc_middle::ty::{self, GenericParamDefKind, Ty, TypeVisitable};
24 use rustc_span::symbol::Ident;
25 use rustc_span::Span;
26 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
27 use rustc_trait_selection::traits::{self, NormalizeExt};
28
29 use self::probe::{IsSuggestion, ProbeScope};
30
31 pub fn provide(providers: &mut ty::query::Providers) {
32     probe::provide(providers);
33 }
34
35 #[derive(Clone, Copy, Debug)]
36 pub struct MethodCallee<'tcx> {
37     /// Impl method ID, for inherent methods, or trait method ID, otherwise.
38     pub def_id: DefId,
39     pub substs: SubstsRef<'tcx>,
40
41     /// Instantiated method signature, i.e., it has been
42     /// substituted, normalized, and has had late-bound
43     /// lifetimes replaced with inference variables.
44     pub sig: ty::FnSig<'tcx>,
45 }
46
47 #[derive(Debug)]
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.
60     IllegalSizedBound(Vec<DefId>, bool, Span),
61
62     // Found a match, but the return type is wrong
63     BadReturnType,
64 }
65
66 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
67 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
68 #[derive(Debug)]
69 pub struct NoMatchData<'tcx> {
70     pub static_candidates: Vec<CandidateSource>,
71     pub unsatisfied_predicates:
72         Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>,
73     pub out_of_scope_traits: Vec<DefId>,
74     pub lev_candidate: Option<ty::AssocItem>,
75     pub mode: probe::Mode,
76 }
77
78 // A pared down enum describing just the places from which a method
79 // candidate can arise. Used for error reporting only.
80 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
81 pub enum CandidateSource {
82     Impl(DefId),
83     Trait(DefId /* trait id */),
84 }
85
86 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
87     /// Determines whether the type `self_ty` supports a method name `method_name` or not.
88     #[instrument(level = "debug", skip(self))]
89     pub fn method_exists(
90         &self,
91         method_name: Ident,
92         self_ty: Ty<'tcx>,
93         call_expr_id: hir::HirId,
94         allow_private: bool,
95     ) -> bool {
96         match self.probe_for_name(
97             probe::Mode::MethodCall,
98             method_name,
99             IsSuggestion(false),
100             self_ty,
101             call_expr_id,
102             ProbeScope::TraitsInScope,
103         ) {
104             Ok(pick) => {
105                 pick.maybe_emit_unstable_name_collision_hint(
106                     self.tcx,
107                     method_name.span,
108                     call_expr_id,
109                 );
110                 true
111             }
112             Err(NoMatch(..)) => false,
113             Err(Ambiguity(..)) => true,
114             Err(PrivateMatch(..)) => allow_private,
115             Err(IllegalSizedBound(..)) => true,
116             Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
117         }
118     }
119
120     /// Adds a suggestion to call the given method to the provided diagnostic.
121     #[instrument(level = "debug", skip(self, err, call_expr))]
122     pub(crate) fn suggest_method_call(
123         &self,
124         err: &mut Diagnostic,
125         msg: &str,
126         method_name: Ident,
127         self_ty: Ty<'tcx>,
128         call_expr: &hir::Expr<'_>,
129         span: Option<Span>,
130     ) {
131         let params = self
132             .probe_for_name(
133                 probe::Mode::MethodCall,
134                 method_name,
135                 IsSuggestion(true),
136                 self_ty,
137                 call_expr.hir_id,
138                 ProbeScope::TraitsInScope,
139             )
140             .map(|pick| {
141                 let sig = self.tcx.fn_sig(pick.item.def_id);
142                 sig.inputs().skip_binder().len().saturating_sub(1)
143             })
144             .unwrap_or(0);
145
146         // Account for `foo.bar<T>`;
147         let sugg_span = span.unwrap_or(call_expr.span).shrink_to_hi();
148         let (suggestion, applicability) = (
149             format!("({})", (0..params).map(|_| "_").collect::<Vec<_>>().join(", ")),
150             if params > 0 { Applicability::HasPlaceholders } else { Applicability::MaybeIncorrect },
151         );
152
153         err.span_suggestion_verbose(sugg_span, msg, suggestion, applicability);
154     }
155
156     /// Performs method lookup. If lookup is successful, it will return the callee
157     /// and store an appropriate adjustment for the self-expr. In some cases it may
158     /// report an error (e.g., invoking the `drop` method).
159     ///
160     /// # Arguments
161     ///
162     /// Given a method call like `foo.bar::<T1,...Tn>(a, b + 1, ...)`:
163     ///
164     /// * `self`:                  the surrounding `FnCtxt` (!)
165     /// * `self_ty`:               the (unadjusted) type of the self expression (`foo`)
166     /// * `segment`:               the name and generic arguments of the method (`bar::<T1, ...Tn>`)
167     /// * `span`:                  the span for the method call
168     /// * `call_expr`:             the complete method call: (`foo.bar::<T1,...Tn>(...)`)
169     /// * `self_expr`:             the self expression (`foo`)
170     /// * `args`:                  the expressions of the arguments (`a, b + 1, ...`)
171     #[instrument(level = "debug", skip(self))]
172     pub fn lookup_method(
173         &self,
174         self_ty: Ty<'tcx>,
175         segment: &hir::PathSegment<'_>,
176         span: Span,
177         call_expr: &'tcx hir::Expr<'tcx>,
178         self_expr: &'tcx hir::Expr<'tcx>,
179         args: &'tcx [hir::Expr<'tcx>],
180     ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
181         let pick =
182             self.lookup_probe(segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
183
184         self.lint_dot_call_from_2018(self_ty, segment, span, call_expr, self_expr, &pick, args);
185
186         for import_id in &pick.import_ids {
187             debug!("used_trait_import: {:?}", import_id);
188             Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports)
189                 .unwrap()
190                 .insert(*import_id);
191         }
192
193         self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span, None);
194
195         let result =
196             self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment);
197         debug!("result = {:?}", result);
198
199         if let Some(span) = result.illegal_sized_bound {
200             let mut needs_mut = false;
201             if let ty::Ref(region, t_type, mutability) = self_ty.kind() {
202                 let trait_type = self
203                     .tcx
204                     .mk_ref(*region, ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() });
205                 // We probe again to see if there might be a borrow mutability discrepancy.
206                 match self.lookup_probe(
207                     segment.ident,
208                     trait_type,
209                     call_expr,
210                     ProbeScope::TraitsInScope,
211                 ) {
212                     Ok(ref new_pick) if pick.differs_from(new_pick) => {
213                         needs_mut = true;
214                     }
215                     _ => {}
216                 }
217             }
218
219             // We probe again, taking all traits into account (not only those in scope).
220             let candidates =
221                 match self.lookup_probe(segment.ident, self_ty, call_expr, ProbeScope::AllTraits) {
222                     // If we find a different result the caller probably forgot to import a trait.
223                     Ok(ref new_pick) if pick.differs_from(new_pick) => {
224                         vec![new_pick.item.container_id(self.tcx)]
225                     }
226                     Err(Ambiguity(ref sources)) => sources
227                         .iter()
228                         .filter_map(|source| {
229                             match *source {
230                                 // Note: this cannot come from an inherent impl,
231                                 // because the first probing succeeded.
232                                 CandidateSource::Impl(def) => self.tcx.trait_id_of_impl(def),
233                                 CandidateSource::Trait(_) => None,
234                             }
235                         })
236                         .collect(),
237                     _ => Vec::new(),
238                 };
239
240             return Err(IllegalSizedBound(candidates, needs_mut, span));
241         }
242
243         Ok(result.callee)
244     }
245
246     #[instrument(level = "debug", skip(self, call_expr))]
247     pub fn lookup_probe(
248         &self,
249         method_name: Ident,
250         self_ty: Ty<'tcx>,
251         call_expr: &'tcx hir::Expr<'tcx>,
252         scope: ProbeScope,
253     ) -> probe::PickResult<'tcx> {
254         let pick = self.probe_for_name(
255             probe::Mode::MethodCall,
256             method_name,
257             IsSuggestion(false),
258             self_ty,
259             call_expr.hir_id,
260             scope,
261         )?;
262         pick.maybe_emit_unstable_name_collision_hint(self.tcx, method_name.span, call_expr.hir_id);
263         Ok(pick)
264     }
265
266     pub(super) fn obligation_for_method(
267         &self,
268         span: Span,
269         trait_def_id: DefId,
270         self_ty: Ty<'tcx>,
271         opt_input_types: Option<&[Ty<'tcx>]>,
272     ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
273     {
274         // Construct a trait-reference `self_ty : Trait<input_tys>`
275         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
276             match param.kind {
277                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
278                 GenericParamDefKind::Type { .. } => {
279                     if param.index == 0 {
280                         return self_ty.into();
281                     } else if let Some(input_types) = opt_input_types {
282                         return input_types[param.index as usize - 1].into();
283                     }
284                 }
285             }
286             self.var_for_def(span, param)
287         });
288
289         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
290
291         // Construct an obligation
292         let poly_trait_ref = ty::Binder::dummy(trait_ref);
293         (
294             traits::Obligation::misc(
295                 self.tcx,
296                 span,
297                 self.body_id,
298                 self.param_env,
299                 poly_trait_ref.without_const(),
300             ),
301             substs,
302         )
303     }
304
305     pub(super) fn obligation_for_op_method(
306         &self,
307         span: Span,
308         trait_def_id: DefId,
309         self_ty: Ty<'tcx>,
310         opt_input_type: Option<Ty<'tcx>>,
311         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
312         expected: Expectation<'tcx>,
313     ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
314     {
315         // Construct a trait-reference `self_ty : Trait<input_tys>`
316         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
317             match param.kind {
318                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
319                 GenericParamDefKind::Type { .. } => {
320                     if param.index == 0 {
321                         return self_ty.into();
322                     } else if let Some(input_type) = opt_input_type {
323                         return input_type.into();
324                     }
325                 }
326             }
327             self.var_for_def(span, param)
328         });
329
330         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
331
332         // Construct an obligation
333         let poly_trait_ref = ty::Binder::dummy(trait_ref);
334         let output_ty = expected.only_has_type(self).and_then(|ty| (!ty.needs_infer()).then(|| ty));
335
336         (
337             traits::Obligation::new(
338                 self.tcx,
339                 traits::ObligationCause::new(
340                     span,
341                     self.body_id,
342                     traits::BinOp {
343                         rhs_span: opt_input_expr.map(|expr| expr.span),
344                         is_lit: opt_input_expr
345                             .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
346                         output_ty,
347                     },
348                 ),
349                 self.param_env,
350                 poly_trait_ref,
351             ),
352             substs,
353         )
354     }
355
356     /// `lookup_method_in_trait` is used for overloaded operators.
357     /// It does a very narrow slice of what the normal probe/confirm path does.
358     /// In particular, it doesn't really do any probing: it simply constructs
359     /// an obligation for a particular trait with the given self type and checks
360     /// whether that trait is implemented.
361     #[instrument(level = "debug", skip(self, span))]
362     pub(super) fn lookup_method_in_trait(
363         &self,
364         span: Span,
365         m_name: Ident,
366         trait_def_id: DefId,
367         self_ty: Ty<'tcx>,
368         opt_input_types: Option<&[Ty<'tcx>]>,
369     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
370         let (obligation, substs) =
371             self.obligation_for_method(span, trait_def_id, self_ty, opt_input_types);
372         self.construct_obligation_for_trait(
373             span,
374             m_name,
375             trait_def_id,
376             obligation,
377             substs,
378             None,
379             false,
380         )
381     }
382
383     pub(super) fn lookup_op_method_in_trait(
384         &self,
385         span: Span,
386         m_name: Ident,
387         trait_def_id: DefId,
388         self_ty: Ty<'tcx>,
389         opt_input_type: Option<Ty<'tcx>>,
390         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
391         expected: Expectation<'tcx>,
392     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
393         let (obligation, substs) = self.obligation_for_op_method(
394             span,
395             trait_def_id,
396             self_ty,
397             opt_input_type,
398             opt_input_expr,
399             expected,
400         );
401         self.construct_obligation_for_trait(
402             span,
403             m_name,
404             trait_def_id,
405             obligation,
406             substs,
407             opt_input_expr,
408             true,
409         )
410     }
411
412     // FIXME(#18741): it seems likely that we can consolidate some of this
413     // code with the other method-lookup code. In particular, the second half
414     // of this method is basically the same as confirmation.
415     fn construct_obligation_for_trait(
416         &self,
417         span: Span,
418         m_name: Ident,
419         trait_def_id: DefId,
420         obligation: traits::PredicateObligation<'tcx>,
421         substs: &'tcx ty::List<ty::subst::GenericArg<'tcx>>,
422         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
423         is_op: bool,
424     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
425         debug!(?obligation);
426
427         // Now we want to know if this can be matched
428         if !self.predicate_may_hold(&obligation) {
429             debug!("--> Cannot match obligation");
430             // Cannot be matched, no such method resolution is possible.
431             return None;
432         }
433
434         // Trait must have a method named `m_name` and it should not have
435         // type parameters or early-bound regions.
436         let tcx = self.tcx;
437         let Some(method_item) = self.associated_value(trait_def_id, m_name) else {
438             tcx.sess.delay_span_bug(
439                 span,
440                 "operator trait does not have corresponding operator method",
441             );
442             return None;
443         };
444         let def_id = method_item.def_id;
445         let generics = tcx.generics_of(def_id);
446
447         if generics.params.len() != 0 {
448             tcx.sess.emit_fatal(OpMethodGenericParams {
449                 span: tcx.def_span(method_item.def_id),
450                 method_name: m_name.to_string(),
451             });
452         }
453
454         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
455         let mut obligations = vec![];
456
457         // Instantiate late-bound regions and substitute the trait
458         // parameters into the method type to get the actual method type.
459         //
460         // N.B., instantiate late-bound regions first so that
461         // `instantiate_type_scheme` can normalize associated types that
462         // may reference those regions.
463         let fn_sig = tcx.bound_fn_sig(def_id);
464         let fn_sig = fn_sig.subst(self.tcx, substs);
465         let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, fn_sig);
466
467         let cause = if is_op {
468             ObligationCause::new(
469                 span,
470                 self.body_id,
471                 traits::BinOp {
472                     rhs_span: opt_input_expr.map(|expr| expr.span),
473                     is_lit: opt_input_expr
474                         .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
475                     output_ty: None,
476                 },
477             )
478         } else {
479             traits::ObligationCause::misc(span, self.body_id)
480         };
481
482         let InferOk { value, obligations: o } = self.at(&cause, self.param_env).normalize(fn_sig);
483         let fn_sig = {
484             obligations.extend(o);
485             value
486         };
487
488         // Register obligations for the parameters. This will include the
489         // `Self` parameter, which in turn has a bound of the main trait,
490         // so this also effectively registers `obligation` as well.  (We
491         // used to register `obligation` explicitly, but that resulted in
492         // double error messages being reported.)
493         //
494         // Note that as the method comes from a trait, it should not have
495         // any late-bound regions appearing in its bounds.
496         let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
497
498         let InferOk { value, obligations: o } = self.at(&cause, self.param_env).normalize(bounds);
499         let bounds = {
500             obligations.extend(o);
501             value
502         };
503
504         assert!(!bounds.has_escaping_bound_vars());
505
506         let predicates_cause = cause.clone();
507         obligations.extend(traits::predicates_for_generics(
508             move |_, _| predicates_cause.clone(),
509             self.param_env,
510             bounds,
511         ));
512
513         // Also add an obligation for the method type being well-formed.
514         let method_ty = tcx.mk_fn_ptr(ty::Binder::dummy(fn_sig));
515         debug!(
516             "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
517             method_ty, obligation
518         );
519         obligations.push(traits::Obligation::new(
520             tcx,
521             cause,
522             self.param_env,
523             ty::Binder::dummy(ty::PredicateKind::WellFormed(method_ty.into())),
524         ));
525
526         let callee = MethodCallee { def_id, substs, sig: fn_sig };
527
528         debug!("callee = {:?}", callee);
529
530         Some(InferOk { obligations, value: callee })
531     }
532
533     /// Performs a [full-qualified function call] (formerly "universal function call") lookup. If
534     /// lookup is successful, it will return the type of definition and the [`DefId`] of the found
535     /// function definition.
536     ///
537     /// [full-qualified function call]: https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls
538     ///
539     /// # Arguments
540     ///
541     /// Given a function call like `Foo::bar::<T1,...Tn>(...)`:
542     ///
543     /// * `self`:                  the surrounding `FnCtxt` (!)
544     /// * `span`:                  the span of the call, excluding arguments (`Foo::bar::<T1, ...Tn>`)
545     /// * `method_name`:           the identifier of the function within the container type (`bar`)
546     /// * `self_ty`:               the type to search within (`Foo`)
547     /// * `self_ty_span`           the span for the type being searched within (span of `Foo`)
548     /// * `expr_id`:               the [`hir::HirId`] of the expression composing the entire call
549     #[instrument(level = "debug", skip(self), ret)]
550     pub fn resolve_fully_qualified_call(
551         &self,
552         span: Span,
553         method_name: Ident,
554         self_ty: Ty<'tcx>,
555         self_ty_span: Span,
556         expr_id: hir::HirId,
557     ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
558         let tcx = self.tcx;
559
560         // Check if we have an enum variant.
561         let mut struct_variant = None;
562         if let ty::Adt(adt_def, _) = self_ty.kind() {
563             if adt_def.is_enum() {
564                 let variant_def = adt_def
565                     .variants()
566                     .iter()
567                     .find(|vd| tcx.hygienic_eq(method_name, vd.ident(tcx), adt_def.did()));
568                 if let Some(variant_def) = variant_def {
569                     if let Some((ctor_kind, ctor_def_id)) = variant_def.ctor {
570                         tcx.check_stability(
571                             ctor_def_id,
572                             Some(expr_id),
573                             span,
574                             Some(method_name.span),
575                         );
576                         return Ok((DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id));
577                     } else {
578                         struct_variant = Some((DefKind::Variant, variant_def.def_id));
579                     }
580                 }
581             }
582         }
583
584         let pick = self.probe_for_name(
585             probe::Mode::Path,
586             method_name,
587             IsSuggestion(false),
588             self_ty,
589             expr_id,
590             ProbeScope::TraitsInScope,
591         );
592         let pick = match (pick, struct_variant) {
593             // Fall back to a resolution that will produce an error later.
594             (Err(_), Some(res)) => return Ok(res),
595             (pick, _) => pick?,
596         };
597
598         pick.maybe_emit_unstable_name_collision_hint(self.tcx, span, expr_id);
599
600         self.lint_fully_qualified_call_from_2018(
601             span,
602             method_name,
603             self_ty,
604             self_ty_span,
605             expr_id,
606             &pick,
607         );
608
609         debug!(?pick);
610         {
611             let mut typeck_results = self.typeck_results.borrow_mut();
612             let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
613             for import_id in pick.import_ids {
614                 debug!(used_trait_import=?import_id);
615                 used_trait_imports.insert(import_id);
616             }
617         }
618
619         let def_kind = pick.item.kind.as_def_kind();
620         tcx.check_stability(pick.item.def_id, Some(expr_id), span, Some(method_name.span));
621         Ok((def_kind, pick.item.def_id))
622     }
623
624     /// Finds item with name `item_name` defined in impl/trait `def_id`
625     /// and return it, or `None`, if no such item was defined there.
626     pub fn associated_value(&self, def_id: DefId, item_name: Ident) -> Option<ty::AssocItem> {
627         self.tcx
628             .associated_items(def_id)
629             .find_by_name_and_namespace(self.tcx, item_name, Namespace::ValueNS, def_id)
630             .copied()
631     }
632 }