1 use GenericParameters::*;
3 use crate::{path_names_to_string, resolve_error};
4 use crate::{AliasPossibility, BindingError, CrateLint, LexicalScopeBinding, Module};
5 use crate::{ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult};
6 use crate::{PathSource, ResolutionError, Resolver, Rib, RibKind, Segment, UseError};
10 use rustc::{bug, lint, span_bug};
11 use rustc::hir::def::{self, PartialRes, DefKind, CtorKind, PerNS};
12 use rustc::hir::def::Namespace::{self, *};
13 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
14 use rustc::hir::TraitCandidate;
15 use rustc::util::nodemap::FxHashMap;
16 use smallvec::{smallvec, SmallVec};
17 use syntax::{unwrap_or, walk_list};
20 use syntax::symbol::{kw, sym};
21 use syntax::util::lev_distance::find_best_match_for_name;
22 use syntax::visit::{self, Visitor, FnKind};
25 use std::collections::BTreeSet;
26 use std::mem::replace;
30 type Res = def::Res<NodeId>;
32 /// Map from the name in a pattern to its binding mode.
33 type BindingMap = FxHashMap<Ident, BindingInfo>;
35 #[derive(Copy, Clone, Debug)]
38 binding_mode: BindingMode,
41 #[derive(Copy, Clone)]
42 enum GenericParameters<'a, 'b> {
44 HasGenericParams(// Type parameters.
47 // The kind of the rib used for type parameters.
51 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
60 fn descr(self) -> &'static str {
62 PatternSource::Match => "match binding",
63 PatternSource::Let => "let binding",
64 PatternSource::For => "for binding",
65 PatternSource::FnParam => "function parameter",
70 struct LateResolutionVisitor<'a, 'b> {
71 r: &'b mut Resolver<'a>,
73 /// The module that represents the current item scope.
74 parent_scope: ParentScope<'a>,
76 /// The current set of local scopes for types and values.
77 /// FIXME #4948: Reuse ribs to avoid allocation.
78 ribs: PerNS<Vec<Rib<'a>>>,
80 /// The current set of local scopes, for labels.
81 label_ribs: Vec<Rib<'a, NodeId>>,
83 /// The trait that the current context can refer to.
84 current_trait_ref: Option<(Module<'a>, TraitRef)>,
86 /// The current trait's associated types' ident, used for diagnostic suggestions.
87 current_trait_assoc_types: Vec<Ident>,
89 /// The current self type if inside an impl (used for better errors).
90 current_self_type: Option<Ty>,
92 /// The current self item if inside an ADT (used for better errors).
93 current_self_item: Option<NodeId>,
95 /// A list of labels as of yet unused. Labels will be removed from this map when
96 /// they are used (in a `break` or `continue` statement)
97 unused_labels: FxHashMap<NodeId, Span>,
99 /// Only used for better errors on `fn(): fn()`.
100 current_type_ascription: Vec<Span>,
103 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
104 impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
105 fn visit_item(&mut self, item: &'tcx Item) {
106 self.resolve_item(item);
108 fn visit_arm(&mut self, arm: &'tcx Arm) {
109 self.resolve_arm(arm);
111 fn visit_block(&mut self, block: &'tcx Block) {
112 self.resolve_block(block);
114 fn visit_anon_const(&mut self, constant: &'tcx AnonConst) {
115 debug!("visit_anon_const {:?}", constant);
116 self.with_constant_rib(|this| {
117 visit::walk_anon_const(this, constant);
120 fn visit_expr(&mut self, expr: &'tcx Expr) {
121 self.resolve_expr(expr, None);
123 fn visit_local(&mut self, local: &'tcx Local) {
124 self.resolve_local(local);
126 fn visit_ty(&mut self, ty: &'tcx Ty) {
128 TyKind::Path(ref qself, ref path) => {
129 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
131 TyKind::ImplicitSelf => {
132 let self_ty = Ident::with_empty_ctxt(kw::SelfUpper);
133 let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
134 .map_or(Res::Err, |d| d.res());
135 self.r.record_partial_res(ty.id, PartialRes::new(res));
139 visit::walk_ty(self, ty);
141 fn visit_poly_trait_ref(&mut self,
142 tref: &'tcx PolyTraitRef,
143 m: &'tcx TraitBoundModifier) {
144 self.smart_resolve_path(tref.trait_ref.ref_id, None,
145 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
146 visit::walk_poly_trait_ref(self, tref, m);
148 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
149 let generic_params = match foreign_item.node {
150 ForeignItemKind::Fn(_, ref generics) => {
151 HasGenericParams(generics, ItemRibKind)
153 ForeignItemKind::Static(..) => NoGenericParams,
154 ForeignItemKind::Ty => NoGenericParams,
155 ForeignItemKind::Macro(..) => NoGenericParams,
157 self.with_generic_param_rib(generic_params, |this| {
158 visit::walk_foreign_item(this, foreign_item);
161 fn visit_fn(&mut self,
162 function_kind: FnKind<'tcx>,
163 declaration: &'tcx FnDecl,
167 debug!("(resolving function) entering function");
168 let rib_kind = match function_kind {
169 FnKind::ItemFn(..) => FnItemRibKind,
170 FnKind::Method(..) | FnKind::Closure(_) => NormalRibKind,
173 // Create a value rib for the function.
174 self.ribs[ValueNS].push(Rib::new(rib_kind));
176 // Create a label rib for the function.
177 self.label_ribs.push(Rib::new(rib_kind));
179 // Add each argument to the rib.
180 let mut bindings_list = FxHashMap::default();
181 for argument in &declaration.inputs {
182 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
184 self.visit_ty(&argument.ty);
186 debug!("(resolving function) recorded argument");
188 visit::walk_fn_ret_ty(self, &declaration.output);
190 // Resolve the function body, potentially inside the body of an async closure
191 match function_kind {
192 FnKind::ItemFn(.., body) |
193 FnKind::Method(.., body) => {
194 self.visit_block(body);
196 FnKind::Closure(body) => {
197 self.visit_expr(body);
201 debug!("(resolving function) leaving function");
203 self.label_ribs.pop();
204 self.ribs[ValueNS].pop();
207 fn visit_generics(&mut self, generics: &'tcx Generics) {
208 // For type parameter defaults, we have to ban access
209 // to following type parameters, as the InternalSubsts can only
210 // provide previous type parameters as they're built. We
211 // put all the parameters on the ban list and then remove
212 // them one by one as they are processed and become available.
213 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
214 let mut found_default = false;
215 default_ban_rib.bindings.extend(generics.params.iter()
216 .filter_map(|param| match param.kind {
217 GenericParamKind::Const { .. } |
218 GenericParamKind::Lifetime { .. } => None,
219 GenericParamKind::Type { ref default, .. } => {
220 found_default |= default.is_some();
222 Some((Ident::with_empty_ctxt(param.ident.name), Res::Err))
229 // We also ban access to type parameters for use as the types of const parameters.
230 let mut const_ty_param_ban_rib = Rib::new(TyParamAsConstParamTy);
231 const_ty_param_ban_rib.bindings.extend(generics.params.iter()
233 if let GenericParamKind::Type { .. } = param.kind {
239 .map(|param| (Ident::with_empty_ctxt(param.ident.name), Res::Err)));
241 for param in &generics.params {
243 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
244 GenericParamKind::Type { ref default, .. } => {
245 for bound in ¶m.bounds {
246 self.visit_param_bound(bound);
249 if let Some(ref ty) = default {
250 self.ribs[TypeNS].push(default_ban_rib);
252 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
255 // Allow all following defaults to refer to this type parameter.
256 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
258 GenericParamKind::Const { ref ty } => {
259 self.ribs[TypeNS].push(const_ty_param_ban_rib);
261 for bound in ¶m.bounds {
262 self.visit_param_bound(bound);
267 const_ty_param_ban_rib = self.ribs[TypeNS].pop().unwrap();
271 for p in &generics.where_clause.predicates {
272 self.visit_where_predicate(p);
277 impl<'a, 'b> LateResolutionVisitor<'a, '_> {
278 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b> {
279 // During late resolution we only track the module component of the parent scope,
280 // although it may be useful to track other components as well for diagnostics.
281 let parent_scope = resolver.dummy_parent_scope();
282 let graph_root = resolver.graph_root;
283 LateResolutionVisitor {
287 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
288 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
289 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
291 label_ribs: Vec::new(),
292 current_trait_ref: None,
293 current_trait_assoc_types: Vec::new(),
294 current_self_type: None,
295 current_self_item: None,
296 unused_labels: Default::default(),
297 current_type_ascription: Vec::new(),
301 fn resolve_ident_in_lexical_scope(&mut self,
304 record_used_id: Option<NodeId>,
306 -> Option<LexicalScopeBinding<'a>> {
307 self.r.resolve_ident_in_lexical_scope(
308 ident, ns, &self.parent_scope, record_used_id, path_span, &self.ribs[ns]
315 opt_ns: Option<Namespace>, // `None` indicates a module path in import
318 crate_lint: CrateLint,
319 ) -> PathResult<'a> {
320 self.r.resolve_path_with_ribs(
321 path, opt_ns, &self.parent_scope, record_used, path_span, crate_lint, &self.ribs
327 // We maintain a list of value ribs and type ribs.
329 // Simultaneously, we keep track of the current position in the module
330 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
331 // the value or type namespaces, we first look through all the ribs and
332 // then query the module graph. When we resolve a name in the module
333 // namespace, we can skip all the ribs (since nested modules are not
334 // allowed within blocks in Rust) and jump straight to the current module
337 // Named implementations are handled separately. When we find a method
338 // call, we consult the module node to find all of the implementations in
339 // scope. This information is lazily cached in the module node. We then
340 // generate a fake "implementation scope" containing all the
341 // implementations thus found, for compatibility with old resolve pass.
343 fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
344 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
346 let id = self.r.definitions.local_def_id(id);
347 let module = self.r.module_map.get(&id).cloned(); // clones a reference
348 if let Some(module) = module {
349 // Move down in the graph.
350 let orig_module = replace(&mut self.parent_scope.module, module);
351 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
352 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
354 self.r.finalize_current_module_macro_resolutions(module);
357 self.parent_scope.module = orig_module;
358 self.ribs[ValueNS].pop();
359 self.ribs[TypeNS].pop();
366 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
367 /// is returned by the given predicate function
369 /// Stops after meeting a closure.
370 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
371 where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
373 for rib in self.label_ribs.iter().rev() {
376 // If an invocation of this macro created `ident`, give up on `ident`
377 // and switch to `ident`'s source from the macro definition.
378 MacroDefinition(def) => {
379 if def == self.r.macro_def(ident.span.ctxt()) {
380 ident.span.remove_mark();
384 // Do not resolve labels across function boundary
388 let r = pred(rib, ident);
396 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
397 debug!("resolve_adt");
398 self.with_current_self_item(item, |this| {
399 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
400 let item_def_id = this.r.definitions.local_def_id(item.id);
401 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
402 visit::walk_item(this, item);
408 fn future_proof_import(&mut self, use_tree: &UseTree) {
409 let segments = &use_tree.prefix.segments;
410 if !segments.is_empty() {
411 let ident = segments[0].ident;
412 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
416 let nss = match use_tree.kind {
417 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
420 let report_error = |this: &Self, ns| {
421 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
422 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
426 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
427 Some(LexicalScopeBinding::Res(..)) => {
428 report_error(self, ns);
430 Some(LexicalScopeBinding::Item(binding)) => {
431 let orig_blacklisted_binding =
432 replace(&mut self.r.blacklisted_binding, Some(binding));
433 if let Some(LexicalScopeBinding::Res(..)) =
434 self.resolve_ident_in_lexical_scope(ident, ns, None,
435 use_tree.prefix.span) {
436 report_error(self, ns);
438 self.r.blacklisted_binding = orig_blacklisted_binding;
443 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
444 for (use_tree, _) in use_trees {
445 self.future_proof_import(use_tree);
450 fn resolve_item(&mut self, item: &Item) {
451 let name = item.ident.name;
452 debug!("(resolving item) resolving {} ({:?})", name, item.node);
455 ItemKind::TyAlias(_, ref generics) |
456 ItemKind::OpaqueTy(_, ref generics) |
457 ItemKind::Fn(_, _, ref generics, _) => {
458 self.with_generic_param_rib(
459 HasGenericParams(generics, ItemRibKind),
460 |this| visit::walk_item(this, item)
464 ItemKind::Enum(_, ref generics) |
465 ItemKind::Struct(_, ref generics) |
466 ItemKind::Union(_, ref generics) => {
467 self.resolve_adt(item, generics);
470 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
471 self.resolve_implementation(generics,
477 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
478 // Create a new rib for the trait-wide type parameters.
479 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
480 let local_def_id = this.r.definitions.local_def_id(item.id);
481 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
482 this.visit_generics(generics);
483 walk_list!(this, visit_param_bound, bounds);
485 for trait_item in trait_items {
486 this.with_trait_items(trait_items, |this| {
487 let generic_params = HasGenericParams(
488 &trait_item.generics,
491 this.with_generic_param_rib(generic_params, |this| {
492 match trait_item.node {
493 TraitItemKind::Const(ref ty, ref default) => {
496 // Only impose the restrictions of
497 // ConstRibKind for an actual constant
498 // expression in a provided default.
499 if let Some(ref expr) = *default{
500 this.with_constant_rib(|this| {
501 this.visit_expr(expr);
505 TraitItemKind::Method(_, _) => {
506 visit::walk_trait_item(this, trait_item)
508 TraitItemKind::Type(..) => {
509 visit::walk_trait_item(this, trait_item)
511 TraitItemKind::Macro(_) => {
512 panic!("unexpanded macro in resolve!")
522 ItemKind::TraitAlias(ref generics, ref bounds) => {
523 // Create a new rib for the trait-wide type parameters.
524 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
525 let local_def_id = this.r.definitions.local_def_id(item.id);
526 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
527 this.visit_generics(generics);
528 walk_list!(this, visit_param_bound, bounds);
533 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
534 self.with_scope(item.id, |this| {
535 visit::walk_item(this, item);
539 ItemKind::Static(ref ty, _, ref expr) |
540 ItemKind::Const(ref ty, ref expr) => {
541 debug!("resolve_item ItemKind::Const");
542 self.with_item_rib(|this| {
544 this.with_constant_rib(|this| {
545 this.visit_expr(expr);
550 ItemKind::Use(ref use_tree) => {
551 self.future_proof_import(use_tree);
554 ItemKind::ExternCrate(..) |
555 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
556 // do nothing, these are just around to be encoded
559 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
563 fn with_generic_param_rib<'c, F>(&'c mut self, generic_params: GenericParameters<'a, 'c>, f: F)
564 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
566 debug!("with_generic_param_rib");
567 match generic_params {
568 HasGenericParams(generics, rib_kind) => {
569 let mut function_type_rib = Rib::new(rib_kind);
570 let mut function_value_rib = Rib::new(rib_kind);
571 let mut seen_bindings = FxHashMap::default();
572 for param in &generics.params {
574 GenericParamKind::Lifetime { .. } => {}
575 GenericParamKind::Type { .. } => {
576 let ident = param.ident.modern();
577 debug!("with_generic_param_rib: {}", param.id);
579 if seen_bindings.contains_key(&ident) {
580 let span = seen_bindings.get(&ident).unwrap();
581 let err = ResolutionError::NameAlreadyUsedInParameterList(
585 resolve_error(&self.r, param.ident.span, err);
587 seen_bindings.entry(ident).or_insert(param.ident.span);
589 // Plain insert (no renaming).
592 self.r.definitions.local_def_id(param.id),
594 function_type_rib.bindings.insert(ident, res);
595 self.r.record_partial_res(param.id, PartialRes::new(res));
597 GenericParamKind::Const { .. } => {
598 let ident = param.ident.modern();
599 debug!("with_generic_param_rib: {}", param.id);
601 if seen_bindings.contains_key(&ident) {
602 let span = seen_bindings.get(&ident).unwrap();
603 let err = ResolutionError::NameAlreadyUsedInParameterList(
607 resolve_error(&self.r, param.ident.span, err);
609 seen_bindings.entry(ident).or_insert(param.ident.span);
613 self.r.definitions.local_def_id(param.id),
615 function_value_rib.bindings.insert(ident, res);
616 self.r.record_partial_res(param.id, PartialRes::new(res));
620 self.ribs[ValueNS].push(function_value_rib);
621 self.ribs[TypeNS].push(function_type_rib);
631 if let HasGenericParams(..) = generic_params {
632 self.ribs[TypeNS].pop();
633 self.ribs[ValueNS].pop();
637 fn with_label_rib<F>(&mut self, f: F)
638 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
640 self.label_ribs.push(Rib::new(NormalRibKind));
642 self.label_ribs.pop();
645 fn with_item_rib<F>(&mut self, f: F)
646 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
648 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
649 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
651 self.ribs[TypeNS].pop();
652 self.ribs[ValueNS].pop();
655 fn with_constant_rib<F>(&mut self, f: F)
656 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
658 debug!("with_constant_rib");
659 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
660 self.label_ribs.push(Rib::new(ConstantItemRibKind));
662 self.label_ribs.pop();
663 self.ribs[ValueNS].pop();
666 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
667 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
669 // Handle nested impls (inside fn bodies)
670 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
671 let result = f(self);
672 self.current_self_type = previous_value;
676 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
677 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
679 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
680 let result = f(self);
681 self.current_self_item = previous_value;
685 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
686 fn with_trait_items<T, F>(&mut self, trait_items: &Vec<TraitItem>, f: F) -> T
687 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
689 let trait_assoc_types = replace(
690 &mut self.current_trait_assoc_types,
691 trait_items.iter().filter_map(|item| match &item.node {
692 TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
696 let result = f(self);
697 self.current_trait_assoc_types = trait_assoc_types;
701 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
702 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
703 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>, Option<DefId>) -> T
705 let mut new_val = None;
706 let mut new_id = None;
707 if let Some(trait_ref) = opt_trait_ref {
708 let path: Vec<_> = Segment::from_path(&trait_ref.path);
709 let res = self.smart_resolve_path_fragment(
714 PathSource::Trait(AliasPossibility::No),
715 CrateLint::SimplePath(trait_ref.ref_id),
718 new_id = Some(res.def_id());
719 let span = trait_ref.path.span;
720 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
726 CrateLint::SimplePath(trait_ref.ref_id),
729 new_val = Some((module, trait_ref.clone()));
733 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
734 let result = f(self, new_id);
735 self.current_trait_ref = original_trait_ref;
739 fn with_self_rib<F>(&mut self, self_res: Res, f: F)
740 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
742 let mut self_type_rib = Rib::new(NormalRibKind);
744 // Plain insert (no renaming, since types are not currently hygienic)
745 self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
746 self.ribs[TypeNS].push(self_type_rib);
748 self.ribs[TypeNS].pop();
751 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
752 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
754 let self_res = Res::SelfCtor(impl_id);
755 let mut self_type_rib = Rib::new(NormalRibKind);
756 self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
757 self.ribs[ValueNS].push(self_type_rib);
759 self.ribs[ValueNS].pop();
762 fn resolve_implementation(&mut self,
764 opt_trait_reference: &Option<TraitRef>,
767 impl_items: &[ImplItem]) {
768 debug!("resolve_implementation");
769 // If applicable, create a rib for the type parameters.
770 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
771 // Dummy self type for better errors if `Self` is used in the trait path.
772 this.with_self_rib(Res::SelfTy(None, None), |this| {
773 // Resolve the trait reference, if necessary.
774 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
775 let item_def_id = this.r.definitions.local_def_id(item_id);
776 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
777 if let Some(trait_ref) = opt_trait_reference.as_ref() {
778 // Resolve type arguments in the trait path.
779 visit::walk_trait_ref(this, trait_ref);
781 // Resolve the self type.
782 this.visit_ty(self_type);
783 // Resolve the generic parameters.
784 this.visit_generics(generics);
785 // Resolve the items within the impl.
786 this.with_current_self_type(self_type, |this| {
787 this.with_self_struct_ctor_rib(item_def_id, |this| {
788 debug!("resolve_implementation with_self_struct_ctor_rib");
789 for impl_item in impl_items {
790 this.r.resolve_visibility(
791 &impl_item.vis, &this.parent_scope
793 // We also need a new scope for the impl item type parameters.
794 let generic_params = HasGenericParams(&impl_item.generics,
796 this.with_generic_param_rib(generic_params, |this| {
797 use crate::ResolutionError::*;
798 match impl_item.node {
799 ImplItemKind::Const(..) => {
801 "resolve_implementation ImplItemKind::Const",
803 // If this is a trait impl, ensure the const
805 this.check_trait_item(
809 |n, s| ConstNotMemberOfTrait(n, s),
812 this.with_constant_rib(|this| {
813 visit::walk_impl_item(this, impl_item)
816 ImplItemKind::Method(..) => {
817 // If this is a trait impl, ensure the method
819 this.check_trait_item(impl_item.ident,
822 |n, s| MethodNotMemberOfTrait(n, s));
824 visit::walk_impl_item(this, impl_item);
826 ImplItemKind::TyAlias(ref ty) => {
827 // If this is a trait impl, ensure the type
829 this.check_trait_item(impl_item.ident,
832 |n, s| TypeNotMemberOfTrait(n, s));
836 ImplItemKind::OpaqueTy(ref bounds) => {
837 // If this is a trait impl, ensure the type
839 this.check_trait_item(impl_item.ident,
842 |n, s| TypeNotMemberOfTrait(n, s));
844 for bound in bounds {
845 this.visit_param_bound(bound);
848 ImplItemKind::Macro(_) =>
849 panic!("unexpanded macro in resolve!"),
861 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
862 where F: FnOnce(Name, &str) -> ResolutionError<'_>
864 // If there is a TraitRef in scope for an impl, then the method must be in the
866 if let Some((module, _)) = self.current_trait_ref {
867 if self.r.resolve_ident_in_module(
868 ModuleOrUniformRoot::Module(module),
875 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
876 resolve_error(&self.r, span, err(ident.name, &path_names_to_string(path)));
881 fn resolve_local(&mut self, local: &Local) {
883 walk_list!(self, visit_ty, &local.ty);
885 // Resolve the initializer.
886 walk_list!(self, visit_expr, &local.init);
888 // Resolve the pattern.
889 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
892 // build a map from pattern identifiers to binding-info's.
893 // this is done hygienically. This could arise for a macro
894 // that expands into an or-pattern where one 'x' was from the
895 // user and one 'x' came from the macro.
896 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
897 let mut binding_map = FxHashMap::default();
899 pat.walk(&mut |pat| {
900 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
901 if sub_pat.is_some() || match self.r.partial_res_map.get(&pat.id)
902 .map(|res| res.base_res()) {
903 Some(Res::Local(..)) => true,
906 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
907 binding_map.insert(ident, binding_info);
916 // Checks that all of the arms in an or-pattern have exactly the
917 // same set of bindings, with the same binding modes for each.
918 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
923 let mut missing_vars = FxHashMap::default();
924 let mut inconsistent_vars = FxHashMap::default();
925 for (i, p) in pats.iter().enumerate() {
926 let map_i = self.binding_mode_map(&p);
928 for (j, q) in pats.iter().enumerate() {
933 let map_j = self.binding_mode_map(&q);
934 for (&key, &binding_i) in &map_i {
935 if map_j.is_empty() { // Account for missing bindings when
936 let binding_error = missing_vars // `map_j` has none.
938 .or_insert(BindingError {
940 origin: BTreeSet::new(),
941 target: BTreeSet::new(),
943 binding_error.origin.insert(binding_i.span);
944 binding_error.target.insert(q.span);
946 for (&key_j, &binding_j) in &map_j {
947 match map_i.get(&key_j) {
948 None => { // missing binding
949 let binding_error = missing_vars
951 .or_insert(BindingError {
953 origin: BTreeSet::new(),
954 target: BTreeSet::new(),
956 binding_error.origin.insert(binding_j.span);
957 binding_error.target.insert(p.span);
959 Some(binding_i) => { // check consistent binding
960 if binding_i.binding_mode != binding_j.binding_mode {
963 .or_insert((binding_j.span, binding_i.span));
971 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
973 for (_, v) in missing_vars {
974 resolve_error(&self.r,
975 *v.origin.iter().next().unwrap(),
976 ResolutionError::VariableNotBoundInPattern(v));
978 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
979 inconsistent_vars.sort();
980 for (name, v) in inconsistent_vars {
981 let err = ResolutionError::VariableBoundWithDifferentMode(*name, v.1);
982 resolve_error(&self.r, v.0, err);
986 fn resolve_arm(&mut self, arm: &Arm) {
987 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
989 self.resolve_pats(&arm.pats, PatternSource::Match);
991 if let Some(ref expr) = arm.guard {
992 self.visit_expr(expr)
994 self.visit_expr(&arm.body);
996 self.ribs[ValueNS].pop();
999 /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
1000 fn resolve_pats(&mut self, pats: &[P<Pat>], source: PatternSource) {
1001 let mut bindings_list = FxHashMap::default();
1003 self.resolve_pattern(pat, source, &mut bindings_list);
1005 // This has to happen *after* we determine which pat_idents are variants
1006 self.check_consistent_bindings(pats);
1009 fn resolve_block(&mut self, block: &Block) {
1010 debug!("(resolving block) entering block");
1011 // Move down in the graph, if there's an anonymous module rooted here.
1012 let orig_module = self.parent_scope.module;
1013 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1015 let mut num_macro_definition_ribs = 0;
1016 if let Some(anonymous_module) = anonymous_module {
1017 debug!("(resolving block) found anonymous module, moving down");
1018 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1019 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1020 self.parent_scope.module = anonymous_module;
1021 self.r.finalize_current_module_macro_resolutions(anonymous_module);
1023 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1026 // Descend into the block.
1027 for stmt in &block.stmts {
1028 if let StmtKind::Item(ref item) = stmt.node {
1029 if let ItemKind::MacroDef(..) = item.node {
1030 num_macro_definition_ribs += 1;
1031 let res = self.r.definitions.local_def_id(item.id);
1032 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
1033 self.label_ribs.push(Rib::new(MacroDefinition(res)));
1037 self.visit_stmt(stmt);
1041 self.parent_scope.module = orig_module;
1042 for _ in 0 .. num_macro_definition_ribs {
1043 self.ribs[ValueNS].pop();
1044 self.label_ribs.pop();
1046 self.ribs[ValueNS].pop();
1047 if anonymous_module.is_some() {
1048 self.ribs[TypeNS].pop();
1050 debug!("(resolving block) leaving block");
1053 fn fresh_binding(&mut self,
1056 outer_pat_id: NodeId,
1057 pat_src: PatternSource,
1058 bindings: &mut FxHashMap<Ident, NodeId>)
1060 // Add the binding to the local ribs, if it
1061 // doesn't already exist in the bindings map. (We
1062 // must not add it if it's in the bindings map
1063 // because that breaks the assumptions later
1064 // passes make about or-patterns.)
1065 let ident = ident.modern_and_legacy();
1066 let mut res = Res::Local(pat_id);
1067 match bindings.get(&ident).cloned() {
1068 Some(id) if id == outer_pat_id => {
1069 // `Variant(a, a)`, error
1073 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
1077 Some(..) if pat_src == PatternSource::FnParam => {
1078 // `fn f(a: u8, a: u8)`, error
1082 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
1086 Some(..) if pat_src == PatternSource::Match ||
1087 pat_src == PatternSource::Let => {
1088 // `Variant1(a) | Variant2(a)`, ok
1089 // Reuse definition from the first `a`.
1090 res = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
1093 span_bug!(ident.span, "two bindings with the same name from \
1094 unexpected pattern source {:?}", pat_src);
1097 // A completely fresh binding, add to the lists if it's valid.
1098 if ident.name != kw::Invalid {
1099 bindings.insert(ident, outer_pat_id);
1100 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, res);
1108 fn resolve_pattern(&mut self,
1110 pat_src: PatternSource,
1111 // Maps idents to the node ID for the
1112 // outermost pattern that binds them.
1113 bindings: &mut FxHashMap<Ident, NodeId>) {
1114 // Visit all direct subpatterns of this pattern.
1115 let outer_pat_id = pat.id;
1116 pat.walk(&mut |pat| {
1117 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
1119 PatKind::Ident(bmode, ident, ref opt_pat) => {
1120 // First try to resolve the identifier as some existing
1121 // entity, then fall back to a fresh binding.
1122 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
1124 .and_then(LexicalScopeBinding::item);
1125 let res = binding.map(NameBinding::res).and_then(|res| {
1126 let is_syntactic_ambiguity = opt_pat.is_none() &&
1127 bmode == BindingMode::ByValue(Mutability::Immutable);
1129 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
1130 Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
1131 // Disambiguate in favor of a unit struct/variant
1132 // or constant pattern.
1133 self.r.record_use(ident, ValueNS, binding.unwrap(), false);
1136 Res::Def(DefKind::Ctor(..), _)
1137 | Res::Def(DefKind::Const, _)
1138 | Res::Def(DefKind::Static, _) => {
1139 // This is unambiguously a fresh binding, either syntactically
1140 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1141 // to something unusable as a pattern (e.g., constructor function),
1142 // but we still conservatively report an error, see
1143 // issues/33118#issuecomment-233962221 for one reason why.
1147 ResolutionError::BindingShadowsSomethingUnacceptable(
1148 pat_src.descr(), ident.name, binding.unwrap())
1152 Res::Def(DefKind::Fn, _) | Res::Err => {
1153 // These entities are explicitly allowed
1154 // to be shadowed by fresh bindings.
1158 span_bug!(ident.span, "unexpected resolution for an \
1159 identifier in pattern: {:?}", res);
1162 }).unwrap_or_else(|| {
1163 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
1166 self.r.record_partial_res(pat.id, PartialRes::new(res));
1169 PatKind::TupleStruct(ref path, ..) => {
1170 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1173 PatKind::Path(ref qself, ref path) => {
1174 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1177 PatKind::Struct(ref path, ..) => {
1178 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1186 visit::walk_pat(self, pat);
1189 // High-level and context dependent path resolution routine.
1190 // Resolves the path and records the resolution into definition map.
1191 // If resolution fails tries several techniques to find likely
1192 // resolution candidates, suggest imports or other help, and report
1193 // errors in user friendly way.
1194 fn smart_resolve_path(&mut self,
1196 qself: Option<&QSelf>,
1198 source: PathSource<'_>) {
1199 self.smart_resolve_path_fragment(
1202 &Segment::from_path(path),
1205 CrateLint::SimplePath(id),
1209 fn smart_resolve_path_fragment(&mut self,
1211 qself: Option<&QSelf>,
1214 source: PathSource<'_>,
1215 crate_lint: CrateLint)
1217 let ns = source.namespace();
1218 let is_expected = &|res| source.is_expected(res);
1220 let report_errors = |this: &mut Self, res: Option<Res>| {
1221 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1222 let def_id = this.parent_scope.module.normal_ancestor_id;
1223 let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1224 let better = res.is_some();
1225 this.r.use_injections.push(UseError { err, candidates, node_id, better });
1226 PartialRes::new(Res::Err)
1229 let partial_res = match self.resolve_qpath_anywhere(
1235 source.defer_to_typeck(),
1238 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1239 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1242 // Add a temporary hack to smooth the transition to new struct ctor
1243 // visibility rules. See #38932 for more details.
1245 if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
1246 if let Some((ctor_res, ctor_vis))
1247 = self.r.struct_constructors.get(&def_id).cloned() {
1248 if is_expected(ctor_res) &&
1249 self.r.is_accessible_from(ctor_vis, self.parent_scope.module) {
1250 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
1251 self.r.session.buffer_lint(lint, id, span,
1252 "private struct constructors are not usable through \
1253 re-exports in outer modules",
1255 res = Some(PartialRes::new(ctor_res));
1260 res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
1263 Some(partial_res) if source.defer_to_typeck() => {
1264 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1265 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1266 // it needs to be added to the trait map.
1268 let item_name = path.last().unwrap().ident;
1269 let traits = self.get_traits_containing_item(item_name, ns);
1270 self.r.trait_map.insert(id, traits);
1273 let mut std_path = vec![Segment::from_ident(Ident::with_empty_ctxt(sym::std))];
1274 std_path.extend(path);
1275 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1276 let cl = CrateLint::No;
1278 if let PathResult::Module(_) | PathResult::NonModule(_) =
1279 self.resolve_path(&std_path, ns, false, span, cl) {
1280 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1281 let item_span = path.iter().last().map(|segment| segment.ident.span)
1283 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1284 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1285 hm.insert(item_span, span);
1286 // In some places (E0223) we only have access to the full path
1287 hm.insert(span, span);
1292 _ => report_errors(self, None)
1295 if let PathSource::TraitItem(..) = source {} else {
1296 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1297 self.r.record_partial_res(id, partial_res);
1302 fn self_type_is_available(&mut self, span: Span) -> bool {
1303 let binding = self.resolve_ident_in_lexical_scope(
1304 Ident::with_empty_ctxt(kw::SelfUpper),
1309 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1312 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1313 let ident = Ident::new(kw::SelfLower, self_span);
1314 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1315 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1318 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1319 fn resolve_qpath_anywhere(
1322 qself: Option<&QSelf>,
1324 primary_ns: Namespace,
1326 defer_to_typeck: bool,
1327 crate_lint: CrateLint,
1328 ) -> Option<PartialRes> {
1329 let mut fin_res = None;
1330 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1331 if i == 0 || ns != primary_ns {
1332 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1333 // If defer_to_typeck, then resolution > no resolution,
1334 // otherwise full resolution > partial resolution > no resolution.
1335 Some(partial_res) if partial_res.unresolved_segments() == 0 ||
1337 return Some(partial_res),
1338 partial_res => if fin_res.is_none() { fin_res = partial_res },
1344 assert!(primary_ns != MacroNS);
1345 if qself.is_none() {
1346 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1347 let path = Path { segments: path.iter().map(path_seg).collect(), span };
1348 if let Ok((_, res)) = self.r.resolve_macro_path(
1349 &path, None, &self.parent_scope, false, false
1351 return Some(PartialRes::new(res));
1358 /// Handles paths that may refer to associated items.
1362 qself: Option<&QSelf>,
1366 crate_lint: CrateLint,
1367 ) -> Option<PartialRes> {
1369 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1377 if let Some(qself) = qself {
1378 if qself.position == 0 {
1379 // This is a case like `<T>::B`, where there is no
1380 // trait to resolve. In that case, we leave the `B`
1381 // segment to be resolved by type-check.
1382 return Some(PartialRes::with_unresolved_segments(
1383 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
1387 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1389 // Currently, `path` names the full item (`A::B::C`, in
1390 // our example). so we extract the prefix of that that is
1391 // the trait (the slice upto and including
1392 // `qself.position`). And then we recursively resolve that,
1393 // but with `qself` set to `None`.
1395 // However, setting `qself` to none (but not changing the
1396 // span) loses the information about where this path
1397 // *actually* appears, so for the purposes of the crate
1398 // lint we pass along information that this is the trait
1399 // name from a fully qualified path, and this also
1400 // contains the full span (the `CrateLint::QPathTrait`).
1401 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1402 let partial_res = self.smart_resolve_path_fragment(
1405 &path[..=qself.position],
1407 PathSource::TraitItem(ns),
1408 CrateLint::QPathTrait {
1410 qpath_span: qself.path_span,
1414 // The remaining segments (the `C` in our example) will
1415 // have to be resolved by type-check, since that requires doing
1416 // trait resolution.
1417 return Some(PartialRes::with_unresolved_segments(
1418 partial_res.base_res(),
1419 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1423 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1424 PathResult::NonModule(path_res) => path_res,
1425 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1426 PartialRes::new(module.res().unwrap())
1428 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1429 // don't report an error right away, but try to fallback to a primitive type.
1430 // So, we are still able to successfully resolve something like
1432 // use std::u8; // bring module u8 in scope
1433 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1434 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
1435 // // not to non-existent std::u8::max_value
1438 // Such behavior is required for backward compatibility.
1439 // The same fallback is used when `a` resolves to nothing.
1440 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
1441 PathResult::Failed { .. }
1442 if (ns == TypeNS || path.len() > 1) &&
1443 self.r.primitive_type_table.primitive_types
1444 .contains_key(&path[0].ident.name) => {
1445 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1446 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1448 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1449 PartialRes::new(module.res().unwrap()),
1450 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1451 let err = ResolutionError::FailedToResolve { label, suggestion };
1452 resolve_error(&self.r, span, err);
1453 PartialRes::new(Res::Err)
1455 PathResult::Module(..) | PathResult::Failed { .. } => return None,
1456 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1459 if path.len() > 1 && result.base_res() != Res::Err &&
1460 path[0].ident.name != kw::PathRoot &&
1461 path[0].ident.name != kw::DollarCrate {
1462 let unqualified_result = {
1463 match self.resolve_path(
1464 &[*path.last().unwrap()],
1470 PathResult::NonModule(path_res) => path_res.base_res(),
1471 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1472 module.res().unwrap(),
1473 _ => return Some(result),
1476 if result.base_res() == unqualified_result {
1477 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1478 self.r.session.buffer_lint(lint, id, span, "unnecessary qualification")
1485 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
1486 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
1488 if let Some(label) = label {
1489 self.unused_labels.insert(id, label.ident.span);
1490 self.with_label_rib(|this| {
1491 let ident = label.ident.modern_and_legacy();
1492 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1500 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
1501 self.with_resolved_label(label, id, |this| this.visit_block(block));
1504 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
1505 // First, record candidate traits for this expression if it could
1506 // result in the invocation of a method call.
1508 self.record_candidate_traits_for_expr_if_necessary(expr);
1510 // Next, resolve the node.
1512 ExprKind::Path(ref qself, ref path) => {
1513 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1514 visit::walk_expr(self, expr);
1517 ExprKind::Struct(ref path, ..) => {
1518 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1519 visit::walk_expr(self, expr);
1522 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1523 let node_id = self.search_label(label.ident, |rib, ident| {
1524 rib.bindings.get(&ident.modern_and_legacy()).cloned()
1528 // Search again for close matches...
1529 // Picks the first label that is "close enough", which is not necessarily
1530 // the closest match
1531 let close_match = self.search_label(label.ident, |rib, ident| {
1532 let names = rib.bindings.iter().filter_map(|(id, _)| {
1533 if id.span.ctxt() == label.ident.span.ctxt() {
1539 find_best_match_for_name(names, &*ident.as_str(), None)
1541 self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1542 resolve_error(&self.r,
1544 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
1548 // Since this res is a label, it is never read.
1549 self.r.label_res_map.insert(expr.id, node_id);
1550 self.unused_labels.remove(&node_id);
1554 // visit `break` argument if any
1555 visit::walk_expr(self, expr);
1558 ExprKind::Let(ref pats, ref scrutinee) => {
1559 self.visit_expr(scrutinee);
1560 self.resolve_pats(pats, PatternSource::Let);
1563 ExprKind::If(ref cond, ref then, ref opt_else) => {
1564 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1565 self.visit_expr(cond);
1566 self.visit_block(then);
1567 self.ribs[ValueNS].pop();
1569 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1572 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1574 ExprKind::While(ref subexpression, ref block, label) => {
1575 self.with_resolved_label(label, expr.id, |this| {
1576 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
1577 this.visit_expr(subexpression);
1578 this.visit_block(block);
1579 this.ribs[ValueNS].pop();
1583 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
1584 self.visit_expr(subexpression);
1585 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1586 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
1588 self.resolve_labeled_block(label, expr.id, block);
1590 self.ribs[ValueNS].pop();
1593 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1595 // Equivalent to `visit::walk_expr` + passing some context to children.
1596 ExprKind::Field(ref subexpression, _) => {
1597 self.resolve_expr(subexpression, Some(expr));
1599 ExprKind::MethodCall(ref segment, ref arguments) => {
1600 let mut arguments = arguments.iter();
1601 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1602 for argument in arguments {
1603 self.resolve_expr(argument, None);
1605 self.visit_path_segment(expr.span, segment);
1608 ExprKind::Call(ref callee, ref arguments) => {
1609 self.resolve_expr(callee, Some(expr));
1610 for argument in arguments {
1611 self.resolve_expr(argument, None);
1614 ExprKind::Type(ref type_expr, _) => {
1615 self.current_type_ascription.push(type_expr.span);
1616 visit::walk_expr(self, expr);
1617 self.current_type_ascription.pop();
1619 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
1620 // resolve the arguments within the proper scopes so that usages of them inside the
1621 // closure are detected as upvars rather than normal closure arg usages.
1623 _, IsAsync::Async { .. }, _,
1624 ref fn_decl, ref body, _span,
1626 let rib_kind = NormalRibKind;
1627 self.ribs[ValueNS].push(Rib::new(rib_kind));
1628 // Resolve arguments:
1629 let mut bindings_list = FxHashMap::default();
1630 for argument in &fn_decl.inputs {
1631 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
1632 self.visit_ty(&argument.ty);
1634 // No need to resolve return type-- the outer closure return type is
1635 // FunctionRetTy::Default
1637 // Now resolve the inner closure
1639 // No need to resolve arguments: the inner closure has none.
1640 // Resolve the return type:
1641 visit::walk_fn_ret_ty(self, &fn_decl.output);
1643 self.visit_expr(body);
1645 self.ribs[ValueNS].pop();
1648 visit::walk_expr(self, expr);
1653 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
1655 ExprKind::Field(_, ident) => {
1656 // FIXME(#6890): Even though you can't treat a method like a
1657 // field, we need to add any trait methods we find that match
1658 // the field name so that we can do some nice error reporting
1659 // later on in typeck.
1660 let traits = self.get_traits_containing_item(ident, ValueNS);
1661 self.r.trait_map.insert(expr.id, traits);
1663 ExprKind::MethodCall(ref segment, ..) => {
1664 debug!("(recording candidate traits for expr) recording traits for {}",
1666 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
1667 self.r.trait_map.insert(expr.id, traits);
1675 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
1676 -> Vec<TraitCandidate> {
1677 debug!("(getting traits containing item) looking for '{}'", ident.name);
1679 let mut found_traits = Vec::new();
1680 // Look for the current trait.
1681 if let Some((module, _)) = self.current_trait_ref {
1682 if self.r.resolve_ident_in_module(
1683 ModuleOrUniformRoot::Module(module),
1690 let def_id = module.def_id().unwrap();
1691 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
1695 ident.span = ident.span.modern();
1696 let mut search_module = self.parent_scope.module;
1698 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
1699 search_module = unwrap_or!(
1700 self.r.hygienic_lexical_parent(search_module, &mut ident.span), break
1704 if let Some(prelude) = self.r.prelude {
1705 if !search_module.no_implicit_prelude {
1706 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
1713 fn get_traits_in_module_containing_item(&mut self,
1717 found_traits: &mut Vec<TraitCandidate>) {
1718 assert!(ns == TypeNS || ns == ValueNS);
1719 let mut traits = module.traits.borrow_mut();
1720 if traits.is_none() {
1721 let mut collected_traits = Vec::new();
1722 module.for_each_child(|name, ns, binding| {
1723 if ns != TypeNS { return }
1724 match binding.res() {
1725 Res::Def(DefKind::Trait, _) |
1726 Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
1730 *traits = Some(collected_traits.into_boxed_slice());
1733 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
1734 // Traits have pseudo-modules that can be used to search for the given ident.
1735 if let Some(module) = binding.module() {
1736 let mut ident = ident;
1737 if ident.span.glob_adjust(
1743 if self.r.resolve_ident_in_module_unadjusted(
1744 ModuleOrUniformRoot::Module(module),
1751 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1752 let trait_def_id = module.def_id().unwrap();
1753 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1755 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
1756 // For now, just treat all trait aliases as possible candidates, since we don't
1757 // know if the ident is somewhere in the transitive bounds.
1758 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1759 let trait_def_id = binding.res().def_id();
1760 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1762 bug!("candidate is not trait or trait alias?")
1767 fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
1768 trait_name: Ident) -> SmallVec<[NodeId; 1]> {
1769 let mut import_ids = smallvec![];
1770 while let NameBindingKind::Import { directive, binding, .. } = kind {
1771 self.r.maybe_unused_trait_imports.insert(directive.id);
1772 self.r.add_to_glob_map(&directive, trait_name);
1773 import_ids.push(directive.id);
1774 kind = &binding.kind;
1780 impl<'a> Resolver<'a> {
1781 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
1782 self.finalize_current_module_macro_resolutions(self.graph_root);
1783 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
1784 visit::walk_crate(&mut late_resolution_visitor, krate);
1785 for (id, span) in late_resolution_visitor.unused_labels.iter() {
1786 self.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");