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")]
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::metadata::csearch;
58 use rustc::metadata::decoder::{DefLike, DlDef};
59 use rustc::middle::def::*;
60 use rustc::middle::def_id::DefId;
61 use rustc::middle::pat_util::pat_bindings_hygienic;
62 use rustc::middle::privacy::*;
63 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
64 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
65 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
66 use rustc::util::lev_distance::lev_distance;
69 use syntax::ast::{CRATE_NODE_ID, Ident, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
70 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
71 use syntax::attr::AttrMetaMethods;
72 use syntax::ext::mtwt;
73 use syntax::parse::token::{self, special_names, special_idents};
75 use syntax::codemap::{self, Span, Pos};
77 use rustc_front::visit::{self, FnKind, Visitor};
79 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
80 use rustc_front::hir::{ConstImplItem, Crate};
81 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprField};
82 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
83 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
84 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
85 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
86 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
87 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
88 use rustc_front::hir::{Local, MethodImplItem};
89 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
90 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
91 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
92 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
93 use rustc_front::hir::TypeImplItem;
94 use rustc_front::util::walk_pat;
96 use std::collections::{HashMap, HashSet};
97 use std::cell::{Cell, RefCell};
99 use std::mem::replace;
100 use std::rc::{Rc, Weak};
103 use resolve_imports::{Target, ImportDirective, ImportResolution};
104 use resolve_imports::Shadowable;
106 // NB: This module needs to be declared first so diagnostics are
107 // registered before they are used.
112 mod build_reduced_graph;
115 // Perform the callback, not walking deeper if the return is true
116 macro_rules! execute_callback {
117 ($node: expr, $walker: expr) => (
118 if let Some(ref callback) = $walker.callback {
119 if callback($node, &mut $walker.resolved) {
126 pub enum ResolutionError<'a> {
127 /// error E0401: can't use type parameters from outer function
128 TypeParametersFromOuterFunction,
129 /// error E0402: cannot use an outer type parameter in this context
130 OuterTypeParameterContext,
131 /// error E0403: the name is already used for a type parameter in this type parameter list
132 NameAlreadyUsedInTypeParameterList(Name),
133 /// error E0404: is not a trait
134 IsNotATrait(&'a str),
135 /// error E0405: use of undeclared trait name
136 UndeclaredTraitName(&'a str),
137 /// error E0406: undeclared associated type
138 UndeclaredAssociatedType,
139 /// error E0407: method is not a member of trait
140 MethodNotMemberOfTrait(Name, &'a str),
141 /// error E0437: type is not a member of trait
142 TypeNotMemberOfTrait(Name, &'a str),
143 /// error E0438: const is not a member of trait
144 ConstNotMemberOfTrait(Name, &'a str),
145 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
146 VariableNotBoundInPattern(Name, usize),
147 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
148 VariableBoundWithDifferentMode(Name, usize),
149 /// error E0410: variable from pattern is not bound in pattern #1
150 VariableNotBoundInParentPattern(Name, usize),
151 /// error E0411: use of `Self` outside of an impl or trait
152 SelfUsedOutsideImplOrTrait,
153 /// error E0412: use of undeclared
154 UseOfUndeclared(&'a str, &'a str),
155 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
156 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
157 /// error E0414: only irrefutable patterns allowed here
158 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
159 /// error E0415: identifier is bound more than once in this parameter list
160 IdentifierBoundMoreThanOnceInParameterList(&'a str),
161 /// error E0416: identifier is bound more than once in the same pattern
162 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
163 /// error E0417: static variables cannot be referenced in a pattern
164 StaticVariableReference,
165 /// error E0418: is not an enum variant, struct or const
166 NotAnEnumVariantStructOrConst(&'a str),
167 /// error E0419: unresolved enum variant, struct or const
168 UnresolvedEnumVariantStructOrConst(&'a str),
169 /// error E0420: is not an associated const
170 NotAnAssociatedConst(&'a str),
171 /// error E0421: unresolved associated const
172 UnresolvedAssociatedConst(&'a str),
173 /// error E0422: does not name a struct
174 DoesNotNameAStruct(&'a str),
175 /// error E0423: is a struct variant name, but this expression uses it like a function name
176 StructVariantUsedAsFunction(&'a str),
177 /// error E0424: `self` is not available in a static method
178 SelfNotAvailableInStaticMethod,
179 /// error E0425: unresolved name
180 UnresolvedName(&'a str, &'a str),
181 /// error E0426: use of undeclared label
182 UndeclaredLabel(&'a str),
183 /// error E0427: cannot use `ref` binding mode with ...
184 CannotUseRefBindingModeWith(&'a str),
185 /// error E0428: duplicate definition
186 DuplicateDefinition(&'a str, Name),
187 /// error E0429: `self` imports are only allowed within a { } list
188 SelfImportsOnlyAllowedWithin,
189 /// error E0430: `self` import can only appear once in the list
190 SelfImportCanOnlyAppearOnceInTheList,
191 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
192 SelfImportOnlyInImportListWithNonEmptyPrefix,
193 /// error E0432: unresolved import
194 UnresolvedImport(Option<(&'a str, &'a str)>),
195 /// error E0433: failed to resolve
196 FailedToResolve(&'a str),
197 /// error E0434: can't capture dynamic environment in a fn item
198 CannotCaptureDynamicEnvironmentInFnItem,
199 /// error E0435: attempt to use a non-constant value in a constant
200 AttemptToUseNonConstantValueInConstant,
203 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
204 span: syntax::codemap::Span,
205 resolution_error: ResolutionError<'b>) {
206 if !resolver.emit_errors {
209 match resolution_error {
210 ResolutionError::TypeParametersFromOuterFunction => {
211 span_err!(resolver.session,
214 "can't use type parameters from outer function; try using a local type \
217 ResolutionError::OuterTypeParameterContext => {
218 span_err!(resolver.session,
221 "cannot use an outer type parameter in this context");
223 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
224 span_err!(resolver.session,
227 "the name `{}` is already used for a type parameter in this type parameter \
231 ResolutionError::IsNotATrait(name) => {
232 span_err!(resolver.session, span, E0404, "`{}` is not a trait", name);
234 ResolutionError::UndeclaredTraitName(name) => {
235 span_err!(resolver.session,
238 "use of undeclared trait name `{}`",
241 ResolutionError::UndeclaredAssociatedType => {
242 span_err!(resolver.session, span, E0406, "undeclared associated type");
244 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
245 span_err!(resolver.session,
248 "method `{}` is not a member of trait `{}`",
252 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
253 span_err!(resolver.session,
256 "type `{}` is not a member of trait `{}`",
260 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
261 span_err!(resolver.session,
264 "const `{}` is not a member of trait `{}`",
268 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
269 span_err!(resolver.session,
272 "variable `{}` from pattern #1 is not bound in pattern #{}",
276 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
277 span_err!(resolver.session,
280 "variable `{}` is bound with different mode in pattern #{} than in pattern \
285 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
286 span_err!(resolver.session,
289 "variable `{}` from pattern #{} is not bound in pattern #1",
293 ResolutionError::SelfUsedOutsideImplOrTrait => {
294 span_err!(resolver.session,
297 "use of `Self` outside of an impl or trait");
299 ResolutionError::UseOfUndeclared(kind, name) => {
300 span_err!(resolver.session,
303 "use of undeclared {} `{}`",
307 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
308 span_err!(resolver.session,
311 "declaration of `{}` shadows an enum variant or unit-like struct in scope",
314 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
315 span_err!(resolver.session,
318 "only irrefutable patterns allowed here");
319 resolver.session.span_note(span,
320 "there already is a constant in scope sharing the same \
321 name as this pattern");
322 if let Some(sp) = resolver.ast_map.span_if_local(did) {
323 resolver.session.span_note(sp, "constant defined here");
325 if let Some(directive) = resolver.current_module
329 let item = resolver.ast_map.expect_item(directive.value_id);
330 resolver.session.span_note(item.span, "constant imported here");
333 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
334 span_err!(resolver.session,
337 "identifier `{}` is bound more than once in this parameter list",
340 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
341 span_err!(resolver.session,
344 "identifier `{}` is bound more than once in the same pattern",
347 ResolutionError::StaticVariableReference => {
348 span_err!(resolver.session,
351 "static variables cannot be referenced in a pattern, use a `const` instead");
353 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
354 span_err!(resolver.session,
357 "`{}` is not an enum variant, struct or const",
360 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
361 span_err!(resolver.session,
364 "unresolved enum variant, struct or const `{}`",
367 ResolutionError::NotAnAssociatedConst(name) => {
368 span_err!(resolver.session,
371 "`{}` is not an associated const",
374 ResolutionError::UnresolvedAssociatedConst(name) => {
375 span_err!(resolver.session,
378 "unresolved associated const `{}`",
381 ResolutionError::DoesNotNameAStruct(name) => {
382 span_err!(resolver.session,
385 "`{}` does not name a structure",
388 ResolutionError::StructVariantUsedAsFunction(path_name) => {
389 span_err!(resolver.session,
392 "`{}` is the name of a struct or struct variant, but this expression uses \
393 it like a function name",
396 ResolutionError::SelfNotAvailableInStaticMethod => {
397 span_err!(resolver.session,
400 "`self` is not available in a static method. Maybe a `self` argument is \
403 ResolutionError::UnresolvedName(path, name) => {
404 span_err!(resolver.session,
407 "unresolved name `{}`{}",
411 ResolutionError::UndeclaredLabel(name) => {
412 span_err!(resolver.session,
415 "use of undeclared label `{}`",
418 ResolutionError::CannotUseRefBindingModeWith(descr) => {
419 span_err!(resolver.session,
422 "cannot use `ref` binding mode with {}",
425 ResolutionError::DuplicateDefinition(namespace, name) => {
426 span_err!(resolver.session,
429 "duplicate definition of {} `{}`",
433 ResolutionError::SelfImportsOnlyAllowedWithin => {
434 span_err!(resolver.session,
438 "`self` imports are only allowed within a { } list");
440 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
441 span_err!(resolver.session,
444 "`self` import can only appear once in the list");
446 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
447 span_err!(resolver.session,
450 "`self` import can only appear in an import list with a non-empty prefix");
452 ResolutionError::UnresolvedImport(name) => {
453 let msg = match name {
454 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
455 None => "unresolved import".to_owned(),
457 span_err!(resolver.session, span, E0432, "{}", msg);
459 ResolutionError::FailedToResolve(msg) => {
460 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
462 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
463 span_err!(resolver.session,
467 "can't capture dynamic environment in a fn item; use the || { ... } \
468 closure form instead");
470 ResolutionError::AttemptToUseNonConstantValueInConstant => {
471 span_err!(resolver.session,
474 "attempt to use a non-constant value in a constant");
479 #[derive(Copy, Clone)]
482 binding_mode: BindingMode,
485 // Map from the name in a pattern to its binding mode.
486 type BindingMap = HashMap<Name, BindingInfo>;
488 #[derive(Copy, Clone, PartialEq)]
489 enum PatternBindingMode {
491 LocalIrrefutableMode,
492 ArgumentIrrefutableMode,
495 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
501 /// A NamespaceResult represents the result of resolving an import in
502 /// a particular namespace. The result is either definitely-resolved,
503 /// definitely- unresolved, or unknown.
505 enum NamespaceResult {
506 /// Means that resolve hasn't gathered enough information yet to determine
507 /// whether the name is bound in this namespace. (That is, it hasn't
508 /// resolved all `use` directives yet.)
510 /// Means that resolve has determined that the name is definitely
511 /// not bound in the namespace.
513 /// Means that resolve has determined that the name is bound in the Module
514 /// argument, and specified by the NameBinding argument.
515 BoundResult(Rc<Module>, NameBinding),
518 impl NamespaceResult {
519 fn is_unknown(&self) -> bool {
521 UnknownResult => true,
525 fn is_unbound(&self) -> bool {
527 UnboundResult => true,
533 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
534 fn visit_item(&mut self, item: &Item) {
535 execute_callback!(hir_map::Node::NodeItem(item), self);
536 self.resolve_item(item);
538 fn visit_arm(&mut self, arm: &Arm) {
539 self.resolve_arm(arm);
541 fn visit_block(&mut self, block: &Block) {
542 execute_callback!(hir_map::Node::NodeBlock(block), self);
543 self.resolve_block(block);
545 fn visit_expr(&mut self, expr: &Expr) {
546 execute_callback!(hir_map::Node::NodeExpr(expr), self);
547 self.resolve_expr(expr);
549 fn visit_local(&mut self, local: &Local) {
550 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
551 self.resolve_local(local);
553 fn visit_ty(&mut self, ty: &Ty) {
554 self.resolve_type(ty);
556 fn visit_generics(&mut self, generics: &Generics) {
557 self.resolve_generics(generics);
559 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
560 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
561 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
563 // error already reported
566 visit::walk_poly_trait_ref(self, tref, m);
568 fn visit_variant(&mut self,
569 variant: &hir::Variant,
571 item_id: ast::NodeId) {
572 execute_callback!(hir_map::Node::NodeVariant(variant), self);
573 if let Some(ref dis_expr) = variant.node.disr_expr {
574 // resolve the discriminator expr as a constant
575 self.with_constant_rib(|this| {
576 this.visit_expr(&**dis_expr);
580 // `visit::walk_variant` without the discriminant expression.
581 self.visit_variant_data(&variant.node.data,
587 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
588 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
589 let type_parameters = match foreign_item.node {
590 ForeignItemFn(_, ref generics) => {
591 HasTypeParameters(generics, FnSpace, ItemRibKind)
593 ForeignItemStatic(..) => NoTypeParameters,
595 self.with_type_parameter_rib(type_parameters, |this| {
596 visit::walk_foreign_item(this, foreign_item);
599 fn visit_fn(&mut self,
600 function_kind: FnKind<'v>,
601 declaration: &'v FnDecl,
605 let rib_kind = match function_kind {
606 FnKind::ItemFn(_, generics, _, _, _, _) => {
607 self.visit_generics(generics);
610 FnKind::Method(_, sig, _) => {
611 self.visit_generics(&sig.generics);
612 self.visit_explicit_self(&sig.explicit_self);
615 FnKind::Closure(..) => ClosureRibKind(node_id),
617 self.resolve_function(rib_kind, declaration, block);
621 type ErrorMessage = Option<(Span, String)>;
623 enum ResolveResult<T> {
624 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
625 Indeterminate, // Couldn't determine due to unresolved globs.
626 Success(T), // Successfully resolved the import.
629 impl<T> ResolveResult<T> {
630 fn success(&self) -> bool {
638 enum FallbackSuggestion {
643 StaticMethod(String),
647 #[derive(Copy, Clone)]
648 enum TypeParameters<'a> {
650 HasTypeParameters(// Type parameters.
653 // Identifies the things that these parameters
654 // were declared on (type, fn, etc)
657 // The kind of the rib used for type parameters.
661 // The rib kind controls the translation of local
662 // definitions (`DefLocal`) to upvars (`DefUpvar`).
663 #[derive(Copy, Clone, Debug)]
665 // No translation needs to be applied.
668 // We passed through a closure scope at the given node ID.
669 // Translate upvars as appropriate.
670 ClosureRibKind(NodeId /* func id */),
672 // We passed through an impl or trait and are now in one of its
673 // methods. Allow references to ty params that impl or trait
674 // binds. Disallow any other upvars (including other ty params that are
678 // We passed through an item scope. Disallow upvars.
681 // We're in a constant item. Can't refer to dynamic stuff.
685 #[derive(Copy, Clone)]
686 enum UseLexicalScopeFlag {
691 enum ModulePrefixResult {
693 PrefixFound(Rc<Module>, usize),
696 #[derive(Copy, Clone)]
697 enum AssocItemResolveResult {
698 /// Syntax such as `<T>::item`, which can't be resolved until type
701 /// We should have been able to resolve the associated item.
702 ResolveAttempt(Option<PathResolution>),
705 #[derive(Copy, Clone, PartialEq)]
706 enum NameSearchType {
707 /// We're doing a name search in order to resolve a `use` directive.
710 /// We're doing a name search in order to resolve a path type, a path
711 /// expression, or a path pattern.
715 #[derive(Copy, Clone)]
716 enum BareIdentifierPatternResolution {
717 FoundStructOrEnumVariant(Def, LastPrivate),
718 FoundConst(Def, LastPrivate, Name),
719 BareIdentifierPatternUnresolved,
725 bindings: HashMap<Name, DefLike>,
730 fn new(kind: RibKind) -> Rib {
732 bindings: HashMap::new(),
738 /// A definition along with the index of the rib it was found on
740 ribs: Option<(Namespace, usize)>,
745 fn from_def(def: Def) -> Self {
753 /// The link from a module up to its nearest parent node.
754 #[derive(Clone,Debug)]
757 ModuleParentLink(Weak<Module>, Name),
758 BlockParentLink(Weak<Module>, NodeId),
761 /// One node in the tree of modules.
763 parent_link: ParentLink,
764 def: Cell<Option<Def>>,
767 children: RefCell<HashMap<Name, NameBindings>>,
768 imports: RefCell<Vec<ImportDirective>>,
770 // The external module children of this node that were declared with
772 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
774 // The anonymous children of this node. Anonymous children are pseudo-
775 // modules that are implicitly created around items contained within
778 // For example, if we have this:
786 // There will be an anonymous module created around `g` with the ID of the
787 // entry block for `f`.
788 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
790 // The status of resolving each import in this module.
791 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
793 // The number of unresolved globs that this module exports.
794 glob_count: Cell<usize>,
796 // The number of unresolved pub imports (both regular and globs) in this module
797 pub_count: Cell<usize>,
799 // The number of unresolved pub glob imports in this module
800 pub_glob_count: Cell<usize>,
802 // The index of the import we're resolving.
803 resolved_import_count: Cell<usize>,
805 // Whether this module is populated. If not populated, any attempt to
806 // access the children must be preceded with a
807 // `populate_module_if_necessary` call.
808 populated: Cell<bool>,
812 fn new(parent_link: ParentLink,
818 parent_link: parent_link,
820 is_public: is_public,
821 children: RefCell::new(HashMap::new()),
822 imports: RefCell::new(Vec::new()),
823 external_module_children: RefCell::new(HashMap::new()),
824 anonymous_children: RefCell::new(NodeMap()),
825 import_resolutions: RefCell::new(HashMap::new()),
826 glob_count: Cell::new(0),
827 pub_count: Cell::new(0),
828 pub_glob_count: Cell::new(0),
829 resolved_import_count: Cell::new(0),
830 populated: Cell::new(!external),
834 fn def_id(&self) -> Option<DefId> {
835 self.def.get().as_ref().map(Def::def_id)
838 fn is_normal(&self) -> bool {
839 match self.def.get() {
840 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
845 fn is_trait(&self) -> bool {
846 match self.def.get() {
847 Some(DefTrait(_)) => true,
852 fn all_imports_resolved(&self) -> bool {
853 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
854 // it is currently being resolved ! so nope
857 self.imports.borrow().len() == self.resolved_import_count.get()
863 pub fn inc_glob_count(&self) {
864 self.glob_count.set(self.glob_count.get() + 1);
866 pub fn dec_glob_count(&self) {
867 assert!(self.glob_count.get() > 0);
868 self.glob_count.set(self.glob_count.get() - 1);
870 pub fn inc_pub_count(&self) {
871 self.pub_count.set(self.pub_count.get() + 1);
873 pub fn dec_pub_count(&self) {
874 assert!(self.pub_count.get() > 0);
875 self.pub_count.set(self.pub_count.get() - 1);
877 pub fn inc_pub_glob_count(&self) {
878 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
880 pub fn dec_pub_glob_count(&self) {
881 assert!(self.pub_glob_count.get() > 0);
882 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
886 impl fmt::Debug for Module {
887 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
901 flags DefModifiers: u8 {
902 const PUBLIC = 1 << 0,
903 const IMPORTABLE = 1 << 1,
907 // Records a possibly-private definition.
908 // FIXME once #21546 is resolved, the def and module fields will never both be Some,
909 // so they can be refactored into something like Result<Def, Rc<Module>>.
912 modifiers: DefModifiers, // see note in ImportResolution about how to use this
914 module: Option<Rc<Module>>,
919 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
920 let modifiers = if module.is_public {
923 DefModifiers::empty()
924 } | DefModifiers::IMPORTABLE;
926 NsDef { modifiers: modifiers, def: None, module: Some(module), span: span }
929 fn def(&self) -> Option<Def> {
930 match (self.def, &self.module) {
931 (def @ Some(_), _) => def,
932 (_, &Some(ref module)) => module.def.get(),
933 _ => panic!("NsDef has neither a Def nor a Module"),
938 // Records at most one definition that a name in a namespace is bound to
939 #[derive(Clone,Debug)]
940 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
944 NameBinding(Rc::new(RefCell::new(None)))
947 fn create_from_module(module: Rc<Module>) -> Self {
948 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
951 fn set(&self, ns_def: NsDef) {
952 *self.0.borrow_mut() = Some(ns_def);
955 fn set_modifiers(&self, modifiers: DefModifiers) {
956 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
957 ns_def.modifiers = modifiers
961 fn and_then<T, F: Fn(&NsDef) -> Option<T>>(&self, f: F) -> Option<T> {
962 self.borrow().as_ref().and_then(f)
965 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> { self.0.borrow() }
967 // Lifted versions of the NsDef fields and method
968 fn def(&self) -> Option<Def> { self.and_then(NsDef::def) }
969 fn span(&self) -> Option<Span> { self.and_then(|def| def.span) }
970 fn module(&self) -> Option<Rc<Module>> { self.and_then(|def| def.module.clone()) }
971 fn modifiers(&self) -> Option<DefModifiers> { self.and_then(|def| Some(def.modifiers)) }
973 fn defined(&self) -> bool { self.borrow().is_some() }
975 fn defined_with(&self, modifiers: DefModifiers) -> bool {
976 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
979 fn is_public(&self) -> bool {
980 self.defined_with(DefModifiers::PUBLIC)
983 fn def_and_lp(&self) -> (Def, LastPrivate) {
984 let def = self.def().unwrap();
985 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
989 // Records the definitions (at most one for each namespace) that a name is
991 #[derive(Clone,Debug)]
992 pub struct NameBindings {
993 type_ns: NameBinding, // < Meaning in type namespace.
994 value_ns: NameBinding, // < Meaning in value namespace.
997 impl ::std::ops::Index<Namespace> for NameBindings {
998 type Output = NameBinding;
999 fn index(&self, namespace: Namespace) -> &NameBinding {
1000 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1005 fn new() -> NameBindings {
1007 type_ns: NameBinding::new(),
1008 value_ns: NameBinding::new(),
1012 fn create_from_module(module: Rc<Module>) -> NameBindings {
1014 type_ns: NameBinding::create_from_module(module),
1015 value_ns: NameBinding::new(),
1019 /// Creates a new module in this set of name bindings.
1020 fn define_module(&self,
1021 parent_link: ParentLink,
1026 let module = Module::new(parent_link, def, external, is_public);
1027 self.type_ns.set(NsDef::create_from_module(Rc::new(module), Some(sp)));
1030 /// Records a type definition.
1031 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1032 debug!("defining type for def {:?} with modifiers {:?}",
1035 // Merges the type with the existing type def or creates a new one.
1036 self.type_ns.set(NsDef {
1037 modifiers: modifiers, def: Some(def), module: self.type_ns.module(), span: Some(sp)
1041 /// Records a value definition.
1042 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1043 debug!("defining value for def {:?} with modifiers {:?}",
1046 self.value_ns.set(NsDef {
1047 modifiers: modifiers, def: Some(def), module: None, span: Some(sp)
1051 /// Returns the module node if applicable.
1052 fn get_module_if_available(&self) -> Option<Rc<Module>> { self.type_ns.module() }
1054 /// Returns the module node. Panics if this node does not have a module
1056 fn get_module(&self) -> Rc<Module> {
1057 match self.get_module_if_available() {
1059 panic!("get_module called on a node with no module definition!")
1061 Some(module_def) => module_def,
1066 /// Interns the names of the primitive types.
1067 struct PrimitiveTypeTable {
1068 primitive_types: HashMap<Name, PrimTy>,
1071 impl PrimitiveTypeTable {
1072 fn new() -> PrimitiveTypeTable {
1073 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1075 table.intern("bool", TyBool);
1076 table.intern("char", TyChar);
1077 table.intern("f32", TyFloat(TyF32));
1078 table.intern("f64", TyFloat(TyF64));
1079 table.intern("isize", TyInt(TyIs));
1080 table.intern("i8", TyInt(TyI8));
1081 table.intern("i16", TyInt(TyI16));
1082 table.intern("i32", TyInt(TyI32));
1083 table.intern("i64", TyInt(TyI64));
1084 table.intern("str", TyStr);
1085 table.intern("usize", TyUint(TyUs));
1086 table.intern("u8", TyUint(TyU8));
1087 table.intern("u16", TyUint(TyU16));
1088 table.intern("u32", TyUint(TyU32));
1089 table.intern("u64", TyUint(TyU64));
1094 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1095 self.primitive_types.insert(token::intern(string), primitive_type);
1099 /// The main resolver class.
1100 pub struct Resolver<'a, 'tcx: 'a> {
1101 session: &'a Session,
1103 ast_map: &'a hir_map::Map<'tcx>,
1105 graph_root: NameBindings,
1107 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1109 structs: FnvHashMap<DefId, Vec<Name>>,
1111 // The number of imports that are currently unresolved.
1112 unresolved_imports: usize,
1114 // The module that represents the current item scope.
1115 current_module: Rc<Module>,
1117 // The current set of local scopes, for values.
1118 // FIXME #4948: Reuse ribs to avoid allocation.
1119 value_ribs: Vec<Rib>,
1121 // The current set of local scopes, for types.
1122 type_ribs: Vec<Rib>,
1124 // The current set of local scopes, for labels.
1125 label_ribs: Vec<Rib>,
1127 // The trait that the current context can refer to.
1128 current_trait_ref: Option<(DefId, TraitRef)>,
1130 // The current self type if inside an impl (used for better errors).
1131 current_self_type: Option<Ty>,
1133 // The idents for the primitive types.
1134 primitive_type_table: PrimitiveTypeTable,
1136 def_map: RefCell<DefMap>,
1137 freevars: FreevarMap,
1138 freevars_seen: NodeMap<NodeMap<usize>>,
1139 export_map: ExportMap,
1140 trait_map: TraitMap,
1141 external_exports: ExternalExports,
1143 // Whether or not to print error messages. Can be set to true
1144 // when getting additional info for error message suggestions,
1145 // so as to avoid printing duplicate errors
1148 make_glob_map: bool,
1149 // Maps imports to the names of items actually imported (this actually maps
1150 // all imports, but only glob imports are actually interesting).
1153 used_imports: HashSet<(NodeId, Namespace)>,
1154 used_crates: HashSet<CrateNum>,
1156 // Callback function for intercepting walks
1157 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1158 // The intention is that the callback modifies this flag.
1159 // Once set, the resolver falls out of the walk, preserving the ribs.
1163 #[derive(PartialEq)]
1164 enum FallbackChecks {
1166 OnlyTraitAndStatics,
1169 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1170 fn new(session: &'a Session,
1171 ast_map: &'a hir_map::Map<'tcx>,
1173 make_glob_map: MakeGlobMap)
1174 -> Resolver<'a, 'tcx> {
1175 let graph_root = NameBindings::new();
1177 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1178 graph_root.define_module(NoParentLink,
1179 Some(DefMod(root_def_id)),
1184 let current_module = graph_root.get_module();
1191 // The outermost module has def ID 0; this is not reflected in the
1193 graph_root: graph_root,
1195 trait_item_map: FnvHashMap(),
1196 structs: FnvHashMap(),
1198 unresolved_imports: 0,
1200 current_module: current_module,
1201 value_ribs: Vec::new(),
1202 type_ribs: Vec::new(),
1203 label_ribs: Vec::new(),
1205 current_trait_ref: None,
1206 current_self_type: None,
1208 primitive_type_table: PrimitiveTypeTable::new(),
1210 def_map: RefCell::new(NodeMap()),
1211 freevars: NodeMap(),
1212 freevars_seen: NodeMap(),
1213 export_map: NodeMap(),
1214 trait_map: NodeMap(),
1215 used_imports: HashSet::new(),
1216 used_crates: HashSet::new(),
1217 external_exports: DefIdSet(),
1220 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1221 glob_map: HashMap::new(),
1229 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1230 if !self.make_glob_map {
1233 if self.glob_map.contains_key(&import_id) {
1234 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1238 let mut new_set = HashSet::new();
1239 new_set.insert(name);
1240 self.glob_map.insert(import_id, new_set);
1243 fn get_trait_name(&self, did: DefId) -> Name {
1244 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1245 self.ast_map.expect_item(node_id).name
1247 csearch::get_trait_name(&self.session.cstore, did)
1251 /// Checks that the names of external crates don't collide with other
1252 /// external crates.
1253 fn check_for_conflicts_between_external_crates(&self,
1257 if module.external_module_children.borrow().contains_key(&name) {
1258 span_err!(self.session,
1261 "an external crate named `{}` has already been imported into this module",
1266 /// Checks that the names of items don't collide with external crates.
1267 fn check_for_conflicts_between_external_crates_and_items(&self,
1271 if module.external_module_children.borrow().contains_key(&name) {
1272 span_err!(self.session,
1275 "the name `{}` conflicts with an external crate that has been imported \
1281 /// Resolves the given module path from the given root `module_`.
1282 fn resolve_module_path_from_root(&mut self,
1283 module_: Rc<Module>,
1284 module_path: &[Name],
1287 name_search_type: NameSearchType,
1289 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1290 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1291 match module.external_module_children.borrow().get(&needle) {
1292 Some(_) => Some(module.clone()),
1293 None => match module.parent_link {
1294 ModuleParentLink(ref parent, _) => {
1295 search_parent_externals(needle, &parent.upgrade().unwrap())
1302 let mut search_module = module_;
1303 let mut index = index;
1304 let module_path_len = module_path.len();
1305 let mut closest_private = lp;
1307 // Resolve the module part of the path. This does not involve looking
1308 // upward though scope chains; we simply resolve names directly in
1309 // modules as we go.
1310 while index < module_path_len {
1311 let name = module_path[index];
1312 match self.resolve_name_in_module(search_module.clone(),
1318 let segment_name = name.as_str();
1319 let module_name = module_to_string(&*search_module);
1320 let mut span = span;
1321 let msg = if "???" == &module_name[..] {
1322 span.hi = span.lo + Pos::from_usize(segment_name.len());
1324 match search_parent_externals(name, &self.current_module) {
1326 let path_str = names_to_string(module_path);
1327 let target_mod_str = module_to_string(&*module);
1328 let current_mod_str = module_to_string(&*self.current_module);
1330 let prefix = if target_mod_str == current_mod_str {
1331 "self::".to_string()
1333 format!("{}::", target_mod_str)
1336 format!("Did you mean `{}{}`?", prefix, path_str)
1338 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1341 format!("Could not find `{}` in `{}`", segment_name, module_name)
1344 return Failed(Some((span, msg)));
1346 Failed(err) => return Failed(err),
1348 debug!("(resolving module path for import) module resolution is \
1351 return Indeterminate;
1353 Success((target, used_proxy)) => {
1354 // Check to see whether there are type bindings, and, if
1355 // so, whether there is a module within.
1356 if let Some(module_def) = target.binding.module() {
1357 // track extern crates for unused_extern_crate lint
1358 if let Some(did) = module_def.def_id() {
1359 self.used_crates.insert(did.krate);
1362 search_module = module_def;
1364 // Keep track of the closest private module used
1365 // when resolving this import chain.
1366 if !used_proxy && !search_module.is_public {
1367 if let Some(did) = search_module.def_id() {
1368 closest_private = LastMod(DependsOn(did));
1372 let msg = format!("Not a module `{}`", name);
1373 return Failed(Some((span, msg)));
1381 return Success((search_module, closest_private));
1384 /// Attempts to resolve the module part of an import directive or path
1385 /// rooted at the given module.
1387 /// On success, returns the resolved module, and the closest *private*
1388 /// module found to the destination when resolving this path.
1389 fn resolve_module_path(&mut self,
1390 module_: Rc<Module>,
1391 module_path: &[Name],
1392 use_lexical_scope: UseLexicalScopeFlag,
1394 name_search_type: NameSearchType)
1395 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1396 let module_path_len = module_path.len();
1397 assert!(module_path_len > 0);
1399 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1400 names_to_string(module_path),
1401 module_to_string(&*module_));
1403 // Resolve the module prefix, if any.
1404 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1409 match module_prefix_result {
1411 let mpath = names_to_string(module_path);
1412 let mpath = &mpath[..];
1413 match mpath.rfind(':') {
1415 let msg = format!("Could not find `{}` in `{}`",
1416 // idx +- 1 to account for the
1417 // colons on either side
1420 return Failed(Some((span, msg)));
1423 return Failed(None);
1427 Failed(err) => return Failed(err),
1429 debug!("(resolving module path for import) indeterminate; bailing");
1430 return Indeterminate;
1432 Success(NoPrefixFound) => {
1433 // There was no prefix, so we're considering the first element
1434 // of the path. How we handle this depends on whether we were
1435 // instructed to use lexical scope or not.
1436 match use_lexical_scope {
1437 DontUseLexicalScope => {
1438 // This is a crate-relative path. We will start the
1439 // resolution process at index zero.
1440 search_module = self.graph_root.get_module();
1442 last_private = LastMod(AllPublic);
1444 UseLexicalScope => {
1445 // This is not a crate-relative path. We resolve the
1446 // first component of the path in the current lexical
1447 // scope and then proceed to resolve below that.
1448 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1449 Failed(err) => return Failed(err),
1451 debug!("(resolving module path for import) indeterminate; bailing");
1452 return Indeterminate;
1454 Success(containing_module) => {
1455 search_module = containing_module;
1457 last_private = LastMod(AllPublic);
1463 Success(PrefixFound(ref containing_module, index)) => {
1464 search_module = containing_module.clone();
1465 start_index = index;
1466 last_private = LastMod(DependsOn(containing_module.def_id()
1471 self.resolve_module_path_from_root(search_module,
1479 /// Invariant: This must only be called during main resolution, not during
1480 /// import resolution.
1481 fn resolve_item_in_lexical_scope(&mut self,
1482 module_: Rc<Module>,
1484 namespace: Namespace)
1485 -> ResolveResult<(Target, bool)> {
1486 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1489 module_to_string(&*module_));
1491 // The current module node is handled specially. First, check for
1492 // its immediate children.
1493 build_reduced_graph::populate_module_if_necessary(self, &module_);
1495 match module_.children.borrow().get(&name) {
1496 Some(name_bindings) if name_bindings[namespace].defined() => {
1497 debug!("top name bindings succeeded");
1498 return Success((Target::new(module_.clone(),
1499 name_bindings[namespace].clone(),
1504 // Not found; continue.
1508 // Now check for its import directives. We don't have to have resolved
1509 // all its imports in the usual way; this is because chains of
1510 // adjacent import statements are processed as though they mutated the
1512 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1513 match (*import_resolution).target_for_namespace(namespace) {
1515 // Not found; continue.
1516 debug!("(resolving item in lexical scope) found import resolution, but not \
1521 debug!("(resolving item in lexical scope) using import resolution");
1522 // track used imports and extern crates as well
1523 let id = import_resolution.id(namespace);
1524 self.used_imports.insert((id, namespace));
1525 self.record_import_use(id, name);
1526 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1527 self.used_crates.insert(kid);
1529 return Success((target, false));
1534 // Search for external modules.
1535 if namespace == TypeNS {
1536 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1537 let child = module_.external_module_children.borrow().get(&name).cloned();
1538 if let Some(module) = child {
1539 let name_binding = NameBinding::create_from_module(module);
1540 debug!("lower name bindings succeeded");
1541 return Success((Target::new(module_, name_binding, Shadowable::Never),
1546 // Finally, proceed up the scope chain looking for parent modules.
1547 let mut search_module = module_;
1549 // Go to the next parent.
1550 match search_module.parent_link.clone() {
1552 // No more parents. This module was unresolved.
1553 debug!("(resolving item in lexical scope) unresolved module");
1554 return Failed(None);
1556 ModuleParentLink(parent_module_node, _) => {
1557 if search_module.is_normal() {
1558 // We stop the search here.
1559 debug!("(resolving item in lexical scope) unresolved module: not \
1560 searching through module parents");
1561 return Failed(None);
1563 search_module = parent_module_node.upgrade().unwrap();
1566 BlockParentLink(ref parent_module_node, _) => {
1567 search_module = parent_module_node.upgrade().unwrap();
1571 // Resolve the name in the parent module.
1572 match self.resolve_name_in_module(search_module.clone(),
1577 Failed(Some((span, msg))) => {
1578 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1580 Failed(None) => (), // Continue up the search chain.
1582 // We couldn't see through the higher scope because of an
1583 // unresolved import higher up. Bail.
1585 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1586 return Indeterminate;
1588 Success((target, used_reexport)) => {
1589 // We found the module.
1590 debug!("(resolving item in lexical scope) found name in module, done");
1591 return Success((target, used_reexport));
1597 /// Resolves a module name in the current lexical scope.
1598 fn resolve_module_in_lexical_scope(&mut self,
1599 module_: Rc<Module>,
1601 -> ResolveResult<Rc<Module>> {
1602 // If this module is an anonymous module, resolve the item in the
1603 // lexical scope. Otherwise, resolve the item from the crate root.
1604 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1605 match resolve_result {
1606 Success((target, _)) => {
1607 if let Some(module_def) = target.binding.module() {
1608 return Success(module_def)
1610 debug!("!!! (resolving module in lexical scope) module \
1611 wasn't actually a module!");
1612 return Failed(None);
1616 debug!("(resolving module in lexical scope) indeterminate; bailing");
1617 return Indeterminate;
1620 debug!("(resolving module in lexical scope) failed to resolve");
1626 /// Returns the nearest normal module parent of the given module.
1627 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1628 let mut module_ = module_;
1630 match module_.parent_link.clone() {
1631 NoParentLink => return None,
1632 ModuleParentLink(new_module, _) |
1633 BlockParentLink(new_module, _) => {
1634 let new_module = new_module.upgrade().unwrap();
1635 if new_module.is_normal() {
1636 return Some(new_module);
1638 module_ = new_module;
1644 /// Returns the nearest normal module parent of the given module, or the
1645 /// module itself if it is a normal module.
1646 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1647 if module_.is_normal() {
1650 match self.get_nearest_normal_module_parent(module_.clone()) {
1652 Some(new_module) => new_module,
1656 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1657 /// (b) some chain of `super::`.
1658 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1659 fn resolve_module_prefix(&mut self,
1660 module_: Rc<Module>,
1661 module_path: &[Name])
1662 -> ResolveResult<ModulePrefixResult> {
1663 // Start at the current module if we see `self` or `super`, or at the
1664 // top of the crate otherwise.
1665 let mut i = match &*module_path[0].as_str() {
1668 _ => return Success(NoPrefixFound),
1670 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1672 // Now loop through all the `super`s we find.
1673 while i < module_path.len() && "super" == module_path[i].as_str() {
1674 debug!("(resolving module prefix) resolving `super` at {}",
1675 module_to_string(&*containing_module));
1676 match self.get_nearest_normal_module_parent(containing_module) {
1677 None => return Failed(None),
1678 Some(new_module) => {
1679 containing_module = new_module;
1685 debug!("(resolving module prefix) finished resolving prefix at {}",
1686 module_to_string(&*containing_module));
1688 return Success(PrefixFound(containing_module, i));
1691 /// Attempts to resolve the supplied name in the given module for the
1692 /// given namespace. If successful, returns the target corresponding to
1695 /// The boolean returned on success is an indicator of whether this lookup
1696 /// passed through a public re-export proxy.
1697 fn resolve_name_in_module(&mut self,
1698 module_: Rc<Module>,
1700 namespace: Namespace,
1701 name_search_type: NameSearchType,
1702 allow_private_imports: bool)
1703 -> ResolveResult<(Target, bool)> {
1704 debug!("(resolving name in module) resolving `{}` in `{}`",
1706 module_to_string(&*module_));
1708 // First, check the direct children of the module.
1709 build_reduced_graph::populate_module_if_necessary(self, &module_);
1711 match module_.children.borrow().get(&name) {
1712 Some(name_bindings) if name_bindings[namespace].defined() => {
1713 debug!("(resolving name in module) found node as child");
1714 return Success((Target::new(module_.clone(),
1715 name_bindings[namespace].clone(),
1724 // Next, check the module's imports if necessary.
1726 // If this is a search of all imports, we should be done with glob
1727 // resolution at this point.
1728 if name_search_type == PathSearch {
1729 assert_eq!(module_.glob_count.get(), 0);
1732 // Check the list of resolved imports.
1733 match module_.import_resolutions.borrow().get(&name) {
1734 Some(import_resolution) if allow_private_imports || import_resolution.is_public => {
1736 if import_resolution.is_public && import_resolution.outstanding_references != 0 {
1737 debug!("(resolving name in module) import unresolved; bailing out");
1738 return Indeterminate;
1740 match import_resolution.target_for_namespace(namespace) {
1742 debug!("(resolving name in module) name found, but not in namespace {:?}",
1746 debug!("(resolving name in module) resolved to import");
1747 // track used imports and extern crates as well
1748 let id = import_resolution.id(namespace);
1749 self.used_imports.insert((id, namespace));
1750 self.record_import_use(id, name);
1751 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1752 self.used_crates.insert(kid);
1754 return Success((target, true));
1758 Some(..) | None => {} // Continue.
1761 // Finally, search through external children.
1762 if namespace == TypeNS {
1763 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1764 let child = module_.external_module_children.borrow().get(&name).cloned();
1765 if let Some(module) = child {
1766 let name_binding = NameBinding::create_from_module(module);
1767 return Success((Target::new(module_, name_binding, Shadowable::Never),
1772 // We're out of luck.
1773 debug!("(resolving name in module) failed to resolve `{}`", name);
1774 return Failed(None);
1777 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1778 let index = module_.resolved_import_count.get();
1779 let imports = module_.imports.borrow();
1780 let import_count = imports.len();
1781 if index != import_count {
1783 (*imports)[index].span,
1784 ResolutionError::UnresolvedImport(None));
1787 // Descend into children and anonymous children.
1788 build_reduced_graph::populate_module_if_necessary(self, &module_);
1790 for (_, child_node) in module_.children.borrow().iter() {
1791 match child_node.get_module_if_available() {
1795 Some(child_module) => {
1796 self.report_unresolved_imports(child_module);
1801 for (_, module_) in module_.anonymous_children.borrow().iter() {
1802 self.report_unresolved_imports(module_.clone());
1808 // We maintain a list of value ribs and type ribs.
1810 // Simultaneously, we keep track of the current position in the module
1811 // graph in the `current_module` pointer. When we go to resolve a name in
1812 // the value or type namespaces, we first look through all the ribs and
1813 // then query the module graph. When we resolve a name in the module
1814 // namespace, we can skip all the ribs (since nested modules are not
1815 // allowed within blocks in Rust) and jump straight to the current module
1818 // Named implementations are handled separately. When we find a method
1819 // call, we consult the module node to find all of the implementations in
1820 // scope. This information is lazily cached in the module node. We then
1821 // generate a fake "implementation scope" containing all the
1822 // implementations thus found, for compatibility with old resolve pass.
1824 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1825 where F: FnOnce(&mut Resolver)
1827 let orig_module = self.current_module.clone();
1829 // Move down in the graph.
1835 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1837 match orig_module.children.borrow().get(&name) {
1839 debug!("!!! (with scope) didn't find `{}` in `{}`",
1841 module_to_string(&*orig_module));
1843 Some(name_bindings) => {
1844 match (*name_bindings).get_module_if_available() {
1846 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1848 module_to_string(&*orig_module));
1851 self.current_module = module_;
1861 self.current_module = orig_module;
1864 /// Searches the current set of local scopes for labels.
1865 /// Stops after meeting a closure.
1866 fn search_label(&self, name: Name) -> Option<DefLike> {
1867 for rib in self.label_ribs.iter().rev() {
1873 // Do not resolve labels across function boundary
1877 let result = rib.bindings.get(&name).cloned();
1878 if result.is_some() {
1885 fn resolve_crate(&mut self, krate: &hir::Crate) {
1886 debug!("(resolving crate) starting");
1888 visit::walk_crate(self, krate);
1891 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1892 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1893 span_err!(self.session,
1896 "user-defined types or type parameters cannot shadow the primitive types");
1900 fn resolve_item(&mut self, item: &Item) {
1901 let name = item.name;
1903 debug!("(resolving item) resolving {}", name);
1906 ItemEnum(_, ref generics) |
1907 ItemTy(_, ref generics) |
1908 ItemStruct(_, ref generics) => {
1909 self.check_if_primitive_type_name(name, item.span);
1911 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1912 |this| visit::walk_item(this, item));
1914 ItemFn(_, _, _, _, ref generics, _) => {
1915 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1916 |this| visit::walk_item(this, item));
1919 ItemDefaultImpl(_, ref trait_ref) => {
1920 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1922 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1923 self.resolve_implementation(generics,
1930 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1931 self.check_if_primitive_type_name(name, item.span);
1933 // Create a new rib for the trait-wide type parameters.
1934 self.with_type_parameter_rib(HasTypeParameters(generics,
1938 let local_def_id = this.ast_map.local_def_id(item.id);
1939 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1940 this.visit_generics(generics);
1941 walk_list!(this, visit_ty_param_bound, bounds);
1943 for trait_item in trait_items {
1944 match trait_item.node {
1945 hir::ConstTraitItem(_, ref default) => {
1946 // Only impose the restrictions of
1947 // ConstRibKind if there's an actual constant
1948 // expression in a provided default.
1949 if default.is_some() {
1950 this.with_constant_rib(|this| {
1951 visit::walk_trait_item(this, trait_item)
1954 visit::walk_trait_item(this, trait_item)
1957 hir::MethodTraitItem(ref sig, _) => {
1958 let type_parameters =
1959 HasTypeParameters(&sig.generics,
1962 this.with_type_parameter_rib(type_parameters, |this| {
1963 visit::walk_trait_item(this, trait_item)
1966 hir::TypeTraitItem(..) => {
1967 this.check_if_primitive_type_name(trait_item.name,
1969 this.with_type_parameter_rib(NoTypeParameters, |this| {
1970 visit::walk_trait_item(this, trait_item)
1979 ItemMod(_) | ItemForeignMod(_) => {
1980 self.with_scope(Some(name), |this| {
1981 visit::walk_item(this, item);
1985 ItemConst(..) | ItemStatic(..) => {
1986 self.with_constant_rib(|this| {
1987 visit::walk_item(this, item);
1991 ItemUse(ref view_path) => {
1992 // check for imports shadowing primitive types
1993 let check_rename = |this: &Self, id, name| {
1994 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
1995 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
1996 this.check_if_primitive_type_name(name, item.span);
2002 match view_path.node {
2003 hir::ViewPathSimple(name, _) => {
2004 check_rename(self, item.id, name);
2006 hir::ViewPathList(ref prefix, ref items) => {
2008 if let Some(name) = item.node.rename() {
2009 check_rename(self, item.node.id(), name);
2013 // Resolve prefix of an import with empty braces (issue #28388)
2014 if items.is_empty() && !prefix.segments.is_empty() {
2015 match self.resolve_crate_relative_path(prefix.span,
2019 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2023 ResolutionError::FailedToResolve(
2024 &path_names_to_string(prefix, 0)));
2033 ItemExternCrate(_) => {
2034 // do nothing, these are just around to be encoded
2039 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2040 where F: FnOnce(&mut Resolver)
2042 match type_parameters {
2043 HasTypeParameters(generics, space, rib_kind) => {
2044 let mut function_type_rib = Rib::new(rib_kind);
2045 let mut seen_bindings = HashSet::new();
2046 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2047 let name = type_parameter.name;
2048 debug!("with_type_parameter_rib: {}", type_parameter.id);
2050 if seen_bindings.contains(&name) {
2052 type_parameter.span,
2053 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2055 seen_bindings.insert(name);
2057 // plain insert (no renaming)
2058 function_type_rib.bindings
2060 DlDef(DefTyParam(space,
2063 .local_def_id(type_parameter.id),
2066 self.type_ribs.push(function_type_rib);
2069 NoTypeParameters => {
2076 match type_parameters {
2077 HasTypeParameters(..) => {
2079 self.type_ribs.pop();
2082 NoTypeParameters => {}
2086 fn with_label_rib<F>(&mut self, f: F)
2087 where F: FnOnce(&mut Resolver)
2089 self.label_ribs.push(Rib::new(NormalRibKind));
2092 self.label_ribs.pop();
2096 fn with_constant_rib<F>(&mut self, f: F)
2097 where F: FnOnce(&mut Resolver)
2099 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2100 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2103 self.type_ribs.pop();
2104 self.value_ribs.pop();
2108 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2109 // Create a value rib for the function.
2110 self.value_ribs.push(Rib::new(rib_kind));
2112 // Create a label rib for the function.
2113 self.label_ribs.push(Rib::new(rib_kind));
2115 // Add each argument to the rib.
2116 let mut bindings_list = HashMap::new();
2117 for argument in &declaration.inputs {
2118 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2120 self.visit_ty(&*argument.ty);
2122 debug!("(resolving function) recorded argument");
2124 visit::walk_fn_ret_ty(self, &declaration.output);
2126 // Resolve the function body.
2127 self.visit_block(&*block);
2129 debug!("(resolving function) leaving function");
2132 self.label_ribs.pop();
2133 self.value_ribs.pop();
2137 fn resolve_trait_reference(&mut self,
2141 -> Result<PathResolution, ()> {
2142 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2143 if let DefTrait(_) = path_res.base_def {
2144 debug!("(resolving trait) found trait def: {:?}", path_res);
2149 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2152 // If it's a typedef, give a note
2153 if let DefTy(..) = path_res.base_def {
2155 .span_note(trait_path.span, "`type` aliases cannot be used for traits");
2162 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2168 fn resolve_generics(&mut self, generics: &Generics) {
2169 for type_parameter in generics.ty_params.iter() {
2170 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2172 for predicate in &generics.where_clause.predicates {
2174 &hir::WherePredicate::BoundPredicate(_) |
2175 &hir::WherePredicate::RegionPredicate(_) => {}
2176 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2177 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2178 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2179 self.record_def(eq_pred.id, path_res.unwrap());
2183 ResolutionError::UndeclaredAssociatedType);
2188 visit::walk_generics(self, generics);
2191 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2192 where F: FnOnce(&mut Resolver) -> T
2194 // Handle nested impls (inside fn bodies)
2195 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2196 let result = f(self);
2197 self.current_self_type = previous_value;
2201 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2202 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2204 let mut new_val = None;
2205 let mut new_id = None;
2206 if let Some(trait_ref) = opt_trait_ref {
2207 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2210 assert!(path_res.depth == 0);
2211 self.record_def(trait_ref.ref_id, path_res);
2212 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2213 new_id = Some(path_res.base_def.def_id());
2215 visit::walk_trait_ref(self, trait_ref);
2217 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2218 let result = f(self, new_id);
2219 self.current_trait_ref = original_trait_ref;
2223 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2224 where F: FnOnce(&mut Resolver)
2226 let mut self_type_rib = Rib::new(NormalRibKind);
2228 // plain insert (no renaming, types are not currently hygienic....)
2229 let name = special_names::type_self;
2230 self_type_rib.bindings.insert(name, DlDef(self_def));
2231 self.type_ribs.push(self_type_rib);
2234 self.type_ribs.pop();
2238 fn resolve_implementation(&mut self,
2239 generics: &Generics,
2240 opt_trait_reference: &Option<TraitRef>,
2243 impl_items: &[P<ImplItem>]) {
2244 // If applicable, create a rib for the type parameters.
2245 self.with_type_parameter_rib(HasTypeParameters(generics,
2249 // Resolve the type parameters.
2250 this.visit_generics(generics);
2252 // Resolve the trait reference, if necessary.
2253 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2254 // Resolve the self type.
2255 this.visit_ty(self_type);
2257 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2258 this.with_current_self_type(self_type, |this| {
2259 for impl_item in impl_items {
2260 match impl_item.node {
2261 ConstImplItem(..) => {
2262 // If this is a trait impl, ensure the const
2264 this.check_trait_item(impl_item.name,
2266 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2267 this.with_constant_rib(|this| {
2268 visit::walk_impl_item(this, impl_item);
2271 MethodImplItem(ref sig, _) => {
2272 // If this is a trait impl, ensure the method
2274 this.check_trait_item(impl_item.name,
2276 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2278 // We also need a new scope for the method-
2279 // specific type parameters.
2280 let type_parameters =
2281 HasTypeParameters(&sig.generics,
2284 this.with_type_parameter_rib(type_parameters, |this| {
2285 visit::walk_impl_item(this, impl_item);
2288 TypeImplItem(ref ty) => {
2289 // If this is a trait impl, ensure the type
2291 this.check_trait_item(impl_item.name,
2293 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2305 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2306 where F: FnOnce(Name, &str) -> ResolutionError
2308 // If there is a TraitRef in scope for an impl, then the method must be in the
2310 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2311 if !self.trait_item_map.contains_key(&(name, did)) {
2312 let path_str = path_names_to_string(&trait_ref.path, 0);
2313 resolve_error(self, span, err(name, &*path_str));
2318 fn resolve_local(&mut self, local: &Local) {
2319 // Resolve the type.
2320 walk_list!(self, visit_ty, &local.ty);
2322 // Resolve the initializer.
2323 walk_list!(self, visit_expr, &local.init);
2325 // Resolve the pattern.
2326 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2329 // build a map from pattern identifiers to binding-info's.
2330 // this is done hygienically. This could arise for a macro
2331 // that expands into an or-pattern where one 'x' was from the
2332 // user and one 'x' came from the macro.
2333 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2334 let mut result = HashMap::new();
2335 pat_bindings_hygienic(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2336 let name = mtwt::resolve(path1.node);
2340 binding_mode: binding_mode,
2346 // check that all of the arms in an or-pattern have exactly the
2347 // same set of bindings, with the same binding modes for each.
2348 fn check_consistent_bindings(&mut self, arm: &Arm) {
2349 if arm.pats.is_empty() {
2352 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2353 for (i, p) in arm.pats.iter().enumerate() {
2354 let map_i = self.binding_mode_map(&**p);
2356 for (&key, &binding_0) in &map_0 {
2357 match map_i.get(&key) {
2361 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2363 Some(binding_i) => {
2364 if binding_0.binding_mode != binding_i.binding_mode {
2367 ResolutionError::VariableBoundWithDifferentMode(key,
2374 for (&key, &binding) in &map_i {
2375 if !map_0.contains_key(&key) {
2378 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2384 fn resolve_arm(&mut self, arm: &Arm) {
2385 self.value_ribs.push(Rib::new(NormalRibKind));
2387 let mut bindings_list = HashMap::new();
2388 for pattern in &arm.pats {
2389 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2392 // This has to happen *after* we determine which
2393 // pat_idents are variants
2394 self.check_consistent_bindings(arm);
2396 walk_list!(self, visit_expr, &arm.guard);
2397 self.visit_expr(&*arm.body);
2400 self.value_ribs.pop();
2404 fn resolve_block(&mut self, block: &Block) {
2405 debug!("(resolving block) entering block");
2406 self.value_ribs.push(Rib::new(NormalRibKind));
2408 // Move down in the graph, if there's an anonymous module rooted here.
2409 let orig_module = self.current_module.clone();
2410 match orig_module.anonymous_children.borrow().get(&block.id) {
2414 Some(anonymous_module) => {
2415 debug!("(resolving block) found anonymous module, moving down");
2416 self.current_module = anonymous_module.clone();
2420 // Check for imports appearing after non-item statements.
2421 let mut found_non_item = false;
2422 for statement in &block.stmts {
2423 if let hir::StmtDecl(ref declaration, _) = statement.node {
2424 if let hir::DeclItem(ref i) = declaration.node {
2426 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2427 span_err!(self.session,
2430 "imports are not allowed after non-item statements");
2435 found_non_item = true
2438 found_non_item = true;
2442 // Descend into the block.
2443 visit::walk_block(self, block);
2447 self.current_module = orig_module;
2448 self.value_ribs.pop();
2450 debug!("(resolving block) leaving block");
2453 fn resolve_type(&mut self, ty: &Ty) {
2455 TyPath(ref maybe_qself, ref path) => {
2456 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2457 maybe_qself.as_ref(),
2461 // `<T>::a::b::c` is resolved by typeck alone.
2462 TypecheckRequired => {
2463 // Resolve embedded types.
2464 visit::walk_ty(self, ty);
2467 ResolveAttempt(resolution) => resolution,
2470 // This is a path in the type namespace. Walk through scopes
2474 // Write the result into the def map.
2475 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2476 path_names_to_string(path, 0),
2479 self.record_def(ty.id, def);
2482 // Keep reporting some errors even if they're ignored above.
2483 self.resolve_path(ty.id, path, 0, TypeNS, true);
2485 let kind = if maybe_qself.is_some() {
2491 let self_type_name = special_idents::type_self.name;
2492 let is_invalid_self_type_name = path.segments.len() > 0 &&
2493 maybe_qself.is_none() &&
2494 path.segments[0].identifier.name ==
2496 if is_invalid_self_type_name {
2499 ResolutionError::SelfUsedOutsideImplOrTrait);
2503 ResolutionError::UseOfUndeclared(
2505 &*path_names_to_string(path,
2514 // Resolve embedded types.
2515 visit::walk_ty(self, ty);
2518 fn resolve_pattern(&mut self,
2520 mode: PatternBindingMode,
2521 // Maps idents to the node ID for the (outermost)
2522 // pattern that binds them
2523 bindings_list: &mut HashMap<Name, NodeId>) {
2524 let pat_id = pattern.id;
2525 walk_pat(pattern, |pattern| {
2526 match pattern.node {
2527 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2528 // The meaning of PatIdent with no type parameters
2529 // depends on whether an enum variant or unit-like struct
2530 // with that name is in scope. The probing lookup has to
2531 // be careful not to emit spurious errors. Only matching
2532 // patterns (match) can match nullary variants or
2533 // unit-like structs. For binding patterns (let
2534 // and the LHS of @-patterns), matching such a value is
2535 // simply disallowed (since it's rarely what you want).
2536 let const_ok = mode == RefutableMode && at_rhs.is_none();
2538 let ident = path1.node;
2539 let renamed = mtwt::resolve(ident);
2541 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2542 FoundStructOrEnumVariant(def, lp) if const_ok => {
2543 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2546 self.enforce_default_binding_mode(pattern,
2549 self.record_def(pattern.id,
2556 FoundStructOrEnumVariant(..) => {
2560 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2564 FoundConst(def, lp, _) if const_ok => {
2565 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2567 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2568 self.record_def(pattern.id,
2575 FoundConst(def, _, name) => {
2579 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2583 BareIdentifierPatternUnresolved => {
2584 debug!("(resolving pattern) binding `{}`", renamed);
2586 let def_id = self.ast_map.local_def_id(pattern.id);
2587 let def = DefLocal(def_id, pattern.id);
2589 // Record the definition so that later passes
2590 // will be able to distinguish variants from
2591 // locals in patterns.
2593 self.record_def(pattern.id,
2596 last_private: LastMod(AllPublic),
2600 // Add the binding to the local ribs, if it
2601 // doesn't already exist in the bindings list. (We
2602 // must not add it if it's in the bindings list
2603 // because that breaks the assumptions later
2604 // passes make about or-patterns.)
2605 if !bindings_list.contains_key(&renamed) {
2606 let this = &mut *self;
2607 let last_rib = this.value_ribs.last_mut().unwrap();
2608 last_rib.bindings.insert(renamed, DlDef(def));
2609 bindings_list.insert(renamed, pat_id);
2610 } else if mode == ArgumentIrrefutableMode &&
2611 bindings_list.contains_key(&renamed) {
2612 // Forbid duplicate bindings in the same
2617 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2618 &ident.name.as_str())
2620 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2621 // Then this is a duplicate variable in the
2622 // same disjunction, which is an error.
2626 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2627 &ident.name.as_str())
2630 // Else, not bound in the same pattern: do
2636 PatEnum(ref path, _) => {
2637 // This must be an enum variant, struct or const.
2638 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2643 // The below shouldn't happen because all
2644 // qualified paths should be in PatQPath.
2645 TypecheckRequired =>
2646 self.session.span_bug(path.span,
2647 "resolve_possibly_assoc_item claimed
2649 that a path in PatEnum requires typecheck
2651 to resolve, but qualified paths should be
2654 ResolveAttempt(resolution) => resolution,
2656 if let Some(path_res) = resolution {
2657 match path_res.base_def {
2658 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2659 self.record_def(pattern.id, path_res);
2662 resolve_error(&self,
2664 ResolutionError::StaticVariableReference);
2667 // If anything ends up here entirely resolved,
2668 // it's an error. If anything ends up here
2669 // partially resolved, that's OK, because it may
2670 // be a `T::CONST` that typeck will resolve.
2671 if path_res.depth == 0 {
2675 ResolutionError::NotAnEnumVariantStructOrConst(
2684 let const_name = path.segments
2689 let traits = self.get_traits_containing_item(const_name);
2690 self.trait_map.insert(pattern.id, traits);
2691 self.record_def(pattern.id, path_res);
2699 ResolutionError::UnresolvedEnumVariantStructOrConst(
2700 &path.segments.last().unwrap().identifier.name.as_str())
2703 visit::walk_path(self, path);
2706 PatQPath(ref qself, ref path) => {
2707 // Associated constants only.
2708 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2713 TypecheckRequired => {
2714 // All `<T>::CONST` should end up here, and will
2715 // require use of the trait map to resolve
2716 // during typechecking.
2717 let const_name = path.segments
2722 let traits = self.get_traits_containing_item(const_name);
2723 self.trait_map.insert(pattern.id, traits);
2724 visit::walk_pat(self, pattern);
2727 ResolveAttempt(resolution) => resolution,
2729 if let Some(path_res) = resolution {
2730 match path_res.base_def {
2731 // All `<T as Trait>::CONST` should end up here, and
2732 // have the trait already selected.
2733 DefAssociatedConst(..) => {
2734 self.record_def(pattern.id, path_res);
2740 ResolutionError::NotAnAssociatedConst(
2741 &path.segments.last().unwrap().identifier.name.as_str()
2749 ResolutionError::UnresolvedAssociatedConst(&path.segments
2756 visit::walk_pat(self, pattern);
2759 PatStruct(ref path, _, _) => {
2760 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2761 Some(definition) => {
2762 self.record_def(pattern.id, definition);
2765 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2769 ResolutionError::DoesNotNameAStruct(
2770 &*path_names_to_string(path, 0))
2774 visit::walk_path(self, path);
2777 PatLit(_) | PatRange(..) => {
2778 visit::walk_pat(self, pattern);
2789 fn resolve_bare_identifier_pattern(&mut self,
2792 -> BareIdentifierPatternResolution {
2793 let module = self.current_module.clone();
2794 match self.resolve_item_in_lexical_scope(module, name, ValueNS) {
2795 Success((target, _)) => {
2796 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2798 target.binding.borrow());
2799 match target.binding.def() {
2801 panic!("resolved name in the value namespace to a set of name bindings \
2804 // For the two success cases, this lookup can be
2805 // considered as not having a private component because
2806 // the lookup happened only within the current module.
2807 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2808 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2810 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2811 return FoundConst(def, LastMod(AllPublic), name);
2813 Some(DefStatic(..)) => {
2814 resolve_error(self, span, ResolutionError::StaticVariableReference);
2815 return BareIdentifierPatternUnresolved;
2817 _ => return BareIdentifierPatternUnresolved
2822 panic!("unexpected indeterminate result");
2826 Some((span, msg)) => {
2827 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2832 debug!("(resolve bare identifier pattern) failed to find {}", name);
2833 return BareIdentifierPatternUnresolved;
2838 /// Handles paths that may refer to associated items
2839 fn resolve_possibly_assoc_item(&mut self,
2841 maybe_qself: Option<&hir::QSelf>,
2843 namespace: Namespace,
2845 -> AssocItemResolveResult {
2846 let max_assoc_types;
2850 if qself.position == 0 {
2851 return TypecheckRequired;
2853 max_assoc_types = path.segments.len() - qself.position;
2854 // Make sure the trait is valid.
2855 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2858 max_assoc_types = path.segments.len();
2862 let mut resolution = self.with_no_errors(|this| {
2863 this.resolve_path(id, path, 0, namespace, check_ribs)
2865 for depth in 1..max_assoc_types {
2866 if resolution.is_some() {
2869 self.with_no_errors(|this| {
2870 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2873 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2874 // A module is not a valid type or value.
2877 ResolveAttempt(resolution)
2880 /// If `check_ribs` is true, checks the local definitions first; i.e.
2881 /// doesn't skip straight to the containing module.
2882 /// Skips `path_depth` trailing segments, which is also reflected in the
2883 /// returned value. See `middle::def::PathResolution` for more info.
2884 pub fn resolve_path(&mut self,
2888 namespace: Namespace,
2890 -> Option<PathResolution> {
2891 let span = path.span;
2892 let segments = &path.segments[..path.segments.len() - path_depth];
2894 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2897 let def = self.resolve_crate_relative_path(span, segments, namespace);
2898 return def.map(mk_res);
2901 // Try to find a path to an item in a module.
2902 let unqualified_def = self.resolve_identifier(segments.last().unwrap().identifier,
2906 if segments.len() <= 1 {
2907 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2909 PathResolution::new(def, LastMod(AllPublic), path_depth)
2913 let def = self.resolve_module_relative_path(span, segments, namespace);
2914 match (def, unqualified_def) {
2915 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2917 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2920 "unnecessary qualification".to_string());
2928 // Resolve a single identifier
2929 fn resolve_identifier(&mut self,
2931 namespace: Namespace,
2933 -> Option<LocalDef> {
2934 // First, check to see whether the name is a primitive type.
2935 if namespace == TypeNS {
2936 if let Some(&prim_ty) = self.primitive_type_table
2938 .get(&identifier.name) {
2939 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
2944 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2949 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
2950 .map(LocalDef::from_def)
2953 // Resolve a local definition, potentially adjusting for closures.
2954 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2955 let ribs = match local_def.ribs {
2956 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2957 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2960 let mut def = local_def.def;
2963 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2965 DefLocal(_, node_id) => {
2969 // Nothing to do. Continue.
2971 ClosureRibKind(function_id) => {
2973 let node_def_id = self.ast_map.local_def_id(node_id);
2975 let seen = self.freevars_seen
2977 .or_insert_with(|| NodeMap());
2978 if let Some(&index) = seen.get(&node_id) {
2979 def = DefUpvar(node_def_id, node_id, index, function_id);
2982 let vec = self.freevars
2984 .or_insert_with(|| vec![]);
2985 let depth = vec.len();
2991 def = DefUpvar(node_def_id, node_id, depth, function_id);
2992 seen.insert(node_id, depth);
2994 ItemRibKind | MethodRibKind => {
2995 // This was an attempt to access an upvar inside a
2996 // named function item. This is not allowed, so we
3000 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3003 ConstantItemRibKind => {
3004 // Still doesn't deal with upvars
3007 ResolutionError::AttemptToUseNonConstantValueInConstant);
3013 DefTyParam(..) | DefSelfTy(..) => {
3016 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3017 // Nothing to do. Continue.
3020 // This was an attempt to use a type parameter outside
3025 ResolutionError::TypeParametersFromOuterFunction);
3028 ConstantItemRibKind => {
3030 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3041 // resolve a "module-relative" path, e.g. a::b::c
3042 fn resolve_module_relative_path(&mut self,
3044 segments: &[hir::PathSegment],
3045 namespace: Namespace)
3046 -> Option<(Def, LastPrivate)> {
3047 let module_path = segments.split_last()
3051 .map(|ps| ps.identifier.name)
3052 .collect::<Vec<_>>();
3054 let containing_module;
3056 let current_module = self.current_module.clone();
3057 match self.resolve_module_path(current_module,
3063 let (span, msg) = match err {
3064 Some((span, msg)) => (span, msg),
3066 let msg = format!("Use of undeclared type or module `{}`",
3067 names_to_string(&module_path));
3072 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3075 Indeterminate => panic!("indeterminate unexpected"),
3076 Success((resulting_module, resulting_last_private)) => {
3077 containing_module = resulting_module;
3078 last_private = resulting_last_private;
3082 let name = segments.last().unwrap().identifier.name;
3083 let def = match self.resolve_name_in_module(containing_module.clone(),
3086 NameSearchType::PathSearch,
3088 Success((Target { binding, .. }, _)) => {
3089 let (def, lp) = binding.def_and_lp();
3090 (def, last_private.or(lp))
3094 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3095 self.used_crates.insert(kid);
3100 /// Invariant: This must be called only during main resolution, not during
3101 /// import resolution.
3102 fn resolve_crate_relative_path(&mut self,
3104 segments: &[hir::PathSegment],
3105 namespace: Namespace)
3106 -> Option<(Def, LastPrivate)> {
3107 let module_path = segments.split_last()
3111 .map(|ps| ps.identifier.name)
3112 .collect::<Vec<_>>();
3114 let root_module = self.graph_root.get_module();
3116 let containing_module;
3118 match self.resolve_module_path_from_root(root_module,
3123 LastMod(AllPublic)) {
3125 let (span, msg) = match err {
3126 Some((span, msg)) => (span, msg),
3128 let msg = format!("Use of undeclared module `::{}`",
3129 names_to_string(&module_path[..]));
3134 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3139 panic!("indeterminate unexpected");
3142 Success((resulting_module, resulting_last_private)) => {
3143 containing_module = resulting_module;
3144 last_private = resulting_last_private;
3148 let name = segments.last().unwrap().identifier.name;
3149 match self.resolve_name_in_module(containing_module,
3152 NameSearchType::PathSearch,
3154 Success((Target { binding, .. }, _)) => {
3155 let (def, lp) = binding.def_and_lp();
3156 Some((def, last_private.or(lp)))
3162 fn resolve_identifier_in_local_ribs(&mut self,
3164 namespace: Namespace)
3165 -> Option<LocalDef> {
3166 // Check the local set of ribs.
3167 let (name, ribs) = match namespace {
3168 ValueNS => (mtwt::resolve(ident), &self.value_ribs),
3169 TypeNS => (ident.name, &self.type_ribs),
3172 for (i, rib) in ribs.iter().enumerate().rev() {
3173 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3176 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3180 return Some(LocalDef {
3181 ribs: Some((namespace, i)),
3186 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3198 fn resolve_item_by_name_in_lexical_scope(&mut self,
3200 namespace: Namespace)
3203 let module = self.current_module.clone();
3204 match self.resolve_item_in_lexical_scope(module, name, namespace) {
3205 Success((target, _)) => {
3206 match target.binding.def() {
3208 // This can happen if we were looking for a type and
3209 // found a module instead. Modules don't have defs.
3210 debug!("(resolving item path by identifier in lexical scope) failed to \
3211 resolve {} after success...",
3216 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3218 // This lookup is "all public" because it only searched
3219 // for one identifier in the current module (couldn't
3220 // have passed through reexports or anything like that.
3226 panic!("unexpected indeterminate result");
3229 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3232 if let Some((span, msg)) = err {
3233 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3241 fn with_no_errors<T, F>(&mut self, f: F) -> T
3242 where F: FnOnce(&mut Resolver) -> T
3244 self.emit_errors = false;
3246 self.emit_errors = true;
3250 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3251 fn extract_path_and_node_id(t: &Ty,
3252 allow: FallbackChecks)
3253 -> Option<(Path, NodeId, FallbackChecks)> {
3255 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3256 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3257 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3258 // This doesn't handle the remaining `Ty` variants as they are not
3259 // that commonly the self_type, it might be interesting to provide
3260 // support for those in future.
3265 fn get_module(this: &mut Resolver,
3267 name_path: &[ast::Name])
3268 -> Option<Rc<Module>> {
3269 let root = this.current_module.clone();
3270 let last_name = name_path.last().unwrap();
3272 if name_path.len() == 1 {
3273 match this.primitive_type_table.primitive_types.get(last_name) {
3276 match this.current_module.children.borrow().get(last_name) {
3277 Some(child) => child.get_module_if_available(),
3283 match this.resolve_module_path(root,
3288 Success((module, _)) => Some(module),
3294 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3295 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3296 let sig = match this.ast_map.get(node_id) {
3297 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3298 hir::MethodTraitItem(ref sig, _) => sig,
3301 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3302 hir::MethodImplItem(ref sig, _) => sig,
3307 sig.explicit_self.node == hir::SelfStatic
3309 csearch::is_static_method(&this.session.cstore, did)
3313 let (path, node_id, allowed) = match self.current_self_type {
3314 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3316 None => return NoSuggestion,
3318 None => return NoSuggestion,
3321 if allowed == Everything {
3322 // Look for a field with the same name in the current self_type.
3323 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3324 Some(DefTy(did, _)) |
3325 Some(DefStruct(did)) |
3326 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3329 if fields.iter().any(|&field_name| name == field_name) {
3334 _ => {} // Self type didn't resolve properly
3338 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3340 // Look for a method in the current self type's impl module.
3341 if let Some(module) = get_module(self, path.span, &name_path) {
3342 if let Some(binding) = module.children.borrow().get(&name) {
3343 if let Some(DefMethod(did)) = binding.value_ns.def() {
3344 if is_static_method(self, did) {
3345 return StaticMethod(path_names_to_string(&path, 0));
3347 if self.current_trait_ref.is_some() {
3349 } else if allowed == Everything {
3356 // Look for a method in the current trait.
3357 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3358 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3359 if is_static_method(self, did) {
3360 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3370 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3371 let mut maybes: Vec<token::InternedString> = Vec::new();
3372 let mut values: Vec<usize> = Vec::new();
3374 for rib in self.value_ribs.iter().rev() {
3375 for (&k, _) in &rib.bindings {
3376 maybes.push(k.as_str());
3377 values.push(usize::MAX);
3381 let mut smallest = 0;
3382 for (i, other) in maybes.iter().enumerate() {
3383 values[i] = lev_distance(name, &other);
3385 if values[i] <= values[smallest] {
3390 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3391 // maximum edit distance we will accept for a suggestion to one third of
3392 // the typo'd name's length.
3393 let max_distance = std::cmp::max(name.len(), 3) / 3;
3395 if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
3397 Some(maybes[smallest].to_string())
3404 fn resolve_expr(&mut self, expr: &Expr) {
3405 // First, record candidate traits for this expression if it could
3406 // result in the invocation of a method call.
3408 self.record_candidate_traits_for_expr_if_necessary(expr);
3410 // Next, resolve the node.
3412 ExprPath(ref maybe_qself, ref path) => {
3413 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3414 maybe_qself.as_ref(),
3418 // `<T>::a::b::c` is resolved by typeck alone.
3419 TypecheckRequired => {
3420 let method_name = path.segments.last().unwrap().identifier.name;
3421 let traits = self.get_traits_containing_item(method_name);
3422 self.trait_map.insert(expr.id, traits);
3423 visit::walk_expr(self, expr);
3426 ResolveAttempt(resolution) => resolution,
3429 // This is a local path in the value namespace. Walk through
3430 // scopes looking for it.
3431 if let Some(path_res) = resolution {
3432 // Check if struct variant
3433 if let DefVariant(_, _, true) = path_res.base_def {
3434 let path_name = path_names_to_string(path, 0);
3438 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3440 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3442 if self.emit_errors {
3443 self.session.fileline_help(expr.span, &msg);
3445 self.session.span_help(expr.span, &msg);
3448 // Write the result into the def map.
3449 debug!("(resolving expr) resolved `{}`",
3450 path_names_to_string(path, 0));
3452 // Partial resolutions will need the set of traits in scope,
3453 // so they can be completed during typeck.
3454 if path_res.depth != 0 {
3455 let method_name = path.segments.last().unwrap().identifier.name;
3456 let traits = self.get_traits_containing_item(method_name);
3457 self.trait_map.insert(expr.id, traits);
3460 self.record_def(expr.id, path_res);
3463 // Be helpful if the name refers to a struct
3464 // (The pattern matching def_tys where the id is in self.structs
3465 // matches on regular structs while excluding tuple- and enum-like
3466 // structs, which wouldn't result in this error.)
3467 let path_name = path_names_to_string(path, 0);
3468 let type_res = self.with_no_errors(|this| {
3469 this.resolve_path(expr.id, path, 0, TypeNS, false)
3471 match type_res.map(|r| r.base_def) {
3472 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3476 ResolutionError::StructVariantUsedAsFunction(
3480 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3482 if self.emit_errors {
3483 self.session.fileline_help(expr.span, &msg);
3485 self.session.span_help(expr.span, &msg);
3489 // Keep reporting some errors even if they're ignored above.
3490 self.resolve_path(expr.id, path, 0, ValueNS, true);
3492 let mut method_scope = false;
3493 self.value_ribs.iter().rev().all(|rib| {
3494 method_scope = match rib.kind {
3495 MethodRibKind => true,
3496 ItemRibKind | ConstantItemRibKind => false,
3497 _ => return true, // Keep advancing
3499 false // Stop advancing
3502 if method_scope && special_names::self_.as_str() == &path_name[..] {
3505 ResolutionError::SelfNotAvailableInStaticMethod);
3507 let last_name = path.segments.last().unwrap().identifier.name;
3508 let mut msg = match self.find_fallback_in_self_type(last_name) {
3510 // limit search to 5 to reduce the number
3511 // of stupid suggestions
3512 self.find_best_match_for_name(&path_name)
3513 .map_or("".to_string(), |x| format!("`{}`", x))
3515 Field => format!("`self.{}`", path_name),
3517 TraitItem => format!("to call `self.{}`", path_name),
3518 TraitMethod(path_str) |
3519 StaticMethod(path_str) =>
3520 format!("to call `{}::{}`", path_str, path_name),
3523 if !msg.is_empty() {
3524 msg = format!(". Did you mean {}?", msg)
3529 ResolutionError::UnresolvedName(&*path_name, &*msg));
3535 visit::walk_expr(self, expr);
3538 ExprStruct(ref path, _, _) => {
3539 // Resolve the path to the structure it goes to. We don't
3540 // check to ensure that the path is actually a structure; that
3541 // is checked later during typeck.
3542 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3543 Some(definition) => self.record_def(expr.id, definition),
3545 debug!("(resolving expression) didn't find struct def",);
3549 ResolutionError::DoesNotNameAStruct(
3550 &*path_names_to_string(path, 0))
3555 visit::walk_expr(self, expr);
3558 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3559 self.with_label_rib(|this| {
3560 let def_like = DlDef(DefLabel(expr.id));
3563 let rib = this.label_ribs.last_mut().unwrap();
3564 let renamed = mtwt::resolve(label);
3565 rib.bindings.insert(renamed, def_like);
3568 visit::walk_expr(this, expr);
3572 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3573 let renamed = mtwt::resolve(label.node);
3574 match self.search_label(renamed) {
3578 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3580 Some(DlDef(def @ DefLabel(_))) => {
3581 // Since this def is a label, it is never read.
3582 self.record_def(expr.id,
3585 last_private: LastMod(AllPublic),
3590 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3596 visit::walk_expr(self, expr);
3601 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3603 ExprField(_, name) => {
3604 // FIXME(#6890): Even though you can't treat a method like a
3605 // field, we need to add any trait methods we find that match
3606 // the field name so that we can do some nice error reporting
3607 // later on in typeck.
3608 let traits = self.get_traits_containing_item(name.node);
3609 self.trait_map.insert(expr.id, traits);
3611 ExprMethodCall(name, _, _) => {
3612 debug!("(recording candidate traits for expr) recording traits for {}",
3614 let traits = self.get_traits_containing_item(name.node);
3615 self.trait_map.insert(expr.id, traits);
3623 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3624 debug!("(getting traits containing item) looking for '{}'", name);
3626 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3627 debug!("(adding trait info) found trait {:?} for method '{}'",
3630 found_traits.push(trait_def_id);
3633 let mut found_traits = Vec::new();
3634 let mut search_module = self.current_module.clone();
3636 // Look for the current trait.
3637 match self.current_trait_ref {
3638 Some((trait_def_id, _)) => {
3639 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3640 add_trait_info(&mut found_traits, trait_def_id, name);
3643 None => {} // Nothing to do.
3646 // Look for trait children.
3647 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3650 for (_, child_names) in search_module.children.borrow().iter() {
3651 let def = match child_names.type_ns.def() {
3655 let trait_def_id = match def {
3656 DefTrait(trait_def_id) => trait_def_id,
3659 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3660 add_trait_info(&mut found_traits, trait_def_id, name);
3665 // Look for imports.
3666 for (_, import) in search_module.import_resolutions.borrow().iter() {
3667 let target = match import.target_for_namespace(TypeNS) {
3669 Some(target) => target,
3671 let did = match target.binding.def() {
3672 Some(DefTrait(trait_def_id)) => trait_def_id,
3673 Some(..) | None => continue,
3675 if self.trait_item_map.contains_key(&(name, did)) {
3676 add_trait_info(&mut found_traits, did, name);
3677 let id = import.type_id;
3678 self.used_imports.insert((id, TypeNS));
3679 let trait_name = self.get_trait_name(did);
3680 self.record_import_use(id, trait_name);
3681 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3682 self.used_crates.insert(kid);
3687 match search_module.parent_link.clone() {
3688 NoParentLink | ModuleParentLink(..) => break,
3689 BlockParentLink(parent_module, _) => {
3690 search_module = parent_module.upgrade().unwrap();
3698 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3699 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3700 assert!(match resolution.last_private {
3701 LastImport{..} => false,
3704 "Import should only be used for `use` directives");
3706 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3707 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3708 self.session.span_bug(span,
3709 &format!("path resolved multiple times ({:?} before, {:?} now)",
3715 fn enforce_default_binding_mode(&mut self,
3717 pat_binding_mode: BindingMode,
3719 match pat_binding_mode {
3720 BindByValue(_) => {}
3724 ResolutionError::CannotUseRefBindingModeWith(descr));
3732 // Diagnostics are not particularly efficient, because they're rarely
3736 #[allow(dead_code)] // useful for debugging
3737 fn dump_module(&mut self, module_: Rc<Module>) {
3738 debug!("Dump of module `{}`:", module_to_string(&*module_));
3740 debug!("Children:");
3741 build_reduced_graph::populate_module_if_necessary(self, &module_);
3742 for (&name, _) in module_.children.borrow().iter() {
3743 debug!("* {}", name);
3746 debug!("Import resolutions:");
3747 let import_resolutions = module_.import_resolutions.borrow();
3748 for (&name, import_resolution) in import_resolutions.iter() {
3750 match import_resolution.target_for_namespace(ValueNS) {
3752 value_repr = "".to_string();
3755 value_repr = " value:?".to_string();
3761 match import_resolution.target_for_namespace(TypeNS) {
3763 type_repr = "".to_string();
3766 type_repr = " type:?".to_string();
3771 debug!("* {}:{}{}", name, value_repr, type_repr);
3777 fn names_to_string(names: &[Name]) -> String {
3778 let mut first = true;
3779 let mut result = String::new();
3784 result.push_str("::")
3786 result.push_str(&name.as_str());
3791 fn path_names_to_string(path: &Path, depth: usize) -> String {
3792 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3794 .map(|seg| seg.identifier.name)
3796 names_to_string(&names[..])
3799 /// A somewhat inefficient routine to obtain the name of a module.
3800 fn module_to_string(module: &Module) -> String {
3801 let mut names = Vec::new();
3803 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3804 match module.parent_link {
3806 ModuleParentLink(ref module, name) => {
3808 collect_mod(names, &*module.upgrade().unwrap());
3810 BlockParentLink(ref module, _) => {
3811 // danger, shouldn't be ident?
3812 names.push(special_idents::opaque.name);
3813 collect_mod(names, &*module.upgrade().unwrap());
3817 collect_mod(&mut names, module);
3819 if names.is_empty() {
3820 return "???".to_string();
3822 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3826 pub struct CrateMap {
3827 pub def_map: RefCell<DefMap>,
3828 pub freevars: FreevarMap,
3829 pub export_map: ExportMap,
3830 pub trait_map: TraitMap,
3831 pub external_exports: ExternalExports,
3832 pub glob_map: Option<GlobMap>,
3835 #[derive(PartialEq,Copy, Clone)]
3836 pub enum MakeGlobMap {
3841 /// Entry point to crate resolution.
3842 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3843 ast_map: &'a hir_map::Map<'tcx>,
3844 make_glob_map: MakeGlobMap)
3846 let krate = ast_map.krate();
3847 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3849 resolver.resolve_crate(krate);
3850 session.abort_if_errors();
3852 check_unused::check_crate(&mut resolver, krate);
3855 def_map: resolver.def_map,
3856 freevars: resolver.freevars,
3857 export_map: resolver.export_map,
3858 trait_map: resolver.trait_map,
3859 external_exports: resolver.external_exports,
3860 glob_map: if resolver.make_glob_map {
3861 Some(resolver.glob_map)
3868 /// Builds a name resolution walker to be used within this module,
3869 /// or used externally, with an optional callback function.
3871 /// The callback takes a &mut bool which allows callbacks to end a
3872 /// walk when set to true, passing through the rest of the walk, while
3873 /// preserving the ribs + current module. This allows resolve_path
3874 /// calls to be made with the correct scope info. The node in the
3875 /// callback corresponds to the current node in the walk.
3876 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3877 ast_map: &'a hir_map::Map<'tcx>,
3879 make_glob_map: MakeGlobMap,
3880 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3881 -> Resolver<'a, 'tcx> {
3882 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
3884 resolver.callback = callback;
3886 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3887 session.abort_if_errors();
3889 resolve_imports::resolve_imports(&mut resolver);
3890 session.abort_if_errors();
3892 record_exports::record(&mut resolver);
3893 session.abort_if_errors();
3898 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }