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;
35 use self::PatternBindingMode::*;
36 use self::Namespace::*;
37 use self::NamespaceResult::*;
38 use self::ResolveResult::*;
39 use self::FallbackSuggestion::*;
40 use self::TypeParameters::*;
42 use self::UseLexicalScopeFlag::*;
43 use self::ModulePrefixResult::*;
44 use self::AssocItemResolveResult::*;
45 use self::NameSearchType::*;
46 use self::BareIdentifierPatternResolution::*;
47 use self::ParentLink::*;
48 use self::FallbackChecks::*;
50 use rustc::front::map as hir_map;
51 use rustc::session::Session;
53 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
54 use rustc::middle::def::*;
55 use rustc::middle::def_id::DefId;
56 use rustc::middle::pat_util::pat_bindings;
57 use rustc::middle::privacy::*;
58 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
60 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
63 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
64 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
65 use syntax::attr::AttrMetaMethods;
66 use syntax::parse::token::{self, special_names, special_idents};
67 use syntax::codemap::{self, Span, Pos};
68 use syntax::util::lev_distance::find_best_match_for_name;
70 use rustc_front::intravisit::{self, FnKind, Visitor};
72 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
73 use rustc_front::hir::Crate;
74 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprField};
75 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
76 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
77 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
78 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
79 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
80 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
81 use rustc_front::hir::Local;
82 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
83 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
84 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
85 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
86 use rustc_front::util::walk_pat;
88 use std::collections::{HashMap, HashSet};
89 use std::cell::{Cell, RefCell};
91 use std::mem::replace;
92 use std::rc::{Rc, Weak};
94 use resolve_imports::{Target, ImportDirective, ImportResolutionPerNamespace};
95 use resolve_imports::Shadowable;
97 // NB: This module needs to be declared first so diagnostics are
98 // registered before they are used.
103 mod build_reduced_graph;
106 // Perform the callback, not walking deeper if the return is true
107 macro_rules! execute_callback {
108 ($node: expr, $walker: expr) => (
109 if let Some(ref callback) = $walker.callback {
110 if callback($node, &mut $walker.resolved) {
117 enum SuggestionType {
119 Function(token::InternedString),
123 pub enum ResolutionError<'a> {
124 /// error E0401: can't use type parameters from outer function
125 TypeParametersFromOuterFunction,
126 /// error E0402: cannot use an outer type parameter in this context
127 OuterTypeParameterContext,
128 /// error E0403: the name is already used for a type parameter in this type parameter list
129 NameAlreadyUsedInTypeParameterList(Name),
130 /// error E0404: is not a trait
131 IsNotATrait(&'a str),
132 /// error E0405: use of undeclared trait name
133 UndeclaredTraitName(&'a str),
134 /// error E0406: undeclared associated type
135 UndeclaredAssociatedType,
136 /// error E0407: method is not a member of trait
137 MethodNotMemberOfTrait(Name, &'a str),
138 /// error E0437: type is not a member of trait
139 TypeNotMemberOfTrait(Name, &'a str),
140 /// error E0438: const is not a member of trait
141 ConstNotMemberOfTrait(Name, &'a str),
142 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
143 VariableNotBoundInPattern(Name, usize),
144 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
145 VariableBoundWithDifferentMode(Name, usize),
146 /// error E0410: variable from pattern is not bound in pattern #1
147 VariableNotBoundInParentPattern(Name, usize),
148 /// error E0411: use of `Self` outside of an impl or trait
149 SelfUsedOutsideImplOrTrait,
150 /// error E0412: use of undeclared
151 UseOfUndeclared(&'a str, &'a str),
152 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
153 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
154 /// error E0414: only irrefutable patterns allowed here
155 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
156 /// error E0415: identifier is bound more than once in this parameter list
157 IdentifierBoundMoreThanOnceInParameterList(&'a str),
158 /// error E0416: identifier is bound more than once in the same pattern
159 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
160 /// error E0417: static variables cannot be referenced in a pattern
161 StaticVariableReference,
162 /// error E0418: is not an enum variant, struct or const
163 NotAnEnumVariantStructOrConst(&'a str),
164 /// error E0419: unresolved enum variant, struct or const
165 UnresolvedEnumVariantStructOrConst(&'a str),
166 /// error E0420: is not an associated const
167 NotAnAssociatedConst(&'a str),
168 /// error E0421: unresolved associated const
169 UnresolvedAssociatedConst(&'a str),
170 /// error E0422: does not name a struct
171 DoesNotNameAStruct(&'a str),
172 /// error E0423: is a struct variant name, but this expression uses it like a function name
173 StructVariantUsedAsFunction(&'a str),
174 /// error E0424: `self` is not available in a static method
175 SelfNotAvailableInStaticMethod,
176 /// error E0425: unresolved name
177 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
178 /// error E0426: use of undeclared label
179 UndeclaredLabel(&'a str),
180 /// error E0427: cannot use `ref` binding mode with ...
181 CannotUseRefBindingModeWith(&'a str),
182 /// error E0428: duplicate definition
183 DuplicateDefinition(&'a str, Name),
184 /// error E0429: `self` imports are only allowed within a { } list
185 SelfImportsOnlyAllowedWithin,
186 /// error E0430: `self` import can only appear once in the list
187 SelfImportCanOnlyAppearOnceInTheList,
188 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
189 SelfImportOnlyInImportListWithNonEmptyPrefix,
190 /// error E0432: unresolved import
191 UnresolvedImport(Option<(&'a str, &'a str)>),
192 /// error E0433: failed to resolve
193 FailedToResolve(&'a str),
194 /// error E0434: can't capture dynamic environment in a fn item
195 CannotCaptureDynamicEnvironmentInFnItem,
196 /// error E0435: attempt to use a non-constant value in a constant
197 AttemptToUseNonConstantValueInConstant,
200 /// Context of where `ResolutionError::UnresolvedName` arose.
201 #[derive(Clone, PartialEq, Eq, Debug)]
202 pub enum UnresolvedNameContext {
203 /// `PathIsMod(id)` indicates that a given path, used in
204 /// expression context, actually resolved to a module rather than
205 /// a value. The `id` attached to the variant is the node id of
206 /// the erroneous path expression.
207 PathIsMod(ast::NodeId),
209 /// `Other` means we have no extra information about the context
210 /// of the unresolved name error. (Maybe we could eliminate all
211 /// such cases; but for now, this is an information-free default.)
215 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
216 span: syntax::codemap::Span,
217 resolution_error: ResolutionError<'b>) {
218 if !resolver.emit_errors {
221 match resolution_error {
222 ResolutionError::TypeParametersFromOuterFunction => {
223 span_err!(resolver.session,
226 "can't use type parameters from outer function; try using a local type \
229 ResolutionError::OuterTypeParameterContext => {
230 span_err!(resolver.session,
233 "cannot use an outer type parameter in this context");
235 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
236 span_err!(resolver.session,
239 "the name `{}` is already used for a type parameter in this type parameter \
243 ResolutionError::IsNotATrait(name) => {
244 span_err!(resolver.session, span, E0404, "`{}` is not a trait", name);
246 ResolutionError::UndeclaredTraitName(name) => {
247 span_err!(resolver.session,
250 "use of undeclared trait name `{}`",
253 ResolutionError::UndeclaredAssociatedType => {
254 span_err!(resolver.session, span, E0406, "undeclared associated type");
256 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
257 span_err!(resolver.session,
260 "method `{}` is not a member of trait `{}`",
264 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
265 span_err!(resolver.session,
268 "type `{}` is not a member of trait `{}`",
272 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
273 span_err!(resolver.session,
276 "const `{}` is not a member of trait `{}`",
280 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
281 span_err!(resolver.session,
284 "variable `{}` from pattern #1 is not bound in pattern #{}",
288 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
289 span_err!(resolver.session,
292 "variable `{}` is bound with different mode in pattern #{} than in pattern \
297 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
298 span_err!(resolver.session,
301 "variable `{}` from pattern #{} is not bound in pattern #1",
305 ResolutionError::SelfUsedOutsideImplOrTrait => {
306 span_err!(resolver.session,
309 "use of `Self` outside of an impl or trait");
311 ResolutionError::UseOfUndeclared(kind, name) => {
312 span_err!(resolver.session,
315 "use of undeclared {} `{}`",
319 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
320 span_err!(resolver.session,
323 "declaration of `{}` shadows an enum variant or unit-like struct in scope",
326 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
327 span_err!(resolver.session,
330 "only irrefutable patterns allowed here");
331 resolver.session.span_note(span,
332 "there already is a constant in scope sharing the same \
333 name as this pattern");
334 if let Some(sp) = resolver.ast_map.span_if_local(did) {
335 resolver.session.span_note(sp, "constant defined here");
337 if let Some(directive) = resolver.current_module
341 let item = resolver.ast_map.expect_item(directive.value_ns.id);
342 resolver.session.span_note(item.span, "constant imported here");
345 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
346 span_err!(resolver.session,
349 "identifier `{}` is bound more than once in this parameter list",
352 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
353 span_err!(resolver.session,
356 "identifier `{}` is bound more than once in the same pattern",
359 ResolutionError::StaticVariableReference => {
360 span_err!(resolver.session,
363 "static variables cannot be referenced in a pattern, use a `const` instead");
365 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
366 span_err!(resolver.session,
369 "`{}` is not an enum variant, struct or const",
372 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
373 span_err!(resolver.session,
376 "unresolved enum variant, struct or const `{}`",
379 ResolutionError::NotAnAssociatedConst(name) => {
380 span_err!(resolver.session,
383 "`{}` is not an associated const",
386 ResolutionError::UnresolvedAssociatedConst(name) => {
387 span_err!(resolver.session,
390 "unresolved associated const `{}`",
393 ResolutionError::DoesNotNameAStruct(name) => {
394 span_err!(resolver.session,
397 "`{}` does not name a structure",
400 ResolutionError::StructVariantUsedAsFunction(path_name) => {
401 span_err!(resolver.session,
404 "`{}` is the name of a struct or struct variant, but this expression uses \
405 it like a function name",
408 ResolutionError::SelfNotAvailableInStaticMethod => {
409 span_err!(resolver.session,
412 "`self` is not available in a static method. Maybe a `self` argument is \
415 ResolutionError::UnresolvedName(path, msg, context) => {
416 span_err!(resolver.session,
419 "unresolved name `{}`{}",
424 UnresolvedNameContext::Other => {} // no help available
425 UnresolvedNameContext::PathIsMod(id) => {
426 let mut help_msg = String::new();
427 let parent_id = resolver.ast_map.get_parent_node(id);
428 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
430 ExprField(_, ident) => {
431 help_msg = format!("To reference an item from the \
432 `{module}` module, use \
433 `{module}::{ident}`",
438 ExprMethodCall(ident, _, _) => {
439 help_msg = format!("To call a function from the \
440 `{module}` module, use \
441 `{module}::{ident}(..)`",
446 _ => {} // no help available
450 if !help_msg.is_empty() {
451 resolver.session.fileline_help(span, &help_msg);
456 ResolutionError::UndeclaredLabel(name) => {
457 span_err!(resolver.session,
460 "use of undeclared label `{}`",
463 ResolutionError::CannotUseRefBindingModeWith(descr) => {
464 span_err!(resolver.session,
467 "cannot use `ref` binding mode with {}",
470 ResolutionError::DuplicateDefinition(namespace, name) => {
471 span_err!(resolver.session,
474 "duplicate definition of {} `{}`",
478 ResolutionError::SelfImportsOnlyAllowedWithin => {
479 span_err!(resolver.session,
483 "`self` imports are only allowed within a { } list");
485 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
486 span_err!(resolver.session,
489 "`self` import can only appear once in the list");
491 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
492 span_err!(resolver.session,
495 "`self` import can only appear in an import list with a non-empty prefix");
497 ResolutionError::UnresolvedImport(name) => {
498 let msg = match name {
499 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
500 None => "unresolved import".to_owned(),
502 span_err!(resolver.session, span, E0432, "{}", msg);
504 ResolutionError::FailedToResolve(msg) => {
505 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
507 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
508 span_err!(resolver.session,
512 "can't capture dynamic environment in a fn item; use the || { ... } \
513 closure form instead");
515 ResolutionError::AttemptToUseNonConstantValueInConstant => {
516 span_err!(resolver.session,
519 "attempt to use a non-constant value in a constant");
524 #[derive(Copy, Clone)]
527 binding_mode: BindingMode,
530 // Map from the name in a pattern to its binding mode.
531 type BindingMap = HashMap<Name, BindingInfo>;
533 #[derive(Copy, Clone, PartialEq)]
534 enum PatternBindingMode {
536 LocalIrrefutableMode,
537 ArgumentIrrefutableMode,
540 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
546 /// A NamespaceResult represents the result of resolving an import in
547 /// a particular namespace. The result is either definitely-resolved,
548 /// definitely- unresolved, or unknown.
550 enum NamespaceResult {
551 /// Means that resolve hasn't gathered enough information yet to determine
552 /// whether the name is bound in this namespace. (That is, it hasn't
553 /// resolved all `use` directives yet.)
555 /// Means that resolve has determined that the name is definitely
556 /// not bound in the namespace.
558 /// Means that resolve has determined that the name is bound in the Module
559 /// argument, and specified by the NameBinding argument.
560 BoundResult(Rc<Module>, NameBinding),
563 impl NamespaceResult {
564 fn is_unknown(&self) -> bool {
566 UnknownResult => true,
570 fn is_unbound(&self) -> bool {
572 UnboundResult => true,
578 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
579 fn visit_nested_item(&mut self, item: hir::ItemId) {
580 self.visit_item(self.ast_map.expect_item(item.id))
582 fn visit_item(&mut self, item: &Item) {
583 execute_callback!(hir_map::Node::NodeItem(item), self);
584 self.resolve_item(item);
586 fn visit_arm(&mut self, arm: &Arm) {
587 self.resolve_arm(arm);
589 fn visit_block(&mut self, block: &Block) {
590 execute_callback!(hir_map::Node::NodeBlock(block), self);
591 self.resolve_block(block);
593 fn visit_expr(&mut self, expr: &Expr) {
594 execute_callback!(hir_map::Node::NodeExpr(expr), self);
595 self.resolve_expr(expr);
597 fn visit_local(&mut self, local: &Local) {
598 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
599 self.resolve_local(local);
601 fn visit_ty(&mut self, ty: &Ty) {
602 self.resolve_type(ty);
604 fn visit_generics(&mut self, generics: &Generics) {
605 self.resolve_generics(generics);
607 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
608 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
609 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
611 // error already reported
612 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
615 intravisit::walk_poly_trait_ref(self, tref, m);
617 fn visit_variant(&mut self,
618 variant: &hir::Variant,
620 item_id: ast::NodeId) {
621 execute_callback!(hir_map::Node::NodeVariant(variant), self);
622 if let Some(ref dis_expr) = variant.node.disr_expr {
623 // resolve the discriminator expr as a constant
624 self.with_constant_rib(|this| {
625 this.visit_expr(dis_expr);
629 // `intravisit::walk_variant` without the discriminant expression.
630 self.visit_variant_data(&variant.node.data,
636 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
637 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
638 let type_parameters = match foreign_item.node {
639 ForeignItemFn(_, ref generics) => {
640 HasTypeParameters(generics, FnSpace, ItemRibKind)
642 ForeignItemStatic(..) => NoTypeParameters,
644 self.with_type_parameter_rib(type_parameters, |this| {
645 intravisit::walk_foreign_item(this, foreign_item);
648 fn visit_fn(&mut self,
649 function_kind: FnKind<'v>,
650 declaration: &'v FnDecl,
654 let rib_kind = match function_kind {
655 FnKind::ItemFn(_, generics, _, _, _, _) => {
656 self.visit_generics(generics);
659 FnKind::Method(_, sig, _) => {
660 self.visit_generics(&sig.generics);
661 self.visit_explicit_self(&sig.explicit_self);
664 FnKind::Closure => ClosureRibKind(node_id),
666 self.resolve_function(rib_kind, declaration, block);
670 type ErrorMessage = Option<(Span, String)>;
672 enum ResolveResult<T> {
673 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
674 Indeterminate, // Couldn't determine due to unresolved globs.
675 Success(T), // Successfully resolved the import.
678 impl<T> ResolveResult<T> {
679 fn success(&self) -> bool {
687 enum FallbackSuggestion {
692 StaticMethod(String),
696 #[derive(Copy, Clone)]
697 enum TypeParameters<'a> {
699 HasTypeParameters(// Type parameters.
702 // Identifies the things that these parameters
703 // were declared on (type, fn, etc)
706 // The kind of the rib used for type parameters.
710 // The rib kind controls the translation of local
711 // definitions (`DefLocal`) to upvars (`DefUpvar`).
712 #[derive(Copy, Clone, Debug)]
714 // No translation needs to be applied.
717 // We passed through a closure scope at the given node ID.
718 // Translate upvars as appropriate.
719 ClosureRibKind(NodeId /* func id */),
721 // We passed through an impl or trait and are now in one of its
722 // methods. Allow references to ty params that impl or trait
723 // binds. Disallow any other upvars (including other ty params that are
727 // We passed through an item scope. Disallow upvars.
730 // We're in a constant item. Can't refer to dynamic stuff.
734 #[derive(Copy, Clone)]
735 enum UseLexicalScopeFlag {
740 enum ModulePrefixResult {
742 PrefixFound(Rc<Module>, usize),
745 #[derive(Copy, Clone)]
746 enum AssocItemResolveResult {
747 /// Syntax such as `<T>::item`, which can't be resolved until type
750 /// We should have been able to resolve the associated item.
751 ResolveAttempt(Option<PathResolution>),
754 #[derive(Copy, Clone, PartialEq)]
755 enum NameSearchType {
756 /// We're doing a name search in order to resolve a `use` directive.
759 /// We're doing a name search in order to resolve a path type, a path
760 /// expression, or a path pattern.
764 #[derive(Copy, Clone)]
765 enum BareIdentifierPatternResolution {
766 FoundStructOrEnumVariant(Def, LastPrivate),
767 FoundConst(Def, LastPrivate, Name),
768 BareIdentifierPatternUnresolved,
774 bindings: HashMap<Name, DefLike>,
779 fn new(kind: RibKind) -> Rib {
781 bindings: HashMap::new(),
787 /// A definition along with the index of the rib it was found on
789 ribs: Option<(Namespace, usize)>,
794 fn from_def(def: Def) -> Self {
802 /// The link from a module up to its nearest parent node.
803 #[derive(Clone,Debug)]
806 ModuleParentLink(Weak<Module>, Name),
807 BlockParentLink(Weak<Module>, NodeId),
810 /// One node in the tree of modules.
812 parent_link: ParentLink,
813 def: Cell<Option<Def>>,
816 children: RefCell<HashMap<Name, NameBindings>>,
817 imports: RefCell<Vec<ImportDirective>>,
819 // The external module children of this node that were declared with
821 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
823 // The anonymous children of this node. Anonymous children are pseudo-
824 // modules that are implicitly created around items contained within
827 // For example, if we have this:
835 // There will be an anonymous module created around `g` with the ID of the
836 // entry block for `f`.
837 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
839 // The status of resolving each import in this module.
840 import_resolutions: RefCell<HashMap<Name, ImportResolutionPerNamespace>>,
842 // The number of unresolved globs that this module exports.
843 glob_count: Cell<usize>,
845 // The number of unresolved pub imports (both regular and globs) in this module
846 pub_count: Cell<usize>,
848 // The number of unresolved pub glob imports in this module
849 pub_glob_count: Cell<usize>,
851 // The index of the import we're resolving.
852 resolved_import_count: Cell<usize>,
854 // Whether this module is populated. If not populated, any attempt to
855 // access the children must be preceded with a
856 // `populate_module_if_necessary` call.
857 populated: Cell<bool>,
861 fn new(parent_link: ParentLink,
867 parent_link: parent_link,
869 is_public: is_public,
870 children: RefCell::new(HashMap::new()),
871 imports: RefCell::new(Vec::new()),
872 external_module_children: RefCell::new(HashMap::new()),
873 anonymous_children: RefCell::new(NodeMap()),
874 import_resolutions: RefCell::new(HashMap::new()),
875 glob_count: Cell::new(0),
876 pub_count: Cell::new(0),
877 pub_glob_count: Cell::new(0),
878 resolved_import_count: Cell::new(0),
879 populated: Cell::new(!external),
883 fn def_id(&self) -> Option<DefId> {
884 self.def.get().as_ref().map(Def::def_id)
887 fn is_normal(&self) -> bool {
888 match self.def.get() {
889 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
894 fn is_trait(&self) -> bool {
895 match self.def.get() {
896 Some(DefTrait(_)) => true,
901 fn all_imports_resolved(&self) -> bool {
902 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
903 // it is currently being resolved ! so nope
906 self.imports.borrow().len() == self.resolved_import_count.get()
912 pub fn inc_glob_count(&self) {
913 self.glob_count.set(self.glob_count.get() + 1);
915 pub fn dec_glob_count(&self) {
916 assert!(self.glob_count.get() > 0);
917 self.glob_count.set(self.glob_count.get() - 1);
919 pub fn inc_pub_count(&self) {
920 self.pub_count.set(self.pub_count.get() + 1);
922 pub fn dec_pub_count(&self) {
923 assert!(self.pub_count.get() > 0);
924 self.pub_count.set(self.pub_count.get() - 1);
926 pub fn inc_pub_glob_count(&self) {
927 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
929 pub fn dec_pub_glob_count(&self) {
930 assert!(self.pub_glob_count.get() > 0);
931 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
935 impl fmt::Debug for Module {
936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
950 flags DefModifiers: u8 {
951 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
952 // or `use Enum::*` to work on private enums.
953 const PUBLIC = 1 << 0,
954 const IMPORTABLE = 1 << 1,
955 // Variants are considered `PUBLIC`, but some of them live in private enums.
956 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
957 const PRIVATE_VARIANT = 1 << 2,
961 // Records a possibly-private value, type, or module definition.
964 modifiers: DefModifiers, // see note in ImportResolutionPerNamespace about how to use this
965 def_or_module: DefOrModule,
976 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
977 let modifiers = if module.is_public {
980 DefModifiers::empty()
981 } | DefModifiers::IMPORTABLE;
983 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
986 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
987 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
990 fn module(&self) -> Option<Rc<Module>> {
991 match self.def_or_module {
992 DefOrModule::Module(ref module) => Some(module.clone()),
993 DefOrModule::Def(_) => None,
997 fn def(&self) -> Option<Def> {
998 match self.def_or_module {
999 DefOrModule::Def(def) => Some(def),
1000 DefOrModule::Module(ref module) => module.def.get(),
1005 // Records at most one definition that a name in a namespace is bound to
1006 #[derive(Clone,Debug)]
1007 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
1011 NameBinding(Rc::new(RefCell::new(None)))
1014 fn create_from_module(module: Rc<Module>) -> Self {
1015 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
1018 fn set(&self, ns_def: NsDef) {
1019 *self.0.borrow_mut() = Some(ns_def);
1022 fn set_modifiers(&self, modifiers: DefModifiers) {
1023 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
1024 ns_def.modifiers = modifiers
1028 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> {
1032 // Lifted versions of the NsDef methods and fields
1033 fn def(&self) -> Option<Def> {
1034 self.borrow().as_ref().and_then(NsDef::def)
1036 fn module(&self) -> Option<Rc<Module>> {
1037 self.borrow().as_ref().and_then(NsDef::module)
1039 fn span(&self) -> Option<Span> {
1040 self.borrow().as_ref().and_then(|def| def.span)
1042 fn modifiers(&self) -> Option<DefModifiers> {
1043 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
1046 fn defined(&self) -> bool {
1047 self.borrow().is_some()
1050 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1051 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1054 fn is_public(&self) -> bool {
1055 self.defined_with(DefModifiers::PUBLIC)
1058 fn def_and_lp(&self) -> (Def, LastPrivate) {
1059 let def = self.def().unwrap();
1060 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1064 // Records the definitions (at most one for each namespace) that a name is
1066 #[derive(Clone,Debug)]
1067 pub struct NameBindings {
1068 type_ns: NameBinding, // < Meaning in type namespace.
1069 value_ns: NameBinding, // < Meaning in value namespace.
1072 impl ::std::ops::Index<Namespace> for NameBindings {
1073 type Output = NameBinding;
1074 fn index(&self, namespace: Namespace) -> &NameBinding {
1075 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1080 fn new() -> NameBindings {
1082 type_ns: NameBinding::new(),
1083 value_ns: NameBinding::new(),
1087 /// Creates a new module in this set of name bindings.
1088 fn define_module(&self, module: Rc<Module>, sp: Span) {
1089 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1092 /// Records a type definition.
1093 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1094 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1095 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1098 /// Records a value definition.
1099 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1100 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1101 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1105 /// Interns the names of the primitive types.
1106 struct PrimitiveTypeTable {
1107 primitive_types: HashMap<Name, PrimTy>,
1110 impl PrimitiveTypeTable {
1111 fn new() -> PrimitiveTypeTable {
1112 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1114 table.intern("bool", TyBool);
1115 table.intern("char", TyChar);
1116 table.intern("f32", TyFloat(TyF32));
1117 table.intern("f64", TyFloat(TyF64));
1118 table.intern("isize", TyInt(TyIs));
1119 table.intern("i8", TyInt(TyI8));
1120 table.intern("i16", TyInt(TyI16));
1121 table.intern("i32", TyInt(TyI32));
1122 table.intern("i64", TyInt(TyI64));
1123 table.intern("str", TyStr);
1124 table.intern("usize", TyUint(TyUs));
1125 table.intern("u8", TyUint(TyU8));
1126 table.intern("u16", TyUint(TyU16));
1127 table.intern("u32", TyUint(TyU32));
1128 table.intern("u64", TyUint(TyU64));
1133 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1134 self.primitive_types.insert(token::intern(string), primitive_type);
1138 /// The main resolver class.
1139 pub struct Resolver<'a, 'tcx: 'a> {
1140 session: &'a Session,
1142 ast_map: &'a hir_map::Map<'tcx>,
1144 graph_root: Rc<Module>,
1146 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1148 structs: FnvHashMap<DefId, Vec<Name>>,
1150 // The number of imports that are currently unresolved.
1151 unresolved_imports: usize,
1153 // The module that represents the current item scope.
1154 current_module: Rc<Module>,
1156 // The current set of local scopes, for values.
1157 // FIXME #4948: Reuse ribs to avoid allocation.
1158 value_ribs: Vec<Rib>,
1160 // The current set of local scopes, for types.
1161 type_ribs: Vec<Rib>,
1163 // The current set of local scopes, for labels.
1164 label_ribs: Vec<Rib>,
1166 // The trait that the current context can refer to.
1167 current_trait_ref: Option<(DefId, TraitRef)>,
1169 // The current self type if inside an impl (used for better errors).
1170 current_self_type: Option<Ty>,
1172 // The idents for the primitive types.
1173 primitive_type_table: PrimitiveTypeTable,
1175 def_map: RefCell<DefMap>,
1176 freevars: FreevarMap,
1177 freevars_seen: NodeMap<NodeMap<usize>>,
1178 export_map: ExportMap,
1179 trait_map: TraitMap,
1180 external_exports: ExternalExports,
1182 // Whether or not to print error messages. Can be set to true
1183 // when getting additional info for error message suggestions,
1184 // so as to avoid printing duplicate errors
1187 make_glob_map: bool,
1188 // Maps imports to the names of items actually imported (this actually maps
1189 // all imports, but only glob imports are actually interesting).
1192 used_imports: HashSet<(NodeId, Namespace)>,
1193 used_crates: HashSet<CrateNum>,
1195 // Callback function for intercepting walks
1196 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1197 // The intention is that the callback modifies this flag.
1198 // Once set, the resolver falls out of the walk, preserving the ribs.
1202 #[derive(PartialEq)]
1203 enum FallbackChecks {
1205 OnlyTraitAndStatics,
1208 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1209 fn new(session: &'a Session,
1210 ast_map: &'a hir_map::Map<'tcx>,
1211 make_glob_map: MakeGlobMap)
1212 -> Resolver<'a, 'tcx> {
1213 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1214 let graph_root = Module::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1221 // The outermost module has def ID 0; this is not reflected in the
1223 graph_root: graph_root.clone(),
1225 trait_item_map: FnvHashMap(),
1226 structs: FnvHashMap(),
1228 unresolved_imports: 0,
1230 current_module: graph_root,
1231 value_ribs: Vec::new(),
1232 type_ribs: Vec::new(),
1233 label_ribs: Vec::new(),
1235 current_trait_ref: None,
1236 current_self_type: None,
1238 primitive_type_table: PrimitiveTypeTable::new(),
1240 def_map: RefCell::new(NodeMap()),
1241 freevars: NodeMap(),
1242 freevars_seen: NodeMap(),
1243 export_map: NodeMap(),
1244 trait_map: NodeMap(),
1245 used_imports: HashSet::new(),
1246 used_crates: HashSet::new(),
1247 external_exports: DefIdSet(),
1250 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1251 glob_map: HashMap::new(),
1259 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1260 if !self.make_glob_map {
1263 if self.glob_map.contains_key(&import_id) {
1264 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1268 let mut new_set = HashSet::new();
1269 new_set.insert(name);
1270 self.glob_map.insert(import_id, new_set);
1273 fn get_trait_name(&self, did: DefId) -> Name {
1274 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1275 self.ast_map.expect_item(node_id).name
1277 self.session.cstore.item_name(did)
1281 /// Checks that the names of external crates don't collide with other
1282 /// external crates.
1283 fn check_for_conflicts_between_external_crates(&self,
1287 if module.external_module_children.borrow().contains_key(&name) {
1288 span_err!(self.session,
1291 "an external crate named `{}` has already been imported into this module",
1296 /// Checks that the names of items don't collide with external crates.
1297 fn check_for_conflicts_between_external_crates_and_items(&self,
1301 if module.external_module_children.borrow().contains_key(&name) {
1302 span_err!(self.session,
1305 "the name `{}` conflicts with an external crate that has been imported \
1311 /// Resolves the given module path from the given root `module_`.
1312 fn resolve_module_path_from_root(&mut self,
1313 module_: Rc<Module>,
1314 module_path: &[Name],
1317 name_search_type: NameSearchType,
1319 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1320 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1321 match module.external_module_children.borrow().get(&needle) {
1322 Some(_) => Some(module.clone()),
1323 None => match module.parent_link {
1324 ModuleParentLink(ref parent, _) => {
1325 search_parent_externals(needle, &parent.upgrade().unwrap())
1332 let mut search_module = module_;
1333 let mut index = index;
1334 let module_path_len = module_path.len();
1335 let mut closest_private = lp;
1337 // Resolve the module part of the path. This does not involve looking
1338 // upward though scope chains; we simply resolve names directly in
1339 // modules as we go.
1340 while index < module_path_len {
1341 let name = module_path[index];
1342 match self.resolve_name_in_module(search_module.clone(),
1348 let segment_name = name.as_str();
1349 let module_name = module_to_string(&*search_module);
1350 let mut span = span;
1351 let msg = if "???" == &module_name[..] {
1352 span.hi = span.lo + Pos::from_usize(segment_name.len());
1354 match search_parent_externals(name, &self.current_module) {
1356 let path_str = names_to_string(module_path);
1357 let target_mod_str = module_to_string(&*module);
1358 let current_mod_str = module_to_string(&*self.current_module);
1360 let prefix = if target_mod_str == current_mod_str {
1361 "self::".to_string()
1363 format!("{}::", target_mod_str)
1366 format!("Did you mean `{}{}`?", prefix, path_str)
1368 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1371 format!("Could not find `{}` in `{}`", segment_name, module_name)
1374 return Failed(Some((span, msg)));
1376 Failed(err) => return Failed(err),
1378 debug!("(resolving module path for import) module resolution is \
1381 return Indeterminate;
1383 Success((target, used_proxy)) => {
1384 // Check to see whether there are type bindings, and, if
1385 // so, whether there is a module within.
1386 if let Some(module_def) = target.binding.module() {
1387 // track extern crates for unused_extern_crate lint
1388 if let Some(did) = module_def.def_id() {
1389 self.used_crates.insert(did.krate);
1392 search_module = module_def;
1394 // Keep track of the closest private module used
1395 // when resolving this import chain.
1396 if !used_proxy && !search_module.is_public {
1397 if let Some(did) = search_module.def_id() {
1398 closest_private = LastMod(DependsOn(did));
1402 let msg = format!("Not a module `{}`", name);
1403 return Failed(Some((span, msg)));
1411 return Success((search_module, closest_private));
1414 /// Attempts to resolve the module part of an import directive or path
1415 /// rooted at the given module.
1417 /// On success, returns the resolved module, and the closest *private*
1418 /// module found to the destination when resolving this path.
1419 fn resolve_module_path(&mut self,
1420 module_: Rc<Module>,
1421 module_path: &[Name],
1422 use_lexical_scope: UseLexicalScopeFlag,
1424 name_search_type: NameSearchType)
1425 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1426 let module_path_len = module_path.len();
1427 assert!(module_path_len > 0);
1429 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1430 names_to_string(module_path),
1431 module_to_string(&*module_));
1433 // Resolve the module prefix, if any.
1434 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1439 match module_prefix_result {
1441 let mpath = names_to_string(module_path);
1442 let mpath = &mpath[..];
1443 match mpath.rfind(':') {
1445 let msg = format!("Could not find `{}` in `{}`",
1446 // idx +- 1 to account for the
1447 // colons on either side
1450 return Failed(Some((span, msg)));
1453 return Failed(None);
1457 Failed(err) => return Failed(err),
1459 debug!("(resolving module path for import) indeterminate; bailing");
1460 return Indeterminate;
1462 Success(NoPrefixFound) => {
1463 // There was no prefix, so we're considering the first element
1464 // of the path. How we handle this depends on whether we were
1465 // instructed to use lexical scope or not.
1466 match use_lexical_scope {
1467 DontUseLexicalScope => {
1468 // This is a crate-relative path. We will start the
1469 // resolution process at index zero.
1470 search_module = self.graph_root.clone();
1472 last_private = LastMod(AllPublic);
1474 UseLexicalScope => {
1475 // This is not a crate-relative path. We resolve the
1476 // first component of the path in the current lexical
1477 // scope and then proceed to resolve below that.
1478 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1479 Failed(err) => return Failed(err),
1481 debug!("(resolving module path for import) indeterminate; bailing");
1482 return Indeterminate;
1484 Success(containing_module) => {
1485 search_module = containing_module;
1487 last_private = LastMod(AllPublic);
1493 Success(PrefixFound(ref containing_module, index)) => {
1494 search_module = containing_module.clone();
1495 start_index = index;
1496 last_private = LastMod(DependsOn(containing_module.def_id()
1501 self.resolve_module_path_from_root(search_module,
1509 /// Invariant: This must only be called during main resolution, not during
1510 /// import resolution.
1511 fn resolve_item_in_lexical_scope(&mut self,
1512 module_: Rc<Module>,
1514 namespace: Namespace,
1516 -> ResolveResult<(Target, bool)> {
1517 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1520 module_to_string(&*module_));
1522 // The current module node is handled specially. First, check for
1523 // its immediate children.
1524 build_reduced_graph::populate_module_if_necessary(self, &module_);
1526 match module_.children.borrow().get(&name) {
1527 Some(name_bindings) if name_bindings[namespace].defined() => {
1528 debug!("top name bindings succeeded");
1529 return Success((Target::new(module_.clone(),
1530 name_bindings[namespace].clone(),
1535 // Not found; continue.
1539 // Now check for its import directives. We don't have to have resolved
1540 // all its imports in the usual way; this is because chains of
1541 // adjacent import statements are processed as though they mutated the
1543 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1544 match import_resolution[namespace].target.clone() {
1546 // Not found; continue.
1547 debug!("(resolving item in lexical scope) found import resolution, but not \
1552 debug!("(resolving item in lexical scope) using import resolution");
1553 // track used imports and extern crates as well
1554 let id = import_resolution[namespace].id;
1556 self.used_imports.insert((id, namespace));
1557 self.record_import_use(id, name);
1558 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1559 self.used_crates.insert(kid);
1562 return Success((target, false));
1567 // Search for external modules.
1568 if namespace == TypeNS {
1569 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1570 let child = module_.external_module_children.borrow().get(&name).cloned();
1571 if let Some(module) = child {
1572 let name_binding = NameBinding::create_from_module(module);
1573 debug!("lower name bindings succeeded");
1574 return Success((Target::new(module_, name_binding, Shadowable::Never),
1579 // Finally, proceed up the scope chain looking for parent modules.
1580 let mut search_module = module_;
1582 // Go to the next parent.
1583 match search_module.parent_link.clone() {
1585 // No more parents. This module was unresolved.
1586 debug!("(resolving item in lexical scope) unresolved module");
1587 return Failed(None);
1589 ModuleParentLink(parent_module_node, _) => {
1590 if search_module.is_normal() {
1591 // We stop the search here.
1592 debug!("(resolving item in lexical scope) unresolved module: not \
1593 searching through module parents");
1594 return Failed(None);
1596 search_module = parent_module_node.upgrade().unwrap();
1599 BlockParentLink(ref parent_module_node, _) => {
1600 search_module = parent_module_node.upgrade().unwrap();
1604 // Resolve the name in the parent module.
1605 match self.resolve_name_in_module(search_module.clone(),
1610 Failed(Some((span, msg))) => {
1611 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1613 Failed(None) => (), // Continue up the search chain.
1615 // We couldn't see through the higher scope because of an
1616 // unresolved import higher up. Bail.
1618 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1619 return Indeterminate;
1621 Success((target, used_reexport)) => {
1622 // We found the module.
1623 debug!("(resolving item in lexical scope) found name in module, done");
1624 return Success((target, used_reexport));
1630 /// Resolves a module name in the current lexical scope.
1631 fn resolve_module_in_lexical_scope(&mut self,
1632 module_: Rc<Module>,
1634 -> ResolveResult<Rc<Module>> {
1635 // If this module is an anonymous module, resolve the item in the
1636 // lexical scope. Otherwise, resolve the item from the crate root.
1637 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS, true);
1638 match resolve_result {
1639 Success((target, _)) => {
1640 if let Some(module_def) = target.binding.module() {
1641 return Success(module_def)
1643 debug!("!!! (resolving module in lexical scope) module \
1644 wasn't actually a module!");
1645 return Failed(None);
1649 debug!("(resolving module in lexical scope) indeterminate; bailing");
1650 return Indeterminate;
1653 debug!("(resolving module in lexical scope) failed to resolve");
1659 /// Returns the nearest normal module parent of the given module.
1660 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1661 let mut module_ = module_;
1663 match module_.parent_link.clone() {
1664 NoParentLink => return None,
1665 ModuleParentLink(new_module, _) |
1666 BlockParentLink(new_module, _) => {
1667 let new_module = new_module.upgrade().unwrap();
1668 if new_module.is_normal() {
1669 return Some(new_module);
1671 module_ = new_module;
1677 /// Returns the nearest normal module parent of the given module, or the
1678 /// module itself if it is a normal module.
1679 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1680 if module_.is_normal() {
1683 match self.get_nearest_normal_module_parent(module_.clone()) {
1685 Some(new_module) => new_module,
1689 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1690 /// (b) some chain of `super::`.
1691 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1692 fn resolve_module_prefix(&mut self,
1693 module_: Rc<Module>,
1694 module_path: &[Name])
1695 -> ResolveResult<ModulePrefixResult> {
1696 // Start at the current module if we see `self` or `super`, or at the
1697 // top of the crate otherwise.
1698 let mut i = match &*module_path[0].as_str() {
1701 _ => return Success(NoPrefixFound),
1703 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1705 // Now loop through all the `super`s we find.
1706 while i < module_path.len() && "super" == module_path[i].as_str() {
1707 debug!("(resolving module prefix) resolving `super` at {}",
1708 module_to_string(&*containing_module));
1709 match self.get_nearest_normal_module_parent(containing_module) {
1710 None => return Failed(None),
1711 Some(new_module) => {
1712 containing_module = new_module;
1718 debug!("(resolving module prefix) finished resolving prefix at {}",
1719 module_to_string(&*containing_module));
1721 return Success(PrefixFound(containing_module, i));
1724 /// Attempts to resolve the supplied name in the given module for the
1725 /// given namespace. If successful, returns the target corresponding to
1728 /// The boolean returned on success is an indicator of whether this lookup
1729 /// passed through a public re-export proxy.
1730 fn resolve_name_in_module(&mut self,
1731 module_: Rc<Module>,
1733 namespace: Namespace,
1734 name_search_type: NameSearchType,
1735 allow_private_imports: bool)
1736 -> ResolveResult<(Target, bool)> {
1737 debug!("(resolving name in module) resolving `{}` in `{}`",
1739 module_to_string(&*module_));
1741 // First, check the direct children of the module.
1742 build_reduced_graph::populate_module_if_necessary(self, &module_);
1744 match module_.children.borrow().get(&name) {
1745 Some(name_bindings) if name_bindings[namespace].defined() => {
1746 debug!("(resolving name in module) found node as child");
1747 return Success((Target::new(module_.clone(),
1748 name_bindings[namespace].clone(),
1757 // Next, check the module's imports if necessary.
1759 // If this is a search of all imports, we should be done with glob
1760 // resolution at this point.
1761 if name_search_type == PathSearch {
1762 assert_eq!(module_.glob_count.get(), 0);
1765 // Check the list of resolved imports.
1766 match module_.import_resolutions.borrow().get(&name) {
1767 Some(import_resolution) if allow_private_imports ||
1768 import_resolution[namespace].is_public => {
1770 if import_resolution[namespace].is_public &&
1771 import_resolution.outstanding_references != 0 {
1772 debug!("(resolving name in module) import unresolved; bailing out");
1773 return Indeterminate;
1775 match import_resolution[namespace].target.clone() {
1777 debug!("(resolving name in module) name found, but not in namespace {:?}",
1781 debug!("(resolving name in module) resolved to import");
1782 // track used imports and extern crates as well
1783 let id = import_resolution[namespace].id;
1784 self.used_imports.insert((id, namespace));
1785 self.record_import_use(id, name);
1786 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1787 self.used_crates.insert(kid);
1789 return Success((target, true));
1793 Some(..) | None => {} // Continue.
1796 // Finally, search through external children.
1797 if namespace == TypeNS {
1798 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1799 let child = module_.external_module_children.borrow().get(&name).cloned();
1800 if let Some(module) = child {
1801 let name_binding = NameBinding::create_from_module(module);
1802 return Success((Target::new(module_, name_binding, Shadowable::Never),
1807 // We're out of luck.
1808 debug!("(resolving name in module) failed to resolve `{}`", name);
1809 return Failed(None);
1812 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1813 let index = module_.resolved_import_count.get();
1814 let imports = module_.imports.borrow();
1815 let import_count = imports.len();
1816 if index != import_count {
1818 (*imports)[index].span,
1819 ResolutionError::UnresolvedImport(None));
1822 // Descend into children and anonymous children.
1823 build_reduced_graph::populate_module_if_necessary(self, &module_);
1825 for (_, child_node) in module_.children.borrow().iter() {
1826 match child_node.type_ns.module() {
1830 Some(child_module) => {
1831 self.report_unresolved_imports(child_module);
1836 for (_, module_) in module_.anonymous_children.borrow().iter() {
1837 self.report_unresolved_imports(module_.clone());
1843 // We maintain a list of value ribs and type ribs.
1845 // Simultaneously, we keep track of the current position in the module
1846 // graph in the `current_module` pointer. When we go to resolve a name in
1847 // the value or type namespaces, we first look through all the ribs and
1848 // then query the module graph. When we resolve a name in the module
1849 // namespace, we can skip all the ribs (since nested modules are not
1850 // allowed within blocks in Rust) and jump straight to the current module
1853 // Named implementations are handled separately. When we find a method
1854 // call, we consult the module node to find all of the implementations in
1855 // scope. This information is lazily cached in the module node. We then
1856 // generate a fake "implementation scope" containing all the
1857 // implementations thus found, for compatibility with old resolve pass.
1859 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1860 where F: FnOnce(&mut Resolver)
1862 let orig_module = self.current_module.clone();
1864 // Move down in the graph.
1870 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1872 match orig_module.children.borrow().get(&name) {
1874 debug!("!!! (with scope) didn't find `{}` in `{}`",
1876 module_to_string(&*orig_module));
1878 Some(name_bindings) => {
1879 match name_bindings.type_ns.module() {
1881 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1883 module_to_string(&*orig_module));
1886 self.current_module = module_;
1896 self.current_module = orig_module;
1899 /// Searches the current set of local scopes for labels.
1900 /// Stops after meeting a closure.
1901 fn search_label(&self, name: Name) -> Option<DefLike> {
1902 for rib in self.label_ribs.iter().rev() {
1908 // Do not resolve labels across function boundary
1912 let result = rib.bindings.get(&name).cloned();
1913 if result.is_some() {
1920 fn resolve_crate(&mut self, krate: &hir::Crate) {
1921 debug!("(resolving crate) starting");
1923 intravisit::walk_crate(self, krate);
1926 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1927 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1928 span_err!(self.session,
1931 "user-defined types or type parameters cannot shadow the primitive types");
1935 fn resolve_item(&mut self, item: &Item) {
1936 let name = item.name;
1938 debug!("(resolving item) resolving {}", name);
1941 ItemEnum(_, ref generics) |
1942 ItemTy(_, ref generics) |
1943 ItemStruct(_, ref generics) => {
1944 self.check_if_primitive_type_name(name, item.span);
1946 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1947 |this| intravisit::walk_item(this, item));
1949 ItemFn(_, _, _, _, ref generics, _) => {
1950 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1951 |this| intravisit::walk_item(this, item));
1954 ItemDefaultImpl(_, ref trait_ref) => {
1955 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1957 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1958 self.resolve_implementation(generics,
1965 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1966 self.check_if_primitive_type_name(name, item.span);
1968 // Create a new rib for the trait-wide type parameters.
1969 self.with_type_parameter_rib(HasTypeParameters(generics,
1973 let local_def_id = this.ast_map.local_def_id(item.id);
1974 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1975 this.visit_generics(generics);
1976 walk_list!(this, visit_ty_param_bound, bounds);
1978 for trait_item in trait_items {
1979 match trait_item.node {
1980 hir::ConstTraitItem(_, ref default) => {
1981 // Only impose the restrictions of
1982 // ConstRibKind if there's an actual constant
1983 // expression in a provided default.
1984 if default.is_some() {
1985 this.with_constant_rib(|this| {
1986 intravisit::walk_trait_item(this, trait_item)
1989 intravisit::walk_trait_item(this, trait_item)
1992 hir::MethodTraitItem(ref sig, _) => {
1993 let type_parameters =
1994 HasTypeParameters(&sig.generics,
1997 this.with_type_parameter_rib(type_parameters, |this| {
1998 intravisit::walk_trait_item(this, trait_item)
2001 hir::TypeTraitItem(..) => {
2002 this.check_if_primitive_type_name(trait_item.name,
2004 this.with_type_parameter_rib(NoTypeParameters, |this| {
2005 intravisit::walk_trait_item(this, trait_item)
2014 ItemMod(_) | ItemForeignMod(_) => {
2015 self.with_scope(Some(name), |this| {
2016 intravisit::walk_item(this, item);
2020 ItemConst(..) | ItemStatic(..) => {
2021 self.with_constant_rib(|this| {
2022 intravisit::walk_item(this, item);
2026 ItemUse(ref view_path) => {
2027 // check for imports shadowing primitive types
2028 let check_rename = |this: &Self, id, name| {
2029 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
2030 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2031 this.check_if_primitive_type_name(name, item.span);
2037 match view_path.node {
2038 hir::ViewPathSimple(name, _) => {
2039 check_rename(self, item.id, name);
2041 hir::ViewPathList(ref prefix, ref items) => {
2043 if let Some(name) = item.node.rename() {
2044 check_rename(self, item.node.id(), name);
2048 // Resolve prefix of an import with empty braces (issue #28388)
2049 if items.is_empty() && !prefix.segments.is_empty() {
2050 match self.resolve_crate_relative_path(prefix.span,
2054 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2058 ResolutionError::FailedToResolve(
2059 &path_names_to_string(prefix, 0)));
2060 self.record_def(item.id, err_path_resolution());
2069 ItemExternCrate(_) => {
2070 // do nothing, these are just around to be encoded
2075 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2076 where F: FnOnce(&mut Resolver)
2078 match type_parameters {
2079 HasTypeParameters(generics, space, rib_kind) => {
2080 let mut function_type_rib = Rib::new(rib_kind);
2081 let mut seen_bindings = HashSet::new();
2082 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2083 let name = type_parameter.name;
2084 debug!("with_type_parameter_rib: {}", type_parameter.id);
2086 if seen_bindings.contains(&name) {
2088 type_parameter.span,
2089 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2091 seen_bindings.insert(name);
2093 // plain insert (no renaming)
2094 function_type_rib.bindings
2096 DlDef(DefTyParam(space,
2099 .local_def_id(type_parameter.id),
2102 self.type_ribs.push(function_type_rib);
2105 NoTypeParameters => {
2112 match type_parameters {
2113 HasTypeParameters(..) => {
2115 self.type_ribs.pop();
2118 NoTypeParameters => {}
2122 fn with_label_rib<F>(&mut self, f: F)
2123 where F: FnOnce(&mut Resolver)
2125 self.label_ribs.push(Rib::new(NormalRibKind));
2128 self.label_ribs.pop();
2132 fn with_constant_rib<F>(&mut self, f: F)
2133 where F: FnOnce(&mut Resolver)
2135 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2136 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2139 self.type_ribs.pop();
2140 self.value_ribs.pop();
2144 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2145 // Create a value rib for the function.
2146 self.value_ribs.push(Rib::new(rib_kind));
2148 // Create a label rib for the function.
2149 self.label_ribs.push(Rib::new(rib_kind));
2151 // Add each argument to the rib.
2152 let mut bindings_list = HashMap::new();
2153 for argument in &declaration.inputs {
2154 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2156 self.visit_ty(&*argument.ty);
2158 debug!("(resolving function) recorded argument");
2160 intravisit::walk_fn_ret_ty(self, &declaration.output);
2162 // Resolve the function body.
2163 self.visit_block(block);
2165 debug!("(resolving function) leaving function");
2168 self.label_ribs.pop();
2169 self.value_ribs.pop();
2173 fn resolve_trait_reference(&mut self,
2177 -> Result<PathResolution, ()> {
2178 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2179 if let DefTrait(_) = path_res.base_def {
2180 debug!("(resolving trait) found trait def: {:?}", path_res);
2185 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2188 // If it's a typedef, give a note
2189 if let DefTy(..) = path_res.base_def {
2191 .span_note(trait_path.span, "`type` aliases cannot be used for traits");
2198 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2204 fn resolve_generics(&mut self, generics: &Generics) {
2205 for type_parameter in generics.ty_params.iter() {
2206 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2208 for predicate in &generics.where_clause.predicates {
2210 &hir::WherePredicate::BoundPredicate(_) |
2211 &hir::WherePredicate::RegionPredicate(_) => {}
2212 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2213 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2214 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2215 self.record_def(eq_pred.id, path_res.unwrap());
2219 ResolutionError::UndeclaredAssociatedType);
2220 self.record_def(eq_pred.id, err_path_resolution());
2225 intravisit::walk_generics(self, generics);
2228 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2229 where F: FnOnce(&mut Resolver) -> T
2231 // Handle nested impls (inside fn bodies)
2232 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2233 let result = f(self);
2234 self.current_self_type = previous_value;
2238 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2239 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2241 let mut new_val = None;
2242 let mut new_id = None;
2243 if let Some(trait_ref) = opt_trait_ref {
2244 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2247 assert!(path_res.depth == 0);
2248 self.record_def(trait_ref.ref_id, path_res);
2249 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2250 new_id = Some(path_res.base_def.def_id());
2252 self.record_def(trait_ref.ref_id, err_path_resolution());
2254 intravisit::walk_trait_ref(self, trait_ref);
2256 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2257 let result = f(self, new_id);
2258 self.current_trait_ref = original_trait_ref;
2262 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2263 where F: FnOnce(&mut Resolver)
2265 let mut self_type_rib = Rib::new(NormalRibKind);
2267 // plain insert (no renaming, types are not currently hygienic....)
2268 let name = special_names::type_self;
2269 self_type_rib.bindings.insert(name, DlDef(self_def));
2270 self.type_ribs.push(self_type_rib);
2273 self.type_ribs.pop();
2277 fn resolve_implementation(&mut self,
2278 generics: &Generics,
2279 opt_trait_reference: &Option<TraitRef>,
2282 impl_items: &[ImplItem]) {
2283 // If applicable, create a rib for the type parameters.
2284 self.with_type_parameter_rib(HasTypeParameters(generics,
2288 // Resolve the type parameters.
2289 this.visit_generics(generics);
2291 // Resolve the trait reference, if necessary.
2292 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2293 // Resolve the self type.
2294 this.visit_ty(self_type);
2296 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2297 this.with_current_self_type(self_type, |this| {
2298 for impl_item in impl_items {
2299 match impl_item.node {
2300 hir::ImplItemKind::Const(..) => {
2301 // If this is a trait impl, ensure the const
2303 this.check_trait_item(impl_item.name,
2305 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2306 this.with_constant_rib(|this| {
2307 intravisit::walk_impl_item(this, impl_item);
2310 hir::ImplItemKind::Method(ref sig, _) => {
2311 // If this is a trait impl, ensure the method
2313 this.check_trait_item(impl_item.name,
2315 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2317 // We also need a new scope for the method-
2318 // specific type parameters.
2319 let type_parameters =
2320 HasTypeParameters(&sig.generics,
2323 this.with_type_parameter_rib(type_parameters, |this| {
2324 intravisit::walk_impl_item(this, impl_item);
2327 hir::ImplItemKind::Type(ref ty) => {
2328 // If this is a trait impl, ensure the type
2330 this.check_trait_item(impl_item.name,
2332 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2344 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2345 where F: FnOnce(Name, &str) -> ResolutionError
2347 // If there is a TraitRef in scope for an impl, then the method must be in the
2349 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2350 if !self.trait_item_map.contains_key(&(name, did)) {
2351 let path_str = path_names_to_string(&trait_ref.path, 0);
2352 resolve_error(self, span, err(name, &*path_str));
2357 fn resolve_local(&mut self, local: &Local) {
2358 // Resolve the type.
2359 walk_list!(self, visit_ty, &local.ty);
2361 // Resolve the initializer.
2362 walk_list!(self, visit_expr, &local.init);
2364 // Resolve the pattern.
2365 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2368 // build a map from pattern identifiers to binding-info's.
2369 // this is done hygienically. This could arise for a macro
2370 // that expands into an or-pattern where one 'x' was from the
2371 // user and one 'x' came from the macro.
2372 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2373 let mut result = HashMap::new();
2374 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2375 let name = path1.node;
2379 binding_mode: binding_mode,
2385 // check that all of the arms in an or-pattern have exactly the
2386 // same set of bindings, with the same binding modes for each.
2387 fn check_consistent_bindings(&mut self, arm: &Arm) {
2388 if arm.pats.is_empty() {
2391 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2392 for (i, p) in arm.pats.iter().enumerate() {
2393 let map_i = self.binding_mode_map(&**p);
2395 for (&key, &binding_0) in &map_0 {
2396 match map_i.get(&key) {
2400 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2402 Some(binding_i) => {
2403 if binding_0.binding_mode != binding_i.binding_mode {
2406 ResolutionError::VariableBoundWithDifferentMode(key,
2413 for (&key, &binding) in &map_i {
2414 if !map_0.contains_key(&key) {
2417 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2423 fn resolve_arm(&mut self, arm: &Arm) {
2424 self.value_ribs.push(Rib::new(NormalRibKind));
2426 let mut bindings_list = HashMap::new();
2427 for pattern in &arm.pats {
2428 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2431 // This has to happen *after* we determine which
2432 // pat_idents are variants
2433 self.check_consistent_bindings(arm);
2435 walk_list!(self, visit_expr, &arm.guard);
2436 self.visit_expr(&*arm.body);
2439 self.value_ribs.pop();
2443 fn resolve_block(&mut self, block: &Block) {
2444 debug!("(resolving block) entering block");
2445 self.value_ribs.push(Rib::new(NormalRibKind));
2447 // Move down in the graph, if there's an anonymous module rooted here.
2448 let orig_module = self.current_module.clone();
2449 match orig_module.anonymous_children.borrow().get(&block.id) {
2453 Some(anonymous_module) => {
2454 debug!("(resolving block) found anonymous module, moving down");
2455 self.current_module = anonymous_module.clone();
2459 // Check for imports appearing after non-item statements.
2460 let mut found_non_item = false;
2461 for statement in &block.stmts {
2462 if let hir::StmtDecl(ref declaration, _) = statement.node {
2463 if let hir::DeclItem(i) = declaration.node {
2464 let i = self.ast_map.expect_item(i.id);
2466 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2467 span_err!(self.session,
2470 "imports are not allowed after non-item statements");
2475 found_non_item = true
2478 found_non_item = true;
2482 // Descend into the block.
2483 intravisit::walk_block(self, block);
2487 self.current_module = orig_module;
2488 self.value_ribs.pop();
2490 debug!("(resolving block) leaving block");
2493 fn resolve_type(&mut self, ty: &Ty) {
2495 TyPath(ref maybe_qself, ref path) => {
2496 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2497 maybe_qself.as_ref(),
2501 // `<T>::a::b::c` is resolved by typeck alone.
2502 TypecheckRequired => {
2503 // Resolve embedded types.
2504 intravisit::walk_ty(self, ty);
2507 ResolveAttempt(resolution) => resolution,
2510 // This is a path in the type namespace. Walk through scopes
2514 // Write the result into the def map.
2515 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2516 path_names_to_string(path, 0),
2519 self.record_def(ty.id, def);
2522 self.record_def(ty.id, err_path_resolution());
2524 // Keep reporting some errors even if they're ignored above.
2525 self.resolve_path(ty.id, path, 0, TypeNS, true);
2527 let kind = if maybe_qself.is_some() {
2533 let self_type_name = special_idents::type_self.name;
2534 let is_invalid_self_type_name = path.segments.len() > 0 &&
2535 maybe_qself.is_none() &&
2536 path.segments[0].identifier.name ==
2538 if is_invalid_self_type_name {
2541 ResolutionError::SelfUsedOutsideImplOrTrait);
2545 ResolutionError::UseOfUndeclared(
2547 &*path_names_to_string(path,
2556 // Resolve embedded types.
2557 intravisit::walk_ty(self, ty);
2560 fn resolve_pattern(&mut self,
2562 mode: PatternBindingMode,
2563 // Maps idents to the node ID for the (outermost)
2564 // pattern that binds them
2565 bindings_list: &mut HashMap<Name, NodeId>) {
2566 let pat_id = pattern.id;
2567 walk_pat(pattern, |pattern| {
2568 match pattern.node {
2569 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2570 // The meaning of PatIdent with no type parameters
2571 // depends on whether an enum variant or unit-like struct
2572 // with that name is in scope. The probing lookup has to
2573 // be careful not to emit spurious errors. Only matching
2574 // patterns (match) can match nullary variants or
2575 // unit-like structs. For binding patterns (let
2576 // and the LHS of @-patterns), matching such a value is
2577 // simply disallowed (since it's rarely what you want).
2578 let const_ok = mode == RefutableMode && at_rhs.is_none();
2580 let ident = path1.node;
2581 let renamed = ident.name;
2583 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2585 FoundStructOrEnumVariant(def, lp) if const_ok => {
2586 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2589 self.enforce_default_binding_mode(pattern,
2592 self.record_def(pattern.id,
2599 FoundStructOrEnumVariant(..) => {
2603 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2606 self.record_def(pattern.id, err_path_resolution());
2608 FoundConst(def, lp, _) if const_ok => {
2609 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2611 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2612 self.record_def(pattern.id,
2619 FoundConst(def, _, name) => {
2623 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2626 self.record_def(pattern.id, err_path_resolution());
2628 BareIdentifierPatternUnresolved => {
2629 debug!("(resolving pattern) binding `{}`", renamed);
2631 let def_id = self.ast_map.local_def_id(pattern.id);
2632 let def = DefLocal(def_id, pattern.id);
2634 // Record the definition so that later passes
2635 // will be able to distinguish variants from
2636 // locals in patterns.
2638 self.record_def(pattern.id,
2641 last_private: LastMod(AllPublic),
2645 // Add the binding to the local ribs, if it
2646 // doesn't already exist in the bindings list. (We
2647 // must not add it if it's in the bindings list
2648 // because that breaks the assumptions later
2649 // passes make about or-patterns.)
2650 if !bindings_list.contains_key(&renamed) {
2651 let this = &mut *self;
2652 let last_rib = this.value_ribs.last_mut().unwrap();
2653 last_rib.bindings.insert(renamed, DlDef(def));
2654 bindings_list.insert(renamed, pat_id);
2655 } else if mode == ArgumentIrrefutableMode &&
2656 bindings_list.contains_key(&renamed) {
2657 // Forbid duplicate bindings in the same
2662 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2663 &ident.name.as_str())
2665 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2666 // Then this is a duplicate variable in the
2667 // same disjunction, which is an error.
2671 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2672 &ident.name.as_str())
2675 // Else, not bound in the same pattern: do
2681 PatEnum(ref path, _) => {
2682 // This must be an enum variant, struct or const.
2683 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2688 // The below shouldn't happen because all
2689 // qualified paths should be in PatQPath.
2690 TypecheckRequired =>
2691 self.session.span_bug(path.span,
2692 "resolve_possibly_assoc_item claimed
2694 that a path in PatEnum requires typecheck
2696 to resolve, but qualified paths should be
2699 ResolveAttempt(resolution) => resolution,
2701 if let Some(path_res) = resolution {
2702 match path_res.base_def {
2703 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2704 self.record_def(pattern.id, path_res);
2707 resolve_error(&self,
2709 ResolutionError::StaticVariableReference);
2710 self.record_def(pattern.id, err_path_resolution());
2713 // If anything ends up here entirely resolved,
2714 // it's an error. If anything ends up here
2715 // partially resolved, that's OK, because it may
2716 // be a `T::CONST` that typeck will resolve.
2717 if path_res.depth == 0 {
2721 ResolutionError::NotAnEnumVariantStructOrConst(
2729 self.record_def(pattern.id, err_path_resolution());
2731 let const_name = path.segments
2736 let traits = self.get_traits_containing_item(const_name);
2737 self.trait_map.insert(pattern.id, traits);
2738 self.record_def(pattern.id, path_res);
2746 ResolutionError::UnresolvedEnumVariantStructOrConst(
2747 &path.segments.last().unwrap().identifier.name.as_str())
2749 self.record_def(pattern.id, err_path_resolution());
2751 intravisit::walk_path(self, path);
2754 PatQPath(ref qself, ref path) => {
2755 // Associated constants only.
2756 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2761 TypecheckRequired => {
2762 // All `<T>::CONST` should end up here, and will
2763 // require use of the trait map to resolve
2764 // during typechecking.
2765 let const_name = path.segments
2770 let traits = self.get_traits_containing_item(const_name);
2771 self.trait_map.insert(pattern.id, traits);
2772 intravisit::walk_pat(self, pattern);
2775 ResolveAttempt(resolution) => resolution,
2777 if let Some(path_res) = resolution {
2778 match path_res.base_def {
2779 // All `<T as Trait>::CONST` should end up here, and
2780 // have the trait already selected.
2781 DefAssociatedConst(..) => {
2782 self.record_def(pattern.id, path_res);
2788 ResolutionError::NotAnAssociatedConst(
2789 &path.segments.last().unwrap().identifier.name.as_str()
2792 self.record_def(pattern.id, err_path_resolution());
2798 ResolutionError::UnresolvedAssociatedConst(&path.segments
2804 self.record_def(pattern.id, err_path_resolution());
2806 intravisit::walk_pat(self, pattern);
2809 PatStruct(ref path, _, _) => {
2810 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2811 Some(definition) => {
2812 self.record_def(pattern.id, definition);
2815 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2819 ResolutionError::DoesNotNameAStruct(
2820 &*path_names_to_string(path, 0))
2822 self.record_def(pattern.id, err_path_resolution());
2825 intravisit::walk_path(self, path);
2828 PatLit(_) | PatRange(..) => {
2829 intravisit::walk_pat(self, pattern);
2840 fn resolve_bare_identifier_pattern(&mut self,
2843 -> BareIdentifierPatternResolution {
2844 let module = self.current_module.clone();
2845 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2846 Success((target, _)) => {
2847 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2849 target.binding.borrow());
2850 match target.binding.def() {
2852 panic!("resolved name in the value namespace to a set of name bindings \
2855 // For the two success cases, this lookup can be
2856 // considered as not having a private component because
2857 // the lookup happened only within the current module.
2858 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2859 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2861 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2862 return FoundConst(def, LastMod(AllPublic), name);
2864 Some(DefStatic(..)) => {
2865 resolve_error(self, span, ResolutionError::StaticVariableReference);
2866 return BareIdentifierPatternUnresolved;
2868 _ => return BareIdentifierPatternUnresolved
2873 panic!("unexpected indeterminate result");
2877 Some((span, msg)) => {
2878 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2883 debug!("(resolve bare identifier pattern) failed to find {}", name);
2884 return BareIdentifierPatternUnresolved;
2889 /// Handles paths that may refer to associated items
2890 fn resolve_possibly_assoc_item(&mut self,
2892 maybe_qself: Option<&hir::QSelf>,
2894 namespace: Namespace,
2896 -> AssocItemResolveResult {
2897 let max_assoc_types;
2901 if qself.position == 0 {
2902 return TypecheckRequired;
2904 max_assoc_types = path.segments.len() - qself.position;
2905 // Make sure the trait is valid.
2906 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2909 max_assoc_types = path.segments.len();
2913 let mut resolution = self.with_no_errors(|this| {
2914 this.resolve_path(id, path, 0, namespace, check_ribs)
2916 for depth in 1..max_assoc_types {
2917 if resolution.is_some() {
2920 self.with_no_errors(|this| {
2921 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2924 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2925 // A module is not a valid type or value.
2928 ResolveAttempt(resolution)
2931 /// If `check_ribs` is true, checks the local definitions first; i.e.
2932 /// doesn't skip straight to the containing module.
2933 /// Skips `path_depth` trailing segments, which is also reflected in the
2934 /// returned value. See `middle::def::PathResolution` for more info.
2935 pub fn resolve_path(&mut self,
2939 namespace: Namespace,
2941 -> Option<PathResolution> {
2942 let span = path.span;
2943 let segments = &path.segments[..path.segments.len() - path_depth];
2945 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2948 let def = self.resolve_crate_relative_path(span, segments, namespace);
2949 return def.map(mk_res);
2952 // Try to find a path to an item in a module.
2953 let last_ident = segments.last().unwrap().identifier;
2954 if segments.len() <= 1 {
2955 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2956 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2958 PathResolution::new(def, LastMod(AllPublic), path_depth)
2962 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2963 let def = self.resolve_module_relative_path(span, segments, namespace);
2964 match (def, unqualified_def) {
2965 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2967 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2970 "unnecessary qualification".to_string());
2978 // Resolve a single identifier
2979 fn resolve_identifier(&mut self,
2980 identifier: hir::Ident,
2981 namespace: Namespace,
2984 -> Option<LocalDef> {
2985 // First, check to see whether the name is a primitive type.
2986 if namespace == TypeNS {
2987 if let Some(&prim_ty) = self.primitive_type_table
2989 .get(&identifier.unhygienic_name) {
2990 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
2995 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
3000 let name = identifier.unhygienic_name;
3001 self.resolve_item_by_name_in_lexical_scope(name, namespace, record_used)
3002 .map(LocalDef::from_def)
3005 // Resolve a local definition, potentially adjusting for closures.
3006 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
3007 let ribs = match local_def.ribs {
3008 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
3009 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
3012 let mut def = local_def.def;
3015 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
3017 DefLocal(_, node_id) => {
3021 // Nothing to do. Continue.
3023 ClosureRibKind(function_id) => {
3025 let node_def_id = self.ast_map.local_def_id(node_id);
3027 let seen = self.freevars_seen
3029 .or_insert_with(|| NodeMap());
3030 if let Some(&index) = seen.get(&node_id) {
3031 def = DefUpvar(node_def_id, node_id, index, function_id);
3034 let vec = self.freevars
3036 .or_insert_with(|| vec![]);
3037 let depth = vec.len();
3043 def = DefUpvar(node_def_id, node_id, depth, function_id);
3044 seen.insert(node_id, depth);
3046 ItemRibKind | MethodRibKind => {
3047 // This was an attempt to access an upvar inside a
3048 // named function item. This is not allowed, so we
3052 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3055 ConstantItemRibKind => {
3056 // Still doesn't deal with upvars
3059 ResolutionError::AttemptToUseNonConstantValueInConstant);
3065 DefTyParam(..) | DefSelfTy(..) => {
3068 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3069 // Nothing to do. Continue.
3072 // This was an attempt to use a type parameter outside
3077 ResolutionError::TypeParametersFromOuterFunction);
3080 ConstantItemRibKind => {
3082 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3093 // resolve a "module-relative" path, e.g. a::b::c
3094 fn resolve_module_relative_path(&mut self,
3096 segments: &[hir::PathSegment],
3097 namespace: Namespace)
3098 -> Option<(Def, LastPrivate)> {
3099 let module_path = segments.split_last()
3103 .map(|ps| ps.identifier.name)
3104 .collect::<Vec<_>>();
3106 let containing_module;
3108 let current_module = self.current_module.clone();
3109 match self.resolve_module_path(current_module,
3115 let (span, msg) = match err {
3116 Some((span, msg)) => (span, msg),
3118 let msg = format!("Use of undeclared type or module `{}`",
3119 names_to_string(&module_path));
3124 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3127 Indeterminate => panic!("indeterminate unexpected"),
3128 Success((resulting_module, resulting_last_private)) => {
3129 containing_module = resulting_module;
3130 last_private = resulting_last_private;
3134 let name = segments.last().unwrap().identifier.name;
3135 let def = match self.resolve_name_in_module(containing_module.clone(),
3138 NameSearchType::PathSearch,
3140 Success((Target { binding, .. }, _)) => {
3141 let (def, lp) = binding.def_and_lp();
3142 (def, last_private.or(lp))
3146 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3147 self.used_crates.insert(kid);
3152 /// Invariant: This must be called only during main resolution, not during
3153 /// import resolution.
3154 fn resolve_crate_relative_path(&mut self,
3156 segments: &[hir::PathSegment],
3157 namespace: Namespace)
3158 -> Option<(Def, LastPrivate)> {
3159 let module_path = segments.split_last()
3163 .map(|ps| ps.identifier.name)
3164 .collect::<Vec<_>>();
3166 let root_module = self.graph_root.clone();
3168 let containing_module;
3170 match self.resolve_module_path_from_root(root_module,
3175 LastMod(AllPublic)) {
3177 let (span, msg) = match err {
3178 Some((span, msg)) => (span, msg),
3180 let msg = format!("Use of undeclared module `::{}`",
3181 names_to_string(&module_path[..]));
3186 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3191 panic!("indeterminate unexpected");
3194 Success((resulting_module, resulting_last_private)) => {
3195 containing_module = resulting_module;
3196 last_private = resulting_last_private;
3200 let name = segments.last().unwrap().identifier.name;
3201 match self.resolve_name_in_module(containing_module,
3204 NameSearchType::PathSearch,
3206 Success((Target { binding, .. }, _)) => {
3207 let (def, lp) = binding.def_and_lp();
3208 Some((def, last_private.or(lp)))
3214 fn resolve_identifier_in_local_ribs(&mut self,
3216 namespace: Namespace)
3217 -> Option<LocalDef> {
3218 // Check the local set of ribs.
3219 let (name, ribs) = match namespace {
3220 ValueNS => (ident.name, &self.value_ribs),
3221 TypeNS => (ident.unhygienic_name, &self.type_ribs),
3224 for (i, rib) in ribs.iter().enumerate().rev() {
3225 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3228 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3232 return Some(LocalDef {
3233 ribs: Some((namespace, i)),
3238 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3250 fn resolve_item_by_name_in_lexical_scope(&mut self,
3252 namespace: Namespace,
3256 let module = self.current_module.clone();
3257 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
3258 Success((target, _)) => {
3259 match target.binding.def() {
3261 // This can happen if we were looking for a type and
3262 // found a module instead. Modules don't have defs.
3263 debug!("(resolving item path by identifier in lexical scope) failed to \
3264 resolve {} after success...",
3269 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3271 // This lookup is "all public" because it only searched
3272 // for one identifier in the current module (couldn't
3273 // have passed through reexports or anything like that.
3279 panic!("unexpected indeterminate result");
3282 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3285 if let Some((span, msg)) = err {
3286 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3294 fn with_no_errors<T, F>(&mut self, f: F) -> T
3295 where F: FnOnce(&mut Resolver) -> T
3297 self.emit_errors = false;
3299 self.emit_errors = true;
3303 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3304 fn extract_path_and_node_id(t: &Ty,
3305 allow: FallbackChecks)
3306 -> Option<(Path, NodeId, FallbackChecks)> {
3308 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3309 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3310 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3311 // This doesn't handle the remaining `Ty` variants as they are not
3312 // that commonly the self_type, it might be interesting to provide
3313 // support for those in future.
3318 fn get_module(this: &mut Resolver,
3320 name_path: &[ast::Name])
3321 -> Option<Rc<Module>> {
3322 let root = this.current_module.clone();
3323 let last_name = name_path.last().unwrap();
3325 if name_path.len() == 1 {
3326 match this.primitive_type_table.primitive_types.get(last_name) {
3329 match this.current_module.children.borrow().get(last_name) {
3330 Some(child) => child.type_ns.module(),
3336 match this.resolve_module_path(root,
3341 Success((module, _)) => Some(module),
3347 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3348 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3349 let sig = match this.ast_map.get(node_id) {
3350 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3351 hir::MethodTraitItem(ref sig, _) => sig,
3354 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3355 hir::ImplItemKind::Method(ref sig, _) => sig,
3360 sig.explicit_self.node == hir::SelfStatic
3362 this.session.cstore.is_static_method(did)
3366 let (path, node_id, allowed) = match self.current_self_type {
3367 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3369 None => return NoSuggestion,
3371 None => return NoSuggestion,
3374 if allowed == Everything {
3375 // Look for a field with the same name in the current self_type.
3376 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3377 Some(DefTy(did, _)) |
3378 Some(DefStruct(did)) |
3379 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3382 if fields.iter().any(|&field_name| name == field_name) {
3387 _ => {} // Self type didn't resolve properly
3391 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3393 // Look for a method in the current self type's impl module.
3394 if let Some(module) = get_module(self, path.span, &name_path) {
3395 if let Some(binding) = module.children.borrow().get(&name) {
3396 if let Some(DefMethod(did)) = binding.value_ns.def() {
3397 if is_static_method(self, did) {
3398 return StaticMethod(path_names_to_string(&path, 0));
3400 if self.current_trait_ref.is_some() {
3402 } else if allowed == Everything {
3409 // Look for a method in the current trait.
3410 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3411 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3412 if is_static_method(self, did) {
3413 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3423 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3424 if let Some(macro_name) = self.session.available_macros
3425 .borrow().iter().find(|n| n.as_str() == name) {
3426 return SuggestionType::Macro(format!("{}!", macro_name));
3429 let names = self.value_ribs
3432 .flat_map(|rib| rib.bindings.keys());
3434 if let Some(found) = find_best_match_for_name(names, name, None) {
3435 if name != &*found {
3436 return SuggestionType::Function(found);
3438 } SuggestionType::NotFound
3441 fn resolve_expr(&mut self, expr: &Expr) {
3442 // First, record candidate traits for this expression if it could
3443 // result in the invocation of a method call.
3445 self.record_candidate_traits_for_expr_if_necessary(expr);
3447 // Next, resolve the node.
3449 ExprPath(ref maybe_qself, ref path) => {
3450 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3451 maybe_qself.as_ref(),
3455 // `<T>::a::b::c` is resolved by typeck alone.
3456 TypecheckRequired => {
3457 let method_name = path.segments.last().unwrap().identifier.name;
3458 let traits = self.get_traits_containing_item(method_name);
3459 self.trait_map.insert(expr.id, traits);
3460 intravisit::walk_expr(self, expr);
3463 ResolveAttempt(resolution) => resolution,
3466 // This is a local path in the value namespace. Walk through
3467 // scopes looking for it.
3468 if let Some(path_res) = resolution {
3469 // Check if struct variant
3470 if let DefVariant(_, _, true) = path_res.base_def {
3471 let path_name = path_names_to_string(path, 0);
3475 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3477 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3479 if self.emit_errors {
3480 self.session.fileline_help(expr.span, &msg);
3482 self.session.span_help(expr.span, &msg);
3484 self.record_def(expr.id, err_path_resolution());
3486 // Write the result into the def map.
3487 debug!("(resolving expr) resolved `{}`",
3488 path_names_to_string(path, 0));
3490 // Partial resolutions will need the set of traits in scope,
3491 // so they can be completed during typeck.
3492 if path_res.depth != 0 {
3493 let method_name = path.segments.last().unwrap().identifier.name;
3494 let traits = self.get_traits_containing_item(method_name);
3495 self.trait_map.insert(expr.id, traits);
3498 self.record_def(expr.id, path_res);
3501 // Be helpful if the name refers to a struct
3502 // (The pattern matching def_tys where the id is in self.structs
3503 // matches on regular structs while excluding tuple- and enum-like
3504 // structs, which wouldn't result in this error.)
3505 let path_name = path_names_to_string(path, 0);
3506 let type_res = self.with_no_errors(|this| {
3507 this.resolve_path(expr.id, path, 0, TypeNS, false)
3510 self.record_def(expr.id, err_path_resolution());
3511 match type_res.map(|r| r.base_def) {
3512 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3516 ResolutionError::StructVariantUsedAsFunction(
3520 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3522 if self.emit_errors {
3523 self.session.fileline_help(expr.span, &msg);
3525 self.session.span_help(expr.span, &msg);
3529 // Keep reporting some errors even if they're ignored above.
3530 self.resolve_path(expr.id, path, 0, ValueNS, true);
3532 let mut method_scope = false;
3533 self.value_ribs.iter().rev().all(|rib| {
3534 method_scope = match rib.kind {
3535 MethodRibKind => true,
3536 ItemRibKind | ConstantItemRibKind => false,
3537 _ => return true, // Keep advancing
3539 false // Stop advancing
3542 if method_scope && special_names::self_.as_str() == &path_name[..] {
3545 ResolutionError::SelfNotAvailableInStaticMethod);
3547 let last_name = path.segments.last().unwrap().identifier.name;
3548 let mut msg = match self.find_fallback_in_self_type(last_name) {
3550 // limit search to 5 to reduce the number
3551 // of stupid suggestions
3552 match self.find_best_match(&path_name) {
3553 SuggestionType::Macro(s) => {
3554 format!("the macro `{}`", s)
3556 SuggestionType::Function(s) => format!("`{}`", s),
3557 SuggestionType::NotFound => "".to_string(),
3560 Field => format!("`self.{}`", path_name),
3562 TraitItem => format!("to call `self.{}`", path_name),
3563 TraitMethod(path_str) |
3564 StaticMethod(path_str) =>
3565 format!("to call `{}::{}`", path_str, path_name),
3568 let mut context = UnresolvedNameContext::Other;
3569 if !msg.is_empty() {
3570 msg = format!(". Did you mean {}?", msg);
3572 // we check if this a module and if so, we display a help
3574 let name_path = path.segments.iter()
3575 .map(|seg| seg.identifier.name)
3576 .collect::<Vec<_>>();
3577 let current_module = self.current_module.clone();
3579 match self.resolve_module_path(current_module,
3585 context = UnresolvedNameContext::PathIsMod(expr.id);
3593 ResolutionError::UnresolvedName(
3594 &*path_name, &*msg, context));
3600 intravisit::walk_expr(self, expr);
3603 ExprStruct(ref path, _, _) => {
3604 // Resolve the path to the structure it goes to. We don't
3605 // check to ensure that the path is actually a structure; that
3606 // is checked later during typeck.
3607 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3608 Some(definition) => self.record_def(expr.id, definition),
3610 debug!("(resolving expression) didn't find struct def",);
3614 ResolutionError::DoesNotNameAStruct(
3615 &*path_names_to_string(path, 0))
3617 self.record_def(expr.id, err_path_resolution());
3621 intravisit::walk_expr(self, expr);
3624 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3625 self.with_label_rib(|this| {
3626 let def_like = DlDef(DefLabel(expr.id));
3629 let rib = this.label_ribs.last_mut().unwrap();
3630 rib.bindings.insert(label.name, def_like);
3633 intravisit::walk_expr(this, expr);
3637 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3638 match self.search_label(label.node.name) {
3640 self.record_def(expr.id, err_path_resolution());
3643 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3645 Some(DlDef(def @ DefLabel(_))) => {
3646 // Since this def is a label, it is never read.
3647 self.record_def(expr.id,
3650 last_private: LastMod(AllPublic),
3655 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3661 intravisit::walk_expr(self, expr);
3666 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3668 ExprField(_, name) => {
3669 // FIXME(#6890): Even though you can't treat a method like a
3670 // field, we need to add any trait methods we find that match
3671 // the field name so that we can do some nice error reporting
3672 // later on in typeck.
3673 let traits = self.get_traits_containing_item(name.node);
3674 self.trait_map.insert(expr.id, traits);
3676 ExprMethodCall(name, _, _) => {
3677 debug!("(recording candidate traits for expr) recording traits for {}",
3679 let traits = self.get_traits_containing_item(name.node);
3680 self.trait_map.insert(expr.id, traits);
3688 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3689 debug!("(getting traits containing item) looking for '{}'", name);
3691 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3692 debug!("(adding trait info) found trait {:?} for method '{}'",
3695 found_traits.push(trait_def_id);
3698 let mut found_traits = Vec::new();
3699 let mut search_module = self.current_module.clone();
3701 // Look for the current trait.
3702 match self.current_trait_ref {
3703 Some((trait_def_id, _)) => {
3704 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3705 add_trait_info(&mut found_traits, trait_def_id, name);
3708 None => {} // Nothing to do.
3711 // Look for trait children.
3712 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3715 for (_, child_names) in search_module.children.borrow().iter() {
3716 let def = match child_names.type_ns.def() {
3720 let trait_def_id = match def {
3721 DefTrait(trait_def_id) => trait_def_id,
3724 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3725 add_trait_info(&mut found_traits, trait_def_id, name);
3730 // Look for imports.
3731 for (_, import) in search_module.import_resolutions.borrow().iter() {
3732 let target = match import.type_ns.target {
3734 Some(ref target) => target,
3736 let did = match target.binding.def() {
3737 Some(DefTrait(trait_def_id)) => trait_def_id,
3738 Some(..) | None => continue,
3740 if self.trait_item_map.contains_key(&(name, did)) {
3741 add_trait_info(&mut found_traits, did, name);
3742 let id = import.type_ns.id;
3743 self.used_imports.insert((id, TypeNS));
3744 let trait_name = self.get_trait_name(did);
3745 self.record_import_use(id, trait_name);
3746 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3747 self.used_crates.insert(kid);
3752 match search_module.parent_link.clone() {
3753 NoParentLink | ModuleParentLink(..) => break,
3754 BlockParentLink(parent_module, _) => {
3755 search_module = parent_module.upgrade().unwrap();
3763 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3764 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3765 assert!(match resolution.last_private {
3766 LastImport{..} => false,
3769 "Import should only be used for `use` directives");
3771 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3772 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3773 self.session.span_bug(span,
3774 &format!("path resolved multiple times ({:?} before, {:?} now)",
3780 fn enforce_default_binding_mode(&mut self,
3782 pat_binding_mode: BindingMode,
3784 match pat_binding_mode {
3785 BindByValue(_) => {}
3789 ResolutionError::CannotUseRefBindingModeWith(descr));
3797 // Diagnostics are not particularly efficient, because they're rarely
3801 #[allow(dead_code)] // useful for debugging
3802 fn dump_module(&mut self, module_: Rc<Module>) {
3803 debug!("Dump of module `{}`:", module_to_string(&*module_));
3805 debug!("Children:");
3806 build_reduced_graph::populate_module_if_necessary(self, &module_);
3807 for (&name, _) in module_.children.borrow().iter() {
3808 debug!("* {}", name);
3811 debug!("Import resolutions:");
3812 let import_resolutions = module_.import_resolutions.borrow();
3813 for (&name, import_resolution) in import_resolutions.iter() {
3815 match import_resolution.value_ns.target {
3817 value_repr = "".to_string();
3820 value_repr = " value:?".to_string();
3826 match import_resolution.type_ns.target {
3828 type_repr = "".to_string();
3831 type_repr = " type:?".to_string();
3836 debug!("* {}:{}{}", name, value_repr, type_repr);
3842 fn names_to_string(names: &[Name]) -> String {
3843 let mut first = true;
3844 let mut result = String::new();
3849 result.push_str("::")
3851 result.push_str(&name.as_str());
3856 fn path_names_to_string(path: &Path, depth: usize) -> String {
3857 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3859 .map(|seg| seg.identifier.name)
3861 names_to_string(&names[..])
3864 /// A somewhat inefficient routine to obtain the name of a module.
3865 fn module_to_string(module: &Module) -> String {
3866 let mut names = Vec::new();
3868 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3869 match module.parent_link {
3871 ModuleParentLink(ref module, name) => {
3873 collect_mod(names, &*module.upgrade().unwrap());
3875 BlockParentLink(ref module, _) => {
3876 // danger, shouldn't be ident?
3877 names.push(special_idents::opaque.name);
3878 collect_mod(names, &*module.upgrade().unwrap());
3882 collect_mod(&mut names, module);
3884 if names.is_empty() {
3885 return "???".to_string();
3887 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3890 fn err_path_resolution() -> PathResolution {
3893 last_private: LastMod(AllPublic),
3899 pub struct CrateMap {
3900 pub def_map: RefCell<DefMap>,
3901 pub freevars: FreevarMap,
3902 pub export_map: ExportMap,
3903 pub trait_map: TraitMap,
3904 pub external_exports: ExternalExports,
3905 pub glob_map: Option<GlobMap>,
3908 #[derive(PartialEq,Copy, Clone)]
3909 pub enum MakeGlobMap {
3914 /// Entry point to crate resolution.
3915 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3916 ast_map: &'a hir_map::Map<'tcx>,
3917 make_glob_map: MakeGlobMap)
3919 let krate = ast_map.krate();
3920 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3922 resolver.resolve_crate(krate);
3924 check_unused::check_crate(&mut resolver, krate);
3927 def_map: resolver.def_map,
3928 freevars: resolver.freevars,
3929 export_map: resolver.export_map,
3930 trait_map: resolver.trait_map,
3931 external_exports: resolver.external_exports,
3932 glob_map: if resolver.make_glob_map {
3933 Some(resolver.glob_map)
3940 /// Builds a name resolution walker to be used within this module,
3941 /// or used externally, with an optional callback function.
3943 /// The callback takes a &mut bool which allows callbacks to end a
3944 /// walk when set to true, passing through the rest of the walk, while
3945 /// preserving the ribs + current module. This allows resolve_path
3946 /// calls to be made with the correct scope info. The node in the
3947 /// callback corresponds to the current node in the walk.
3948 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3949 ast_map: &'a hir_map::Map<'tcx>,
3951 make_glob_map: MakeGlobMap,
3952 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3953 -> Resolver<'a, 'tcx> {
3954 let mut resolver = Resolver::new(session, ast_map, make_glob_map);
3956 resolver.callback = callback;
3958 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3959 session.abort_if_errors();
3961 resolve_imports::resolve_imports(&mut resolver);
3962 session.abort_if_errors();
3964 record_exports::record(&mut resolver);
3965 session.abort_if_errors();
3970 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }