1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
18 #![cfg_attr(not(stage0), deny(warnings))]
20 #![feature(associated_consts)]
21 #![feature(borrow_state)]
22 #![feature(rustc_diagnostic_macros)]
23 #![feature(rustc_private)]
24 #![feature(staged_api)]
33 extern crate rustc_bitflags;
34 extern crate rustc_front;
37 use self::PatternBindingMode::*;
38 use self::Namespace::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::BareIdentifierPatternResolution::*;
47 use self::ParentLink::*;
48 use self::FallbackChecks::*;
50 use rustc::dep_graph::DepNode;
51 use rustc::front::map as hir_map;
52 use rustc::session::Session;
54 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
55 use rustc::middle::def::*;
56 use rustc::middle::def_id::DefId;
57 use rustc::middle::pat_util::pat_bindings;
58 use rustc::middle::privacy::*;
59 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
60 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
61 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
63 use syntax::ast::{self, FloatTy};
64 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
65 use syntax::attr::AttrMetaMethods;
66 use syntax::codemap::{self, Span, Pos};
67 use syntax::errors::DiagnosticBuilder;
68 use syntax::parse::token::{self, special_names, special_idents};
69 use syntax::util::lev_distance::find_best_match_for_name;
71 use rustc_front::intravisit::{self, FnKind, Visitor};
73 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
74 use rustc_front::hir::Crate;
75 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
76 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
77 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
78 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
79 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
80 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
81 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
82 use rustc_front::hir::Local;
83 use rustc_front::hir::{Pat, PatKind, Path, PrimTy};
84 use rustc_front::hir::{PathSegment, PathParameters};
85 use rustc_front::hir::HirVec;
86 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
87 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
88 use rustc_front::util::walk_pat;
90 use std::collections::{HashMap, HashSet};
91 use std::cell::{Cell, RefCell};
93 use std::mem::replace;
95 use resolve_imports::{ImportDirective, NameResolution};
97 // NB: This module needs to be declared first so diagnostics are
98 // registered before they are used.
102 mod build_reduced_graph;
105 // Perform the callback, not walking deeper if the return is true
106 macro_rules! execute_callback {
107 ($node: expr, $walker: expr) => (
108 if let Some(ref callback) = $walker.callback {
109 if callback($node, &mut $walker.resolved) {
116 enum SuggestionType {
118 Function(token::InternedString),
122 /// Candidates for a name resolution failure
123 pub struct SuggestedCandidates {
125 candidates: Vec<Path>,
128 pub enum ResolutionError<'a> {
129 /// error E0401: can't use type parameters from outer function
130 TypeParametersFromOuterFunction,
131 /// error E0402: cannot use an outer type parameter in this context
132 OuterTypeParameterContext,
133 /// error E0403: the name is already used for a type parameter in this type parameter list
134 NameAlreadyUsedInTypeParameterList(Name),
135 /// error E0404: is not a trait
136 IsNotATrait(&'a str),
137 /// error E0405: use of undeclared trait name
138 UndeclaredTraitName(&'a str, SuggestedCandidates),
139 /// error E0406: undeclared associated type
140 UndeclaredAssociatedType,
141 /// error E0407: method is not a member of trait
142 MethodNotMemberOfTrait(Name, &'a str),
143 /// error E0437: type is not a member of trait
144 TypeNotMemberOfTrait(Name, &'a str),
145 /// error E0438: const is not a member of trait
146 ConstNotMemberOfTrait(Name, &'a str),
147 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
148 VariableNotBoundInPattern(Name, usize),
149 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
150 VariableBoundWithDifferentMode(Name, usize),
151 /// error E0410: variable from pattern is not bound in pattern #1
152 VariableNotBoundInParentPattern(Name, usize),
153 /// error E0411: use of `Self` outside of an impl or trait
154 SelfUsedOutsideImplOrTrait,
155 /// error E0412: use of undeclared
156 UseOfUndeclared(&'a str, &'a str, SuggestedCandidates),
157 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
158 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
159 /// error E0414: only irrefutable patterns allowed here
160 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
161 /// error E0415: identifier is bound more than once in this parameter list
162 IdentifierBoundMoreThanOnceInParameterList(&'a str),
163 /// error E0416: identifier is bound more than once in the same pattern
164 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
165 /// error E0417: static variables cannot be referenced in a pattern
166 StaticVariableReference,
167 /// error E0418: is not an enum variant, struct or const
168 NotAnEnumVariantStructOrConst(&'a str),
169 /// error E0419: unresolved enum variant, struct or const
170 UnresolvedEnumVariantStructOrConst(&'a str),
171 /// error E0420: is not an associated const
172 NotAnAssociatedConst(&'a str),
173 /// error E0421: unresolved associated const
174 UnresolvedAssociatedConst(&'a str),
175 /// error E0422: does not name a struct
176 DoesNotNameAStruct(&'a str),
177 /// error E0423: is a struct variant name, but this expression uses it like a function name
178 StructVariantUsedAsFunction(&'a str),
179 /// error E0424: `self` is not available in a static method
180 SelfNotAvailableInStaticMethod,
181 /// error E0425: unresolved name
182 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
183 /// error E0426: use of undeclared label
184 UndeclaredLabel(&'a str),
185 /// error E0427: cannot use `ref` binding mode with ...
186 CannotUseRefBindingModeWith(&'a str),
187 /// error E0428: duplicate definition
188 DuplicateDefinition(&'a str, Name),
189 /// error E0429: `self` imports are only allowed within a { } list
190 SelfImportsOnlyAllowedWithin,
191 /// error E0430: `self` import can only appear once in the list
192 SelfImportCanOnlyAppearOnceInTheList,
193 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
194 SelfImportOnlyInImportListWithNonEmptyPrefix,
195 /// error E0432: unresolved import
196 UnresolvedImport(Option<(&'a str, &'a str)>),
197 /// error E0433: failed to resolve
198 FailedToResolve(&'a str),
199 /// error E0434: can't capture dynamic environment in a fn item
200 CannotCaptureDynamicEnvironmentInFnItem,
201 /// error E0435: attempt to use a non-constant value in a constant
202 AttemptToUseNonConstantValueInConstant,
205 /// Context of where `ResolutionError::UnresolvedName` arose.
206 #[derive(Clone, PartialEq, Eq, Debug)]
207 pub enum UnresolvedNameContext {
208 /// `PathIsMod(id)` indicates that a given path, used in
209 /// expression context, actually resolved to a module rather than
210 /// a value. The `id` attached to the variant is the node id of
211 /// the erroneous path expression.
212 PathIsMod(ast::NodeId),
214 /// `Other` means we have no extra information about the context
215 /// of the unresolved name error. (Maybe we could eliminate all
216 /// such cases; but for now, this is an information-free default.)
220 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
221 span: syntax::codemap::Span,
222 resolution_error: ResolutionError<'b>) {
223 resolve_struct_error(resolver, span, resolution_error).emit();
226 fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
227 span: syntax::codemap::Span,
228 resolution_error: ResolutionError<'b>)
229 -> DiagnosticBuilder<'a> {
230 if !resolver.emit_errors {
231 return resolver.session.diagnostic().struct_dummy();
234 match resolution_error {
235 ResolutionError::TypeParametersFromOuterFunction => {
236 struct_span_err!(resolver.session,
239 "can't use type parameters from outer function; try using a local \
240 type parameter instead")
242 ResolutionError::OuterTypeParameterContext => {
243 struct_span_err!(resolver.session,
246 "cannot use an outer type parameter in this context")
248 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
249 struct_span_err!(resolver.session,
252 "the name `{}` is already used for a type parameter in this type \
256 ResolutionError::IsNotATrait(name) => {
257 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
259 ResolutionError::UndeclaredTraitName(name, candidates) => {
260 let mut err = struct_span_err!(resolver.session,
263 "trait `{}` is not in scope",
265 show_candidates(&mut err, span, &candidates);
268 ResolutionError::UndeclaredAssociatedType => {
269 struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
271 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
272 struct_span_err!(resolver.session,
275 "method `{}` is not a member of trait `{}`",
279 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
280 struct_span_err!(resolver.session,
283 "type `{}` is not a member of trait `{}`",
287 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
288 struct_span_err!(resolver.session,
291 "const `{}` is not a member of trait `{}`",
295 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
296 struct_span_err!(resolver.session,
299 "variable `{}` from pattern #1 is not bound in pattern #{}",
303 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
304 struct_span_err!(resolver.session,
307 "variable `{}` is bound with different mode in pattern #{} than in \
312 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
313 struct_span_err!(resolver.session,
316 "variable `{}` from pattern #{} is not bound in pattern #1",
320 ResolutionError::SelfUsedOutsideImplOrTrait => {
321 struct_span_err!(resolver.session,
324 "use of `Self` outside of an impl or trait")
326 ResolutionError::UseOfUndeclared(kind, name, candidates) => {
327 let mut err = struct_span_err!(resolver.session,
330 "{} `{}` is undefined or not in scope",
333 show_candidates(&mut err, span, &candidates);
336 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
337 struct_span_err!(resolver.session,
340 "declaration of `{}` shadows an enum variant \
341 or unit-like struct in scope",
344 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
345 let mut err = struct_span_err!(resolver.session,
348 "only irrefutable patterns allowed here");
350 "there already is a constant in scope sharing the same \
351 name as this pattern");
352 if let Some(sp) = resolver.ast_map.span_if_local(did) {
353 err.span_note(sp, "constant defined here");
355 if let Success(binding) = resolver.current_module.resolve_name(name, ValueNS, true) {
356 if binding.is_import() {
357 err.span_note(binding.span.unwrap(), "constant imported here");
362 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
363 struct_span_err!(resolver.session,
366 "identifier `{}` is bound more than once in this parameter list",
369 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
370 struct_span_err!(resolver.session,
373 "identifier `{}` is bound more than once in the same pattern",
376 ResolutionError::StaticVariableReference => {
377 struct_span_err!(resolver.session,
380 "static variables cannot be referenced in a pattern, use a \
383 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
384 struct_span_err!(resolver.session,
387 "`{}` is not an enum variant, struct or const",
390 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
391 struct_span_err!(resolver.session,
394 "unresolved enum variant, struct or const `{}`",
397 ResolutionError::NotAnAssociatedConst(name) => {
398 struct_span_err!(resolver.session,
401 "`{}` is not an associated const",
404 ResolutionError::UnresolvedAssociatedConst(name) => {
405 struct_span_err!(resolver.session,
408 "unresolved associated const `{}`",
411 ResolutionError::DoesNotNameAStruct(name) => {
412 struct_span_err!(resolver.session,
415 "`{}` does not name a structure",
418 ResolutionError::StructVariantUsedAsFunction(path_name) => {
419 struct_span_err!(resolver.session,
422 "`{}` is the name of a struct or struct variant, but this expression \
423 uses it like a function name",
426 ResolutionError::SelfNotAvailableInStaticMethod => {
427 struct_span_err!(resolver.session,
430 "`self` is not available in a static method. Maybe a `self` \
431 argument is missing?")
433 ResolutionError::UnresolvedName(path, msg, context) => {
434 let mut err = struct_span_err!(resolver.session,
437 "unresolved name `{}`{}",
442 UnresolvedNameContext::Other => { } // no help available
443 UnresolvedNameContext::PathIsMod(id) => {
444 let mut help_msg = String::new();
445 let parent_id = resolver.ast_map.get_parent_node(id);
446 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
448 ExprField(_, ident) => {
449 help_msg = format!("To reference an item from the \
450 `{module}` module, use \
451 `{module}::{ident}`",
455 ExprMethodCall(ident, _, _) => {
456 help_msg = format!("To call a function from the \
457 `{module}` module, use \
458 `{module}::{ident}(..)`",
463 help_msg = format!("No function corresponds to `{module}(..)`",
466 _ => { } // no help available
469 help_msg = format!("Module `{module}` cannot be the value of an expression",
473 if !help_msg.is_empty() {
474 err.fileline_help(span, &help_msg);
480 ResolutionError::UndeclaredLabel(name) => {
481 struct_span_err!(resolver.session,
484 "use of undeclared label `{}`",
487 ResolutionError::CannotUseRefBindingModeWith(descr) => {
488 struct_span_err!(resolver.session,
491 "cannot use `ref` binding mode with {}",
494 ResolutionError::DuplicateDefinition(namespace, name) => {
495 struct_span_err!(resolver.session,
498 "duplicate definition of {} `{}`",
502 ResolutionError::SelfImportsOnlyAllowedWithin => {
503 struct_span_err!(resolver.session,
507 "`self` imports are only allowed within a { } list")
509 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
510 struct_span_err!(resolver.session,
513 "`self` import can only appear once in the list")
515 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
516 struct_span_err!(resolver.session,
519 "`self` import can only appear in an import list with a \
522 ResolutionError::UnresolvedImport(name) => {
523 let msg = match name {
524 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
525 None => "unresolved import".to_owned(),
527 struct_span_err!(resolver.session, span, E0432, "{}", msg)
529 ResolutionError::FailedToResolve(msg) => {
530 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
532 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
533 struct_span_err!(resolver.session,
537 "can't capture dynamic environment in a fn item; use the || { ... } \
538 closure form instead")
540 ResolutionError::AttemptToUseNonConstantValueInConstant => {
541 struct_span_err!(resolver.session,
544 "attempt to use a non-constant value in a constant")
549 #[derive(Copy, Clone)]
552 binding_mode: BindingMode,
555 // Map from the name in a pattern to its binding mode.
556 type BindingMap = HashMap<Name, BindingInfo>;
558 #[derive(Copy, Clone, PartialEq)]
559 enum PatternBindingMode {
561 LocalIrrefutableMode,
562 ArgumentIrrefutableMode,
565 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
571 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
572 fn visit_nested_item(&mut self, item: hir::ItemId) {
573 self.visit_item(self.ast_map.expect_item(item.id))
575 fn visit_item(&mut self, item: &Item) {
576 execute_callback!(hir_map::Node::NodeItem(item), self);
577 self.resolve_item(item);
579 fn visit_arm(&mut self, arm: &Arm) {
580 self.resolve_arm(arm);
582 fn visit_block(&mut self, block: &Block) {
583 execute_callback!(hir_map::Node::NodeBlock(block), self);
584 self.resolve_block(block);
586 fn visit_expr(&mut self, expr: &Expr) {
587 execute_callback!(hir_map::Node::NodeExpr(expr), self);
588 self.resolve_expr(expr);
590 fn visit_local(&mut self, local: &Local) {
591 execute_callback!(hir_map::Node::NodeLocal(&local.pat), self);
592 self.resolve_local(local);
594 fn visit_ty(&mut self, ty: &Ty) {
595 self.resolve_type(ty);
597 fn visit_generics(&mut self, generics: &Generics) {
598 self.resolve_generics(generics);
600 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
601 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
602 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
604 // error already reported
605 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
608 intravisit::walk_poly_trait_ref(self, tref, m);
610 fn visit_variant(&mut self,
611 variant: &hir::Variant,
613 item_id: ast::NodeId) {
614 execute_callback!(hir_map::Node::NodeVariant(variant), self);
615 if let Some(ref dis_expr) = variant.node.disr_expr {
616 // resolve the discriminator expr as a constant
617 self.with_constant_rib(|this| {
618 this.visit_expr(dis_expr);
622 // `intravisit::walk_variant` without the discriminant expression.
623 self.visit_variant_data(&variant.node.data,
629 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
630 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
631 let type_parameters = match foreign_item.node {
632 ForeignItemFn(_, ref generics) => {
633 HasTypeParameters(generics, FnSpace, ItemRibKind)
635 ForeignItemStatic(..) => NoTypeParameters,
637 self.with_type_parameter_rib(type_parameters, |this| {
638 intravisit::walk_foreign_item(this, foreign_item);
641 fn visit_fn(&mut self,
642 function_kind: FnKind<'v>,
643 declaration: &'v FnDecl,
647 let rib_kind = match function_kind {
648 FnKind::ItemFn(_, generics, _, _, _, _) => {
649 self.visit_generics(generics);
652 FnKind::Method(_, sig, _) => {
653 self.visit_generics(&sig.generics);
654 self.visit_explicit_self(&sig.explicit_self);
657 FnKind::Closure => ClosureRibKind(node_id),
659 self.resolve_function(rib_kind, declaration, block);
663 pub type ErrorMessage = Option<(Span, String)>;
665 #[derive(Clone, PartialEq, Eq)]
666 pub enum ResolveResult<T> {
667 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
668 Indeterminate, // Couldn't determine due to unresolved globs.
669 Success(T), // Successfully resolved the import.
672 impl<T> ResolveResult<T> {
673 fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
675 Failed(msg) => Failed(msg),
676 Indeterminate => Indeterminate,
681 fn success(self) -> Option<T> {
683 Success(t) => Some(t),
689 enum FallbackSuggestion {
694 StaticMethod(String),
698 #[derive(Copy, Clone)]
699 enum TypeParameters<'tcx, 'a> {
701 HasTypeParameters(// Type parameters.
704 // Identifies the things that these parameters
705 // were declared on (type, fn, etc)
708 // The kind of the rib used for type parameters.
712 // The rib kind controls the translation of local
713 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
714 #[derive(Copy, Clone, Debug)]
716 // No translation needs to be applied.
719 // We passed through a closure scope at the given node ID.
720 // Translate upvars as appropriate.
721 ClosureRibKind(NodeId /* func id */),
723 // We passed through an impl or trait and are now in one of its
724 // methods. Allow references to ty params that impl or trait
725 // binds. Disallow any other upvars (including other ty params that are
729 // We passed through an item scope. Disallow upvars.
732 // We're in a constant item. Can't refer to dynamic stuff.
735 // We passed through an anonymous module.
736 AnonymousModuleRibKind(Module<'a>),
739 #[derive(Copy, Clone)]
740 enum UseLexicalScopeFlag {
745 enum ModulePrefixResult<'a> {
747 PrefixFound(Module<'a>, usize),
750 #[derive(Copy, Clone)]
751 enum AssocItemResolveResult {
752 /// Syntax such as `<T>::item`, which can't be resolved until type
755 /// We should have been able to resolve the associated item.
756 ResolveAttempt(Option<PathResolution>),
759 #[derive(Copy, Clone)]
760 enum BareIdentifierPatternResolution {
761 FoundStructOrEnumVariant(Def, LastPrivate),
762 FoundConst(Def, LastPrivate, Name),
763 BareIdentifierPatternUnresolved,
769 bindings: HashMap<Name, DefLike>,
774 fn new(kind: RibKind<'a>) -> Rib<'a> {
776 bindings: HashMap::new(),
782 /// A definition along with the index of the rib it was found on
784 ribs: Option<(Namespace, usize)>,
789 fn from_def(def: Def) -> Self {
797 /// The link from a module up to its nearest parent node.
798 #[derive(Clone,Debug)]
799 enum ParentLink<'a> {
801 ModuleParentLink(Module<'a>, Name),
802 BlockParentLink(Module<'a>, NodeId),
805 /// One node in the tree of modules.
806 pub struct ModuleS<'a> {
807 parent_link: ParentLink<'a>,
810 is_extern_crate: bool,
812 resolutions: RefCell<HashMap<(Name, Namespace), NameResolution<'a>>>,
813 imports: RefCell<Vec<ImportDirective>>,
815 // The module children of this node, including normal modules and anonymous modules.
816 // Anonymous children are pseudo-modules that are implicitly created around items
817 // contained within blocks.
819 // For example, if we have this:
827 // There will be an anonymous module created around `g` with the ID of the
828 // entry block for `f`.
829 module_children: RefCell<NodeMap<Module<'a>>>,
831 shadowed_traits: RefCell<Vec<&'a NameBinding<'a>>>,
833 // The number of unresolved globs that this module exports.
834 glob_count: Cell<usize>,
836 // The number of unresolved pub imports (both regular and globs) in this module
837 pub_count: Cell<usize>,
839 // The number of unresolved pub glob imports in this module
840 pub_glob_count: Cell<usize>,
842 // The index of the import we're resolving.
843 resolved_import_count: Cell<usize>,
845 // Whether this module is populated. If not populated, any attempt to
846 // access the children must be preceded with a
847 // `populate_module_if_necessary` call.
848 populated: Cell<bool>,
851 pub type Module<'a> = &'a ModuleS<'a>;
853 impl<'a> ModuleS<'a> {
855 fn new(parent_link: ParentLink<'a>, def: Option<Def>, external: bool, is_public: bool) -> Self {
857 parent_link: parent_link,
859 is_public: is_public,
860 is_extern_crate: false,
861 resolutions: RefCell::new(HashMap::new()),
862 imports: RefCell::new(Vec::new()),
863 module_children: RefCell::new(NodeMap()),
864 shadowed_traits: RefCell::new(Vec::new()),
865 glob_count: Cell::new(0),
866 pub_count: Cell::new(0),
867 pub_glob_count: Cell::new(0),
868 resolved_import_count: Cell::new(0),
869 populated: Cell::new(!external),
873 fn resolve_name(&self, name: Name, ns: Namespace, allow_private_imports: bool)
874 -> ResolveResult<&'a NameBinding<'a>> {
876 if allow_private_imports { self.glob_count.get() } else { self.pub_glob_count.get() };
878 self.resolutions.borrow().get(&(name, ns)).cloned().unwrap_or_default().result(glob_count)
879 .and_then(|binding| {
880 let allowed = allow_private_imports || !binding.is_import() || binding.is_public();
881 if allowed { Success(binding) } else { Failed(None) }
885 // Define the name or return the existing binding if there is a collision.
886 fn try_define_child(&self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>)
887 -> Result<(), &'a NameBinding<'a>> {
888 let mut children = self.resolutions.borrow_mut();
889 let resolution = children.entry((name, ns)).or_insert_with(Default::default);
891 // FIXME #31379: We can use methods from imported traits shadowed by non-import items
892 if let Some(old_binding) = resolution.binding {
893 if !old_binding.is_import() && binding.is_import() {
894 if let Some(Def::Trait(_)) = binding.def() {
895 self.shadowed_traits.borrow_mut().push(binding);
900 resolution.try_define(binding)
903 fn increment_outstanding_references_for(&self, name: Name, ns: Namespace) {
904 let mut children = self.resolutions.borrow_mut();
905 children.entry((name, ns)).or_insert_with(Default::default).outstanding_references += 1;
908 fn decrement_outstanding_references_for(&self, name: Name, ns: Namespace) {
909 match self.resolutions.borrow_mut().get_mut(&(name, ns)).unwrap().outstanding_references {
910 0 => panic!("No more outstanding references!"),
911 ref mut outstanding_references => { *outstanding_references -= 1; }
915 fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
916 for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
917 name_resolution.binding.map(|binding| f(name, ns, binding));
921 fn def_id(&self) -> Option<DefId> {
922 self.def.as_ref().map(Def::def_id)
925 fn is_normal(&self) -> bool {
927 Some(Def::Mod(_)) | Some(Def::ForeignMod(_)) => true,
932 fn is_trait(&self) -> bool {
934 Some(Def::Trait(_)) => true,
939 fn all_imports_resolved(&self) -> bool {
940 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
941 // it is currently being resolved ! so nope
944 self.imports.borrow().len() == self.resolved_import_count.get()
948 pub fn inc_glob_count(&self) {
949 self.glob_count.set(self.glob_count.get() + 1);
951 pub fn dec_glob_count(&self) {
952 assert!(self.glob_count.get() > 0);
953 self.glob_count.set(self.glob_count.get() - 1);
955 pub fn inc_pub_count(&self) {
956 self.pub_count.set(self.pub_count.get() + 1);
958 pub fn dec_pub_count(&self) {
959 assert!(self.pub_count.get() > 0);
960 self.pub_count.set(self.pub_count.get() - 1);
962 pub fn inc_pub_glob_count(&self) {
963 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
965 pub fn dec_pub_glob_count(&self) {
966 assert!(self.pub_glob_count.get() > 0);
967 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
971 impl<'a> fmt::Debug for ModuleS<'a> {
972 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
986 flags DefModifiers: u8 {
987 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
988 // or `use Enum::*` to work on private enums.
989 const PUBLIC = 1 << 0,
990 const IMPORTABLE = 1 << 1,
991 // Variants are considered `PUBLIC`, but some of them live in private enums.
992 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
993 const PRIVATE_VARIANT = 1 << 2,
994 const PRELUDE = 1 << 3,
995 const GLOB_IMPORTED = 1 << 4,
999 // Records a possibly-private value, type, or module definition.
1001 pub struct NameBinding<'a> {
1002 modifiers: DefModifiers,
1003 kind: NameBindingKind<'a>,
1008 enum NameBindingKind<'a> {
1012 binding: &'a NameBinding<'a>,
1017 impl<'a> NameBinding<'a> {
1018 fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
1019 let modifiers = if module.is_public {
1020 DefModifiers::PUBLIC
1022 DefModifiers::empty()
1023 } | DefModifiers::IMPORTABLE;
1025 NameBinding { modifiers: modifiers, kind: NameBindingKind::Module(module), span: span }
1028 fn module(&self) -> Option<Module<'a>> {
1030 NameBindingKind::Module(module) => Some(module),
1031 NameBindingKind::Def(_) => None,
1032 NameBindingKind::Import { binding, .. } => binding.module(),
1036 fn def(&self) -> Option<Def> {
1038 NameBindingKind::Def(def) => Some(def),
1039 NameBindingKind::Module(module) => module.def,
1040 NameBindingKind::Import { binding, .. } => binding.def(),
1044 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1045 self.modifiers.contains(modifiers)
1048 fn is_public(&self) -> bool {
1049 self.defined_with(DefModifiers::PUBLIC)
1052 fn def_and_lp(&self) -> (Def, LastPrivate) {
1053 let def = self.def().unwrap();
1054 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1057 fn is_extern_crate(&self) -> bool {
1058 self.module().map(|module| module.is_extern_crate).unwrap_or(false)
1061 fn is_import(&self) -> bool {
1063 NameBindingKind::Import { .. } => true,
1069 /// Interns the names of the primitive types.
1070 struct PrimitiveTypeTable {
1071 primitive_types: HashMap<Name, PrimTy>,
1074 impl PrimitiveTypeTable {
1075 fn new() -> PrimitiveTypeTable {
1076 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1078 table.intern("bool", TyBool);
1079 table.intern("char", TyChar);
1080 table.intern("f32", TyFloat(FloatTy::F32));
1081 table.intern("f64", TyFloat(FloatTy::F64));
1082 table.intern("isize", TyInt(IntTy::Is));
1083 table.intern("i8", TyInt(IntTy::I8));
1084 table.intern("i16", TyInt(IntTy::I16));
1085 table.intern("i32", TyInt(IntTy::I32));
1086 table.intern("i64", TyInt(IntTy::I64));
1087 table.intern("str", TyStr);
1088 table.intern("usize", TyUint(UintTy::Us));
1089 table.intern("u8", TyUint(UintTy::U8));
1090 table.intern("u16", TyUint(UintTy::U16));
1091 table.intern("u32", TyUint(UintTy::U32));
1092 table.intern("u64", TyUint(UintTy::U64));
1097 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1098 self.primitive_types.insert(token::intern(string), primitive_type);
1102 /// The main resolver class.
1103 pub struct Resolver<'a, 'tcx: 'a> {
1104 session: &'a Session,
1106 ast_map: &'a hir_map::Map<'tcx>,
1108 graph_root: Module<'a>,
1110 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1112 structs: FnvHashMap<DefId, Vec<Name>>,
1114 // The number of imports that are currently unresolved.
1115 unresolved_imports: usize,
1117 // The module that represents the current item scope.
1118 current_module: Module<'a>,
1120 // The current set of local scopes, for values.
1121 // FIXME #4948: Reuse ribs to avoid allocation.
1122 value_ribs: Vec<Rib<'a>>,
1124 // The current set of local scopes, for types.
1125 type_ribs: Vec<Rib<'a>>,
1127 // The current set of local scopes, for labels.
1128 label_ribs: Vec<Rib<'a>>,
1130 // The trait that the current context can refer to.
1131 current_trait_ref: Option<(DefId, TraitRef)>,
1133 // The current self type if inside an impl (used for better errors).
1134 current_self_type: Option<Ty>,
1136 // The idents for the primitive types.
1137 primitive_type_table: PrimitiveTypeTable,
1139 def_map: RefCell<DefMap>,
1140 freevars: FreevarMap,
1141 freevars_seen: NodeMap<NodeMap<usize>>,
1142 export_map: ExportMap,
1143 trait_map: TraitMap,
1144 external_exports: ExternalExports,
1146 // Whether or not to print error messages. Can be set to true
1147 // when getting additional info for error message suggestions,
1148 // so as to avoid printing duplicate errors
1151 make_glob_map: bool,
1152 // Maps imports to the names of items actually imported (this actually maps
1153 // all imports, but only glob imports are actually interesting).
1156 used_imports: HashSet<(NodeId, Namespace)>,
1157 used_crates: HashSet<CrateNum>,
1159 // Callback function for intercepting walks
1160 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1161 // The intention is that the callback modifies this flag.
1162 // Once set, the resolver falls out of the walk, preserving the ribs.
1165 arenas: &'a ResolverArenas<'a>,
1168 pub struct ResolverArenas<'a> {
1169 modules: arena::TypedArena<ModuleS<'a>>,
1170 name_bindings: arena::TypedArena<NameBinding<'a>>,
1173 #[derive(PartialEq)]
1174 enum FallbackChecks {
1176 OnlyTraitAndStatics,
1179 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1180 fn new(session: &'a Session,
1181 ast_map: &'a hir_map::Map<'tcx>,
1182 make_glob_map: MakeGlobMap,
1183 arenas: &'a ResolverArenas<'a>)
1184 -> Resolver<'a, 'tcx> {
1185 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1186 let graph_root = ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, true);
1187 let graph_root = arenas.modules.alloc(graph_root);
1194 // The outermost module has def ID 0; this is not reflected in the
1196 graph_root: graph_root,
1198 trait_item_map: FnvHashMap(),
1199 structs: FnvHashMap(),
1201 unresolved_imports: 0,
1203 current_module: graph_root,
1204 value_ribs: Vec::new(),
1205 type_ribs: Vec::new(),
1206 label_ribs: Vec::new(),
1208 current_trait_ref: None,
1209 current_self_type: None,
1211 primitive_type_table: PrimitiveTypeTable::new(),
1213 def_map: RefCell::new(NodeMap()),
1214 freevars: NodeMap(),
1215 freevars_seen: NodeMap(),
1216 export_map: NodeMap(),
1217 trait_map: NodeMap(),
1218 used_imports: HashSet::new(),
1219 used_crates: HashSet::new(),
1220 external_exports: DefIdSet(),
1223 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1224 glob_map: HashMap::new(),
1233 fn arenas() -> ResolverArenas<'a> {
1235 modules: arena::TypedArena::new(),
1236 name_bindings: arena::TypedArena::new(),
1240 fn new_module(&self,
1241 parent_link: ParentLink<'a>,
1244 is_public: bool) -> Module<'a> {
1245 self.arenas.modules.alloc(ModuleS::new(parent_link, def, external, is_public))
1248 fn new_name_binding(&self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1249 self.arenas.name_bindings.alloc(name_binding)
1252 fn new_extern_crate_module(&self, parent_link: ParentLink<'a>, def: Def) -> Module<'a> {
1253 let mut module = ModuleS::new(parent_link, Some(def), false, true);
1254 module.is_extern_crate = true;
1255 self.arenas.modules.alloc(module)
1258 fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
1259 match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
1263 fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>) {
1264 // track extern crates for unused_extern_crate lint
1265 if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
1266 self.used_crates.insert(krate);
1269 let import_id = match binding.kind {
1270 NameBindingKind::Import { id, .. } => id,
1274 self.used_imports.insert((import_id, ns));
1276 if !self.make_glob_map {
1279 if self.glob_map.contains_key(&import_id) {
1280 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1284 let mut new_set = HashSet::new();
1285 new_set.insert(name);
1286 self.glob_map.insert(import_id, new_set);
1289 fn get_trait_name(&self, did: DefId) -> Name {
1290 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1291 self.ast_map.expect_item(node_id).name
1293 self.session.cstore.item_name(did)
1297 /// Resolves the given module path from the given root `module_`.
1298 fn resolve_module_path_from_root(&mut self,
1299 module_: Module<'a>,
1300 module_path: &[Name],
1304 -> ResolveResult<(Module<'a>, LastPrivate)> {
1305 fn search_parent_externals<'a>(needle: Name, module: Module<'a>) -> Option<Module<'a>> {
1306 match module.resolve_name(needle, TypeNS, false) {
1307 Success(binding) if binding.is_extern_crate() => Some(module),
1308 _ => match module.parent_link {
1309 ModuleParentLink(ref parent, _) => {
1310 search_parent_externals(needle, parent)
1317 let mut search_module = module_;
1318 let mut index = index;
1319 let module_path_len = module_path.len();
1320 let mut closest_private = lp;
1322 // Resolve the module part of the path. This does not involve looking
1323 // upward though scope chains; we simply resolve names directly in
1324 // modules as we go.
1325 while index < module_path_len {
1326 let name = module_path[index];
1327 match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1329 let segment_name = name.as_str();
1330 let module_name = module_to_string(search_module);
1331 let mut span = span;
1332 let msg = if "???" == &module_name {
1333 span.hi = span.lo + Pos::from_usize(segment_name.len());
1335 match search_parent_externals(name, &self.current_module) {
1337 let path_str = names_to_string(module_path);
1338 let target_mod_str = module_to_string(&module);
1339 let current_mod_str = module_to_string(&self.current_module);
1341 let prefix = if target_mod_str == current_mod_str {
1342 "self::".to_string()
1344 format!("{}::", target_mod_str)
1347 format!("Did you mean `{}{}`?", prefix, path_str)
1349 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1352 format!("Could not find `{}` in `{}`", segment_name, module_name)
1355 return Failed(Some((span, msg)));
1357 Failed(err) => return Failed(err),
1359 debug!("(resolving module path for import) module resolution is \
1362 return Indeterminate;
1364 Success(binding) => {
1365 // Check to see whether there are type bindings, and, if
1366 // so, whether there is a module within.
1367 if let Some(module_def) = binding.module() {
1368 search_module = module_def;
1370 // Keep track of the closest private module used
1371 // when resolving this import chain.
1372 if !binding.is_public() {
1373 if let Some(did) = search_module.def_id() {
1374 closest_private = LastMod(DependsOn(did));
1378 let msg = format!("Not a module `{}`", name);
1379 return Failed(Some((span, msg)));
1387 return Success((search_module, closest_private));
1390 /// Attempts to resolve the module part of an import directive or path
1391 /// rooted at the given module.
1393 /// On success, returns the resolved module, and the closest *private*
1394 /// module found to the destination when resolving this path.
1395 fn resolve_module_path(&mut self,
1396 module_: Module<'a>,
1397 module_path: &[Name],
1398 use_lexical_scope: UseLexicalScopeFlag,
1400 -> ResolveResult<(Module<'a>, LastPrivate)> {
1401 if module_path.len() == 0 {
1402 return Success((self.graph_root, LastMod(AllPublic))) // Use the crate root
1405 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1406 names_to_string(module_path),
1407 module_to_string(&module_));
1409 // Resolve the module prefix, if any.
1410 let module_prefix_result = self.resolve_module_prefix(module_, module_path);
1415 match module_prefix_result {
1417 let mpath = names_to_string(module_path);
1418 let mpath = &mpath[..];
1419 match mpath.rfind(':') {
1421 let msg = format!("Could not find `{}` in `{}`",
1422 // idx +- 1 to account for the
1423 // colons on either side
1426 return Failed(Some((span, msg)));
1429 return Failed(None);
1433 Failed(err) => return Failed(err),
1435 debug!("(resolving module path for import) indeterminate; bailing");
1436 return Indeterminate;
1438 Success(NoPrefixFound) => {
1439 // There was no prefix, so we're considering the first element
1440 // of the path. How we handle this depends on whether we were
1441 // instructed to use lexical scope or not.
1442 match use_lexical_scope {
1443 DontUseLexicalScope => {
1444 // This is a crate-relative path. We will start the
1445 // resolution process at index zero.
1446 search_module = self.graph_root;
1448 last_private = LastMod(AllPublic);
1450 UseLexicalScope => {
1451 // This is not a crate-relative path. We resolve the
1452 // first component of the path in the current lexical
1453 // scope and then proceed to resolve below that.
1454 match self.resolve_item_in_lexical_scope(module_,
1458 Failed(err) => return Failed(err),
1460 debug!("(resolving module path for import) indeterminate; bailing");
1461 return Indeterminate;
1463 Success(binding) => match binding.module() {
1464 Some(containing_module) => {
1465 search_module = containing_module;
1467 last_private = LastMod(AllPublic);
1469 None => return Failed(None),
1475 Success(PrefixFound(ref containing_module, index)) => {
1476 search_module = containing_module;
1477 start_index = index;
1478 last_private = LastMod(DependsOn(containing_module.def_id()
1483 self.resolve_module_path_from_root(search_module,
1490 /// Invariant: This must only be called during main resolution, not during
1491 /// import resolution.
1492 fn resolve_item_in_lexical_scope(&mut self,
1493 module_: Module<'a>,
1495 namespace: Namespace,
1497 -> ResolveResult<&'a NameBinding<'a>> {
1498 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1501 module_to_string(&module_));
1503 // Proceed up the scope chain looking for parent modules.
1504 let mut search_module = module_;
1506 // Resolve the name in the parent module.
1507 match self.resolve_name_in_module(search_module, name, namespace, true, record_used) {
1508 Failed(Some((span, msg))) => {
1509 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
1511 Failed(None) => (), // Continue up the search chain.
1513 // We couldn't see through the higher scope because of an
1514 // unresolved import higher up. Bail.
1516 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1517 return Indeterminate;
1519 Success(binding) => {
1520 // We found the module.
1521 debug!("(resolving item in lexical scope) found name in module, done");
1522 return Success(binding);
1526 // Go to the next parent.
1527 match search_module.parent_link {
1529 // No more parents. This module was unresolved.
1530 debug!("(resolving item in lexical scope) unresolved module: no parent module");
1531 return Failed(None);
1533 ModuleParentLink(parent_module_node, _) => {
1534 if search_module.is_normal() {
1535 // We stop the search here.
1536 debug!("(resolving item in lexical scope) unresolved module: not \
1537 searching through module parents");
1538 return Failed(None);
1540 search_module = parent_module_node;
1543 BlockParentLink(parent_module_node, _) => {
1544 search_module = parent_module_node;
1550 /// Returns the nearest normal module parent of the given module.
1551 fn get_nearest_normal_module_parent(&mut self, module_: Module<'a>) -> Option<Module<'a>> {
1552 let mut module_ = module_;
1554 match module_.parent_link {
1555 NoParentLink => return None,
1556 ModuleParentLink(new_module, _) |
1557 BlockParentLink(new_module, _) => {
1558 let new_module = new_module;
1559 if new_module.is_normal() {
1560 return Some(new_module);
1562 module_ = new_module;
1568 /// Returns the nearest normal module parent of the given module, or the
1569 /// module itself if it is a normal module.
1570 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Module<'a>) -> Module<'a> {
1571 if module_.is_normal() {
1574 match self.get_nearest_normal_module_parent(module_) {
1576 Some(new_module) => new_module,
1580 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1581 /// (b) some chain of `super::`.
1582 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1583 fn resolve_module_prefix(&mut self,
1584 module_: Module<'a>,
1585 module_path: &[Name])
1586 -> ResolveResult<ModulePrefixResult<'a>> {
1587 // Start at the current module if we see `self` or `super`, or at the
1588 // top of the crate otherwise.
1589 let mut i = match &*module_path[0].as_str() {
1592 _ => return Success(NoPrefixFound),
1594 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1596 // Now loop through all the `super`s we find.
1597 while i < module_path.len() && "super" == module_path[i].as_str() {
1598 debug!("(resolving module prefix) resolving `super` at {}",
1599 module_to_string(&containing_module));
1600 match self.get_nearest_normal_module_parent(containing_module) {
1601 None => return Failed(None),
1602 Some(new_module) => {
1603 containing_module = new_module;
1609 debug!("(resolving module prefix) finished resolving prefix at {}",
1610 module_to_string(&containing_module));
1612 return Success(PrefixFound(containing_module, i));
1615 /// Attempts to resolve the supplied name in the given module for the
1616 /// given namespace. If successful, returns the binding corresponding to
1618 fn resolve_name_in_module(&mut self,
1621 namespace: Namespace,
1622 allow_private_imports: bool,
1624 -> ResolveResult<&'a NameBinding<'a>> {
1625 debug!("(resolving name in module) resolving `{}` in `{}`", name, module_to_string(module));
1627 build_reduced_graph::populate_module_if_necessary(self, module);
1628 module.resolve_name(name, namespace, allow_private_imports).and_then(|binding| {
1630 self.record_use(name, namespace, binding);
1636 fn report_unresolved_imports(&mut self, module_: Module<'a>) {
1637 let index = module_.resolved_import_count.get();
1638 let imports = module_.imports.borrow();
1639 let import_count = imports.len();
1640 if index != import_count {
1642 (*imports)[index].span,
1643 ResolutionError::UnresolvedImport(None));
1646 // Descend into children and anonymous children.
1647 for (_, module_) in module_.module_children.borrow().iter() {
1648 self.report_unresolved_imports(module_);
1654 // We maintain a list of value ribs and type ribs.
1656 // Simultaneously, we keep track of the current position in the module
1657 // graph in the `current_module` pointer. When we go to resolve a name in
1658 // the value or type namespaces, we first look through all the ribs and
1659 // then query the module graph. When we resolve a name in the module
1660 // namespace, we can skip all the ribs (since nested modules are not
1661 // allowed within blocks in Rust) and jump straight to the current module
1664 // Named implementations are handled separately. When we find a method
1665 // call, we consult the module node to find all of the implementations in
1666 // scope. This information is lazily cached in the module node. We then
1667 // generate a fake "implementation scope" containing all the
1668 // implementations thus found, for compatibility with old resolve pass.
1670 fn with_scope<F>(&mut self, id: NodeId, f: F)
1671 where F: FnOnce(&mut Resolver)
1673 let orig_module = self.current_module;
1675 // Move down in the graph.
1676 if let Some(module) = orig_module.module_children.borrow().get(&id) {
1677 self.current_module = module;
1682 self.current_module = orig_module;
1685 /// Searches the current set of local scopes for labels.
1686 /// Stops after meeting a closure.
1687 fn search_label(&self, name: Name) -> Option<DefLike> {
1688 for rib in self.label_ribs.iter().rev() {
1694 // Do not resolve labels across function boundary
1698 let result = rib.bindings.get(&name).cloned();
1699 if result.is_some() {
1706 fn resolve_crate(&mut self, krate: &hir::Crate) {
1707 debug!("(resolving crate) starting");
1709 intravisit::walk_crate(self, krate);
1712 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1713 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1714 span_err!(self.session,
1717 "user-defined types or type parameters cannot shadow the primitive types");
1721 fn resolve_item(&mut self, item: &Item) {
1722 let name = item.name;
1724 debug!("(resolving item) resolving {}", name);
1727 ItemEnum(_, ref generics) |
1728 ItemTy(_, ref generics) |
1729 ItemStruct(_, ref generics) => {
1730 self.check_if_primitive_type_name(name, item.span);
1732 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1733 |this| intravisit::walk_item(this, item));
1735 ItemFn(_, _, _, _, ref generics, _) => {
1736 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1737 |this| intravisit::walk_item(this, item));
1740 ItemDefaultImpl(_, ref trait_ref) => {
1741 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1743 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1744 self.resolve_implementation(generics,
1751 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1752 self.check_if_primitive_type_name(name, item.span);
1754 // Create a new rib for the trait-wide type parameters.
1755 self.with_type_parameter_rib(HasTypeParameters(generics,
1759 let local_def_id = this.ast_map.local_def_id(item.id);
1760 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1761 this.visit_generics(generics);
1762 walk_list!(this, visit_ty_param_bound, bounds);
1764 for trait_item in trait_items {
1765 match trait_item.node {
1766 hir::ConstTraitItem(_, ref default) => {
1767 // Only impose the restrictions of
1768 // ConstRibKind if there's an actual constant
1769 // expression in a provided default.
1770 if default.is_some() {
1771 this.with_constant_rib(|this| {
1772 intravisit::walk_trait_item(this, trait_item)
1775 intravisit::walk_trait_item(this, trait_item)
1778 hir::MethodTraitItem(ref sig, _) => {
1779 let type_parameters =
1780 HasTypeParameters(&sig.generics,
1783 this.with_type_parameter_rib(type_parameters, |this| {
1784 intravisit::walk_trait_item(this, trait_item)
1787 hir::TypeTraitItem(..) => {
1788 this.check_if_primitive_type_name(trait_item.name,
1790 this.with_type_parameter_rib(NoTypeParameters, |this| {
1791 intravisit::walk_trait_item(this, trait_item)
1800 ItemMod(_) | ItemForeignMod(_) => {
1801 self.with_scope(item.id, |this| {
1802 intravisit::walk_item(this, item);
1806 ItemConst(..) | ItemStatic(..) => {
1807 self.with_constant_rib(|this| {
1808 intravisit::walk_item(this, item);
1812 ItemUse(ref view_path) => {
1813 // check for imports shadowing primitive types
1814 let check_rename = |this: &Self, id, name| {
1815 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
1816 Some(Def::Enum(..)) | Some(Def::TyAlias(..)) | Some(Def::Struct(..)) |
1817 Some(Def::Trait(..)) | None => {
1818 this.check_if_primitive_type_name(name, item.span);
1824 match view_path.node {
1825 hir::ViewPathSimple(name, _) => {
1826 check_rename(self, item.id, name);
1828 hir::ViewPathList(ref prefix, ref items) => {
1830 if let Some(name) = item.node.rename() {
1831 check_rename(self, item.node.id(), name);
1835 // Resolve prefix of an import with empty braces (issue #28388)
1836 if items.is_empty() && !prefix.segments.is_empty() {
1837 match self.resolve_crate_relative_path(prefix.span,
1841 self.record_def(item.id, PathResolution::new(def, lp, 0)),
1845 ResolutionError::FailedToResolve(
1846 &path_names_to_string(prefix, 0)));
1847 self.record_def(item.id, err_path_resolution());
1856 ItemExternCrate(_) => {
1857 // do nothing, these are just around to be encoded
1862 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
1863 where F: FnOnce(&mut Resolver)
1865 match type_parameters {
1866 HasTypeParameters(generics, space, rib_kind) => {
1867 let mut function_type_rib = Rib::new(rib_kind);
1868 let mut seen_bindings = HashSet::new();
1869 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1870 let name = type_parameter.name;
1871 debug!("with_type_parameter_rib: {}", type_parameter.id);
1873 if seen_bindings.contains(&name) {
1875 type_parameter.span,
1876 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1878 seen_bindings.insert(name);
1880 // plain insert (no renaming)
1881 function_type_rib.bindings
1883 DlDef(Def::TyParam(space,
1886 .local_def_id(type_parameter.id),
1889 self.type_ribs.push(function_type_rib);
1892 NoTypeParameters => {
1899 match type_parameters {
1900 HasTypeParameters(..) => {
1902 self.type_ribs.pop();
1905 NoTypeParameters => {}
1909 fn with_label_rib<F>(&mut self, f: F)
1910 where F: FnOnce(&mut Resolver)
1912 self.label_ribs.push(Rib::new(NormalRibKind));
1915 self.label_ribs.pop();
1919 fn with_constant_rib<F>(&mut self, f: F)
1920 where F: FnOnce(&mut Resolver)
1922 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1923 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1926 self.type_ribs.pop();
1927 self.value_ribs.pop();
1931 fn resolve_function(&mut self, rib_kind: RibKind<'a>, declaration: &FnDecl, block: &Block) {
1932 // Create a value rib for the function.
1933 self.value_ribs.push(Rib::new(rib_kind));
1935 // Create a label rib for the function.
1936 self.label_ribs.push(Rib::new(rib_kind));
1938 // Add each argument to the rib.
1939 let mut bindings_list = HashMap::new();
1940 for argument in &declaration.inputs {
1941 self.resolve_pattern(&argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
1943 self.visit_ty(&argument.ty);
1945 debug!("(resolving function) recorded argument");
1947 intravisit::walk_fn_ret_ty(self, &declaration.output);
1949 // Resolve the function body.
1950 self.visit_block(block);
1952 debug!("(resolving function) leaving function");
1955 self.label_ribs.pop();
1956 self.value_ribs.pop();
1960 fn resolve_trait_reference(&mut self,
1964 -> Result<PathResolution, ()> {
1965 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
1966 if let Def::Trait(_) = path_res.base_def {
1967 debug!("(resolving trait) found trait def: {:?}", path_res);
1971 resolve_struct_error(self,
1973 ResolutionError::IsNotATrait(&path_names_to_string(trait_path,
1976 // If it's a typedef, give a note
1977 if let Def::TyAlias(..) = path_res.base_def {
1978 err.span_note(trait_path.span,
1979 "`type` aliases cannot be used for traits");
1986 // find possible candidates
1987 let trait_name = trait_path.segments.last().unwrap().identifier.name;
1989 self.lookup_candidates(
1993 Def::Trait(_) => true,
1998 // create error object
1999 let name = &path_names_to_string(trait_path, path_depth);
2001 ResolutionError::UndeclaredTraitName(
2006 resolve_error(self, trait_path.span, error);
2011 fn resolve_generics(&mut self, generics: &Generics) {
2012 for type_parameter in generics.ty_params.iter() {
2013 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2015 for predicate in &generics.where_clause.predicates {
2017 &hir::WherePredicate::BoundPredicate(_) |
2018 &hir::WherePredicate::RegionPredicate(_) => {}
2019 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2020 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2021 if let Some(PathResolution { base_def: Def::TyParam(..), .. }) = path_res {
2022 self.record_def(eq_pred.id, path_res.unwrap());
2026 ResolutionError::UndeclaredAssociatedType);
2027 self.record_def(eq_pred.id, err_path_resolution());
2032 intravisit::walk_generics(self, generics);
2035 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2036 where F: FnOnce(&mut Resolver) -> T
2038 // Handle nested impls (inside fn bodies)
2039 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2040 let result = f(self);
2041 self.current_self_type = previous_value;
2045 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2046 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2048 let mut new_val = None;
2049 let mut new_id = None;
2050 if let Some(trait_ref) = opt_trait_ref {
2051 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2054 assert!(path_res.depth == 0);
2055 self.record_def(trait_ref.ref_id, path_res);
2056 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2057 new_id = Some(path_res.base_def.def_id());
2059 self.record_def(trait_ref.ref_id, err_path_resolution());
2061 intravisit::walk_trait_ref(self, trait_ref);
2063 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2064 let result = f(self, new_id);
2065 self.current_trait_ref = original_trait_ref;
2069 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2070 where F: FnOnce(&mut Resolver)
2072 let mut self_type_rib = Rib::new(NormalRibKind);
2074 // plain insert (no renaming, types are not currently hygienic....)
2075 let name = special_names::type_self;
2076 self_type_rib.bindings.insert(name, DlDef(self_def));
2077 self.type_ribs.push(self_type_rib);
2080 self.type_ribs.pop();
2084 fn resolve_implementation(&mut self,
2085 generics: &Generics,
2086 opt_trait_reference: &Option<TraitRef>,
2089 impl_items: &[ImplItem]) {
2090 // If applicable, create a rib for the type parameters.
2091 self.with_type_parameter_rib(HasTypeParameters(generics,
2095 // Resolve the type parameters.
2096 this.visit_generics(generics);
2098 // Resolve the trait reference, if necessary.
2099 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2100 // Resolve the self type.
2101 this.visit_ty(self_type);
2103 this.with_self_rib(Def::SelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2104 this.with_current_self_type(self_type, |this| {
2105 for impl_item in impl_items {
2106 match impl_item.node {
2107 hir::ImplItemKind::Const(..) => {
2108 // If this is a trait impl, ensure the const
2110 this.check_trait_item(impl_item.name,
2112 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2113 this.with_constant_rib(|this| {
2114 intravisit::walk_impl_item(this, impl_item);
2117 hir::ImplItemKind::Method(ref sig, _) => {
2118 // If this is a trait impl, ensure the method
2120 this.check_trait_item(impl_item.name,
2122 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2124 // We also need a new scope for the method-
2125 // specific type parameters.
2126 let type_parameters =
2127 HasTypeParameters(&sig.generics,
2130 this.with_type_parameter_rib(type_parameters, |this| {
2131 intravisit::walk_impl_item(this, impl_item);
2134 hir::ImplItemKind::Type(ref ty) => {
2135 // If this is a trait impl, ensure the type
2137 this.check_trait_item(impl_item.name,
2139 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2151 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2152 where F: FnOnce(Name, &str) -> ResolutionError
2154 // If there is a TraitRef in scope for an impl, then the method must be in the
2156 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2157 if !self.trait_item_map.contains_key(&(name, did)) {
2158 let path_str = path_names_to_string(&trait_ref.path, 0);
2159 resolve_error(self, span, err(name, &path_str));
2164 fn resolve_local(&mut self, local: &Local) {
2165 // Resolve the type.
2166 walk_list!(self, visit_ty, &local.ty);
2168 // Resolve the initializer.
2169 walk_list!(self, visit_expr, &local.init);
2171 // Resolve the pattern.
2172 self.resolve_pattern(&local.pat, LocalIrrefutableMode, &mut HashMap::new());
2175 // build a map from pattern identifiers to binding-info's.
2176 // this is done hygienically. This could arise for a macro
2177 // that expands into an or-pattern where one 'x' was from the
2178 // user and one 'x' came from the macro.
2179 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2180 let mut result = HashMap::new();
2181 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2182 let name = path1.node;
2186 binding_mode: binding_mode,
2192 // check that all of the arms in an or-pattern have exactly the
2193 // same set of bindings, with the same binding modes for each.
2194 fn check_consistent_bindings(&mut self, arm: &Arm) {
2195 if arm.pats.is_empty() {
2198 let map_0 = self.binding_mode_map(&arm.pats[0]);
2199 for (i, p) in arm.pats.iter().enumerate() {
2200 let map_i = self.binding_mode_map(&p);
2202 for (&key, &binding_0) in &map_0 {
2203 match map_i.get(&key) {
2207 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2209 Some(binding_i) => {
2210 if binding_0.binding_mode != binding_i.binding_mode {
2213 ResolutionError::VariableBoundWithDifferentMode(key,
2220 for (&key, &binding) in &map_i {
2221 if !map_0.contains_key(&key) {
2224 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2230 fn resolve_arm(&mut self, arm: &Arm) {
2231 self.value_ribs.push(Rib::new(NormalRibKind));
2233 let mut bindings_list = HashMap::new();
2234 for pattern in &arm.pats {
2235 self.resolve_pattern(&pattern, RefutableMode, &mut bindings_list);
2238 // This has to happen *after* we determine which
2239 // pat_idents are variants
2240 self.check_consistent_bindings(arm);
2242 walk_list!(self, visit_expr, &arm.guard);
2243 self.visit_expr(&arm.body);
2246 self.value_ribs.pop();
2250 fn resolve_block(&mut self, block: &Block) {
2251 debug!("(resolving block) entering block");
2252 // Move down in the graph, if there's an anonymous module rooted here.
2253 let orig_module = self.current_module;
2254 let anonymous_module =
2255 orig_module.module_children.borrow().get(&block.id).map(|module| *module);
2257 if let Some(anonymous_module) = anonymous_module {
2258 debug!("(resolving block) found anonymous module, moving down");
2259 self.value_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2260 self.type_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2261 self.current_module = anonymous_module;
2263 self.value_ribs.push(Rib::new(NormalRibKind));
2266 // Descend into the block.
2267 intravisit::walk_block(self, block);
2271 self.current_module = orig_module;
2272 self.value_ribs.pop();
2273 if let Some(_) = anonymous_module {
2274 self.type_ribs.pop();
2277 debug!("(resolving block) leaving block");
2280 fn resolve_type(&mut self, ty: &Ty) {
2282 TyPath(ref maybe_qself, ref path) => {
2283 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2284 maybe_qself.as_ref(),
2288 // `<T>::a::b::c` is resolved by typeck alone.
2289 TypecheckRequired => {
2290 // Resolve embedded types.
2291 intravisit::walk_ty(self, ty);
2294 ResolveAttempt(resolution) => resolution,
2297 // This is a path in the type namespace. Walk through scopes
2301 // Write the result into the def map.
2302 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2303 path_names_to_string(path, 0),
2306 self.record_def(ty.id, def);
2309 self.record_def(ty.id, err_path_resolution());
2311 // Keep reporting some errors even if they're ignored above.
2312 self.resolve_path(ty.id, path, 0, TypeNS, true);
2314 let kind = if maybe_qself.is_some() {
2320 let self_type_name = special_idents::type_self.name;
2321 let is_invalid_self_type_name = path.segments.len() > 0 &&
2322 maybe_qself.is_none() &&
2323 path.segments[0].identifier.name ==
2325 if is_invalid_self_type_name {
2328 ResolutionError::SelfUsedOutsideImplOrTrait);
2330 let segment = path.segments.last();
2331 let segment = segment.expect("missing name in path");
2332 let type_name = segment.identifier.name;
2335 self.lookup_candidates(
2342 Def::TyAlias(_) => true,
2347 // create error object
2348 let name = &path_names_to_string(path, 0);
2350 ResolutionError::UseOfUndeclared(
2356 resolve_error(self, ty.span, error);
2363 // Resolve embedded types.
2364 intravisit::walk_ty(self, ty);
2367 fn resolve_pattern(&mut self,
2369 mode: PatternBindingMode,
2370 // Maps idents to the node ID for the (outermost)
2371 // pattern that binds them
2372 bindings_list: &mut HashMap<Name, NodeId>) {
2373 let pat_id = pattern.id;
2374 walk_pat(pattern, |pattern| {
2375 match pattern.node {
2376 PatKind::Ident(binding_mode, ref path1, ref at_rhs) => {
2377 // The meaning of PatKind::Ident with no type parameters
2378 // depends on whether an enum variant or unit-like struct
2379 // with that name is in scope. The probing lookup has to
2380 // be careful not to emit spurious errors. Only matching
2381 // patterns (match) can match nullary variants or
2382 // unit-like structs. For binding patterns (let
2383 // and the LHS of @-patterns), matching such a value is
2384 // simply disallowed (since it's rarely what you want).
2385 let const_ok = mode == RefutableMode && at_rhs.is_none();
2387 let ident = path1.node;
2388 let renamed = ident.name;
2390 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2392 FoundStructOrEnumVariant(def, lp) if const_ok => {
2393 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2396 self.enforce_default_binding_mode(pattern,
2399 self.record_def(pattern.id,
2406 FoundStructOrEnumVariant(..) => {
2410 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2413 self.record_def(pattern.id, err_path_resolution());
2415 FoundConst(def, lp, _) if const_ok => {
2416 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2418 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2419 self.record_def(pattern.id,
2426 FoundConst(def, _, name) => {
2430 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2433 self.record_def(pattern.id, err_path_resolution());
2435 BareIdentifierPatternUnresolved => {
2436 debug!("(resolving pattern) binding `{}`", renamed);
2438 let def_id = self.ast_map.local_def_id(pattern.id);
2439 let def = Def::Local(def_id, pattern.id);
2441 // Record the definition so that later passes
2442 // will be able to distinguish variants from
2443 // locals in patterns.
2445 self.record_def(pattern.id,
2448 last_private: LastMod(AllPublic),
2452 // Add the binding to the local ribs, if it
2453 // doesn't already exist in the bindings list. (We
2454 // must not add it if it's in the bindings list
2455 // because that breaks the assumptions later
2456 // passes make about or-patterns.)
2457 if !bindings_list.contains_key(&renamed) {
2458 let this = &mut *self;
2459 let last_rib = this.value_ribs.last_mut().unwrap();
2460 last_rib.bindings.insert(renamed, DlDef(def));
2461 bindings_list.insert(renamed, pat_id);
2462 } else if mode == ArgumentIrrefutableMode &&
2463 bindings_list.contains_key(&renamed) {
2464 // Forbid duplicate bindings in the same
2469 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2470 &ident.name.as_str())
2472 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2473 // Then this is a duplicate variable in the
2474 // same disjunction, which is an error.
2478 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2479 &ident.name.as_str())
2482 // Else, not bound in the same pattern: do
2488 PatKind::TupleStruct(ref path, _) | PatKind::Path(ref path) => {
2489 // This must be an enum variant, struct or const.
2490 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2495 // The below shouldn't happen because all
2496 // qualified paths should be in PatKind::QPath.
2497 TypecheckRequired =>
2498 self.session.span_bug(path.span,
2499 "resolve_possibly_assoc_item claimed that a path \
2500 in PatKind::Path or PatKind::TupleStruct \
2501 requires typecheck to resolve, but qualified \
2502 paths should be PatKind::QPath"),
2503 ResolveAttempt(resolution) => resolution,
2505 if let Some(path_res) = resolution {
2506 match path_res.base_def {
2507 Def::Struct(..) if path_res.depth == 0 => {
2508 self.record_def(pattern.id, path_res);
2510 Def::Variant(..) | Def::Const(..) => {
2511 self.record_def(pattern.id, path_res);
2513 Def::Static(..) => {
2514 resolve_error(&self,
2516 ResolutionError::StaticVariableReference);
2517 self.record_def(pattern.id, err_path_resolution());
2520 // If anything ends up here entirely resolved,
2521 // it's an error. If anything ends up here
2522 // partially resolved, that's OK, because it may
2523 // be a `T::CONST` that typeck will resolve.
2524 if path_res.depth == 0 {
2528 ResolutionError::NotAnEnumVariantStructOrConst(
2536 self.record_def(pattern.id, err_path_resolution());
2538 let const_name = path.segments
2543 let traits = self.get_traits_containing_item(const_name);
2544 self.trait_map.insert(pattern.id, traits);
2545 self.record_def(pattern.id, path_res);
2553 ResolutionError::UnresolvedEnumVariantStructOrConst(
2554 &path.segments.last().unwrap().identifier.name.as_str())
2556 self.record_def(pattern.id, err_path_resolution());
2558 intravisit::walk_path(self, path);
2561 PatKind::QPath(ref qself, ref path) => {
2562 // Associated constants only.
2563 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2568 TypecheckRequired => {
2569 // All `<T>::CONST` should end up here, and will
2570 // require use of the trait map to resolve
2571 // during typechecking.
2572 let const_name = path.segments
2577 let traits = self.get_traits_containing_item(const_name);
2578 self.trait_map.insert(pattern.id, traits);
2579 intravisit::walk_pat(self, pattern);
2582 ResolveAttempt(resolution) => resolution,
2584 if let Some(path_res) = resolution {
2585 match path_res.base_def {
2586 // All `<T as Trait>::CONST` should end up here, and
2587 // have the trait already selected.
2588 Def::AssociatedConst(..) => {
2589 self.record_def(pattern.id, path_res);
2595 ResolutionError::NotAnAssociatedConst(
2596 &path.segments.last().unwrap().identifier.name.as_str()
2599 self.record_def(pattern.id, err_path_resolution());
2605 ResolutionError::UnresolvedAssociatedConst(&path.segments
2611 self.record_def(pattern.id, err_path_resolution());
2613 intravisit::walk_pat(self, pattern);
2616 PatKind::Struct(ref path, _, _) => {
2617 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2618 Some(definition) => {
2619 self.record_def(pattern.id, definition);
2622 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2626 ResolutionError::DoesNotNameAStruct(
2627 &path_names_to_string(path, 0))
2629 self.record_def(pattern.id, err_path_resolution());
2632 intravisit::walk_path(self, path);
2635 PatKind::Lit(_) | PatKind::Range(..) => {
2636 intravisit::walk_pat(self, pattern);
2647 fn resolve_bare_identifier_pattern(&mut self,
2650 -> BareIdentifierPatternResolution {
2651 let module = self.current_module;
2652 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2653 Success(binding) => {
2654 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2657 match binding.def() {
2659 panic!("resolved name in the value namespace to a set of name bindings \
2662 // For the two success cases, this lookup can be
2663 // considered as not having a private component because
2664 // the lookup happened only within the current module.
2665 Some(def @ Def::Variant(..)) | Some(def @ Def::Struct(..)) => {
2666 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2668 Some(def @ Def::Const(..)) | Some(def @ Def::AssociatedConst(..)) => {
2669 return FoundConst(def, LastMod(AllPublic), name);
2671 Some(Def::Static(..)) => {
2672 resolve_error(self, span, ResolutionError::StaticVariableReference);
2673 return BareIdentifierPatternUnresolved;
2675 _ => return BareIdentifierPatternUnresolved
2679 Indeterminate => return BareIdentifierPatternUnresolved,
2682 Some((span, msg)) => {
2683 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2688 debug!("(resolve bare identifier pattern) failed to find {}", name);
2689 return BareIdentifierPatternUnresolved;
2694 /// Handles paths that may refer to associated items
2695 fn resolve_possibly_assoc_item(&mut self,
2697 maybe_qself: Option<&hir::QSelf>,
2699 namespace: Namespace,
2701 -> AssocItemResolveResult {
2702 let max_assoc_types;
2706 if qself.position == 0 {
2707 return TypecheckRequired;
2709 max_assoc_types = path.segments.len() - qself.position;
2710 // Make sure the trait is valid.
2711 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2714 max_assoc_types = path.segments.len();
2718 let mut resolution = self.with_no_errors(|this| {
2719 this.resolve_path(id, path, 0, namespace, check_ribs)
2721 for depth in 1..max_assoc_types {
2722 if resolution.is_some() {
2725 self.with_no_errors(|this| {
2726 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2729 if let Some(Def::Mod(_)) = resolution.map(|r| r.base_def) {
2730 // A module is not a valid type or value.
2733 ResolveAttempt(resolution)
2736 /// If `check_ribs` is true, checks the local definitions first; i.e.
2737 /// doesn't skip straight to the containing module.
2738 /// Skips `path_depth` trailing segments, which is also reflected in the
2739 /// returned value. See `middle::def::PathResolution` for more info.
2740 pub fn resolve_path(&mut self,
2744 namespace: Namespace,
2746 -> Option<PathResolution> {
2747 let span = path.span;
2748 let segments = &path.segments[..path.segments.len() - path_depth];
2750 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2753 let def = self.resolve_crate_relative_path(span, segments, namespace);
2754 return def.map(mk_res);
2757 // Try to find a path to an item in a module.
2758 let last_ident = segments.last().unwrap().identifier;
2759 if segments.len() <= 1 {
2760 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2761 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2763 PathResolution::new(def, LastMod(AllPublic), path_depth)
2767 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2768 let def = self.resolve_module_relative_path(span, segments, namespace);
2769 match (def, unqualified_def) {
2770 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2772 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2775 "unnecessary qualification".to_string());
2783 // Resolve a single identifier
2784 fn resolve_identifier(&mut self,
2785 identifier: hir::Ident,
2786 namespace: Namespace,
2789 -> Option<LocalDef> {
2790 if identifier.name == special_idents::invalid.name {
2791 return Some(LocalDef::from_def(Def::Err));
2794 // First, check to see whether the name is a primitive type.
2795 if namespace == TypeNS {
2796 if let Some(&prim_ty) = self.primitive_type_table
2798 .get(&identifier.unhygienic_name) {
2799 return Some(LocalDef::from_def(Def::PrimTy(prim_ty)));
2804 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2810 let module = self.current_module;
2811 let name = identifier.unhygienic_name;
2812 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
2813 Success(binding) => binding.def().map(LocalDef::from_def),
2814 Failed(Some((span, msg))) => {
2815 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2822 // Resolve a local definition, potentially adjusting for closures.
2823 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2824 let ribs = match local_def.ribs {
2825 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2826 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2829 let mut def = local_def.def;
2832 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2834 Def::Local(_, node_id) => {
2837 NormalRibKind | AnonymousModuleRibKind(..) => {
2838 // Nothing to do. Continue.
2840 ClosureRibKind(function_id) => {
2842 let node_def_id = self.ast_map.local_def_id(node_id);
2844 let seen = self.freevars_seen
2846 .or_insert_with(|| NodeMap());
2847 if let Some(&index) = seen.get(&node_id) {
2848 def = Def::Upvar(node_def_id, node_id, index, function_id);
2851 let vec = self.freevars
2853 .or_insert_with(|| vec![]);
2854 let depth = vec.len();
2860 def = Def::Upvar(node_def_id, node_id, depth, function_id);
2861 seen.insert(node_id, depth);
2863 ItemRibKind | MethodRibKind => {
2864 // This was an attempt to access an upvar inside a
2865 // named function item. This is not allowed, so we
2869 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2872 ConstantItemRibKind => {
2873 // Still doesn't deal with upvars
2876 ResolutionError::AttemptToUseNonConstantValueInConstant);
2882 Def::TyParam(..) | Def::SelfTy(..) => {
2885 NormalRibKind | MethodRibKind | ClosureRibKind(..) |
2886 AnonymousModuleRibKind(..) => {
2887 // Nothing to do. Continue.
2890 // This was an attempt to use a type parameter outside
2895 ResolutionError::TypeParametersFromOuterFunction);
2898 ConstantItemRibKind => {
2900 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2911 // resolve a "module-relative" path, e.g. a::b::c
2912 fn resolve_module_relative_path(&mut self,
2914 segments: &[hir::PathSegment],
2915 namespace: Namespace)
2916 -> Option<(Def, LastPrivate)> {
2917 let module_path = segments.split_last()
2921 .map(|ps| ps.identifier.name)
2922 .collect::<Vec<_>>();
2924 let containing_module;
2926 let current_module = self.current_module;
2927 match self.resolve_module_path(current_module, &module_path, UseLexicalScope, span) {
2929 let (span, msg) = match err {
2930 Some((span, msg)) => (span, msg),
2932 let msg = format!("Use of undeclared type or module `{}`",
2933 names_to_string(&module_path));
2938 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2941 Indeterminate => return None,
2942 Success((resulting_module, resulting_last_private)) => {
2943 containing_module = resulting_module;
2944 last_private = resulting_last_private;
2948 let name = segments.last().unwrap().identifier.name;
2949 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2950 let def = match result {
2951 Success(binding) => {
2952 let (def, lp) = binding.def_and_lp();
2953 (def, last_private.or(lp))
2960 /// Invariant: This must be called only during main resolution, not during
2961 /// import resolution.
2962 fn resolve_crate_relative_path(&mut self,
2964 segments: &[hir::PathSegment],
2965 namespace: Namespace)
2966 -> Option<(Def, LastPrivate)> {
2967 let module_path = segments.split_last()
2971 .map(|ps| ps.identifier.name)
2972 .collect::<Vec<_>>();
2974 let root_module = self.graph_root;
2976 let containing_module;
2978 match self.resolve_module_path_from_root(root_module,
2982 LastMod(AllPublic)) {
2984 let (span, msg) = match err {
2985 Some((span, msg)) => (span, msg),
2987 let msg = format!("Use of undeclared module `::{}`",
2988 names_to_string(&module_path));
2993 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2997 Indeterminate => return None,
2999 Success((resulting_module, resulting_last_private)) => {
3000 containing_module = resulting_module;
3001 last_private = resulting_last_private;
3005 let name = segments.last().unwrap().identifier.name;
3006 match self.resolve_name_in_module(containing_module, name, namespace, false, true) {
3007 Success(binding) => {
3008 let (def, lp) = binding.def_and_lp();
3009 Some((def, last_private.or(lp)))
3015 fn resolve_identifier_in_local_ribs(&mut self,
3017 namespace: Namespace)
3018 -> Option<LocalDef> {
3019 // Check the local set of ribs.
3020 let name = match namespace { ValueNS => ident.name, TypeNS => ident.unhygienic_name };
3022 for i in (0 .. self.get_ribs(namespace).len()).rev() {
3023 if let Some(def_like) = self.get_ribs(namespace)[i].bindings.get(&name).cloned() {
3026 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3030 return Some(LocalDef {
3031 ribs: Some((namespace, i)),
3036 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3044 if let AnonymousModuleRibKind(module) = self.get_ribs(namespace)[i].kind {
3045 if let Success(binding) = self.resolve_name_in_module(module,
3046 ident.unhygienic_name,
3050 if let Some(def) = binding.def() {
3051 return Some(LocalDef::from_def(def));
3060 fn with_no_errors<T, F>(&mut self, f: F) -> T
3061 where F: FnOnce(&mut Resolver) -> T
3063 self.emit_errors = false;
3065 self.emit_errors = true;
3069 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3070 fn extract_path_and_node_id(t: &Ty,
3071 allow: FallbackChecks)
3072 -> Option<(Path, NodeId, FallbackChecks)> {
3074 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3075 TyPtr(ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, OnlyTraitAndStatics),
3076 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, allow),
3077 // This doesn't handle the remaining `Ty` variants as they are not
3078 // that commonly the self_type, it might be interesting to provide
3079 // support for those in future.
3084 fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
3086 name_path: &[ast::Name])
3087 -> Option<Module<'a>> {
3088 let root = this.current_module;
3089 let last_name = name_path.last().unwrap();
3091 if name_path.len() == 1 {
3092 match this.primitive_type_table.primitive_types.get(last_name) {
3094 None => this.current_module.resolve_name(*last_name, TypeNS, true).success()
3095 .and_then(NameBinding::module)
3098 match this.resolve_module_path(root, &name_path, UseLexicalScope, span) {
3099 Success((module, _)) => Some(module),
3105 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3106 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3107 let sig = match this.ast_map.get(node_id) {
3108 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3109 hir::MethodTraitItem(ref sig, _) => sig,
3112 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3113 hir::ImplItemKind::Method(ref sig, _) => sig,
3118 sig.explicit_self.node == hir::SelfStatic
3120 this.session.cstore.is_static_method(did)
3124 let (path, node_id, allowed) = match self.current_self_type {
3125 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3127 None => return NoSuggestion,
3129 None => return NoSuggestion,
3132 if allowed == Everything {
3133 // Look for a field with the same name in the current self_type.
3134 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3135 Some(Def::Enum(did)) |
3136 Some(Def::TyAlias(did)) |
3137 Some(Def::Struct(did)) |
3138 Some(Def::Variant(_, did)) => match self.structs.get(&did) {
3141 if fields.iter().any(|&field_name| name == field_name) {
3146 _ => {} // Self type didn't resolve properly
3150 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3152 // Look for a method in the current self type's impl module.
3153 if let Some(module) = get_module(self, path.span, &name_path) {
3154 if let Success(binding) = module.resolve_name(name, ValueNS, true) {
3155 if let Some(Def::Method(did)) = binding.def() {
3156 if is_static_method(self, did) {
3157 return StaticMethod(path_names_to_string(&path, 0));
3159 if self.current_trait_ref.is_some() {
3161 } else if allowed == Everything {
3168 // Look for a method in the current trait.
3169 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3170 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3171 if is_static_method(self, did) {
3172 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3182 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3183 if let Some(macro_name) = self.session.available_macros
3184 .borrow().iter().find(|n| n.as_str() == name) {
3185 return SuggestionType::Macro(format!("{}!", macro_name));
3188 let names = self.value_ribs
3191 .flat_map(|rib| rib.bindings.keys());
3193 if let Some(found) = find_best_match_for_name(names, name, None) {
3195 return SuggestionType::Function(found);
3197 } SuggestionType::NotFound
3200 fn resolve_expr(&mut self, expr: &Expr) {
3201 // First, record candidate traits for this expression if it could
3202 // result in the invocation of a method call.
3204 self.record_candidate_traits_for_expr_if_necessary(expr);
3206 // Next, resolve the node.
3208 ExprPath(ref maybe_qself, ref path) => {
3209 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3210 maybe_qself.as_ref(),
3214 // `<T>::a::b::c` is resolved by typeck alone.
3215 TypecheckRequired => {
3216 let method_name = path.segments.last().unwrap().identifier.name;
3217 let traits = self.get_traits_containing_item(method_name);
3218 self.trait_map.insert(expr.id, traits);
3219 intravisit::walk_expr(self, expr);
3222 ResolveAttempt(resolution) => resolution,
3225 // This is a local path in the value namespace. Walk through
3226 // scopes looking for it.
3227 if let Some(path_res) = resolution {
3228 // Check if struct variant
3229 let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
3230 self.structs.contains_key(&variant_id)
3234 if is_struct_variant {
3235 let _ = self.structs.contains_key(&path_res.base_def.def_id());
3236 let path_name = path_names_to_string(path, 0);
3238 let mut err = resolve_struct_error(self,
3240 ResolutionError::StructVariantUsedAsFunction(&path_name));
3242 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3244 if self.emit_errors {
3245 err.fileline_help(expr.span, &msg);
3247 err.span_help(expr.span, &msg);
3250 self.record_def(expr.id, err_path_resolution());
3252 // Write the result into the def map.
3253 debug!("(resolving expr) resolved `{}`",
3254 path_names_to_string(path, 0));
3256 // Partial resolutions will need the set of traits in scope,
3257 // so they can be completed during typeck.
3258 if path_res.depth != 0 {
3259 let method_name = path.segments.last().unwrap().identifier.name;
3260 let traits = self.get_traits_containing_item(method_name);
3261 self.trait_map.insert(expr.id, traits);
3264 self.record_def(expr.id, path_res);
3267 // Be helpful if the name refers to a struct
3268 // (The pattern matching def_tys where the id is in self.structs
3269 // matches on regular structs while excluding tuple- and enum-like
3270 // structs, which wouldn't result in this error.)
3271 let path_name = path_names_to_string(path, 0);
3272 let type_res = self.with_no_errors(|this| {
3273 this.resolve_path(expr.id, path, 0, TypeNS, false)
3276 self.record_def(expr.id, err_path_resolution());
3277 match type_res.map(|r| r.base_def) {
3278 Some(Def::Struct(..)) => {
3279 let mut err = resolve_struct_error(self,
3281 ResolutionError::StructVariantUsedAsFunction(&path_name));
3283 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3285 if self.emit_errors {
3286 err.fileline_help(expr.span, &msg);
3288 err.span_help(expr.span, &msg);
3293 // Keep reporting some errors even if they're ignored above.
3294 self.resolve_path(expr.id, path, 0, ValueNS, true);
3296 let mut method_scope = false;
3297 self.value_ribs.iter().rev().all(|rib| {
3298 method_scope = match rib.kind {
3299 MethodRibKind => true,
3300 ItemRibKind | ConstantItemRibKind => false,
3301 _ => return true, // Keep advancing
3303 false // Stop advancing
3306 if method_scope && special_names::self_.as_str() == &path_name[..] {
3309 ResolutionError::SelfNotAvailableInStaticMethod);
3311 let last_name = path.segments.last().unwrap().identifier.name;
3312 let mut msg = match self.find_fallback_in_self_type(last_name) {
3314 // limit search to 5 to reduce the number
3315 // of stupid suggestions
3316 match self.find_best_match(&path_name) {
3317 SuggestionType::Macro(s) => {
3318 format!("the macro `{}`", s)
3320 SuggestionType::Function(s) => format!("`{}`", s),
3321 SuggestionType::NotFound => "".to_string(),
3324 Field => format!("`self.{}`", path_name),
3326 TraitItem => format!("to call `self.{}`", path_name),
3327 TraitMethod(path_str) |
3328 StaticMethod(path_str) =>
3329 format!("to call `{}::{}`", path_str, path_name),
3332 let mut context = UnresolvedNameContext::Other;
3333 if !msg.is_empty() {
3334 msg = format!(". Did you mean {}?", msg);
3336 // we check if this a module and if so, we display a help
3338 let name_path = path.segments.iter()
3339 .map(|seg| seg.identifier.name)
3340 .collect::<Vec<_>>();
3341 let current_module = self.current_module;
3343 match self.resolve_module_path(current_module,
3348 context = UnresolvedNameContext::PathIsMod(expr.id);
3356 ResolutionError::UnresolvedName(
3357 &path_name, &msg, context));
3363 intravisit::walk_expr(self, expr);
3366 ExprStruct(ref path, _, _) => {
3367 // Resolve the path to the structure it goes to. We don't
3368 // check to ensure that the path is actually a structure; that
3369 // is checked later during typeck.
3370 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3371 Some(definition) => self.record_def(expr.id, definition),
3373 debug!("(resolving expression) didn't find struct def",);
3377 ResolutionError::DoesNotNameAStruct(
3378 &path_names_to_string(path, 0))
3380 self.record_def(expr.id, err_path_resolution());
3384 intravisit::walk_expr(self, expr);
3387 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3388 self.with_label_rib(|this| {
3389 let def_like = DlDef(Def::Label(expr.id));
3392 let rib = this.label_ribs.last_mut().unwrap();
3393 rib.bindings.insert(label.name, def_like);
3396 intravisit::walk_expr(this, expr);
3400 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3401 match self.search_label(label.node.name) {
3403 self.record_def(expr.id, err_path_resolution());
3406 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3408 Some(DlDef(def @ Def::Label(_))) => {
3409 // Since this def is a label, it is never read.
3410 self.record_def(expr.id,
3413 last_private: LastMod(AllPublic),
3418 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3424 intravisit::walk_expr(self, expr);
3429 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3431 ExprField(_, name) => {
3432 // FIXME(#6890): Even though you can't treat a method like a
3433 // field, we need to add any trait methods we find that match
3434 // the field name so that we can do some nice error reporting
3435 // later on in typeck.
3436 let traits = self.get_traits_containing_item(name.node);
3437 self.trait_map.insert(expr.id, traits);
3439 ExprMethodCall(name, _, _) => {
3440 debug!("(recording candidate traits for expr) recording traits for {}",
3442 let traits = self.get_traits_containing_item(name.node);
3443 self.trait_map.insert(expr.id, traits);
3451 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3452 debug!("(getting traits containing item) looking for '{}'", name);
3454 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3455 debug!("(adding trait info) found trait {:?} for method '{}'",
3458 found_traits.push(trait_def_id);
3461 let mut found_traits = Vec::new();
3462 let mut search_module = self.current_module;
3464 // Look for the current trait.
3465 match self.current_trait_ref {
3466 Some((trait_def_id, _)) => {
3467 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3468 add_trait_info(&mut found_traits, trait_def_id, name);
3471 None => {} // Nothing to do.
3474 // Look for trait children.
3475 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3477 search_module.for_each_child(|_, ns, name_binding| {
3478 if ns != TypeNS { return }
3479 let trait_def_id = match name_binding.def() {
3480 Some(Def::Trait(trait_def_id)) => trait_def_id,
3481 Some(..) | None => return,
3483 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3484 add_trait_info(&mut found_traits, trait_def_id, name);
3485 let trait_name = self.get_trait_name(trait_def_id);
3486 self.record_use(trait_name, TypeNS, name_binding);
3490 // Look for shadowed traits.
3491 for binding in search_module.shadowed_traits.borrow().iter() {
3492 let did = binding.def().unwrap().def_id();
3493 if self.trait_item_map.contains_key(&(name, did)) {
3494 add_trait_info(&mut found_traits, did, name);
3495 let trait_name = self.get_trait_name(did);
3496 self.record_use(trait_name, TypeNS, binding);
3500 match search_module.parent_link {
3501 NoParentLink | ModuleParentLink(..) => break,
3502 BlockParentLink(parent_module, _) => {
3503 search_module = parent_module;
3511 /// When name resolution fails, this method can be used to look up candidate
3512 /// entities with the expected name. It allows filtering them using the
3513 /// supplied predicate (which should be used to only accept the types of
3514 /// definitions expected e.g. traits). The lookup spans across all crates.
3516 /// NOTE: The method does not look into imports, but this is not a problem,
3517 /// since we report the definitions (thus, the de-aliased imports).
3518 fn lookup_candidates<FilterFn>(&mut self,
3520 namespace: Namespace,
3521 filter_fn: FilterFn) -> SuggestedCandidates
3522 where FilterFn: Fn(Def) -> bool {
3524 let mut lookup_results = Vec::new();
3525 let mut worklist = Vec::new();
3526 worklist.push((self.graph_root, Vec::new(), false));
3528 while let Some((in_module,
3530 in_module_is_extern)) = worklist.pop() {
3531 build_reduced_graph::populate_module_if_necessary(self, &in_module);
3533 in_module.for_each_child(|name, ns, name_binding| {
3535 // avoid imports entirely
3536 if name_binding.is_import() { return; }
3538 // collect results based on the filter function
3539 if let Some(def) = name_binding.def() {
3540 if name == lookup_name && ns == namespace && filter_fn(def) {
3542 let ident = hir::Ident::from_name(name);
3543 let params = PathParameters::none();
3544 let segment = PathSegment {
3548 let span = name_binding.span.unwrap_or(syntax::codemap::DUMMY_SP);
3549 let mut segms = path_segments.clone();
3550 segms.push(segment);
3551 let segms = HirVec::from_vec(segms);
3557 // the entity is accessible in the following cases:
3558 // 1. if it's defined in the same crate, it's always
3559 // accessible (since private entities can be made public)
3560 // 2. if it's defined in another crate, it's accessible
3561 // only if both the module is public and the entity is
3562 // declared as public (due to pruning, we don't explore
3563 // outside crate private modules => no need to check this)
3564 if !in_module_is_extern || name_binding.is_public() {
3565 lookup_results.push(path);
3570 // collect submodules to explore
3571 if let Some(module) = name_binding.module() {
3573 let path_segments = match module.parent_link {
3574 NoParentLink => path_segments.clone(),
3575 ModuleParentLink(_, name) => {
3576 let mut paths = path_segments.clone();
3577 let ident = hir::Ident::from_name(name);
3578 let params = PathParameters::none();
3579 let segm = PathSegment {
3586 _ => unreachable!(),
3589 if !in_module_is_extern || name_binding.is_public() {
3590 // add the module to the lookup
3591 let is_extern = in_module_is_extern || module.is_extern_crate;
3592 worklist.push((module, path_segments, is_extern));
3598 SuggestedCandidates {
3599 name: lookup_name.as_str().to_string(),
3600 candidates: lookup_results,
3604 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3605 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3606 assert!(match resolution.last_private {
3607 LastImport{..} => false,
3610 "Import should only be used for `use` directives");
3612 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3613 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3614 self.session.span_bug(span,
3615 &format!("path resolved multiple times ({:?} before, {:?} now)",
3621 fn enforce_default_binding_mode(&mut self,
3623 pat_binding_mode: BindingMode,
3625 match pat_binding_mode {
3626 BindByValue(_) => {}
3630 ResolutionError::CannotUseRefBindingModeWith(descr));
3637 fn names_to_string(names: &[Name]) -> String {
3638 let mut first = true;
3639 let mut result = String::new();
3644 result.push_str("::")
3646 result.push_str(&name.as_str());
3651 fn path_names_to_string(path: &Path, depth: usize) -> String {
3652 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3654 .map(|seg| seg.identifier.name)
3656 names_to_string(&names[..])
3659 /// When an entity with a given name is not available in scope, we search for
3660 /// entities with that name in all crates. This method allows outputting the
3661 /// results of this search in a programmer-friendly way
3662 fn show_candidates(session: &mut DiagnosticBuilder,
3663 span: syntax::codemap::Span,
3664 candidates: &SuggestedCandidates) {
3666 let paths = &candidates.candidates;
3668 if paths.len() > 0 {
3669 // don't show more than MAX_CANDIDATES results, so
3670 // we're consistent with the trait suggestions
3671 const MAX_CANDIDATES: usize = 5;
3673 // we want consistent results across executions, but candidates are produced
3674 // by iterating through a hash map, so make sure they are ordered:
3675 let mut path_strings: Vec<_> = paths.into_iter()
3676 .map(|p| path_names_to_string(&p, 0))
3678 path_strings.sort();
3680 // behave differently based on how many candidates we have:
3681 if !paths.is_empty() {
3682 if paths.len() == 1 {
3683 session.fileline_help(
3685 &format!("you can to import it into scope: `use {};`.",
3689 session.fileline_help(span, "you can import several candidates \
3690 into scope (`use ...;`):");
3691 let count = path_strings.len() as isize - MAX_CANDIDATES as isize + 1;
3693 for (idx, path_string) in path_strings.iter().enumerate() {
3694 if idx == MAX_CANDIDATES - 1 && count > 1 {
3695 session.fileline_help(
3697 &format!(" and {} other candidates", count).to_string(),
3701 session.fileline_help(
3703 &format!(" `{}`", path_string).to_string(),
3711 session.fileline_help(
3713 &format!("no candidates by the name of `{}` found in your \
3714 project; maybe you misspelled the name or forgot to import \
3715 an external crate?", candidates.name.to_string()),
3720 /// A somewhat inefficient routine to obtain the name of a module.
3721 fn module_to_string<'a>(module: Module<'a>) -> String {
3722 let mut names = Vec::new();
3724 fn collect_mod<'a>(names: &mut Vec<ast::Name>, module: Module<'a>) {
3725 match module.parent_link {
3727 ModuleParentLink(ref module, name) => {
3729 collect_mod(names, module);
3731 BlockParentLink(ref module, _) => {
3732 // danger, shouldn't be ident?
3733 names.push(special_idents::opaque.name);
3734 collect_mod(names, module);
3738 collect_mod(&mut names, module);
3740 if names.is_empty() {
3741 return "???".to_string();
3743 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3746 fn err_path_resolution() -> PathResolution {
3749 last_private: LastMod(AllPublic),
3755 pub struct CrateMap {
3756 pub def_map: RefCell<DefMap>,
3757 pub freevars: FreevarMap,
3758 pub export_map: ExportMap,
3759 pub trait_map: TraitMap,
3760 pub external_exports: ExternalExports,
3761 pub glob_map: Option<GlobMap>,
3764 #[derive(PartialEq,Copy, Clone)]
3765 pub enum MakeGlobMap {
3770 /// Entry point to crate resolution.
3771 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3772 ast_map: &'a hir_map::Map<'tcx>,
3773 make_glob_map: MakeGlobMap)
3775 // Currently, we ignore the name resolution data structures for
3776 // the purposes of dependency tracking. Instead we will run name
3777 // resolution and include its output in the hash of each item,
3778 // much like we do for macro expansion. In other words, the hash
3779 // reflects not just its contents but the results of name
3780 // resolution on those contents. Hopefully we'll push this back at
3782 let _task = ast_map.dep_graph.in_task(DepNode::Resolve);
3784 let krate = ast_map.krate();
3785 let arenas = Resolver::arenas();
3786 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3788 resolver.resolve_crate(krate);
3790 check_unused::check_crate(&mut resolver, krate);
3793 def_map: resolver.def_map,
3794 freevars: resolver.freevars,
3795 export_map: resolver.export_map,
3796 trait_map: resolver.trait_map,
3797 external_exports: resolver.external_exports,
3798 glob_map: if resolver.make_glob_map {
3799 Some(resolver.glob_map)
3806 /// Builds a name resolution walker to be used within this module,
3807 /// or used externally, with an optional callback function.
3809 /// The callback takes a &mut bool which allows callbacks to end a
3810 /// walk when set to true, passing through the rest of the walk, while
3811 /// preserving the ribs + current module. This allows resolve_path
3812 /// calls to be made with the correct scope info. The node in the
3813 /// callback corresponds to the current node in the walk.
3814 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3815 ast_map: &'a hir_map::Map<'tcx>,
3817 make_glob_map: MakeGlobMap,
3818 arenas: &'a ResolverArenas<'a>,
3819 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3820 -> Resolver<'a, 'tcx> {
3821 let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
3823 resolver.callback = callback;
3825 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3827 resolve_imports::resolve_imports(&mut resolver);
3832 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }