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