1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
18 #![cfg_attr(not(stage0), deny(warnings))]
20 #![feature(associated_consts)]
21 #![feature(borrow_state)]
22 #![feature(rustc_diagnostic_macros)]
23 #![feature(rustc_private)]
24 #![feature(staged_api)]
33 extern crate rustc_bitflags;
34 extern crate rustc_front;
37 use self::PatternBindingMode::*;
38 use self::Namespace::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::BareIdentifierPatternResolution::*;
47 use self::ParentLink::*;
48 use self::FallbackChecks::*;
50 use rustc::front::map as hir_map;
51 use rustc::session::Session;
53 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
54 use rustc::middle::def::*;
55 use rustc::middle::def_id::DefId;
56 use rustc::middle::pat_util::pat_bindings;
57 use rustc::middle::privacy::*;
58 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
60 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
63 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
64 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
65 use syntax::attr::AttrMetaMethods;
66 use syntax::codemap::{self, Span, Pos};
67 use syntax::errors::DiagnosticBuilder;
68 use syntax::parse::token::{self, special_names, special_idents};
69 use syntax::util::lev_distance::find_best_match_for_name;
71 use rustc_front::intravisit::{self, FnKind, Visitor};
73 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
74 use rustc_front::hir::Crate;
75 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
76 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
77 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
78 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
79 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
80 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
81 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
82 use rustc_front::hir::Local;
83 use rustc_front::hir::{Pat, 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::{hash_map, HashMap, HashSet};
90 use std::cell::{Cell, RefCell};
92 use std::mem::replace;
94 use resolve_imports::{Target, ImportDirective, ImportResolution};
95 use resolve_imports::Shadowable;
97 // NB: This module needs to be declared first so diagnostics are
98 // registered before they are used.
102 mod build_reduced_graph;
105 // Perform the callback, not walking deeper if the return is true
106 macro_rules! execute_callback {
107 ($node: expr, $walker: expr) => (
108 if let Some(ref callback) = $walker.callback {
109 if callback($node, &mut $walker.resolved) {
116 enum SuggestionType {
118 Function(token::InternedString),
122 pub enum ResolutionError<'a> {
123 /// error E0401: can't use type parameters from outer function
124 TypeParametersFromOuterFunction,
125 /// error E0402: cannot use an outer type parameter in this context
126 OuterTypeParameterContext,
127 /// error E0403: the name is already used for a type parameter in this type parameter list
128 NameAlreadyUsedInTypeParameterList(Name),
129 /// error E0404: is not a trait
130 IsNotATrait(&'a str),
131 /// error E0405: use of undeclared trait name
132 UndeclaredTraitName(&'a str),
133 /// error E0406: undeclared associated type
134 UndeclaredAssociatedType,
135 /// error E0407: method is not a member of trait
136 MethodNotMemberOfTrait(Name, &'a str),
137 /// error E0437: type is not a member of trait
138 TypeNotMemberOfTrait(Name, &'a str),
139 /// error E0438: const is not a member of trait
140 ConstNotMemberOfTrait(Name, &'a str),
141 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
142 VariableNotBoundInPattern(Name, usize),
143 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
144 VariableBoundWithDifferentMode(Name, usize),
145 /// error E0410: variable from pattern is not bound in pattern #1
146 VariableNotBoundInParentPattern(Name, usize),
147 /// error E0411: use of `Self` outside of an impl or trait
148 SelfUsedOutsideImplOrTrait,
149 /// error E0412: use of undeclared
150 UseOfUndeclared(&'a str, &'a str),
151 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
152 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
153 /// error E0414: only irrefutable patterns allowed here
154 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
155 /// error E0415: identifier is bound more than once in this parameter list
156 IdentifierBoundMoreThanOnceInParameterList(&'a str),
157 /// error E0416: identifier is bound more than once in the same pattern
158 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
159 /// error E0417: static variables cannot be referenced in a pattern
160 StaticVariableReference,
161 /// error E0418: is not an enum variant, struct or const
162 NotAnEnumVariantStructOrConst(&'a str),
163 /// error E0419: unresolved enum variant, struct or const
164 UnresolvedEnumVariantStructOrConst(&'a str),
165 /// error E0420: is not an associated const
166 NotAnAssociatedConst(&'a str),
167 /// error E0421: unresolved associated const
168 UnresolvedAssociatedConst(&'a str),
169 /// error E0422: does not name a struct
170 DoesNotNameAStruct(&'a str),
171 /// error E0423: is a struct variant name, but this expression uses it like a function name
172 StructVariantUsedAsFunction(&'a str),
173 /// error E0424: `self` is not available in a static method
174 SelfNotAvailableInStaticMethod,
175 /// error E0425: unresolved name
176 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
177 /// error E0426: use of undeclared label
178 UndeclaredLabel(&'a str),
179 /// error E0427: cannot use `ref` binding mode with ...
180 CannotUseRefBindingModeWith(&'a str),
181 /// error E0428: duplicate definition
182 DuplicateDefinition(&'a str, Name),
183 /// error E0429: `self` imports are only allowed within a { } list
184 SelfImportsOnlyAllowedWithin,
185 /// error E0430: `self` import can only appear once in the list
186 SelfImportCanOnlyAppearOnceInTheList,
187 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
188 SelfImportOnlyInImportListWithNonEmptyPrefix,
189 /// error E0432: unresolved import
190 UnresolvedImport(Option<(&'a str, &'a str)>),
191 /// error E0433: failed to resolve
192 FailedToResolve(&'a str),
193 /// error E0434: can't capture dynamic environment in a fn item
194 CannotCaptureDynamicEnvironmentInFnItem,
195 /// error E0435: attempt to use a non-constant value in a constant
196 AttemptToUseNonConstantValueInConstant,
199 /// Context of where `ResolutionError::UnresolvedName` arose.
200 #[derive(Clone, PartialEq, Eq, Debug)]
201 pub enum UnresolvedNameContext {
202 /// `PathIsMod(id)` indicates that a given path, used in
203 /// expression context, actually resolved to a module rather than
204 /// a value. The `id` attached to the variant is the node id of
205 /// the erroneous path expression.
206 PathIsMod(ast::NodeId),
208 /// `Other` means we have no extra information about the context
209 /// of the unresolved name error. (Maybe we could eliminate all
210 /// such cases; but for now, this is an information-free default.)
214 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
215 span: syntax::codemap::Span,
216 resolution_error: ResolutionError<'b>) {
217 resolve_struct_error(resolver, span, resolution_error).emit();
220 fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
221 span: syntax::codemap::Span,
222 resolution_error: ResolutionError<'b>)
223 -> DiagnosticBuilder<'a> {
224 if !resolver.emit_errors {
225 return resolver.session.diagnostic().struct_dummy();
228 match resolution_error {
229 ResolutionError::TypeParametersFromOuterFunction => {
230 struct_span_err!(resolver.session,
233 "can't use type parameters from outer function; try using a local \
234 type parameter instead")
236 ResolutionError::OuterTypeParameterContext => {
237 struct_span_err!(resolver.session,
240 "cannot use an outer type parameter in this context")
242 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
243 struct_span_err!(resolver.session,
246 "the name `{}` is already used for a type parameter in this type \
250 ResolutionError::IsNotATrait(name) => {
251 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
253 ResolutionError::UndeclaredTraitName(name) => {
254 struct_span_err!(resolver.session,
257 "use of undeclared trait name `{}`",
260 ResolutionError::UndeclaredAssociatedType => {
261 struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
263 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
264 struct_span_err!(resolver.session,
267 "method `{}` is not a member of trait `{}`",
271 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
272 struct_span_err!(resolver.session,
275 "type `{}` is not a member of trait `{}`",
279 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
280 struct_span_err!(resolver.session,
283 "const `{}` is not a member of trait `{}`",
287 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
288 struct_span_err!(resolver.session,
291 "variable `{}` from pattern #1 is not bound in pattern #{}",
295 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
296 struct_span_err!(resolver.session,
299 "variable `{}` is bound with different mode in pattern #{} than in \
304 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
305 struct_span_err!(resolver.session,
308 "variable `{}` from pattern #{} is not bound in pattern #1",
312 ResolutionError::SelfUsedOutsideImplOrTrait => {
313 struct_span_err!(resolver.session,
316 "use of `Self` outside of an impl or trait")
318 ResolutionError::UseOfUndeclared(kind, name) => {
319 struct_span_err!(resolver.session,
322 "use of undeclared {} `{}`",
326 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
327 struct_span_err!(resolver.session,
330 "declaration of `{}` shadows an enum variant \
331 or unit-like struct in scope",
334 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
335 let mut err = struct_span_err!(resolver.session,
338 "only irrefutable patterns allowed here");
340 "there already is a constant in scope sharing the same \
341 name as this pattern");
342 if let Some(sp) = resolver.ast_map.span_if_local(did) {
343 err.span_note(sp, "constant defined here");
345 if let Some(directive) = resolver.current_module
348 .get(&(name, ValueNS)) {
349 let item = resolver.ast_map.expect_item(directive.id);
350 err.span_note(item.span, "constant imported here");
354 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
355 struct_span_err!(resolver.session,
358 "identifier `{}` is bound more than once in this parameter list",
361 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
362 struct_span_err!(resolver.session,
365 "identifier `{}` is bound more than once in the same pattern",
368 ResolutionError::StaticVariableReference => {
369 struct_span_err!(resolver.session,
372 "static variables cannot be referenced in a pattern, use a \
375 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
376 struct_span_err!(resolver.session,
379 "`{}` is not an enum variant, struct or const",
382 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
383 struct_span_err!(resolver.session,
386 "unresolved enum variant, struct or const `{}`",
389 ResolutionError::NotAnAssociatedConst(name) => {
390 struct_span_err!(resolver.session,
393 "`{}` is not an associated const",
396 ResolutionError::UnresolvedAssociatedConst(name) => {
397 struct_span_err!(resolver.session,
400 "unresolved associated const `{}`",
403 ResolutionError::DoesNotNameAStruct(name) => {
404 struct_span_err!(resolver.session,
407 "`{}` does not name a structure",
410 ResolutionError::StructVariantUsedAsFunction(path_name) => {
411 struct_span_err!(resolver.session,
414 "`{}` is the name of a struct or struct variant, but this expression \
415 uses it like a function name",
418 ResolutionError::SelfNotAvailableInStaticMethod => {
419 struct_span_err!(resolver.session,
422 "`self` is not available in a static method. Maybe a `self` \
423 argument is missing?")
425 ResolutionError::UnresolvedName(path, msg, context) => {
426 let mut err = struct_span_err!(resolver.session,
429 "unresolved name `{}`{}",
434 UnresolvedNameContext::Other => { } // no help available
435 UnresolvedNameContext::PathIsMod(id) => {
436 let mut help_msg = String::new();
437 let parent_id = resolver.ast_map.get_parent_node(id);
438 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
440 ExprField(_, ident) => {
441 help_msg = format!("To reference an item from the \
442 `{module}` module, use \
443 `{module}::{ident}`",
447 ExprMethodCall(ident, _, _) => {
448 help_msg = format!("To call a function from the \
449 `{module}` module, use \
450 `{module}::{ident}(..)`",
455 help_msg = format!("No function corresponds to `{module}(..)`",
458 _ => { } // no help available
461 help_msg = format!("Module `{module}` cannot be the value of an expression",
465 if !help_msg.is_empty() {
466 err.fileline_help(span, &help_msg);
472 ResolutionError::UndeclaredLabel(name) => {
473 struct_span_err!(resolver.session,
476 "use of undeclared label `{}`",
479 ResolutionError::CannotUseRefBindingModeWith(descr) => {
480 struct_span_err!(resolver.session,
483 "cannot use `ref` binding mode with {}",
486 ResolutionError::DuplicateDefinition(namespace, name) => {
487 struct_span_err!(resolver.session,
490 "duplicate definition of {} `{}`",
494 ResolutionError::SelfImportsOnlyAllowedWithin => {
495 struct_span_err!(resolver.session,
499 "`self` imports are only allowed within a { } list")
501 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
502 struct_span_err!(resolver.session,
505 "`self` import can only appear once in the list")
507 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
508 struct_span_err!(resolver.session,
511 "`self` import can only appear in an import list with a \
514 ResolutionError::UnresolvedImport(name) => {
515 let msg = match name {
516 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
517 None => "unresolved import".to_owned(),
519 struct_span_err!(resolver.session, span, E0432, "{}", msg)
521 ResolutionError::FailedToResolve(msg) => {
522 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
524 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
525 struct_span_err!(resolver.session,
529 "can't capture dynamic environment in a fn item; use the || { ... } \
530 closure form instead")
532 ResolutionError::AttemptToUseNonConstantValueInConstant => {
533 struct_span_err!(resolver.session,
536 "attempt to use a non-constant value in a constant")
541 #[derive(Copy, Clone)]
544 binding_mode: BindingMode,
547 // Map from the name in a pattern to its binding mode.
548 type BindingMap = HashMap<Name, BindingInfo>;
550 #[derive(Copy, Clone, PartialEq)]
551 enum PatternBindingMode {
553 LocalIrrefutableMode,
554 ArgumentIrrefutableMode,
557 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
563 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
564 fn visit_nested_item(&mut self, item: hir::ItemId) {
565 self.visit_item(self.ast_map.expect_item(item.id))
567 fn visit_item(&mut self, item: &Item) {
568 execute_callback!(hir_map::Node::NodeItem(item), self);
569 self.resolve_item(item);
571 fn visit_arm(&mut self, arm: &Arm) {
572 self.resolve_arm(arm);
574 fn visit_block(&mut self, block: &Block) {
575 execute_callback!(hir_map::Node::NodeBlock(block), self);
576 self.resolve_block(block);
578 fn visit_expr(&mut self, expr: &Expr) {
579 execute_callback!(hir_map::Node::NodeExpr(expr), self);
580 self.resolve_expr(expr);
582 fn visit_local(&mut self, local: &Local) {
583 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
584 self.resolve_local(local);
586 fn visit_ty(&mut self, ty: &Ty) {
587 self.resolve_type(ty);
589 fn visit_generics(&mut self, generics: &Generics) {
590 self.resolve_generics(generics);
592 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
593 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
594 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
596 // error already reported
597 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
600 intravisit::walk_poly_trait_ref(self, tref, m);
602 fn visit_variant(&mut self,
603 variant: &hir::Variant,
605 item_id: ast::NodeId) {
606 execute_callback!(hir_map::Node::NodeVariant(variant), self);
607 if let Some(ref dis_expr) = variant.node.disr_expr {
608 // resolve the discriminator expr as a constant
609 self.with_constant_rib(|this| {
610 this.visit_expr(dis_expr);
614 // `intravisit::walk_variant` without the discriminant expression.
615 self.visit_variant_data(&variant.node.data,
621 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
622 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
623 let type_parameters = match foreign_item.node {
624 ForeignItemFn(_, ref generics) => {
625 HasTypeParameters(generics, FnSpace, ItemRibKind)
627 ForeignItemStatic(..) => NoTypeParameters,
629 self.with_type_parameter_rib(type_parameters, |this| {
630 intravisit::walk_foreign_item(this, foreign_item);
633 fn visit_fn(&mut self,
634 function_kind: FnKind<'v>,
635 declaration: &'v FnDecl,
639 let rib_kind = match function_kind {
640 FnKind::ItemFn(_, generics, _, _, _, _) => {
641 self.visit_generics(generics);
644 FnKind::Method(_, sig, _) => {
645 self.visit_generics(&sig.generics);
646 self.visit_explicit_self(&sig.explicit_self);
649 FnKind::Closure => ClosureRibKind(node_id),
651 self.resolve_function(rib_kind, declaration, block);
655 type ErrorMessage = Option<(Span, String)>;
657 #[derive(Clone, PartialEq, Eq)]
658 enum ResolveResult<T> {
659 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
660 Indeterminate, // Couldn't determine due to unresolved globs.
661 Success(T), // Successfully resolved the import.
664 impl<T> ResolveResult<T> {
665 fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
667 Failed(msg) => Failed(msg),
668 Indeterminate => Indeterminate,
674 enum FallbackSuggestion {
679 StaticMethod(String),
683 #[derive(Copy, Clone)]
684 enum TypeParameters<'tcx, 'a> {
686 HasTypeParameters(// Type parameters.
689 // Identifies the things that these parameters
690 // were declared on (type, fn, etc)
693 // The kind of the rib used for type parameters.
697 // The rib kind controls the translation of local
698 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
699 #[derive(Copy, Clone, Debug)]
701 // No translation needs to be applied.
704 // We passed through a closure scope at the given node ID.
705 // Translate upvars as appropriate.
706 ClosureRibKind(NodeId /* func id */),
708 // We passed through an impl or trait and are now in one of its
709 // methods. Allow references to ty params that impl or trait
710 // binds. Disallow any other upvars (including other ty params that are
714 // We passed through an item scope. Disallow upvars.
717 // We're in a constant item. Can't refer to dynamic stuff.
720 // We passed through an anonymous module.
721 AnonymousModuleRibKind(Module<'a>),
724 #[derive(Copy, Clone)]
725 enum UseLexicalScopeFlag {
730 enum ModulePrefixResult<'a> {
732 PrefixFound(Module<'a>, usize),
735 #[derive(Copy, Clone)]
736 enum AssocItemResolveResult {
737 /// Syntax such as `<T>::item`, which can't be resolved until type
740 /// We should have been able to resolve the associated item.
741 ResolveAttempt(Option<PathResolution>),
744 #[derive(Copy, Clone)]
745 enum BareIdentifierPatternResolution {
746 FoundStructOrEnumVariant(Def, LastPrivate),
747 FoundConst(Def, LastPrivate, Name),
748 BareIdentifierPatternUnresolved,
754 bindings: HashMap<Name, DefLike>,
759 fn new(kind: RibKind<'a>) -> Rib<'a> {
761 bindings: HashMap::new(),
767 /// A definition along with the index of the rib it was found on
769 ribs: Option<(Namespace, usize)>,
774 fn from_def(def: Def) -> Self {
782 /// The link from a module up to its nearest parent node.
783 #[derive(Clone,Debug)]
784 enum ParentLink<'a> {
786 ModuleParentLink(Module<'a>, Name),
787 BlockParentLink(Module<'a>, NodeId),
790 /// One node in the tree of modules.
791 pub struct ModuleS<'a> {
792 parent_link: ParentLink<'a>,
795 is_extern_crate: bool,
797 children: RefCell<HashMap<(Name, Namespace), NameBinding<'a>>>,
798 imports: RefCell<Vec<ImportDirective>>,
800 // The anonymous children of this node. Anonymous children are pseudo-
801 // modules that are implicitly created around items contained within
804 // For example, if we have this:
812 // There will be an anonymous module created around `g` with the ID of the
813 // entry block for `f`.
814 anonymous_children: RefCell<NodeMap<Module<'a>>>,
816 // The status of resolving each import in this module.
817 import_resolutions: RefCell<HashMap<(Name, Namespace), ImportResolution<'a>>>,
819 // The number of unresolved globs that this module exports.
820 glob_count: Cell<usize>,
822 // The number of unresolved pub imports (both regular and globs) in this module
823 pub_count: Cell<usize>,
825 // The number of unresolved pub glob imports in this module
826 pub_glob_count: Cell<usize>,
828 // The index of the import we're resolving.
829 resolved_import_count: Cell<usize>,
831 // Whether this module is populated. If not populated, any attempt to
832 // access the children must be preceded with a
833 // `populate_module_if_necessary` call.
834 populated: Cell<bool>,
837 pub type Module<'a> = &'a ModuleS<'a>;
839 impl<'a> ModuleS<'a> {
840 fn new(parent_link: ParentLink<'a>, def: Option<Def>, external: bool, is_public: bool) -> Self {
842 parent_link: parent_link,
844 is_public: is_public,
845 is_extern_crate: false,
846 children: RefCell::new(HashMap::new()),
847 imports: RefCell::new(Vec::new()),
848 anonymous_children: RefCell::new(NodeMap()),
849 import_resolutions: RefCell::new(HashMap::new()),
850 glob_count: Cell::new(0),
851 pub_count: Cell::new(0),
852 pub_glob_count: Cell::new(0),
853 resolved_import_count: Cell::new(0),
854 populated: Cell::new(!external),
858 fn get_child(&self, name: Name, ns: Namespace) -> Option<NameBinding<'a>> {
859 self.children.borrow().get(&(name, ns)).cloned()
862 // If the name is not yet defined, define the name and return None.
863 // Otherwise, return the existing definition.
864 fn try_define_child(&self, name: Name, ns: Namespace, binding: NameBinding<'a>)
865 -> Option<NameBinding<'a>> {
866 match self.children.borrow_mut().entry((name, ns)) {
867 hash_map::Entry::Vacant(entry) => { entry.insert(binding); None }
868 hash_map::Entry::Occupied(entry) => { Some(entry.get().clone()) },
872 fn for_each_local_child<F: FnMut(Name, Namespace, &NameBinding<'a>)>(&self, mut f: F) {
873 for (&(name, ns), name_binding) in self.children.borrow().iter() {
874 if !name_binding.is_extern_crate() {
875 f(name, ns, name_binding)
880 fn def_id(&self) -> Option<DefId> {
881 self.def.as_ref().map(Def::def_id)
884 fn is_normal(&self) -> bool {
886 Some(Def::Mod(_)) | Some(Def::ForeignMod(_)) => true,
891 fn is_trait(&self) -> bool {
893 Some(Def::Trait(_)) => true,
898 fn all_imports_resolved(&self) -> bool {
899 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
900 // it is currently being resolved ! so nope
903 self.imports.borrow().len() == self.resolved_import_count.get()
907 pub fn inc_glob_count(&self) {
908 self.glob_count.set(self.glob_count.get() + 1);
910 pub fn dec_glob_count(&self) {
911 assert!(self.glob_count.get() > 0);
912 self.glob_count.set(self.glob_count.get() - 1);
914 pub fn inc_pub_count(&self) {
915 self.pub_count.set(self.pub_count.get() + 1);
917 pub fn dec_pub_count(&self) {
918 assert!(self.pub_count.get() > 0);
919 self.pub_count.set(self.pub_count.get() - 1);
921 pub fn inc_pub_glob_count(&self) {
922 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
924 pub fn dec_pub_glob_count(&self) {
925 assert!(self.pub_glob_count.get() > 0);
926 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
930 impl<'a> fmt::Debug for ModuleS<'a> {
931 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
945 flags DefModifiers: u8 {
946 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
947 // or `use Enum::*` to work on private enums.
948 const PUBLIC = 1 << 0,
949 const IMPORTABLE = 1 << 1,
950 // Variants are considered `PUBLIC`, but some of them live in private enums.
951 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
952 const PRIVATE_VARIANT = 1 << 2,
956 // Records a possibly-private value, type, or module definition.
957 #[derive(Clone, Debug)]
958 pub struct NameBinding<'a> {
959 modifiers: DefModifiers, // see note in ImportResolution about how to use this
960 def_or_module: DefOrModule<'a>,
964 #[derive(Clone, Debug)]
965 enum DefOrModule<'a> {
970 impl<'a> NameBinding<'a> {
971 fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
972 let modifiers = if module.is_public {
975 DefModifiers::empty()
976 } | DefModifiers::IMPORTABLE;
978 NameBinding { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
981 fn module(&self) -> Option<Module<'a>> {
982 match self.def_or_module {
983 DefOrModule::Module(ref module) => Some(module),
984 DefOrModule::Def(_) => None,
988 fn def(&self) -> Option<Def> {
989 match self.def_or_module {
990 DefOrModule::Def(def) => Some(def),
991 DefOrModule::Module(ref module) => module.def,
995 fn defined_with(&self, modifiers: DefModifiers) -> bool {
996 self.modifiers.contains(modifiers)
999 fn is_public(&self) -> bool {
1000 self.defined_with(DefModifiers::PUBLIC)
1003 fn def_and_lp(&self) -> (Def, LastPrivate) {
1004 let def = self.def().unwrap();
1005 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1008 fn is_extern_crate(&self) -> bool {
1009 self.module().map(|module| module.is_extern_crate).unwrap_or(false)
1013 /// Interns the names of the primitive types.
1014 struct PrimitiveTypeTable {
1015 primitive_types: HashMap<Name, PrimTy>,
1018 impl PrimitiveTypeTable {
1019 fn new() -> PrimitiveTypeTable {
1020 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1022 table.intern("bool", TyBool);
1023 table.intern("char", TyChar);
1024 table.intern("f32", TyFloat(TyF32));
1025 table.intern("f64", TyFloat(TyF64));
1026 table.intern("isize", TyInt(TyIs));
1027 table.intern("i8", TyInt(TyI8));
1028 table.intern("i16", TyInt(TyI16));
1029 table.intern("i32", TyInt(TyI32));
1030 table.intern("i64", TyInt(TyI64));
1031 table.intern("str", TyStr);
1032 table.intern("usize", TyUint(TyUs));
1033 table.intern("u8", TyUint(TyU8));
1034 table.intern("u16", TyUint(TyU16));
1035 table.intern("u32", TyUint(TyU32));
1036 table.intern("u64", TyUint(TyU64));
1041 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1042 self.primitive_types.insert(token::intern(string), primitive_type);
1046 /// The main resolver class.
1047 pub struct Resolver<'a, 'tcx: 'a> {
1048 session: &'a Session,
1050 ast_map: &'a hir_map::Map<'tcx>,
1052 graph_root: Module<'a>,
1054 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1056 structs: FnvHashMap<DefId, Vec<Name>>,
1058 // The number of imports that are currently unresolved.
1059 unresolved_imports: usize,
1061 // The module that represents the current item scope.
1062 current_module: Module<'a>,
1064 // The current set of local scopes, for values.
1065 // FIXME #4948: Reuse ribs to avoid allocation.
1066 value_ribs: Vec<Rib<'a>>,
1068 // The current set of local scopes, for types.
1069 type_ribs: Vec<Rib<'a>>,
1071 // The current set of local scopes, for labels.
1072 label_ribs: Vec<Rib<'a>>,
1074 // The trait that the current context can refer to.
1075 current_trait_ref: Option<(DefId, TraitRef)>,
1077 // The current self type if inside an impl (used for better errors).
1078 current_self_type: Option<Ty>,
1080 // The idents for the primitive types.
1081 primitive_type_table: PrimitiveTypeTable,
1083 def_map: RefCell<DefMap>,
1084 freevars: FreevarMap,
1085 freevars_seen: NodeMap<NodeMap<usize>>,
1086 export_map: ExportMap,
1087 trait_map: TraitMap,
1088 external_exports: ExternalExports,
1090 // Whether or not to print error messages. Can be set to true
1091 // when getting additional info for error message suggestions,
1092 // so as to avoid printing duplicate errors
1095 make_glob_map: bool,
1096 // Maps imports to the names of items actually imported (this actually maps
1097 // all imports, but only glob imports are actually interesting).
1100 used_imports: HashSet<(NodeId, Namespace)>,
1101 used_crates: HashSet<CrateNum>,
1103 // Callback function for intercepting walks
1104 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1105 // The intention is that the callback modifies this flag.
1106 // Once set, the resolver falls out of the walk, preserving the ribs.
1109 arenas: &'a ResolverArenas<'a>,
1112 pub struct ResolverArenas<'a> {
1113 modules: arena::TypedArena<ModuleS<'a>>,
1116 #[derive(PartialEq)]
1117 enum FallbackChecks {
1119 OnlyTraitAndStatics,
1122 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1123 fn new(session: &'a Session,
1124 ast_map: &'a hir_map::Map<'tcx>,
1125 make_glob_map: MakeGlobMap,
1126 arenas: &'a ResolverArenas<'a>)
1127 -> Resolver<'a, 'tcx> {
1128 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1129 let graph_root = ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, true);
1130 let graph_root = arenas.modules.alloc(graph_root);
1137 // The outermost module has def ID 0; this is not reflected in the
1139 graph_root: graph_root,
1141 trait_item_map: FnvHashMap(),
1142 structs: FnvHashMap(),
1144 unresolved_imports: 0,
1146 current_module: graph_root,
1147 value_ribs: Vec::new(),
1148 type_ribs: Vec::new(),
1149 label_ribs: Vec::new(),
1151 current_trait_ref: None,
1152 current_self_type: None,
1154 primitive_type_table: PrimitiveTypeTable::new(),
1156 def_map: RefCell::new(NodeMap()),
1157 freevars: NodeMap(),
1158 freevars_seen: NodeMap(),
1159 export_map: NodeMap(),
1160 trait_map: NodeMap(),
1161 used_imports: HashSet::new(),
1162 used_crates: HashSet::new(),
1163 external_exports: DefIdSet(),
1166 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1167 glob_map: HashMap::new(),
1176 fn arenas() -> ResolverArenas<'a> {
1178 modules: arena::TypedArena::new(),
1182 fn new_module(&self,
1183 parent_link: ParentLink<'a>,
1186 is_public: bool) -> Module<'a> {
1187 self.arenas.modules.alloc(ModuleS::new(parent_link, def, external, is_public))
1190 fn new_extern_crate_module(&self, parent_link: ParentLink<'a>, def: Def) -> Module<'a> {
1191 let mut module = ModuleS::new(parent_link, Some(def), false, true);
1192 module.is_extern_crate = true;
1193 self.arenas.modules.alloc(module)
1196 fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
1197 match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
1201 fn record_import_use(&mut self, name: Name, ns: Namespace, resolution: &ImportResolution<'a>) {
1202 let import_id = resolution.id;
1203 self.used_imports.insert((import_id, ns));
1204 match resolution.target.as_ref().and_then(|target| target.target_module.def_id()) {
1205 Some(DefId { krate, .. }) => { self.used_crates.insert(krate); }
1209 if !self.make_glob_map {
1212 if self.glob_map.contains_key(&import_id) {
1213 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1217 let mut new_set = HashSet::new();
1218 new_set.insert(name);
1219 self.glob_map.insert(import_id, new_set);
1222 fn get_trait_name(&self, did: DefId) -> Name {
1223 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1224 self.ast_map.expect_item(node_id).name
1226 self.session.cstore.item_name(did)
1230 /// Resolves the given module path from the given root `module_`.
1231 fn resolve_module_path_from_root(&mut self,
1232 module_: Module<'a>,
1233 module_path: &[Name],
1237 -> ResolveResult<(Module<'a>, LastPrivate)> {
1238 fn search_parent_externals<'a>(needle: Name, module: Module<'a>) -> Option<Module<'a>> {
1239 match module.get_child(needle, TypeNS) {
1240 Some(ref binding) if binding.is_extern_crate() => Some(module),
1241 _ => match module.parent_link {
1242 ModuleParentLink(ref parent, _) => {
1243 search_parent_externals(needle, parent)
1250 let mut search_module = module_;
1251 let mut index = index;
1252 let module_path_len = module_path.len();
1253 let mut closest_private = lp;
1255 // Resolve the module part of the path. This does not involve looking
1256 // upward though scope chains; we simply resolve names directly in
1257 // modules as we go.
1258 while index < module_path_len {
1259 let name = module_path[index];
1260 match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1262 let segment_name = name.as_str();
1263 let module_name = module_to_string(search_module);
1264 let mut span = span;
1265 let msg = if "???" == &module_name[..] {
1266 span.hi = span.lo + Pos::from_usize(segment_name.len());
1268 match search_parent_externals(name, &self.current_module) {
1270 let path_str = names_to_string(module_path);
1271 let target_mod_str = module_to_string(&*module);
1272 let current_mod_str = module_to_string(&*self.current_module);
1274 let prefix = if target_mod_str == current_mod_str {
1275 "self::".to_string()
1277 format!("{}::", target_mod_str)
1280 format!("Did you mean `{}{}`?", prefix, path_str)
1282 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1285 format!("Could not find `{}` in `{}`", segment_name, module_name)
1288 return Failed(Some((span, msg)));
1290 Failed(err) => return Failed(err),
1292 debug!("(resolving module path for import) module resolution is \
1295 return Indeterminate;
1297 Success((target, used_proxy)) => {
1298 // Check to see whether there are type bindings, and, if
1299 // so, whether there is a module within.
1300 if let Some(module_def) = target.binding.module() {
1301 // track extern crates for unused_extern_crate lint
1302 if let Some(did) = module_def.def_id() {
1303 self.used_crates.insert(did.krate);
1306 search_module = module_def;
1308 // Keep track of the closest private module used
1309 // when resolving this import chain.
1310 if !used_proxy && !search_module.is_public {
1311 if let Some(did) = search_module.def_id() {
1312 closest_private = LastMod(DependsOn(did));
1316 let msg = format!("Not a module `{}`", name);
1317 return Failed(Some((span, msg)));
1325 return Success((search_module, closest_private));
1328 /// Attempts to resolve the module part of an import directive or path
1329 /// rooted at the given module.
1331 /// On success, returns the resolved module, and the closest *private*
1332 /// module found to the destination when resolving this path.
1333 fn resolve_module_path(&mut self,
1334 module_: Module<'a>,
1335 module_path: &[Name],
1336 use_lexical_scope: UseLexicalScopeFlag,
1338 -> ResolveResult<(Module<'a>, LastPrivate)> {
1339 if module_path.len() == 0 {
1340 return Success((self.graph_root, LastMod(AllPublic))) // Use the crate root
1343 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1344 names_to_string(module_path),
1345 module_to_string(&*module_));
1347 // Resolve the module prefix, if any.
1348 let module_prefix_result = self.resolve_module_prefix(module_, module_path);
1353 match module_prefix_result {
1355 let mpath = names_to_string(module_path);
1356 let mpath = &mpath[..];
1357 match mpath.rfind(':') {
1359 let msg = format!("Could not find `{}` in `{}`",
1360 // idx +- 1 to account for the
1361 // colons on either side
1364 return Failed(Some((span, msg)));
1367 return Failed(None);
1371 Failed(err) => return Failed(err),
1373 debug!("(resolving module path for import) indeterminate; bailing");
1374 return Indeterminate;
1376 Success(NoPrefixFound) => {
1377 // There was no prefix, so we're considering the first element
1378 // of the path. How we handle this depends on whether we were
1379 // instructed to use lexical scope or not.
1380 match use_lexical_scope {
1381 DontUseLexicalScope => {
1382 // This is a crate-relative path. We will start the
1383 // resolution process at index zero.
1384 search_module = self.graph_root;
1386 last_private = LastMod(AllPublic);
1388 UseLexicalScope => {
1389 // This is not a crate-relative path. We resolve the
1390 // first component of the path in the current lexical
1391 // scope and then proceed to resolve below that.
1392 match self.resolve_item_in_lexical_scope(module_,
1396 Failed(err) => return Failed(err),
1398 debug!("(resolving module path for import) indeterminate; bailing");
1399 return Indeterminate;
1401 Success((target, _)) => match target.binding.module() {
1402 Some(containing_module) => {
1403 search_module = containing_module;
1405 last_private = LastMod(AllPublic);
1407 None => return Failed(None),
1413 Success(PrefixFound(ref containing_module, index)) => {
1414 search_module = containing_module;
1415 start_index = index;
1416 last_private = LastMod(DependsOn(containing_module.def_id()
1421 self.resolve_module_path_from_root(search_module,
1428 /// Invariant: This must only be called during main resolution, not during
1429 /// import resolution.
1430 fn resolve_item_in_lexical_scope(&mut self,
1431 module_: Module<'a>,
1433 namespace: Namespace,
1435 -> ResolveResult<(Target<'a>, bool)> {
1436 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1439 module_to_string(&*module_));
1441 // Proceed up the scope chain looking for parent modules.
1442 let mut search_module = module_;
1444 // Resolve the name in the parent module.
1445 match self.resolve_name_in_module(search_module, name, namespace, true, record_used) {
1446 Failed(Some((span, msg))) => {
1447 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1449 Failed(None) => (), // Continue up the search chain.
1451 // We couldn't see through the higher scope because of an
1452 // unresolved import higher up. Bail.
1454 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1455 return Indeterminate;
1457 Success((target, used_reexport)) => {
1458 // We found the module.
1459 debug!("(resolving item in lexical scope) found name in module, done");
1460 return Success((target, used_reexport));
1464 // Go to the next parent.
1465 match search_module.parent_link {
1467 // No more parents. This module was unresolved.
1468 debug!("(resolving item in lexical scope) unresolved module: no parent module");
1469 return Failed(None);
1471 ModuleParentLink(parent_module_node, _) => {
1472 if search_module.is_normal() {
1473 // We stop the search here.
1474 debug!("(resolving item in lexical scope) unresolved module: not \
1475 searching through module parents");
1476 return Failed(None);
1478 search_module = parent_module_node;
1481 BlockParentLink(parent_module_node, _) => {
1482 search_module = parent_module_node;
1488 /// Returns the nearest normal module parent of the given module.
1489 fn get_nearest_normal_module_parent(&mut self, module_: Module<'a>) -> Option<Module<'a>> {
1490 let mut module_ = module_;
1492 match module_.parent_link {
1493 NoParentLink => return None,
1494 ModuleParentLink(new_module, _) |
1495 BlockParentLink(new_module, _) => {
1496 let new_module = new_module;
1497 if new_module.is_normal() {
1498 return Some(new_module);
1500 module_ = new_module;
1506 /// Returns the nearest normal module parent of the given module, or the
1507 /// module itself if it is a normal module.
1508 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Module<'a>) -> Module<'a> {
1509 if module_.is_normal() {
1512 match self.get_nearest_normal_module_parent(module_) {
1514 Some(new_module) => new_module,
1518 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1519 /// (b) some chain of `super::`.
1520 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1521 fn resolve_module_prefix(&mut self,
1522 module_: Module<'a>,
1523 module_path: &[Name])
1524 -> ResolveResult<ModulePrefixResult<'a>> {
1525 // Start at the current module if we see `self` or `super`, or at the
1526 // top of the crate otherwise.
1527 let mut i = match &*module_path[0].as_str() {
1530 _ => return Success(NoPrefixFound),
1532 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1534 // Now loop through all the `super`s we find.
1535 while i < module_path.len() && "super" == module_path[i].as_str() {
1536 debug!("(resolving module prefix) resolving `super` at {}",
1537 module_to_string(&*containing_module));
1538 match self.get_nearest_normal_module_parent(containing_module) {
1539 None => return Failed(None),
1540 Some(new_module) => {
1541 containing_module = new_module;
1547 debug!("(resolving module prefix) finished resolving prefix at {}",
1548 module_to_string(&*containing_module));
1550 return Success(PrefixFound(containing_module, i));
1553 /// Attempts to resolve the supplied name in the given module for the
1554 /// given namespace. If successful, returns the target corresponding to
1557 /// The boolean returned on success is an indicator of whether this lookup
1558 /// passed through a public re-export proxy.
1559 fn resolve_name_in_module(&mut self,
1560 module_: Module<'a>,
1562 namespace: Namespace,
1563 allow_private_imports: bool,
1565 -> ResolveResult<(Target<'a>, bool)> {
1566 debug!("(resolving name in module) resolving `{}` in `{}`",
1568 module_to_string(&*module_));
1570 // First, check the direct children of the module.
1571 build_reduced_graph::populate_module_if_necessary(self, &module_);
1573 if let Some(binding) = module_.get_child(name, namespace) {
1574 debug!("(resolving name in module) found node as child");
1575 return Success((Target::new(module_, binding, Shadowable::Never), false));
1578 // Check the list of resolved imports.
1579 match module_.import_resolutions.borrow().get(&(name, namespace)) {
1580 Some(import_resolution) if allow_private_imports || import_resolution.is_public => {
1581 if import_resolution.is_public && import_resolution.outstanding_references != 0 {
1582 debug!("(resolving name in module) import unresolved; bailing out");
1583 return Indeterminate;
1585 if let Some(target) = import_resolution.target.clone() {
1586 debug!("(resolving name in module) resolved to import");
1588 self.record_import_use(name, namespace, &import_resolution);
1590 return Success((target, true));
1593 Some(..) | None => {} // Continue.
1596 // We're out of luck.
1597 debug!("(resolving name in module) failed to resolve `{}`", name);
1598 return Failed(None);
1601 fn report_unresolved_imports(&mut self, module_: Module<'a>) {
1602 let index = module_.resolved_import_count.get();
1603 let imports = module_.imports.borrow();
1604 let import_count = imports.len();
1605 if index != import_count {
1607 (*imports)[index].span,
1608 ResolutionError::UnresolvedImport(None));
1611 // Descend into children and anonymous children.
1612 build_reduced_graph::populate_module_if_necessary(self, &module_);
1614 module_.for_each_local_child(|_, _, child_node| {
1615 match child_node.module() {
1619 Some(child_module) => {
1620 self.report_unresolved_imports(child_module);
1625 for (_, module_) in module_.anonymous_children.borrow().iter() {
1626 self.report_unresolved_imports(module_);
1632 // We maintain a list of value ribs and type ribs.
1634 // Simultaneously, we keep track of the current position in the module
1635 // graph in the `current_module` pointer. When we go to resolve a name in
1636 // the value or type namespaces, we first look through all the ribs and
1637 // then query the module graph. When we resolve a name in the module
1638 // namespace, we can skip all the ribs (since nested modules are not
1639 // allowed within blocks in Rust) and jump straight to the current module
1642 // Named implementations are handled separately. When we find a method
1643 // call, we consult the module node to find all of the implementations in
1644 // scope. This information is lazily cached in the module node. We then
1645 // generate a fake "implementation scope" containing all the
1646 // implementations thus found, for compatibility with old resolve pass.
1648 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1649 where F: FnOnce(&mut Resolver)
1651 let orig_module = self.current_module;
1653 // Move down in the graph.
1659 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1661 match orig_module.get_child(name, TypeNS) {
1663 debug!("!!! (with scope) didn't find `{}` in `{}`",
1665 module_to_string(&*orig_module));
1667 Some(name_binding) => {
1668 match name_binding.module() {
1670 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1672 module_to_string(&*orig_module));
1675 self.current_module = module_;
1685 self.current_module = orig_module;
1688 /// Searches the current set of local scopes for labels.
1689 /// Stops after meeting a closure.
1690 fn search_label(&self, name: Name) -> Option<DefLike> {
1691 for rib in self.label_ribs.iter().rev() {
1697 // Do not resolve labels across function boundary
1701 let result = rib.bindings.get(&name).cloned();
1702 if result.is_some() {
1709 fn resolve_crate(&mut self, krate: &hir::Crate) {
1710 debug!("(resolving crate) starting");
1712 intravisit::walk_crate(self, krate);
1715 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1716 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1717 span_err!(self.session,
1720 "user-defined types or type parameters cannot shadow the primitive types");
1724 fn resolve_item(&mut self, item: &Item) {
1725 let name = item.name;
1727 debug!("(resolving item) resolving {}", name);
1730 ItemEnum(_, ref generics) |
1731 ItemTy(_, ref generics) |
1732 ItemStruct(_, ref generics) => {
1733 self.check_if_primitive_type_name(name, item.span);
1735 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1736 |this| intravisit::walk_item(this, item));
1738 ItemFn(_, _, _, _, ref generics, _) => {
1739 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1740 |this| intravisit::walk_item(this, item));
1743 ItemDefaultImpl(_, ref trait_ref) => {
1744 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1746 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1747 self.resolve_implementation(generics,
1754 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1755 self.check_if_primitive_type_name(name, item.span);
1757 // Create a new rib for the trait-wide type parameters.
1758 self.with_type_parameter_rib(HasTypeParameters(generics,
1762 let local_def_id = this.ast_map.local_def_id(item.id);
1763 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1764 this.visit_generics(generics);
1765 walk_list!(this, visit_ty_param_bound, bounds);
1767 for trait_item in trait_items {
1768 match trait_item.node {
1769 hir::ConstTraitItem(_, ref default) => {
1770 // Only impose the restrictions of
1771 // ConstRibKind if there's an actual constant
1772 // expression in a provided default.
1773 if default.is_some() {
1774 this.with_constant_rib(|this| {
1775 intravisit::walk_trait_item(this, trait_item)
1778 intravisit::walk_trait_item(this, trait_item)
1781 hir::MethodTraitItem(ref sig, _) => {
1782 let type_parameters =
1783 HasTypeParameters(&sig.generics,
1786 this.with_type_parameter_rib(type_parameters, |this| {
1787 intravisit::walk_trait_item(this, trait_item)
1790 hir::TypeTraitItem(..) => {
1791 this.check_if_primitive_type_name(trait_item.name,
1793 this.with_type_parameter_rib(NoTypeParameters, |this| {
1794 intravisit::walk_trait_item(this, trait_item)
1803 ItemMod(_) | ItemForeignMod(_) => {
1804 self.with_scope(Some(name), |this| {
1805 intravisit::walk_item(this, item);
1809 ItemConst(..) | ItemStatic(..) => {
1810 self.with_constant_rib(|this| {
1811 intravisit::walk_item(this, item);
1815 ItemUse(ref view_path) => {
1816 // check for imports shadowing primitive types
1817 let check_rename = |this: &Self, id, name| {
1818 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
1819 Some(Def::Enum(..)) | Some(Def::TyAlias(..)) | Some(Def::Struct(..)) |
1820 Some(Def::Trait(..)) | None => {
1821 this.check_if_primitive_type_name(name, item.span);
1827 match view_path.node {
1828 hir::ViewPathSimple(name, _) => {
1829 check_rename(self, item.id, name);
1831 hir::ViewPathList(ref prefix, ref items) => {
1833 if let Some(name) = item.node.rename() {
1834 check_rename(self, item.node.id(), name);
1838 // Resolve prefix of an import with empty braces (issue #28388)
1839 if items.is_empty() && !prefix.segments.is_empty() {
1840 match self.resolve_crate_relative_path(prefix.span,
1844 self.record_def(item.id, PathResolution::new(def, lp, 0)),
1848 ResolutionError::FailedToResolve(
1849 &path_names_to_string(prefix, 0)));
1850 self.record_def(item.id, err_path_resolution());
1859 ItemExternCrate(_) => {
1860 // do nothing, these are just around to be encoded
1865 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
1866 where F: FnOnce(&mut Resolver)
1868 match type_parameters {
1869 HasTypeParameters(generics, space, rib_kind) => {
1870 let mut function_type_rib = Rib::new(rib_kind);
1871 let mut seen_bindings = HashSet::new();
1872 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1873 let name = type_parameter.name;
1874 debug!("with_type_parameter_rib: {}", type_parameter.id);
1876 if seen_bindings.contains(&name) {
1878 type_parameter.span,
1879 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1881 seen_bindings.insert(name);
1883 // plain insert (no renaming)
1884 function_type_rib.bindings
1886 DlDef(Def::TyParam(space,
1889 .local_def_id(type_parameter.id),
1892 self.type_ribs.push(function_type_rib);
1895 NoTypeParameters => {
1902 match type_parameters {
1903 HasTypeParameters(..) => {
1905 self.type_ribs.pop();
1908 NoTypeParameters => {}
1912 fn with_label_rib<F>(&mut self, f: F)
1913 where F: FnOnce(&mut Resolver)
1915 self.label_ribs.push(Rib::new(NormalRibKind));
1918 self.label_ribs.pop();
1922 fn with_constant_rib<F>(&mut self, f: F)
1923 where F: FnOnce(&mut Resolver)
1925 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1926 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1929 self.type_ribs.pop();
1930 self.value_ribs.pop();
1934 fn resolve_function(&mut self, rib_kind: RibKind<'a>, declaration: &FnDecl, block: &Block) {
1935 // Create a value rib for the function.
1936 self.value_ribs.push(Rib::new(rib_kind));
1938 // Create a label rib for the function.
1939 self.label_ribs.push(Rib::new(rib_kind));
1941 // Add each argument to the rib.
1942 let mut bindings_list = HashMap::new();
1943 for argument in &declaration.inputs {
1944 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
1946 self.visit_ty(&*argument.ty);
1948 debug!("(resolving function) recorded argument");
1950 intravisit::walk_fn_ret_ty(self, &declaration.output);
1952 // Resolve the function body.
1953 self.visit_block(block);
1955 debug!("(resolving function) leaving function");
1958 self.label_ribs.pop();
1959 self.value_ribs.pop();
1963 fn resolve_trait_reference(&mut self,
1967 -> Result<PathResolution, ()> {
1968 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
1969 if let Def::Trait(_) = path_res.base_def {
1970 debug!("(resolving trait) found trait def: {:?}", path_res);
1974 resolve_struct_error(self,
1976 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
1979 // If it's a typedef, give a note
1980 if let Def::TyAlias(..) = path_res.base_def {
1981 err.span_note(trait_path.span,
1982 "`type` aliases cannot be used for traits");
1990 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
1996 fn resolve_generics(&mut self, generics: &Generics) {
1997 for type_parameter in generics.ty_params.iter() {
1998 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2000 for predicate in &generics.where_clause.predicates {
2002 &hir::WherePredicate::BoundPredicate(_) |
2003 &hir::WherePredicate::RegionPredicate(_) => {}
2004 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2005 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2006 if let Some(PathResolution { base_def: Def::TyParam(..), .. }) = path_res {
2007 self.record_def(eq_pred.id, path_res.unwrap());
2011 ResolutionError::UndeclaredAssociatedType);
2012 self.record_def(eq_pred.id, err_path_resolution());
2017 intravisit::walk_generics(self, generics);
2020 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2021 where F: FnOnce(&mut Resolver) -> T
2023 // Handle nested impls (inside fn bodies)
2024 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2025 let result = f(self);
2026 self.current_self_type = previous_value;
2030 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2031 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2033 let mut new_val = None;
2034 let mut new_id = None;
2035 if let Some(trait_ref) = opt_trait_ref {
2036 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2039 assert!(path_res.depth == 0);
2040 self.record_def(trait_ref.ref_id, path_res);
2041 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2042 new_id = Some(path_res.base_def.def_id());
2044 self.record_def(trait_ref.ref_id, err_path_resolution());
2046 intravisit::walk_trait_ref(self, trait_ref);
2048 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2049 let result = f(self, new_id);
2050 self.current_trait_ref = original_trait_ref;
2054 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2055 where F: FnOnce(&mut Resolver)
2057 let mut self_type_rib = Rib::new(NormalRibKind);
2059 // plain insert (no renaming, types are not currently hygienic....)
2060 let name = special_names::type_self;
2061 self_type_rib.bindings.insert(name, DlDef(self_def));
2062 self.type_ribs.push(self_type_rib);
2065 self.type_ribs.pop();
2069 fn resolve_implementation(&mut self,
2070 generics: &Generics,
2071 opt_trait_reference: &Option<TraitRef>,
2074 impl_items: &[ImplItem]) {
2075 // If applicable, create a rib for the type parameters.
2076 self.with_type_parameter_rib(HasTypeParameters(generics,
2080 // Resolve the type parameters.
2081 this.visit_generics(generics);
2083 // Resolve the trait reference, if necessary.
2084 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2085 // Resolve the self type.
2086 this.visit_ty(self_type);
2088 this.with_self_rib(Def::SelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2089 this.with_current_self_type(self_type, |this| {
2090 for impl_item in impl_items {
2091 match impl_item.node {
2092 hir::ImplItemKind::Const(..) => {
2093 // If this is a trait impl, ensure the const
2095 this.check_trait_item(impl_item.name,
2097 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2098 this.with_constant_rib(|this| {
2099 intravisit::walk_impl_item(this, impl_item);
2102 hir::ImplItemKind::Method(ref sig, _) => {
2103 // If this is a trait impl, ensure the method
2105 this.check_trait_item(impl_item.name,
2107 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2109 // We also need a new scope for the method-
2110 // specific type parameters.
2111 let type_parameters =
2112 HasTypeParameters(&sig.generics,
2115 this.with_type_parameter_rib(type_parameters, |this| {
2116 intravisit::walk_impl_item(this, impl_item);
2119 hir::ImplItemKind::Type(ref ty) => {
2120 // If this is a trait impl, ensure the type
2122 this.check_trait_item(impl_item.name,
2124 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2136 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2137 where F: FnOnce(Name, &str) -> ResolutionError
2139 // If there is a TraitRef in scope for an impl, then the method must be in the
2141 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2142 if !self.trait_item_map.contains_key(&(name, did)) {
2143 let path_str = path_names_to_string(&trait_ref.path, 0);
2144 resolve_error(self, span, err(name, &*path_str));
2149 fn resolve_local(&mut self, local: &Local) {
2150 // Resolve the type.
2151 walk_list!(self, visit_ty, &local.ty);
2153 // Resolve the initializer.
2154 walk_list!(self, visit_expr, &local.init);
2156 // Resolve the pattern.
2157 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2160 // build a map from pattern identifiers to binding-info's.
2161 // this is done hygienically. This could arise for a macro
2162 // that expands into an or-pattern where one 'x' was from the
2163 // user and one 'x' came from the macro.
2164 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2165 let mut result = HashMap::new();
2166 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2167 let name = path1.node;
2171 binding_mode: binding_mode,
2177 // check that all of the arms in an or-pattern have exactly the
2178 // same set of bindings, with the same binding modes for each.
2179 fn check_consistent_bindings(&mut self, arm: &Arm) {
2180 if arm.pats.is_empty() {
2183 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2184 for (i, p) in arm.pats.iter().enumerate() {
2185 let map_i = self.binding_mode_map(&**p);
2187 for (&key, &binding_0) in &map_0 {
2188 match map_i.get(&key) {
2192 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2194 Some(binding_i) => {
2195 if binding_0.binding_mode != binding_i.binding_mode {
2198 ResolutionError::VariableBoundWithDifferentMode(key,
2205 for (&key, &binding) in &map_i {
2206 if !map_0.contains_key(&key) {
2209 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2215 fn resolve_arm(&mut self, arm: &Arm) {
2216 self.value_ribs.push(Rib::new(NormalRibKind));
2218 let mut bindings_list = HashMap::new();
2219 for pattern in &arm.pats {
2220 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2223 // This has to happen *after* we determine which
2224 // pat_idents are variants
2225 self.check_consistent_bindings(arm);
2227 walk_list!(self, visit_expr, &arm.guard);
2228 self.visit_expr(&*arm.body);
2231 self.value_ribs.pop();
2235 fn resolve_block(&mut self, block: &Block) {
2236 debug!("(resolving block) entering block");
2237 // Move down in the graph, if there's an anonymous module rooted here.
2238 let orig_module = self.current_module;
2239 let anonymous_module =
2240 orig_module.anonymous_children.borrow().get(&block.id).map(|module| *module);
2242 if let Some(anonymous_module) = anonymous_module {
2243 debug!("(resolving block) found anonymous module, moving down");
2244 self.value_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2245 self.type_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2246 self.current_module = anonymous_module;
2248 self.value_ribs.push(Rib::new(NormalRibKind));
2251 // Descend into the block.
2252 intravisit::walk_block(self, block);
2256 self.current_module = orig_module;
2257 self.value_ribs.pop();
2258 if let Some(_) = anonymous_module {
2259 self.type_ribs.pop();
2262 debug!("(resolving block) leaving block");
2265 fn resolve_type(&mut self, ty: &Ty) {
2267 TyPath(ref maybe_qself, ref path) => {
2268 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2269 maybe_qself.as_ref(),
2273 // `<T>::a::b::c` is resolved by typeck alone.
2274 TypecheckRequired => {
2275 // Resolve embedded types.
2276 intravisit::walk_ty(self, ty);
2279 ResolveAttempt(resolution) => resolution,
2282 // This is a path in the type namespace. Walk through scopes
2286 // Write the result into the def map.
2287 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2288 path_names_to_string(path, 0),
2291 self.record_def(ty.id, def);
2294 self.record_def(ty.id, err_path_resolution());
2296 // Keep reporting some errors even if they're ignored above.
2297 self.resolve_path(ty.id, path, 0, TypeNS, true);
2299 let kind = if maybe_qself.is_some() {
2305 let self_type_name = special_idents::type_self.name;
2306 let is_invalid_self_type_name = path.segments.len() > 0 &&
2307 maybe_qself.is_none() &&
2308 path.segments[0].identifier.name ==
2310 if is_invalid_self_type_name {
2313 ResolutionError::SelfUsedOutsideImplOrTrait);
2317 ResolutionError::UseOfUndeclared(
2319 &*path_names_to_string(path,
2328 // Resolve embedded types.
2329 intravisit::walk_ty(self, ty);
2332 fn resolve_pattern(&mut self,
2334 mode: PatternBindingMode,
2335 // Maps idents to the node ID for the (outermost)
2336 // pattern that binds them
2337 bindings_list: &mut HashMap<Name, NodeId>) {
2338 let pat_id = pattern.id;
2339 walk_pat(pattern, |pattern| {
2340 match pattern.node {
2341 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2342 // The meaning of PatIdent with no type parameters
2343 // depends on whether an enum variant or unit-like struct
2344 // with that name is in scope. The probing lookup has to
2345 // be careful not to emit spurious errors. Only matching
2346 // patterns (match) can match nullary variants or
2347 // unit-like structs. For binding patterns (let
2348 // and the LHS of @-patterns), matching such a value is
2349 // simply disallowed (since it's rarely what you want).
2350 let const_ok = mode == RefutableMode && at_rhs.is_none();
2352 let ident = path1.node;
2353 let renamed = ident.name;
2355 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2357 FoundStructOrEnumVariant(def, lp) if const_ok => {
2358 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2361 self.enforce_default_binding_mode(pattern,
2364 self.record_def(pattern.id,
2371 FoundStructOrEnumVariant(..) => {
2375 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2378 self.record_def(pattern.id, err_path_resolution());
2380 FoundConst(def, lp, _) if const_ok => {
2381 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2383 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2384 self.record_def(pattern.id,
2391 FoundConst(def, _, name) => {
2395 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2398 self.record_def(pattern.id, err_path_resolution());
2400 BareIdentifierPatternUnresolved => {
2401 debug!("(resolving pattern) binding `{}`", renamed);
2403 let def_id = self.ast_map.local_def_id(pattern.id);
2404 let def = Def::Local(def_id, pattern.id);
2406 // Record the definition so that later passes
2407 // will be able to distinguish variants from
2408 // locals in patterns.
2410 self.record_def(pattern.id,
2413 last_private: LastMod(AllPublic),
2417 // Add the binding to the local ribs, if it
2418 // doesn't already exist in the bindings list. (We
2419 // must not add it if it's in the bindings list
2420 // because that breaks the assumptions later
2421 // passes make about or-patterns.)
2422 if !bindings_list.contains_key(&renamed) {
2423 let this = &mut *self;
2424 let last_rib = this.value_ribs.last_mut().unwrap();
2425 last_rib.bindings.insert(renamed, DlDef(def));
2426 bindings_list.insert(renamed, pat_id);
2427 } else if mode == ArgumentIrrefutableMode &&
2428 bindings_list.contains_key(&renamed) {
2429 // Forbid duplicate bindings in the same
2434 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2435 &ident.name.as_str())
2437 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2438 // Then this is a duplicate variable in the
2439 // same disjunction, which is an error.
2443 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2444 &ident.name.as_str())
2447 // Else, not bound in the same pattern: do
2453 PatEnum(ref path, _) => {
2454 // This must be an enum variant, struct or const.
2455 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2460 // The below shouldn't happen because all
2461 // qualified paths should be in PatQPath.
2462 TypecheckRequired =>
2463 self.session.span_bug(path.span,
2464 "resolve_possibly_assoc_item claimed
2466 that a path in PatEnum requires typecheck
2468 to resolve, but qualified paths should be
2471 ResolveAttempt(resolution) => resolution,
2473 if let Some(path_res) = resolution {
2474 match path_res.base_def {
2475 Def::Struct(..) if path_res.depth == 0 => {
2476 self.record_def(pattern.id, path_res);
2478 Def::Variant(..) | Def::Const(..) => {
2479 self.record_def(pattern.id, path_res);
2481 Def::Static(..) => {
2482 resolve_error(&self,
2484 ResolutionError::StaticVariableReference);
2485 self.record_def(pattern.id, err_path_resolution());
2488 // If anything ends up here entirely resolved,
2489 // it's an error. If anything ends up here
2490 // partially resolved, that's OK, because it may
2491 // be a `T::CONST` that typeck will resolve.
2492 if path_res.depth == 0 {
2496 ResolutionError::NotAnEnumVariantStructOrConst(
2504 self.record_def(pattern.id, err_path_resolution());
2506 let const_name = path.segments
2511 let traits = self.get_traits_containing_item(const_name);
2512 self.trait_map.insert(pattern.id, traits);
2513 self.record_def(pattern.id, path_res);
2521 ResolutionError::UnresolvedEnumVariantStructOrConst(
2522 &path.segments.last().unwrap().identifier.name.as_str())
2524 self.record_def(pattern.id, err_path_resolution());
2526 intravisit::walk_path(self, path);
2529 PatQPath(ref qself, ref path) => {
2530 // Associated constants only.
2531 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2536 TypecheckRequired => {
2537 // All `<T>::CONST` should end up here, and will
2538 // require use of the trait map to resolve
2539 // during typechecking.
2540 let const_name = path.segments
2545 let traits = self.get_traits_containing_item(const_name);
2546 self.trait_map.insert(pattern.id, traits);
2547 intravisit::walk_pat(self, pattern);
2550 ResolveAttempt(resolution) => resolution,
2552 if let Some(path_res) = resolution {
2553 match path_res.base_def {
2554 // All `<T as Trait>::CONST` should end up here, and
2555 // have the trait already selected.
2556 Def::AssociatedConst(..) => {
2557 self.record_def(pattern.id, path_res);
2563 ResolutionError::NotAnAssociatedConst(
2564 &path.segments.last().unwrap().identifier.name.as_str()
2567 self.record_def(pattern.id, err_path_resolution());
2573 ResolutionError::UnresolvedAssociatedConst(&path.segments
2579 self.record_def(pattern.id, err_path_resolution());
2581 intravisit::walk_pat(self, pattern);
2584 PatStruct(ref path, _, _) => {
2585 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2586 Some(definition) => {
2587 self.record_def(pattern.id, definition);
2590 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2594 ResolutionError::DoesNotNameAStruct(
2595 &*path_names_to_string(path, 0))
2597 self.record_def(pattern.id, err_path_resolution());
2600 intravisit::walk_path(self, path);
2603 PatLit(_) | PatRange(..) => {
2604 intravisit::walk_pat(self, pattern);
2615 fn resolve_bare_identifier_pattern(&mut self,
2618 -> BareIdentifierPatternResolution {
2619 let module = self.current_module;
2620 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2621 Success((target, _)) => {
2622 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2625 match target.binding.def() {
2627 panic!("resolved name in the value namespace to a set of name bindings \
2630 // For the two success cases, this lookup can be
2631 // considered as not having a private component because
2632 // the lookup happened only within the current module.
2633 Some(def @ Def::Variant(..)) | Some(def @ Def::Struct(..)) => {
2634 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2636 Some(def @ Def::Const(..)) | Some(def @ Def::AssociatedConst(..)) => {
2637 return FoundConst(def, LastMod(AllPublic), name);
2639 Some(Def::Static(..)) => {
2640 resolve_error(self, span, ResolutionError::StaticVariableReference);
2641 return BareIdentifierPatternUnresolved;
2643 _ => return BareIdentifierPatternUnresolved
2647 Indeterminate => return BareIdentifierPatternUnresolved,
2650 Some((span, msg)) => {
2651 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2656 debug!("(resolve bare identifier pattern) failed to find {}", name);
2657 return BareIdentifierPatternUnresolved;
2662 /// Handles paths that may refer to associated items
2663 fn resolve_possibly_assoc_item(&mut self,
2665 maybe_qself: Option<&hir::QSelf>,
2667 namespace: Namespace,
2669 -> AssocItemResolveResult {
2670 let max_assoc_types;
2674 if qself.position == 0 {
2675 return TypecheckRequired;
2677 max_assoc_types = path.segments.len() - qself.position;
2678 // Make sure the trait is valid.
2679 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2682 max_assoc_types = path.segments.len();
2686 let mut resolution = self.with_no_errors(|this| {
2687 this.resolve_path(id, path, 0, namespace, check_ribs)
2689 for depth in 1..max_assoc_types {
2690 if resolution.is_some() {
2693 self.with_no_errors(|this| {
2694 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2697 if let Some(Def::Mod(_)) = resolution.map(|r| r.base_def) {
2698 // A module is not a valid type or value.
2701 ResolveAttempt(resolution)
2704 /// If `check_ribs` is true, checks the local definitions first; i.e.
2705 /// doesn't skip straight to the containing module.
2706 /// Skips `path_depth` trailing segments, which is also reflected in the
2707 /// returned value. See `middle::def::PathResolution` for more info.
2708 pub fn resolve_path(&mut self,
2712 namespace: Namespace,
2714 -> Option<PathResolution> {
2715 let span = path.span;
2716 let segments = &path.segments[..path.segments.len() - path_depth];
2718 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2721 let def = self.resolve_crate_relative_path(span, segments, namespace);
2722 return def.map(mk_res);
2725 // Try to find a path to an item in a module.
2726 let last_ident = segments.last().unwrap().identifier;
2727 if segments.len() <= 1 {
2728 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2729 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2731 PathResolution::new(def, LastMod(AllPublic), path_depth)
2735 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2736 let def = self.resolve_module_relative_path(span, segments, namespace);
2737 match (def, unqualified_def) {
2738 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2740 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2743 "unnecessary qualification".to_string());
2751 // Resolve a single identifier
2752 fn resolve_identifier(&mut self,
2753 identifier: hir::Ident,
2754 namespace: Namespace,
2757 -> Option<LocalDef> {
2758 if identifier.name == special_idents::invalid.name {
2759 return Some(LocalDef::from_def(Def::Err));
2762 // First, check to see whether the name is a primitive type.
2763 if namespace == TypeNS {
2764 if let Some(&prim_ty) = self.primitive_type_table
2766 .get(&identifier.unhygienic_name) {
2767 return Some(LocalDef::from_def(Def::PrimTy(prim_ty)));
2772 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2778 let module = self.current_module;
2779 let name = identifier.unhygienic_name;
2780 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
2781 Success((target, _)) => target.binding.def().map(LocalDef::from_def),
2782 Failed(Some((span, msg))) => {
2783 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2790 // Resolve a local definition, potentially adjusting for closures.
2791 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2792 let ribs = match local_def.ribs {
2793 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2794 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2797 let mut def = local_def.def;
2800 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2802 Def::Local(_, node_id) => {
2805 NormalRibKind | AnonymousModuleRibKind(..) => {
2806 // Nothing to do. Continue.
2808 ClosureRibKind(function_id) => {
2810 let node_def_id = self.ast_map.local_def_id(node_id);
2812 let seen = self.freevars_seen
2814 .or_insert_with(|| NodeMap());
2815 if let Some(&index) = seen.get(&node_id) {
2816 def = Def::Upvar(node_def_id, node_id, index, function_id);
2819 let vec = self.freevars
2821 .or_insert_with(|| vec![]);
2822 let depth = vec.len();
2828 def = Def::Upvar(node_def_id, node_id, depth, function_id);
2829 seen.insert(node_id, depth);
2831 ItemRibKind | MethodRibKind => {
2832 // This was an attempt to access an upvar inside a
2833 // named function item. This is not allowed, so we
2837 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2840 ConstantItemRibKind => {
2841 // Still doesn't deal with upvars
2844 ResolutionError::AttemptToUseNonConstantValueInConstant);
2850 Def::TyParam(..) | Def::SelfTy(..) => {
2853 NormalRibKind | MethodRibKind | ClosureRibKind(..) |
2854 AnonymousModuleRibKind(..) => {
2855 // Nothing to do. Continue.
2858 // This was an attempt to use a type parameter outside
2863 ResolutionError::TypeParametersFromOuterFunction);
2866 ConstantItemRibKind => {
2868 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2879 // resolve a "module-relative" path, e.g. a::b::c
2880 fn resolve_module_relative_path(&mut self,
2882 segments: &[hir::PathSegment],
2883 namespace: Namespace)
2884 -> Option<(Def, LastPrivate)> {
2885 let module_path = segments.split_last()
2889 .map(|ps| ps.identifier.name)
2890 .collect::<Vec<_>>();
2892 let containing_module;
2894 let current_module = self.current_module;
2895 match self.resolve_module_path(current_module, &module_path, UseLexicalScope, span) {
2897 let (span, msg) = match err {
2898 Some((span, msg)) => (span, msg),
2900 let msg = format!("Use of undeclared type or module `{}`",
2901 names_to_string(&module_path));
2906 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2909 Indeterminate => return None,
2910 Success((resulting_module, resulting_last_private)) => {
2911 containing_module = resulting_module;
2912 last_private = resulting_last_private;
2916 let name = segments.last().unwrap().identifier.name;
2917 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2918 let def = match result {
2919 Success((Target { binding, .. }, _)) => {
2920 let (def, lp) = binding.def_and_lp();
2921 (def, last_private.or(lp))
2925 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
2926 self.used_crates.insert(kid);
2931 /// Invariant: This must be called only during main resolution, not during
2932 /// import resolution.
2933 fn resolve_crate_relative_path(&mut self,
2935 segments: &[hir::PathSegment],
2936 namespace: Namespace)
2937 -> Option<(Def, LastPrivate)> {
2938 let module_path = segments.split_last()
2942 .map(|ps| ps.identifier.name)
2943 .collect::<Vec<_>>();
2945 let root_module = self.graph_root;
2947 let containing_module;
2949 match self.resolve_module_path_from_root(root_module,
2953 LastMod(AllPublic)) {
2955 let (span, msg) = match err {
2956 Some((span, msg)) => (span, msg),
2958 let msg = format!("Use of undeclared module `::{}`",
2959 names_to_string(&module_path[..]));
2964 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2968 Indeterminate => return None,
2970 Success((resulting_module, resulting_last_private)) => {
2971 containing_module = resulting_module;
2972 last_private = resulting_last_private;
2976 let name = segments.last().unwrap().identifier.name;
2977 match self.resolve_name_in_module(containing_module, name, namespace, false, true) {
2978 Success((Target { binding, .. }, _)) => {
2979 let (def, lp) = binding.def_and_lp();
2980 Some((def, last_private.or(lp)))
2986 fn resolve_identifier_in_local_ribs(&mut self,
2988 namespace: Namespace)
2989 -> Option<LocalDef> {
2990 // Check the local set of ribs.
2991 let name = match namespace { ValueNS => ident.name, TypeNS => ident.unhygienic_name };
2993 for i in (0 .. self.get_ribs(namespace).len()).rev() {
2994 if let Some(def_like) = self.get_ribs(namespace)[i].bindings.get(&name).cloned() {
2997 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3001 return Some(LocalDef {
3002 ribs: Some((namespace, i)),
3007 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3015 if let AnonymousModuleRibKind(module) = self.get_ribs(namespace)[i].kind {
3016 if let Success((target, _)) = self.resolve_name_in_module(module,
3017 ident.unhygienic_name,
3021 if let Some(def) = target.binding.def() {
3022 return Some(LocalDef::from_def(def));
3031 fn with_no_errors<T, F>(&mut self, f: F) -> T
3032 where F: FnOnce(&mut Resolver) -> T
3034 self.emit_errors = false;
3036 self.emit_errors = true;
3040 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3041 fn extract_path_and_node_id(t: &Ty,
3042 allow: FallbackChecks)
3043 -> Option<(Path, NodeId, FallbackChecks)> {
3045 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3046 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3047 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3048 // This doesn't handle the remaining `Ty` variants as they are not
3049 // that commonly the self_type, it might be interesting to provide
3050 // support for those in future.
3055 fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
3057 name_path: &[ast::Name])
3058 -> Option<Module<'a>> {
3059 let root = this.current_module;
3060 let last_name = name_path.last().unwrap();
3062 if name_path.len() == 1 {
3063 match this.primitive_type_table.primitive_types.get(last_name) {
3065 None => this.current_module.get_child(*last_name, TypeNS)
3067 .and_then(NameBinding::module)
3070 match this.resolve_module_path(root, &name_path, UseLexicalScope, span) {
3071 Success((module, _)) => Some(module),
3077 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3078 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3079 let sig = match this.ast_map.get(node_id) {
3080 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3081 hir::MethodTraitItem(ref sig, _) => sig,
3084 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3085 hir::ImplItemKind::Method(ref sig, _) => sig,
3090 sig.explicit_self.node == hir::SelfStatic
3092 this.session.cstore.is_static_method(did)
3096 let (path, node_id, allowed) = match self.current_self_type {
3097 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3099 None => return NoSuggestion,
3101 None => return NoSuggestion,
3104 if allowed == Everything {
3105 // Look for a field with the same name in the current self_type.
3106 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3107 Some(Def::Enum(did)) |
3108 Some(Def::TyAlias(did)) |
3109 Some(Def::Struct(did)) |
3110 Some(Def::Variant(_, did)) => match self.structs.get(&did) {
3113 if fields.iter().any(|&field_name| name == field_name) {
3118 _ => {} // Self type didn't resolve properly
3122 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3124 // Look for a method in the current self type's impl module.
3125 if let Some(module) = get_module(self, path.span, &name_path) {
3126 if let Some(binding) = module.get_child(name, ValueNS) {
3127 if let Some(Def::Method(did)) = binding.def() {
3128 if is_static_method(self, did) {
3129 return StaticMethod(path_names_to_string(&path, 0));
3131 if self.current_trait_ref.is_some() {
3133 } else if allowed == Everything {
3140 // Look for a method in the current trait.
3141 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3142 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3143 if is_static_method(self, did) {
3144 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3154 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3155 if let Some(macro_name) = self.session.available_macros
3156 .borrow().iter().find(|n| n.as_str() == name) {
3157 return SuggestionType::Macro(format!("{}!", macro_name));
3160 let names = self.value_ribs
3163 .flat_map(|rib| rib.bindings.keys());
3165 if let Some(found) = find_best_match_for_name(names, name, None) {
3166 if name != &*found {
3167 return SuggestionType::Function(found);
3169 } SuggestionType::NotFound
3172 fn resolve_expr(&mut self, expr: &Expr) {
3173 // First, record candidate traits for this expression if it could
3174 // result in the invocation of a method call.
3176 self.record_candidate_traits_for_expr_if_necessary(expr);
3178 // Next, resolve the node.
3180 ExprPath(ref maybe_qself, ref path) => {
3181 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3182 maybe_qself.as_ref(),
3186 // `<T>::a::b::c` is resolved by typeck alone.
3187 TypecheckRequired => {
3188 let method_name = path.segments.last().unwrap().identifier.name;
3189 let traits = self.get_traits_containing_item(method_name);
3190 self.trait_map.insert(expr.id, traits);
3191 intravisit::walk_expr(self, expr);
3194 ResolveAttempt(resolution) => resolution,
3197 // This is a local path in the value namespace. Walk through
3198 // scopes looking for it.
3199 if let Some(path_res) = resolution {
3200 // Check if struct variant
3201 let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
3202 self.structs.contains_key(&variant_id)
3206 if is_struct_variant {
3207 let _ = self.structs.contains_key(&path_res.base_def.def_id());
3208 let path_name = path_names_to_string(path, 0);
3210 let mut err = resolve_struct_error(self,
3212 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3214 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3216 if self.emit_errors {
3217 err.fileline_help(expr.span, &msg);
3219 err.span_help(expr.span, &msg);
3222 self.record_def(expr.id, err_path_resolution());
3224 // Write the result into the def map.
3225 debug!("(resolving expr) resolved `{}`",
3226 path_names_to_string(path, 0));
3228 // Partial resolutions will need the set of traits in scope,
3229 // so they can be completed during typeck.
3230 if path_res.depth != 0 {
3231 let method_name = path.segments.last().unwrap().identifier.name;
3232 let traits = self.get_traits_containing_item(method_name);
3233 self.trait_map.insert(expr.id, traits);
3236 self.record_def(expr.id, path_res);
3239 // Be helpful if the name refers to a struct
3240 // (The pattern matching def_tys where the id is in self.structs
3241 // matches on regular structs while excluding tuple- and enum-like
3242 // structs, which wouldn't result in this error.)
3243 let path_name = path_names_to_string(path, 0);
3244 let type_res = self.with_no_errors(|this| {
3245 this.resolve_path(expr.id, path, 0, TypeNS, false)
3248 self.record_def(expr.id, err_path_resolution());
3249 match type_res.map(|r| r.base_def) {
3250 Some(Def::Struct(..)) => {
3251 let mut err = resolve_struct_error(self,
3253 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3255 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3257 if self.emit_errors {
3258 err.fileline_help(expr.span, &msg);
3260 err.span_help(expr.span, &msg);
3265 // Keep reporting some errors even if they're ignored above.
3266 self.resolve_path(expr.id, path, 0, ValueNS, true);
3268 let mut method_scope = false;
3269 self.value_ribs.iter().rev().all(|rib| {
3270 method_scope = match rib.kind {
3271 MethodRibKind => true,
3272 ItemRibKind | ConstantItemRibKind => false,
3273 _ => return true, // Keep advancing
3275 false // Stop advancing
3278 if method_scope && special_names::self_.as_str() == &path_name[..] {
3281 ResolutionError::SelfNotAvailableInStaticMethod);
3283 let last_name = path.segments.last().unwrap().identifier.name;
3284 let mut msg = match self.find_fallback_in_self_type(last_name) {
3286 // limit search to 5 to reduce the number
3287 // of stupid suggestions
3288 match self.find_best_match(&path_name) {
3289 SuggestionType::Macro(s) => {
3290 format!("the macro `{}`", s)
3292 SuggestionType::Function(s) => format!("`{}`", s),
3293 SuggestionType::NotFound => "".to_string(),
3296 Field => format!("`self.{}`", path_name),
3298 TraitItem => format!("to call `self.{}`", path_name),
3299 TraitMethod(path_str) |
3300 StaticMethod(path_str) =>
3301 format!("to call `{}::{}`", path_str, path_name),
3304 let mut context = UnresolvedNameContext::Other;
3305 if !msg.is_empty() {
3306 msg = format!(". Did you mean {}?", msg);
3308 // we check if this a module and if so, we display a help
3310 let name_path = path.segments.iter()
3311 .map(|seg| seg.identifier.name)
3312 .collect::<Vec<_>>();
3313 let current_module = self.current_module;
3315 match self.resolve_module_path(current_module,
3320 context = UnresolvedNameContext::PathIsMod(expr.id);
3328 ResolutionError::UnresolvedName(
3329 &*path_name, &*msg, context));
3335 intravisit::walk_expr(self, expr);
3338 ExprStruct(ref path, _, _) => {
3339 // Resolve the path to the structure it goes to. We don't
3340 // check to ensure that the path is actually a structure; that
3341 // is checked later during typeck.
3342 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3343 Some(definition) => self.record_def(expr.id, definition),
3345 debug!("(resolving expression) didn't find struct def",);
3349 ResolutionError::DoesNotNameAStruct(
3350 &*path_names_to_string(path, 0))
3352 self.record_def(expr.id, err_path_resolution());
3356 intravisit::walk_expr(self, expr);
3359 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3360 self.with_label_rib(|this| {
3361 let def_like = DlDef(Def::Label(expr.id));
3364 let rib = this.label_ribs.last_mut().unwrap();
3365 rib.bindings.insert(label.name, def_like);
3368 intravisit::walk_expr(this, expr);
3372 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3373 match self.search_label(label.node.name) {
3375 self.record_def(expr.id, err_path_resolution());
3378 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3380 Some(DlDef(def @ Def::Label(_))) => {
3381 // Since this def is a label, it is never read.
3382 self.record_def(expr.id,
3385 last_private: LastMod(AllPublic),
3390 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3396 intravisit::walk_expr(self, expr);
3401 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3403 ExprField(_, name) => {
3404 // FIXME(#6890): Even though you can't treat a method like a
3405 // field, we need to add any trait methods we find that match
3406 // the field name so that we can do some nice error reporting
3407 // later on in typeck.
3408 let traits = self.get_traits_containing_item(name.node);
3409 self.trait_map.insert(expr.id, traits);
3411 ExprMethodCall(name, _, _) => {
3412 debug!("(recording candidate traits for expr) recording traits for {}",
3414 let traits = self.get_traits_containing_item(name.node);
3415 self.trait_map.insert(expr.id, traits);
3423 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3424 debug!("(getting traits containing item) looking for '{}'", name);
3426 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3427 debug!("(adding trait info) found trait {:?} for method '{}'",
3430 found_traits.push(trait_def_id);
3433 let mut found_traits = Vec::new();
3434 let mut search_module = self.current_module;
3436 // Look for the current trait.
3437 match self.current_trait_ref {
3438 Some((trait_def_id, _)) => {
3439 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3440 add_trait_info(&mut found_traits, trait_def_id, name);
3443 None => {} // Nothing to do.
3446 // Look for trait children.
3447 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3449 for (&(_, ns), name_binding) in search_module.children.borrow().iter() {
3450 if ns != TypeNS { continue }
3451 let trait_def_id = match name_binding.def() {
3452 Some(Def::Trait(trait_def_id)) => trait_def_id,
3453 Some(..) | None => continue,
3455 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3456 add_trait_info(&mut found_traits, trait_def_id, name);
3460 // Look for imports.
3461 for (&(_, ns), import) in search_module.import_resolutions.borrow().iter() {
3462 if ns != TypeNS { continue }
3463 let target = match import.target {
3464 Some(ref target) => target,
3467 let did = match target.binding.def() {
3468 Some(Def::Trait(trait_def_id)) => trait_def_id,
3469 Some(..) | None => continue,
3471 if self.trait_item_map.contains_key(&(name, did)) {
3472 add_trait_info(&mut found_traits, did, name);
3473 let trait_name = self.get_trait_name(did);
3474 self.record_import_use(trait_name, TypeNS, &import);
3478 match search_module.parent_link {
3479 NoParentLink | ModuleParentLink(..) => break,
3480 BlockParentLink(parent_module, _) => {
3481 search_module = parent_module;
3489 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3490 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3491 assert!(match resolution.last_private {
3492 LastImport{..} => false,
3495 "Import should only be used for `use` directives");
3497 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3498 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3499 self.session.span_bug(span,
3500 &format!("path resolved multiple times ({:?} before, {:?} now)",
3506 fn enforce_default_binding_mode(&mut self,
3508 pat_binding_mode: BindingMode,
3510 match pat_binding_mode {
3511 BindByValue(_) => {}
3515 ResolutionError::CannotUseRefBindingModeWith(descr));
3522 fn names_to_string(names: &[Name]) -> String {
3523 let mut first = true;
3524 let mut result = String::new();
3529 result.push_str("::")
3531 result.push_str(&name.as_str());
3536 fn path_names_to_string(path: &Path, depth: usize) -> String {
3537 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3539 .map(|seg| seg.identifier.name)
3541 names_to_string(&names[..])
3544 /// A somewhat inefficient routine to obtain the name of a module.
3545 fn module_to_string<'a>(module: Module<'a>) -> String {
3546 let mut names = Vec::new();
3548 fn collect_mod<'a>(names: &mut Vec<ast::Name>, module: Module<'a>) {
3549 match module.parent_link {
3551 ModuleParentLink(ref module, name) => {
3553 collect_mod(names, module);
3555 BlockParentLink(ref module, _) => {
3556 // danger, shouldn't be ident?
3557 names.push(special_idents::opaque.name);
3558 collect_mod(names, module);
3562 collect_mod(&mut names, module);
3564 if names.is_empty() {
3565 return "???".to_string();
3567 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3570 fn err_path_resolution() -> PathResolution {
3573 last_private: LastMod(AllPublic),
3579 pub struct CrateMap {
3580 pub def_map: RefCell<DefMap>,
3581 pub freevars: FreevarMap,
3582 pub export_map: ExportMap,
3583 pub trait_map: TraitMap,
3584 pub external_exports: ExternalExports,
3585 pub glob_map: Option<GlobMap>,
3588 #[derive(PartialEq,Copy, Clone)]
3589 pub enum MakeGlobMap {
3594 /// Entry point to crate resolution.
3595 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3596 ast_map: &'a hir_map::Map<'tcx>,
3597 make_glob_map: MakeGlobMap)
3599 let krate = ast_map.krate();
3600 let arenas = Resolver::arenas();
3601 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3603 resolver.resolve_crate(krate);
3605 check_unused::check_crate(&mut resolver, krate);
3608 def_map: resolver.def_map,
3609 freevars: resolver.freevars,
3610 export_map: resolver.export_map,
3611 trait_map: resolver.trait_map,
3612 external_exports: resolver.external_exports,
3613 glob_map: if resolver.make_glob_map {
3614 Some(resolver.glob_map)
3621 /// Builds a name resolution walker to be used within this module,
3622 /// or used externally, with an optional callback function.
3624 /// The callback takes a &mut bool which allows callbacks to end a
3625 /// walk when set to true, passing through the rest of the walk, while
3626 /// preserving the ribs + current module. This allows resolve_path
3627 /// calls to be made with the correct scope info. The node in the
3628 /// callback corresponds to the current node in the walk.
3629 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3630 ast_map: &'a hir_map::Map<'tcx>,
3632 make_glob_map: MakeGlobMap,
3633 arenas: &'a ResolverArenas<'a>,
3634 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3635 -> Resolver<'a, 'tcx> {
3636 let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
3638 resolver.callback = callback;
3640 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3642 resolve_imports::resolve_imports(&mut resolver);
3647 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }