1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
19 #![feature(associated_consts)]
20 #![feature(borrow_state)]
21 #![feature(rustc_diagnostic_macros)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
31 extern crate rustc_bitflags;
32 extern crate rustc_front;
36 use self::PatternBindingMode::*;
37 use self::Namespace::*;
38 use self::NamespaceResult::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::NameSearchType::*;
47 use self::BareIdentifierPatternResolution::*;
48 use self::ParentLink::*;
49 use self::FallbackChecks::*;
51 use rustc::front::map as hir_map;
52 use rustc::session::Session;
54 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
55 use rustc::middle::def::*;
56 use rustc::middle::def_id::DefId;
57 use rustc::middle::pat_util::pat_bindings;
58 use rustc::middle::privacy::*;
59 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
60 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
61 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
64 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
65 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
66 use syntax::attr::AttrMetaMethods;
67 use syntax::parse::token::{self, special_names, special_idents};
68 use syntax::codemap::{self, Span, Pos};
69 use syntax::util::lev_distance::{lev_distance, max_suggestion_distance};
71 use rustc_front::intravisit::{self, FnKind, Visitor};
73 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
74 use rustc_front::hir::Crate;
75 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
76 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
77 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
78 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
79 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
80 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
81 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
82 use rustc_front::hir::Local;
83 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
84 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
85 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
86 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
87 use rustc_front::util::walk_pat;
89 use std::collections::{HashMap, HashSet};
90 use std::cell::{Cell, RefCell};
92 use std::mem::replace;
93 use std::rc::{Rc, Weak};
96 use resolve_imports::{Target, ImportDirective, ImportResolutionPerNamespace};
97 use resolve_imports::Shadowable;
99 // NB: This module needs to be declared first so diagnostics are
100 // registered before they are used.
105 mod build_reduced_graph;
108 // Perform the callback, not walking deeper if the return is true
109 macro_rules! execute_callback {
110 ($node: expr, $walker: expr) => (
111 if let Some(ref callback) = $walker.callback {
112 if callback($node, &mut $walker.resolved) {
119 enum SuggestionType {
125 pub enum ResolutionError<'a> {
126 /// error E0401: can't use type parameters from outer function
127 TypeParametersFromOuterFunction,
128 /// error E0402: cannot use an outer type parameter in this context
129 OuterTypeParameterContext,
130 /// error E0403: the name is already used for a type parameter in this type parameter list
131 NameAlreadyUsedInTypeParameterList(Name),
132 /// error E0404: is not a trait
133 IsNotATrait(&'a str),
134 /// error E0405: use of undeclared trait name
135 UndeclaredTraitName(&'a str),
136 /// error E0406: undeclared associated type
137 UndeclaredAssociatedType,
138 /// error E0407: method is not a member of trait
139 MethodNotMemberOfTrait(Name, &'a str),
140 /// error E0437: type is not a member of trait
141 TypeNotMemberOfTrait(Name, &'a str),
142 /// error E0438: const is not a member of trait
143 ConstNotMemberOfTrait(Name, &'a str),
144 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
145 VariableNotBoundInPattern(Name, usize),
146 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
147 VariableBoundWithDifferentMode(Name, usize),
148 /// error E0410: variable from pattern is not bound in pattern #1
149 VariableNotBoundInParentPattern(Name, usize),
150 /// error E0411: use of `Self` outside of an impl or trait
151 SelfUsedOutsideImplOrTrait,
152 /// error E0412: use of undeclared
153 UseOfUndeclared(&'a str, &'a str),
154 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
155 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
156 /// error E0414: only irrefutable patterns allowed here
157 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
158 /// error E0415: identifier is bound more than once in this parameter list
159 IdentifierBoundMoreThanOnceInParameterList(&'a str),
160 /// error E0416: identifier is bound more than once in the same pattern
161 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
162 /// error E0417: static variables cannot be referenced in a pattern
163 StaticVariableReference,
164 /// error E0418: is not an enum variant, struct or const
165 NotAnEnumVariantStructOrConst(&'a str),
166 /// error E0419: unresolved enum variant, struct or const
167 UnresolvedEnumVariantStructOrConst(&'a str),
168 /// error E0420: is not an associated const
169 NotAnAssociatedConst(&'a str),
170 /// error E0421: unresolved associated const
171 UnresolvedAssociatedConst(&'a str),
172 /// error E0422: does not name a struct
173 DoesNotNameAStruct(&'a str),
174 /// error E0423: is a struct variant name, but this expression uses it like a function name
175 StructVariantUsedAsFunction(&'a str),
176 /// error E0424: `self` is not available in a static method
177 SelfNotAvailableInStaticMethod,
178 /// error E0425: unresolved name
179 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
180 /// error E0426: use of undeclared label
181 UndeclaredLabel(&'a str),
182 /// error E0427: cannot use `ref` binding mode with ...
183 CannotUseRefBindingModeWith(&'a str),
184 /// error E0428: duplicate definition
185 DuplicateDefinition(&'a str, Name),
186 /// error E0429: `self` imports are only allowed within a { } list
187 SelfImportsOnlyAllowedWithin,
188 /// error E0430: `self` import can only appear once in the list
189 SelfImportCanOnlyAppearOnceInTheList,
190 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
191 SelfImportOnlyInImportListWithNonEmptyPrefix,
192 /// error E0432: unresolved import
193 UnresolvedImport(Option<(&'a str, &'a str)>),
194 /// error E0433: failed to resolve
195 FailedToResolve(&'a str),
196 /// error E0434: can't capture dynamic environment in a fn item
197 CannotCaptureDynamicEnvironmentInFnItem,
198 /// error E0435: attempt to use a non-constant value in a constant
199 AttemptToUseNonConstantValueInConstant,
202 /// Context of where `ResolutionError::UnresolvedName` arose.
203 #[derive(Clone, PartialEq, Eq, Debug)]
204 pub enum UnresolvedNameContext {
205 /// `PathIsMod(id)` indicates that a given path, used in
206 /// expression context, actually resolved to a module rather than
207 /// a value. The `id` attached to the variant is the node id of
208 /// the erroneous path expression.
209 PathIsMod(ast::NodeId),
211 /// `Other` means we have no extra information about the context
212 /// of the unresolved name error. (Maybe we could eliminate all
213 /// such cases; but for now, this is an information-free default.)
217 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
218 span: syntax::codemap::Span,
219 resolution_error: ResolutionError<'b>) {
220 if !resolver.emit_errors {
223 match resolution_error {
224 ResolutionError::TypeParametersFromOuterFunction => {
225 span_err!(resolver.session,
228 "can't use type parameters from outer function; try using a local type \
231 ResolutionError::OuterTypeParameterContext => {
232 span_err!(resolver.session,
235 "cannot use an outer type parameter in this context");
237 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
238 span_err!(resolver.session,
241 "the name `{}` is already used for a type parameter in this type parameter \
245 ResolutionError::IsNotATrait(name) => {
246 span_err!(resolver.session, span, E0404, "`{}` is not a trait", name);
248 ResolutionError::UndeclaredTraitName(name) => {
249 span_err!(resolver.session,
252 "use of undeclared trait name `{}`",
255 ResolutionError::UndeclaredAssociatedType => {
256 span_err!(resolver.session, span, E0406, "undeclared associated type");
258 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
259 span_err!(resolver.session,
262 "method `{}` is not a member of trait `{}`",
266 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
267 span_err!(resolver.session,
270 "type `{}` is not a member of trait `{}`",
274 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
275 span_err!(resolver.session,
278 "const `{}` is not a member of trait `{}`",
282 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
283 span_err!(resolver.session,
286 "variable `{}` from pattern #1 is not bound in pattern #{}",
290 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
291 span_err!(resolver.session,
294 "variable `{}` is bound with different mode in pattern #{} than in pattern \
299 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
300 span_err!(resolver.session,
303 "variable `{}` from pattern #{} is not bound in pattern #1",
307 ResolutionError::SelfUsedOutsideImplOrTrait => {
308 span_err!(resolver.session,
311 "use of `Self` outside of an impl or trait");
313 ResolutionError::UseOfUndeclared(kind, name) => {
314 span_err!(resolver.session,
317 "use of undeclared {} `{}`",
321 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
322 span_err!(resolver.session,
325 "declaration of `{}` shadows an enum variant or unit-like struct in scope",
328 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
329 span_err!(resolver.session,
332 "only irrefutable patterns allowed here");
333 resolver.session.span_note(span,
334 "there already is a constant in scope sharing the same \
335 name as this pattern");
336 if let Some(sp) = resolver.ast_map.span_if_local(did) {
337 resolver.session.span_note(sp, "constant defined here");
339 if let Some(directive) = resolver.current_module
343 let item = resolver.ast_map.expect_item(directive.value_ns.id);
344 resolver.session.span_note(item.span, "constant imported here");
347 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
348 span_err!(resolver.session,
351 "identifier `{}` is bound more than once in this parameter list",
354 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
355 span_err!(resolver.session,
358 "identifier `{}` is bound more than once in the same pattern",
361 ResolutionError::StaticVariableReference => {
362 span_err!(resolver.session,
365 "static variables cannot be referenced in a pattern, use a `const` instead");
367 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
368 span_err!(resolver.session,
371 "`{}` is not an enum variant, struct or const",
374 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
375 span_err!(resolver.session,
378 "unresolved enum variant, struct or const `{}`",
381 ResolutionError::NotAnAssociatedConst(name) => {
382 span_err!(resolver.session,
385 "`{}` is not an associated const",
388 ResolutionError::UnresolvedAssociatedConst(name) => {
389 span_err!(resolver.session,
392 "unresolved associated const `{}`",
395 ResolutionError::DoesNotNameAStruct(name) => {
396 span_err!(resolver.session,
399 "`{}` does not name a structure",
402 ResolutionError::StructVariantUsedAsFunction(path_name) => {
403 span_err!(resolver.session,
406 "`{}` is the name of a struct or struct variant, but this expression uses \
407 it like a function name",
410 ResolutionError::SelfNotAvailableInStaticMethod => {
411 span_err!(resolver.session,
414 "`self` is not available in a static method. Maybe a `self` argument is \
417 ResolutionError::UnresolvedName(path, msg, context) => {
418 span_err!(resolver.session,
421 "unresolved name `{}`{}",
426 UnresolvedNameContext::Other => { } // no help available
427 UnresolvedNameContext::PathIsMod(id) => {
428 let mut help_msg = String::new();
429 let parent_id = resolver.ast_map.get_parent_node(id);
430 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
432 ExprField(_, ident) => {
433 help_msg = format!("To reference an item from the \
434 `{module}` module, use \
435 `{module}::{ident}`",
439 ExprMethodCall(ident, _, _) => {
440 help_msg = format!("To call a function from the \
441 `{module}` module, use \
442 `{module}::{ident}(..)`",
447 help_msg = format!("No function corresponds to `{module}(..)`",
450 _ => { } // no help available
453 help_msg = format!("Module `{module}` cannot be the value of an expression",
457 if !help_msg.is_empty() {
458 resolver.session.fileline_help(span, &help_msg);
463 ResolutionError::UndeclaredLabel(name) => {
464 span_err!(resolver.session,
467 "use of undeclared label `{}`",
470 ResolutionError::CannotUseRefBindingModeWith(descr) => {
471 span_err!(resolver.session,
474 "cannot use `ref` binding mode with {}",
477 ResolutionError::DuplicateDefinition(namespace, name) => {
478 span_err!(resolver.session,
481 "duplicate definition of {} `{}`",
485 ResolutionError::SelfImportsOnlyAllowedWithin => {
486 span_err!(resolver.session,
490 "`self` imports are only allowed within a { } list");
492 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
493 span_err!(resolver.session,
496 "`self` import can only appear once in the list");
498 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
499 span_err!(resolver.session,
502 "`self` import can only appear in an import list with a non-empty prefix");
504 ResolutionError::UnresolvedImport(name) => {
505 let msg = match name {
506 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
507 None => "unresolved import".to_owned(),
509 span_err!(resolver.session, span, E0432, "{}", msg);
511 ResolutionError::FailedToResolve(msg) => {
512 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
514 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
515 span_err!(resolver.session,
519 "can't capture dynamic environment in a fn item; use the || { ... } \
520 closure form instead");
522 ResolutionError::AttemptToUseNonConstantValueInConstant => {
523 span_err!(resolver.session,
526 "attempt to use a non-constant value in a constant");
531 #[derive(Copy, Clone)]
534 binding_mode: BindingMode,
537 // Map from the name in a pattern to its binding mode.
538 type BindingMap = HashMap<Name, BindingInfo>;
540 #[derive(Copy, Clone, PartialEq)]
541 enum PatternBindingMode {
543 LocalIrrefutableMode,
544 ArgumentIrrefutableMode,
547 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
553 /// A NamespaceResult represents the result of resolving an import in
554 /// a particular namespace. The result is either definitely-resolved,
555 /// definitely- unresolved, or unknown.
557 enum NamespaceResult {
558 /// Means that resolve hasn't gathered enough information yet to determine
559 /// whether the name is bound in this namespace. (That is, it hasn't
560 /// resolved all `use` directives yet.)
562 /// Means that resolve has determined that the name is definitely
563 /// not bound in the namespace.
565 /// Means that resolve has determined that the name is bound in the Module
566 /// argument, and specified by the NameBinding argument.
567 BoundResult(Rc<Module>, NameBinding),
570 impl NamespaceResult {
571 fn is_unknown(&self) -> bool {
573 UnknownResult => true,
577 fn is_unbound(&self) -> bool {
579 UnboundResult => true,
585 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
586 fn visit_nested_item(&mut self, item: hir::ItemId) {
587 self.visit_item(self.ast_map.expect_item(item.id))
589 fn visit_item(&mut self, item: &Item) {
590 execute_callback!(hir_map::Node::NodeItem(item), self);
591 self.resolve_item(item);
593 fn visit_arm(&mut self, arm: &Arm) {
594 self.resolve_arm(arm);
596 fn visit_block(&mut self, block: &Block) {
597 execute_callback!(hir_map::Node::NodeBlock(block), self);
598 self.resolve_block(block);
600 fn visit_expr(&mut self, expr: &Expr) {
601 execute_callback!(hir_map::Node::NodeExpr(expr), self);
602 self.resolve_expr(expr);
604 fn visit_local(&mut self, local: &Local) {
605 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
606 self.resolve_local(local);
608 fn visit_ty(&mut self, ty: &Ty) {
609 self.resolve_type(ty);
611 fn visit_generics(&mut self, generics: &Generics) {
612 self.resolve_generics(generics);
614 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
615 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
616 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
618 // error already reported
619 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
622 intravisit::walk_poly_trait_ref(self, tref, m);
624 fn visit_variant(&mut self,
625 variant: &hir::Variant,
627 item_id: ast::NodeId) {
628 execute_callback!(hir_map::Node::NodeVariant(variant), self);
629 if let Some(ref dis_expr) = variant.node.disr_expr {
630 // resolve the discriminator expr as a constant
631 self.with_constant_rib(|this| {
632 this.visit_expr(dis_expr);
636 // `intravisit::walk_variant` without the discriminant expression.
637 self.visit_variant_data(&variant.node.data,
643 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
644 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
645 let type_parameters = match foreign_item.node {
646 ForeignItemFn(_, ref generics) => {
647 HasTypeParameters(generics, FnSpace, ItemRibKind)
649 ForeignItemStatic(..) => NoTypeParameters,
651 self.with_type_parameter_rib(type_parameters, |this| {
652 intravisit::walk_foreign_item(this, foreign_item);
655 fn visit_fn(&mut self,
656 function_kind: FnKind<'v>,
657 declaration: &'v FnDecl,
661 let rib_kind = match function_kind {
662 FnKind::ItemFn(_, generics, _, _, _, _) => {
663 self.visit_generics(generics);
666 FnKind::Method(_, sig, _) => {
667 self.visit_generics(&sig.generics);
668 self.visit_explicit_self(&sig.explicit_self);
671 FnKind::Closure => ClosureRibKind(node_id),
673 self.resolve_function(rib_kind, declaration, block);
677 type ErrorMessage = Option<(Span, String)>;
679 enum ResolveResult<T> {
680 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
681 Indeterminate, // Couldn't determine due to unresolved globs.
682 Success(T), // Successfully resolved the import.
685 impl<T> ResolveResult<T> {
686 fn success(&self) -> bool {
694 enum FallbackSuggestion {
699 StaticMethod(String),
703 #[derive(Copy, Clone)]
704 enum TypeParameters<'a> {
706 HasTypeParameters(// Type parameters.
709 // Identifies the things that these parameters
710 // were declared on (type, fn, etc)
713 // The kind of the rib used for type parameters.
717 // The rib kind controls the translation of local
718 // definitions (`DefLocal`) to upvars (`DefUpvar`).
719 #[derive(Copy, Clone, Debug)]
721 // No translation needs to be applied.
724 // We passed through a closure scope at the given node ID.
725 // Translate upvars as appropriate.
726 ClosureRibKind(NodeId /* func id */),
728 // We passed through an impl or trait and are now in one of its
729 // methods. Allow references to ty params that impl or trait
730 // binds. Disallow any other upvars (including other ty params that are
734 // We passed through an item scope. Disallow upvars.
737 // We're in a constant item. Can't refer to dynamic stuff.
741 #[derive(Copy, Clone)]
742 enum UseLexicalScopeFlag {
747 enum ModulePrefixResult {
749 PrefixFound(Rc<Module>, usize),
752 #[derive(Copy, Clone)]
753 enum AssocItemResolveResult {
754 /// Syntax such as `<T>::item`, which can't be resolved until type
757 /// We should have been able to resolve the associated item.
758 ResolveAttempt(Option<PathResolution>),
761 #[derive(Copy, Clone, PartialEq)]
762 enum NameSearchType {
763 /// We're doing a name search in order to resolve a `use` directive.
766 /// We're doing a name search in order to resolve a path type, a path
767 /// expression, or a path pattern.
771 #[derive(Copy, Clone)]
772 enum BareIdentifierPatternResolution {
773 FoundStructOrEnumVariant(Def, LastPrivate),
774 FoundConst(Def, LastPrivate, Name),
775 BareIdentifierPatternUnresolved,
781 bindings: HashMap<Name, DefLike>,
786 fn new(kind: RibKind) -> Rib {
788 bindings: HashMap::new(),
794 /// A definition along with the index of the rib it was found on
796 ribs: Option<(Namespace, usize)>,
801 fn from_def(def: Def) -> Self {
809 /// The link from a module up to its nearest parent node.
810 #[derive(Clone,Debug)]
813 ModuleParentLink(Weak<Module>, Name),
814 BlockParentLink(Weak<Module>, NodeId),
817 /// One node in the tree of modules.
819 parent_link: ParentLink,
820 def: Cell<Option<Def>>,
823 children: RefCell<HashMap<Name, NameBindings>>,
824 imports: RefCell<Vec<ImportDirective>>,
826 // The external module children of this node that were declared with
828 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
830 // The anonymous children of this node. Anonymous children are pseudo-
831 // modules that are implicitly created around items contained within
834 // For example, if we have this:
842 // There will be an anonymous module created around `g` with the ID of the
843 // entry block for `f`.
844 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
846 // The status of resolving each import in this module.
847 import_resolutions: RefCell<HashMap<Name, ImportResolutionPerNamespace>>,
849 // The number of unresolved globs that this module exports.
850 glob_count: Cell<usize>,
852 // The number of unresolved pub imports (both regular and globs) in this module
853 pub_count: Cell<usize>,
855 // The number of unresolved pub glob imports in this module
856 pub_glob_count: Cell<usize>,
858 // The index of the import we're resolving.
859 resolved_import_count: Cell<usize>,
861 // Whether this module is populated. If not populated, any attempt to
862 // access the children must be preceded with a
863 // `populate_module_if_necessary` call.
864 populated: Cell<bool>,
868 fn new(parent_link: ParentLink,
874 parent_link: parent_link,
876 is_public: is_public,
877 children: RefCell::new(HashMap::new()),
878 imports: RefCell::new(Vec::new()),
879 external_module_children: RefCell::new(HashMap::new()),
880 anonymous_children: RefCell::new(NodeMap()),
881 import_resolutions: RefCell::new(HashMap::new()),
882 glob_count: Cell::new(0),
883 pub_count: Cell::new(0),
884 pub_glob_count: Cell::new(0),
885 resolved_import_count: Cell::new(0),
886 populated: Cell::new(!external),
890 fn def_id(&self) -> Option<DefId> {
891 self.def.get().as_ref().map(Def::def_id)
894 fn is_normal(&self) -> bool {
895 match self.def.get() {
896 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
901 fn is_trait(&self) -> bool {
902 match self.def.get() {
903 Some(DefTrait(_)) => true,
908 fn all_imports_resolved(&self) -> bool {
909 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
910 // it is currently being resolved ! so nope
913 self.imports.borrow().len() == self.resolved_import_count.get()
919 pub fn inc_glob_count(&self) {
920 self.glob_count.set(self.glob_count.get() + 1);
922 pub fn dec_glob_count(&self) {
923 assert!(self.glob_count.get() > 0);
924 self.glob_count.set(self.glob_count.get() - 1);
926 pub fn inc_pub_count(&self) {
927 self.pub_count.set(self.pub_count.get() + 1);
929 pub fn dec_pub_count(&self) {
930 assert!(self.pub_count.get() > 0);
931 self.pub_count.set(self.pub_count.get() - 1);
933 pub fn inc_pub_glob_count(&self) {
934 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
936 pub fn dec_pub_glob_count(&self) {
937 assert!(self.pub_glob_count.get() > 0);
938 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
942 impl fmt::Debug for Module {
943 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
957 flags DefModifiers: u8 {
958 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
959 // or `use Enum::*` to work on private enums.
960 const PUBLIC = 1 << 0,
961 const IMPORTABLE = 1 << 1,
962 // Variants are considered `PUBLIC`, but some of them live in private enums.
963 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
964 const PRIVATE_VARIANT = 1 << 2,
968 // Records a possibly-private value, type, or module definition.
971 modifiers: DefModifiers, // see note in ImportResolutionPerNamespace about how to use this
972 def_or_module: DefOrModule,
983 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
984 let modifiers = if module.is_public {
987 DefModifiers::empty()
988 } | DefModifiers::IMPORTABLE;
990 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
993 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
994 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
997 fn module(&self) -> Option<Rc<Module>> {
998 match self.def_or_module {
999 DefOrModule::Module(ref module) => Some(module.clone()),
1000 DefOrModule::Def(_) => None,
1004 fn def(&self) -> Option<Def> {
1005 match self.def_or_module {
1006 DefOrModule::Def(def) => Some(def),
1007 DefOrModule::Module(ref module) => module.def.get(),
1012 // Records at most one definition that a name in a namespace is bound to
1013 #[derive(Clone,Debug)]
1014 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
1018 NameBinding(Rc::new(RefCell::new(None)))
1021 fn create_from_module(module: Rc<Module>) -> Self {
1022 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
1025 fn set(&self, ns_def: NsDef) {
1026 *self.0.borrow_mut() = Some(ns_def);
1029 fn set_modifiers(&self, modifiers: DefModifiers) {
1030 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
1031 ns_def.modifiers = modifiers
1035 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> {
1039 // Lifted versions of the NsDef methods and fields
1040 fn def(&self) -> Option<Def> {
1041 self.borrow().as_ref().and_then(NsDef::def)
1043 fn module(&self) -> Option<Rc<Module>> {
1044 self.borrow().as_ref().and_then(NsDef::module)
1046 fn span(&self) -> Option<Span> {
1047 self.borrow().as_ref().and_then(|def| def.span)
1049 fn modifiers(&self) -> Option<DefModifiers> {
1050 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
1053 fn defined(&self) -> bool {
1054 self.borrow().is_some()
1057 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1058 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1061 fn is_public(&self) -> bool {
1062 self.defined_with(DefModifiers::PUBLIC)
1065 fn def_and_lp(&self) -> (Def, LastPrivate) {
1066 let def = self.def().unwrap();
1067 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1071 // Records the definitions (at most one for each namespace) that a name is
1073 #[derive(Clone,Debug)]
1074 pub struct NameBindings {
1075 type_ns: NameBinding, // < Meaning in type namespace.
1076 value_ns: NameBinding, // < Meaning in value namespace.
1079 impl ::std::ops::Index<Namespace> for NameBindings {
1080 type Output = NameBinding;
1081 fn index(&self, namespace: Namespace) -> &NameBinding {
1082 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1087 fn new() -> NameBindings {
1089 type_ns: NameBinding::new(),
1090 value_ns: NameBinding::new(),
1094 /// Creates a new module in this set of name bindings.
1095 fn define_module(&self, module: Rc<Module>, sp: Span) {
1096 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1099 /// Records a type definition.
1100 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1101 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1102 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1105 /// Records a value definition.
1106 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1107 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1108 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1112 /// Interns the names of the primitive types.
1113 struct PrimitiveTypeTable {
1114 primitive_types: HashMap<Name, PrimTy>,
1117 impl PrimitiveTypeTable {
1118 fn new() -> PrimitiveTypeTable {
1119 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1121 table.intern("bool", TyBool);
1122 table.intern("char", TyChar);
1123 table.intern("f32", TyFloat(TyF32));
1124 table.intern("f64", TyFloat(TyF64));
1125 table.intern("isize", TyInt(TyIs));
1126 table.intern("i8", TyInt(TyI8));
1127 table.intern("i16", TyInt(TyI16));
1128 table.intern("i32", TyInt(TyI32));
1129 table.intern("i64", TyInt(TyI64));
1130 table.intern("str", TyStr);
1131 table.intern("usize", TyUint(TyUs));
1132 table.intern("u8", TyUint(TyU8));
1133 table.intern("u16", TyUint(TyU16));
1134 table.intern("u32", TyUint(TyU32));
1135 table.intern("u64", TyUint(TyU64));
1140 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1141 self.primitive_types.insert(token::intern(string), primitive_type);
1145 /// The main resolver class.
1146 pub struct Resolver<'a, 'tcx: 'a> {
1147 session: &'a Session,
1149 ast_map: &'a hir_map::Map<'tcx>,
1151 graph_root: Rc<Module>,
1153 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1155 structs: FnvHashMap<DefId, Vec<Name>>,
1157 // The number of imports that are currently unresolved.
1158 unresolved_imports: usize,
1160 // The module that represents the current item scope.
1161 current_module: Rc<Module>,
1163 // The current set of local scopes, for values.
1164 // FIXME #4948: Reuse ribs to avoid allocation.
1165 value_ribs: Vec<Rib>,
1167 // The current set of local scopes, for types.
1168 type_ribs: Vec<Rib>,
1170 // The current set of local scopes, for labels.
1171 label_ribs: Vec<Rib>,
1173 // The trait that the current context can refer to.
1174 current_trait_ref: Option<(DefId, TraitRef)>,
1176 // The current self type if inside an impl (used for better errors).
1177 current_self_type: Option<Ty>,
1179 // The idents for the primitive types.
1180 primitive_type_table: PrimitiveTypeTable,
1182 def_map: RefCell<DefMap>,
1183 freevars: FreevarMap,
1184 freevars_seen: NodeMap<NodeMap<usize>>,
1185 export_map: ExportMap,
1186 trait_map: TraitMap,
1187 external_exports: ExternalExports,
1189 // Whether or not to print error messages. Can be set to true
1190 // when getting additional info for error message suggestions,
1191 // so as to avoid printing duplicate errors
1194 make_glob_map: bool,
1195 // Maps imports to the names of items actually imported (this actually maps
1196 // all imports, but only glob imports are actually interesting).
1199 used_imports: HashSet<(NodeId, Namespace)>,
1200 used_crates: HashSet<CrateNum>,
1202 // Callback function for intercepting walks
1203 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1204 // The intention is that the callback modifies this flag.
1205 // Once set, the resolver falls out of the walk, preserving the ribs.
1209 #[derive(PartialEq)]
1210 enum FallbackChecks {
1212 OnlyTraitAndStatics,
1215 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1216 fn new(session: &'a Session,
1217 ast_map: &'a hir_map::Map<'tcx>,
1218 make_glob_map: MakeGlobMap)
1219 -> Resolver<'a, 'tcx> {
1220 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1221 let graph_root = Module::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1228 // The outermost module has def ID 0; this is not reflected in the
1230 graph_root: graph_root.clone(),
1232 trait_item_map: FnvHashMap(),
1233 structs: FnvHashMap(),
1235 unresolved_imports: 0,
1237 current_module: graph_root,
1238 value_ribs: Vec::new(),
1239 type_ribs: Vec::new(),
1240 label_ribs: Vec::new(),
1242 current_trait_ref: None,
1243 current_self_type: None,
1245 primitive_type_table: PrimitiveTypeTable::new(),
1247 def_map: RefCell::new(NodeMap()),
1248 freevars: NodeMap(),
1249 freevars_seen: NodeMap(),
1250 export_map: NodeMap(),
1251 trait_map: NodeMap(),
1252 used_imports: HashSet::new(),
1253 used_crates: HashSet::new(),
1254 external_exports: DefIdSet(),
1257 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1258 glob_map: HashMap::new(),
1266 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1267 if !self.make_glob_map {
1270 if self.glob_map.contains_key(&import_id) {
1271 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1275 let mut new_set = HashSet::new();
1276 new_set.insert(name);
1277 self.glob_map.insert(import_id, new_set);
1280 fn get_trait_name(&self, did: DefId) -> Name {
1281 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1282 self.ast_map.expect_item(node_id).name
1284 self.session.cstore.item_name(did)
1288 /// Checks that the names of external crates don't collide with other
1289 /// external crates.
1290 fn check_for_conflicts_between_external_crates(&self,
1294 if module.external_module_children.borrow().contains_key(&name) {
1295 span_err!(self.session,
1298 "an external crate named `{}` has already been imported into this module",
1303 /// Checks that the names of items don't collide with external crates.
1304 fn check_for_conflicts_between_external_crates_and_items(&self,
1308 if module.external_module_children.borrow().contains_key(&name) {
1309 span_err!(self.session,
1312 "the name `{}` conflicts with an external crate that has been imported \
1318 /// Resolves the given module path from the given root `module_`.
1319 fn resolve_module_path_from_root(&mut self,
1320 module_: Rc<Module>,
1321 module_path: &[Name],
1324 name_search_type: NameSearchType,
1326 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1327 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1328 match module.external_module_children.borrow().get(&needle) {
1329 Some(_) => Some(module.clone()),
1330 None => match module.parent_link {
1331 ModuleParentLink(ref parent, _) => {
1332 search_parent_externals(needle, &parent.upgrade().unwrap())
1339 let mut search_module = module_;
1340 let mut index = index;
1341 let module_path_len = module_path.len();
1342 let mut closest_private = lp;
1344 // Resolve the module part of the path. This does not involve looking
1345 // upward though scope chains; we simply resolve names directly in
1346 // modules as we go.
1347 while index < module_path_len {
1348 let name = module_path[index];
1349 match self.resolve_name_in_module(search_module.clone(),
1355 let segment_name = name.as_str();
1356 let module_name = module_to_string(&*search_module);
1357 let mut span = span;
1358 let msg = if "???" == &module_name[..] {
1359 span.hi = span.lo + Pos::from_usize(segment_name.len());
1361 match search_parent_externals(name, &self.current_module) {
1363 let path_str = names_to_string(module_path);
1364 let target_mod_str = module_to_string(&*module);
1365 let current_mod_str = module_to_string(&*self.current_module);
1367 let prefix = if target_mod_str == current_mod_str {
1368 "self::".to_string()
1370 format!("{}::", target_mod_str)
1373 format!("Did you mean `{}{}`?", prefix, path_str)
1375 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1378 format!("Could not find `{}` in `{}`", segment_name, module_name)
1381 return Failed(Some((span, msg)));
1383 Failed(err) => return Failed(err),
1385 debug!("(resolving module path for import) module resolution is \
1388 return Indeterminate;
1390 Success((target, used_proxy)) => {
1391 // Check to see whether there are type bindings, and, if
1392 // so, whether there is a module within.
1393 if let Some(module_def) = target.binding.module() {
1394 // track extern crates for unused_extern_crate lint
1395 if let Some(did) = module_def.def_id() {
1396 self.used_crates.insert(did.krate);
1399 search_module = module_def;
1401 // Keep track of the closest private module used
1402 // when resolving this import chain.
1403 if !used_proxy && !search_module.is_public {
1404 if let Some(did) = search_module.def_id() {
1405 closest_private = LastMod(DependsOn(did));
1409 let msg = format!("Not a module `{}`", name);
1410 return Failed(Some((span, msg)));
1418 return Success((search_module, closest_private));
1421 /// Attempts to resolve the module part of an import directive or path
1422 /// rooted at the given module.
1424 /// On success, returns the resolved module, and the closest *private*
1425 /// module found to the destination when resolving this path.
1426 fn resolve_module_path(&mut self,
1427 module_: Rc<Module>,
1428 module_path: &[Name],
1429 use_lexical_scope: UseLexicalScopeFlag,
1431 name_search_type: NameSearchType)
1432 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1433 let module_path_len = module_path.len();
1434 assert!(module_path_len > 0);
1436 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1437 names_to_string(module_path),
1438 module_to_string(&*module_));
1440 // Resolve the module prefix, if any.
1441 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1446 match module_prefix_result {
1448 let mpath = names_to_string(module_path);
1449 let mpath = &mpath[..];
1450 match mpath.rfind(':') {
1452 let msg = format!("Could not find `{}` in `{}`",
1453 // idx +- 1 to account for the
1454 // colons on either side
1457 return Failed(Some((span, msg)));
1460 return Failed(None);
1464 Failed(err) => return Failed(err),
1466 debug!("(resolving module path for import) indeterminate; bailing");
1467 return Indeterminate;
1469 Success(NoPrefixFound) => {
1470 // There was no prefix, so we're considering the first element
1471 // of the path. How we handle this depends on whether we were
1472 // instructed to use lexical scope or not.
1473 match use_lexical_scope {
1474 DontUseLexicalScope => {
1475 // This is a crate-relative path. We will start the
1476 // resolution process at index zero.
1477 search_module = self.graph_root.clone();
1479 last_private = LastMod(AllPublic);
1481 UseLexicalScope => {
1482 // This is not a crate-relative path. We resolve the
1483 // first component of the path in the current lexical
1484 // scope and then proceed to resolve below that.
1485 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1486 Failed(err) => return Failed(err),
1488 debug!("(resolving module path for import) indeterminate; bailing");
1489 return Indeterminate;
1491 Success(containing_module) => {
1492 search_module = containing_module;
1494 last_private = LastMod(AllPublic);
1500 Success(PrefixFound(ref containing_module, index)) => {
1501 search_module = containing_module.clone();
1502 start_index = index;
1503 last_private = LastMod(DependsOn(containing_module.def_id()
1508 self.resolve_module_path_from_root(search_module,
1516 /// Invariant: This must only be called during main resolution, not during
1517 /// import resolution.
1518 fn resolve_item_in_lexical_scope(&mut self,
1519 module_: Rc<Module>,
1521 namespace: Namespace,
1523 -> ResolveResult<(Target, bool)> {
1524 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1527 module_to_string(&*module_));
1529 // The current module node is handled specially. First, check for
1530 // its immediate children.
1531 build_reduced_graph::populate_module_if_necessary(self, &module_);
1533 match module_.children.borrow().get(&name) {
1534 Some(name_bindings) if name_bindings[namespace].defined() => {
1535 debug!("top name bindings succeeded");
1536 return Success((Target::new(module_.clone(),
1537 name_bindings[namespace].clone(),
1542 // Not found; continue.
1546 // Now check for its import directives. We don't have to have resolved
1547 // all its imports in the usual way; this is because chains of
1548 // adjacent import statements are processed as though they mutated the
1550 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1551 match import_resolution[namespace].target.clone() {
1553 // Not found; continue.
1554 debug!("(resolving item in lexical scope) found import resolution, but not \
1559 debug!("(resolving item in lexical scope) using import resolution");
1560 // track used imports and extern crates as well
1561 let id = import_resolution[namespace].id;
1563 self.used_imports.insert((id, namespace));
1564 self.record_import_use(id, name);
1565 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1566 self.used_crates.insert(kid);
1569 return Success((target, false));
1574 // Search for external modules.
1575 if namespace == TypeNS {
1576 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1577 let child = module_.external_module_children.borrow().get(&name).cloned();
1578 if let Some(module) = child {
1579 let name_binding = NameBinding::create_from_module(module);
1580 debug!("lower name bindings succeeded");
1581 return Success((Target::new(module_, name_binding, Shadowable::Never),
1586 // Finally, proceed up the scope chain looking for parent modules.
1587 let mut search_module = module_;
1589 // Go to the next parent.
1590 match search_module.parent_link.clone() {
1592 // No more parents. This module was unresolved.
1593 debug!("(resolving item in lexical scope) unresolved module");
1594 return Failed(None);
1596 ModuleParentLink(parent_module_node, _) => {
1597 if search_module.is_normal() {
1598 // We stop the search here.
1599 debug!("(resolving item in lexical scope) unresolved module: not \
1600 searching through module parents");
1601 return Failed(None);
1603 search_module = parent_module_node.upgrade().unwrap();
1606 BlockParentLink(ref parent_module_node, _) => {
1607 search_module = parent_module_node.upgrade().unwrap();
1611 // Resolve the name in the parent module.
1612 match self.resolve_name_in_module(search_module.clone(),
1617 Failed(Some((span, msg))) => {
1618 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1620 Failed(None) => (), // Continue up the search chain.
1622 // We couldn't see through the higher scope because of an
1623 // unresolved import higher up. Bail.
1625 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1626 return Indeterminate;
1628 Success((target, used_reexport)) => {
1629 // We found the module.
1630 debug!("(resolving item in lexical scope) found name in module, done");
1631 return Success((target, used_reexport));
1637 /// Resolves a module name in the current lexical scope.
1638 fn resolve_module_in_lexical_scope(&mut self,
1639 module_: Rc<Module>,
1641 -> ResolveResult<Rc<Module>> {
1642 // If this module is an anonymous module, resolve the item in the
1643 // lexical scope. Otherwise, resolve the item from the crate root.
1644 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS, true);
1645 match resolve_result {
1646 Success((target, _)) => {
1647 if let Some(module_def) = target.binding.module() {
1648 return Success(module_def)
1650 debug!("!!! (resolving module in lexical scope) module \
1651 wasn't actually a module!");
1652 return Failed(None);
1656 debug!("(resolving module in lexical scope) indeterminate; bailing");
1657 return Indeterminate;
1660 debug!("(resolving module in lexical scope) failed to resolve");
1666 /// Returns the nearest normal module parent of the given module.
1667 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1668 let mut module_ = module_;
1670 match module_.parent_link.clone() {
1671 NoParentLink => return None,
1672 ModuleParentLink(new_module, _) |
1673 BlockParentLink(new_module, _) => {
1674 let new_module = new_module.upgrade().unwrap();
1675 if new_module.is_normal() {
1676 return Some(new_module);
1678 module_ = new_module;
1684 /// Returns the nearest normal module parent of the given module, or the
1685 /// module itself if it is a normal module.
1686 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1687 if module_.is_normal() {
1690 match self.get_nearest_normal_module_parent(module_.clone()) {
1692 Some(new_module) => new_module,
1696 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1697 /// (b) some chain of `super::`.
1698 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1699 fn resolve_module_prefix(&mut self,
1700 module_: Rc<Module>,
1701 module_path: &[Name])
1702 -> ResolveResult<ModulePrefixResult> {
1703 // Start at the current module if we see `self` or `super`, or at the
1704 // top of the crate otherwise.
1705 let mut i = match &*module_path[0].as_str() {
1708 _ => return Success(NoPrefixFound),
1710 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1712 // Now loop through all the `super`s we find.
1713 while i < module_path.len() && "super" == module_path[i].as_str() {
1714 debug!("(resolving module prefix) resolving `super` at {}",
1715 module_to_string(&*containing_module));
1716 match self.get_nearest_normal_module_parent(containing_module) {
1717 None => return Failed(None),
1718 Some(new_module) => {
1719 containing_module = new_module;
1725 debug!("(resolving module prefix) finished resolving prefix at {}",
1726 module_to_string(&*containing_module));
1728 return Success(PrefixFound(containing_module, i));
1731 /// Attempts to resolve the supplied name in the given module for the
1732 /// given namespace. If successful, returns the target corresponding to
1735 /// The boolean returned on success is an indicator of whether this lookup
1736 /// passed through a public re-export proxy.
1737 fn resolve_name_in_module(&mut self,
1738 module_: Rc<Module>,
1740 namespace: Namespace,
1741 name_search_type: NameSearchType,
1742 allow_private_imports: bool)
1743 -> ResolveResult<(Target, bool)> {
1744 debug!("(resolving name in module) resolving `{}` in `{}`",
1746 module_to_string(&*module_));
1748 // First, check the direct children of the module.
1749 build_reduced_graph::populate_module_if_necessary(self, &module_);
1751 match module_.children.borrow().get(&name) {
1752 Some(name_bindings) if name_bindings[namespace].defined() => {
1753 debug!("(resolving name in module) found node as child");
1754 return Success((Target::new(module_.clone(),
1755 name_bindings[namespace].clone(),
1764 // Next, check the module's imports if necessary.
1766 // If this is a search of all imports, we should be done with glob
1767 // resolution at this point.
1768 if name_search_type == PathSearch {
1769 assert_eq!(module_.glob_count.get(), 0);
1772 // Check the list of resolved imports.
1773 match module_.import_resolutions.borrow().get(&name) {
1774 Some(import_resolution) if allow_private_imports ||
1775 import_resolution[namespace].is_public => {
1777 if import_resolution[namespace].is_public &&
1778 import_resolution.outstanding_references != 0 {
1779 debug!("(resolving name in module) import unresolved; bailing out");
1780 return Indeterminate;
1782 match import_resolution[namespace].target.clone() {
1784 debug!("(resolving name in module) name found, but not in namespace {:?}",
1788 debug!("(resolving name in module) resolved to import");
1789 // track used imports and extern crates as well
1790 let id = import_resolution[namespace].id;
1791 self.used_imports.insert((id, namespace));
1792 self.record_import_use(id, name);
1793 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1794 self.used_crates.insert(kid);
1796 return Success((target, true));
1800 Some(..) | None => {} // Continue.
1803 // Finally, search through external children.
1804 if namespace == TypeNS {
1805 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1806 let child = module_.external_module_children.borrow().get(&name).cloned();
1807 if let Some(module) = child {
1808 let name_binding = NameBinding::create_from_module(module);
1809 return Success((Target::new(module_, name_binding, Shadowable::Never),
1814 // We're out of luck.
1815 debug!("(resolving name in module) failed to resolve `{}`", name);
1816 return Failed(None);
1819 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1820 let index = module_.resolved_import_count.get();
1821 let imports = module_.imports.borrow();
1822 let import_count = imports.len();
1823 if index != import_count {
1825 (*imports)[index].span,
1826 ResolutionError::UnresolvedImport(None));
1829 // Descend into children and anonymous children.
1830 build_reduced_graph::populate_module_if_necessary(self, &module_);
1832 for (_, child_node) in module_.children.borrow().iter() {
1833 match child_node.type_ns.module() {
1837 Some(child_module) => {
1838 self.report_unresolved_imports(child_module);
1843 for (_, module_) in module_.anonymous_children.borrow().iter() {
1844 self.report_unresolved_imports(module_.clone());
1850 // We maintain a list of value ribs and type ribs.
1852 // Simultaneously, we keep track of the current position in the module
1853 // graph in the `current_module` pointer. When we go to resolve a name in
1854 // the value or type namespaces, we first look through all the ribs and
1855 // then query the module graph. When we resolve a name in the module
1856 // namespace, we can skip all the ribs (since nested modules are not
1857 // allowed within blocks in Rust) and jump straight to the current module
1860 // Named implementations are handled separately. When we find a method
1861 // call, we consult the module node to find all of the implementations in
1862 // scope. This information is lazily cached in the module node. We then
1863 // generate a fake "implementation scope" containing all the
1864 // implementations thus found, for compatibility with old resolve pass.
1866 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1867 where F: FnOnce(&mut Resolver)
1869 let orig_module = self.current_module.clone();
1871 // Move down in the graph.
1877 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1879 match orig_module.children.borrow().get(&name) {
1881 debug!("!!! (with scope) didn't find `{}` in `{}`",
1883 module_to_string(&*orig_module));
1885 Some(name_bindings) => {
1886 match name_bindings.type_ns.module() {
1888 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1890 module_to_string(&*orig_module));
1893 self.current_module = module_;
1903 self.current_module = orig_module;
1906 /// Searches the current set of local scopes for labels.
1907 /// Stops after meeting a closure.
1908 fn search_label(&self, name: Name) -> Option<DefLike> {
1909 for rib in self.label_ribs.iter().rev() {
1915 // Do not resolve labels across function boundary
1919 let result = rib.bindings.get(&name).cloned();
1920 if result.is_some() {
1927 fn resolve_crate(&mut self, krate: &hir::Crate) {
1928 debug!("(resolving crate) starting");
1930 intravisit::walk_crate(self, krate);
1933 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1934 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1935 span_err!(self.session,
1938 "user-defined types or type parameters cannot shadow the primitive types");
1942 fn resolve_item(&mut self, item: &Item) {
1943 let name = item.name;
1945 debug!("(resolving item) resolving {}", name);
1948 ItemEnum(_, ref generics) |
1949 ItemTy(_, ref generics) |
1950 ItemStruct(_, ref generics) => {
1951 self.check_if_primitive_type_name(name, item.span);
1953 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1954 |this| intravisit::walk_item(this, item));
1956 ItemFn(_, _, _, _, ref generics, _) => {
1957 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1958 |this| intravisit::walk_item(this, item));
1961 ItemDefaultImpl(_, ref trait_ref) => {
1962 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1964 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1965 self.resolve_implementation(generics,
1972 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1973 self.check_if_primitive_type_name(name, item.span);
1975 // Create a new rib for the trait-wide type parameters.
1976 self.with_type_parameter_rib(HasTypeParameters(generics,
1980 let local_def_id = this.ast_map.local_def_id(item.id);
1981 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1982 this.visit_generics(generics);
1983 walk_list!(this, visit_ty_param_bound, bounds);
1985 for trait_item in trait_items {
1986 match trait_item.node {
1987 hir::ConstTraitItem(_, ref default) => {
1988 // Only impose the restrictions of
1989 // ConstRibKind if there's an actual constant
1990 // expression in a provided default.
1991 if default.is_some() {
1992 this.with_constant_rib(|this| {
1993 intravisit::walk_trait_item(this, trait_item)
1996 intravisit::walk_trait_item(this, trait_item)
1999 hir::MethodTraitItem(ref sig, _) => {
2000 let type_parameters =
2001 HasTypeParameters(&sig.generics,
2004 this.with_type_parameter_rib(type_parameters, |this| {
2005 intravisit::walk_trait_item(this, trait_item)
2008 hir::TypeTraitItem(..) => {
2009 this.check_if_primitive_type_name(trait_item.name,
2011 this.with_type_parameter_rib(NoTypeParameters, |this| {
2012 intravisit::walk_trait_item(this, trait_item)
2021 ItemMod(_) | ItemForeignMod(_) => {
2022 self.with_scope(Some(name), |this| {
2023 intravisit::walk_item(this, item);
2027 ItemConst(..) | ItemStatic(..) => {
2028 self.with_constant_rib(|this| {
2029 intravisit::walk_item(this, item);
2033 ItemUse(ref view_path) => {
2034 // check for imports shadowing primitive types
2035 let check_rename = |this: &Self, id, name| {
2036 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
2037 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2038 this.check_if_primitive_type_name(name, item.span);
2044 match view_path.node {
2045 hir::ViewPathSimple(name, _) => {
2046 check_rename(self, item.id, name);
2048 hir::ViewPathList(ref prefix, ref items) => {
2050 if let Some(name) = item.node.rename() {
2051 check_rename(self, item.node.id(), name);
2055 // Resolve prefix of an import with empty braces (issue #28388)
2056 if items.is_empty() && !prefix.segments.is_empty() {
2057 match self.resolve_crate_relative_path(prefix.span,
2061 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2065 ResolutionError::FailedToResolve(
2066 &path_names_to_string(prefix, 0)));
2067 self.record_def(item.id, err_path_resolution());
2076 ItemExternCrate(_) => {
2077 // do nothing, these are just around to be encoded
2082 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2083 where F: FnOnce(&mut Resolver)
2085 match type_parameters {
2086 HasTypeParameters(generics, space, rib_kind) => {
2087 let mut function_type_rib = Rib::new(rib_kind);
2088 let mut seen_bindings = HashSet::new();
2089 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2090 let name = type_parameter.name;
2091 debug!("with_type_parameter_rib: {}", type_parameter.id);
2093 if seen_bindings.contains(&name) {
2095 type_parameter.span,
2096 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2098 seen_bindings.insert(name);
2100 // plain insert (no renaming)
2101 function_type_rib.bindings
2103 DlDef(DefTyParam(space,
2106 .local_def_id(type_parameter.id),
2109 self.type_ribs.push(function_type_rib);
2112 NoTypeParameters => {
2119 match type_parameters {
2120 HasTypeParameters(..) => {
2122 self.type_ribs.pop();
2125 NoTypeParameters => {}
2129 fn with_label_rib<F>(&mut self, f: F)
2130 where F: FnOnce(&mut Resolver)
2132 self.label_ribs.push(Rib::new(NormalRibKind));
2135 self.label_ribs.pop();
2139 fn with_constant_rib<F>(&mut self, f: F)
2140 where F: FnOnce(&mut Resolver)
2142 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2143 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2146 self.type_ribs.pop();
2147 self.value_ribs.pop();
2151 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2152 // Create a value rib for the function.
2153 self.value_ribs.push(Rib::new(rib_kind));
2155 // Create a label rib for the function.
2156 self.label_ribs.push(Rib::new(rib_kind));
2158 // Add each argument to the rib.
2159 let mut bindings_list = HashMap::new();
2160 for argument in &declaration.inputs {
2161 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2163 self.visit_ty(&*argument.ty);
2165 debug!("(resolving function) recorded argument");
2167 intravisit::walk_fn_ret_ty(self, &declaration.output);
2169 // Resolve the function body.
2170 self.visit_block(block);
2172 debug!("(resolving function) leaving function");
2175 self.label_ribs.pop();
2176 self.value_ribs.pop();
2180 fn resolve_trait_reference(&mut self,
2184 -> Result<PathResolution, ()> {
2185 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2186 if let DefTrait(_) = path_res.base_def {
2187 debug!("(resolving trait) found trait def: {:?}", path_res);
2192 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2195 // If it's a typedef, give a note
2196 if let DefTy(..) = path_res.base_def {
2198 .span_note(trait_path.span, "`type` aliases cannot be used for traits");
2205 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2211 fn resolve_generics(&mut self, generics: &Generics) {
2212 for type_parameter in generics.ty_params.iter() {
2213 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2215 for predicate in &generics.where_clause.predicates {
2217 &hir::WherePredicate::BoundPredicate(_) |
2218 &hir::WherePredicate::RegionPredicate(_) => {}
2219 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2220 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2221 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2222 self.record_def(eq_pred.id, path_res.unwrap());
2226 ResolutionError::UndeclaredAssociatedType);
2227 self.record_def(eq_pred.id, err_path_resolution());
2232 intravisit::walk_generics(self, generics);
2235 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2236 where F: FnOnce(&mut Resolver) -> T
2238 // Handle nested impls (inside fn bodies)
2239 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2240 let result = f(self);
2241 self.current_self_type = previous_value;
2245 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2246 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2248 let mut new_val = None;
2249 let mut new_id = None;
2250 if let Some(trait_ref) = opt_trait_ref {
2251 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2254 assert!(path_res.depth == 0);
2255 self.record_def(trait_ref.ref_id, path_res);
2256 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2257 new_id = Some(path_res.base_def.def_id());
2259 self.record_def(trait_ref.ref_id, err_path_resolution());
2261 intravisit::walk_trait_ref(self, trait_ref);
2263 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2264 let result = f(self, new_id);
2265 self.current_trait_ref = original_trait_ref;
2269 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2270 where F: FnOnce(&mut Resolver)
2272 let mut self_type_rib = Rib::new(NormalRibKind);
2274 // plain insert (no renaming, types are not currently hygienic....)
2275 let name = special_names::type_self;
2276 self_type_rib.bindings.insert(name, DlDef(self_def));
2277 self.type_ribs.push(self_type_rib);
2280 self.type_ribs.pop();
2284 fn resolve_implementation(&mut self,
2285 generics: &Generics,
2286 opt_trait_reference: &Option<TraitRef>,
2289 impl_items: &[ImplItem]) {
2290 // If applicable, create a rib for the type parameters.
2291 self.with_type_parameter_rib(HasTypeParameters(generics,
2295 // Resolve the type parameters.
2296 this.visit_generics(generics);
2298 // Resolve the trait reference, if necessary.
2299 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2300 // Resolve the self type.
2301 this.visit_ty(self_type);
2303 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2304 this.with_current_self_type(self_type, |this| {
2305 for impl_item in impl_items {
2306 match impl_item.node {
2307 hir::ImplItemKind::Const(..) => {
2308 // If this is a trait impl, ensure the const
2310 this.check_trait_item(impl_item.name,
2312 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2313 this.with_constant_rib(|this| {
2314 intravisit::walk_impl_item(this, impl_item);
2317 hir::ImplItemKind::Method(ref sig, _) => {
2318 // If this is a trait impl, ensure the method
2320 this.check_trait_item(impl_item.name,
2322 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2324 // We also need a new scope for the method-
2325 // specific type parameters.
2326 let type_parameters =
2327 HasTypeParameters(&sig.generics,
2330 this.with_type_parameter_rib(type_parameters, |this| {
2331 intravisit::walk_impl_item(this, impl_item);
2334 hir::ImplItemKind::Type(ref ty) => {
2335 // If this is a trait impl, ensure the type
2337 this.check_trait_item(impl_item.name,
2339 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2351 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2352 where F: FnOnce(Name, &str) -> ResolutionError
2354 // If there is a TraitRef in scope for an impl, then the method must be in the
2356 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2357 if !self.trait_item_map.contains_key(&(name, did)) {
2358 let path_str = path_names_to_string(&trait_ref.path, 0);
2359 resolve_error(self, span, err(name, &*path_str));
2364 fn resolve_local(&mut self, local: &Local) {
2365 // Resolve the type.
2366 walk_list!(self, visit_ty, &local.ty);
2368 // Resolve the initializer.
2369 walk_list!(self, visit_expr, &local.init);
2371 // Resolve the pattern.
2372 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2375 // build a map from pattern identifiers to binding-info's.
2376 // this is done hygienically. This could arise for a macro
2377 // that expands into an or-pattern where one 'x' was from the
2378 // user and one 'x' came from the macro.
2379 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2380 let mut result = HashMap::new();
2381 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2382 let name = path1.node;
2386 binding_mode: binding_mode,
2392 // check that all of the arms in an or-pattern have exactly the
2393 // same set of bindings, with the same binding modes for each.
2394 fn check_consistent_bindings(&mut self, arm: &Arm) {
2395 if arm.pats.is_empty() {
2398 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2399 for (i, p) in arm.pats.iter().enumerate() {
2400 let map_i = self.binding_mode_map(&**p);
2402 for (&key, &binding_0) in &map_0 {
2403 match map_i.get(&key) {
2407 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2409 Some(binding_i) => {
2410 if binding_0.binding_mode != binding_i.binding_mode {
2413 ResolutionError::VariableBoundWithDifferentMode(key,
2420 for (&key, &binding) in &map_i {
2421 if !map_0.contains_key(&key) {
2424 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2430 fn resolve_arm(&mut self, arm: &Arm) {
2431 self.value_ribs.push(Rib::new(NormalRibKind));
2433 let mut bindings_list = HashMap::new();
2434 for pattern in &arm.pats {
2435 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2438 // This has to happen *after* we determine which
2439 // pat_idents are variants
2440 self.check_consistent_bindings(arm);
2442 walk_list!(self, visit_expr, &arm.guard);
2443 self.visit_expr(&*arm.body);
2446 self.value_ribs.pop();
2450 fn resolve_block(&mut self, block: &Block) {
2451 debug!("(resolving block) entering block");
2452 self.value_ribs.push(Rib::new(NormalRibKind));
2454 // Move down in the graph, if there's an anonymous module rooted here.
2455 let orig_module = self.current_module.clone();
2456 match orig_module.anonymous_children.borrow().get(&block.id) {
2460 Some(anonymous_module) => {
2461 debug!("(resolving block) found anonymous module, moving down");
2462 self.current_module = anonymous_module.clone();
2466 // Check for imports appearing after non-item statements.
2467 let mut found_non_item = false;
2468 for statement in &block.stmts {
2469 if let hir::StmtDecl(ref declaration, _) = statement.node {
2470 if let hir::DeclItem(i) = declaration.node {
2471 let i = self.ast_map.expect_item(i.id);
2473 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2474 span_err!(self.session,
2477 "imports are not allowed after non-item statements");
2482 found_non_item = true
2485 found_non_item = true;
2489 // Descend into the block.
2490 intravisit::walk_block(self, block);
2494 self.current_module = orig_module;
2495 self.value_ribs.pop();
2497 debug!("(resolving block) leaving block");
2500 fn resolve_type(&mut self, ty: &Ty) {
2502 TyPath(ref maybe_qself, ref path) => {
2503 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2504 maybe_qself.as_ref(),
2508 // `<T>::a::b::c` is resolved by typeck alone.
2509 TypecheckRequired => {
2510 // Resolve embedded types.
2511 intravisit::walk_ty(self, ty);
2514 ResolveAttempt(resolution) => resolution,
2517 // This is a path in the type namespace. Walk through scopes
2521 // Write the result into the def map.
2522 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2523 path_names_to_string(path, 0),
2526 self.record_def(ty.id, def);
2529 self.record_def(ty.id, err_path_resolution());
2531 // Keep reporting some errors even if they're ignored above.
2532 self.resolve_path(ty.id, path, 0, TypeNS, true);
2534 let kind = if maybe_qself.is_some() {
2540 let self_type_name = special_idents::type_self.name;
2541 let is_invalid_self_type_name = path.segments.len() > 0 &&
2542 maybe_qself.is_none() &&
2543 path.segments[0].identifier.name ==
2545 if is_invalid_self_type_name {
2548 ResolutionError::SelfUsedOutsideImplOrTrait);
2552 ResolutionError::UseOfUndeclared(
2554 &*path_names_to_string(path,
2563 // Resolve embedded types.
2564 intravisit::walk_ty(self, ty);
2567 fn resolve_pattern(&mut self,
2569 mode: PatternBindingMode,
2570 // Maps idents to the node ID for the (outermost)
2571 // pattern that binds them
2572 bindings_list: &mut HashMap<Name, NodeId>) {
2573 let pat_id = pattern.id;
2574 walk_pat(pattern, |pattern| {
2575 match pattern.node {
2576 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2577 // The meaning of PatIdent with no type parameters
2578 // depends on whether an enum variant or unit-like struct
2579 // with that name is in scope. The probing lookup has to
2580 // be careful not to emit spurious errors. Only matching
2581 // patterns (match) can match nullary variants or
2582 // unit-like structs. For binding patterns (let
2583 // and the LHS of @-patterns), matching such a value is
2584 // simply disallowed (since it's rarely what you want).
2585 let const_ok = mode == RefutableMode && at_rhs.is_none();
2587 let ident = path1.node;
2588 let renamed = ident.name;
2590 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2592 FoundStructOrEnumVariant(def, lp) if const_ok => {
2593 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2596 self.enforce_default_binding_mode(pattern,
2599 self.record_def(pattern.id,
2606 FoundStructOrEnumVariant(..) => {
2610 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2613 self.record_def(pattern.id, err_path_resolution());
2615 FoundConst(def, lp, _) if const_ok => {
2616 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2618 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2619 self.record_def(pattern.id,
2626 FoundConst(def, _, name) => {
2630 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2633 self.record_def(pattern.id, err_path_resolution());
2635 BareIdentifierPatternUnresolved => {
2636 debug!("(resolving pattern) binding `{}`", renamed);
2638 let def_id = self.ast_map.local_def_id(pattern.id);
2639 let def = DefLocal(def_id, pattern.id);
2641 // Record the definition so that later passes
2642 // will be able to distinguish variants from
2643 // locals in patterns.
2645 self.record_def(pattern.id,
2648 last_private: LastMod(AllPublic),
2652 // Add the binding to the local ribs, if it
2653 // doesn't already exist in the bindings list. (We
2654 // must not add it if it's in the bindings list
2655 // because that breaks the assumptions later
2656 // passes make about or-patterns.)
2657 if !bindings_list.contains_key(&renamed) {
2658 let this = &mut *self;
2659 let last_rib = this.value_ribs.last_mut().unwrap();
2660 last_rib.bindings.insert(renamed, DlDef(def));
2661 bindings_list.insert(renamed, pat_id);
2662 } else if mode == ArgumentIrrefutableMode &&
2663 bindings_list.contains_key(&renamed) {
2664 // Forbid duplicate bindings in the same
2669 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2670 &ident.name.as_str())
2672 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2673 // Then this is a duplicate variable in the
2674 // same disjunction, which is an error.
2678 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2679 &ident.name.as_str())
2682 // Else, not bound in the same pattern: do
2688 PatEnum(ref path, _) => {
2689 // This must be an enum variant, struct or const.
2690 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2695 // The below shouldn't happen because all
2696 // qualified paths should be in PatQPath.
2697 TypecheckRequired =>
2698 self.session.span_bug(path.span,
2699 "resolve_possibly_assoc_item claimed
2701 that a path in PatEnum requires typecheck
2703 to resolve, but qualified paths should be
2706 ResolveAttempt(resolution) => resolution,
2708 if let Some(path_res) = resolution {
2709 match path_res.base_def {
2710 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2711 self.record_def(pattern.id, path_res);
2714 resolve_error(&self,
2716 ResolutionError::StaticVariableReference);
2717 self.record_def(pattern.id, err_path_resolution());
2720 // If anything ends up here entirely resolved,
2721 // it's an error. If anything ends up here
2722 // partially resolved, that's OK, because it may
2723 // be a `T::CONST` that typeck will resolve.
2724 if path_res.depth == 0 {
2728 ResolutionError::NotAnEnumVariantStructOrConst(
2736 self.record_def(pattern.id, err_path_resolution());
2738 let const_name = path.segments
2743 let traits = self.get_traits_containing_item(const_name);
2744 self.trait_map.insert(pattern.id, traits);
2745 self.record_def(pattern.id, path_res);
2753 ResolutionError::UnresolvedEnumVariantStructOrConst(
2754 &path.segments.last().unwrap().identifier.name.as_str())
2756 self.record_def(pattern.id, err_path_resolution());
2758 intravisit::walk_path(self, path);
2761 PatQPath(ref qself, ref path) => {
2762 // Associated constants only.
2763 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2768 TypecheckRequired => {
2769 // All `<T>::CONST` should end up here, and will
2770 // require use of the trait map to resolve
2771 // during typechecking.
2772 let const_name = path.segments
2777 let traits = self.get_traits_containing_item(const_name);
2778 self.trait_map.insert(pattern.id, traits);
2779 intravisit::walk_pat(self, pattern);
2782 ResolveAttempt(resolution) => resolution,
2784 if let Some(path_res) = resolution {
2785 match path_res.base_def {
2786 // All `<T as Trait>::CONST` should end up here, and
2787 // have the trait already selected.
2788 DefAssociatedConst(..) => {
2789 self.record_def(pattern.id, path_res);
2795 ResolutionError::NotAnAssociatedConst(
2796 &path.segments.last().unwrap().identifier.name.as_str()
2799 self.record_def(pattern.id, err_path_resolution());
2805 ResolutionError::UnresolvedAssociatedConst(&path.segments
2811 self.record_def(pattern.id, err_path_resolution());
2813 intravisit::walk_pat(self, pattern);
2816 PatStruct(ref path, _, _) => {
2817 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2818 Some(definition) => {
2819 self.record_def(pattern.id, definition);
2822 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2826 ResolutionError::DoesNotNameAStruct(
2827 &*path_names_to_string(path, 0))
2829 self.record_def(pattern.id, err_path_resolution());
2832 intravisit::walk_path(self, path);
2835 PatLit(_) | PatRange(..) => {
2836 intravisit::walk_pat(self, pattern);
2847 fn resolve_bare_identifier_pattern(&mut self,
2850 -> BareIdentifierPatternResolution {
2851 let module = self.current_module.clone();
2852 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2853 Success((target, _)) => {
2854 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2856 target.binding.borrow());
2857 match target.binding.def() {
2859 panic!("resolved name in the value namespace to a set of name bindings \
2862 // For the two success cases, this lookup can be
2863 // considered as not having a private component because
2864 // the lookup happened only within the current module.
2865 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2866 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2868 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2869 return FoundConst(def, LastMod(AllPublic), name);
2871 Some(DefStatic(..)) => {
2872 resolve_error(self, span, ResolutionError::StaticVariableReference);
2873 return BareIdentifierPatternUnresolved;
2875 _ => return BareIdentifierPatternUnresolved
2880 panic!("unexpected indeterminate result");
2884 Some((span, msg)) => {
2885 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2890 debug!("(resolve bare identifier pattern) failed to find {}", name);
2891 return BareIdentifierPatternUnresolved;
2896 /// Handles paths that may refer to associated items
2897 fn resolve_possibly_assoc_item(&mut self,
2899 maybe_qself: Option<&hir::QSelf>,
2901 namespace: Namespace,
2903 -> AssocItemResolveResult {
2904 let max_assoc_types;
2908 if qself.position == 0 {
2909 return TypecheckRequired;
2911 max_assoc_types = path.segments.len() - qself.position;
2912 // Make sure the trait is valid.
2913 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2916 max_assoc_types = path.segments.len();
2920 let mut resolution = self.with_no_errors(|this| {
2921 this.resolve_path(id, path, 0, namespace, check_ribs)
2923 for depth in 1..max_assoc_types {
2924 if resolution.is_some() {
2927 self.with_no_errors(|this| {
2928 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2931 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2932 // A module is not a valid type or value.
2935 ResolveAttempt(resolution)
2938 /// If `check_ribs` is true, checks the local definitions first; i.e.
2939 /// doesn't skip straight to the containing module.
2940 /// Skips `path_depth` trailing segments, which is also reflected in the
2941 /// returned value. See `middle::def::PathResolution` for more info.
2942 pub fn resolve_path(&mut self,
2946 namespace: Namespace,
2948 -> Option<PathResolution> {
2949 let span = path.span;
2950 let segments = &path.segments[..path.segments.len() - path_depth];
2952 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2955 let def = self.resolve_crate_relative_path(span, segments, namespace);
2956 return def.map(mk_res);
2959 // Try to find a path to an item in a module.
2960 let last_ident = segments.last().unwrap().identifier;
2961 if segments.len() <= 1 {
2962 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2963 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2965 PathResolution::new(def, LastMod(AllPublic), path_depth)
2969 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2970 let def = self.resolve_module_relative_path(span, segments, namespace);
2971 match (def, unqualified_def) {
2972 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2974 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2977 "unnecessary qualification".to_string());
2985 // Resolve a single identifier
2986 fn resolve_identifier(&mut self,
2987 identifier: hir::Ident,
2988 namespace: Namespace,
2991 -> Option<LocalDef> {
2992 // First, check to see whether the name is a primitive type.
2993 if namespace == TypeNS {
2994 if let Some(&prim_ty) = self.primitive_type_table
2996 .get(&identifier.unhygienic_name) {
2997 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
3002 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
3007 let name = identifier.unhygienic_name;
3008 self.resolve_item_by_name_in_lexical_scope(name, namespace, record_used)
3009 .map(LocalDef::from_def)
3012 // Resolve a local definition, potentially adjusting for closures.
3013 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
3014 let ribs = match local_def.ribs {
3015 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
3016 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
3019 let mut def = local_def.def;
3022 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
3024 DefLocal(_, node_id) => {
3028 // Nothing to do. Continue.
3030 ClosureRibKind(function_id) => {
3032 let node_def_id = self.ast_map.local_def_id(node_id);
3034 let seen = self.freevars_seen
3036 .or_insert_with(|| NodeMap());
3037 if let Some(&index) = seen.get(&node_id) {
3038 def = DefUpvar(node_def_id, node_id, index, function_id);
3041 let vec = self.freevars
3043 .or_insert_with(|| vec![]);
3044 let depth = vec.len();
3050 def = DefUpvar(node_def_id, node_id, depth, function_id);
3051 seen.insert(node_id, depth);
3053 ItemRibKind | MethodRibKind => {
3054 // This was an attempt to access an upvar inside a
3055 // named function item. This is not allowed, so we
3059 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3062 ConstantItemRibKind => {
3063 // Still doesn't deal with upvars
3066 ResolutionError::AttemptToUseNonConstantValueInConstant);
3072 DefTyParam(..) | DefSelfTy(..) => {
3075 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3076 // Nothing to do. Continue.
3079 // This was an attempt to use a type parameter outside
3084 ResolutionError::TypeParametersFromOuterFunction);
3087 ConstantItemRibKind => {
3089 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3100 // resolve a "module-relative" path, e.g. a::b::c
3101 fn resolve_module_relative_path(&mut self,
3103 segments: &[hir::PathSegment],
3104 namespace: Namespace)
3105 -> Option<(Def, LastPrivate)> {
3106 let module_path = segments.split_last()
3110 .map(|ps| ps.identifier.name)
3111 .collect::<Vec<_>>();
3113 let containing_module;
3115 let current_module = self.current_module.clone();
3116 match self.resolve_module_path(current_module,
3122 let (span, msg) = match err {
3123 Some((span, msg)) => (span, msg),
3125 let msg = format!("Use of undeclared type or module `{}`",
3126 names_to_string(&module_path));
3131 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3134 Indeterminate => panic!("indeterminate unexpected"),
3135 Success((resulting_module, resulting_last_private)) => {
3136 containing_module = resulting_module;
3137 last_private = resulting_last_private;
3141 let name = segments.last().unwrap().identifier.name;
3142 let def = match self.resolve_name_in_module(containing_module.clone(),
3145 NameSearchType::PathSearch,
3147 Success((Target { binding, .. }, _)) => {
3148 let (def, lp) = binding.def_and_lp();
3149 (def, last_private.or(lp))
3153 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3154 self.used_crates.insert(kid);
3159 /// Invariant: This must be called only during main resolution, not during
3160 /// import resolution.
3161 fn resolve_crate_relative_path(&mut self,
3163 segments: &[hir::PathSegment],
3164 namespace: Namespace)
3165 -> Option<(Def, LastPrivate)> {
3166 let module_path = segments.split_last()
3170 .map(|ps| ps.identifier.name)
3171 .collect::<Vec<_>>();
3173 let root_module = self.graph_root.clone();
3175 let containing_module;
3177 match self.resolve_module_path_from_root(root_module,
3182 LastMod(AllPublic)) {
3184 let (span, msg) = match err {
3185 Some((span, msg)) => (span, msg),
3187 let msg = format!("Use of undeclared module `::{}`",
3188 names_to_string(&module_path[..]));
3193 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3198 panic!("indeterminate unexpected");
3201 Success((resulting_module, resulting_last_private)) => {
3202 containing_module = resulting_module;
3203 last_private = resulting_last_private;
3207 let name = segments.last().unwrap().identifier.name;
3208 match self.resolve_name_in_module(containing_module,
3211 NameSearchType::PathSearch,
3213 Success((Target { binding, .. }, _)) => {
3214 let (def, lp) = binding.def_and_lp();
3215 Some((def, last_private.or(lp)))
3221 fn resolve_identifier_in_local_ribs(&mut self,
3223 namespace: Namespace)
3224 -> Option<LocalDef> {
3225 // Check the local set of ribs.
3226 let (name, ribs) = match namespace {
3227 ValueNS => (ident.name, &self.value_ribs),
3228 TypeNS => (ident.unhygienic_name, &self.type_ribs),
3231 for (i, rib) in ribs.iter().enumerate().rev() {
3232 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3235 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3239 return Some(LocalDef {
3240 ribs: Some((namespace, i)),
3245 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3257 fn resolve_item_by_name_in_lexical_scope(&mut self,
3259 namespace: Namespace,
3263 let module = self.current_module.clone();
3264 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
3265 Success((target, _)) => {
3266 match target.binding.def() {
3268 // This can happen if we were looking for a type and
3269 // found a module instead. Modules don't have defs.
3270 debug!("(resolving item path by identifier in lexical scope) failed to \
3271 resolve {} after success...",
3276 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3278 // This lookup is "all public" because it only searched
3279 // for one identifier in the current module (couldn't
3280 // have passed through reexports or anything like that.
3286 panic!("unexpected indeterminate result");
3289 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3292 if let Some((span, msg)) = err {
3293 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3301 fn with_no_errors<T, F>(&mut self, f: F) -> T
3302 where F: FnOnce(&mut Resolver) -> T
3304 self.emit_errors = false;
3306 self.emit_errors = true;
3310 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3311 fn extract_path_and_node_id(t: &Ty,
3312 allow: FallbackChecks)
3313 -> Option<(Path, NodeId, FallbackChecks)> {
3315 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3316 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3317 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3318 // This doesn't handle the remaining `Ty` variants as they are not
3319 // that commonly the self_type, it might be interesting to provide
3320 // support for those in future.
3325 fn get_module(this: &mut Resolver,
3327 name_path: &[ast::Name])
3328 -> Option<Rc<Module>> {
3329 let root = this.current_module.clone();
3330 let last_name = name_path.last().unwrap();
3332 if name_path.len() == 1 {
3333 match this.primitive_type_table.primitive_types.get(last_name) {
3336 match this.current_module.children.borrow().get(last_name) {
3337 Some(child) => child.type_ns.module(),
3343 match this.resolve_module_path(root,
3348 Success((module, _)) => Some(module),
3354 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3355 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3356 let sig = match this.ast_map.get(node_id) {
3357 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3358 hir::MethodTraitItem(ref sig, _) => sig,
3361 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3362 hir::ImplItemKind::Method(ref sig, _) => sig,
3367 sig.explicit_self.node == hir::SelfStatic
3369 this.session.cstore.is_static_method(did)
3373 let (path, node_id, allowed) = match self.current_self_type {
3374 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3376 None => return NoSuggestion,
3378 None => return NoSuggestion,
3381 if allowed == Everything {
3382 // Look for a field with the same name in the current self_type.
3383 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3384 Some(DefTy(did, _)) |
3385 Some(DefStruct(did)) |
3386 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3389 if fields.iter().any(|&field_name| name == field_name) {
3394 _ => {} // Self type didn't resolve properly
3398 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3400 // Look for a method in the current self type's impl module.
3401 if let Some(module) = get_module(self, path.span, &name_path) {
3402 if let Some(binding) = module.children.borrow().get(&name) {
3403 if let Some(DefMethod(did)) = binding.value_ns.def() {
3404 if is_static_method(self, did) {
3405 return StaticMethod(path_names_to_string(&path, 0));
3407 if self.current_trait_ref.is_some() {
3409 } else if allowed == Everything {
3416 // Look for a method in the current trait.
3417 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3418 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3419 if is_static_method(self, did) {
3420 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3430 fn find_best_match_for_name(&mut self, name: &str) -> SuggestionType {
3431 let mut maybes: Vec<token::InternedString> = Vec::new();
3432 let mut values: Vec<usize> = Vec::new();
3434 if let Some(macro_name) = self.session.available_macros
3435 .borrow().iter().find(|n| n.as_str() == name) {
3436 return SuggestionType::Macro(format!("{}!", macro_name));
3439 for rib in self.value_ribs.iter().rev() {
3440 for (&k, _) in &rib.bindings {
3441 maybes.push(k.as_str());
3442 values.push(usize::MAX);
3446 let mut smallest = 0;
3447 for (i, other) in maybes.iter().enumerate() {
3448 values[i] = lev_distance(name, &other);
3450 if values[i] <= values[smallest] {
3455 let max_distance = max_suggestion_distance(name);
3456 if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
3458 SuggestionType::Function(maybes[smallest].to_string())
3461 SuggestionType::NotFound
3465 fn resolve_expr(&mut self, expr: &Expr) {
3466 // First, record candidate traits for this expression if it could
3467 // result in the invocation of a method call.
3469 self.record_candidate_traits_for_expr_if_necessary(expr);
3471 // Next, resolve the node.
3473 ExprPath(ref maybe_qself, ref path) => {
3474 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3475 maybe_qself.as_ref(),
3479 // `<T>::a::b::c` is resolved by typeck alone.
3480 TypecheckRequired => {
3481 let method_name = path.segments.last().unwrap().identifier.name;
3482 let traits = self.get_traits_containing_item(method_name);
3483 self.trait_map.insert(expr.id, traits);
3484 intravisit::walk_expr(self, expr);
3487 ResolveAttempt(resolution) => resolution,
3490 // This is a local path in the value namespace. Walk through
3491 // scopes looking for it.
3492 if let Some(path_res) = resolution {
3493 // Check if struct variant
3494 if let DefVariant(_, _, true) = path_res.base_def {
3495 let path_name = path_names_to_string(path, 0);
3499 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3501 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3503 if self.emit_errors {
3504 self.session.fileline_help(expr.span, &msg);
3506 self.session.span_help(expr.span, &msg);
3508 self.record_def(expr.id, err_path_resolution());
3510 // Write the result into the def map.
3511 debug!("(resolving expr) resolved `{}`",
3512 path_names_to_string(path, 0));
3514 // Partial resolutions will need the set of traits in scope,
3515 // so they can be completed during typeck.
3516 if path_res.depth != 0 {
3517 let method_name = path.segments.last().unwrap().identifier.name;
3518 let traits = self.get_traits_containing_item(method_name);
3519 self.trait_map.insert(expr.id, traits);
3522 self.record_def(expr.id, path_res);
3525 // Be helpful if the name refers to a struct
3526 // (The pattern matching def_tys where the id is in self.structs
3527 // matches on regular structs while excluding tuple- and enum-like
3528 // structs, which wouldn't result in this error.)
3529 let path_name = path_names_to_string(path, 0);
3530 let type_res = self.with_no_errors(|this| {
3531 this.resolve_path(expr.id, path, 0, TypeNS, false)
3534 self.record_def(expr.id, err_path_resolution());
3535 match type_res.map(|r| r.base_def) {
3536 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3540 ResolutionError::StructVariantUsedAsFunction(
3544 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3546 if self.emit_errors {
3547 self.session.fileline_help(expr.span, &msg);
3549 self.session.span_help(expr.span, &msg);
3553 // Keep reporting some errors even if they're ignored above.
3554 self.resolve_path(expr.id, path, 0, ValueNS, true);
3556 let mut method_scope = false;
3557 self.value_ribs.iter().rev().all(|rib| {
3558 method_scope = match rib.kind {
3559 MethodRibKind => true,
3560 ItemRibKind | ConstantItemRibKind => false,
3561 _ => return true, // Keep advancing
3563 false // Stop advancing
3566 if method_scope && special_names::self_.as_str() == &path_name[..] {
3569 ResolutionError::SelfNotAvailableInStaticMethod);
3571 let last_name = path.segments.last().unwrap().identifier.name;
3572 let mut msg = match self.find_fallback_in_self_type(last_name) {
3574 // limit search to 5 to reduce the number
3575 // of stupid suggestions
3576 match self.find_best_match_for_name(&path_name) {
3577 SuggestionType::Macro(s) => {
3578 format!("the macro `{}`", s)
3580 SuggestionType::Function(s) => format!("`{}`", s),
3581 SuggestionType::NotFound => "".to_string(),
3584 Field => format!("`self.{}`", path_name),
3586 TraitItem => format!("to call `self.{}`", path_name),
3587 TraitMethod(path_str) |
3588 StaticMethod(path_str) =>
3589 format!("to call `{}::{}`", path_str, path_name),
3592 let mut context = UnresolvedNameContext::Other;
3593 if !msg.is_empty() {
3594 msg = format!(". Did you mean {}?", msg);
3596 // we check if this a module and if so, we display a help
3598 let name_path = path.segments.iter()
3599 .map(|seg| seg.identifier.name)
3600 .collect::<Vec<_>>();
3601 let current_module = self.current_module.clone();
3603 match self.resolve_module_path(current_module,
3609 context = UnresolvedNameContext::PathIsMod(expr.id);
3617 ResolutionError::UnresolvedName(
3618 &*path_name, &*msg, context));
3624 intravisit::walk_expr(self, expr);
3627 ExprStruct(ref path, _, _) => {
3628 // Resolve the path to the structure it goes to. We don't
3629 // check to ensure that the path is actually a structure; that
3630 // is checked later during typeck.
3631 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3632 Some(definition) => self.record_def(expr.id, definition),
3634 debug!("(resolving expression) didn't find struct def",);
3638 ResolutionError::DoesNotNameAStruct(
3639 &*path_names_to_string(path, 0))
3641 self.record_def(expr.id, err_path_resolution());
3645 intravisit::walk_expr(self, expr);
3648 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3649 self.with_label_rib(|this| {
3650 let def_like = DlDef(DefLabel(expr.id));
3653 let rib = this.label_ribs.last_mut().unwrap();
3654 rib.bindings.insert(label.name, def_like);
3657 intravisit::walk_expr(this, expr);
3661 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3662 match self.search_label(label.node.name) {
3664 self.record_def(expr.id, err_path_resolution());
3667 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3669 Some(DlDef(def @ DefLabel(_))) => {
3670 // Since this def is a label, it is never read.
3671 self.record_def(expr.id,
3674 last_private: LastMod(AllPublic),
3679 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3685 intravisit::walk_expr(self, expr);
3690 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3692 ExprField(_, name) => {
3693 // FIXME(#6890): Even though you can't treat a method like a
3694 // field, we need to add any trait methods we find that match
3695 // the field name so that we can do some nice error reporting
3696 // later on in typeck.
3697 let traits = self.get_traits_containing_item(name.node);
3698 self.trait_map.insert(expr.id, traits);
3700 ExprMethodCall(name, _, _) => {
3701 debug!("(recording candidate traits for expr) recording traits for {}",
3703 let traits = self.get_traits_containing_item(name.node);
3704 self.trait_map.insert(expr.id, traits);
3712 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3713 debug!("(getting traits containing item) looking for '{}'", name);
3715 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3716 debug!("(adding trait info) found trait {:?} for method '{}'",
3719 found_traits.push(trait_def_id);
3722 let mut found_traits = Vec::new();
3723 let mut search_module = self.current_module.clone();
3725 // Look for the current trait.
3726 match self.current_trait_ref {
3727 Some((trait_def_id, _)) => {
3728 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3729 add_trait_info(&mut found_traits, trait_def_id, name);
3732 None => {} // Nothing to do.
3735 // Look for trait children.
3736 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3739 for (_, child_names) in search_module.children.borrow().iter() {
3740 let def = match child_names.type_ns.def() {
3744 let trait_def_id = match def {
3745 DefTrait(trait_def_id) => trait_def_id,
3748 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3749 add_trait_info(&mut found_traits, trait_def_id, name);
3754 // Look for imports.
3755 for (_, import) in search_module.import_resolutions.borrow().iter() {
3756 let target = match import.type_ns.target {
3758 Some(ref target) => target,
3760 let did = match target.binding.def() {
3761 Some(DefTrait(trait_def_id)) => trait_def_id,
3762 Some(..) | None => continue,
3764 if self.trait_item_map.contains_key(&(name, did)) {
3765 add_trait_info(&mut found_traits, did, name);
3766 let id = import.type_ns.id;
3767 self.used_imports.insert((id, TypeNS));
3768 let trait_name = self.get_trait_name(did);
3769 self.record_import_use(id, trait_name);
3770 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3771 self.used_crates.insert(kid);
3776 match search_module.parent_link.clone() {
3777 NoParentLink | ModuleParentLink(..) => break,
3778 BlockParentLink(parent_module, _) => {
3779 search_module = parent_module.upgrade().unwrap();
3787 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3788 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3789 assert!(match resolution.last_private {
3790 LastImport{..} => false,
3793 "Import should only be used for `use` directives");
3795 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3796 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3797 self.session.span_bug(span,
3798 &format!("path resolved multiple times ({:?} before, {:?} now)",
3804 fn enforce_default_binding_mode(&mut self,
3806 pat_binding_mode: BindingMode,
3808 match pat_binding_mode {
3809 BindByValue(_) => {}
3813 ResolutionError::CannotUseRefBindingModeWith(descr));
3821 // Diagnostics are not particularly efficient, because they're rarely
3825 #[allow(dead_code)] // useful for debugging
3826 fn dump_module(&mut self, module_: Rc<Module>) {
3827 debug!("Dump of module `{}`:", module_to_string(&*module_));
3829 debug!("Children:");
3830 build_reduced_graph::populate_module_if_necessary(self, &module_);
3831 for (&name, _) in module_.children.borrow().iter() {
3832 debug!("* {}", name);
3835 debug!("Import resolutions:");
3836 let import_resolutions = module_.import_resolutions.borrow();
3837 for (&name, import_resolution) in import_resolutions.iter() {
3839 match import_resolution.value_ns.target {
3841 value_repr = "".to_string();
3844 value_repr = " value:?".to_string();
3850 match import_resolution.type_ns.target {
3852 type_repr = "".to_string();
3855 type_repr = " type:?".to_string();
3860 debug!("* {}:{}{}", name, value_repr, type_repr);
3866 fn names_to_string(names: &[Name]) -> String {
3867 let mut first = true;
3868 let mut result = String::new();
3873 result.push_str("::")
3875 result.push_str(&name.as_str());
3880 fn path_names_to_string(path: &Path, depth: usize) -> String {
3881 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3883 .map(|seg| seg.identifier.name)
3885 names_to_string(&names[..])
3888 /// A somewhat inefficient routine to obtain the name of a module.
3889 fn module_to_string(module: &Module) -> String {
3890 let mut names = Vec::new();
3892 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3893 match module.parent_link {
3895 ModuleParentLink(ref module, name) => {
3897 collect_mod(names, &*module.upgrade().unwrap());
3899 BlockParentLink(ref module, _) => {
3900 // danger, shouldn't be ident?
3901 names.push(special_idents::opaque.name);
3902 collect_mod(names, &*module.upgrade().unwrap());
3906 collect_mod(&mut names, module);
3908 if names.is_empty() {
3909 return "???".to_string();
3911 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3914 fn err_path_resolution() -> PathResolution {
3917 last_private: LastMod(AllPublic),
3923 pub struct CrateMap {
3924 pub def_map: RefCell<DefMap>,
3925 pub freevars: FreevarMap,
3926 pub export_map: ExportMap,
3927 pub trait_map: TraitMap,
3928 pub external_exports: ExternalExports,
3929 pub glob_map: Option<GlobMap>,
3932 #[derive(PartialEq,Copy, Clone)]
3933 pub enum MakeGlobMap {
3938 /// Entry point to crate resolution.
3939 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3940 ast_map: &'a hir_map::Map<'tcx>,
3941 make_glob_map: MakeGlobMap)
3943 let krate = ast_map.krate();
3944 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3946 resolver.resolve_crate(krate);
3948 check_unused::check_crate(&mut resolver, krate);
3951 def_map: resolver.def_map,
3952 freevars: resolver.freevars,
3953 export_map: resolver.export_map,
3954 trait_map: resolver.trait_map,
3955 external_exports: resolver.external_exports,
3956 glob_map: if resolver.make_glob_map {
3957 Some(resolver.glob_map)
3964 /// Builds a name resolution walker to be used within this module,
3965 /// or used externally, with an optional callback function.
3967 /// The callback takes a &mut bool which allows callbacks to end a
3968 /// walk when set to true, passing through the rest of the walk, while
3969 /// preserving the ribs + current module. This allows resolve_path
3970 /// calls to be made with the correct scope info. The node in the
3971 /// callback corresponds to the current node in the walk.
3972 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3973 ast_map: &'a hir_map::Map<'tcx>,
3975 make_glob_map: MakeGlobMap,
3976 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3977 -> Resolver<'a, 'tcx> {
3978 let mut resolver = Resolver::new(session, ast_map, make_glob_map);
3980 resolver.callback = callback;
3982 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3983 session.abort_if_errors();
3985 resolve_imports::resolve_imports(&mut resolver);
3986 session.abort_if_errors();
3988 record_exports::record(&mut resolver);
3989 session.abort_if_errors();
3994 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }