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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_resolve"]
14 #![unstable(feature = "rustc_private", issue = "27812")]
15 #![cfg_attr(stage0, staged_api)]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20 html_root_url = "https://doc.rust-lang.org/nightly/")]
22 #![feature(associated_consts)]
23 #![feature(borrow_state)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(staged_api)]
34 extern crate rustc_bitflags;
35 extern crate rustc_front;
39 use self::PatternBindingMode::*;
40 use self::Namespace::*;
41 use self::NamespaceResult::*;
42 use self::ResolveResult::*;
43 use self::FallbackSuggestion::*;
44 use self::TypeParameters::*;
46 use self::UseLexicalScopeFlag::*;
47 use self::ModulePrefixResult::*;
48 use self::AssocItemResolveResult::*;
49 use self::NameSearchType::*;
50 use self::BareIdentifierPatternResolution::*;
51 use self::ParentLink::*;
52 use self::FallbackChecks::*;
54 use rustc::front::map as hir_map;
55 use rustc::session::Session;
57 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
58 use rustc::middle::def::*;
59 use rustc::middle::def_id::DefId;
60 use rustc::middle::pat_util::pat_bindings;
61 use rustc::middle::privacy::*;
62 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
63 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
64 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
67 use syntax::ast::{CRATE_NODE_ID, Ident, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
68 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
69 use syntax::attr::AttrMetaMethods;
70 use syntax::parse::token::{self, special_names, special_idents};
71 use syntax::codemap::{self, Span, Pos};
72 use syntax::util::lev_distance::{lev_distance, max_suggestion_distance};
74 use rustc_front::intravisit::{self, FnKind, Visitor};
76 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
77 use rustc_front::hir::Crate;
78 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprField};
79 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
80 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
81 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
82 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
83 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
84 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
85 use rustc_front::hir::Local;
86 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
87 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
88 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
89 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
90 use rustc_front::util::walk_pat;
92 use std::collections::{HashMap, HashSet};
93 use std::cell::{Cell, RefCell};
95 use std::mem::replace;
96 use std::rc::{Rc, Weak};
99 use resolve_imports::{Target, ImportDirective, ImportResolution};
100 use resolve_imports::Shadowable;
102 // NB: This module needs to be declared first so diagnostics are
103 // registered before they are used.
108 mod build_reduced_graph;
111 // Perform the callback, not walking deeper if the return is true
112 macro_rules! execute_callback {
113 ($node: expr, $walker: expr) => (
114 if let Some(ref callback) = $walker.callback {
115 if callback($node, &mut $walker.resolved) {
122 enum SuggestionType {
128 pub enum ResolutionError<'a> {
129 /// error E0401: can't use type parameters from outer function
130 TypeParametersFromOuterFunction,
131 /// error E0402: cannot use an outer type parameter in this context
132 OuterTypeParameterContext,
133 /// error E0403: the name is already used for a type parameter in this type parameter list
134 NameAlreadyUsedInTypeParameterList(Name),
135 /// error E0404: is not a trait
136 IsNotATrait(&'a str),
137 /// error E0405: use of undeclared trait name
138 UndeclaredTraitName(&'a str),
139 /// error E0406: undeclared associated type
140 UndeclaredAssociatedType,
141 /// error E0407: method is not a member of trait
142 MethodNotMemberOfTrait(Name, &'a str),
143 /// error E0437: type is not a member of trait
144 TypeNotMemberOfTrait(Name, &'a str),
145 /// error E0438: const is not a member of trait
146 ConstNotMemberOfTrait(Name, &'a str),
147 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
148 VariableNotBoundInPattern(Name, usize),
149 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
150 VariableBoundWithDifferentMode(Name, usize),
151 /// error E0410: variable from pattern is not bound in pattern #1
152 VariableNotBoundInParentPattern(Name, usize),
153 /// error E0411: use of `Self` outside of an impl or trait
154 SelfUsedOutsideImplOrTrait,
155 /// error E0412: use of undeclared
156 UseOfUndeclared(&'a str, &'a str),
157 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
158 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
159 /// error E0414: only irrefutable patterns allowed here
160 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
161 /// error E0415: identifier is bound more than once in this parameter list
162 IdentifierBoundMoreThanOnceInParameterList(&'a str),
163 /// error E0416: identifier is bound more than once in the same pattern
164 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
165 /// error E0417: static variables cannot be referenced in a pattern
166 StaticVariableReference,
167 /// error E0418: is not an enum variant, struct or const
168 NotAnEnumVariantStructOrConst(&'a str),
169 /// error E0419: unresolved enum variant, struct or const
170 UnresolvedEnumVariantStructOrConst(&'a str),
171 /// error E0420: is not an associated const
172 NotAnAssociatedConst(&'a str),
173 /// error E0421: unresolved associated const
174 UnresolvedAssociatedConst(&'a str),
175 /// error E0422: does not name a struct
176 DoesNotNameAStruct(&'a str),
177 /// error E0423: is a struct variant name, but this expression uses it like a function name
178 StructVariantUsedAsFunction(&'a str),
179 /// error E0424: `self` is not available in a static method
180 SelfNotAvailableInStaticMethod,
181 /// error E0425: unresolved name
182 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
183 /// error E0426: use of undeclared label
184 UndeclaredLabel(&'a str),
185 /// error E0427: cannot use `ref` binding mode with ...
186 CannotUseRefBindingModeWith(&'a str),
187 /// error E0428: duplicate definition
188 DuplicateDefinition(&'a str, Name),
189 /// error E0429: `self` imports are only allowed within a { } list
190 SelfImportsOnlyAllowedWithin,
191 /// error E0430: `self` import can only appear once in the list
192 SelfImportCanOnlyAppearOnceInTheList,
193 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
194 SelfImportOnlyInImportListWithNonEmptyPrefix,
195 /// error E0432: unresolved import
196 UnresolvedImport(Option<(&'a str, &'a str)>),
197 /// error E0433: failed to resolve
198 FailedToResolve(&'a str),
199 /// error E0434: can't capture dynamic environment in a fn item
200 CannotCaptureDynamicEnvironmentInFnItem,
201 /// error E0435: attempt to use a non-constant value in a constant
202 AttemptToUseNonConstantValueInConstant,
205 #[derive(Clone, PartialEq, Eq, Debug)]
206 pub enum UnresolvedNameContext {
207 PathIsMod(ast::NodeId),
211 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
212 span: syntax::codemap::Span,
213 resolution_error: ResolutionError<'b>) {
214 if !resolver.emit_errors {
217 match resolution_error {
218 ResolutionError::TypeParametersFromOuterFunction => {
219 span_err!(resolver.session,
222 "can't use type parameters from outer function; try using a local type \
225 ResolutionError::OuterTypeParameterContext => {
226 span_err!(resolver.session,
229 "cannot use an outer type parameter in this context");
231 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
232 span_err!(resolver.session,
235 "the name `{}` is already used for a type parameter in this type parameter \
239 ResolutionError::IsNotATrait(name) => {
240 span_err!(resolver.session, span, E0404, "`{}` is not a trait", name);
242 ResolutionError::UndeclaredTraitName(name) => {
243 span_err!(resolver.session,
246 "use of undeclared trait name `{}`",
249 ResolutionError::UndeclaredAssociatedType => {
250 span_err!(resolver.session, span, E0406, "undeclared associated type");
252 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
253 span_err!(resolver.session,
256 "method `{}` is not a member of trait `{}`",
260 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
261 span_err!(resolver.session,
264 "type `{}` is not a member of trait `{}`",
268 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
269 span_err!(resolver.session,
272 "const `{}` is not a member of trait `{}`",
276 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
277 span_err!(resolver.session,
280 "variable `{}` from pattern #1 is not bound in pattern #{}",
284 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
285 span_err!(resolver.session,
288 "variable `{}` is bound with different mode in pattern #{} than in pattern \
293 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
294 span_err!(resolver.session,
297 "variable `{}` from pattern #{} is not bound in pattern #1",
301 ResolutionError::SelfUsedOutsideImplOrTrait => {
302 span_err!(resolver.session,
305 "use of `Self` outside of an impl or trait");
307 ResolutionError::UseOfUndeclared(kind, name) => {
308 span_err!(resolver.session,
311 "use of undeclared {} `{}`",
315 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
316 span_err!(resolver.session,
319 "declaration of `{}` shadows an enum variant or unit-like struct in scope",
322 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
323 span_err!(resolver.session,
326 "only irrefutable patterns allowed here");
327 resolver.session.span_note(span,
328 "there already is a constant in scope sharing the same \
329 name as this pattern");
330 if let Some(sp) = resolver.ast_map.span_if_local(did) {
331 resolver.session.span_note(sp, "constant defined here");
333 if let Some(directive) = resolver.current_module
337 let item = resolver.ast_map.expect_item(directive.value_id);
338 resolver.session.span_note(item.span, "constant imported here");
341 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
342 span_err!(resolver.session,
345 "identifier `{}` is bound more than once in this parameter list",
348 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
349 span_err!(resolver.session,
352 "identifier `{}` is bound more than once in the same pattern",
355 ResolutionError::StaticVariableReference => {
356 span_err!(resolver.session,
359 "static variables cannot be referenced in a pattern, use a `const` instead");
361 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
362 span_err!(resolver.session,
365 "`{}` is not an enum variant, struct or const",
368 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
369 span_err!(resolver.session,
372 "unresolved enum variant, struct or const `{}`",
375 ResolutionError::NotAnAssociatedConst(name) => {
376 span_err!(resolver.session,
379 "`{}` is not an associated const",
382 ResolutionError::UnresolvedAssociatedConst(name) => {
383 span_err!(resolver.session,
386 "unresolved associated const `{}`",
389 ResolutionError::DoesNotNameAStruct(name) => {
390 span_err!(resolver.session,
393 "`{}` does not name a structure",
396 ResolutionError::StructVariantUsedAsFunction(path_name) => {
397 span_err!(resolver.session,
400 "`{}` is the name of a struct or struct variant, but this expression uses \
401 it like a function name",
404 ResolutionError::SelfNotAvailableInStaticMethod => {
405 span_err!(resolver.session,
408 "`self` is not available in a static method. Maybe a `self` argument is \
411 ResolutionError::UnresolvedName(path, msg, context) => {
412 span_err!(resolver.session,
415 "unresolved name `{}`{}",
420 UnresolvedNameContext::Other => {} // no help available
421 UnresolvedNameContext::PathIsMod(id) => {
422 let mut help_msg = String::new();
423 let parent_id = resolver.ast_map.get_parent_node(id);
424 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
426 ExprField(_, ident) => {
427 help_msg = format!("To reference an item from the \
428 `{module}` module, use \
429 `{module}::{ident}`",
434 ExprMethodCall(ident, _, _) => {
435 help_msg = format!("To call a function from the \
436 `{module}` module, use \
437 `{module}::{ident}(..)`",
442 _ => {} // no help available
446 if !help_msg.is_empty() {
447 resolver.session.fileline_help(span, &help_msg);
452 ResolutionError::UndeclaredLabel(name) => {
453 span_err!(resolver.session,
456 "use of undeclared label `{}`",
459 ResolutionError::CannotUseRefBindingModeWith(descr) => {
460 span_err!(resolver.session,
463 "cannot use `ref` binding mode with {}",
466 ResolutionError::DuplicateDefinition(namespace, name) => {
467 span_err!(resolver.session,
470 "duplicate definition of {} `{}`",
474 ResolutionError::SelfImportsOnlyAllowedWithin => {
475 span_err!(resolver.session,
479 "`self` imports are only allowed within a { } list");
481 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
482 span_err!(resolver.session,
485 "`self` import can only appear once in the list");
487 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
488 span_err!(resolver.session,
491 "`self` import can only appear in an import list with a non-empty prefix");
493 ResolutionError::UnresolvedImport(name) => {
494 let msg = match name {
495 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
496 None => "unresolved import".to_owned(),
498 span_err!(resolver.session, span, E0432, "{}", msg);
500 ResolutionError::FailedToResolve(msg) => {
501 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
503 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
504 span_err!(resolver.session,
508 "can't capture dynamic environment in a fn item; use the || { ... } \
509 closure form instead");
511 ResolutionError::AttemptToUseNonConstantValueInConstant => {
512 span_err!(resolver.session,
515 "attempt to use a non-constant value in a constant");
520 #[derive(Copy, Clone)]
523 binding_mode: BindingMode,
526 // Map from the name in a pattern to its binding mode.
527 type BindingMap = HashMap<Name, BindingInfo>;
529 #[derive(Copy, Clone, PartialEq)]
530 enum PatternBindingMode {
532 LocalIrrefutableMode,
533 ArgumentIrrefutableMode,
536 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
542 /// A NamespaceResult represents the result of resolving an import in
543 /// a particular namespace. The result is either definitely-resolved,
544 /// definitely- unresolved, or unknown.
546 enum NamespaceResult {
547 /// Means that resolve hasn't gathered enough information yet to determine
548 /// whether the name is bound in this namespace. (That is, it hasn't
549 /// resolved all `use` directives yet.)
551 /// Means that resolve has determined that the name is definitely
552 /// not bound in the namespace.
554 /// Means that resolve has determined that the name is bound in the Module
555 /// argument, and specified by the NameBinding argument.
556 BoundResult(Rc<Module>, NameBinding),
559 impl NamespaceResult {
560 fn is_unknown(&self) -> bool {
562 UnknownResult => true,
566 fn is_unbound(&self) -> bool {
568 UnboundResult => true,
574 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
575 fn visit_nested_item(&mut self, item: hir::ItemId) {
576 self.visit_item(self.ast_map.expect_item(item.id))
578 fn visit_item(&mut self, item: &Item) {
579 execute_callback!(hir_map::Node::NodeItem(item), self);
580 self.resolve_item(item);
582 fn visit_arm(&mut self, arm: &Arm) {
583 self.resolve_arm(arm);
585 fn visit_block(&mut self, block: &Block) {
586 execute_callback!(hir_map::Node::NodeBlock(block), self);
587 self.resolve_block(block);
589 fn visit_expr(&mut self, expr: &Expr) {
590 execute_callback!(hir_map::Node::NodeExpr(expr), self);
591 self.resolve_expr(expr);
593 fn visit_local(&mut self, local: &Local) {
594 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
595 self.resolve_local(local);
597 fn visit_ty(&mut self, ty: &Ty) {
598 self.resolve_type(ty);
600 fn visit_generics(&mut self, generics: &Generics) {
601 self.resolve_generics(generics);
603 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
604 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
605 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
607 // error already reported
610 intravisit::walk_poly_trait_ref(self, tref, m);
612 fn visit_variant(&mut self,
613 variant: &hir::Variant,
615 item_id: ast::NodeId) {
616 execute_callback!(hir_map::Node::NodeVariant(variant), self);
617 if let Some(ref dis_expr) = variant.node.disr_expr {
618 // resolve the discriminator expr as a constant
619 self.with_constant_rib(|this| {
620 this.visit_expr(dis_expr);
624 // `intravisit::walk_variant` without the discriminant expression.
625 self.visit_variant_data(&variant.node.data,
631 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
632 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
633 let type_parameters = match foreign_item.node {
634 ForeignItemFn(_, ref generics) => {
635 HasTypeParameters(generics, FnSpace, ItemRibKind)
637 ForeignItemStatic(..) => NoTypeParameters,
639 self.with_type_parameter_rib(type_parameters, |this| {
640 intravisit::walk_foreign_item(this, foreign_item);
643 fn visit_fn(&mut self,
644 function_kind: FnKind<'v>,
645 declaration: &'v FnDecl,
649 let rib_kind = match function_kind {
650 FnKind::ItemFn(_, generics, _, _, _, _) => {
651 self.visit_generics(generics);
654 FnKind::Method(_, sig, _) => {
655 self.visit_generics(&sig.generics);
656 self.visit_explicit_self(&sig.explicit_self);
659 FnKind::Closure => ClosureRibKind(node_id),
661 self.resolve_function(rib_kind, declaration, block);
665 type ErrorMessage = Option<(Span, String)>;
667 enum ResolveResult<T> {
668 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
669 Indeterminate, // Couldn't determine due to unresolved globs.
670 Success(T), // Successfully resolved the import.
673 impl<T> ResolveResult<T> {
674 fn success(&self) -> bool {
682 enum FallbackSuggestion {
687 StaticMethod(String),
691 #[derive(Copy, Clone)]
692 enum TypeParameters<'a> {
694 HasTypeParameters(// Type parameters.
697 // Identifies the things that these parameters
698 // were declared on (type, fn, etc)
701 // The kind of the rib used for type parameters.
705 // The rib kind controls the translation of local
706 // definitions (`DefLocal`) to upvars (`DefUpvar`).
707 #[derive(Copy, Clone, Debug)]
709 // No translation needs to be applied.
712 // We passed through a closure scope at the given node ID.
713 // Translate upvars as appropriate.
714 ClosureRibKind(NodeId /* func id */),
716 // We passed through an impl or trait and are now in one of its
717 // methods. Allow references to ty params that impl or trait
718 // binds. Disallow any other upvars (including other ty params that are
722 // We passed through an item scope. Disallow upvars.
725 // We're in a constant item. Can't refer to dynamic stuff.
729 #[derive(Copy, Clone)]
730 enum UseLexicalScopeFlag {
735 enum ModulePrefixResult {
737 PrefixFound(Rc<Module>, usize),
740 #[derive(Copy, Clone)]
741 enum AssocItemResolveResult {
742 /// Syntax such as `<T>::item`, which can't be resolved until type
745 /// We should have been able to resolve the associated item.
746 ResolveAttempt(Option<PathResolution>),
749 #[derive(Copy, Clone, PartialEq)]
750 enum NameSearchType {
751 /// We're doing a name search in order to resolve a `use` directive.
754 /// We're doing a name search in order to resolve a path type, a path
755 /// expression, or a path pattern.
759 #[derive(Copy, Clone)]
760 enum BareIdentifierPatternResolution {
761 FoundStructOrEnumVariant(Def, LastPrivate),
762 FoundConst(Def, LastPrivate, Name),
763 BareIdentifierPatternUnresolved,
769 bindings: HashMap<Name, DefLike>,
774 fn new(kind: RibKind) -> Rib {
776 bindings: HashMap::new(),
782 /// A definition along with the index of the rib it was found on
784 ribs: Option<(Namespace, usize)>,
789 fn from_def(def: Def) -> Self {
797 /// The link from a module up to its nearest parent node.
798 #[derive(Clone,Debug)]
801 ModuleParentLink(Weak<Module>, Name),
802 BlockParentLink(Weak<Module>, NodeId),
805 /// One node in the tree of modules.
807 parent_link: ParentLink,
808 def: Cell<Option<Def>>,
811 children: RefCell<HashMap<Name, NameBindings>>,
812 imports: RefCell<Vec<ImportDirective>>,
814 // The external module children of this node that were declared with
816 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
818 // The anonymous children of this node. Anonymous children are pseudo-
819 // modules that are implicitly created around items contained within
822 // For example, if we have this:
830 // There will be an anonymous module created around `g` with the ID of the
831 // entry block for `f`.
832 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
834 // The status of resolving each import in this module.
835 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
837 // The number of unresolved globs that this module exports.
838 glob_count: Cell<usize>,
840 // The number of unresolved pub imports (both regular and globs) in this module
841 pub_count: Cell<usize>,
843 // The number of unresolved pub glob imports in this module
844 pub_glob_count: Cell<usize>,
846 // The index of the import we're resolving.
847 resolved_import_count: Cell<usize>,
849 // Whether this module is populated. If not populated, any attempt to
850 // access the children must be preceded with a
851 // `populate_module_if_necessary` call.
852 populated: Cell<bool>,
856 fn new(parent_link: ParentLink,
862 parent_link: parent_link,
864 is_public: is_public,
865 children: RefCell::new(HashMap::new()),
866 imports: RefCell::new(Vec::new()),
867 external_module_children: RefCell::new(HashMap::new()),
868 anonymous_children: RefCell::new(NodeMap()),
869 import_resolutions: RefCell::new(HashMap::new()),
870 glob_count: Cell::new(0),
871 pub_count: Cell::new(0),
872 pub_glob_count: Cell::new(0),
873 resolved_import_count: Cell::new(0),
874 populated: Cell::new(!external),
878 fn def_id(&self) -> Option<DefId> {
879 self.def.get().as_ref().map(Def::def_id)
882 fn is_normal(&self) -> bool {
883 match self.def.get() {
884 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
889 fn is_trait(&self) -> bool {
890 match self.def.get() {
891 Some(DefTrait(_)) => true,
896 fn all_imports_resolved(&self) -> bool {
897 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
898 // it is currently being resolved ! so nope
901 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 fmt::Debug for Module {
931 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
945 flags DefModifiers: u8 {
946 const PUBLIC = 1 << 0,
947 const IMPORTABLE = 1 << 1,
951 // Records a possibly-private value, type, or module definition.
954 modifiers: DefModifiers, // see note in ImportResolution about how to use this
955 def_or_module: DefOrModule,
966 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
967 let modifiers = if module.is_public {
970 DefModifiers::empty()
971 } | DefModifiers::IMPORTABLE;
973 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
976 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
977 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
980 fn module(&self) -> Option<Rc<Module>> {
981 match self.def_or_module {
982 DefOrModule::Module(ref module) => Some(module.clone()),
983 DefOrModule::Def(_) => None,
987 fn def(&self) -> Option<Def> {
988 match self.def_or_module {
989 DefOrModule::Def(def) => Some(def),
990 DefOrModule::Module(ref module) => module.def.get(),
995 // Records at most one definition that a name in a namespace is bound to
996 #[derive(Clone,Debug)]
997 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
1001 NameBinding(Rc::new(RefCell::new(None)))
1004 fn create_from_module(module: Rc<Module>) -> Self {
1005 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
1008 fn set(&self, ns_def: NsDef) {
1009 *self.0.borrow_mut() = Some(ns_def);
1012 fn set_modifiers(&self, modifiers: DefModifiers) {
1013 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
1014 ns_def.modifiers = modifiers
1018 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> {
1022 // Lifted versions of the NsDef methods and fields
1023 fn def(&self) -> Option<Def> {
1024 self.borrow().as_ref().and_then(NsDef::def)
1026 fn module(&self) -> Option<Rc<Module>> {
1027 self.borrow().as_ref().and_then(NsDef::module)
1029 fn span(&self) -> Option<Span> {
1030 self.borrow().as_ref().and_then(|def| def.span)
1032 fn modifiers(&self) -> Option<DefModifiers> {
1033 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
1036 fn defined(&self) -> bool {
1037 self.borrow().is_some()
1040 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1041 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1044 fn is_public(&self) -> bool {
1045 self.defined_with(DefModifiers::PUBLIC)
1048 fn def_and_lp(&self) -> (Def, LastPrivate) {
1049 let def = self.def().unwrap();
1050 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1054 // Records the definitions (at most one for each namespace) that a name is
1056 #[derive(Clone,Debug)]
1057 pub struct NameBindings {
1058 type_ns: NameBinding, // < Meaning in type namespace.
1059 value_ns: NameBinding, // < Meaning in value namespace.
1062 impl ::std::ops::Index<Namespace> for NameBindings {
1063 type Output = NameBinding;
1064 fn index(&self, namespace: Namespace) -> &NameBinding {
1065 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1070 fn new() -> NameBindings {
1072 type_ns: NameBinding::new(),
1073 value_ns: NameBinding::new(),
1077 /// Creates a new module in this set of name bindings.
1078 fn define_module(&self, module: Rc<Module>, sp: Span) {
1079 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1082 /// Records a type definition.
1083 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1084 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1085 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1088 /// Records a value definition.
1089 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1090 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1091 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1095 /// Interns the names of the primitive types.
1096 struct PrimitiveTypeTable {
1097 primitive_types: HashMap<Name, PrimTy>,
1100 impl PrimitiveTypeTable {
1101 fn new() -> PrimitiveTypeTable {
1102 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1104 table.intern("bool", TyBool);
1105 table.intern("char", TyChar);
1106 table.intern("f32", TyFloat(TyF32));
1107 table.intern("f64", TyFloat(TyF64));
1108 table.intern("isize", TyInt(TyIs));
1109 table.intern("i8", TyInt(TyI8));
1110 table.intern("i16", TyInt(TyI16));
1111 table.intern("i32", TyInt(TyI32));
1112 table.intern("i64", TyInt(TyI64));
1113 table.intern("str", TyStr);
1114 table.intern("usize", TyUint(TyUs));
1115 table.intern("u8", TyUint(TyU8));
1116 table.intern("u16", TyUint(TyU16));
1117 table.intern("u32", TyUint(TyU32));
1118 table.intern("u64", TyUint(TyU64));
1123 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1124 self.primitive_types.insert(token::intern(string), primitive_type);
1128 /// The main resolver class.
1129 pub struct Resolver<'a, 'tcx: 'a> {
1130 session: &'a Session,
1132 ast_map: &'a hir_map::Map<'tcx>,
1134 graph_root: Rc<Module>,
1136 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1138 structs: FnvHashMap<DefId, Vec<Name>>,
1140 // The number of imports that are currently unresolved.
1141 unresolved_imports: usize,
1143 // The module that represents the current item scope.
1144 current_module: Rc<Module>,
1146 // The current set of local scopes, for values.
1147 // FIXME #4948: Reuse ribs to avoid allocation.
1148 value_ribs: Vec<Rib>,
1150 // The current set of local scopes, for types.
1151 type_ribs: Vec<Rib>,
1153 // The current set of local scopes, for labels.
1154 label_ribs: Vec<Rib>,
1156 // The trait that the current context can refer to.
1157 current_trait_ref: Option<(DefId, TraitRef)>,
1159 // The current self type if inside an impl (used for better errors).
1160 current_self_type: Option<Ty>,
1162 // The idents for the primitive types.
1163 primitive_type_table: PrimitiveTypeTable,
1165 def_map: RefCell<DefMap>,
1166 freevars: FreevarMap,
1167 freevars_seen: NodeMap<NodeMap<usize>>,
1168 export_map: ExportMap,
1169 trait_map: TraitMap,
1170 external_exports: ExternalExports,
1172 // Whether or not to print error messages. Can be set to true
1173 // when getting additional info for error message suggestions,
1174 // so as to avoid printing duplicate errors
1177 make_glob_map: bool,
1178 // Maps imports to the names of items actually imported (this actually maps
1179 // all imports, but only glob imports are actually interesting).
1182 used_imports: HashSet<(NodeId, Namespace)>,
1183 used_crates: HashSet<CrateNum>,
1185 // Callback function for intercepting walks
1186 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1187 // The intention is that the callback modifies this flag.
1188 // Once set, the resolver falls out of the walk, preserving the ribs.
1192 #[derive(PartialEq)]
1193 enum FallbackChecks {
1195 OnlyTraitAndStatics,
1198 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1199 fn new(session: &'a Session,
1200 ast_map: &'a hir_map::Map<'tcx>,
1201 make_glob_map: MakeGlobMap)
1202 -> Resolver<'a, 'tcx> {
1203 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1204 let graph_root = Module::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1211 // The outermost module has def ID 0; this is not reflected in the
1213 graph_root: graph_root.clone(),
1215 trait_item_map: FnvHashMap(),
1216 structs: FnvHashMap(),
1218 unresolved_imports: 0,
1220 current_module: graph_root,
1221 value_ribs: Vec::new(),
1222 type_ribs: Vec::new(),
1223 label_ribs: Vec::new(),
1225 current_trait_ref: None,
1226 current_self_type: None,
1228 primitive_type_table: PrimitiveTypeTable::new(),
1230 def_map: RefCell::new(NodeMap()),
1231 freevars: NodeMap(),
1232 freevars_seen: NodeMap(),
1233 export_map: NodeMap(),
1234 trait_map: NodeMap(),
1235 used_imports: HashSet::new(),
1236 used_crates: HashSet::new(),
1237 external_exports: DefIdSet(),
1240 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1241 glob_map: HashMap::new(),
1249 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1250 if !self.make_glob_map {
1253 if self.glob_map.contains_key(&import_id) {
1254 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1258 let mut new_set = HashSet::new();
1259 new_set.insert(name);
1260 self.glob_map.insert(import_id, new_set);
1263 fn get_trait_name(&self, did: DefId) -> Name {
1264 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1265 self.ast_map.expect_item(node_id).name
1267 self.session.cstore.item_name(did)
1271 /// Checks that the names of external crates don't collide with other
1272 /// external crates.
1273 fn check_for_conflicts_between_external_crates(&self,
1277 if module.external_module_children.borrow().contains_key(&name) {
1278 span_err!(self.session,
1281 "an external crate named `{}` has already been imported into this module",
1286 /// Checks that the names of items don't collide with external crates.
1287 fn check_for_conflicts_between_external_crates_and_items(&self,
1291 if module.external_module_children.borrow().contains_key(&name) {
1292 span_err!(self.session,
1295 "the name `{}` conflicts with an external crate that has been imported \
1301 /// Resolves the given module path from the given root `module_`.
1302 fn resolve_module_path_from_root(&mut self,
1303 module_: Rc<Module>,
1304 module_path: &[Name],
1307 name_search_type: NameSearchType,
1309 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1310 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1311 match module.external_module_children.borrow().get(&needle) {
1312 Some(_) => Some(module.clone()),
1313 None => match module.parent_link {
1314 ModuleParentLink(ref parent, _) => {
1315 search_parent_externals(needle, &parent.upgrade().unwrap())
1322 let mut search_module = module_;
1323 let mut index = index;
1324 let module_path_len = module_path.len();
1325 let mut closest_private = lp;
1327 // Resolve the module part of the path. This does not involve looking
1328 // upward though scope chains; we simply resolve names directly in
1329 // modules as we go.
1330 while index < module_path_len {
1331 let name = module_path[index];
1332 match self.resolve_name_in_module(search_module.clone(),
1338 let segment_name = name.as_str();
1339 let module_name = module_to_string(&*search_module);
1340 let mut span = span;
1341 let msg = if "???" == &module_name[..] {
1342 span.hi = span.lo + Pos::from_usize(segment_name.len());
1344 match search_parent_externals(name, &self.current_module) {
1346 let path_str = names_to_string(module_path);
1347 let target_mod_str = module_to_string(&*module);
1348 let current_mod_str = module_to_string(&*self.current_module);
1350 let prefix = if target_mod_str == current_mod_str {
1351 "self::".to_string()
1353 format!("{}::", target_mod_str)
1356 format!("Did you mean `{}{}`?", prefix, path_str)
1358 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1361 format!("Could not find `{}` in `{}`", segment_name, module_name)
1364 return Failed(Some((span, msg)));
1366 Failed(err) => return Failed(err),
1368 debug!("(resolving module path for import) module resolution is \
1371 return Indeterminate;
1373 Success((target, used_proxy)) => {
1374 // Check to see whether there are type bindings, and, if
1375 // so, whether there is a module within.
1376 if let Some(module_def) = target.binding.module() {
1377 // track extern crates for unused_extern_crate lint
1378 if let Some(did) = module_def.def_id() {
1379 self.used_crates.insert(did.krate);
1382 search_module = module_def;
1384 // Keep track of the closest private module used
1385 // when resolving this import chain.
1386 if !used_proxy && !search_module.is_public {
1387 if let Some(did) = search_module.def_id() {
1388 closest_private = LastMod(DependsOn(did));
1392 let msg = format!("Not a module `{}`", name);
1393 return Failed(Some((span, msg)));
1401 return Success((search_module, closest_private));
1404 /// Attempts to resolve the module part of an import directive or path
1405 /// rooted at the given module.
1407 /// On success, returns the resolved module, and the closest *private*
1408 /// module found to the destination when resolving this path.
1409 fn resolve_module_path(&mut self,
1410 module_: Rc<Module>,
1411 module_path: &[Name],
1412 use_lexical_scope: UseLexicalScopeFlag,
1414 name_search_type: NameSearchType)
1415 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1416 let module_path_len = module_path.len();
1417 assert!(module_path_len > 0);
1419 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1420 names_to_string(module_path),
1421 module_to_string(&*module_));
1423 // Resolve the module prefix, if any.
1424 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1429 match module_prefix_result {
1431 let mpath = names_to_string(module_path);
1432 let mpath = &mpath[..];
1433 match mpath.rfind(':') {
1435 let msg = format!("Could not find `{}` in `{}`",
1436 // idx +- 1 to account for the
1437 // colons on either side
1440 return Failed(Some((span, msg)));
1443 return Failed(None);
1447 Failed(err) => return Failed(err),
1449 debug!("(resolving module path for import) indeterminate; bailing");
1450 return Indeterminate;
1452 Success(NoPrefixFound) => {
1453 // There was no prefix, so we're considering the first element
1454 // of the path. How we handle this depends on whether we were
1455 // instructed to use lexical scope or not.
1456 match use_lexical_scope {
1457 DontUseLexicalScope => {
1458 // This is a crate-relative path. We will start the
1459 // resolution process at index zero.
1460 search_module = self.graph_root.clone();
1462 last_private = LastMod(AllPublic);
1464 UseLexicalScope => {
1465 // This is not a crate-relative path. We resolve the
1466 // first component of the path in the current lexical
1467 // scope and then proceed to resolve below that.
1468 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1469 Failed(err) => return Failed(err),
1471 debug!("(resolving module path for import) indeterminate; bailing");
1472 return Indeterminate;
1474 Success(containing_module) => {
1475 search_module = containing_module;
1477 last_private = LastMod(AllPublic);
1483 Success(PrefixFound(ref containing_module, index)) => {
1484 search_module = containing_module.clone();
1485 start_index = index;
1486 last_private = LastMod(DependsOn(containing_module.def_id()
1491 self.resolve_module_path_from_root(search_module,
1499 /// Invariant: This must only be called during main resolution, not during
1500 /// import resolution.
1501 fn resolve_item_in_lexical_scope(&mut self,
1502 module_: Rc<Module>,
1504 namespace: Namespace)
1505 -> ResolveResult<(Target, bool)> {
1506 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1509 module_to_string(&*module_));
1511 // The current module node is handled specially. First, check for
1512 // its immediate children.
1513 build_reduced_graph::populate_module_if_necessary(self, &module_);
1515 match module_.children.borrow().get(&name) {
1516 Some(name_bindings) if name_bindings[namespace].defined() => {
1517 debug!("top name bindings succeeded");
1518 return Success((Target::new(module_.clone(),
1519 name_bindings[namespace].clone(),
1524 // Not found; continue.
1528 // Now check for its import directives. We don't have to have resolved
1529 // all its imports in the usual way; this is because chains of
1530 // adjacent import statements are processed as though they mutated the
1532 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1533 match (*import_resolution).target_for_namespace(namespace) {
1535 // Not found; continue.
1536 debug!("(resolving item in lexical scope) found import resolution, but not \
1541 debug!("(resolving item in lexical scope) using import resolution");
1542 // track used imports and extern crates as well
1543 let id = import_resolution.id(namespace);
1544 self.used_imports.insert((id, namespace));
1545 self.record_import_use(id, name);
1546 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1547 self.used_crates.insert(kid);
1549 return Success((target, false));
1554 // Search for external modules.
1555 if namespace == TypeNS {
1556 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1557 let child = module_.external_module_children.borrow().get(&name).cloned();
1558 if let Some(module) = child {
1559 let name_binding = NameBinding::create_from_module(module);
1560 debug!("lower name bindings succeeded");
1561 return Success((Target::new(module_, name_binding, Shadowable::Never),
1566 // Finally, proceed up the scope chain looking for parent modules.
1567 let mut search_module = module_;
1569 // Go to the next parent.
1570 match search_module.parent_link.clone() {
1572 // No more parents. This module was unresolved.
1573 debug!("(resolving item in lexical scope) unresolved module");
1574 return Failed(None);
1576 ModuleParentLink(parent_module_node, _) => {
1577 if search_module.is_normal() {
1578 // We stop the search here.
1579 debug!("(resolving item in lexical scope) unresolved module: not \
1580 searching through module parents");
1581 return Failed(None);
1583 search_module = parent_module_node.upgrade().unwrap();
1586 BlockParentLink(ref parent_module_node, _) => {
1587 search_module = parent_module_node.upgrade().unwrap();
1591 // Resolve the name in the parent module.
1592 match self.resolve_name_in_module(search_module.clone(),
1597 Failed(Some((span, msg))) => {
1598 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1600 Failed(None) => (), // Continue up the search chain.
1602 // We couldn't see through the higher scope because of an
1603 // unresolved import higher up. Bail.
1605 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1606 return Indeterminate;
1608 Success((target, used_reexport)) => {
1609 // We found the module.
1610 debug!("(resolving item in lexical scope) found name in module, done");
1611 return Success((target, used_reexport));
1617 /// Resolves a module name in the current lexical scope.
1618 fn resolve_module_in_lexical_scope(&mut self,
1619 module_: Rc<Module>,
1621 -> ResolveResult<Rc<Module>> {
1622 // If this module is an anonymous module, resolve the item in the
1623 // lexical scope. Otherwise, resolve the item from the crate root.
1624 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1625 match resolve_result {
1626 Success((target, _)) => {
1627 if let Some(module_def) = target.binding.module() {
1628 return Success(module_def)
1630 debug!("!!! (resolving module in lexical scope) module \
1631 wasn't actually a module!");
1632 return Failed(None);
1636 debug!("(resolving module in lexical scope) indeterminate; bailing");
1637 return Indeterminate;
1640 debug!("(resolving module in lexical scope) failed to resolve");
1646 /// Returns the nearest normal module parent of the given module.
1647 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1648 let mut module_ = module_;
1650 match module_.parent_link.clone() {
1651 NoParentLink => return None,
1652 ModuleParentLink(new_module, _) |
1653 BlockParentLink(new_module, _) => {
1654 let new_module = new_module.upgrade().unwrap();
1655 if new_module.is_normal() {
1656 return Some(new_module);
1658 module_ = new_module;
1664 /// Returns the nearest normal module parent of the given module, or the
1665 /// module itself if it is a normal module.
1666 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1667 if module_.is_normal() {
1670 match self.get_nearest_normal_module_parent(module_.clone()) {
1672 Some(new_module) => new_module,
1676 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1677 /// (b) some chain of `super::`.
1678 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1679 fn resolve_module_prefix(&mut self,
1680 module_: Rc<Module>,
1681 module_path: &[Name])
1682 -> ResolveResult<ModulePrefixResult> {
1683 // Start at the current module if we see `self` or `super`, or at the
1684 // top of the crate otherwise.
1685 let mut i = match &*module_path[0].as_str() {
1688 _ => return Success(NoPrefixFound),
1690 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1692 // Now loop through all the `super`s we find.
1693 while i < module_path.len() && "super" == module_path[i].as_str() {
1694 debug!("(resolving module prefix) resolving `super` at {}",
1695 module_to_string(&*containing_module));
1696 match self.get_nearest_normal_module_parent(containing_module) {
1697 None => return Failed(None),
1698 Some(new_module) => {
1699 containing_module = new_module;
1705 debug!("(resolving module prefix) finished resolving prefix at {}",
1706 module_to_string(&*containing_module));
1708 return Success(PrefixFound(containing_module, i));
1711 /// Attempts to resolve the supplied name in the given module for the
1712 /// given namespace. If successful, returns the target corresponding to
1715 /// The boolean returned on success is an indicator of whether this lookup
1716 /// passed through a public re-export proxy.
1717 fn resolve_name_in_module(&mut self,
1718 module_: Rc<Module>,
1720 namespace: Namespace,
1721 name_search_type: NameSearchType,
1722 allow_private_imports: bool)
1723 -> ResolveResult<(Target, bool)> {
1724 debug!("(resolving name in module) resolving `{}` in `{}`",
1726 module_to_string(&*module_));
1728 // First, check the direct children of the module.
1729 build_reduced_graph::populate_module_if_necessary(self, &module_);
1731 match module_.children.borrow().get(&name) {
1732 Some(name_bindings) if name_bindings[namespace].defined() => {
1733 debug!("(resolving name in module) found node as child");
1734 return Success((Target::new(module_.clone(),
1735 name_bindings[namespace].clone(),
1744 // Next, check the module's imports if necessary.
1746 // If this is a search of all imports, we should be done with glob
1747 // resolution at this point.
1748 if name_search_type == PathSearch {
1749 assert_eq!(module_.glob_count.get(), 0);
1752 // Check the list of resolved imports.
1753 match module_.import_resolutions.borrow().get(&name) {
1754 Some(import_resolution) if allow_private_imports || import_resolution.is_public => {
1756 if import_resolution.is_public && import_resolution.outstanding_references != 0 {
1757 debug!("(resolving name in module) import unresolved; bailing out");
1758 return Indeterminate;
1760 match import_resolution.target_for_namespace(namespace) {
1762 debug!("(resolving name in module) name found, but not in namespace {:?}",
1766 debug!("(resolving name in module) resolved to import");
1767 // track used imports and extern crates as well
1768 let id = import_resolution.id(namespace);
1769 self.used_imports.insert((id, namespace));
1770 self.record_import_use(id, name);
1771 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1772 self.used_crates.insert(kid);
1774 return Success((target, true));
1778 Some(..) | None => {} // Continue.
1781 // Finally, search through external children.
1782 if namespace == TypeNS {
1783 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1784 let child = module_.external_module_children.borrow().get(&name).cloned();
1785 if let Some(module) = child {
1786 let name_binding = NameBinding::create_from_module(module);
1787 return Success((Target::new(module_, name_binding, Shadowable::Never),
1792 // We're out of luck.
1793 debug!("(resolving name in module) failed to resolve `{}`", name);
1794 return Failed(None);
1797 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1798 let index = module_.resolved_import_count.get();
1799 let imports = module_.imports.borrow();
1800 let import_count = imports.len();
1801 if index != import_count {
1803 (*imports)[index].span,
1804 ResolutionError::UnresolvedImport(None));
1807 // Descend into children and anonymous children.
1808 build_reduced_graph::populate_module_if_necessary(self, &module_);
1810 for (_, child_node) in module_.children.borrow().iter() {
1811 match child_node.type_ns.module() {
1815 Some(child_module) => {
1816 self.report_unresolved_imports(child_module);
1821 for (_, module_) in module_.anonymous_children.borrow().iter() {
1822 self.report_unresolved_imports(module_.clone());
1828 // We maintain a list of value ribs and type ribs.
1830 // Simultaneously, we keep track of the current position in the module
1831 // graph in the `current_module` pointer. When we go to resolve a name in
1832 // the value or type namespaces, we first look through all the ribs and
1833 // then query the module graph. When we resolve a name in the module
1834 // namespace, we can skip all the ribs (since nested modules are not
1835 // allowed within blocks in Rust) and jump straight to the current module
1838 // Named implementations are handled separately. When we find a method
1839 // call, we consult the module node to find all of the implementations in
1840 // scope. This information is lazily cached in the module node. We then
1841 // generate a fake "implementation scope" containing all the
1842 // implementations thus found, for compatibility with old resolve pass.
1844 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1845 where F: FnOnce(&mut Resolver)
1847 let orig_module = self.current_module.clone();
1849 // Move down in the graph.
1855 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1857 match orig_module.children.borrow().get(&name) {
1859 debug!("!!! (with scope) didn't find `{}` in `{}`",
1861 module_to_string(&*orig_module));
1863 Some(name_bindings) => {
1864 match name_bindings.type_ns.module() {
1866 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1868 module_to_string(&*orig_module));
1871 self.current_module = module_;
1881 self.current_module = orig_module;
1884 /// Searches the current set of local scopes for labels.
1885 /// Stops after meeting a closure.
1886 fn search_label(&self, name: Name) -> Option<DefLike> {
1887 for rib in self.label_ribs.iter().rev() {
1893 // Do not resolve labels across function boundary
1897 let result = rib.bindings.get(&name).cloned();
1898 if result.is_some() {
1905 fn resolve_crate(&mut self, krate: &hir::Crate) {
1906 debug!("(resolving crate) starting");
1908 intravisit::walk_crate(self, krate);
1911 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1912 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1913 span_err!(self.session,
1916 "user-defined types or type parameters cannot shadow the primitive types");
1920 fn resolve_item(&mut self, item: &Item) {
1921 let name = item.name;
1923 debug!("(resolving item) resolving {}", name);
1926 ItemEnum(_, ref generics) |
1927 ItemTy(_, ref generics) |
1928 ItemStruct(_, ref generics) => {
1929 self.check_if_primitive_type_name(name, item.span);
1931 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1932 |this| intravisit::walk_item(this, item));
1934 ItemFn(_, _, _, _, ref generics, _) => {
1935 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1936 |this| intravisit::walk_item(this, item));
1939 ItemDefaultImpl(_, ref trait_ref) => {
1940 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1942 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1943 self.resolve_implementation(generics,
1950 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1951 self.check_if_primitive_type_name(name, item.span);
1953 // Create a new rib for the trait-wide type parameters.
1954 self.with_type_parameter_rib(HasTypeParameters(generics,
1958 let local_def_id = this.ast_map.local_def_id(item.id);
1959 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1960 this.visit_generics(generics);
1961 walk_list!(this, visit_ty_param_bound, bounds);
1963 for trait_item in trait_items {
1964 match trait_item.node {
1965 hir::ConstTraitItem(_, ref default) => {
1966 // Only impose the restrictions of
1967 // ConstRibKind if there's an actual constant
1968 // expression in a provided default.
1969 if default.is_some() {
1970 this.with_constant_rib(|this| {
1971 intravisit::walk_trait_item(this, trait_item)
1974 intravisit::walk_trait_item(this, trait_item)
1977 hir::MethodTraitItem(ref sig, _) => {
1978 let type_parameters =
1979 HasTypeParameters(&sig.generics,
1982 this.with_type_parameter_rib(type_parameters, |this| {
1983 intravisit::walk_trait_item(this, trait_item)
1986 hir::TypeTraitItem(..) => {
1987 this.check_if_primitive_type_name(trait_item.name,
1989 this.with_type_parameter_rib(NoTypeParameters, |this| {
1990 intravisit::walk_trait_item(this, trait_item)
1999 ItemMod(_) | ItemForeignMod(_) => {
2000 self.with_scope(Some(name), |this| {
2001 intravisit::walk_item(this, item);
2005 ItemConst(..) | ItemStatic(..) => {
2006 self.with_constant_rib(|this| {
2007 intravisit::walk_item(this, item);
2011 ItemUse(ref view_path) => {
2012 // check for imports shadowing primitive types
2013 let check_rename = |this: &Self, id, name| {
2014 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
2015 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2016 this.check_if_primitive_type_name(name, item.span);
2022 match view_path.node {
2023 hir::ViewPathSimple(name, _) => {
2024 check_rename(self, item.id, name);
2026 hir::ViewPathList(ref prefix, ref items) => {
2028 if let Some(name) = item.node.rename() {
2029 check_rename(self, item.node.id(), name);
2033 // Resolve prefix of an import with empty braces (issue #28388)
2034 if items.is_empty() && !prefix.segments.is_empty() {
2035 match self.resolve_crate_relative_path(prefix.span,
2039 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2043 ResolutionError::FailedToResolve(
2044 &path_names_to_string(prefix, 0)));
2053 ItemExternCrate(_) => {
2054 // do nothing, these are just around to be encoded
2059 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2060 where F: FnOnce(&mut Resolver)
2062 match type_parameters {
2063 HasTypeParameters(generics, space, rib_kind) => {
2064 let mut function_type_rib = Rib::new(rib_kind);
2065 let mut seen_bindings = HashSet::new();
2066 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2067 let name = type_parameter.name;
2068 debug!("with_type_parameter_rib: {}", type_parameter.id);
2070 if seen_bindings.contains(&name) {
2072 type_parameter.span,
2073 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2075 seen_bindings.insert(name);
2077 // plain insert (no renaming)
2078 function_type_rib.bindings
2080 DlDef(DefTyParam(space,
2083 .local_def_id(type_parameter.id),
2086 self.type_ribs.push(function_type_rib);
2089 NoTypeParameters => {
2096 match type_parameters {
2097 HasTypeParameters(..) => {
2099 self.type_ribs.pop();
2102 NoTypeParameters => {}
2106 fn with_label_rib<F>(&mut self, f: F)
2107 where F: FnOnce(&mut Resolver)
2109 self.label_ribs.push(Rib::new(NormalRibKind));
2112 self.label_ribs.pop();
2116 fn with_constant_rib<F>(&mut self, f: F)
2117 where F: FnOnce(&mut Resolver)
2119 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2120 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2123 self.type_ribs.pop();
2124 self.value_ribs.pop();
2128 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2129 // Create a value rib for the function.
2130 self.value_ribs.push(Rib::new(rib_kind));
2132 // Create a label rib for the function.
2133 self.label_ribs.push(Rib::new(rib_kind));
2135 // Add each argument to the rib.
2136 let mut bindings_list = HashMap::new();
2137 for argument in &declaration.inputs {
2138 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2140 self.visit_ty(&*argument.ty);
2142 debug!("(resolving function) recorded argument");
2144 intravisit::walk_fn_ret_ty(self, &declaration.output);
2146 // Resolve the function body.
2147 self.visit_block(block);
2149 debug!("(resolving function) leaving function");
2152 self.label_ribs.pop();
2153 self.value_ribs.pop();
2157 fn resolve_trait_reference(&mut self,
2161 -> Result<PathResolution, ()> {
2162 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2163 if let DefTrait(_) = path_res.base_def {
2164 debug!("(resolving trait) found trait def: {:?}", path_res);
2169 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2172 // If it's a typedef, give a note
2173 if let DefTy(..) = path_res.base_def {
2175 .span_note(trait_path.span, "`type` aliases cannot be used for traits");
2182 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2188 fn resolve_generics(&mut self, generics: &Generics) {
2189 for type_parameter in generics.ty_params.iter() {
2190 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2192 for predicate in &generics.where_clause.predicates {
2194 &hir::WherePredicate::BoundPredicate(_) |
2195 &hir::WherePredicate::RegionPredicate(_) => {}
2196 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2197 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2198 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2199 self.record_def(eq_pred.id, path_res.unwrap());
2203 ResolutionError::UndeclaredAssociatedType);
2208 intravisit::walk_generics(self, generics);
2211 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2212 where F: FnOnce(&mut Resolver) -> T
2214 // Handle nested impls (inside fn bodies)
2215 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2216 let result = f(self);
2217 self.current_self_type = previous_value;
2221 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2222 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2224 let mut new_val = None;
2225 let mut new_id = None;
2226 if let Some(trait_ref) = opt_trait_ref {
2227 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2230 assert!(path_res.depth == 0);
2231 self.record_def(trait_ref.ref_id, path_res);
2232 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2233 new_id = Some(path_res.base_def.def_id());
2235 intravisit::walk_trait_ref(self, trait_ref);
2237 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2238 let result = f(self, new_id);
2239 self.current_trait_ref = original_trait_ref;
2243 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2244 where F: FnOnce(&mut Resolver)
2246 let mut self_type_rib = Rib::new(NormalRibKind);
2248 // plain insert (no renaming, types are not currently hygienic....)
2249 let name = special_names::type_self;
2250 self_type_rib.bindings.insert(name, DlDef(self_def));
2251 self.type_ribs.push(self_type_rib);
2254 self.type_ribs.pop();
2258 fn resolve_implementation(&mut self,
2259 generics: &Generics,
2260 opt_trait_reference: &Option<TraitRef>,
2263 impl_items: &[ImplItem]) {
2264 // If applicable, create a rib for the type parameters.
2265 self.with_type_parameter_rib(HasTypeParameters(generics,
2269 // Resolve the type parameters.
2270 this.visit_generics(generics);
2272 // Resolve the trait reference, if necessary.
2273 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2274 // Resolve the self type.
2275 this.visit_ty(self_type);
2277 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2278 this.with_current_self_type(self_type, |this| {
2279 for impl_item in impl_items {
2280 match impl_item.node {
2281 hir::ImplItemKind::Const(..) => {
2282 // If this is a trait impl, ensure the const
2284 this.check_trait_item(impl_item.name,
2286 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2287 this.with_constant_rib(|this| {
2288 intravisit::walk_impl_item(this, impl_item);
2291 hir::ImplItemKind::Method(ref sig, _) => {
2292 // If this is a trait impl, ensure the method
2294 this.check_trait_item(impl_item.name,
2296 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2298 // We also need a new scope for the method-
2299 // specific type parameters.
2300 let type_parameters =
2301 HasTypeParameters(&sig.generics,
2304 this.with_type_parameter_rib(type_parameters, |this| {
2305 intravisit::walk_impl_item(this, impl_item);
2308 hir::ImplItemKind::Type(ref ty) => {
2309 // If this is a trait impl, ensure the type
2311 this.check_trait_item(impl_item.name,
2313 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2325 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2326 where F: FnOnce(Name, &str) -> ResolutionError
2328 // If there is a TraitRef in scope for an impl, then the method must be in the
2330 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2331 if !self.trait_item_map.contains_key(&(name, did)) {
2332 let path_str = path_names_to_string(&trait_ref.path, 0);
2333 resolve_error(self, span, err(name, &*path_str));
2338 fn resolve_local(&mut self, local: &Local) {
2339 // Resolve the type.
2340 walk_list!(self, visit_ty, &local.ty);
2342 // Resolve the initializer.
2343 walk_list!(self, visit_expr, &local.init);
2345 // Resolve the pattern.
2346 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2349 // build a map from pattern identifiers to binding-info's.
2350 // this is done hygienically. This could arise for a macro
2351 // that expands into an or-pattern where one 'x' was from the
2352 // user and one 'x' came from the macro.
2353 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2354 let mut result = HashMap::new();
2355 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2356 let name = path1.node;
2360 binding_mode: binding_mode,
2366 // check that all of the arms in an or-pattern have exactly the
2367 // same set of bindings, with the same binding modes for each.
2368 fn check_consistent_bindings(&mut self, arm: &Arm) {
2369 if arm.pats.is_empty() {
2372 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2373 for (i, p) in arm.pats.iter().enumerate() {
2374 let map_i = self.binding_mode_map(&**p);
2376 for (&key, &binding_0) in &map_0 {
2377 match map_i.get(&key) {
2381 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2383 Some(binding_i) => {
2384 if binding_0.binding_mode != binding_i.binding_mode {
2387 ResolutionError::VariableBoundWithDifferentMode(key,
2394 for (&key, &binding) in &map_i {
2395 if !map_0.contains_key(&key) {
2398 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2404 fn resolve_arm(&mut self, arm: &Arm) {
2405 self.value_ribs.push(Rib::new(NormalRibKind));
2407 let mut bindings_list = HashMap::new();
2408 for pattern in &arm.pats {
2409 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2412 // This has to happen *after* we determine which
2413 // pat_idents are variants
2414 self.check_consistent_bindings(arm);
2416 walk_list!(self, visit_expr, &arm.guard);
2417 self.visit_expr(&*arm.body);
2420 self.value_ribs.pop();
2424 fn resolve_block(&mut self, block: &Block) {
2425 debug!("(resolving block) entering block");
2426 self.value_ribs.push(Rib::new(NormalRibKind));
2428 // Move down in the graph, if there's an anonymous module rooted here.
2429 let orig_module = self.current_module.clone();
2430 match orig_module.anonymous_children.borrow().get(&block.id) {
2434 Some(anonymous_module) => {
2435 debug!("(resolving block) found anonymous module, moving down");
2436 self.current_module = anonymous_module.clone();
2440 // Check for imports appearing after non-item statements.
2441 let mut found_non_item = false;
2442 for statement in &block.stmts {
2443 if let hir::StmtDecl(ref declaration, _) = statement.node {
2444 if let hir::DeclItem(i) = declaration.node {
2445 let i = self.ast_map.expect_item(i.id);
2447 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2448 span_err!(self.session,
2451 "imports are not allowed after non-item statements");
2456 found_non_item = true
2459 found_non_item = true;
2463 // Descend into the block.
2464 intravisit::walk_block(self, block);
2468 self.current_module = orig_module;
2469 self.value_ribs.pop();
2471 debug!("(resolving block) leaving block");
2474 fn resolve_type(&mut self, ty: &Ty) {
2476 TyPath(ref maybe_qself, ref path) => {
2477 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2478 maybe_qself.as_ref(),
2482 // `<T>::a::b::c` is resolved by typeck alone.
2483 TypecheckRequired => {
2484 // Resolve embedded types.
2485 intravisit::walk_ty(self, ty);
2488 ResolveAttempt(resolution) => resolution,
2491 // This is a path in the type namespace. Walk through scopes
2495 // Write the result into the def map.
2496 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2497 path_names_to_string(path, 0),
2500 self.record_def(ty.id, def);
2503 // Keep reporting some errors even if they're ignored above.
2504 self.resolve_path(ty.id, path, 0, TypeNS, true);
2506 let kind = if maybe_qself.is_some() {
2512 let self_type_name = special_idents::type_self.name;
2513 let is_invalid_self_type_name = path.segments.len() > 0 &&
2514 maybe_qself.is_none() &&
2515 path.segments[0].identifier.name ==
2517 if is_invalid_self_type_name {
2520 ResolutionError::SelfUsedOutsideImplOrTrait);
2524 ResolutionError::UseOfUndeclared(
2526 &*path_names_to_string(path,
2535 // Resolve embedded types.
2536 intravisit::walk_ty(self, ty);
2539 fn resolve_pattern(&mut self,
2541 mode: PatternBindingMode,
2542 // Maps idents to the node ID for the (outermost)
2543 // pattern that binds them
2544 bindings_list: &mut HashMap<Name, NodeId>) {
2545 let pat_id = pattern.id;
2546 walk_pat(pattern, |pattern| {
2547 match pattern.node {
2548 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2549 // The meaning of PatIdent with no type parameters
2550 // depends on whether an enum variant or unit-like struct
2551 // with that name is in scope. The probing lookup has to
2552 // be careful not to emit spurious errors. Only matching
2553 // patterns (match) can match nullary variants or
2554 // unit-like structs. For binding patterns (let
2555 // and the LHS of @-patterns), matching such a value is
2556 // simply disallowed (since it's rarely what you want).
2557 let const_ok = mode == RefutableMode && at_rhs.is_none();
2559 let ident = path1.node;
2560 let renamed = ident.name;
2562 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2564 FoundStructOrEnumVariant(def, lp) if const_ok => {
2565 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2568 self.enforce_default_binding_mode(pattern,
2571 self.record_def(pattern.id,
2578 FoundStructOrEnumVariant(..) => {
2582 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2586 FoundConst(def, lp, _) if const_ok => {
2587 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2589 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2590 self.record_def(pattern.id,
2597 FoundConst(def, _, name) => {
2601 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2605 BareIdentifierPatternUnresolved => {
2606 debug!("(resolving pattern) binding `{}`", renamed);
2608 let def_id = self.ast_map.local_def_id(pattern.id);
2609 let def = DefLocal(def_id, pattern.id);
2611 // Record the definition so that later passes
2612 // will be able to distinguish variants from
2613 // locals in patterns.
2615 self.record_def(pattern.id,
2618 last_private: LastMod(AllPublic),
2622 // Add the binding to the local ribs, if it
2623 // doesn't already exist in the bindings list. (We
2624 // must not add it if it's in the bindings list
2625 // because that breaks the assumptions later
2626 // passes make about or-patterns.)
2627 if !bindings_list.contains_key(&renamed) {
2628 let this = &mut *self;
2629 let last_rib = this.value_ribs.last_mut().unwrap();
2630 last_rib.bindings.insert(renamed, DlDef(def));
2631 bindings_list.insert(renamed, pat_id);
2632 } else if mode == ArgumentIrrefutableMode &&
2633 bindings_list.contains_key(&renamed) {
2634 // Forbid duplicate bindings in the same
2639 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2640 &ident.name.as_str())
2642 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2643 // Then this is a duplicate variable in the
2644 // same disjunction, which is an error.
2648 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2649 &ident.name.as_str())
2652 // Else, not bound in the same pattern: do
2658 PatEnum(ref path, _) => {
2659 // This must be an enum variant, struct or const.
2660 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2665 // The below shouldn't happen because all
2666 // qualified paths should be in PatQPath.
2667 TypecheckRequired =>
2668 self.session.span_bug(path.span,
2669 "resolve_possibly_assoc_item claimed
2671 that a path in PatEnum requires typecheck
2673 to resolve, but qualified paths should be
2676 ResolveAttempt(resolution) => resolution,
2678 if let Some(path_res) = resolution {
2679 match path_res.base_def {
2680 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2681 self.record_def(pattern.id, path_res);
2684 resolve_error(&self,
2686 ResolutionError::StaticVariableReference);
2689 // If anything ends up here entirely resolved,
2690 // it's an error. If anything ends up here
2691 // partially resolved, that's OK, because it may
2692 // be a `T::CONST` that typeck will resolve.
2693 if path_res.depth == 0 {
2697 ResolutionError::NotAnEnumVariantStructOrConst(
2706 let const_name = path.segments
2711 let traits = self.get_traits_containing_item(const_name);
2712 self.trait_map.insert(pattern.id, traits);
2713 self.record_def(pattern.id, path_res);
2721 ResolutionError::UnresolvedEnumVariantStructOrConst(
2722 &path.segments.last().unwrap().identifier.name.as_str())
2725 intravisit::walk_path(self, path);
2728 PatQPath(ref qself, ref path) => {
2729 // Associated constants only.
2730 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2735 TypecheckRequired => {
2736 // All `<T>::CONST` should end up here, and will
2737 // require use of the trait map to resolve
2738 // during typechecking.
2739 let const_name = path.segments
2744 let traits = self.get_traits_containing_item(const_name);
2745 self.trait_map.insert(pattern.id, traits);
2746 intravisit::walk_pat(self, pattern);
2749 ResolveAttempt(resolution) => resolution,
2751 if let Some(path_res) = resolution {
2752 match path_res.base_def {
2753 // All `<T as Trait>::CONST` should end up here, and
2754 // have the trait already selected.
2755 DefAssociatedConst(..) => {
2756 self.record_def(pattern.id, path_res);
2762 ResolutionError::NotAnAssociatedConst(
2763 &path.segments.last().unwrap().identifier.name.as_str()
2771 ResolutionError::UnresolvedAssociatedConst(&path.segments
2778 intravisit::walk_pat(self, pattern);
2781 PatStruct(ref path, _, _) => {
2782 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2783 Some(definition) => {
2784 self.record_def(pattern.id, definition);
2787 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2791 ResolutionError::DoesNotNameAStruct(
2792 &*path_names_to_string(path, 0))
2796 intravisit::walk_path(self, path);
2799 PatLit(_) | PatRange(..) => {
2800 intravisit::walk_pat(self, pattern);
2811 fn resolve_bare_identifier_pattern(&mut self,
2814 -> BareIdentifierPatternResolution {
2815 let module = self.current_module.clone();
2816 match self.resolve_item_in_lexical_scope(module, name, ValueNS) {
2817 Success((target, _)) => {
2818 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2820 target.binding.borrow());
2821 match target.binding.def() {
2823 panic!("resolved name in the value namespace to a set of name bindings \
2826 // For the two success cases, this lookup can be
2827 // considered as not having a private component because
2828 // the lookup happened only within the current module.
2829 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2830 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2832 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2833 return FoundConst(def, LastMod(AllPublic), name);
2835 Some(DefStatic(..)) => {
2836 resolve_error(self, span, ResolutionError::StaticVariableReference);
2837 return BareIdentifierPatternUnresolved;
2839 _ => return BareIdentifierPatternUnresolved
2844 panic!("unexpected indeterminate result");
2848 Some((span, msg)) => {
2849 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2854 debug!("(resolve bare identifier pattern) failed to find {}", name);
2855 return BareIdentifierPatternUnresolved;
2860 /// Handles paths that may refer to associated items
2861 fn resolve_possibly_assoc_item(&mut self,
2863 maybe_qself: Option<&hir::QSelf>,
2865 namespace: Namespace,
2867 -> AssocItemResolveResult {
2868 let max_assoc_types;
2872 if qself.position == 0 {
2873 return TypecheckRequired;
2875 max_assoc_types = path.segments.len() - qself.position;
2876 // Make sure the trait is valid.
2877 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2880 max_assoc_types = path.segments.len();
2884 let mut resolution = self.with_no_errors(|this| {
2885 this.resolve_path(id, path, 0, namespace, check_ribs)
2887 for depth in 1..max_assoc_types {
2888 if resolution.is_some() {
2891 self.with_no_errors(|this| {
2892 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2895 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2896 // A module is not a valid type or value.
2899 ResolveAttempt(resolution)
2902 /// If `check_ribs` is true, checks the local definitions first; i.e.
2903 /// doesn't skip straight to the containing module.
2904 /// Skips `path_depth` trailing segments, which is also reflected in the
2905 /// returned value. See `middle::def::PathResolution` for more info.
2906 pub fn resolve_path(&mut self,
2910 namespace: Namespace,
2912 -> Option<PathResolution> {
2913 let span = path.span;
2914 let segments = &path.segments[..path.segments.len() - path_depth];
2916 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2919 let def = self.resolve_crate_relative_path(span, segments, namespace);
2920 return def.map(mk_res);
2923 // Try to find a path to an item in a module.
2924 let unqualified_def = self.resolve_identifier(segments.last().unwrap().identifier,
2928 if segments.len() <= 1 {
2929 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2931 PathResolution::new(def, LastMod(AllPublic), path_depth)
2935 let def = self.resolve_module_relative_path(span, segments, namespace);
2936 match (def, unqualified_def) {
2937 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2939 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2942 "unnecessary qualification".to_string());
2950 // Resolve a single identifier
2951 fn resolve_identifier(&mut self,
2952 identifier: hir::Ident,
2953 namespace: Namespace,
2955 -> Option<LocalDef> {
2956 // First, check to see whether the name is a primitive type.
2957 if namespace == TypeNS {
2958 if let Some(&prim_ty) = self.primitive_type_table
2960 .get(&identifier.unhygienic_name) {
2961 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
2966 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2971 self.resolve_item_by_name_in_lexical_scope(identifier.unhygienic_name, namespace)
2972 .map(LocalDef::from_def)
2975 // Resolve a local definition, potentially adjusting for closures.
2976 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2977 let ribs = match local_def.ribs {
2978 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2979 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2982 let mut def = local_def.def;
2985 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2987 DefLocal(_, node_id) => {
2991 // Nothing to do. Continue.
2993 ClosureRibKind(function_id) => {
2995 let node_def_id = self.ast_map.local_def_id(node_id);
2997 let seen = self.freevars_seen
2999 .or_insert_with(|| NodeMap());
3000 if let Some(&index) = seen.get(&node_id) {
3001 def = DefUpvar(node_def_id, node_id, index, function_id);
3004 let vec = self.freevars
3006 .or_insert_with(|| vec![]);
3007 let depth = vec.len();
3013 def = DefUpvar(node_def_id, node_id, depth, function_id);
3014 seen.insert(node_id, depth);
3016 ItemRibKind | MethodRibKind => {
3017 // This was an attempt to access an upvar inside a
3018 // named function item. This is not allowed, so we
3022 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3025 ConstantItemRibKind => {
3026 // Still doesn't deal with upvars
3029 ResolutionError::AttemptToUseNonConstantValueInConstant);
3035 DefTyParam(..) | DefSelfTy(..) => {
3038 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3039 // Nothing to do. Continue.
3042 // This was an attempt to use a type parameter outside
3047 ResolutionError::TypeParametersFromOuterFunction);
3050 ConstantItemRibKind => {
3052 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3063 // resolve a "module-relative" path, e.g. a::b::c
3064 fn resolve_module_relative_path(&mut self,
3066 segments: &[hir::PathSegment],
3067 namespace: Namespace)
3068 -> Option<(Def, LastPrivate)> {
3069 let module_path = segments.split_last()
3073 .map(|ps| ps.identifier.name)
3074 .collect::<Vec<_>>();
3076 let containing_module;
3078 let current_module = self.current_module.clone();
3079 match self.resolve_module_path(current_module,
3085 let (span, msg) = match err {
3086 Some((span, msg)) => (span, msg),
3088 let msg = format!("Use of undeclared type or module `{}`",
3089 names_to_string(&module_path));
3094 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3097 Indeterminate => panic!("indeterminate unexpected"),
3098 Success((resulting_module, resulting_last_private)) => {
3099 containing_module = resulting_module;
3100 last_private = resulting_last_private;
3104 let name = segments.last().unwrap().identifier.name;
3105 let def = match self.resolve_name_in_module(containing_module.clone(),
3108 NameSearchType::PathSearch,
3110 Success((Target { binding, .. }, _)) => {
3111 let (def, lp) = binding.def_and_lp();
3112 (def, last_private.or(lp))
3116 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3117 self.used_crates.insert(kid);
3122 /// Invariant: This must be called only during main resolution, not during
3123 /// import resolution.
3124 fn resolve_crate_relative_path(&mut self,
3126 segments: &[hir::PathSegment],
3127 namespace: Namespace)
3128 -> Option<(Def, LastPrivate)> {
3129 let module_path = segments.split_last()
3133 .map(|ps| ps.identifier.name)
3134 .collect::<Vec<_>>();
3136 let root_module = self.graph_root.clone();
3138 let containing_module;
3140 match self.resolve_module_path_from_root(root_module,
3145 LastMod(AllPublic)) {
3147 let (span, msg) = match err {
3148 Some((span, msg)) => (span, msg),
3150 let msg = format!("Use of undeclared module `::{}`",
3151 names_to_string(&module_path[..]));
3156 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3161 panic!("indeterminate unexpected");
3164 Success((resulting_module, resulting_last_private)) => {
3165 containing_module = resulting_module;
3166 last_private = resulting_last_private;
3170 let name = segments.last().unwrap().identifier.name;
3171 match self.resolve_name_in_module(containing_module,
3174 NameSearchType::PathSearch,
3176 Success((Target { binding, .. }, _)) => {
3177 let (def, lp) = binding.def_and_lp();
3178 Some((def, last_private.or(lp)))
3184 fn resolve_identifier_in_local_ribs(&mut self,
3186 namespace: Namespace)
3187 -> Option<LocalDef> {
3188 // Check the local set of ribs.
3189 let (name, ribs) = match namespace {
3190 ValueNS => (ident.name, &self.value_ribs),
3191 TypeNS => (ident.unhygienic_name, &self.type_ribs),
3194 for (i, rib) in ribs.iter().enumerate().rev() {
3195 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3198 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3202 return Some(LocalDef {
3203 ribs: Some((namespace, i)),
3208 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3220 fn resolve_item_by_name_in_lexical_scope(&mut self,
3222 namespace: Namespace)
3225 let module = self.current_module.clone();
3226 match self.resolve_item_in_lexical_scope(module, name, namespace) {
3227 Success((target, _)) => {
3228 match target.binding.def() {
3230 // This can happen if we were looking for a type and
3231 // found a module instead. Modules don't have defs.
3232 debug!("(resolving item path by identifier in lexical scope) failed to \
3233 resolve {} after success...",
3238 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3240 // This lookup is "all public" because it only searched
3241 // for one identifier in the current module (couldn't
3242 // have passed through reexports or anything like that.
3248 panic!("unexpected indeterminate result");
3251 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3254 if let Some((span, msg)) = err {
3255 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3263 fn with_no_errors<T, F>(&mut self, f: F) -> T
3264 where F: FnOnce(&mut Resolver) -> T
3266 self.emit_errors = false;
3268 self.emit_errors = true;
3272 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3273 fn extract_path_and_node_id(t: &Ty,
3274 allow: FallbackChecks)
3275 -> Option<(Path, NodeId, FallbackChecks)> {
3277 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3278 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3279 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3280 // This doesn't handle the remaining `Ty` variants as they are not
3281 // that commonly the self_type, it might be interesting to provide
3282 // support for those in future.
3287 fn get_module(this: &mut Resolver,
3289 name_path: &[ast::Name])
3290 -> Option<Rc<Module>> {
3291 let root = this.current_module.clone();
3292 let last_name = name_path.last().unwrap();
3294 if name_path.len() == 1 {
3295 match this.primitive_type_table.primitive_types.get(last_name) {
3298 match this.current_module.children.borrow().get(last_name) {
3299 Some(child) => child.type_ns.module(),
3305 match this.resolve_module_path(root,
3310 Success((module, _)) => Some(module),
3316 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3317 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3318 let sig = match this.ast_map.get(node_id) {
3319 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3320 hir::MethodTraitItem(ref sig, _) => sig,
3323 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3324 hir::ImplItemKind::Method(ref sig, _) => sig,
3329 sig.explicit_self.node == hir::SelfStatic
3331 this.session.cstore.is_static_method(did)
3335 let (path, node_id, allowed) = match self.current_self_type {
3336 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3338 None => return NoSuggestion,
3340 None => return NoSuggestion,
3343 if allowed == Everything {
3344 // Look for a field with the same name in the current self_type.
3345 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3346 Some(DefTy(did, _)) |
3347 Some(DefStruct(did)) |
3348 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3351 if fields.iter().any(|&field_name| name == field_name) {
3356 _ => {} // Self type didn't resolve properly
3360 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3362 // Look for a method in the current self type's impl module.
3363 if let Some(module) = get_module(self, path.span, &name_path) {
3364 if let Some(binding) = module.children.borrow().get(&name) {
3365 if let Some(DefMethod(did)) = binding.value_ns.def() {
3366 if is_static_method(self, did) {
3367 return StaticMethod(path_names_to_string(&path, 0));
3369 if self.current_trait_ref.is_some() {
3371 } else if allowed == Everything {
3378 // Look for a method in the current trait.
3379 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3380 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3381 if is_static_method(self, did) {
3382 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3392 fn find_best_match_for_name(&mut self, name: &str) -> SuggestionType {
3393 let mut maybes: Vec<token::InternedString> = Vec::new();
3394 let mut values: Vec<usize> = Vec::new();
3396 if let Some(macro_name) = self.session.available_macros
3397 .borrow().iter().find(|n| n.as_str() == name) {
3398 return SuggestionType::Macro(format!("{}!", macro_name));
3401 for rib in self.value_ribs.iter().rev() {
3402 for (&k, _) in &rib.bindings {
3403 maybes.push(k.as_str());
3404 values.push(usize::MAX);
3408 let mut smallest = 0;
3409 for (i, other) in maybes.iter().enumerate() {
3410 values[i] = lev_distance(name, &other);
3412 if values[i] <= values[smallest] {
3417 let max_distance = max_suggestion_distance(name);
3418 if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
3420 SuggestionType::Function(maybes[smallest].to_string())
3423 SuggestionType::NotFound
3427 fn resolve_expr(&mut self, expr: &Expr) {
3428 // First, record candidate traits for this expression if it could
3429 // result in the invocation of a method call.
3431 self.record_candidate_traits_for_expr_if_necessary(expr);
3433 // Next, resolve the node.
3435 ExprPath(ref maybe_qself, ref path) => {
3436 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3437 maybe_qself.as_ref(),
3441 // `<T>::a::b::c` is resolved by typeck alone.
3442 TypecheckRequired => {
3443 let method_name = path.segments.last().unwrap().identifier.name;
3444 let traits = self.get_traits_containing_item(method_name);
3445 self.trait_map.insert(expr.id, traits);
3446 intravisit::walk_expr(self, expr);
3449 ResolveAttempt(resolution) => resolution,
3452 // This is a local path in the value namespace. Walk through
3453 // scopes looking for it.
3454 if let Some(path_res) = resolution {
3455 // Check if struct variant
3456 if let DefVariant(_, _, true) = path_res.base_def {
3457 let path_name = path_names_to_string(path, 0);
3461 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3463 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3465 if self.emit_errors {
3466 self.session.fileline_help(expr.span, &msg);
3468 self.session.span_help(expr.span, &msg);
3471 // Write the result into the def map.
3472 debug!("(resolving expr) resolved `{}`",
3473 path_names_to_string(path, 0));
3475 // Partial resolutions will need the set of traits in scope,
3476 // so they can be completed during typeck.
3477 if path_res.depth != 0 {
3478 let method_name = path.segments.last().unwrap().identifier.name;
3479 let traits = self.get_traits_containing_item(method_name);
3480 self.trait_map.insert(expr.id, traits);
3483 self.record_def(expr.id, path_res);
3486 // Be helpful if the name refers to a struct
3487 // (The pattern matching def_tys where the id is in self.structs
3488 // matches on regular structs while excluding tuple- and enum-like
3489 // structs, which wouldn't result in this error.)
3490 let path_name = path_names_to_string(path, 0);
3491 let type_res = self.with_no_errors(|this| {
3492 this.resolve_path(expr.id, path, 0, TypeNS, false)
3494 match type_res.map(|r| r.base_def) {
3495 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3499 ResolutionError::StructVariantUsedAsFunction(
3503 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3505 if self.emit_errors {
3506 self.session.fileline_help(expr.span, &msg);
3508 self.session.span_help(expr.span, &msg);
3512 // Keep reporting some errors even if they're ignored above.
3513 self.resolve_path(expr.id, path, 0, ValueNS, true);
3515 let mut method_scope = false;
3516 self.value_ribs.iter().rev().all(|rib| {
3517 method_scope = match rib.kind {
3518 MethodRibKind => true,
3519 ItemRibKind | ConstantItemRibKind => false,
3520 _ => return true, // Keep advancing
3522 false // Stop advancing
3525 if method_scope && special_names::self_.as_str() == &path_name[..] {
3528 ResolutionError::SelfNotAvailableInStaticMethod);
3530 let last_name = path.segments.last().unwrap().identifier.name;
3531 let mut msg = match self.find_fallback_in_self_type(last_name) {
3533 // limit search to 5 to reduce the number
3534 // of stupid suggestions
3535 match self.find_best_match_for_name(&path_name) {
3536 SuggestionType::Macro(s) => {
3537 format!("the macro `{}`", s)
3539 SuggestionType::Function(s) => format!("`{}`", s),
3540 SuggestionType::NotFound => "".to_string(),
3543 Field => format!("`self.{}`", path_name),
3545 TraitItem => format!("to call `self.{}`", path_name),
3546 TraitMethod(path_str) |
3547 StaticMethod(path_str) =>
3548 format!("to call `{}::{}`", path_str, path_name),
3551 let mut context = UnresolvedNameContext::Other;
3552 if !msg.is_empty() {
3553 msg = format!(". Did you mean {}?", msg);
3555 // we check if this a module and if so, we display a help
3557 let name_path = path.segments.iter()
3558 .map(|seg| seg.identifier.name)
3559 .collect::<Vec<_>>();
3560 let current_module = self.current_module.clone();
3562 match self.resolve_module_path(current_module,
3568 context = UnresolvedNameContext::PathIsMod(expr.id);
3576 ResolutionError::UnresolvedName(
3577 &*path_name, &*msg, context));
3583 intravisit::walk_expr(self, expr);
3586 ExprStruct(ref path, _, _) => {
3587 // Resolve the path to the structure it goes to. We don't
3588 // check to ensure that the path is actually a structure; that
3589 // is checked later during typeck.
3590 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3591 Some(definition) => self.record_def(expr.id, definition),
3593 debug!("(resolving expression) didn't find struct def",);
3597 ResolutionError::DoesNotNameAStruct(
3598 &*path_names_to_string(path, 0))
3603 intravisit::walk_expr(self, expr);
3606 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3607 self.with_label_rib(|this| {
3608 let def_like = DlDef(DefLabel(expr.id));
3611 let rib = this.label_ribs.last_mut().unwrap();
3612 rib.bindings.insert(label.name, def_like);
3615 intravisit::walk_expr(this, expr);
3619 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3620 match self.search_label(label.node.name) {
3624 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3626 Some(DlDef(def @ DefLabel(_))) => {
3627 // Since this def is a label, it is never read.
3628 self.record_def(expr.id,
3631 last_private: LastMod(AllPublic),
3636 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3642 intravisit::walk_expr(self, expr);
3647 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3649 ExprField(_, name) => {
3650 // FIXME(#6890): Even though you can't treat a method like a
3651 // field, we need to add any trait methods we find that match
3652 // the field name so that we can do some nice error reporting
3653 // later on in typeck.
3654 let traits = self.get_traits_containing_item(name.node);
3655 self.trait_map.insert(expr.id, traits);
3657 ExprMethodCall(name, _, _) => {
3658 debug!("(recording candidate traits for expr) recording traits for {}",
3660 let traits = self.get_traits_containing_item(name.node);
3661 self.trait_map.insert(expr.id, traits);
3669 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3670 debug!("(getting traits containing item) looking for '{}'", name);
3672 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3673 debug!("(adding trait info) found trait {:?} for method '{}'",
3676 found_traits.push(trait_def_id);
3679 let mut found_traits = Vec::new();
3680 let mut search_module = self.current_module.clone();
3682 // Look for the current trait.
3683 match self.current_trait_ref {
3684 Some((trait_def_id, _)) => {
3685 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3686 add_trait_info(&mut found_traits, trait_def_id, name);
3689 None => {} // Nothing to do.
3692 // Look for trait children.
3693 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3696 for (_, child_names) in search_module.children.borrow().iter() {
3697 let def = match child_names.type_ns.def() {
3701 let trait_def_id = match def {
3702 DefTrait(trait_def_id) => trait_def_id,
3705 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3706 add_trait_info(&mut found_traits, trait_def_id, name);
3711 // Look for imports.
3712 for (_, import) in search_module.import_resolutions.borrow().iter() {
3713 let target = match import.target_for_namespace(TypeNS) {
3715 Some(target) => target,
3717 let did = match target.binding.def() {
3718 Some(DefTrait(trait_def_id)) => trait_def_id,
3719 Some(..) | None => continue,
3721 if self.trait_item_map.contains_key(&(name, did)) {
3722 add_trait_info(&mut found_traits, did, name);
3723 let id = import.type_id;
3724 self.used_imports.insert((id, TypeNS));
3725 let trait_name = self.get_trait_name(did);
3726 self.record_import_use(id, trait_name);
3727 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3728 self.used_crates.insert(kid);
3733 match search_module.parent_link.clone() {
3734 NoParentLink | ModuleParentLink(..) => break,
3735 BlockParentLink(parent_module, _) => {
3736 search_module = parent_module.upgrade().unwrap();
3744 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3745 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3746 assert!(match resolution.last_private {
3747 LastImport{..} => false,
3750 "Import should only be used for `use` directives");
3752 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3753 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3754 self.session.span_bug(span,
3755 &format!("path resolved multiple times ({:?} before, {:?} now)",
3761 fn enforce_default_binding_mode(&mut self,
3763 pat_binding_mode: BindingMode,
3765 match pat_binding_mode {
3766 BindByValue(_) => {}
3770 ResolutionError::CannotUseRefBindingModeWith(descr));
3778 // Diagnostics are not particularly efficient, because they're rarely
3782 #[allow(dead_code)] // useful for debugging
3783 fn dump_module(&mut self, module_: Rc<Module>) {
3784 debug!("Dump of module `{}`:", module_to_string(&*module_));
3786 debug!("Children:");
3787 build_reduced_graph::populate_module_if_necessary(self, &module_);
3788 for (&name, _) in module_.children.borrow().iter() {
3789 debug!("* {}", name);
3792 debug!("Import resolutions:");
3793 let import_resolutions = module_.import_resolutions.borrow();
3794 for (&name, import_resolution) in import_resolutions.iter() {
3796 match import_resolution.target_for_namespace(ValueNS) {
3798 value_repr = "".to_string();
3801 value_repr = " value:?".to_string();
3807 match import_resolution.target_for_namespace(TypeNS) {
3809 type_repr = "".to_string();
3812 type_repr = " type:?".to_string();
3817 debug!("* {}:{}{}", name, value_repr, type_repr);
3823 fn names_to_string(names: &[Name]) -> String {
3824 let mut first = true;
3825 let mut result = String::new();
3830 result.push_str("::")
3832 result.push_str(&name.as_str());
3837 fn path_names_to_string(path: &Path, depth: usize) -> String {
3838 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3840 .map(|seg| seg.identifier.name)
3842 names_to_string(&names[..])
3845 /// A somewhat inefficient routine to obtain the name of a module.
3846 fn module_to_string(module: &Module) -> String {
3847 let mut names = Vec::new();
3849 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3850 match module.parent_link {
3852 ModuleParentLink(ref module, name) => {
3854 collect_mod(names, &*module.upgrade().unwrap());
3856 BlockParentLink(ref module, _) => {
3857 // danger, shouldn't be ident?
3858 names.push(special_idents::opaque.name);
3859 collect_mod(names, &*module.upgrade().unwrap());
3863 collect_mod(&mut names, module);
3865 if names.is_empty() {
3866 return "???".to_string();
3868 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3872 pub struct CrateMap {
3873 pub def_map: RefCell<DefMap>,
3874 pub freevars: FreevarMap,
3875 pub export_map: ExportMap,
3876 pub trait_map: TraitMap,
3877 pub external_exports: ExternalExports,
3878 pub glob_map: Option<GlobMap>,
3881 #[derive(PartialEq,Copy, Clone)]
3882 pub enum MakeGlobMap {
3887 /// Entry point to crate resolution.
3888 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3889 ast_map: &'a hir_map::Map<'tcx>,
3890 make_glob_map: MakeGlobMap)
3892 let krate = ast_map.krate();
3893 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3895 resolver.resolve_crate(krate);
3896 session.abort_if_errors();
3898 check_unused::check_crate(&mut resolver, krate);
3901 def_map: resolver.def_map,
3902 freevars: resolver.freevars,
3903 export_map: resolver.export_map,
3904 trait_map: resolver.trait_map,
3905 external_exports: resolver.external_exports,
3906 glob_map: if resolver.make_glob_map {
3907 Some(resolver.glob_map)
3914 /// Builds a name resolution walker to be used within this module,
3915 /// or used externally, with an optional callback function.
3917 /// The callback takes a &mut bool which allows callbacks to end a
3918 /// walk when set to true, passing through the rest of the walk, while
3919 /// preserving the ribs + current module. This allows resolve_path
3920 /// calls to be made with the correct scope info. The node in the
3921 /// callback corresponds to the current node in the walk.
3922 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3923 ast_map: &'a hir_map::Map<'tcx>,
3925 make_glob_map: MakeGlobMap,
3926 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3927 -> Resolver<'a, 'tcx> {
3928 let mut resolver = Resolver::new(session, ast_map, make_glob_map);
3930 resolver.callback = callback;
3932 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3933 session.abort_if_errors();
3935 resolve_imports::resolve_imports(&mut resolver);
3936 session.abort_if_errors();
3938 record_exports::record(&mut resolver);
3939 session.abort_if_errors();
3944 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }