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 value, type, or module definition.
910 modifiers: DefModifiers, // see note in ImportResolution about how to use this
911 def_or_module: DefOrModule,
922 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
923 let modifiers = if module.is_public {
926 DefModifiers::empty()
927 } | DefModifiers::IMPORTABLE;
929 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
932 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
933 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
936 fn module(&self) -> Option<Rc<Module>> {
937 match self.def_or_module {
938 DefOrModule::Module(ref module) => Some(module.clone()),
939 DefOrModule::Def(_) => None,
943 fn def(&self) -> Option<Def> {
944 match self.def_or_module {
945 DefOrModule::Def(def) => Some(def),
946 DefOrModule::Module(ref module) => module.def.get(),
951 // Records at most one definition that a name in a namespace is bound to
952 #[derive(Clone,Debug)]
953 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
957 NameBinding(Rc::new(RefCell::new(None)))
960 fn create_from_module(module: Rc<Module>) -> Self {
961 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
964 fn set(&self, ns_def: NsDef) {
965 *self.0.borrow_mut() = Some(ns_def);
968 fn set_modifiers(&self, modifiers: DefModifiers) {
969 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
970 ns_def.modifiers = modifiers
974 fn and_then<T, F: Fn(&NsDef) -> Option<T>>(&self, f: F) -> Option<T> {
975 self.borrow().as_ref().and_then(f)
978 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> { self.0.borrow() }
980 // Lifted versions of the NsDef methods and fields
981 fn def(&self) -> Option<Def> { self.and_then(NsDef::def) }
982 fn module(&self) -> Option<Rc<Module>> { self.and_then(NsDef::module) }
983 fn span(&self) -> Option<Span> { self.and_then(|def| def.span) }
984 fn modifiers(&self) -> Option<DefModifiers> { self.and_then(|def| Some(def.modifiers)) }
986 fn defined(&self) -> bool { self.borrow().is_some() }
988 fn defined_with(&self, modifiers: DefModifiers) -> bool {
989 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
992 fn is_public(&self) -> bool {
993 self.defined_with(DefModifiers::PUBLIC)
996 fn def_and_lp(&self) -> (Def, LastPrivate) {
997 let def = self.def().unwrap();
998 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1002 // Records the definitions (at most one for each namespace) that a name is
1004 #[derive(Clone,Debug)]
1005 pub struct NameBindings {
1006 type_ns: NameBinding, // < Meaning in type namespace.
1007 value_ns: NameBinding, // < Meaning in value namespace.
1010 impl ::std::ops::Index<Namespace> for NameBindings {
1011 type Output = NameBinding;
1012 fn index(&self, namespace: Namespace) -> &NameBinding {
1013 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1018 fn new() -> NameBindings {
1020 type_ns: NameBinding::new(),
1021 value_ns: NameBinding::new(),
1025 fn create_from_module(module: Rc<Module>) -> NameBindings {
1027 type_ns: NameBinding::create_from_module(module),
1028 value_ns: NameBinding::new(),
1032 /// Creates a new module in this set of name bindings.
1033 fn define_module(&self,
1034 parent_link: ParentLink,
1039 let module = Module::new(parent_link, def, external, is_public);
1040 self.type_ns.set(NsDef::create_from_module(Rc::new(module), Some(sp)));
1043 /// Records a type definition.
1044 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1045 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1046 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1049 /// Records a value definition.
1050 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1051 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1052 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1055 /// Returns the module node if applicable.
1056 fn get_module_if_available(&self) -> Option<Rc<Module>> { self.type_ns.module() }
1058 /// Returns the module node. Panics if this node does not have a module
1060 fn get_module(&self) -> Rc<Module> {
1061 match self.get_module_if_available() {
1063 panic!("get_module called on a node with no module definition!")
1065 Some(module_def) => module_def,
1070 /// Interns the names of the primitive types.
1071 struct PrimitiveTypeTable {
1072 primitive_types: HashMap<Name, PrimTy>,
1075 impl PrimitiveTypeTable {
1076 fn new() -> PrimitiveTypeTable {
1077 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1079 table.intern("bool", TyBool);
1080 table.intern("char", TyChar);
1081 table.intern("f32", TyFloat(TyF32));
1082 table.intern("f64", TyFloat(TyF64));
1083 table.intern("isize", TyInt(TyIs));
1084 table.intern("i8", TyInt(TyI8));
1085 table.intern("i16", TyInt(TyI16));
1086 table.intern("i32", TyInt(TyI32));
1087 table.intern("i64", TyInt(TyI64));
1088 table.intern("str", TyStr);
1089 table.intern("usize", TyUint(TyUs));
1090 table.intern("u8", TyUint(TyU8));
1091 table.intern("u16", TyUint(TyU16));
1092 table.intern("u32", TyUint(TyU32));
1093 table.intern("u64", TyUint(TyU64));
1098 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1099 self.primitive_types.insert(token::intern(string), primitive_type);
1103 /// The main resolver class.
1104 pub struct Resolver<'a, 'tcx: 'a> {
1105 session: &'a Session,
1107 ast_map: &'a hir_map::Map<'tcx>,
1109 graph_root: NameBindings,
1111 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1113 structs: FnvHashMap<DefId, Vec<Name>>,
1115 // The number of imports that are currently unresolved.
1116 unresolved_imports: usize,
1118 // The module that represents the current item scope.
1119 current_module: Rc<Module>,
1121 // The current set of local scopes, for values.
1122 // FIXME #4948: Reuse ribs to avoid allocation.
1123 value_ribs: Vec<Rib>,
1125 // The current set of local scopes, for types.
1126 type_ribs: Vec<Rib>,
1128 // The current set of local scopes, for labels.
1129 label_ribs: Vec<Rib>,
1131 // The trait that the current context can refer to.
1132 current_trait_ref: Option<(DefId, TraitRef)>,
1134 // The current self type if inside an impl (used for better errors).
1135 current_self_type: Option<Ty>,
1137 // The idents for the primitive types.
1138 primitive_type_table: PrimitiveTypeTable,
1140 def_map: RefCell<DefMap>,
1141 freevars: FreevarMap,
1142 freevars_seen: NodeMap<NodeMap<usize>>,
1143 export_map: ExportMap,
1144 trait_map: TraitMap,
1145 external_exports: ExternalExports,
1147 // Whether or not to print error messages. Can be set to true
1148 // when getting additional info for error message suggestions,
1149 // so as to avoid printing duplicate errors
1152 make_glob_map: bool,
1153 // Maps imports to the names of items actually imported (this actually maps
1154 // all imports, but only glob imports are actually interesting).
1157 used_imports: HashSet<(NodeId, Namespace)>,
1158 used_crates: HashSet<CrateNum>,
1160 // Callback function for intercepting walks
1161 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1162 // The intention is that the callback modifies this flag.
1163 // Once set, the resolver falls out of the walk, preserving the ribs.
1167 #[derive(PartialEq)]
1168 enum FallbackChecks {
1170 OnlyTraitAndStatics,
1173 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1174 fn new(session: &'a Session,
1175 ast_map: &'a hir_map::Map<'tcx>,
1177 make_glob_map: MakeGlobMap)
1178 -> Resolver<'a, 'tcx> {
1179 let graph_root = NameBindings::new();
1181 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1182 graph_root.define_module(NoParentLink,
1183 Some(DefMod(root_def_id)),
1188 let current_module = graph_root.get_module();
1195 // The outermost module has def ID 0; this is not reflected in the
1197 graph_root: graph_root,
1199 trait_item_map: FnvHashMap(),
1200 structs: FnvHashMap(),
1202 unresolved_imports: 0,
1204 current_module: current_module,
1205 value_ribs: Vec::new(),
1206 type_ribs: Vec::new(),
1207 label_ribs: Vec::new(),
1209 current_trait_ref: None,
1210 current_self_type: None,
1212 primitive_type_table: PrimitiveTypeTable::new(),
1214 def_map: RefCell::new(NodeMap()),
1215 freevars: NodeMap(),
1216 freevars_seen: NodeMap(),
1217 export_map: NodeMap(),
1218 trait_map: NodeMap(),
1219 used_imports: HashSet::new(),
1220 used_crates: HashSet::new(),
1221 external_exports: DefIdSet(),
1224 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1225 glob_map: HashMap::new(),
1233 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1234 if !self.make_glob_map {
1237 if self.glob_map.contains_key(&import_id) {
1238 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1242 let mut new_set = HashSet::new();
1243 new_set.insert(name);
1244 self.glob_map.insert(import_id, new_set);
1247 fn get_trait_name(&self, did: DefId) -> Name {
1248 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1249 self.ast_map.expect_item(node_id).name
1251 csearch::get_trait_name(&self.session.cstore, did)
1255 /// Checks that the names of external crates don't collide with other
1256 /// external crates.
1257 fn check_for_conflicts_between_external_crates(&self,
1261 if module.external_module_children.borrow().contains_key(&name) {
1262 span_err!(self.session,
1265 "an external crate named `{}` has already been imported into this module",
1270 /// Checks that the names of items don't collide with external crates.
1271 fn check_for_conflicts_between_external_crates_and_items(&self,
1275 if module.external_module_children.borrow().contains_key(&name) {
1276 span_err!(self.session,
1279 "the name `{}` conflicts with an external crate that has been imported \
1285 /// Resolves the given module path from the given root `module_`.
1286 fn resolve_module_path_from_root(&mut self,
1287 module_: Rc<Module>,
1288 module_path: &[Name],
1291 name_search_type: NameSearchType,
1293 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1294 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1295 match module.external_module_children.borrow().get(&needle) {
1296 Some(_) => Some(module.clone()),
1297 None => match module.parent_link {
1298 ModuleParentLink(ref parent, _) => {
1299 search_parent_externals(needle, &parent.upgrade().unwrap())
1306 let mut search_module = module_;
1307 let mut index = index;
1308 let module_path_len = module_path.len();
1309 let mut closest_private = lp;
1311 // Resolve the module part of the path. This does not involve looking
1312 // upward though scope chains; we simply resolve names directly in
1313 // modules as we go.
1314 while index < module_path_len {
1315 let name = module_path[index];
1316 match self.resolve_name_in_module(search_module.clone(),
1322 let segment_name = name.as_str();
1323 let module_name = module_to_string(&*search_module);
1324 let mut span = span;
1325 let msg = if "???" == &module_name[..] {
1326 span.hi = span.lo + Pos::from_usize(segment_name.len());
1328 match search_parent_externals(name, &self.current_module) {
1330 let path_str = names_to_string(module_path);
1331 let target_mod_str = module_to_string(&*module);
1332 let current_mod_str = module_to_string(&*self.current_module);
1334 let prefix = if target_mod_str == current_mod_str {
1335 "self::".to_string()
1337 format!("{}::", target_mod_str)
1340 format!("Did you mean `{}{}`?", prefix, path_str)
1342 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1345 format!("Could not find `{}` in `{}`", segment_name, module_name)
1348 return Failed(Some((span, msg)));
1350 Failed(err) => return Failed(err),
1352 debug!("(resolving module path for import) module resolution is \
1355 return Indeterminate;
1357 Success((target, used_proxy)) => {
1358 // Check to see whether there are type bindings, and, if
1359 // so, whether there is a module within.
1360 if let Some(module_def) = target.binding.module() {
1361 // track extern crates for unused_extern_crate lint
1362 if let Some(did) = module_def.def_id() {
1363 self.used_crates.insert(did.krate);
1366 search_module = module_def;
1368 // Keep track of the closest private module used
1369 // when resolving this import chain.
1370 if !used_proxy && !search_module.is_public {
1371 if let Some(did) = search_module.def_id() {
1372 closest_private = LastMod(DependsOn(did));
1376 let msg = format!("Not a module `{}`", name);
1377 return Failed(Some((span, msg)));
1385 return Success((search_module, closest_private));
1388 /// Attempts to resolve the module part of an import directive or path
1389 /// rooted at the given module.
1391 /// On success, returns the resolved module, and the closest *private*
1392 /// module found to the destination when resolving this path.
1393 fn resolve_module_path(&mut self,
1394 module_: Rc<Module>,
1395 module_path: &[Name],
1396 use_lexical_scope: UseLexicalScopeFlag,
1398 name_search_type: NameSearchType)
1399 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1400 let module_path_len = module_path.len();
1401 assert!(module_path_len > 0);
1403 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1404 names_to_string(module_path),
1405 module_to_string(&*module_));
1407 // Resolve the module prefix, if any.
1408 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1413 match module_prefix_result {
1415 let mpath = names_to_string(module_path);
1416 let mpath = &mpath[..];
1417 match mpath.rfind(':') {
1419 let msg = format!("Could not find `{}` in `{}`",
1420 // idx +- 1 to account for the
1421 // colons on either side
1424 return Failed(Some((span, msg)));
1427 return Failed(None);
1431 Failed(err) => return Failed(err),
1433 debug!("(resolving module path for import) indeterminate; bailing");
1434 return Indeterminate;
1436 Success(NoPrefixFound) => {
1437 // There was no prefix, so we're considering the first element
1438 // of the path. How we handle this depends on whether we were
1439 // instructed to use lexical scope or not.
1440 match use_lexical_scope {
1441 DontUseLexicalScope => {
1442 // This is a crate-relative path. We will start the
1443 // resolution process at index zero.
1444 search_module = self.graph_root.get_module();
1446 last_private = LastMod(AllPublic);
1448 UseLexicalScope => {
1449 // This is not a crate-relative path. We resolve the
1450 // first component of the path in the current lexical
1451 // scope and then proceed to resolve below that.
1452 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1453 Failed(err) => return Failed(err),
1455 debug!("(resolving module path for import) indeterminate; bailing");
1456 return Indeterminate;
1458 Success(containing_module) => {
1459 search_module = containing_module;
1461 last_private = LastMod(AllPublic);
1467 Success(PrefixFound(ref containing_module, index)) => {
1468 search_module = containing_module.clone();
1469 start_index = index;
1470 last_private = LastMod(DependsOn(containing_module.def_id()
1475 self.resolve_module_path_from_root(search_module,
1483 /// Invariant: This must only be called during main resolution, not during
1484 /// import resolution.
1485 fn resolve_item_in_lexical_scope(&mut self,
1486 module_: Rc<Module>,
1488 namespace: Namespace)
1489 -> ResolveResult<(Target, bool)> {
1490 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1493 module_to_string(&*module_));
1495 // The current module node is handled specially. First, check for
1496 // its immediate children.
1497 build_reduced_graph::populate_module_if_necessary(self, &module_);
1499 match module_.children.borrow().get(&name) {
1500 Some(name_bindings) if name_bindings[namespace].defined() => {
1501 debug!("top name bindings succeeded");
1502 return Success((Target::new(module_.clone(),
1503 name_bindings[namespace].clone(),
1508 // Not found; continue.
1512 // Now check for its import directives. We don't have to have resolved
1513 // all its imports in the usual way; this is because chains of
1514 // adjacent import statements are processed as though they mutated the
1516 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1517 match (*import_resolution).target_for_namespace(namespace) {
1519 // Not found; continue.
1520 debug!("(resolving item in lexical scope) found import resolution, but not \
1525 debug!("(resolving item in lexical scope) using import resolution");
1526 // track used imports and extern crates as well
1527 let id = import_resolution.id(namespace);
1528 self.used_imports.insert((id, namespace));
1529 self.record_import_use(id, name);
1530 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1531 self.used_crates.insert(kid);
1533 return Success((target, false));
1538 // Search for external modules.
1539 if namespace == TypeNS {
1540 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1541 let child = module_.external_module_children.borrow().get(&name).cloned();
1542 if let Some(module) = child {
1543 let name_binding = NameBinding::create_from_module(module);
1544 debug!("lower name bindings succeeded");
1545 return Success((Target::new(module_, name_binding, Shadowable::Never),
1550 // Finally, proceed up the scope chain looking for parent modules.
1551 let mut search_module = module_;
1553 // Go to the next parent.
1554 match search_module.parent_link.clone() {
1556 // No more parents. This module was unresolved.
1557 debug!("(resolving item in lexical scope) unresolved module");
1558 return Failed(None);
1560 ModuleParentLink(parent_module_node, _) => {
1561 if search_module.is_normal() {
1562 // We stop the search here.
1563 debug!("(resolving item in lexical scope) unresolved module: not \
1564 searching through module parents");
1565 return Failed(None);
1567 search_module = parent_module_node.upgrade().unwrap();
1570 BlockParentLink(ref parent_module_node, _) => {
1571 search_module = parent_module_node.upgrade().unwrap();
1575 // Resolve the name in the parent module.
1576 match self.resolve_name_in_module(search_module.clone(),
1581 Failed(Some((span, msg))) => {
1582 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1584 Failed(None) => (), // Continue up the search chain.
1586 // We couldn't see through the higher scope because of an
1587 // unresolved import higher up. Bail.
1589 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1590 return Indeterminate;
1592 Success((target, used_reexport)) => {
1593 // We found the module.
1594 debug!("(resolving item in lexical scope) found name in module, done");
1595 return Success((target, used_reexport));
1601 /// Resolves a module name in the current lexical scope.
1602 fn resolve_module_in_lexical_scope(&mut self,
1603 module_: Rc<Module>,
1605 -> ResolveResult<Rc<Module>> {
1606 // If this module is an anonymous module, resolve the item in the
1607 // lexical scope. Otherwise, resolve the item from the crate root.
1608 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1609 match resolve_result {
1610 Success((target, _)) => {
1611 if let Some(module_def) = target.binding.module() {
1612 return Success(module_def)
1614 debug!("!!! (resolving module in lexical scope) module \
1615 wasn't actually a module!");
1616 return Failed(None);
1620 debug!("(resolving module in lexical scope) indeterminate; bailing");
1621 return Indeterminate;
1624 debug!("(resolving module in lexical scope) failed to resolve");
1630 /// Returns the nearest normal module parent of the given module.
1631 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1632 let mut module_ = module_;
1634 match module_.parent_link.clone() {
1635 NoParentLink => return None,
1636 ModuleParentLink(new_module, _) |
1637 BlockParentLink(new_module, _) => {
1638 let new_module = new_module.upgrade().unwrap();
1639 if new_module.is_normal() {
1640 return Some(new_module);
1642 module_ = new_module;
1648 /// Returns the nearest normal module parent of the given module, or the
1649 /// module itself if it is a normal module.
1650 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1651 if module_.is_normal() {
1654 match self.get_nearest_normal_module_parent(module_.clone()) {
1656 Some(new_module) => new_module,
1660 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1661 /// (b) some chain of `super::`.
1662 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1663 fn resolve_module_prefix(&mut self,
1664 module_: Rc<Module>,
1665 module_path: &[Name])
1666 -> ResolveResult<ModulePrefixResult> {
1667 // Start at the current module if we see `self` or `super`, or at the
1668 // top of the crate otherwise.
1669 let mut i = match &*module_path[0].as_str() {
1672 _ => return Success(NoPrefixFound),
1674 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1676 // Now loop through all the `super`s we find.
1677 while i < module_path.len() && "super" == module_path[i].as_str() {
1678 debug!("(resolving module prefix) resolving `super` at {}",
1679 module_to_string(&*containing_module));
1680 match self.get_nearest_normal_module_parent(containing_module) {
1681 None => return Failed(None),
1682 Some(new_module) => {
1683 containing_module = new_module;
1689 debug!("(resolving module prefix) finished resolving prefix at {}",
1690 module_to_string(&*containing_module));
1692 return Success(PrefixFound(containing_module, i));
1695 /// Attempts to resolve the supplied name in the given module for the
1696 /// given namespace. If successful, returns the target corresponding to
1699 /// The boolean returned on success is an indicator of whether this lookup
1700 /// passed through a public re-export proxy.
1701 fn resolve_name_in_module(&mut self,
1702 module_: Rc<Module>,
1704 namespace: Namespace,
1705 name_search_type: NameSearchType,
1706 allow_private_imports: bool)
1707 -> ResolveResult<(Target, bool)> {
1708 debug!("(resolving name in module) resolving `{}` in `{}`",
1710 module_to_string(&*module_));
1712 // First, check the direct children of the module.
1713 build_reduced_graph::populate_module_if_necessary(self, &module_);
1715 match module_.children.borrow().get(&name) {
1716 Some(name_bindings) if name_bindings[namespace].defined() => {
1717 debug!("(resolving name in module) found node as child");
1718 return Success((Target::new(module_.clone(),
1719 name_bindings[namespace].clone(),
1728 // Next, check the module's imports if necessary.
1730 // If this is a search of all imports, we should be done with glob
1731 // resolution at this point.
1732 if name_search_type == PathSearch {
1733 assert_eq!(module_.glob_count.get(), 0);
1736 // Check the list of resolved imports.
1737 match module_.import_resolutions.borrow().get(&name) {
1738 Some(import_resolution) if allow_private_imports || import_resolution.is_public => {
1740 if import_resolution.is_public && import_resolution.outstanding_references != 0 {
1741 debug!("(resolving name in module) import unresolved; bailing out");
1742 return Indeterminate;
1744 match import_resolution.target_for_namespace(namespace) {
1746 debug!("(resolving name in module) name found, but not in namespace {:?}",
1750 debug!("(resolving name in module) resolved to import");
1751 // track used imports and extern crates as well
1752 let id = import_resolution.id(namespace);
1753 self.used_imports.insert((id, namespace));
1754 self.record_import_use(id, name);
1755 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1756 self.used_crates.insert(kid);
1758 return Success((target, true));
1762 Some(..) | None => {} // Continue.
1765 // Finally, search through external children.
1766 if namespace == TypeNS {
1767 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1768 let child = module_.external_module_children.borrow().get(&name).cloned();
1769 if let Some(module) = child {
1770 let name_binding = NameBinding::create_from_module(module);
1771 return Success((Target::new(module_, name_binding, Shadowable::Never),
1776 // We're out of luck.
1777 debug!("(resolving name in module) failed to resolve `{}`", name);
1778 return Failed(None);
1781 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1782 let index = module_.resolved_import_count.get();
1783 let imports = module_.imports.borrow();
1784 let import_count = imports.len();
1785 if index != import_count {
1787 (*imports)[index].span,
1788 ResolutionError::UnresolvedImport(None));
1791 // Descend into children and anonymous children.
1792 build_reduced_graph::populate_module_if_necessary(self, &module_);
1794 for (_, child_node) in module_.children.borrow().iter() {
1795 match child_node.get_module_if_available() {
1799 Some(child_module) => {
1800 self.report_unresolved_imports(child_module);
1805 for (_, module_) in module_.anonymous_children.borrow().iter() {
1806 self.report_unresolved_imports(module_.clone());
1812 // We maintain a list of value ribs and type ribs.
1814 // Simultaneously, we keep track of the current position in the module
1815 // graph in the `current_module` pointer. When we go to resolve a name in
1816 // the value or type namespaces, we first look through all the ribs and
1817 // then query the module graph. When we resolve a name in the module
1818 // namespace, we can skip all the ribs (since nested modules are not
1819 // allowed within blocks in Rust) and jump straight to the current module
1822 // Named implementations are handled separately. When we find a method
1823 // call, we consult the module node to find all of the implementations in
1824 // scope. This information is lazily cached in the module node. We then
1825 // generate a fake "implementation scope" containing all the
1826 // implementations thus found, for compatibility with old resolve pass.
1828 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1829 where F: FnOnce(&mut Resolver)
1831 let orig_module = self.current_module.clone();
1833 // Move down in the graph.
1839 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1841 match orig_module.children.borrow().get(&name) {
1843 debug!("!!! (with scope) didn't find `{}` in `{}`",
1845 module_to_string(&*orig_module));
1847 Some(name_bindings) => {
1848 match (*name_bindings).get_module_if_available() {
1850 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1852 module_to_string(&*orig_module));
1855 self.current_module = module_;
1865 self.current_module = orig_module;
1868 /// Searches the current set of local scopes for labels.
1869 /// Stops after meeting a closure.
1870 fn search_label(&self, name: Name) -> Option<DefLike> {
1871 for rib in self.label_ribs.iter().rev() {
1877 // Do not resolve labels across function boundary
1881 let result = rib.bindings.get(&name).cloned();
1882 if result.is_some() {
1889 fn resolve_crate(&mut self, krate: &hir::Crate) {
1890 debug!("(resolving crate) starting");
1892 visit::walk_crate(self, krate);
1895 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1896 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1897 span_err!(self.session,
1900 "user-defined types or type parameters cannot shadow the primitive types");
1904 fn resolve_item(&mut self, item: &Item) {
1905 let name = item.name;
1907 debug!("(resolving item) resolving {}", name);
1910 ItemEnum(_, ref generics) |
1911 ItemTy(_, ref generics) |
1912 ItemStruct(_, ref generics) => {
1913 self.check_if_primitive_type_name(name, item.span);
1915 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1916 |this| visit::walk_item(this, item));
1918 ItemFn(_, _, _, _, ref generics, _) => {
1919 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1920 |this| visit::walk_item(this, item));
1923 ItemDefaultImpl(_, ref trait_ref) => {
1924 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1926 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1927 self.resolve_implementation(generics,
1934 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1935 self.check_if_primitive_type_name(name, item.span);
1937 // Create a new rib for the trait-wide type parameters.
1938 self.with_type_parameter_rib(HasTypeParameters(generics,
1942 let local_def_id = this.ast_map.local_def_id(item.id);
1943 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1944 this.visit_generics(generics);
1945 walk_list!(this, visit_ty_param_bound, bounds);
1947 for trait_item in trait_items {
1948 match trait_item.node {
1949 hir::ConstTraitItem(_, ref default) => {
1950 // Only impose the restrictions of
1951 // ConstRibKind if there's an actual constant
1952 // expression in a provided default.
1953 if default.is_some() {
1954 this.with_constant_rib(|this| {
1955 visit::walk_trait_item(this, trait_item)
1958 visit::walk_trait_item(this, trait_item)
1961 hir::MethodTraitItem(ref sig, _) => {
1962 let type_parameters =
1963 HasTypeParameters(&sig.generics,
1966 this.with_type_parameter_rib(type_parameters, |this| {
1967 visit::walk_trait_item(this, trait_item)
1970 hir::TypeTraitItem(..) => {
1971 this.check_if_primitive_type_name(trait_item.name,
1973 this.with_type_parameter_rib(NoTypeParameters, |this| {
1974 visit::walk_trait_item(this, trait_item)
1983 ItemMod(_) | ItemForeignMod(_) => {
1984 self.with_scope(Some(name), |this| {
1985 visit::walk_item(this, item);
1989 ItemConst(..) | ItemStatic(..) => {
1990 self.with_constant_rib(|this| {
1991 visit::walk_item(this, item);
1995 ItemUse(ref view_path) => {
1996 // check for imports shadowing primitive types
1997 let check_rename = |this: &Self, id, name| {
1998 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
1999 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2000 this.check_if_primitive_type_name(name, item.span);
2006 match view_path.node {
2007 hir::ViewPathSimple(name, _) => {
2008 check_rename(self, item.id, name);
2010 hir::ViewPathList(ref prefix, ref items) => {
2012 if let Some(name) = item.node.rename() {
2013 check_rename(self, item.node.id(), name);
2017 // Resolve prefix of an import with empty braces (issue #28388)
2018 if items.is_empty() && !prefix.segments.is_empty() {
2019 match self.resolve_crate_relative_path(prefix.span,
2023 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2027 ResolutionError::FailedToResolve(
2028 &path_names_to_string(prefix, 0)));
2037 ItemExternCrate(_) => {
2038 // do nothing, these are just around to be encoded
2043 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2044 where F: FnOnce(&mut Resolver)
2046 match type_parameters {
2047 HasTypeParameters(generics, space, rib_kind) => {
2048 let mut function_type_rib = Rib::new(rib_kind);
2049 let mut seen_bindings = HashSet::new();
2050 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2051 let name = type_parameter.name;
2052 debug!("with_type_parameter_rib: {}", type_parameter.id);
2054 if seen_bindings.contains(&name) {
2056 type_parameter.span,
2057 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2059 seen_bindings.insert(name);
2061 // plain insert (no renaming)
2062 function_type_rib.bindings
2064 DlDef(DefTyParam(space,
2067 .local_def_id(type_parameter.id),
2070 self.type_ribs.push(function_type_rib);
2073 NoTypeParameters => {
2080 match type_parameters {
2081 HasTypeParameters(..) => {
2083 self.type_ribs.pop();
2086 NoTypeParameters => {}
2090 fn with_label_rib<F>(&mut self, f: F)
2091 where F: FnOnce(&mut Resolver)
2093 self.label_ribs.push(Rib::new(NormalRibKind));
2096 self.label_ribs.pop();
2100 fn with_constant_rib<F>(&mut self, f: F)
2101 where F: FnOnce(&mut Resolver)
2103 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2104 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2107 self.type_ribs.pop();
2108 self.value_ribs.pop();
2112 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2113 // Create a value rib for the function.
2114 self.value_ribs.push(Rib::new(rib_kind));
2116 // Create a label rib for the function.
2117 self.label_ribs.push(Rib::new(rib_kind));
2119 // Add each argument to the rib.
2120 let mut bindings_list = HashMap::new();
2121 for argument in &declaration.inputs {
2122 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2124 self.visit_ty(&*argument.ty);
2126 debug!("(resolving function) recorded argument");
2128 visit::walk_fn_ret_ty(self, &declaration.output);
2130 // Resolve the function body.
2131 self.visit_block(&*block);
2133 debug!("(resolving function) leaving function");
2136 self.label_ribs.pop();
2137 self.value_ribs.pop();
2141 fn resolve_trait_reference(&mut self,
2145 -> Result<PathResolution, ()> {
2146 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2147 if let DefTrait(_) = path_res.base_def {
2148 debug!("(resolving trait) found trait def: {:?}", path_res);
2153 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2156 // If it's a typedef, give a note
2157 if let DefTy(..) = path_res.base_def {
2159 .span_note(trait_path.span, "`type` aliases cannot be used for traits");
2166 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2172 fn resolve_generics(&mut self, generics: &Generics) {
2173 for type_parameter in generics.ty_params.iter() {
2174 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2176 for predicate in &generics.where_clause.predicates {
2178 &hir::WherePredicate::BoundPredicate(_) |
2179 &hir::WherePredicate::RegionPredicate(_) => {}
2180 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2181 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2182 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2183 self.record_def(eq_pred.id, path_res.unwrap());
2187 ResolutionError::UndeclaredAssociatedType);
2192 visit::walk_generics(self, generics);
2195 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2196 where F: FnOnce(&mut Resolver) -> T
2198 // Handle nested impls (inside fn bodies)
2199 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2200 let result = f(self);
2201 self.current_self_type = previous_value;
2205 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2206 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2208 let mut new_val = None;
2209 let mut new_id = None;
2210 if let Some(trait_ref) = opt_trait_ref {
2211 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2214 assert!(path_res.depth == 0);
2215 self.record_def(trait_ref.ref_id, path_res);
2216 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2217 new_id = Some(path_res.base_def.def_id());
2219 visit::walk_trait_ref(self, trait_ref);
2221 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2222 let result = f(self, new_id);
2223 self.current_trait_ref = original_trait_ref;
2227 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2228 where F: FnOnce(&mut Resolver)
2230 let mut self_type_rib = Rib::new(NormalRibKind);
2232 // plain insert (no renaming, types are not currently hygienic....)
2233 let name = special_names::type_self;
2234 self_type_rib.bindings.insert(name, DlDef(self_def));
2235 self.type_ribs.push(self_type_rib);
2238 self.type_ribs.pop();
2242 fn resolve_implementation(&mut self,
2243 generics: &Generics,
2244 opt_trait_reference: &Option<TraitRef>,
2247 impl_items: &[P<ImplItem>]) {
2248 // If applicable, create a rib for the type parameters.
2249 self.with_type_parameter_rib(HasTypeParameters(generics,
2253 // Resolve the type parameters.
2254 this.visit_generics(generics);
2256 // Resolve the trait reference, if necessary.
2257 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2258 // Resolve the self type.
2259 this.visit_ty(self_type);
2261 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2262 this.with_current_self_type(self_type, |this| {
2263 for impl_item in impl_items {
2264 match impl_item.node {
2265 ConstImplItem(..) => {
2266 // If this is a trait impl, ensure the const
2268 this.check_trait_item(impl_item.name,
2270 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2271 this.with_constant_rib(|this| {
2272 visit::walk_impl_item(this, impl_item);
2275 MethodImplItem(ref sig, _) => {
2276 // If this is a trait impl, ensure the method
2278 this.check_trait_item(impl_item.name,
2280 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2282 // We also need a new scope for the method-
2283 // specific type parameters.
2284 let type_parameters =
2285 HasTypeParameters(&sig.generics,
2288 this.with_type_parameter_rib(type_parameters, |this| {
2289 visit::walk_impl_item(this, impl_item);
2292 TypeImplItem(ref ty) => {
2293 // If this is a trait impl, ensure the type
2295 this.check_trait_item(impl_item.name,
2297 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2309 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2310 where F: FnOnce(Name, &str) -> ResolutionError
2312 // If there is a TraitRef in scope for an impl, then the method must be in the
2314 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2315 if !self.trait_item_map.contains_key(&(name, did)) {
2316 let path_str = path_names_to_string(&trait_ref.path, 0);
2317 resolve_error(self, span, err(name, &*path_str));
2322 fn resolve_local(&mut self, local: &Local) {
2323 // Resolve the type.
2324 walk_list!(self, visit_ty, &local.ty);
2326 // Resolve the initializer.
2327 walk_list!(self, visit_expr, &local.init);
2329 // Resolve the pattern.
2330 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2333 // build a map from pattern identifiers to binding-info's.
2334 // this is done hygienically. This could arise for a macro
2335 // that expands into an or-pattern where one 'x' was from the
2336 // user and one 'x' came from the macro.
2337 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2338 let mut result = HashMap::new();
2339 pat_bindings_hygienic(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2340 let name = mtwt::resolve(path1.node);
2344 binding_mode: binding_mode,
2350 // check that all of the arms in an or-pattern have exactly the
2351 // same set of bindings, with the same binding modes for each.
2352 fn check_consistent_bindings(&mut self, arm: &Arm) {
2353 if arm.pats.is_empty() {
2356 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2357 for (i, p) in arm.pats.iter().enumerate() {
2358 let map_i = self.binding_mode_map(&**p);
2360 for (&key, &binding_0) in &map_0 {
2361 match map_i.get(&key) {
2365 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2367 Some(binding_i) => {
2368 if binding_0.binding_mode != binding_i.binding_mode {
2371 ResolutionError::VariableBoundWithDifferentMode(key,
2378 for (&key, &binding) in &map_i {
2379 if !map_0.contains_key(&key) {
2382 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2388 fn resolve_arm(&mut self, arm: &Arm) {
2389 self.value_ribs.push(Rib::new(NormalRibKind));
2391 let mut bindings_list = HashMap::new();
2392 for pattern in &arm.pats {
2393 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2396 // This has to happen *after* we determine which
2397 // pat_idents are variants
2398 self.check_consistent_bindings(arm);
2400 walk_list!(self, visit_expr, &arm.guard);
2401 self.visit_expr(&*arm.body);
2404 self.value_ribs.pop();
2408 fn resolve_block(&mut self, block: &Block) {
2409 debug!("(resolving block) entering block");
2410 self.value_ribs.push(Rib::new(NormalRibKind));
2412 // Move down in the graph, if there's an anonymous module rooted here.
2413 let orig_module = self.current_module.clone();
2414 match orig_module.anonymous_children.borrow().get(&block.id) {
2418 Some(anonymous_module) => {
2419 debug!("(resolving block) found anonymous module, moving down");
2420 self.current_module = anonymous_module.clone();
2424 // Check for imports appearing after non-item statements.
2425 let mut found_non_item = false;
2426 for statement in &block.stmts {
2427 if let hir::StmtDecl(ref declaration, _) = statement.node {
2428 if let hir::DeclItem(ref i) = declaration.node {
2430 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2431 span_err!(self.session,
2434 "imports are not allowed after non-item statements");
2439 found_non_item = true
2442 found_non_item = true;
2446 // Descend into the block.
2447 visit::walk_block(self, block);
2451 self.current_module = orig_module;
2452 self.value_ribs.pop();
2454 debug!("(resolving block) leaving block");
2457 fn resolve_type(&mut self, ty: &Ty) {
2459 TyPath(ref maybe_qself, ref path) => {
2460 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2461 maybe_qself.as_ref(),
2465 // `<T>::a::b::c` is resolved by typeck alone.
2466 TypecheckRequired => {
2467 // Resolve embedded types.
2468 visit::walk_ty(self, ty);
2471 ResolveAttempt(resolution) => resolution,
2474 // This is a path in the type namespace. Walk through scopes
2478 // Write the result into the def map.
2479 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2480 path_names_to_string(path, 0),
2483 self.record_def(ty.id, def);
2486 // Keep reporting some errors even if they're ignored above.
2487 self.resolve_path(ty.id, path, 0, TypeNS, true);
2489 let kind = if maybe_qself.is_some() {
2495 let self_type_name = special_idents::type_self.name;
2496 let is_invalid_self_type_name = path.segments.len() > 0 &&
2497 maybe_qself.is_none() &&
2498 path.segments[0].identifier.name ==
2500 if is_invalid_self_type_name {
2503 ResolutionError::SelfUsedOutsideImplOrTrait);
2507 ResolutionError::UseOfUndeclared(
2509 &*path_names_to_string(path,
2518 // Resolve embedded types.
2519 visit::walk_ty(self, ty);
2522 fn resolve_pattern(&mut self,
2524 mode: PatternBindingMode,
2525 // Maps idents to the node ID for the (outermost)
2526 // pattern that binds them
2527 bindings_list: &mut HashMap<Name, NodeId>) {
2528 let pat_id = pattern.id;
2529 walk_pat(pattern, |pattern| {
2530 match pattern.node {
2531 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2532 // The meaning of PatIdent with no type parameters
2533 // depends on whether an enum variant or unit-like struct
2534 // with that name is in scope. The probing lookup has to
2535 // be careful not to emit spurious errors. Only matching
2536 // patterns (match) can match nullary variants or
2537 // unit-like structs. For binding patterns (let
2538 // and the LHS of @-patterns), matching such a value is
2539 // simply disallowed (since it's rarely what you want).
2540 let const_ok = mode == RefutableMode && at_rhs.is_none();
2542 let ident = path1.node;
2543 let renamed = mtwt::resolve(ident);
2545 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2546 FoundStructOrEnumVariant(def, lp) if const_ok => {
2547 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2550 self.enforce_default_binding_mode(pattern,
2553 self.record_def(pattern.id,
2560 FoundStructOrEnumVariant(..) => {
2564 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2568 FoundConst(def, lp, _) if const_ok => {
2569 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2571 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2572 self.record_def(pattern.id,
2579 FoundConst(def, _, name) => {
2583 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2587 BareIdentifierPatternUnresolved => {
2588 debug!("(resolving pattern) binding `{}`", renamed);
2590 let def_id = self.ast_map.local_def_id(pattern.id);
2591 let def = DefLocal(def_id, pattern.id);
2593 // Record the definition so that later passes
2594 // will be able to distinguish variants from
2595 // locals in patterns.
2597 self.record_def(pattern.id,
2600 last_private: LastMod(AllPublic),
2604 // Add the binding to the local ribs, if it
2605 // doesn't already exist in the bindings list. (We
2606 // must not add it if it's in the bindings list
2607 // because that breaks the assumptions later
2608 // passes make about or-patterns.)
2609 if !bindings_list.contains_key(&renamed) {
2610 let this = &mut *self;
2611 let last_rib = this.value_ribs.last_mut().unwrap();
2612 last_rib.bindings.insert(renamed, DlDef(def));
2613 bindings_list.insert(renamed, pat_id);
2614 } else if mode == ArgumentIrrefutableMode &&
2615 bindings_list.contains_key(&renamed) {
2616 // Forbid duplicate bindings in the same
2621 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2622 &ident.name.as_str())
2624 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2625 // Then this is a duplicate variable in the
2626 // same disjunction, which is an error.
2630 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2631 &ident.name.as_str())
2634 // Else, not bound in the same pattern: do
2640 PatEnum(ref path, _) => {
2641 // This must be an enum variant, struct or const.
2642 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2647 // The below shouldn't happen because all
2648 // qualified paths should be in PatQPath.
2649 TypecheckRequired =>
2650 self.session.span_bug(path.span,
2651 "resolve_possibly_assoc_item claimed
2653 that a path in PatEnum requires typecheck
2655 to resolve, but qualified paths should be
2658 ResolveAttempt(resolution) => resolution,
2660 if let Some(path_res) = resolution {
2661 match path_res.base_def {
2662 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2663 self.record_def(pattern.id, path_res);
2666 resolve_error(&self,
2668 ResolutionError::StaticVariableReference);
2671 // If anything ends up here entirely resolved,
2672 // it's an error. If anything ends up here
2673 // partially resolved, that's OK, because it may
2674 // be a `T::CONST` that typeck will resolve.
2675 if path_res.depth == 0 {
2679 ResolutionError::NotAnEnumVariantStructOrConst(
2688 let const_name = path.segments
2693 let traits = self.get_traits_containing_item(const_name);
2694 self.trait_map.insert(pattern.id, traits);
2695 self.record_def(pattern.id, path_res);
2703 ResolutionError::UnresolvedEnumVariantStructOrConst(
2704 &path.segments.last().unwrap().identifier.name.as_str())
2707 visit::walk_path(self, path);
2710 PatQPath(ref qself, ref path) => {
2711 // Associated constants only.
2712 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2717 TypecheckRequired => {
2718 // All `<T>::CONST` should end up here, and will
2719 // require use of the trait map to resolve
2720 // during typechecking.
2721 let const_name = path.segments
2726 let traits = self.get_traits_containing_item(const_name);
2727 self.trait_map.insert(pattern.id, traits);
2728 visit::walk_pat(self, pattern);
2731 ResolveAttempt(resolution) => resolution,
2733 if let Some(path_res) = resolution {
2734 match path_res.base_def {
2735 // All `<T as Trait>::CONST` should end up here, and
2736 // have the trait already selected.
2737 DefAssociatedConst(..) => {
2738 self.record_def(pattern.id, path_res);
2744 ResolutionError::NotAnAssociatedConst(
2745 &path.segments.last().unwrap().identifier.name.as_str()
2753 ResolutionError::UnresolvedAssociatedConst(&path.segments
2760 visit::walk_pat(self, pattern);
2763 PatStruct(ref path, _, _) => {
2764 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2765 Some(definition) => {
2766 self.record_def(pattern.id, definition);
2769 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2773 ResolutionError::DoesNotNameAStruct(
2774 &*path_names_to_string(path, 0))
2778 visit::walk_path(self, path);
2781 PatLit(_) | PatRange(..) => {
2782 visit::walk_pat(self, pattern);
2793 fn resolve_bare_identifier_pattern(&mut self,
2796 -> BareIdentifierPatternResolution {
2797 let module = self.current_module.clone();
2798 match self.resolve_item_in_lexical_scope(module, name, ValueNS) {
2799 Success((target, _)) => {
2800 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2802 target.binding.borrow());
2803 match target.binding.def() {
2805 panic!("resolved name in the value namespace to a set of name bindings \
2808 // For the two success cases, this lookup can be
2809 // considered as not having a private component because
2810 // the lookup happened only within the current module.
2811 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2812 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2814 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2815 return FoundConst(def, LastMod(AllPublic), name);
2817 Some(DefStatic(..)) => {
2818 resolve_error(self, span, ResolutionError::StaticVariableReference);
2819 return BareIdentifierPatternUnresolved;
2821 _ => return BareIdentifierPatternUnresolved
2826 panic!("unexpected indeterminate result");
2830 Some((span, msg)) => {
2831 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2836 debug!("(resolve bare identifier pattern) failed to find {}", name);
2837 return BareIdentifierPatternUnresolved;
2842 /// Handles paths that may refer to associated items
2843 fn resolve_possibly_assoc_item(&mut self,
2845 maybe_qself: Option<&hir::QSelf>,
2847 namespace: Namespace,
2849 -> AssocItemResolveResult {
2850 let max_assoc_types;
2854 if qself.position == 0 {
2855 return TypecheckRequired;
2857 max_assoc_types = path.segments.len() - qself.position;
2858 // Make sure the trait is valid.
2859 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2862 max_assoc_types = path.segments.len();
2866 let mut resolution = self.with_no_errors(|this| {
2867 this.resolve_path(id, path, 0, namespace, check_ribs)
2869 for depth in 1..max_assoc_types {
2870 if resolution.is_some() {
2873 self.with_no_errors(|this| {
2874 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2877 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2878 // A module is not a valid type or value.
2881 ResolveAttempt(resolution)
2884 /// If `check_ribs` is true, checks the local definitions first; i.e.
2885 /// doesn't skip straight to the containing module.
2886 /// Skips `path_depth` trailing segments, which is also reflected in the
2887 /// returned value. See `middle::def::PathResolution` for more info.
2888 pub fn resolve_path(&mut self,
2892 namespace: Namespace,
2894 -> Option<PathResolution> {
2895 let span = path.span;
2896 let segments = &path.segments[..path.segments.len() - path_depth];
2898 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2901 let def = self.resolve_crate_relative_path(span, segments, namespace);
2902 return def.map(mk_res);
2905 // Try to find a path to an item in a module.
2906 let unqualified_def = self.resolve_identifier(segments.last().unwrap().identifier,
2910 if segments.len() <= 1 {
2911 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2913 PathResolution::new(def, LastMod(AllPublic), path_depth)
2917 let def = self.resolve_module_relative_path(span, segments, namespace);
2918 match (def, unqualified_def) {
2919 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2921 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2924 "unnecessary qualification".to_string());
2932 // Resolve a single identifier
2933 fn resolve_identifier(&mut self,
2935 namespace: Namespace,
2937 -> Option<LocalDef> {
2938 // First, check to see whether the name is a primitive type.
2939 if namespace == TypeNS {
2940 if let Some(&prim_ty) = self.primitive_type_table
2942 .get(&identifier.name) {
2943 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
2948 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2953 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
2954 .map(LocalDef::from_def)
2957 // Resolve a local definition, potentially adjusting for closures.
2958 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2959 let ribs = match local_def.ribs {
2960 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2961 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2964 let mut def = local_def.def;
2967 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2969 DefLocal(_, node_id) => {
2973 // Nothing to do. Continue.
2975 ClosureRibKind(function_id) => {
2977 let node_def_id = self.ast_map.local_def_id(node_id);
2979 let seen = self.freevars_seen
2981 .or_insert_with(|| NodeMap());
2982 if let Some(&index) = seen.get(&node_id) {
2983 def = DefUpvar(node_def_id, node_id, index, function_id);
2986 let vec = self.freevars
2988 .or_insert_with(|| vec![]);
2989 let depth = vec.len();
2995 def = DefUpvar(node_def_id, node_id, depth, function_id);
2996 seen.insert(node_id, depth);
2998 ItemRibKind | MethodRibKind => {
2999 // This was an attempt to access an upvar inside a
3000 // named function item. This is not allowed, so we
3004 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3007 ConstantItemRibKind => {
3008 // Still doesn't deal with upvars
3011 ResolutionError::AttemptToUseNonConstantValueInConstant);
3017 DefTyParam(..) | DefSelfTy(..) => {
3020 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3021 // Nothing to do. Continue.
3024 // This was an attempt to use a type parameter outside
3029 ResolutionError::TypeParametersFromOuterFunction);
3032 ConstantItemRibKind => {
3034 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3045 // resolve a "module-relative" path, e.g. a::b::c
3046 fn resolve_module_relative_path(&mut self,
3048 segments: &[hir::PathSegment],
3049 namespace: Namespace)
3050 -> Option<(Def, LastPrivate)> {
3051 let module_path = segments.split_last()
3055 .map(|ps| ps.identifier.name)
3056 .collect::<Vec<_>>();
3058 let containing_module;
3060 let current_module = self.current_module.clone();
3061 match self.resolve_module_path(current_module,
3067 let (span, msg) = match err {
3068 Some((span, msg)) => (span, msg),
3070 let msg = format!("Use of undeclared type or module `{}`",
3071 names_to_string(&module_path));
3076 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3079 Indeterminate => panic!("indeterminate unexpected"),
3080 Success((resulting_module, resulting_last_private)) => {
3081 containing_module = resulting_module;
3082 last_private = resulting_last_private;
3086 let name = segments.last().unwrap().identifier.name;
3087 let def = match self.resolve_name_in_module(containing_module.clone(),
3090 NameSearchType::PathSearch,
3092 Success((Target { binding, .. }, _)) => {
3093 let (def, lp) = binding.def_and_lp();
3094 (def, last_private.or(lp))
3098 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3099 self.used_crates.insert(kid);
3104 /// Invariant: This must be called only during main resolution, not during
3105 /// import resolution.
3106 fn resolve_crate_relative_path(&mut self,
3108 segments: &[hir::PathSegment],
3109 namespace: Namespace)
3110 -> Option<(Def, LastPrivate)> {
3111 let module_path = segments.split_last()
3115 .map(|ps| ps.identifier.name)
3116 .collect::<Vec<_>>();
3118 let root_module = self.graph_root.get_module();
3120 let containing_module;
3122 match self.resolve_module_path_from_root(root_module,
3127 LastMod(AllPublic)) {
3129 let (span, msg) = match err {
3130 Some((span, msg)) => (span, msg),
3132 let msg = format!("Use of undeclared module `::{}`",
3133 names_to_string(&module_path[..]));
3138 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3143 panic!("indeterminate unexpected");
3146 Success((resulting_module, resulting_last_private)) => {
3147 containing_module = resulting_module;
3148 last_private = resulting_last_private;
3152 let name = segments.last().unwrap().identifier.name;
3153 match self.resolve_name_in_module(containing_module,
3156 NameSearchType::PathSearch,
3158 Success((Target { binding, .. }, _)) => {
3159 let (def, lp) = binding.def_and_lp();
3160 Some((def, last_private.or(lp)))
3166 fn resolve_identifier_in_local_ribs(&mut self,
3168 namespace: Namespace)
3169 -> Option<LocalDef> {
3170 // Check the local set of ribs.
3171 let (name, ribs) = match namespace {
3172 ValueNS => (mtwt::resolve(ident), &self.value_ribs),
3173 TypeNS => (ident.name, &self.type_ribs),
3176 for (i, rib) in ribs.iter().enumerate().rev() {
3177 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3180 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3184 return Some(LocalDef {
3185 ribs: Some((namespace, i)),
3190 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3202 fn resolve_item_by_name_in_lexical_scope(&mut self,
3204 namespace: Namespace)
3207 let module = self.current_module.clone();
3208 match self.resolve_item_in_lexical_scope(module, name, namespace) {
3209 Success((target, _)) => {
3210 match target.binding.def() {
3212 // This can happen if we were looking for a type and
3213 // found a module instead. Modules don't have defs.
3214 debug!("(resolving item path by identifier in lexical scope) failed to \
3215 resolve {} after success...",
3220 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3222 // This lookup is "all public" because it only searched
3223 // for one identifier in the current module (couldn't
3224 // have passed through reexports or anything like that.
3230 panic!("unexpected indeterminate result");
3233 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3236 if let Some((span, msg)) = err {
3237 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3245 fn with_no_errors<T, F>(&mut self, f: F) -> T
3246 where F: FnOnce(&mut Resolver) -> T
3248 self.emit_errors = false;
3250 self.emit_errors = true;
3254 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3255 fn extract_path_and_node_id(t: &Ty,
3256 allow: FallbackChecks)
3257 -> Option<(Path, NodeId, FallbackChecks)> {
3259 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3260 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3261 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3262 // This doesn't handle the remaining `Ty` variants as they are not
3263 // that commonly the self_type, it might be interesting to provide
3264 // support for those in future.
3269 fn get_module(this: &mut Resolver,
3271 name_path: &[ast::Name])
3272 -> Option<Rc<Module>> {
3273 let root = this.current_module.clone();
3274 let last_name = name_path.last().unwrap();
3276 if name_path.len() == 1 {
3277 match this.primitive_type_table.primitive_types.get(last_name) {
3280 match this.current_module.children.borrow().get(last_name) {
3281 Some(child) => child.get_module_if_available(),
3287 match this.resolve_module_path(root,
3292 Success((module, _)) => Some(module),
3298 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3299 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3300 let sig = match this.ast_map.get(node_id) {
3301 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3302 hir::MethodTraitItem(ref sig, _) => sig,
3305 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3306 hir::MethodImplItem(ref sig, _) => sig,
3311 sig.explicit_self.node == hir::SelfStatic
3313 csearch::is_static_method(&this.session.cstore, did)
3317 let (path, node_id, allowed) = match self.current_self_type {
3318 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3320 None => return NoSuggestion,
3322 None => return NoSuggestion,
3325 if allowed == Everything {
3326 // Look for a field with the same name in the current self_type.
3327 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3328 Some(DefTy(did, _)) |
3329 Some(DefStruct(did)) |
3330 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3333 if fields.iter().any(|&field_name| name == field_name) {
3338 _ => {} // Self type didn't resolve properly
3342 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3344 // Look for a method in the current self type's impl module.
3345 if let Some(module) = get_module(self, path.span, &name_path) {
3346 if let Some(binding) = module.children.borrow().get(&name) {
3347 if let Some(DefMethod(did)) = binding.value_ns.def() {
3348 if is_static_method(self, did) {
3349 return StaticMethod(path_names_to_string(&path, 0));
3351 if self.current_trait_ref.is_some() {
3353 } else if allowed == Everything {
3360 // Look for a method in the current trait.
3361 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3362 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3363 if is_static_method(self, did) {
3364 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3374 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3375 let mut maybes: Vec<token::InternedString> = Vec::new();
3376 let mut values: Vec<usize> = Vec::new();
3378 for rib in self.value_ribs.iter().rev() {
3379 for (&k, _) in &rib.bindings {
3380 maybes.push(k.as_str());
3381 values.push(usize::MAX);
3385 let mut smallest = 0;
3386 for (i, other) in maybes.iter().enumerate() {
3387 values[i] = lev_distance(name, &other);
3389 if values[i] <= values[smallest] {
3394 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3395 // maximum edit distance we will accept for a suggestion to one third of
3396 // the typo'd name's length.
3397 let max_distance = std::cmp::max(name.len(), 3) / 3;
3399 if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
3401 Some(maybes[smallest].to_string())
3408 fn resolve_expr(&mut self, expr: &Expr) {
3409 // First, record candidate traits for this expression if it could
3410 // result in the invocation of a method call.
3412 self.record_candidate_traits_for_expr_if_necessary(expr);
3414 // Next, resolve the node.
3416 ExprPath(ref maybe_qself, ref path) => {
3417 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3418 maybe_qself.as_ref(),
3422 // `<T>::a::b::c` is resolved by typeck alone.
3423 TypecheckRequired => {
3424 let method_name = path.segments.last().unwrap().identifier.name;
3425 let traits = self.get_traits_containing_item(method_name);
3426 self.trait_map.insert(expr.id, traits);
3427 visit::walk_expr(self, expr);
3430 ResolveAttempt(resolution) => resolution,
3433 // This is a local path in the value namespace. Walk through
3434 // scopes looking for it.
3435 if let Some(path_res) = resolution {
3436 // Check if struct variant
3437 if let DefVariant(_, _, true) = path_res.base_def {
3438 let path_name = path_names_to_string(path, 0);
3442 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3444 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3446 if self.emit_errors {
3447 self.session.fileline_help(expr.span, &msg);
3449 self.session.span_help(expr.span, &msg);
3452 // Write the result into the def map.
3453 debug!("(resolving expr) resolved `{}`",
3454 path_names_to_string(path, 0));
3456 // Partial resolutions will need the set of traits in scope,
3457 // so they can be completed during typeck.
3458 if path_res.depth != 0 {
3459 let method_name = path.segments.last().unwrap().identifier.name;
3460 let traits = self.get_traits_containing_item(method_name);
3461 self.trait_map.insert(expr.id, traits);
3464 self.record_def(expr.id, path_res);
3467 // Be helpful if the name refers to a struct
3468 // (The pattern matching def_tys where the id is in self.structs
3469 // matches on regular structs while excluding tuple- and enum-like
3470 // structs, which wouldn't result in this error.)
3471 let path_name = path_names_to_string(path, 0);
3472 let type_res = self.with_no_errors(|this| {
3473 this.resolve_path(expr.id, path, 0, TypeNS, false)
3475 match type_res.map(|r| r.base_def) {
3476 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3480 ResolutionError::StructVariantUsedAsFunction(
3484 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3486 if self.emit_errors {
3487 self.session.fileline_help(expr.span, &msg);
3489 self.session.span_help(expr.span, &msg);
3493 // Keep reporting some errors even if they're ignored above.
3494 self.resolve_path(expr.id, path, 0, ValueNS, true);
3496 let mut method_scope = false;
3497 self.value_ribs.iter().rev().all(|rib| {
3498 method_scope = match rib.kind {
3499 MethodRibKind => true,
3500 ItemRibKind | ConstantItemRibKind => false,
3501 _ => return true, // Keep advancing
3503 false // Stop advancing
3506 if method_scope && special_names::self_.as_str() == &path_name[..] {
3509 ResolutionError::SelfNotAvailableInStaticMethod);
3511 let last_name = path.segments.last().unwrap().identifier.name;
3512 let mut msg = match self.find_fallback_in_self_type(last_name) {
3514 // limit search to 5 to reduce the number
3515 // of stupid suggestions
3516 self.find_best_match_for_name(&path_name)
3517 .map_or("".to_string(), |x| format!("`{}`", x))
3519 Field => format!("`self.{}`", path_name),
3521 TraitItem => format!("to call `self.{}`", path_name),
3522 TraitMethod(path_str) |
3523 StaticMethod(path_str) =>
3524 format!("to call `{}::{}`", path_str, path_name),
3527 if !msg.is_empty() {
3528 msg = format!(". Did you mean {}?", msg)
3533 ResolutionError::UnresolvedName(&*path_name, &*msg));
3539 visit::walk_expr(self, expr);
3542 ExprStruct(ref path, _, _) => {
3543 // Resolve the path to the structure it goes to. We don't
3544 // check to ensure that the path is actually a structure; that
3545 // is checked later during typeck.
3546 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3547 Some(definition) => self.record_def(expr.id, definition),
3549 debug!("(resolving expression) didn't find struct def",);
3553 ResolutionError::DoesNotNameAStruct(
3554 &*path_names_to_string(path, 0))
3559 visit::walk_expr(self, expr);
3562 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3563 self.with_label_rib(|this| {
3564 let def_like = DlDef(DefLabel(expr.id));
3567 let rib = this.label_ribs.last_mut().unwrap();
3568 let renamed = mtwt::resolve(label);
3569 rib.bindings.insert(renamed, def_like);
3572 visit::walk_expr(this, expr);
3576 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3577 let renamed = mtwt::resolve(label.node);
3578 match self.search_label(renamed) {
3582 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3584 Some(DlDef(def @ DefLabel(_))) => {
3585 // Since this def is a label, it is never read.
3586 self.record_def(expr.id,
3589 last_private: LastMod(AllPublic),
3594 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3600 visit::walk_expr(self, expr);
3605 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3607 ExprField(_, name) => {
3608 // FIXME(#6890): Even though you can't treat a method like a
3609 // field, we need to add any trait methods we find that match
3610 // the field name so that we can do some nice error reporting
3611 // later on in typeck.
3612 let traits = self.get_traits_containing_item(name.node);
3613 self.trait_map.insert(expr.id, traits);
3615 ExprMethodCall(name, _, _) => {
3616 debug!("(recording candidate traits for expr) recording traits for {}",
3618 let traits = self.get_traits_containing_item(name.node);
3619 self.trait_map.insert(expr.id, traits);
3627 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3628 debug!("(getting traits containing item) looking for '{}'", name);
3630 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3631 debug!("(adding trait info) found trait {:?} for method '{}'",
3634 found_traits.push(trait_def_id);
3637 let mut found_traits = Vec::new();
3638 let mut search_module = self.current_module.clone();
3640 // Look for the current trait.
3641 match self.current_trait_ref {
3642 Some((trait_def_id, _)) => {
3643 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3644 add_trait_info(&mut found_traits, trait_def_id, name);
3647 None => {} // Nothing to do.
3650 // Look for trait children.
3651 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3654 for (_, child_names) in search_module.children.borrow().iter() {
3655 let def = match child_names.type_ns.def() {
3659 let trait_def_id = match def {
3660 DefTrait(trait_def_id) => trait_def_id,
3663 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3664 add_trait_info(&mut found_traits, trait_def_id, name);
3669 // Look for imports.
3670 for (_, import) in search_module.import_resolutions.borrow().iter() {
3671 let target = match import.target_for_namespace(TypeNS) {
3673 Some(target) => target,
3675 let did = match target.binding.def() {
3676 Some(DefTrait(trait_def_id)) => trait_def_id,
3677 Some(..) | None => continue,
3679 if self.trait_item_map.contains_key(&(name, did)) {
3680 add_trait_info(&mut found_traits, did, name);
3681 let id = import.type_id;
3682 self.used_imports.insert((id, TypeNS));
3683 let trait_name = self.get_trait_name(did);
3684 self.record_import_use(id, trait_name);
3685 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3686 self.used_crates.insert(kid);
3691 match search_module.parent_link.clone() {
3692 NoParentLink | ModuleParentLink(..) => break,
3693 BlockParentLink(parent_module, _) => {
3694 search_module = parent_module.upgrade().unwrap();
3702 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3703 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3704 assert!(match resolution.last_private {
3705 LastImport{..} => false,
3708 "Import should only be used for `use` directives");
3710 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3711 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3712 self.session.span_bug(span,
3713 &format!("path resolved multiple times ({:?} before, {:?} now)",
3719 fn enforce_default_binding_mode(&mut self,
3721 pat_binding_mode: BindingMode,
3723 match pat_binding_mode {
3724 BindByValue(_) => {}
3728 ResolutionError::CannotUseRefBindingModeWith(descr));
3736 // Diagnostics are not particularly efficient, because they're rarely
3740 #[allow(dead_code)] // useful for debugging
3741 fn dump_module(&mut self, module_: Rc<Module>) {
3742 debug!("Dump of module `{}`:", module_to_string(&*module_));
3744 debug!("Children:");
3745 build_reduced_graph::populate_module_if_necessary(self, &module_);
3746 for (&name, _) in module_.children.borrow().iter() {
3747 debug!("* {}", name);
3750 debug!("Import resolutions:");
3751 let import_resolutions = module_.import_resolutions.borrow();
3752 for (&name, import_resolution) in import_resolutions.iter() {
3754 match import_resolution.target_for_namespace(ValueNS) {
3756 value_repr = "".to_string();
3759 value_repr = " value:?".to_string();
3765 match import_resolution.target_for_namespace(TypeNS) {
3767 type_repr = "".to_string();
3770 type_repr = " type:?".to_string();
3775 debug!("* {}:{}{}", name, value_repr, type_repr);
3781 fn names_to_string(names: &[Name]) -> String {
3782 let mut first = true;
3783 let mut result = String::new();
3788 result.push_str("::")
3790 result.push_str(&name.as_str());
3795 fn path_names_to_string(path: &Path, depth: usize) -> String {
3796 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3798 .map(|seg| seg.identifier.name)
3800 names_to_string(&names[..])
3803 /// A somewhat inefficient routine to obtain the name of a module.
3804 fn module_to_string(module: &Module) -> String {
3805 let mut names = Vec::new();
3807 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3808 match module.parent_link {
3810 ModuleParentLink(ref module, name) => {
3812 collect_mod(names, &*module.upgrade().unwrap());
3814 BlockParentLink(ref module, _) => {
3815 // danger, shouldn't be ident?
3816 names.push(special_idents::opaque.name);
3817 collect_mod(names, &*module.upgrade().unwrap());
3821 collect_mod(&mut names, module);
3823 if names.is_empty() {
3824 return "???".to_string();
3826 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3830 pub struct CrateMap {
3831 pub def_map: RefCell<DefMap>,
3832 pub freevars: FreevarMap,
3833 pub export_map: ExportMap,
3834 pub trait_map: TraitMap,
3835 pub external_exports: ExternalExports,
3836 pub glob_map: Option<GlobMap>,
3839 #[derive(PartialEq,Copy, Clone)]
3840 pub enum MakeGlobMap {
3845 /// Entry point to crate resolution.
3846 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3847 ast_map: &'a hir_map::Map<'tcx>,
3848 make_glob_map: MakeGlobMap)
3850 let krate = ast_map.krate();
3851 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3853 resolver.resolve_crate(krate);
3854 session.abort_if_errors();
3856 check_unused::check_crate(&mut resolver, krate);
3859 def_map: resolver.def_map,
3860 freevars: resolver.freevars,
3861 export_map: resolver.export_map,
3862 trait_map: resolver.trait_map,
3863 external_exports: resolver.external_exports,
3864 glob_map: if resolver.make_glob_map {
3865 Some(resolver.glob_map)
3872 /// Builds a name resolution walker to be used within this module,
3873 /// or used externally, with an optional callback function.
3875 /// The callback takes a &mut bool which allows callbacks to end a
3876 /// walk when set to true, passing through the rest of the walk, while
3877 /// preserving the ribs + current module. This allows resolve_path
3878 /// calls to be made with the correct scope info. The node in the
3879 /// callback corresponds to the current node in the walk.
3880 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3881 ast_map: &'a hir_map::Map<'tcx>,
3883 make_glob_map: MakeGlobMap,
3884 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3885 -> Resolver<'a, 'tcx> {
3886 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
3888 resolver.callback = callback;
3890 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3891 session.abort_if_errors();
3893 resolve_imports::resolve_imports(&mut resolver);
3894 session.abort_if_errors();
3896 record_exports::record(&mut resolver);
3897 session.abort_if_errors();
3902 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }