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/")]
19 #![feature(associated_consts)]
20 #![feature(borrow_state)]
21 #![feature(rustc_diagnostic_macros)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
31 extern crate rustc_bitflags;
32 extern crate rustc_front;
36 use self::PatternBindingMode::*;
37 use self::Namespace::*;
38 use self::NamespaceResult::*;
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::NameSearchType::*;
47 use self::BareIdentifierPatternResolution::*;
48 use self::ParentLink::*;
49 use self::FallbackChecks::*;
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};
64 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
65 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
66 use syntax::attr::AttrMetaMethods;
67 use syntax::parse::token::{self, special_names, special_idents};
68 use syntax::codemap::{self, Span, Pos};
69 use syntax::util::lev_distance::{lev_distance, max_suggestion_distance};
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, 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, PatEnum, PatIdent, PatLit, PatQPath};
84 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
85 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
86 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
87 use rustc_front::util::walk_pat;
89 use std::collections::{HashMap, HashSet};
90 use std::cell::{Cell, RefCell};
92 use std::mem::replace;
93 use std::rc::{Rc, Weak};
96 use resolve_imports::{Target, ImportDirective, ImportResolutionPerNamespace};
97 use resolve_imports::Shadowable;
99 // NB: This module needs to be declared first so diagnostics are
100 // registered before they are used.
105 mod build_reduced_graph;
108 // Perform the callback, not walking deeper if the return is true
109 macro_rules! execute_callback {
110 ($node: expr, $walker: expr) => (
111 if let Some(ref callback) = $walker.callback {
112 if callback($node, &mut $walker.resolved) {
119 enum SuggestionType {
125 pub enum ResolutionError<'a> {
126 /// error E0401: can't use type parameters from outer function
127 TypeParametersFromOuterFunction,
128 /// error E0402: cannot use an outer type parameter in this context
129 OuterTypeParameterContext,
130 /// error E0403: the name is already used for a type parameter in this type parameter list
131 NameAlreadyUsedInTypeParameterList(Name),
132 /// error E0404: is not a trait
133 IsNotATrait(&'a str),
134 /// error E0405: use of undeclared trait name
135 UndeclaredTraitName(&'a str),
136 /// error E0406: undeclared associated type
137 UndeclaredAssociatedType,
138 /// error E0407: method is not a member of trait
139 MethodNotMemberOfTrait(Name, &'a str),
140 /// error E0437: type is not a member of trait
141 TypeNotMemberOfTrait(Name, &'a str),
142 /// error E0438: const is not a member of trait
143 ConstNotMemberOfTrait(Name, &'a str),
144 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
145 VariableNotBoundInPattern(Name, usize),
146 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
147 VariableBoundWithDifferentMode(Name, usize),
148 /// error E0410: variable from pattern is not bound in pattern #1
149 VariableNotBoundInParentPattern(Name, usize),
150 /// error E0411: use of `Self` outside of an impl or trait
151 SelfUsedOutsideImplOrTrait,
152 /// error E0412: use of undeclared
153 UseOfUndeclared(&'a str, &'a str),
154 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
155 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
156 /// error E0414: only irrefutable patterns allowed here
157 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
158 /// error E0415: identifier is bound more than once in this parameter list
159 IdentifierBoundMoreThanOnceInParameterList(&'a str),
160 /// error E0416: identifier is bound more than once in the same pattern
161 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
162 /// error E0417: static variables cannot be referenced in a pattern
163 StaticVariableReference,
164 /// error E0418: is not an enum variant, struct or const
165 NotAnEnumVariantStructOrConst(&'a str),
166 /// error E0419: unresolved enum variant, struct or const
167 UnresolvedEnumVariantStructOrConst(&'a str),
168 /// error E0420: is not an associated const
169 NotAnAssociatedConst(&'a str),
170 /// error E0421: unresolved associated const
171 UnresolvedAssociatedConst(&'a str),
172 /// error E0422: does not name a struct
173 DoesNotNameAStruct(&'a str),
174 /// error E0423: is a struct variant name, but this expression uses it like a function name
175 StructVariantUsedAsFunction(&'a str),
176 /// error E0424: `self` is not available in a static method
177 SelfNotAvailableInStaticMethod,
178 /// error E0425: unresolved name
179 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
180 /// error E0426: use of undeclared label
181 UndeclaredLabel(&'a str),
182 /// error E0427: cannot use `ref` binding mode with ...
183 CannotUseRefBindingModeWith(&'a str),
184 /// error E0428: duplicate definition
185 DuplicateDefinition(&'a str, Name),
186 /// error E0429: `self` imports are only allowed within a { } list
187 SelfImportsOnlyAllowedWithin,
188 /// error E0430: `self` import can only appear once in the list
189 SelfImportCanOnlyAppearOnceInTheList,
190 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
191 SelfImportOnlyInImportListWithNonEmptyPrefix,
192 /// error E0432: unresolved import
193 UnresolvedImport(Option<(&'a str, &'a str)>),
194 /// error E0433: failed to resolve
195 FailedToResolve(&'a str),
196 /// error E0434: can't capture dynamic environment in a fn item
197 CannotCaptureDynamicEnvironmentInFnItem,
198 /// error E0435: attempt to use a non-constant value in a constant
199 AttemptToUseNonConstantValueInConstant,
202 /// Context of where `ResolutionError::UnresolvedName` arose.
203 #[derive(Clone, PartialEq, Eq, Debug)]
204 pub enum UnresolvedNameContext {
205 /// `PathIsMod(id)` indicates that a given path, used in
206 /// expression context, actually resolved to a module rather than
207 /// a value. The `id` attached to the variant is the node id of
208 /// the erroneous path expression.
209 PathIsMod(ast::NodeId),
211 /// `Other` means we have no extra information about the context
212 /// of the unresolved name error. (Maybe we could eliminate all
213 /// such cases; but for now, this is an information-free default.)
217 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
218 span: syntax::codemap::Span,
219 resolution_error: ResolutionError<'b>) {
220 if !resolver.emit_errors {
223 match resolution_error {
224 ResolutionError::TypeParametersFromOuterFunction => {
225 span_err!(resolver.session,
228 "can't use type parameters from outer function; try using a local type \
231 ResolutionError::OuterTypeParameterContext => {
232 span_err!(resolver.session,
235 "cannot use an outer type parameter in this context");
237 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
238 span_err!(resolver.session,
241 "the name `{}` is already used for a type parameter in this type parameter \
245 ResolutionError::IsNotATrait(name) => {
246 span_err!(resolver.session, span, E0404, "`{}` is not a trait", name);
248 ResolutionError::UndeclaredTraitName(name) => {
249 span_err!(resolver.session,
252 "use of undeclared trait name `{}`",
255 ResolutionError::UndeclaredAssociatedType => {
256 span_err!(resolver.session, span, E0406, "undeclared associated type");
258 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
259 span_err!(resolver.session,
262 "method `{}` is not a member of trait `{}`",
266 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
267 span_err!(resolver.session,
270 "type `{}` is not a member of trait `{}`",
274 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
275 span_err!(resolver.session,
278 "const `{}` is not a member of trait `{}`",
282 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
283 span_err!(resolver.session,
286 "variable `{}` from pattern #1 is not bound in pattern #{}",
290 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
291 span_err!(resolver.session,
294 "variable `{}` is bound with different mode in pattern #{} than in pattern \
299 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
300 span_err!(resolver.session,
303 "variable `{}` from pattern #{} is not bound in pattern #1",
307 ResolutionError::SelfUsedOutsideImplOrTrait => {
308 span_err!(resolver.session,
311 "use of `Self` outside of an impl or trait");
313 ResolutionError::UseOfUndeclared(kind, name) => {
314 span_err!(resolver.session,
317 "use of undeclared {} `{}`",
321 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
322 span_err!(resolver.session,
325 "declaration of `{}` shadows an enum variant or unit-like struct in scope",
328 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
329 span_err!(resolver.session,
332 "only irrefutable patterns allowed here");
333 resolver.session.span_note(span,
334 "there already is a constant in scope sharing the same \
335 name as this pattern");
336 if let Some(sp) = resolver.ast_map.span_if_local(did) {
337 resolver.session.span_note(sp, "constant defined here");
339 if let Some(directive) = resolver.current_module
343 let item = resolver.ast_map.expect_item(directive.value_ns.id);
344 resolver.session.span_note(item.span, "constant imported here");
347 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
348 span_err!(resolver.session,
351 "identifier `{}` is bound more than once in this parameter list",
354 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
355 span_err!(resolver.session,
358 "identifier `{}` is bound more than once in the same pattern",
361 ResolutionError::StaticVariableReference => {
362 span_err!(resolver.session,
365 "static variables cannot be referenced in a pattern, use a `const` instead");
367 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
368 span_err!(resolver.session,
371 "`{}` is not an enum variant, struct or const",
374 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
375 span_err!(resolver.session,
378 "unresolved enum variant, struct or const `{}`",
381 ResolutionError::NotAnAssociatedConst(name) => {
382 span_err!(resolver.session,
385 "`{}` is not an associated const",
388 ResolutionError::UnresolvedAssociatedConst(name) => {
389 span_err!(resolver.session,
392 "unresolved associated const `{}`",
395 ResolutionError::DoesNotNameAStruct(name) => {
396 span_err!(resolver.session,
399 "`{}` does not name a structure",
402 ResolutionError::StructVariantUsedAsFunction(path_name) => {
403 span_err!(resolver.session,
406 "`{}` is the name of a struct or struct variant, but this expression uses \
407 it like a function name",
410 ResolutionError::SelfNotAvailableInStaticMethod => {
411 span_err!(resolver.session,
414 "`self` is not available in a static method. Maybe a `self` argument is \
417 ResolutionError::UnresolvedName(path, msg, context) => {
418 span_err!(resolver.session,
421 "unresolved name `{}`{}",
426 UnresolvedNameContext::Other => {} // no help available
427 UnresolvedNameContext::PathIsMod(id) => {
428 let mut help_msg = String::new();
429 let parent_id = resolver.ast_map.get_parent_node(id);
430 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
432 ExprField(_, ident) => {
433 help_msg = format!("To reference an item from the \
434 `{module}` module, use \
435 `{module}::{ident}`",
440 ExprMethodCall(ident, _, _) => {
441 help_msg = format!("To call a function from the \
442 `{module}` module, use \
443 `{module}::{ident}(..)`",
448 _ => {} // no help available
452 if !help_msg.is_empty() {
453 resolver.session.fileline_help(span, &help_msg);
458 ResolutionError::UndeclaredLabel(name) => {
459 span_err!(resolver.session,
462 "use of undeclared label `{}`",
465 ResolutionError::CannotUseRefBindingModeWith(descr) => {
466 span_err!(resolver.session,
469 "cannot use `ref` binding mode with {}",
472 ResolutionError::DuplicateDefinition(namespace, name) => {
473 span_err!(resolver.session,
476 "duplicate definition of {} `{}`",
480 ResolutionError::SelfImportsOnlyAllowedWithin => {
481 span_err!(resolver.session,
485 "`self` imports are only allowed within a { } list");
487 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
488 span_err!(resolver.session,
491 "`self` import can only appear once in the list");
493 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
494 span_err!(resolver.session,
497 "`self` import can only appear in an import list with a non-empty prefix");
499 ResolutionError::UnresolvedImport(name) => {
500 let msg = match name {
501 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
502 None => "unresolved import".to_owned(),
504 span_err!(resolver.session, span, E0432, "{}", msg);
506 ResolutionError::FailedToResolve(msg) => {
507 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
509 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
510 span_err!(resolver.session,
514 "can't capture dynamic environment in a fn item; use the || { ... } \
515 closure form instead");
517 ResolutionError::AttemptToUseNonConstantValueInConstant => {
518 span_err!(resolver.session,
521 "attempt to use a non-constant value in a constant");
526 #[derive(Copy, Clone)]
529 binding_mode: BindingMode,
532 // Map from the name in a pattern to its binding mode.
533 type BindingMap = HashMap<Name, BindingInfo>;
535 #[derive(Copy, Clone, PartialEq)]
536 enum PatternBindingMode {
538 LocalIrrefutableMode,
539 ArgumentIrrefutableMode,
542 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
548 /// A NamespaceResult represents the result of resolving an import in
549 /// a particular namespace. The result is either definitely-resolved,
550 /// definitely- unresolved, or unknown.
552 enum NamespaceResult {
553 /// Means that resolve hasn't gathered enough information yet to determine
554 /// whether the name is bound in this namespace. (That is, it hasn't
555 /// resolved all `use` directives yet.)
557 /// Means that resolve has determined that the name is definitely
558 /// not bound in the namespace.
560 /// Means that resolve has determined that the name is bound in the Module
561 /// argument, and specified by the NameBinding argument.
562 BoundResult(Rc<Module>, NameBinding),
565 impl NamespaceResult {
566 fn is_unknown(&self) -> bool {
568 UnknownResult => true,
572 fn is_unbound(&self) -> bool {
574 UnboundResult => true,
580 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
581 fn visit_nested_item(&mut self, item: hir::ItemId) {
582 self.visit_item(self.ast_map.expect_item(item.id))
584 fn visit_item(&mut self, item: &Item) {
585 execute_callback!(hir_map::Node::NodeItem(item), self);
586 self.resolve_item(item);
588 fn visit_arm(&mut self, arm: &Arm) {
589 self.resolve_arm(arm);
591 fn visit_block(&mut self, block: &Block) {
592 execute_callback!(hir_map::Node::NodeBlock(block), self);
593 self.resolve_block(block);
595 fn visit_expr(&mut self, expr: &Expr) {
596 execute_callback!(hir_map::Node::NodeExpr(expr), self);
597 self.resolve_expr(expr);
599 fn visit_local(&mut self, local: &Local) {
600 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
601 self.resolve_local(local);
603 fn visit_ty(&mut self, ty: &Ty) {
604 self.resolve_type(ty);
606 fn visit_generics(&mut self, generics: &Generics) {
607 self.resolve_generics(generics);
609 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
610 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
611 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
613 // error already reported
614 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
617 intravisit::walk_poly_trait_ref(self, tref, m);
619 fn visit_variant(&mut self,
620 variant: &hir::Variant,
622 item_id: ast::NodeId) {
623 execute_callback!(hir_map::Node::NodeVariant(variant), self);
624 if let Some(ref dis_expr) = variant.node.disr_expr {
625 // resolve the discriminator expr as a constant
626 self.with_constant_rib(|this| {
627 this.visit_expr(dis_expr);
631 // `intravisit::walk_variant` without the discriminant expression.
632 self.visit_variant_data(&variant.node.data,
638 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
639 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
640 let type_parameters = match foreign_item.node {
641 ForeignItemFn(_, ref generics) => {
642 HasTypeParameters(generics, FnSpace, ItemRibKind)
644 ForeignItemStatic(..) => NoTypeParameters,
646 self.with_type_parameter_rib(type_parameters, |this| {
647 intravisit::walk_foreign_item(this, foreign_item);
650 fn visit_fn(&mut self,
651 function_kind: FnKind<'v>,
652 declaration: &'v FnDecl,
656 let rib_kind = match function_kind {
657 FnKind::ItemFn(_, generics, _, _, _, _) => {
658 self.visit_generics(generics);
661 FnKind::Method(_, sig, _) => {
662 self.visit_generics(&sig.generics);
663 self.visit_explicit_self(&sig.explicit_self);
666 FnKind::Closure => ClosureRibKind(node_id),
668 self.resolve_function(rib_kind, declaration, block);
672 type ErrorMessage = Option<(Span, String)>;
674 enum ResolveResult<T> {
675 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
676 Indeterminate, // Couldn't determine due to unresolved globs.
677 Success(T), // Successfully resolved the import.
680 impl<T> ResolveResult<T> {
681 fn success(&self) -> bool {
689 enum FallbackSuggestion {
694 StaticMethod(String),
698 #[derive(Copy, Clone)]
699 enum TypeParameters<'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 (`DefLocal`) to upvars (`DefUpvar`).
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.
736 #[derive(Copy, Clone)]
737 enum UseLexicalScopeFlag {
742 enum ModulePrefixResult {
744 PrefixFound(Rc<Module>, usize),
747 #[derive(Copy, Clone)]
748 enum AssocItemResolveResult {
749 /// Syntax such as `<T>::item`, which can't be resolved until type
752 /// We should have been able to resolve the associated item.
753 ResolveAttempt(Option<PathResolution>),
756 #[derive(Copy, Clone, PartialEq)]
757 enum NameSearchType {
758 /// We're doing a name search in order to resolve a `use` directive.
761 /// We're doing a name search in order to resolve a path type, a path
762 /// expression, or a path pattern.
766 #[derive(Copy, Clone)]
767 enum BareIdentifierPatternResolution {
768 FoundStructOrEnumVariant(Def, LastPrivate),
769 FoundConst(Def, LastPrivate, Name),
770 BareIdentifierPatternUnresolved,
776 bindings: HashMap<Name, DefLike>,
781 fn new(kind: RibKind) -> Rib {
783 bindings: HashMap::new(),
789 /// A definition along with the index of the rib it was found on
791 ribs: Option<(Namespace, usize)>,
796 fn from_def(def: Def) -> Self {
804 /// The link from a module up to its nearest parent node.
805 #[derive(Clone,Debug)]
808 ModuleParentLink(Weak<Module>, Name),
809 BlockParentLink(Weak<Module>, NodeId),
812 /// One node in the tree of modules.
814 parent_link: ParentLink,
815 def: Cell<Option<Def>>,
818 children: RefCell<HashMap<Name, NameBindings>>,
819 imports: RefCell<Vec<ImportDirective>>,
821 // The external module children of this node that were declared with
823 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
825 // The anonymous children of this node. Anonymous children are pseudo-
826 // modules that are implicitly created around items contained within
829 // For example, if we have this:
837 // There will be an anonymous module created around `g` with the ID of the
838 // entry block for `f`.
839 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
841 // The status of resolving each import in this module.
842 import_resolutions: RefCell<HashMap<Name, ImportResolutionPerNamespace>>,
844 // The number of unresolved globs that this module exports.
845 glob_count: Cell<usize>,
847 // The number of unresolved pub imports (both regular and globs) in this module
848 pub_count: Cell<usize>,
850 // The number of unresolved pub glob imports in this module
851 pub_glob_count: Cell<usize>,
853 // The index of the import we're resolving.
854 resolved_import_count: Cell<usize>,
856 // Whether this module is populated. If not populated, any attempt to
857 // access the children must be preceded with a
858 // `populate_module_if_necessary` call.
859 populated: Cell<bool>,
863 fn new(parent_link: ParentLink,
869 parent_link: parent_link,
871 is_public: is_public,
872 children: RefCell::new(HashMap::new()),
873 imports: RefCell::new(Vec::new()),
874 external_module_children: RefCell::new(HashMap::new()),
875 anonymous_children: RefCell::new(NodeMap()),
876 import_resolutions: RefCell::new(HashMap::new()),
877 glob_count: Cell::new(0),
878 pub_count: Cell::new(0),
879 pub_glob_count: Cell::new(0),
880 resolved_import_count: Cell::new(0),
881 populated: Cell::new(!external),
885 fn def_id(&self) -> Option<DefId> {
886 self.def.get().as_ref().map(Def::def_id)
889 fn is_normal(&self) -> bool {
890 match self.def.get() {
891 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
896 fn is_trait(&self) -> bool {
897 match self.def.get() {
898 Some(DefTrait(_)) => true,
903 fn all_imports_resolved(&self) -> bool {
904 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
905 // it is currently being resolved ! so nope
908 self.imports.borrow().len() == self.resolved_import_count.get()
914 pub fn inc_glob_count(&self) {
915 self.glob_count.set(self.glob_count.get() + 1);
917 pub fn dec_glob_count(&self) {
918 assert!(self.glob_count.get() > 0);
919 self.glob_count.set(self.glob_count.get() - 1);
921 pub fn inc_pub_count(&self) {
922 self.pub_count.set(self.pub_count.get() + 1);
924 pub fn dec_pub_count(&self) {
925 assert!(self.pub_count.get() > 0);
926 self.pub_count.set(self.pub_count.get() - 1);
928 pub fn inc_pub_glob_count(&self) {
929 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
931 pub fn dec_pub_glob_count(&self) {
932 assert!(self.pub_glob_count.get() > 0);
933 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
937 impl fmt::Debug for Module {
938 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
952 flags DefModifiers: u8 {
953 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
954 // or `use Enum::*` to work on private enums.
955 const PUBLIC = 1 << 0,
956 const IMPORTABLE = 1 << 1,
957 // Variants are considered `PUBLIC`, but some of them live in private enums.
958 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
959 const PRIVATE_VARIANT = 1 << 2,
963 // Records a possibly-private value, type, or module definition.
966 modifiers: DefModifiers, // see note in ImportResolutionPerNamespace about how to use this
967 def_or_module: DefOrModule,
978 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
979 let modifiers = if module.is_public {
982 DefModifiers::empty()
983 } | DefModifiers::IMPORTABLE;
985 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
988 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
989 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
992 fn module(&self) -> Option<Rc<Module>> {
993 match self.def_or_module {
994 DefOrModule::Module(ref module) => Some(module.clone()),
995 DefOrModule::Def(_) => None,
999 fn def(&self) -> Option<Def> {
1000 match self.def_or_module {
1001 DefOrModule::Def(def) => Some(def),
1002 DefOrModule::Module(ref module) => module.def.get(),
1007 // Records at most one definition that a name in a namespace is bound to
1008 #[derive(Clone,Debug)]
1009 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
1013 NameBinding(Rc::new(RefCell::new(None)))
1016 fn create_from_module(module: Rc<Module>) -> Self {
1017 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
1020 fn set(&self, ns_def: NsDef) {
1021 *self.0.borrow_mut() = Some(ns_def);
1024 fn set_modifiers(&self, modifiers: DefModifiers) {
1025 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
1026 ns_def.modifiers = modifiers
1030 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> {
1034 // Lifted versions of the NsDef methods and fields
1035 fn def(&self) -> Option<Def> {
1036 self.borrow().as_ref().and_then(NsDef::def)
1038 fn module(&self) -> Option<Rc<Module>> {
1039 self.borrow().as_ref().and_then(NsDef::module)
1041 fn span(&self) -> Option<Span> {
1042 self.borrow().as_ref().and_then(|def| def.span)
1044 fn modifiers(&self) -> Option<DefModifiers> {
1045 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
1048 fn defined(&self) -> bool {
1049 self.borrow().is_some()
1052 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1053 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1056 fn is_public(&self) -> bool {
1057 self.defined_with(DefModifiers::PUBLIC)
1060 fn def_and_lp(&self) -> (Def, LastPrivate) {
1061 let def = self.def().unwrap();
1062 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1066 // Records the definitions (at most one for each namespace) that a name is
1068 #[derive(Clone,Debug)]
1069 pub struct NameBindings {
1070 type_ns: NameBinding, // < Meaning in type namespace.
1071 value_ns: NameBinding, // < Meaning in value namespace.
1074 impl ::std::ops::Index<Namespace> for NameBindings {
1075 type Output = NameBinding;
1076 fn index(&self, namespace: Namespace) -> &NameBinding {
1077 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1082 fn new() -> NameBindings {
1084 type_ns: NameBinding::new(),
1085 value_ns: NameBinding::new(),
1089 /// Creates a new module in this set of name bindings.
1090 fn define_module(&self, module: Rc<Module>, sp: Span) {
1091 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1094 /// Records a type definition.
1095 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1096 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1097 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1100 /// Records a value definition.
1101 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1102 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1103 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1107 /// Interns the names of the primitive types.
1108 struct PrimitiveTypeTable {
1109 primitive_types: HashMap<Name, PrimTy>,
1112 impl PrimitiveTypeTable {
1113 fn new() -> PrimitiveTypeTable {
1114 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1116 table.intern("bool", TyBool);
1117 table.intern("char", TyChar);
1118 table.intern("f32", TyFloat(TyF32));
1119 table.intern("f64", TyFloat(TyF64));
1120 table.intern("isize", TyInt(TyIs));
1121 table.intern("i8", TyInt(TyI8));
1122 table.intern("i16", TyInt(TyI16));
1123 table.intern("i32", TyInt(TyI32));
1124 table.intern("i64", TyInt(TyI64));
1125 table.intern("str", TyStr);
1126 table.intern("usize", TyUint(TyUs));
1127 table.intern("u8", TyUint(TyU8));
1128 table.intern("u16", TyUint(TyU16));
1129 table.intern("u32", TyUint(TyU32));
1130 table.intern("u64", TyUint(TyU64));
1135 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1136 self.primitive_types.insert(token::intern(string), primitive_type);
1140 /// The main resolver class.
1141 pub struct Resolver<'a, 'tcx: 'a> {
1142 session: &'a Session,
1144 ast_map: &'a hir_map::Map<'tcx>,
1146 graph_root: Rc<Module>,
1148 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1150 structs: FnvHashMap<DefId, Vec<Name>>,
1152 // The number of imports that are currently unresolved.
1153 unresolved_imports: usize,
1155 // The module that represents the current item scope.
1156 current_module: Rc<Module>,
1158 // The current set of local scopes, for values.
1159 // FIXME #4948: Reuse ribs to avoid allocation.
1160 value_ribs: Vec<Rib>,
1162 // The current set of local scopes, for types.
1163 type_ribs: Vec<Rib>,
1165 // The current set of local scopes, for labels.
1166 label_ribs: Vec<Rib>,
1168 // The trait that the current context can refer to.
1169 current_trait_ref: Option<(DefId, TraitRef)>,
1171 // The current self type if inside an impl (used for better errors).
1172 current_self_type: Option<Ty>,
1174 // The idents for the primitive types.
1175 primitive_type_table: PrimitiveTypeTable,
1177 def_map: RefCell<DefMap>,
1178 freevars: FreevarMap,
1179 freevars_seen: NodeMap<NodeMap<usize>>,
1180 export_map: ExportMap,
1181 trait_map: TraitMap,
1182 external_exports: ExternalExports,
1184 // Whether or not to print error messages. Can be set to true
1185 // when getting additional info for error message suggestions,
1186 // so as to avoid printing duplicate errors
1189 make_glob_map: bool,
1190 // Maps imports to the names of items actually imported (this actually maps
1191 // all imports, but only glob imports are actually interesting).
1194 used_imports: HashSet<(NodeId, Namespace)>,
1195 used_crates: HashSet<CrateNum>,
1197 // Callback function for intercepting walks
1198 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1199 // The intention is that the callback modifies this flag.
1200 // Once set, the resolver falls out of the walk, preserving the ribs.
1204 #[derive(PartialEq)]
1205 enum FallbackChecks {
1207 OnlyTraitAndStatics,
1210 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1211 fn new(session: &'a Session,
1212 ast_map: &'a hir_map::Map<'tcx>,
1213 make_glob_map: MakeGlobMap)
1214 -> Resolver<'a, 'tcx> {
1215 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1216 let graph_root = Module::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1223 // The outermost module has def ID 0; this is not reflected in the
1225 graph_root: graph_root.clone(),
1227 trait_item_map: FnvHashMap(),
1228 structs: FnvHashMap(),
1230 unresolved_imports: 0,
1232 current_module: graph_root,
1233 value_ribs: Vec::new(),
1234 type_ribs: Vec::new(),
1235 label_ribs: Vec::new(),
1237 current_trait_ref: None,
1238 current_self_type: None,
1240 primitive_type_table: PrimitiveTypeTable::new(),
1242 def_map: RefCell::new(NodeMap()),
1243 freevars: NodeMap(),
1244 freevars_seen: NodeMap(),
1245 export_map: NodeMap(),
1246 trait_map: NodeMap(),
1247 used_imports: HashSet::new(),
1248 used_crates: HashSet::new(),
1249 external_exports: DefIdSet(),
1252 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1253 glob_map: HashMap::new(),
1261 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1262 if !self.make_glob_map {
1265 if self.glob_map.contains_key(&import_id) {
1266 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1270 let mut new_set = HashSet::new();
1271 new_set.insert(name);
1272 self.glob_map.insert(import_id, new_set);
1275 fn get_trait_name(&self, did: DefId) -> Name {
1276 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1277 self.ast_map.expect_item(node_id).name
1279 self.session.cstore.item_name(did)
1283 /// Checks that the names of external crates don't collide with other
1284 /// external crates.
1285 fn check_for_conflicts_between_external_crates(&self,
1289 if module.external_module_children.borrow().contains_key(&name) {
1290 span_err!(self.session,
1293 "an external crate named `{}` has already been imported into this module",
1298 /// Checks that the names of items don't collide with external crates.
1299 fn check_for_conflicts_between_external_crates_and_items(&self,
1303 if module.external_module_children.borrow().contains_key(&name) {
1304 span_err!(self.session,
1307 "the name `{}` conflicts with an external crate that has been imported \
1313 /// Resolves the given module path from the given root `module_`.
1314 fn resolve_module_path_from_root(&mut self,
1315 module_: Rc<Module>,
1316 module_path: &[Name],
1319 name_search_type: NameSearchType,
1321 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1322 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1323 match module.external_module_children.borrow().get(&needle) {
1324 Some(_) => Some(module.clone()),
1325 None => match module.parent_link {
1326 ModuleParentLink(ref parent, _) => {
1327 search_parent_externals(needle, &parent.upgrade().unwrap())
1334 let mut search_module = module_;
1335 let mut index = index;
1336 let module_path_len = module_path.len();
1337 let mut closest_private = lp;
1339 // Resolve the module part of the path. This does not involve looking
1340 // upward though scope chains; we simply resolve names directly in
1341 // modules as we go.
1342 while index < module_path_len {
1343 let name = module_path[index];
1344 match self.resolve_name_in_module(search_module.clone(),
1350 let segment_name = name.as_str();
1351 let module_name = module_to_string(&*search_module);
1352 let mut span = span;
1353 let msg = if "???" == &module_name[..] {
1354 span.hi = span.lo + Pos::from_usize(segment_name.len());
1356 match search_parent_externals(name, &self.current_module) {
1358 let path_str = names_to_string(module_path);
1359 let target_mod_str = module_to_string(&*module);
1360 let current_mod_str = module_to_string(&*self.current_module);
1362 let prefix = if target_mod_str == current_mod_str {
1363 "self::".to_string()
1365 format!("{}::", target_mod_str)
1368 format!("Did you mean `{}{}`?", prefix, path_str)
1370 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1373 format!("Could not find `{}` in `{}`", segment_name, module_name)
1376 return Failed(Some((span, msg)));
1378 Failed(err) => return Failed(err),
1380 debug!("(resolving module path for import) module resolution is \
1383 return Indeterminate;
1385 Success((target, used_proxy)) => {
1386 // Check to see whether there are type bindings, and, if
1387 // so, whether there is a module within.
1388 if let Some(module_def) = target.binding.module() {
1389 // track extern crates for unused_extern_crate lint
1390 if let Some(did) = module_def.def_id() {
1391 self.used_crates.insert(did.krate);
1394 search_module = module_def;
1396 // Keep track of the closest private module used
1397 // when resolving this import chain.
1398 if !used_proxy && !search_module.is_public {
1399 if let Some(did) = search_module.def_id() {
1400 closest_private = LastMod(DependsOn(did));
1404 let msg = format!("Not a module `{}`", name);
1405 return Failed(Some((span, msg)));
1413 return Success((search_module, closest_private));
1416 /// Attempts to resolve the module part of an import directive or path
1417 /// rooted at the given module.
1419 /// On success, returns the resolved module, and the closest *private*
1420 /// module found to the destination when resolving this path.
1421 fn resolve_module_path(&mut self,
1422 module_: Rc<Module>,
1423 module_path: &[Name],
1424 use_lexical_scope: UseLexicalScopeFlag,
1426 name_search_type: NameSearchType)
1427 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1428 let module_path_len = module_path.len();
1429 assert!(module_path_len > 0);
1431 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1432 names_to_string(module_path),
1433 module_to_string(&*module_));
1435 // Resolve the module prefix, if any.
1436 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1441 match module_prefix_result {
1443 let mpath = names_to_string(module_path);
1444 let mpath = &mpath[..];
1445 match mpath.rfind(':') {
1447 let msg = format!("Could not find `{}` in `{}`",
1448 // idx +- 1 to account for the
1449 // colons on either side
1452 return Failed(Some((span, msg)));
1455 return Failed(None);
1459 Failed(err) => return Failed(err),
1461 debug!("(resolving module path for import) indeterminate; bailing");
1462 return Indeterminate;
1464 Success(NoPrefixFound) => {
1465 // There was no prefix, so we're considering the first element
1466 // of the path. How we handle this depends on whether we were
1467 // instructed to use lexical scope or not.
1468 match use_lexical_scope {
1469 DontUseLexicalScope => {
1470 // This is a crate-relative path. We will start the
1471 // resolution process at index zero.
1472 search_module = self.graph_root.clone();
1474 last_private = LastMod(AllPublic);
1476 UseLexicalScope => {
1477 // This is not a crate-relative path. We resolve the
1478 // first component of the path in the current lexical
1479 // scope and then proceed to resolve below that.
1480 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1481 Failed(err) => return Failed(err),
1483 debug!("(resolving module path for import) indeterminate; bailing");
1484 return Indeterminate;
1486 Success(containing_module) => {
1487 search_module = containing_module;
1489 last_private = LastMod(AllPublic);
1495 Success(PrefixFound(ref containing_module, index)) => {
1496 search_module = containing_module.clone();
1497 start_index = index;
1498 last_private = LastMod(DependsOn(containing_module.def_id()
1503 self.resolve_module_path_from_root(search_module,
1511 /// Invariant: This must only be called during main resolution, not during
1512 /// import resolution.
1513 fn resolve_item_in_lexical_scope(&mut self,
1514 module_: Rc<Module>,
1516 namespace: Namespace,
1518 -> ResolveResult<(Target, bool)> {
1519 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1522 module_to_string(&*module_));
1524 // The current module node is handled specially. First, check for
1525 // its immediate children.
1526 build_reduced_graph::populate_module_if_necessary(self, &module_);
1528 match module_.children.borrow().get(&name) {
1529 Some(name_bindings) if name_bindings[namespace].defined() => {
1530 debug!("top name bindings succeeded");
1531 return Success((Target::new(module_.clone(),
1532 name_bindings[namespace].clone(),
1537 // Not found; continue.
1541 // Now check for its import directives. We don't have to have resolved
1542 // all its imports in the usual way; this is because chains of
1543 // adjacent import statements are processed as though they mutated the
1545 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1546 match import_resolution[namespace].target.clone() {
1548 // Not found; continue.
1549 debug!("(resolving item in lexical scope) found import resolution, but not \
1554 debug!("(resolving item in lexical scope) using import resolution");
1555 // track used imports and extern crates as well
1556 let id = import_resolution[namespace].id;
1558 self.used_imports.insert((id, namespace));
1559 self.record_import_use(id, name);
1560 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1561 self.used_crates.insert(kid);
1564 return Success((target, false));
1569 // Search for external modules.
1570 if namespace == TypeNS {
1571 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1572 let child = module_.external_module_children.borrow().get(&name).cloned();
1573 if let Some(module) = child {
1574 let name_binding = NameBinding::create_from_module(module);
1575 debug!("lower name bindings succeeded");
1576 return Success((Target::new(module_, name_binding, Shadowable::Never),
1581 // Finally, proceed up the scope chain looking for parent modules.
1582 let mut search_module = module_;
1584 // Go to the next parent.
1585 match search_module.parent_link.clone() {
1587 // No more parents. This module was unresolved.
1588 debug!("(resolving item in lexical scope) unresolved module");
1589 return Failed(None);
1591 ModuleParentLink(parent_module_node, _) => {
1592 if search_module.is_normal() {
1593 // We stop the search here.
1594 debug!("(resolving item in lexical scope) unresolved module: not \
1595 searching through module parents");
1596 return Failed(None);
1598 search_module = parent_module_node.upgrade().unwrap();
1601 BlockParentLink(ref parent_module_node, _) => {
1602 search_module = parent_module_node.upgrade().unwrap();
1606 // Resolve the name in the parent module.
1607 match self.resolve_name_in_module(search_module.clone(),
1612 Failed(Some((span, msg))) => {
1613 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1615 Failed(None) => (), // Continue up the search chain.
1617 // We couldn't see through the higher scope because of an
1618 // unresolved import higher up. Bail.
1620 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1621 return Indeterminate;
1623 Success((target, used_reexport)) => {
1624 // We found the module.
1625 debug!("(resolving item in lexical scope) found name in module, done");
1626 return Success((target, used_reexport));
1632 /// Resolves a module name in the current lexical scope.
1633 fn resolve_module_in_lexical_scope(&mut self,
1634 module_: Rc<Module>,
1636 -> ResolveResult<Rc<Module>> {
1637 // If this module is an anonymous module, resolve the item in the
1638 // lexical scope. Otherwise, resolve the item from the crate root.
1639 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS, true);
1640 match resolve_result {
1641 Success((target, _)) => {
1642 if let Some(module_def) = target.binding.module() {
1643 return Success(module_def)
1645 debug!("!!! (resolving module in lexical scope) module \
1646 wasn't actually a module!");
1647 return Failed(None);
1651 debug!("(resolving module in lexical scope) indeterminate; bailing");
1652 return Indeterminate;
1655 debug!("(resolving module in lexical scope) failed to resolve");
1661 /// Returns the nearest normal module parent of the given module.
1662 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1663 let mut module_ = module_;
1665 match module_.parent_link.clone() {
1666 NoParentLink => return None,
1667 ModuleParentLink(new_module, _) |
1668 BlockParentLink(new_module, _) => {
1669 let new_module = new_module.upgrade().unwrap();
1670 if new_module.is_normal() {
1671 return Some(new_module);
1673 module_ = new_module;
1679 /// Returns the nearest normal module parent of the given module, or the
1680 /// module itself if it is a normal module.
1681 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1682 if module_.is_normal() {
1685 match self.get_nearest_normal_module_parent(module_.clone()) {
1687 Some(new_module) => new_module,
1691 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1692 /// (b) some chain of `super::`.
1693 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1694 fn resolve_module_prefix(&mut self,
1695 module_: Rc<Module>,
1696 module_path: &[Name])
1697 -> ResolveResult<ModulePrefixResult> {
1698 // Start at the current module if we see `self` or `super`, or at the
1699 // top of the crate otherwise.
1700 let mut i = match &*module_path[0].as_str() {
1703 _ => return Success(NoPrefixFound),
1705 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1707 // Now loop through all the `super`s we find.
1708 while i < module_path.len() && "super" == module_path[i].as_str() {
1709 debug!("(resolving module prefix) resolving `super` at {}",
1710 module_to_string(&*containing_module));
1711 match self.get_nearest_normal_module_parent(containing_module) {
1712 None => return Failed(None),
1713 Some(new_module) => {
1714 containing_module = new_module;
1720 debug!("(resolving module prefix) finished resolving prefix at {}",
1721 module_to_string(&*containing_module));
1723 return Success(PrefixFound(containing_module, i));
1726 /// Attempts to resolve the supplied name in the given module for the
1727 /// given namespace. If successful, returns the target corresponding to
1730 /// The boolean returned on success is an indicator of whether this lookup
1731 /// passed through a public re-export proxy.
1732 fn resolve_name_in_module(&mut self,
1733 module_: Rc<Module>,
1735 namespace: Namespace,
1736 name_search_type: NameSearchType,
1737 allow_private_imports: bool)
1738 -> ResolveResult<(Target, bool)> {
1739 debug!("(resolving name in module) resolving `{}` in `{}`",
1741 module_to_string(&*module_));
1743 // First, check the direct children of the module.
1744 build_reduced_graph::populate_module_if_necessary(self, &module_);
1746 match module_.children.borrow().get(&name) {
1747 Some(name_bindings) if name_bindings[namespace].defined() => {
1748 debug!("(resolving name in module) found node as child");
1749 return Success((Target::new(module_.clone(),
1750 name_bindings[namespace].clone(),
1759 // Next, check the module's imports if necessary.
1761 // If this is a search of all imports, we should be done with glob
1762 // resolution at this point.
1763 if name_search_type == PathSearch {
1764 assert_eq!(module_.glob_count.get(), 0);
1767 // Check the list of resolved imports.
1768 match module_.import_resolutions.borrow().get(&name) {
1769 Some(import_resolution) if allow_private_imports ||
1770 import_resolution[namespace].is_public => {
1772 if import_resolution[namespace].is_public &&
1773 import_resolution.outstanding_references != 0 {
1774 debug!("(resolving name in module) import unresolved; bailing out");
1775 return Indeterminate;
1777 match import_resolution[namespace].target.clone() {
1779 debug!("(resolving name in module) name found, but not in namespace {:?}",
1783 debug!("(resolving name in module) resolved to import");
1784 // track used imports and extern crates as well
1785 let id = import_resolution[namespace].id;
1786 self.used_imports.insert((id, namespace));
1787 self.record_import_use(id, name);
1788 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1789 self.used_crates.insert(kid);
1791 return Success((target, true));
1795 Some(..) | None => {} // Continue.
1798 // Finally, search through external children.
1799 if namespace == TypeNS {
1800 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1801 let child = module_.external_module_children.borrow().get(&name).cloned();
1802 if let Some(module) = child {
1803 let name_binding = NameBinding::create_from_module(module);
1804 return Success((Target::new(module_, name_binding, Shadowable::Never),
1809 // We're out of luck.
1810 debug!("(resolving name in module) failed to resolve `{}`", name);
1811 return Failed(None);
1814 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1815 let index = module_.resolved_import_count.get();
1816 let imports = module_.imports.borrow();
1817 let import_count = imports.len();
1818 if index != import_count {
1820 (*imports)[index].span,
1821 ResolutionError::UnresolvedImport(None));
1824 // Descend into children and anonymous children.
1825 build_reduced_graph::populate_module_if_necessary(self, &module_);
1827 for (_, child_node) in module_.children.borrow().iter() {
1828 match child_node.type_ns.module() {
1832 Some(child_module) => {
1833 self.report_unresolved_imports(child_module);
1838 for (_, module_) in module_.anonymous_children.borrow().iter() {
1839 self.report_unresolved_imports(module_.clone());
1845 // We maintain a list of value ribs and type ribs.
1847 // Simultaneously, we keep track of the current position in the module
1848 // graph in the `current_module` pointer. When we go to resolve a name in
1849 // the value or type namespaces, we first look through all the ribs and
1850 // then query the module graph. When we resolve a name in the module
1851 // namespace, we can skip all the ribs (since nested modules are not
1852 // allowed within blocks in Rust) and jump straight to the current module
1855 // Named implementations are handled separately. When we find a method
1856 // call, we consult the module node to find all of the implementations in
1857 // scope. This information is lazily cached in the module node. We then
1858 // generate a fake "implementation scope" containing all the
1859 // implementations thus found, for compatibility with old resolve pass.
1861 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1862 where F: FnOnce(&mut Resolver)
1864 let orig_module = self.current_module.clone();
1866 // Move down in the graph.
1872 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1874 match orig_module.children.borrow().get(&name) {
1876 debug!("!!! (with scope) didn't find `{}` in `{}`",
1878 module_to_string(&*orig_module));
1880 Some(name_bindings) => {
1881 match name_bindings.type_ns.module() {
1883 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1885 module_to_string(&*orig_module));
1888 self.current_module = module_;
1898 self.current_module = orig_module;
1901 /// Searches the current set of local scopes for labels.
1902 /// Stops after meeting a closure.
1903 fn search_label(&self, name: Name) -> Option<DefLike> {
1904 for rib in self.label_ribs.iter().rev() {
1910 // Do not resolve labels across function boundary
1914 let result = rib.bindings.get(&name).cloned();
1915 if result.is_some() {
1922 fn resolve_crate(&mut self, krate: &hir::Crate) {
1923 debug!("(resolving crate) starting");
1925 intravisit::walk_crate(self, krate);
1928 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1929 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1930 span_err!(self.session,
1933 "user-defined types or type parameters cannot shadow the primitive types");
1937 fn resolve_item(&mut self, item: &Item) {
1938 let name = item.name;
1940 debug!("(resolving item) resolving {}", name);
1943 ItemEnum(_, ref generics) |
1944 ItemTy(_, ref generics) |
1945 ItemStruct(_, ref generics) => {
1946 self.check_if_primitive_type_name(name, item.span);
1948 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1949 |this| intravisit::walk_item(this, item));
1951 ItemFn(_, _, _, _, ref generics, _) => {
1952 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1953 |this| intravisit::walk_item(this, item));
1956 ItemDefaultImpl(_, ref trait_ref) => {
1957 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1959 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1960 self.resolve_implementation(generics,
1967 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1968 self.check_if_primitive_type_name(name, item.span);
1970 // Create a new rib for the trait-wide type parameters.
1971 self.with_type_parameter_rib(HasTypeParameters(generics,
1975 let local_def_id = this.ast_map.local_def_id(item.id);
1976 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1977 this.visit_generics(generics);
1978 walk_list!(this, visit_ty_param_bound, bounds);
1980 for trait_item in trait_items {
1981 match trait_item.node {
1982 hir::ConstTraitItem(_, ref default) => {
1983 // Only impose the restrictions of
1984 // ConstRibKind if there's an actual constant
1985 // expression in a provided default.
1986 if default.is_some() {
1987 this.with_constant_rib(|this| {
1988 intravisit::walk_trait_item(this, trait_item)
1991 intravisit::walk_trait_item(this, trait_item)
1994 hir::MethodTraitItem(ref sig, _) => {
1995 let type_parameters =
1996 HasTypeParameters(&sig.generics,
1999 this.with_type_parameter_rib(type_parameters, |this| {
2000 intravisit::walk_trait_item(this, trait_item)
2003 hir::TypeTraitItem(..) => {
2004 this.check_if_primitive_type_name(trait_item.name,
2006 this.with_type_parameter_rib(NoTypeParameters, |this| {
2007 intravisit::walk_trait_item(this, trait_item)
2016 ItemMod(_) | ItemForeignMod(_) => {
2017 self.with_scope(Some(name), |this| {
2018 intravisit::walk_item(this, item);
2022 ItemConst(..) | ItemStatic(..) => {
2023 self.with_constant_rib(|this| {
2024 intravisit::walk_item(this, item);
2028 ItemUse(ref view_path) => {
2029 // check for imports shadowing primitive types
2030 let check_rename = |this: &Self, id, name| {
2031 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
2032 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2033 this.check_if_primitive_type_name(name, item.span);
2039 match view_path.node {
2040 hir::ViewPathSimple(name, _) => {
2041 check_rename(self, item.id, name);
2043 hir::ViewPathList(ref prefix, ref items) => {
2045 if let Some(name) = item.node.rename() {
2046 check_rename(self, item.node.id(), name);
2050 // Resolve prefix of an import with empty braces (issue #28388)
2051 if items.is_empty() && !prefix.segments.is_empty() {
2052 match self.resolve_crate_relative_path(prefix.span,
2056 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2060 ResolutionError::FailedToResolve(
2061 &path_names_to_string(prefix, 0)));
2062 self.record_def(item.id, err_path_resolution());
2071 ItemExternCrate(_) => {
2072 // do nothing, these are just around to be encoded
2077 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2078 where F: FnOnce(&mut Resolver)
2080 match type_parameters {
2081 HasTypeParameters(generics, space, rib_kind) => {
2082 let mut function_type_rib = Rib::new(rib_kind);
2083 let mut seen_bindings = HashSet::new();
2084 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2085 let name = type_parameter.name;
2086 debug!("with_type_parameter_rib: {}", type_parameter.id);
2088 if seen_bindings.contains(&name) {
2090 type_parameter.span,
2091 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2093 seen_bindings.insert(name);
2095 // plain insert (no renaming)
2096 function_type_rib.bindings
2098 DlDef(DefTyParam(space,
2101 .local_def_id(type_parameter.id),
2104 self.type_ribs.push(function_type_rib);
2107 NoTypeParameters => {
2114 match type_parameters {
2115 HasTypeParameters(..) => {
2117 self.type_ribs.pop();
2120 NoTypeParameters => {}
2124 fn with_label_rib<F>(&mut self, f: F)
2125 where F: FnOnce(&mut Resolver)
2127 self.label_ribs.push(Rib::new(NormalRibKind));
2130 self.label_ribs.pop();
2134 fn with_constant_rib<F>(&mut self, f: F)
2135 where F: FnOnce(&mut Resolver)
2137 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2138 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2141 self.type_ribs.pop();
2142 self.value_ribs.pop();
2146 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2147 // Create a value rib for the function.
2148 self.value_ribs.push(Rib::new(rib_kind));
2150 // Create a label rib for the function.
2151 self.label_ribs.push(Rib::new(rib_kind));
2153 // Add each argument to the rib.
2154 let mut bindings_list = HashMap::new();
2155 for argument in &declaration.inputs {
2156 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2158 self.visit_ty(&*argument.ty);
2160 debug!("(resolving function) recorded argument");
2162 intravisit::walk_fn_ret_ty(self, &declaration.output);
2164 // Resolve the function body.
2165 self.visit_block(block);
2167 debug!("(resolving function) leaving function");
2170 self.label_ribs.pop();
2171 self.value_ribs.pop();
2175 fn resolve_trait_reference(&mut self,
2179 -> Result<PathResolution, ()> {
2180 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2181 if let DefTrait(_) = path_res.base_def {
2182 debug!("(resolving trait) found trait def: {:?}", path_res);
2187 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2190 // If it's a typedef, give a note
2191 if let DefTy(..) = path_res.base_def {
2193 .span_note(trait_path.span, "`type` aliases cannot be used for traits");
2200 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2206 fn resolve_generics(&mut self, generics: &Generics) {
2207 for type_parameter in generics.ty_params.iter() {
2208 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2210 for predicate in &generics.where_clause.predicates {
2212 &hir::WherePredicate::BoundPredicate(_) |
2213 &hir::WherePredicate::RegionPredicate(_) => {}
2214 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2215 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2216 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2217 self.record_def(eq_pred.id, path_res.unwrap());
2221 ResolutionError::UndeclaredAssociatedType);
2222 self.record_def(eq_pred.id, err_path_resolution());
2227 intravisit::walk_generics(self, generics);
2230 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2231 where F: FnOnce(&mut Resolver) -> T
2233 // Handle nested impls (inside fn bodies)
2234 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2235 let result = f(self);
2236 self.current_self_type = previous_value;
2240 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2241 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2243 let mut new_val = None;
2244 let mut new_id = None;
2245 if let Some(trait_ref) = opt_trait_ref {
2246 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2249 assert!(path_res.depth == 0);
2250 self.record_def(trait_ref.ref_id, path_res);
2251 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2252 new_id = Some(path_res.base_def.def_id());
2254 self.record_def(trait_ref.ref_id, err_path_resolution());
2256 intravisit::walk_trait_ref(self, trait_ref);
2258 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2259 let result = f(self, new_id);
2260 self.current_trait_ref = original_trait_ref;
2264 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2265 where F: FnOnce(&mut Resolver)
2267 let mut self_type_rib = Rib::new(NormalRibKind);
2269 // plain insert (no renaming, types are not currently hygienic....)
2270 let name = special_names::type_self;
2271 self_type_rib.bindings.insert(name, DlDef(self_def));
2272 self.type_ribs.push(self_type_rib);
2275 self.type_ribs.pop();
2279 fn resolve_implementation(&mut self,
2280 generics: &Generics,
2281 opt_trait_reference: &Option<TraitRef>,
2284 impl_items: &[ImplItem]) {
2285 // If applicable, create a rib for the type parameters.
2286 self.with_type_parameter_rib(HasTypeParameters(generics,
2290 // Resolve the type parameters.
2291 this.visit_generics(generics);
2293 // Resolve the trait reference, if necessary.
2294 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2295 // Resolve the self type.
2296 this.visit_ty(self_type);
2298 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2299 this.with_current_self_type(self_type, |this| {
2300 for impl_item in impl_items {
2301 match impl_item.node {
2302 hir::ImplItemKind::Const(..) => {
2303 // If this is a trait impl, ensure the const
2305 this.check_trait_item(impl_item.name,
2307 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2308 this.with_constant_rib(|this| {
2309 intravisit::walk_impl_item(this, impl_item);
2312 hir::ImplItemKind::Method(ref sig, _) => {
2313 // If this is a trait impl, ensure the method
2315 this.check_trait_item(impl_item.name,
2317 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2319 // We also need a new scope for the method-
2320 // specific type parameters.
2321 let type_parameters =
2322 HasTypeParameters(&sig.generics,
2325 this.with_type_parameter_rib(type_parameters, |this| {
2326 intravisit::walk_impl_item(this, impl_item);
2329 hir::ImplItemKind::Type(ref ty) => {
2330 // If this is a trait impl, ensure the type
2332 this.check_trait_item(impl_item.name,
2334 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2346 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2347 where F: FnOnce(Name, &str) -> ResolutionError
2349 // If there is a TraitRef in scope for an impl, then the method must be in the
2351 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2352 if !self.trait_item_map.contains_key(&(name, did)) {
2353 let path_str = path_names_to_string(&trait_ref.path, 0);
2354 resolve_error(self, span, err(name, &*path_str));
2359 fn resolve_local(&mut self, local: &Local) {
2360 // Resolve the type.
2361 walk_list!(self, visit_ty, &local.ty);
2363 // Resolve the initializer.
2364 walk_list!(self, visit_expr, &local.init);
2366 // Resolve the pattern.
2367 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2370 // build a map from pattern identifiers to binding-info's.
2371 // this is done hygienically. This could arise for a macro
2372 // that expands into an or-pattern where one 'x' was from the
2373 // user and one 'x' came from the macro.
2374 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2375 let mut result = HashMap::new();
2376 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2377 let name = path1.node;
2381 binding_mode: binding_mode,
2387 // check that all of the arms in an or-pattern have exactly the
2388 // same set of bindings, with the same binding modes for each.
2389 fn check_consistent_bindings(&mut self, arm: &Arm) {
2390 if arm.pats.is_empty() {
2393 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2394 for (i, p) in arm.pats.iter().enumerate() {
2395 let map_i = self.binding_mode_map(&**p);
2397 for (&key, &binding_0) in &map_0 {
2398 match map_i.get(&key) {
2402 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2404 Some(binding_i) => {
2405 if binding_0.binding_mode != binding_i.binding_mode {
2408 ResolutionError::VariableBoundWithDifferentMode(key,
2415 for (&key, &binding) in &map_i {
2416 if !map_0.contains_key(&key) {
2419 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2425 fn resolve_arm(&mut self, arm: &Arm) {
2426 self.value_ribs.push(Rib::new(NormalRibKind));
2428 let mut bindings_list = HashMap::new();
2429 for pattern in &arm.pats {
2430 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2433 // This has to happen *after* we determine which
2434 // pat_idents are variants
2435 self.check_consistent_bindings(arm);
2437 walk_list!(self, visit_expr, &arm.guard);
2438 self.visit_expr(&*arm.body);
2441 self.value_ribs.pop();
2445 fn resolve_block(&mut self, block: &Block) {
2446 debug!("(resolving block) entering block");
2447 self.value_ribs.push(Rib::new(NormalRibKind));
2449 // Move down in the graph, if there's an anonymous module rooted here.
2450 let orig_module = self.current_module.clone();
2451 match orig_module.anonymous_children.borrow().get(&block.id) {
2455 Some(anonymous_module) => {
2456 debug!("(resolving block) found anonymous module, moving down");
2457 self.current_module = anonymous_module.clone();
2461 // Check for imports appearing after non-item statements.
2462 let mut found_non_item = false;
2463 for statement in &block.stmts {
2464 if let hir::StmtDecl(ref declaration, _) = statement.node {
2465 if let hir::DeclItem(i) = declaration.node {
2466 let i = self.ast_map.expect_item(i.id);
2468 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2469 span_err!(self.session,
2472 "imports are not allowed after non-item statements");
2477 found_non_item = true
2480 found_non_item = true;
2484 // Descend into the block.
2485 intravisit::walk_block(self, block);
2489 self.current_module = orig_module;
2490 self.value_ribs.pop();
2492 debug!("(resolving block) leaving block");
2495 fn resolve_type(&mut self, ty: &Ty) {
2497 TyPath(ref maybe_qself, ref path) => {
2498 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2499 maybe_qself.as_ref(),
2503 // `<T>::a::b::c` is resolved by typeck alone.
2504 TypecheckRequired => {
2505 // Resolve embedded types.
2506 intravisit::walk_ty(self, ty);
2509 ResolveAttempt(resolution) => resolution,
2512 // This is a path in the type namespace. Walk through scopes
2516 // Write the result into the def map.
2517 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2518 path_names_to_string(path, 0),
2521 self.record_def(ty.id, def);
2524 self.record_def(ty.id, err_path_resolution());
2526 // Keep reporting some errors even if they're ignored above.
2527 self.resolve_path(ty.id, path, 0, TypeNS, true);
2529 let kind = if maybe_qself.is_some() {
2535 let self_type_name = special_idents::type_self.name;
2536 let is_invalid_self_type_name = path.segments.len() > 0 &&
2537 maybe_qself.is_none() &&
2538 path.segments[0].identifier.name ==
2540 if is_invalid_self_type_name {
2543 ResolutionError::SelfUsedOutsideImplOrTrait);
2547 ResolutionError::UseOfUndeclared(
2549 &*path_names_to_string(path,
2558 // Resolve embedded types.
2559 intravisit::walk_ty(self, ty);
2562 fn resolve_pattern(&mut self,
2564 mode: PatternBindingMode,
2565 // Maps idents to the node ID for the (outermost)
2566 // pattern that binds them
2567 bindings_list: &mut HashMap<Name, NodeId>) {
2568 let pat_id = pattern.id;
2569 walk_pat(pattern, |pattern| {
2570 match pattern.node {
2571 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2572 // The meaning of PatIdent with no type parameters
2573 // depends on whether an enum variant or unit-like struct
2574 // with that name is in scope. The probing lookup has to
2575 // be careful not to emit spurious errors. Only matching
2576 // patterns (match) can match nullary variants or
2577 // unit-like structs. For binding patterns (let
2578 // and the LHS of @-patterns), matching such a value is
2579 // simply disallowed (since it's rarely what you want).
2580 let const_ok = mode == RefutableMode && at_rhs.is_none();
2582 let ident = path1.node;
2583 let renamed = ident.name;
2585 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2587 FoundStructOrEnumVariant(def, lp) if const_ok => {
2588 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2591 self.enforce_default_binding_mode(pattern,
2594 self.record_def(pattern.id,
2601 FoundStructOrEnumVariant(..) => {
2605 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2608 self.record_def(pattern.id, err_path_resolution());
2610 FoundConst(def, lp, _) if const_ok => {
2611 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2613 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2614 self.record_def(pattern.id,
2621 FoundConst(def, _, name) => {
2625 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2628 self.record_def(pattern.id, err_path_resolution());
2630 BareIdentifierPatternUnresolved => {
2631 debug!("(resolving pattern) binding `{}`", renamed);
2633 let def_id = self.ast_map.local_def_id(pattern.id);
2634 let def = DefLocal(def_id, pattern.id);
2636 // Record the definition so that later passes
2637 // will be able to distinguish variants from
2638 // locals in patterns.
2640 self.record_def(pattern.id,
2643 last_private: LastMod(AllPublic),
2647 // Add the binding to the local ribs, if it
2648 // doesn't already exist in the bindings list. (We
2649 // must not add it if it's in the bindings list
2650 // because that breaks the assumptions later
2651 // passes make about or-patterns.)
2652 if !bindings_list.contains_key(&renamed) {
2653 let this = &mut *self;
2654 let last_rib = this.value_ribs.last_mut().unwrap();
2655 last_rib.bindings.insert(renamed, DlDef(def));
2656 bindings_list.insert(renamed, pat_id);
2657 } else if mode == ArgumentIrrefutableMode &&
2658 bindings_list.contains_key(&renamed) {
2659 // Forbid duplicate bindings in the same
2664 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2665 &ident.name.as_str())
2667 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2668 // Then this is a duplicate variable in the
2669 // same disjunction, which is an error.
2673 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2674 &ident.name.as_str())
2677 // Else, not bound in the same pattern: do
2683 PatEnum(ref path, _) => {
2684 // This must be an enum variant, struct or const.
2685 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2690 // The below shouldn't happen because all
2691 // qualified paths should be in PatQPath.
2692 TypecheckRequired =>
2693 self.session.span_bug(path.span,
2694 "resolve_possibly_assoc_item claimed
2696 that a path in PatEnum requires typecheck
2698 to resolve, but qualified paths should be
2701 ResolveAttempt(resolution) => resolution,
2703 if let Some(path_res) = resolution {
2704 match path_res.base_def {
2705 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2706 self.record_def(pattern.id, path_res);
2709 resolve_error(&self,
2711 ResolutionError::StaticVariableReference);
2712 self.record_def(pattern.id, err_path_resolution());
2715 // If anything ends up here entirely resolved,
2716 // it's an error. If anything ends up here
2717 // partially resolved, that's OK, because it may
2718 // be a `T::CONST` that typeck will resolve.
2719 if path_res.depth == 0 {
2723 ResolutionError::NotAnEnumVariantStructOrConst(
2731 self.record_def(pattern.id, err_path_resolution());
2733 let const_name = path.segments
2738 let traits = self.get_traits_containing_item(const_name);
2739 self.trait_map.insert(pattern.id, traits);
2740 self.record_def(pattern.id, path_res);
2748 ResolutionError::UnresolvedEnumVariantStructOrConst(
2749 &path.segments.last().unwrap().identifier.name.as_str())
2751 self.record_def(pattern.id, err_path_resolution());
2753 intravisit::walk_path(self, path);
2756 PatQPath(ref qself, ref path) => {
2757 // Associated constants only.
2758 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2763 TypecheckRequired => {
2764 // All `<T>::CONST` should end up here, and will
2765 // require use of the trait map to resolve
2766 // during typechecking.
2767 let const_name = path.segments
2772 let traits = self.get_traits_containing_item(const_name);
2773 self.trait_map.insert(pattern.id, traits);
2774 intravisit::walk_pat(self, pattern);
2777 ResolveAttempt(resolution) => resolution,
2779 if let Some(path_res) = resolution {
2780 match path_res.base_def {
2781 // All `<T as Trait>::CONST` should end up here, and
2782 // have the trait already selected.
2783 DefAssociatedConst(..) => {
2784 self.record_def(pattern.id, path_res);
2790 ResolutionError::NotAnAssociatedConst(
2791 &path.segments.last().unwrap().identifier.name.as_str()
2794 self.record_def(pattern.id, err_path_resolution());
2800 ResolutionError::UnresolvedAssociatedConst(&path.segments
2806 self.record_def(pattern.id, err_path_resolution());
2808 intravisit::walk_pat(self, pattern);
2811 PatStruct(ref path, _, _) => {
2812 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2813 Some(definition) => {
2814 self.record_def(pattern.id, definition);
2817 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2821 ResolutionError::DoesNotNameAStruct(
2822 &*path_names_to_string(path, 0))
2824 self.record_def(pattern.id, err_path_resolution());
2827 intravisit::walk_path(self, path);
2830 PatLit(_) | PatRange(..) => {
2831 intravisit::walk_pat(self, pattern);
2842 fn resolve_bare_identifier_pattern(&mut self,
2845 -> BareIdentifierPatternResolution {
2846 let module = self.current_module.clone();
2847 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2848 Success((target, _)) => {
2849 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2851 target.binding.borrow());
2852 match target.binding.def() {
2854 panic!("resolved name in the value namespace to a set of name bindings \
2857 // For the two success cases, this lookup can be
2858 // considered as not having a private component because
2859 // the lookup happened only within the current module.
2860 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2861 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2863 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2864 return FoundConst(def, LastMod(AllPublic), name);
2866 Some(DefStatic(..)) => {
2867 resolve_error(self, span, ResolutionError::StaticVariableReference);
2868 return BareIdentifierPatternUnresolved;
2870 _ => return BareIdentifierPatternUnresolved
2875 panic!("unexpected indeterminate result");
2879 Some((span, msg)) => {
2880 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2885 debug!("(resolve bare identifier pattern) failed to find {}", name);
2886 return BareIdentifierPatternUnresolved;
2891 /// Handles paths that may refer to associated items
2892 fn resolve_possibly_assoc_item(&mut self,
2894 maybe_qself: Option<&hir::QSelf>,
2896 namespace: Namespace,
2898 -> AssocItemResolveResult {
2899 let max_assoc_types;
2903 if qself.position == 0 {
2904 return TypecheckRequired;
2906 max_assoc_types = path.segments.len() - qself.position;
2907 // Make sure the trait is valid.
2908 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2911 max_assoc_types = path.segments.len();
2915 let mut resolution = self.with_no_errors(|this| {
2916 this.resolve_path(id, path, 0, namespace, check_ribs)
2918 for depth in 1..max_assoc_types {
2919 if resolution.is_some() {
2922 self.with_no_errors(|this| {
2923 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2926 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2927 // A module is not a valid type or value.
2930 ResolveAttempt(resolution)
2933 /// If `check_ribs` is true, checks the local definitions first; i.e.
2934 /// doesn't skip straight to the containing module.
2935 /// Skips `path_depth` trailing segments, which is also reflected in the
2936 /// returned value. See `middle::def::PathResolution` for more info.
2937 pub fn resolve_path(&mut self,
2941 namespace: Namespace,
2943 -> Option<PathResolution> {
2944 let span = path.span;
2945 let segments = &path.segments[..path.segments.len() - path_depth];
2947 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2950 let def = self.resolve_crate_relative_path(span, segments, namespace);
2951 return def.map(mk_res);
2954 // Try to find a path to an item in a module.
2955 let last_ident = segments.last().unwrap().identifier;
2956 if segments.len() <= 1 {
2957 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2958 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2960 PathResolution::new(def, LastMod(AllPublic), path_depth)
2964 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2965 let def = self.resolve_module_relative_path(span, segments, namespace);
2966 match (def, unqualified_def) {
2967 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2969 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2972 "unnecessary qualification".to_string());
2980 // Resolve a single identifier
2981 fn resolve_identifier(&mut self,
2982 identifier: hir::Ident,
2983 namespace: Namespace,
2986 -> Option<LocalDef> {
2987 // First, check to see whether the name is a primitive type.
2988 if namespace == TypeNS {
2989 if let Some(&prim_ty) = self.primitive_type_table
2991 .get(&identifier.unhygienic_name) {
2992 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
2997 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
3002 let name = identifier.unhygienic_name;
3003 self.resolve_item_by_name_in_lexical_scope(name, namespace, record_used)
3004 .map(LocalDef::from_def)
3007 // Resolve a local definition, potentially adjusting for closures.
3008 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
3009 let ribs = match local_def.ribs {
3010 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
3011 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
3014 let mut def = local_def.def;
3017 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
3019 DefLocal(_, node_id) => {
3023 // Nothing to do. Continue.
3025 ClosureRibKind(function_id) => {
3027 let node_def_id = self.ast_map.local_def_id(node_id);
3029 let seen = self.freevars_seen
3031 .or_insert_with(|| NodeMap());
3032 if let Some(&index) = seen.get(&node_id) {
3033 def = DefUpvar(node_def_id, node_id, index, function_id);
3036 let vec = self.freevars
3038 .or_insert_with(|| vec![]);
3039 let depth = vec.len();
3045 def = DefUpvar(node_def_id, node_id, depth, function_id);
3046 seen.insert(node_id, depth);
3048 ItemRibKind | MethodRibKind => {
3049 // This was an attempt to access an upvar inside a
3050 // named function item. This is not allowed, so we
3054 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3057 ConstantItemRibKind => {
3058 // Still doesn't deal with upvars
3061 ResolutionError::AttemptToUseNonConstantValueInConstant);
3067 DefTyParam(..) | DefSelfTy(..) => {
3070 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3071 // Nothing to do. Continue.
3074 // This was an attempt to use a type parameter outside
3079 ResolutionError::TypeParametersFromOuterFunction);
3082 ConstantItemRibKind => {
3084 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3095 // resolve a "module-relative" path, e.g. a::b::c
3096 fn resolve_module_relative_path(&mut self,
3098 segments: &[hir::PathSegment],
3099 namespace: Namespace)
3100 -> Option<(Def, LastPrivate)> {
3101 let module_path = segments.split_last()
3105 .map(|ps| ps.identifier.name)
3106 .collect::<Vec<_>>();
3108 let containing_module;
3110 let current_module = self.current_module.clone();
3111 match self.resolve_module_path(current_module,
3117 let (span, msg) = match err {
3118 Some((span, msg)) => (span, msg),
3120 let msg = format!("Use of undeclared type or module `{}`",
3121 names_to_string(&module_path));
3126 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3129 Indeterminate => panic!("indeterminate unexpected"),
3130 Success((resulting_module, resulting_last_private)) => {
3131 containing_module = resulting_module;
3132 last_private = resulting_last_private;
3136 let name = segments.last().unwrap().identifier.name;
3137 let def = match self.resolve_name_in_module(containing_module.clone(),
3140 NameSearchType::PathSearch,
3142 Success((Target { binding, .. }, _)) => {
3143 let (def, lp) = binding.def_and_lp();
3144 (def, last_private.or(lp))
3148 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3149 self.used_crates.insert(kid);
3154 /// Invariant: This must be called only during main resolution, not during
3155 /// import resolution.
3156 fn resolve_crate_relative_path(&mut self,
3158 segments: &[hir::PathSegment],
3159 namespace: Namespace)
3160 -> Option<(Def, LastPrivate)> {
3161 let module_path = segments.split_last()
3165 .map(|ps| ps.identifier.name)
3166 .collect::<Vec<_>>();
3168 let root_module = self.graph_root.clone();
3170 let containing_module;
3172 match self.resolve_module_path_from_root(root_module,
3177 LastMod(AllPublic)) {
3179 let (span, msg) = match err {
3180 Some((span, msg)) => (span, msg),
3182 let msg = format!("Use of undeclared module `::{}`",
3183 names_to_string(&module_path[..]));
3188 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3193 panic!("indeterminate unexpected");
3196 Success((resulting_module, resulting_last_private)) => {
3197 containing_module = resulting_module;
3198 last_private = resulting_last_private;
3202 let name = segments.last().unwrap().identifier.name;
3203 match self.resolve_name_in_module(containing_module,
3206 NameSearchType::PathSearch,
3208 Success((Target { binding, .. }, _)) => {
3209 let (def, lp) = binding.def_and_lp();
3210 Some((def, last_private.or(lp)))
3216 fn resolve_identifier_in_local_ribs(&mut self,
3218 namespace: Namespace)
3219 -> Option<LocalDef> {
3220 // Check the local set of ribs.
3221 let (name, ribs) = match namespace {
3222 ValueNS => (ident.name, &self.value_ribs),
3223 TypeNS => (ident.unhygienic_name, &self.type_ribs),
3226 for (i, rib) in ribs.iter().enumerate().rev() {
3227 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3230 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3234 return Some(LocalDef {
3235 ribs: Some((namespace, i)),
3240 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3252 fn resolve_item_by_name_in_lexical_scope(&mut self,
3254 namespace: Namespace,
3258 let module = self.current_module.clone();
3259 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
3260 Success((target, _)) => {
3261 match target.binding.def() {
3263 // This can happen if we were looking for a type and
3264 // found a module instead. Modules don't have defs.
3265 debug!("(resolving item path by identifier in lexical scope) failed to \
3266 resolve {} after success...",
3271 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3273 // This lookup is "all public" because it only searched
3274 // for one identifier in the current module (couldn't
3275 // have passed through reexports or anything like that.
3281 panic!("unexpected indeterminate result");
3284 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3287 if let Some((span, msg)) = err {
3288 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3296 fn with_no_errors<T, F>(&mut self, f: F) -> T
3297 where F: FnOnce(&mut Resolver) -> T
3299 self.emit_errors = false;
3301 self.emit_errors = true;
3305 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3306 fn extract_path_and_node_id(t: &Ty,
3307 allow: FallbackChecks)
3308 -> Option<(Path, NodeId, FallbackChecks)> {
3310 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3311 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3312 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3313 // This doesn't handle the remaining `Ty` variants as they are not
3314 // that commonly the self_type, it might be interesting to provide
3315 // support for those in future.
3320 fn get_module(this: &mut Resolver,
3322 name_path: &[ast::Name])
3323 -> Option<Rc<Module>> {
3324 let root = this.current_module.clone();
3325 let last_name = name_path.last().unwrap();
3327 if name_path.len() == 1 {
3328 match this.primitive_type_table.primitive_types.get(last_name) {
3331 match this.current_module.children.borrow().get(last_name) {
3332 Some(child) => child.type_ns.module(),
3338 match this.resolve_module_path(root,
3343 Success((module, _)) => Some(module),
3349 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3350 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3351 let sig = match this.ast_map.get(node_id) {
3352 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3353 hir::MethodTraitItem(ref sig, _) => sig,
3356 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3357 hir::ImplItemKind::Method(ref sig, _) => sig,
3362 sig.explicit_self.node == hir::SelfStatic
3364 this.session.cstore.is_static_method(did)
3368 let (path, node_id, allowed) = match self.current_self_type {
3369 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3371 None => return NoSuggestion,
3373 None => return NoSuggestion,
3376 if allowed == Everything {
3377 // Look for a field with the same name in the current self_type.
3378 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3379 Some(DefTy(did, _)) |
3380 Some(DefStruct(did)) |
3381 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3384 if fields.iter().any(|&field_name| name == field_name) {
3389 _ => {} // Self type didn't resolve properly
3393 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3395 // Look for a method in the current self type's impl module.
3396 if let Some(module) = get_module(self, path.span, &name_path) {
3397 if let Some(binding) = module.children.borrow().get(&name) {
3398 if let Some(DefMethod(did)) = binding.value_ns.def() {
3399 if is_static_method(self, did) {
3400 return StaticMethod(path_names_to_string(&path, 0));
3402 if self.current_trait_ref.is_some() {
3404 } else if allowed == Everything {
3411 // Look for a method in the current trait.
3412 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3413 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3414 if is_static_method(self, did) {
3415 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3425 fn find_best_match_for_name(&mut self, name: &str) -> SuggestionType {
3426 let mut maybes: Vec<token::InternedString> = Vec::new();
3427 let mut values: Vec<usize> = Vec::new();
3429 if let Some(macro_name) = self.session.available_macros
3430 .borrow().iter().find(|n| n.as_str() == name) {
3431 return SuggestionType::Macro(format!("{}!", macro_name));
3434 for rib in self.value_ribs.iter().rev() {
3435 for (&k, _) in &rib.bindings {
3436 maybes.push(k.as_str());
3437 values.push(usize::MAX);
3441 let mut smallest = 0;
3442 for (i, other) in maybes.iter().enumerate() {
3443 values[i] = lev_distance(name, &other);
3445 if values[i] <= values[smallest] {
3450 let max_distance = max_suggestion_distance(name);
3451 if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
3453 SuggestionType::Function(maybes[smallest].to_string())
3456 SuggestionType::NotFound
3460 fn resolve_expr(&mut self, expr: &Expr) {
3461 // First, record candidate traits for this expression if it could
3462 // result in the invocation of a method call.
3464 self.record_candidate_traits_for_expr_if_necessary(expr);
3466 // Next, resolve the node.
3468 ExprPath(ref maybe_qself, ref path) => {
3469 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3470 maybe_qself.as_ref(),
3474 // `<T>::a::b::c` is resolved by typeck alone.
3475 TypecheckRequired => {
3476 let method_name = path.segments.last().unwrap().identifier.name;
3477 let traits = self.get_traits_containing_item(method_name);
3478 self.trait_map.insert(expr.id, traits);
3479 intravisit::walk_expr(self, expr);
3482 ResolveAttempt(resolution) => resolution,
3485 // This is a local path in the value namespace. Walk through
3486 // scopes looking for it.
3487 if let Some(path_res) = resolution {
3488 // Check if struct variant
3489 if let DefVariant(_, _, true) = path_res.base_def {
3490 let path_name = path_names_to_string(path, 0);
3494 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3496 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3498 if self.emit_errors {
3499 self.session.fileline_help(expr.span, &msg);
3501 self.session.span_help(expr.span, &msg);
3503 self.record_def(expr.id, err_path_resolution());
3505 // Write the result into the def map.
3506 debug!("(resolving expr) resolved `{}`",
3507 path_names_to_string(path, 0));
3509 // Partial resolutions will need the set of traits in scope,
3510 // so they can be completed during typeck.
3511 if path_res.depth != 0 {
3512 let method_name = path.segments.last().unwrap().identifier.name;
3513 let traits = self.get_traits_containing_item(method_name);
3514 self.trait_map.insert(expr.id, traits);
3517 self.record_def(expr.id, path_res);
3520 // Be helpful if the name refers to a struct
3521 // (The pattern matching def_tys where the id is in self.structs
3522 // matches on regular structs while excluding tuple- and enum-like
3523 // structs, which wouldn't result in this error.)
3524 let path_name = path_names_to_string(path, 0);
3525 let type_res = self.with_no_errors(|this| {
3526 this.resolve_path(expr.id, path, 0, TypeNS, false)
3529 self.record_def(expr.id, err_path_resolution());
3530 match type_res.map(|r| r.base_def) {
3531 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3535 ResolutionError::StructVariantUsedAsFunction(
3539 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3541 if self.emit_errors {
3542 self.session.fileline_help(expr.span, &msg);
3544 self.session.span_help(expr.span, &msg);
3548 // Keep reporting some errors even if they're ignored above.
3549 self.resolve_path(expr.id, path, 0, ValueNS, true);
3551 let mut method_scope = false;
3552 self.value_ribs.iter().rev().all(|rib| {
3553 method_scope = match rib.kind {
3554 MethodRibKind => true,
3555 ItemRibKind | ConstantItemRibKind => false,
3556 _ => return true, // Keep advancing
3558 false // Stop advancing
3561 if method_scope && special_names::self_.as_str() == &path_name[..] {
3564 ResolutionError::SelfNotAvailableInStaticMethod);
3566 let last_name = path.segments.last().unwrap().identifier.name;
3567 let mut msg = match self.find_fallback_in_self_type(last_name) {
3569 // limit search to 5 to reduce the number
3570 // of stupid suggestions
3571 match self.find_best_match_for_name(&path_name) {
3572 SuggestionType::Macro(s) => {
3573 format!("the macro `{}`", s)
3575 SuggestionType::Function(s) => format!("`{}`", s),
3576 SuggestionType::NotFound => "".to_string(),
3579 Field => format!("`self.{}`", path_name),
3581 TraitItem => format!("to call `self.{}`", path_name),
3582 TraitMethod(path_str) |
3583 StaticMethod(path_str) =>
3584 format!("to call `{}::{}`", path_str, path_name),
3587 let mut context = UnresolvedNameContext::Other;
3588 if !msg.is_empty() {
3589 msg = format!(". Did you mean {}?", msg);
3591 // we check if this a module and if so, we display a help
3593 let name_path = path.segments.iter()
3594 .map(|seg| seg.identifier.name)
3595 .collect::<Vec<_>>();
3596 let current_module = self.current_module.clone();
3598 match self.resolve_module_path(current_module,
3604 context = UnresolvedNameContext::PathIsMod(expr.id);
3612 ResolutionError::UnresolvedName(
3613 &*path_name, &*msg, context));
3619 intravisit::walk_expr(self, expr);
3622 ExprStruct(ref path, _, _) => {
3623 // Resolve the path to the structure it goes to. We don't
3624 // check to ensure that the path is actually a structure; that
3625 // is checked later during typeck.
3626 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3627 Some(definition) => self.record_def(expr.id, definition),
3629 debug!("(resolving expression) didn't find struct def",);
3633 ResolutionError::DoesNotNameAStruct(
3634 &*path_names_to_string(path, 0))
3636 self.record_def(expr.id, err_path_resolution());
3640 intravisit::walk_expr(self, expr);
3643 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3644 self.with_label_rib(|this| {
3645 let def_like = DlDef(DefLabel(expr.id));
3648 let rib = this.label_ribs.last_mut().unwrap();
3649 rib.bindings.insert(label.name, def_like);
3652 intravisit::walk_expr(this, expr);
3656 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3657 match self.search_label(label.node.name) {
3659 self.record_def(expr.id, err_path_resolution());
3662 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3664 Some(DlDef(def @ DefLabel(_))) => {
3665 // Since this def is a label, it is never read.
3666 self.record_def(expr.id,
3669 last_private: LastMod(AllPublic),
3674 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3680 intravisit::walk_expr(self, expr);
3685 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3687 ExprField(_, name) => {
3688 // FIXME(#6890): Even though you can't treat a method like a
3689 // field, we need to add any trait methods we find that match
3690 // the field name so that we can do some nice error reporting
3691 // later on in typeck.
3692 let traits = self.get_traits_containing_item(name.node);
3693 self.trait_map.insert(expr.id, traits);
3695 ExprMethodCall(name, _, _) => {
3696 debug!("(recording candidate traits for expr) recording traits for {}",
3698 let traits = self.get_traits_containing_item(name.node);
3699 self.trait_map.insert(expr.id, traits);
3707 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3708 debug!("(getting traits containing item) looking for '{}'", name);
3710 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3711 debug!("(adding trait info) found trait {:?} for method '{}'",
3714 found_traits.push(trait_def_id);
3717 let mut found_traits = Vec::new();
3718 let mut search_module = self.current_module.clone();
3720 // Look for the current trait.
3721 match self.current_trait_ref {
3722 Some((trait_def_id, _)) => {
3723 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3724 add_trait_info(&mut found_traits, trait_def_id, name);
3727 None => {} // Nothing to do.
3730 // Look for trait children.
3731 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3734 for (_, child_names) in search_module.children.borrow().iter() {
3735 let def = match child_names.type_ns.def() {
3739 let trait_def_id = match def {
3740 DefTrait(trait_def_id) => trait_def_id,
3743 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3744 add_trait_info(&mut found_traits, trait_def_id, name);
3749 // Look for imports.
3750 for (_, import) in search_module.import_resolutions.borrow().iter() {
3751 let target = match import.type_ns.target {
3753 Some(ref target) => target,
3755 let did = match target.binding.def() {
3756 Some(DefTrait(trait_def_id)) => trait_def_id,
3757 Some(..) | None => continue,
3759 if self.trait_item_map.contains_key(&(name, did)) {
3760 add_trait_info(&mut found_traits, did, name);
3761 let id = import.type_ns.id;
3762 self.used_imports.insert((id, TypeNS));
3763 let trait_name = self.get_trait_name(did);
3764 self.record_import_use(id, trait_name);
3765 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3766 self.used_crates.insert(kid);
3771 match search_module.parent_link.clone() {
3772 NoParentLink | ModuleParentLink(..) => break,
3773 BlockParentLink(parent_module, _) => {
3774 search_module = parent_module.upgrade().unwrap();
3782 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3783 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3784 assert!(match resolution.last_private {
3785 LastImport{..} => false,
3788 "Import should only be used for `use` directives");
3790 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3791 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3792 self.session.span_bug(span,
3793 &format!("path resolved multiple times ({:?} before, {:?} now)",
3799 fn enforce_default_binding_mode(&mut self,
3801 pat_binding_mode: BindingMode,
3803 match pat_binding_mode {
3804 BindByValue(_) => {}
3808 ResolutionError::CannotUseRefBindingModeWith(descr));
3816 // Diagnostics are not particularly efficient, because they're rarely
3820 #[allow(dead_code)] // useful for debugging
3821 fn dump_module(&mut self, module_: Rc<Module>) {
3822 debug!("Dump of module `{}`:", module_to_string(&*module_));
3824 debug!("Children:");
3825 build_reduced_graph::populate_module_if_necessary(self, &module_);
3826 for (&name, _) in module_.children.borrow().iter() {
3827 debug!("* {}", name);
3830 debug!("Import resolutions:");
3831 let import_resolutions = module_.import_resolutions.borrow();
3832 for (&name, import_resolution) in import_resolutions.iter() {
3834 match import_resolution.value_ns.target {
3836 value_repr = "".to_string();
3839 value_repr = " value:?".to_string();
3845 match import_resolution.type_ns.target {
3847 type_repr = "".to_string();
3850 type_repr = " type:?".to_string();
3855 debug!("* {}:{}{}", name, value_repr, type_repr);
3861 fn names_to_string(names: &[Name]) -> String {
3862 let mut first = true;
3863 let mut result = String::new();
3868 result.push_str("::")
3870 result.push_str(&name.as_str());
3875 fn path_names_to_string(path: &Path, depth: usize) -> String {
3876 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3878 .map(|seg| seg.identifier.name)
3880 names_to_string(&names[..])
3883 /// A somewhat inefficient routine to obtain the name of a module.
3884 fn module_to_string(module: &Module) -> String {
3885 let mut names = Vec::new();
3887 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3888 match module.parent_link {
3890 ModuleParentLink(ref module, name) => {
3892 collect_mod(names, &*module.upgrade().unwrap());
3894 BlockParentLink(ref module, _) => {
3895 // danger, shouldn't be ident?
3896 names.push(special_idents::opaque.name);
3897 collect_mod(names, &*module.upgrade().unwrap());
3901 collect_mod(&mut names, module);
3903 if names.is_empty() {
3904 return "???".to_string();
3906 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3909 fn err_path_resolution() -> PathResolution {
3912 last_private: LastMod(AllPublic),
3918 pub struct CrateMap {
3919 pub def_map: RefCell<DefMap>,
3920 pub freevars: FreevarMap,
3921 pub export_map: ExportMap,
3922 pub trait_map: TraitMap,
3923 pub external_exports: ExternalExports,
3924 pub glob_map: Option<GlobMap>,
3927 #[derive(PartialEq,Copy, Clone)]
3928 pub enum MakeGlobMap {
3933 /// Entry point to crate resolution.
3934 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3935 ast_map: &'a hir_map::Map<'tcx>,
3936 make_glob_map: MakeGlobMap)
3938 let krate = ast_map.krate();
3939 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3941 resolver.resolve_crate(krate);
3943 check_unused::check_crate(&mut resolver, krate);
3946 def_map: resolver.def_map,
3947 freevars: resolver.freevars,
3948 export_map: resolver.export_map,
3949 trait_map: resolver.trait_map,
3950 external_exports: resolver.external_exports,
3951 glob_map: if resolver.make_glob_map {
3952 Some(resolver.glob_map)
3959 /// Builds a name resolution walker to be used within this module,
3960 /// or used externally, with an optional callback function.
3962 /// The callback takes a &mut bool which allows callbacks to end a
3963 /// walk when set to true, passing through the rest of the walk, while
3964 /// preserving the ribs + current module. This allows resolve_path
3965 /// calls to be made with the correct scope info. The node in the
3966 /// callback corresponds to the current node in the walk.
3967 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3968 ast_map: &'a hir_map::Map<'tcx>,
3970 make_glob_map: MakeGlobMap,
3971 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3972 -> Resolver<'a, 'tcx> {
3973 let mut resolver = Resolver::new(session, ast_map, make_glob_map);
3975 resolver.callback = callback;
3977 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3978 session.abort_if_errors();
3980 resolve_imports::resolve_imports(&mut resolver);
3981 session.abort_if_errors();
3983 record_exports::record(&mut resolver);
3984 session.abort_if_errors();
3989 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }