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