1 use GenericParameters::*;
4 use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
5 use crate::{Module, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult};
6 use crate::{ResolutionError, Resolver, Segment, UseError};
9 use rustc::{bug, lint, span_bug};
10 use rustc::hir::def::{self, PartialRes, DefKind, CtorKind, PerNS};
11 use rustc::hir::def::Namespace::{self, *};
12 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
13 use rustc::hir::TraitCandidate;
14 use rustc::util::nodemap::FxHashMap;
15 use smallvec::{smallvec, SmallVec};
16 use syntax::{unwrap_or, walk_list};
19 use syntax::symbol::{kw, sym};
20 use syntax::util::lev_distance::find_best_match_for_name;
21 use syntax::visit::{self, Visitor, FnKind};
24 use std::collections::BTreeSet;
25 use std::mem::replace;
29 type Res = def::Res<NodeId>;
31 /// Map from the name in a pattern to its binding mode.
32 type BindingMap = FxHashMap<Ident, BindingInfo>;
34 #[derive(Copy, Clone, Debug)]
37 binding_mode: BindingMode,
40 #[derive(Copy, Clone)]
41 enum GenericParameters<'a, 'b> {
43 HasGenericParams(// Type parameters.
46 // The kind of the rib used for type parameters.
50 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
59 fn descr(self) -> &'static str {
61 PatternSource::Match => "match binding",
62 PatternSource::Let => "let binding",
63 PatternSource::For => "for binding",
64 PatternSource::FnParam => "function parameter",
69 /// The rib kind restricts certain accesses,
70 /// e.g. to a `Res::Local` of an outer item.
71 #[derive(Copy, Clone, Debug)]
72 crate enum RibKind<'a> {
73 /// No restriction needs to be applied.
76 /// We passed through an impl or trait and are now in one of its
77 /// methods or associated types. Allow references to ty params that impl or trait
78 /// binds. Disallow any other upvars (including other ty params that are
82 /// We passed through a function definition. Disallow upvars.
83 /// Permit only those const parameters that are specified in the function's generics.
86 /// We passed through an item scope. Disallow upvars.
89 /// We're in a constant item. Can't refer to dynamic stuff.
92 /// We passed through a module.
93 ModuleRibKind(Module<'a>),
95 /// We passed through a `macro_rules!` statement
96 MacroDefinition(DefId),
98 /// All bindings in this rib are type parameters that can't be used
99 /// from the default of a type parameter because they're not declared
100 /// before said type parameter. Also see the `visit_generics` override.
101 ForwardTyParamBanRibKind,
103 /// We forbid the use of type parameters as the types of const parameters.
104 TyParamAsConstParamTy,
107 /// A single local scope.
109 /// A rib represents a scope names can live in. Note that these appear in many places, not just
110 /// around braces. At any place where the list of accessible names (of the given namespace)
111 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
112 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
115 /// Different [rib kinds](enum.RibKind) are transparent for different names.
117 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
118 /// resolving, the name is looked up from inside out.
120 crate struct Rib<'a, R = Res> {
121 pub bindings: FxHashMap<Ident, R>,
122 pub kind: RibKind<'a>,
125 impl<'a, R> Rib<'a, R> {
126 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
128 bindings: Default::default(),
134 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
135 crate enum AliasPossibility {
140 #[derive(Copy, Clone, Debug)]
141 crate enum PathSource<'a> {
142 // Type paths `Path`.
144 // Trait paths in bounds or impls.
145 Trait(AliasPossibility),
146 // Expression paths `path`, with optional parent context.
147 Expr(Option<&'a Expr>),
148 // Paths in path patterns `Path`.
150 // Paths in struct expressions and patterns `Path { .. }`.
152 // Paths in tuple struct patterns `Path(..)`.
154 // `m::A::B` in `<T as m::A>::B::C`.
155 TraitItem(Namespace),
158 impl<'a> PathSource<'a> {
159 fn namespace(self) -> Namespace {
161 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
162 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
163 PathSource::TraitItem(ns) => ns,
167 fn defer_to_typeck(self) -> bool {
169 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
170 PathSource::Struct | PathSource::TupleStruct => true,
171 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
175 fn descr_expected(self) -> &'static str {
177 PathSource::Type => "type",
178 PathSource::Trait(_) => "trait",
179 PathSource::Pat => "unit struct/variant or constant",
180 PathSource::Struct => "struct, variant or union type",
181 PathSource::TupleStruct => "tuple struct/variant",
182 PathSource::TraitItem(ns) => match ns {
183 TypeNS => "associated type",
184 ValueNS => "method or associated constant",
185 MacroNS => bug!("associated macro"),
187 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
188 // "function" here means "anything callable" rather than `DefKind::Fn`,
189 // this is not precise but usually more helpful than just "value".
190 Some(&ExprKind::Call(..)) => "function",
196 crate fn is_expected(self, res: Res) -> bool {
198 PathSource::Type => match res {
199 Res::Def(DefKind::Struct, _)
200 | Res::Def(DefKind::Union, _)
201 | Res::Def(DefKind::Enum, _)
202 | Res::Def(DefKind::Trait, _)
203 | Res::Def(DefKind::TraitAlias, _)
204 | Res::Def(DefKind::TyAlias, _)
205 | Res::Def(DefKind::AssocTy, _)
207 | Res::Def(DefKind::TyParam, _)
209 | Res::Def(DefKind::OpaqueTy, _)
210 | Res::Def(DefKind::ForeignTy, _) => true,
213 PathSource::Trait(AliasPossibility::No) => match res {
214 Res::Def(DefKind::Trait, _) => true,
217 PathSource::Trait(AliasPossibility::Maybe) => match res {
218 Res::Def(DefKind::Trait, _) => true,
219 Res::Def(DefKind::TraitAlias, _) => true,
222 PathSource::Expr(..) => match res {
223 Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
224 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
225 | Res::Def(DefKind::Const, _)
226 | Res::Def(DefKind::Static, _)
228 | Res::Def(DefKind::Fn, _)
229 | Res::Def(DefKind::Method, _)
230 | Res::Def(DefKind::AssocConst, _)
232 | Res::Def(DefKind::ConstParam, _) => true,
235 PathSource::Pat => match res {
236 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
237 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) |
238 Res::SelfCtor(..) => true,
241 PathSource::TupleStruct => match res {
242 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
245 PathSource::Struct => match res {
246 Res::Def(DefKind::Struct, _)
247 | Res::Def(DefKind::Union, _)
248 | Res::Def(DefKind::Variant, _)
249 | Res::Def(DefKind::TyAlias, _)
250 | Res::Def(DefKind::AssocTy, _)
251 | Res::SelfTy(..) => true,
254 PathSource::TraitItem(ns) => match res {
255 Res::Def(DefKind::AssocConst, _)
256 | Res::Def(DefKind::Method, _) if ns == ValueNS => true,
257 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
263 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
264 __diagnostic_used!(E0404);
265 __diagnostic_used!(E0405);
266 __diagnostic_used!(E0412);
267 __diagnostic_used!(E0422);
268 __diagnostic_used!(E0423);
269 __diagnostic_used!(E0425);
270 __diagnostic_used!(E0531);
271 __diagnostic_used!(E0532);
272 __diagnostic_used!(E0573);
273 __diagnostic_used!(E0574);
274 __diagnostic_used!(E0575);
275 __diagnostic_used!(E0576);
276 match (self, has_unexpected_resolution) {
277 (PathSource::Trait(_), true) => "E0404",
278 (PathSource::Trait(_), false) => "E0405",
279 (PathSource::Type, true) => "E0573",
280 (PathSource::Type, false) => "E0412",
281 (PathSource::Struct, true) => "E0574",
282 (PathSource::Struct, false) => "E0422",
283 (PathSource::Expr(..), true) => "E0423",
284 (PathSource::Expr(..), false) => "E0425",
285 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
286 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
287 (PathSource::TraitItem(..), true) => "E0575",
288 (PathSource::TraitItem(..), false) => "E0576",
293 struct LateResolutionVisitor<'a, 'b> {
294 r: &'b mut Resolver<'a>,
296 /// The module that represents the current item scope.
297 parent_scope: ParentScope<'a>,
299 /// The current set of local scopes for types and values.
300 /// FIXME #4948: Reuse ribs to avoid allocation.
301 ribs: PerNS<Vec<Rib<'a>>>,
303 /// The current set of local scopes, for labels.
304 label_ribs: Vec<Rib<'a, NodeId>>,
306 /// The trait that the current context can refer to.
307 current_trait_ref: Option<(Module<'a>, TraitRef)>,
309 /// The current trait's associated types' ident, used for diagnostic suggestions.
310 current_trait_assoc_types: Vec<Ident>,
312 /// The current self type if inside an impl (used for better errors).
313 current_self_type: Option<Ty>,
315 /// The current self item if inside an ADT (used for better errors).
316 current_self_item: Option<NodeId>,
318 /// A list of labels as of yet unused. Labels will be removed from this map when
319 /// they are used (in a `break` or `continue` statement)
320 unused_labels: FxHashMap<NodeId, Span>,
322 /// Only used for better errors on `fn(): fn()`.
323 current_type_ascription: Vec<Span>,
326 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
327 impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
328 fn visit_item(&mut self, item: &'tcx Item) {
329 self.resolve_item(item);
331 fn visit_arm(&mut self, arm: &'tcx Arm) {
332 self.resolve_arm(arm);
334 fn visit_block(&mut self, block: &'tcx Block) {
335 self.resolve_block(block);
337 fn visit_anon_const(&mut self, constant: &'tcx AnonConst) {
338 debug!("visit_anon_const {:?}", constant);
339 self.with_constant_rib(|this| {
340 visit::walk_anon_const(this, constant);
343 fn visit_expr(&mut self, expr: &'tcx Expr) {
344 self.resolve_expr(expr, None);
346 fn visit_local(&mut self, local: &'tcx Local) {
347 self.resolve_local(local);
349 fn visit_ty(&mut self, ty: &'tcx Ty) {
351 TyKind::Path(ref qself, ref path) => {
352 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
354 TyKind::ImplicitSelf => {
355 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
356 let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
357 .map_or(Res::Err, |d| d.res());
358 self.r.record_partial_res(ty.id, PartialRes::new(res));
362 visit::walk_ty(self, ty);
364 fn visit_poly_trait_ref(&mut self,
365 tref: &'tcx PolyTraitRef,
366 m: &'tcx TraitBoundModifier) {
367 self.smart_resolve_path(tref.trait_ref.ref_id, None,
368 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
369 visit::walk_poly_trait_ref(self, tref, m);
371 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
372 let generic_params = match foreign_item.node {
373 ForeignItemKind::Fn(_, ref generics) => {
374 HasGenericParams(generics, ItemRibKind)
376 ForeignItemKind::Static(..) => NoGenericParams,
377 ForeignItemKind::Ty => NoGenericParams,
378 ForeignItemKind::Macro(..) => NoGenericParams,
380 self.with_generic_param_rib(generic_params, |this| {
381 visit::walk_foreign_item(this, foreign_item);
384 fn visit_fn(&mut self,
385 function_kind: FnKind<'tcx>,
386 declaration: &'tcx FnDecl,
390 debug!("(resolving function) entering function");
391 let rib_kind = match function_kind {
392 FnKind::ItemFn(..) => FnItemRibKind,
393 FnKind::Method(..) | FnKind::Closure(_) => NormalRibKind,
396 // Create a value rib for the function.
397 self.ribs[ValueNS].push(Rib::new(rib_kind));
399 // Create a label rib for the function.
400 self.label_ribs.push(Rib::new(rib_kind));
402 // Add each argument to the rib.
403 let mut bindings_list = FxHashMap::default();
404 for argument in &declaration.inputs {
405 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
407 self.visit_ty(&argument.ty);
409 debug!("(resolving function) recorded argument");
411 visit::walk_fn_ret_ty(self, &declaration.output);
413 // Resolve the function body, potentially inside the body of an async closure
414 match function_kind {
415 FnKind::ItemFn(.., body) |
416 FnKind::Method(.., body) => {
417 self.visit_block(body);
419 FnKind::Closure(body) => {
420 self.visit_expr(body);
424 debug!("(resolving function) leaving function");
426 self.label_ribs.pop();
427 self.ribs[ValueNS].pop();
430 fn visit_generics(&mut self, generics: &'tcx Generics) {
431 // For type parameter defaults, we have to ban access
432 // to following type parameters, as the InternalSubsts can only
433 // provide previous type parameters as they're built. We
434 // put all the parameters on the ban list and then remove
435 // them one by one as they are processed and become available.
436 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
437 let mut found_default = false;
438 default_ban_rib.bindings.extend(generics.params.iter()
439 .filter_map(|param| match param.kind {
440 GenericParamKind::Const { .. } |
441 GenericParamKind::Lifetime { .. } => None,
442 GenericParamKind::Type { ref default, .. } => {
443 found_default |= default.is_some();
445 Some((Ident::with_dummy_span(param.ident.name), Res::Err))
452 // We also ban access to type parameters for use as the types of const parameters.
453 let mut const_ty_param_ban_rib = Rib::new(TyParamAsConstParamTy);
454 const_ty_param_ban_rib.bindings.extend(generics.params.iter()
456 if let GenericParamKind::Type { .. } = param.kind {
462 .map(|param| (Ident::with_dummy_span(param.ident.name), Res::Err)));
464 for param in &generics.params {
466 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
467 GenericParamKind::Type { ref default, .. } => {
468 for bound in ¶m.bounds {
469 self.visit_param_bound(bound);
472 if let Some(ref ty) = default {
473 self.ribs[TypeNS].push(default_ban_rib);
475 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
478 // Allow all following defaults to refer to this type parameter.
479 default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
481 GenericParamKind::Const { ref ty } => {
482 self.ribs[TypeNS].push(const_ty_param_ban_rib);
484 for bound in ¶m.bounds {
485 self.visit_param_bound(bound);
490 const_ty_param_ban_rib = self.ribs[TypeNS].pop().unwrap();
494 for p in &generics.where_clause.predicates {
495 self.visit_where_predicate(p);
500 impl<'a, 'b> LateResolutionVisitor<'a, '_> {
501 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b> {
502 // During late resolution we only track the module component of the parent scope,
503 // although it may be useful to track other components as well for diagnostics.
504 let parent_scope = resolver.dummy_parent_scope();
505 let graph_root = resolver.graph_root;
506 LateResolutionVisitor {
510 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
511 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
512 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
514 label_ribs: Vec::new(),
515 current_trait_ref: None,
516 current_trait_assoc_types: Vec::new(),
517 current_self_type: None,
518 current_self_item: None,
519 unused_labels: Default::default(),
520 current_type_ascription: Vec::new(),
524 fn resolve_ident_in_lexical_scope(&mut self,
527 record_used_id: Option<NodeId>,
529 -> Option<LexicalScopeBinding<'a>> {
530 self.r.resolve_ident_in_lexical_scope(
531 ident, ns, &self.parent_scope, record_used_id, path_span, &self.ribs[ns]
538 opt_ns: Option<Namespace>, // `None` indicates a module path in import
541 crate_lint: CrateLint,
542 ) -> PathResult<'a> {
543 self.r.resolve_path_with_ribs(
544 path, opt_ns, &self.parent_scope, record_used, path_span, crate_lint, Some(&self.ribs)
550 // We maintain a list of value ribs and type ribs.
552 // Simultaneously, we keep track of the current position in the module
553 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
554 // the value or type namespaces, we first look through all the ribs and
555 // then query the module graph. When we resolve a name in the module
556 // namespace, we can skip all the ribs (since nested modules are not
557 // allowed within blocks in Rust) and jump straight to the current module
560 // Named implementations are handled separately. When we find a method
561 // call, we consult the module node to find all of the implementations in
562 // scope. This information is lazily cached in the module node. We then
563 // generate a fake "implementation scope" containing all the
564 // implementations thus found, for compatibility with old resolve pass.
566 fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
567 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
569 let id = self.r.definitions.local_def_id(id);
570 let module = self.r.module_map.get(&id).cloned(); // clones a reference
571 if let Some(module) = module {
572 // Move down in the graph.
573 let orig_module = replace(&mut self.parent_scope.module, module);
574 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
575 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
579 self.parent_scope.module = orig_module;
580 self.ribs[ValueNS].pop();
581 self.ribs[TypeNS].pop();
588 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
589 /// is returned by the given predicate function
591 /// Stops after meeting a closure.
592 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
593 where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
595 for rib in self.label_ribs.iter().rev() {
598 // If an invocation of this macro created `ident`, give up on `ident`
599 // and switch to `ident`'s source from the macro definition.
600 MacroDefinition(def) => {
601 if def == self.r.macro_def(ident.span.ctxt()) {
602 ident.span.remove_mark();
606 // Do not resolve labels across function boundary
610 let r = pred(rib, ident);
618 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
619 debug!("resolve_adt");
620 self.with_current_self_item(item, |this| {
621 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
622 let item_def_id = this.r.definitions.local_def_id(item.id);
623 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
624 visit::walk_item(this, item);
630 fn future_proof_import(&mut self, use_tree: &UseTree) {
631 let segments = &use_tree.prefix.segments;
632 if !segments.is_empty() {
633 let ident = segments[0].ident;
634 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
638 let nss = match use_tree.kind {
639 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
642 let report_error = |this: &Self, ns| {
643 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
644 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
648 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
649 Some(LexicalScopeBinding::Res(..)) => {
650 report_error(self, ns);
652 Some(LexicalScopeBinding::Item(binding)) => {
653 let orig_blacklisted_binding =
654 replace(&mut self.r.blacklisted_binding, Some(binding));
655 if let Some(LexicalScopeBinding::Res(..)) =
656 self.resolve_ident_in_lexical_scope(ident, ns, None,
657 use_tree.prefix.span) {
658 report_error(self, ns);
660 self.r.blacklisted_binding = orig_blacklisted_binding;
665 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
666 for (use_tree, _) in use_trees {
667 self.future_proof_import(use_tree);
672 fn resolve_item(&mut self, item: &Item) {
673 let name = item.ident.name;
674 debug!("(resolving item) resolving {} ({:?})", name, item.node);
677 ItemKind::TyAlias(_, ref generics) |
678 ItemKind::OpaqueTy(_, ref generics) |
679 ItemKind::Fn(_, _, ref generics, _) => {
680 self.with_generic_param_rib(
681 HasGenericParams(generics, ItemRibKind),
682 |this| visit::walk_item(this, item)
686 ItemKind::Enum(_, ref generics) |
687 ItemKind::Struct(_, ref generics) |
688 ItemKind::Union(_, ref generics) => {
689 self.resolve_adt(item, generics);
692 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
693 self.resolve_implementation(generics,
699 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
700 // Create a new rib for the trait-wide type parameters.
701 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
702 let local_def_id = this.r.definitions.local_def_id(item.id);
703 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
704 this.visit_generics(generics);
705 walk_list!(this, visit_param_bound, bounds);
707 for trait_item in trait_items {
708 this.with_trait_items(trait_items, |this| {
709 let generic_params = HasGenericParams(
710 &trait_item.generics,
713 this.with_generic_param_rib(generic_params, |this| {
714 match trait_item.node {
715 TraitItemKind::Const(ref ty, ref default) => {
718 // Only impose the restrictions of
719 // ConstRibKind for an actual constant
720 // expression in a provided default.
721 if let Some(ref expr) = *default{
722 this.with_constant_rib(|this| {
723 this.visit_expr(expr);
727 TraitItemKind::Method(_, _) => {
728 visit::walk_trait_item(this, trait_item)
730 TraitItemKind::Type(..) => {
731 visit::walk_trait_item(this, trait_item)
733 TraitItemKind::Macro(_) => {
734 panic!("unexpanded macro in resolve!")
744 ItemKind::TraitAlias(ref generics, ref bounds) => {
745 // Create a new rib for the trait-wide type parameters.
746 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
747 let local_def_id = this.r.definitions.local_def_id(item.id);
748 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
749 this.visit_generics(generics);
750 walk_list!(this, visit_param_bound, bounds);
755 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
756 self.with_scope(item.id, |this| {
757 visit::walk_item(this, item);
761 ItemKind::Static(ref ty, _, ref expr) |
762 ItemKind::Const(ref ty, ref expr) => {
763 debug!("resolve_item ItemKind::Const");
764 self.with_item_rib(|this| {
766 this.with_constant_rib(|this| {
767 this.visit_expr(expr);
772 ItemKind::Use(ref use_tree) => {
773 self.future_proof_import(use_tree);
776 ItemKind::ExternCrate(..) |
777 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
778 // do nothing, these are just around to be encoded
781 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
785 fn with_generic_param_rib<'c, F>(&'c mut self, generic_params: GenericParameters<'a, 'c>, f: F)
786 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
788 debug!("with_generic_param_rib");
789 match generic_params {
790 HasGenericParams(generics, rib_kind) => {
791 let mut function_type_rib = Rib::new(rib_kind);
792 let mut function_value_rib = Rib::new(rib_kind);
793 let mut seen_bindings = FxHashMap::default();
794 for param in &generics.params {
796 GenericParamKind::Lifetime { .. } => {}
797 GenericParamKind::Type { .. } => {
798 let ident = param.ident.modern();
799 debug!("with_generic_param_rib: {}", param.id);
801 if seen_bindings.contains_key(&ident) {
802 let span = seen_bindings.get(&ident).unwrap();
803 let err = ResolutionError::NameAlreadyUsedInParameterList(
807 self.r.report_error(param.ident.span, err);
809 seen_bindings.entry(ident).or_insert(param.ident.span);
811 // Plain insert (no renaming).
814 self.r.definitions.local_def_id(param.id),
816 function_type_rib.bindings.insert(ident, res);
817 self.r.record_partial_res(param.id, PartialRes::new(res));
819 GenericParamKind::Const { .. } => {
820 let ident = param.ident.modern();
821 debug!("with_generic_param_rib: {}", param.id);
823 if seen_bindings.contains_key(&ident) {
824 let span = seen_bindings.get(&ident).unwrap();
825 let err = ResolutionError::NameAlreadyUsedInParameterList(
829 self.r.report_error(param.ident.span, err);
831 seen_bindings.entry(ident).or_insert(param.ident.span);
835 self.r.definitions.local_def_id(param.id),
837 function_value_rib.bindings.insert(ident, res);
838 self.r.record_partial_res(param.id, PartialRes::new(res));
842 self.ribs[ValueNS].push(function_value_rib);
843 self.ribs[TypeNS].push(function_type_rib);
853 if let HasGenericParams(..) = generic_params {
854 self.ribs[TypeNS].pop();
855 self.ribs[ValueNS].pop();
859 fn with_label_rib<F>(&mut self, f: F)
860 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
862 self.label_ribs.push(Rib::new(NormalRibKind));
864 self.label_ribs.pop();
867 fn with_item_rib<F>(&mut self, f: F)
868 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
870 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
871 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
873 self.ribs[TypeNS].pop();
874 self.ribs[ValueNS].pop();
877 fn with_constant_rib<F>(&mut self, f: F)
878 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
880 debug!("with_constant_rib");
881 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
882 self.label_ribs.push(Rib::new(ConstantItemRibKind));
884 self.label_ribs.pop();
885 self.ribs[ValueNS].pop();
888 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
889 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
891 // Handle nested impls (inside fn bodies)
892 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
893 let result = f(self);
894 self.current_self_type = previous_value;
898 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
899 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
901 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
902 let result = f(self);
903 self.current_self_item = previous_value;
907 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
908 fn with_trait_items<T, F>(&mut self, trait_items: &Vec<TraitItem>, f: F) -> T
909 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
911 let trait_assoc_types = replace(
912 &mut self.current_trait_assoc_types,
913 trait_items.iter().filter_map(|item| match &item.node {
914 TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
918 let result = f(self);
919 self.current_trait_assoc_types = trait_assoc_types;
923 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
924 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
925 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>, Option<DefId>) -> T
927 let mut new_val = None;
928 let mut new_id = None;
929 if let Some(trait_ref) = opt_trait_ref {
930 let path: Vec<_> = Segment::from_path(&trait_ref.path);
931 let res = self.smart_resolve_path_fragment(
936 PathSource::Trait(AliasPossibility::No),
937 CrateLint::SimplePath(trait_ref.ref_id),
940 new_id = Some(res.def_id());
941 let span = trait_ref.path.span;
942 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
948 CrateLint::SimplePath(trait_ref.ref_id),
951 new_val = Some((module, trait_ref.clone()));
955 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
956 let result = f(self, new_id);
957 self.current_trait_ref = original_trait_ref;
961 fn with_self_rib<F>(&mut self, self_res: Res, f: F)
962 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
964 let mut self_type_rib = Rib::new(NormalRibKind);
966 // Plain insert (no renaming, since types are not currently hygienic)
967 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
968 self.ribs[TypeNS].push(self_type_rib);
970 self.ribs[TypeNS].pop();
973 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
974 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
976 let self_res = Res::SelfCtor(impl_id);
977 let mut self_type_rib = Rib::new(NormalRibKind);
978 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
979 self.ribs[ValueNS].push(self_type_rib);
981 self.ribs[ValueNS].pop();
984 fn resolve_implementation(&mut self,
986 opt_trait_reference: &Option<TraitRef>,
989 impl_items: &[ImplItem]) {
990 debug!("resolve_implementation");
991 // If applicable, create a rib for the type parameters.
992 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
993 // Dummy self type for better errors if `Self` is used in the trait path.
994 this.with_self_rib(Res::SelfTy(None, None), |this| {
995 // Resolve the trait reference, if necessary.
996 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
997 let item_def_id = this.r.definitions.local_def_id(item_id);
998 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
999 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1000 // Resolve type arguments in the trait path.
1001 visit::walk_trait_ref(this, trait_ref);
1003 // Resolve the self type.
1004 this.visit_ty(self_type);
1005 // Resolve the generic parameters.
1006 this.visit_generics(generics);
1007 // Resolve the items within the impl.
1008 this.with_current_self_type(self_type, |this| {
1009 this.with_self_struct_ctor_rib(item_def_id, |this| {
1010 debug!("resolve_implementation with_self_struct_ctor_rib");
1011 for impl_item in impl_items {
1012 // We also need a new scope for the impl item type parameters.
1013 let generic_params = HasGenericParams(&impl_item.generics,
1015 this.with_generic_param_rib(generic_params, |this| {
1016 use crate::ResolutionError::*;
1017 match impl_item.node {
1018 ImplItemKind::Const(..) => {
1020 "resolve_implementation ImplItemKind::Const",
1022 // If this is a trait impl, ensure the const
1024 this.check_trait_item(
1028 |n, s| ConstNotMemberOfTrait(n, s),
1031 this.with_constant_rib(|this| {
1032 visit::walk_impl_item(this, impl_item)
1035 ImplItemKind::Method(..) => {
1036 // If this is a trait impl, ensure the method
1038 this.check_trait_item(impl_item.ident,
1041 |n, s| MethodNotMemberOfTrait(n, s));
1043 visit::walk_impl_item(this, impl_item);
1045 ImplItemKind::TyAlias(ref ty) => {
1046 // If this is a trait impl, ensure the type
1048 this.check_trait_item(impl_item.ident,
1051 |n, s| TypeNotMemberOfTrait(n, s));
1055 ImplItemKind::OpaqueTy(ref bounds) => {
1056 // If this is a trait impl, ensure the type
1058 this.check_trait_item(impl_item.ident,
1061 |n, s| TypeNotMemberOfTrait(n, s));
1063 for bound in bounds {
1064 this.visit_param_bound(bound);
1067 ImplItemKind::Macro(_) =>
1068 panic!("unexpanded macro in resolve!"),
1080 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1081 where F: FnOnce(Name, &str) -> ResolutionError<'_>
1083 // If there is a TraitRef in scope for an impl, then the method must be in the
1085 if let Some((module, _)) = self.current_trait_ref {
1086 if self.r.resolve_ident_in_module(
1087 ModuleOrUniformRoot::Module(module),
1094 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1095 self.r.report_error(span, err(ident.name, &path_names_to_string(path)));
1100 fn resolve_local(&mut self, local: &Local) {
1101 // Resolve the type.
1102 walk_list!(self, visit_ty, &local.ty);
1104 // Resolve the initializer.
1105 walk_list!(self, visit_expr, &local.init);
1107 // Resolve the pattern.
1108 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
1111 // build a map from pattern identifiers to binding-info's.
1112 // this is done hygienically. This could arise for a macro
1113 // that expands into an or-pattern where one 'x' was from the
1114 // user and one 'x' came from the macro.
1115 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1116 let mut binding_map = FxHashMap::default();
1118 pat.walk(&mut |pat| {
1119 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
1120 if sub_pat.is_some() || match self.r.partial_res_map.get(&pat.id)
1121 .map(|res| res.base_res()) {
1122 Some(Res::Local(..)) => true,
1125 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
1126 binding_map.insert(ident, binding_info);
1135 // Checks that all of the arms in an or-pattern have exactly the
1136 // same set of bindings, with the same binding modes for each.
1137 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
1138 let mut missing_vars = FxHashMap::default();
1139 let mut inconsistent_vars = FxHashMap::default();
1141 for pat_outer in pats.iter() {
1142 let map_outer = self.binding_mode_map(&pat_outer);
1144 for pat_inner in pats.iter().filter(|pat| pat.id != pat_outer.id) {
1145 let map_inner = self.binding_mode_map(&pat_inner);
1147 for (&key_inner, &binding_inner) in map_inner.iter() {
1148 match map_outer.get(&key_inner) {
1149 None => { // missing binding
1150 let binding_error = missing_vars
1151 .entry(key_inner.name)
1152 .or_insert(BindingError {
1153 name: key_inner.name,
1154 origin: BTreeSet::new(),
1155 target: BTreeSet::new(),
1157 key_inner.name.as_str().starts_with(char::is_uppercase)
1159 binding_error.origin.insert(binding_inner.span);
1160 binding_error.target.insert(pat_outer.span);
1162 Some(binding_outer) => { // check consistent binding
1163 if binding_outer.binding_mode != binding_inner.binding_mode {
1165 .entry(key_inner.name)
1166 .or_insert((binding_inner.span, binding_outer.span));
1174 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1175 missing_vars.sort();
1176 for (name, mut v) in missing_vars {
1177 if inconsistent_vars.contains_key(name) {
1178 v.could_be_path = false;
1180 self.r.report_error(
1181 *v.origin.iter().next().unwrap(),
1182 ResolutionError::VariableNotBoundInPattern(v));
1185 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1186 inconsistent_vars.sort();
1187 for (name, v) in inconsistent_vars {
1188 self.r.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1192 fn resolve_arm(&mut self, arm: &Arm) {
1193 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1195 self.resolve_pats(&arm.pats, PatternSource::Match);
1197 if let Some(ref expr) = arm.guard {
1198 self.visit_expr(expr)
1200 self.visit_expr(&arm.body);
1202 self.ribs[ValueNS].pop();
1205 /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
1206 fn resolve_pats(&mut self, pats: &[P<Pat>], source: PatternSource) {
1207 let mut bindings_list = FxHashMap::default();
1209 self.resolve_pattern(pat, source, &mut bindings_list);
1211 // This has to happen *after* we determine which pat_idents are variants
1213 self.check_consistent_bindings(pats);
1217 fn resolve_block(&mut self, block: &Block) {
1218 debug!("(resolving block) entering block");
1219 // Move down in the graph, if there's an anonymous module rooted here.
1220 let orig_module = self.parent_scope.module;
1221 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1223 let mut num_macro_definition_ribs = 0;
1224 if let Some(anonymous_module) = anonymous_module {
1225 debug!("(resolving block) found anonymous module, moving down");
1226 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1227 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1228 self.parent_scope.module = anonymous_module;
1230 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1233 // Descend into the block.
1234 for stmt in &block.stmts {
1235 if let StmtKind::Item(ref item) = stmt.node {
1236 if let ItemKind::MacroDef(..) = item.node {
1237 num_macro_definition_ribs += 1;
1238 let res = self.r.definitions.local_def_id(item.id);
1239 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
1240 self.label_ribs.push(Rib::new(MacroDefinition(res)));
1244 self.visit_stmt(stmt);
1248 self.parent_scope.module = orig_module;
1249 for _ in 0 .. num_macro_definition_ribs {
1250 self.ribs[ValueNS].pop();
1251 self.label_ribs.pop();
1253 self.ribs[ValueNS].pop();
1254 if anonymous_module.is_some() {
1255 self.ribs[TypeNS].pop();
1257 debug!("(resolving block) leaving block");
1260 fn fresh_binding(&mut self,
1263 outer_pat_id: NodeId,
1264 pat_src: PatternSource,
1265 bindings: &mut FxHashMap<Ident, NodeId>)
1267 // Add the binding to the local ribs, if it
1268 // doesn't already exist in the bindings map. (We
1269 // must not add it if it's in the bindings map
1270 // because that breaks the assumptions later
1271 // passes make about or-patterns.)
1272 let ident = ident.modern_and_legacy();
1273 let mut res = Res::Local(pat_id);
1274 match bindings.get(&ident).cloned() {
1275 Some(id) if id == outer_pat_id => {
1276 // `Variant(a, a)`, error
1277 self.r.report_error(
1279 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
1283 Some(..) if pat_src == PatternSource::FnParam => {
1284 // `fn f(a: u8, a: u8)`, error
1285 self.r.report_error(
1287 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
1291 Some(..) if pat_src == PatternSource::Match ||
1292 pat_src == PatternSource::Let => {
1293 // `Variant1(a) | Variant2(a)`, ok
1294 // Reuse definition from the first `a`.
1295 res = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
1298 span_bug!(ident.span, "two bindings with the same name from \
1299 unexpected pattern source {:?}", pat_src);
1302 // A completely fresh binding, add to the lists if it's valid.
1303 if ident.name != kw::Invalid {
1304 bindings.insert(ident, outer_pat_id);
1305 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, res);
1313 fn resolve_pattern(&mut self,
1315 pat_src: PatternSource,
1316 // Maps idents to the node ID for the
1317 // outermost pattern that binds them.
1318 bindings: &mut FxHashMap<Ident, NodeId>) {
1319 // Visit all direct subpatterns of this pattern.
1320 let outer_pat_id = pat.id;
1321 pat.walk(&mut |pat| {
1322 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
1324 PatKind::Ident(bmode, ident, ref opt_pat) => {
1325 // First try to resolve the identifier as some existing
1326 // entity, then fall back to a fresh binding.
1327 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
1329 .and_then(LexicalScopeBinding::item);
1330 let res = binding.map(NameBinding::res).and_then(|res| {
1331 let is_syntactic_ambiguity = opt_pat.is_none() &&
1332 bmode == BindingMode::ByValue(Mutability::Immutable);
1334 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
1335 Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
1336 // Disambiguate in favor of a unit struct/variant
1337 // or constant pattern.
1338 self.r.record_use(ident, ValueNS, binding.unwrap(), false);
1341 Res::Def(DefKind::Ctor(..), _)
1342 | Res::Def(DefKind::Const, _)
1343 | Res::Def(DefKind::Static, _) => {
1344 // This is unambiguously a fresh binding, either syntactically
1345 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1346 // to something unusable as a pattern (e.g., constructor function),
1347 // but we still conservatively report an error, see
1348 // issues/33118#issuecomment-233962221 for one reason why.
1349 self.r.report_error(
1351 ResolutionError::BindingShadowsSomethingUnacceptable(
1352 pat_src.descr(), ident.name, binding.unwrap())
1356 Res::Def(DefKind::Fn, _) | Res::Err => {
1357 // These entities are explicitly allowed
1358 // to be shadowed by fresh bindings.
1362 span_bug!(ident.span, "unexpected resolution for an \
1363 identifier in pattern: {:?}", res);
1366 }).unwrap_or_else(|| {
1367 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
1370 self.r.record_partial_res(pat.id, PartialRes::new(res));
1373 PatKind::TupleStruct(ref path, ..) => {
1374 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1377 PatKind::Path(ref qself, ref path) => {
1378 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1381 PatKind::Struct(ref path, ..) => {
1382 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1390 visit::walk_pat(self, pat);
1393 // High-level and context dependent path resolution routine.
1394 // Resolves the path and records the resolution into definition map.
1395 // If resolution fails tries several techniques to find likely
1396 // resolution candidates, suggest imports or other help, and report
1397 // errors in user friendly way.
1398 fn smart_resolve_path(&mut self,
1400 qself: Option<&QSelf>,
1402 source: PathSource<'_>) {
1403 self.smart_resolve_path_fragment(
1406 &Segment::from_path(path),
1409 CrateLint::SimplePath(id),
1413 fn smart_resolve_path_fragment(&mut self,
1415 qself: Option<&QSelf>,
1418 source: PathSource<'_>,
1419 crate_lint: CrateLint)
1421 let ns = source.namespace();
1422 let is_expected = &|res| source.is_expected(res);
1424 let report_errors = |this: &mut Self, res: Option<Res>| {
1425 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1426 let def_id = this.parent_scope.module.normal_ancestor_id;
1427 let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1428 let better = res.is_some();
1429 this.r.use_injections.push(UseError { err, candidates, node_id, better });
1430 PartialRes::new(Res::Err)
1433 let partial_res = match self.resolve_qpath_anywhere(
1439 source.defer_to_typeck(),
1442 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1443 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1446 // Add a temporary hack to smooth the transition to new struct ctor
1447 // visibility rules. See #38932 for more details.
1449 if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
1450 if let Some((ctor_res, ctor_vis))
1451 = self.r.struct_constructors.get(&def_id).cloned() {
1452 if is_expected(ctor_res) &&
1453 self.r.is_accessible_from(ctor_vis, self.parent_scope.module) {
1454 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
1455 self.r.session.buffer_lint(lint, id, span,
1456 "private struct constructors are not usable through \
1457 re-exports in outer modules",
1459 res = Some(PartialRes::new(ctor_res));
1464 res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
1467 Some(partial_res) if source.defer_to_typeck() => {
1468 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1469 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1470 // it needs to be added to the trait map.
1472 let item_name = path.last().unwrap().ident;
1473 let traits = self.get_traits_containing_item(item_name, ns);
1474 self.r.trait_map.insert(id, traits);
1477 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1478 std_path.extend(path);
1479 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1480 let cl = CrateLint::No;
1482 if let PathResult::Module(_) | PathResult::NonModule(_) =
1483 self.resolve_path(&std_path, ns, false, span, cl) {
1484 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1485 let item_span = path.iter().last().map(|segment| segment.ident.span)
1487 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1488 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1489 hm.insert(item_span, span);
1490 // In some places (E0223) we only have access to the full path
1491 hm.insert(span, span);
1496 _ => report_errors(self, None)
1499 if let PathSource::TraitItem(..) = source {} else {
1500 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1501 self.r.record_partial_res(id, partial_res);
1506 fn self_type_is_available(&mut self, span: Span) -> bool {
1507 let binding = self.resolve_ident_in_lexical_scope(
1508 Ident::with_dummy_span(kw::SelfUpper),
1513 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1516 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1517 let ident = Ident::new(kw::SelfLower, self_span);
1518 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1519 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1522 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1523 fn resolve_qpath_anywhere(
1526 qself: Option<&QSelf>,
1528 primary_ns: Namespace,
1530 defer_to_typeck: bool,
1531 crate_lint: CrateLint,
1532 ) -> Option<PartialRes> {
1533 let mut fin_res = None;
1534 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1535 if i == 0 || ns != primary_ns {
1536 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1537 // If defer_to_typeck, then resolution > no resolution,
1538 // otherwise full resolution > partial resolution > no resolution.
1539 Some(partial_res) if partial_res.unresolved_segments() == 0 ||
1541 return Some(partial_res),
1542 partial_res => if fin_res.is_none() { fin_res = partial_res },
1548 assert!(primary_ns != MacroNS);
1549 if qself.is_none() {
1550 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1551 let path = Path { segments: path.iter().map(path_seg).collect(), span };
1552 if let Ok((_, res)) = self.r.resolve_macro_path(
1553 &path, None, &self.parent_scope, false, false
1555 return Some(PartialRes::new(res));
1562 /// Handles paths that may refer to associated items.
1566 qself: Option<&QSelf>,
1570 crate_lint: CrateLint,
1571 ) -> Option<PartialRes> {
1573 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1581 if let Some(qself) = qself {
1582 if qself.position == 0 {
1583 // This is a case like `<T>::B`, where there is no
1584 // trait to resolve. In that case, we leave the `B`
1585 // segment to be resolved by type-check.
1586 return Some(PartialRes::with_unresolved_segments(
1587 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
1591 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1593 // Currently, `path` names the full item (`A::B::C`, in
1594 // our example). so we extract the prefix of that that is
1595 // the trait (the slice upto and including
1596 // `qself.position`). And then we recursively resolve that,
1597 // but with `qself` set to `None`.
1599 // However, setting `qself` to none (but not changing the
1600 // span) loses the information about where this path
1601 // *actually* appears, so for the purposes of the crate
1602 // lint we pass along information that this is the trait
1603 // name from a fully qualified path, and this also
1604 // contains the full span (the `CrateLint::QPathTrait`).
1605 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1606 let partial_res = self.smart_resolve_path_fragment(
1609 &path[..=qself.position],
1611 PathSource::TraitItem(ns),
1612 CrateLint::QPathTrait {
1614 qpath_span: qself.path_span,
1618 // The remaining segments (the `C` in our example) will
1619 // have to be resolved by type-check, since that requires doing
1620 // trait resolution.
1621 return Some(PartialRes::with_unresolved_segments(
1622 partial_res.base_res(),
1623 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1627 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1628 PathResult::NonModule(path_res) => path_res,
1629 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1630 PartialRes::new(module.res().unwrap())
1632 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1633 // don't report an error right away, but try to fallback to a primitive type.
1634 // So, we are still able to successfully resolve something like
1636 // use std::u8; // bring module u8 in scope
1637 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1638 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
1639 // // not to non-existent std::u8::max_value
1642 // Such behavior is required for backward compatibility.
1643 // The same fallback is used when `a` resolves to nothing.
1644 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
1645 PathResult::Failed { .. }
1646 if (ns == TypeNS || path.len() > 1) &&
1647 self.r.primitive_type_table.primitive_types
1648 .contains_key(&path[0].ident.name) => {
1649 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1650 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1652 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1653 PartialRes::new(module.res().unwrap()),
1654 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1655 self.r.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
1656 PartialRes::new(Res::Err)
1658 PathResult::Module(..) | PathResult::Failed { .. } => return None,
1659 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1662 if path.len() > 1 && result.base_res() != Res::Err &&
1663 path[0].ident.name != kw::PathRoot &&
1664 path[0].ident.name != kw::DollarCrate {
1665 let unqualified_result = {
1666 match self.resolve_path(
1667 &[*path.last().unwrap()],
1673 PathResult::NonModule(path_res) => path_res.base_res(),
1674 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1675 module.res().unwrap(),
1676 _ => return Some(result),
1679 if result.base_res() == unqualified_result {
1680 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1681 self.r.session.buffer_lint(lint, id, span, "unnecessary qualification")
1688 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
1689 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
1691 if let Some(label) = label {
1692 self.unused_labels.insert(id, label.ident.span);
1693 self.with_label_rib(|this| {
1694 let ident = label.ident.modern_and_legacy();
1695 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1703 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
1704 self.with_resolved_label(label, id, |this| this.visit_block(block));
1707 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
1708 // First, record candidate traits for this expression if it could
1709 // result in the invocation of a method call.
1711 self.record_candidate_traits_for_expr_if_necessary(expr);
1713 // Next, resolve the node.
1715 ExprKind::Path(ref qself, ref path) => {
1716 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1717 visit::walk_expr(self, expr);
1720 ExprKind::Struct(ref path, ..) => {
1721 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1722 visit::walk_expr(self, expr);
1725 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1726 let node_id = self.search_label(label.ident, |rib, ident| {
1727 rib.bindings.get(&ident.modern_and_legacy()).cloned()
1731 // Search again for close matches...
1732 // Picks the first label that is "close enough", which is not necessarily
1733 // the closest match
1734 let close_match = self.search_label(label.ident, |rib, ident| {
1735 let names = rib.bindings.iter().filter_map(|(id, _)| {
1736 if id.span.ctxt() == label.ident.span.ctxt() {
1742 find_best_match_for_name(names, &*ident.as_str(), None)
1744 self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1745 self.r.report_error(
1747 ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
1751 // Since this res is a label, it is never read.
1752 self.r.label_res_map.insert(expr.id, node_id);
1753 self.unused_labels.remove(&node_id);
1757 // visit `break` argument if any
1758 visit::walk_expr(self, expr);
1761 ExprKind::Let(ref pats, ref scrutinee) => {
1762 self.visit_expr(scrutinee);
1763 self.resolve_pats(pats, PatternSource::Let);
1766 ExprKind::If(ref cond, ref then, ref opt_else) => {
1767 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1768 self.visit_expr(cond);
1769 self.visit_block(then);
1770 self.ribs[ValueNS].pop();
1772 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1775 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1777 ExprKind::While(ref subexpression, ref block, label) => {
1778 self.with_resolved_label(label, expr.id, |this| {
1779 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
1780 this.visit_expr(subexpression);
1781 this.visit_block(block);
1782 this.ribs[ValueNS].pop();
1786 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
1787 self.visit_expr(subexpression);
1788 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1789 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
1791 self.resolve_labeled_block(label, expr.id, block);
1793 self.ribs[ValueNS].pop();
1796 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1798 // Equivalent to `visit::walk_expr` + passing some context to children.
1799 ExprKind::Field(ref subexpression, _) => {
1800 self.resolve_expr(subexpression, Some(expr));
1802 ExprKind::MethodCall(ref segment, ref arguments) => {
1803 let mut arguments = arguments.iter();
1804 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1805 for argument in arguments {
1806 self.resolve_expr(argument, None);
1808 self.visit_path_segment(expr.span, segment);
1811 ExprKind::Call(ref callee, ref arguments) => {
1812 self.resolve_expr(callee, Some(expr));
1813 for argument in arguments {
1814 self.resolve_expr(argument, None);
1817 ExprKind::Type(ref type_expr, _) => {
1818 self.current_type_ascription.push(type_expr.span);
1819 visit::walk_expr(self, expr);
1820 self.current_type_ascription.pop();
1822 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
1823 // resolve the arguments within the proper scopes so that usages of them inside the
1824 // closure are detected as upvars rather than normal closure arg usages.
1826 _, IsAsync::Async { .. }, _,
1827 ref fn_decl, ref body, _span,
1829 let rib_kind = NormalRibKind;
1830 self.ribs[ValueNS].push(Rib::new(rib_kind));
1831 // Resolve arguments:
1832 let mut bindings_list = FxHashMap::default();
1833 for argument in &fn_decl.inputs {
1834 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
1835 self.visit_ty(&argument.ty);
1837 // No need to resolve return type-- the outer closure return type is
1838 // FunctionRetTy::Default
1840 // Now resolve the inner closure
1842 // No need to resolve arguments: the inner closure has none.
1843 // Resolve the return type:
1844 visit::walk_fn_ret_ty(self, &fn_decl.output);
1846 self.visit_expr(body);
1848 self.ribs[ValueNS].pop();
1851 visit::walk_expr(self, expr);
1856 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
1858 ExprKind::Field(_, ident) => {
1859 // FIXME(#6890): Even though you can't treat a method like a
1860 // field, we need to add any trait methods we find that match
1861 // the field name so that we can do some nice error reporting
1862 // later on in typeck.
1863 let traits = self.get_traits_containing_item(ident, ValueNS);
1864 self.r.trait_map.insert(expr.id, traits);
1866 ExprKind::MethodCall(ref segment, ..) => {
1867 debug!("(recording candidate traits for expr) recording traits for {}",
1869 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
1870 self.r.trait_map.insert(expr.id, traits);
1878 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
1879 -> Vec<TraitCandidate> {
1880 debug!("(getting traits containing item) looking for '{}'", ident.name);
1882 let mut found_traits = Vec::new();
1883 // Look for the current trait.
1884 if let Some((module, _)) = self.current_trait_ref {
1885 if self.r.resolve_ident_in_module(
1886 ModuleOrUniformRoot::Module(module),
1893 let def_id = module.def_id().unwrap();
1894 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
1898 ident.span = ident.span.modern();
1899 let mut search_module = self.parent_scope.module;
1901 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
1902 search_module = unwrap_or!(
1903 self.r.hygienic_lexical_parent(search_module, &mut ident.span), break
1907 if let Some(prelude) = self.r.prelude {
1908 if !search_module.no_implicit_prelude {
1909 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
1916 fn get_traits_in_module_containing_item(&mut self,
1920 found_traits: &mut Vec<TraitCandidate>) {
1921 assert!(ns == TypeNS || ns == ValueNS);
1922 let mut traits = module.traits.borrow_mut();
1923 if traits.is_none() {
1924 let mut collected_traits = Vec::new();
1925 module.for_each_child(|name, ns, binding| {
1926 if ns != TypeNS { return }
1927 match binding.res() {
1928 Res::Def(DefKind::Trait, _) |
1929 Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
1933 *traits = Some(collected_traits.into_boxed_slice());
1936 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
1937 // Traits have pseudo-modules that can be used to search for the given ident.
1938 if let Some(module) = binding.module() {
1939 let mut ident = ident;
1940 if ident.span.glob_adjust(
1946 if self.r.resolve_ident_in_module_unadjusted(
1947 ModuleOrUniformRoot::Module(module),
1954 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1955 let trait_def_id = module.def_id().unwrap();
1956 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1958 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
1959 // For now, just treat all trait aliases as possible candidates, since we don't
1960 // know if the ident is somewhere in the transitive bounds.
1961 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1962 let trait_def_id = binding.res().def_id();
1963 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1965 bug!("candidate is not trait or trait alias?")
1970 fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
1971 trait_name: Ident) -> SmallVec<[NodeId; 1]> {
1972 let mut import_ids = smallvec![];
1973 while let NameBindingKind::Import { directive, binding, .. } = kind {
1974 self.r.maybe_unused_trait_imports.insert(directive.id);
1975 self.r.add_to_glob_map(&directive, trait_name);
1976 import_ids.push(directive.id);
1977 kind = &binding.kind;
1983 impl<'a> Resolver<'a> {
1984 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
1985 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
1986 visit::walk_crate(&mut late_resolution_visitor, krate);
1987 for (id, span) in late_resolution_visitor.unused_labels.iter() {
1988 self.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");