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(slice_splits)]
27 #![feature(staged_api)]
30 #[macro_use] extern crate log;
31 #[macro_use] extern crate syntax;
32 #[macro_use] #[no_link] extern crate rustc_bitflags;
33 extern crate rustc_front;
37 use self::PatternBindingMode::*;
38 use self::Namespace::*;
39 use self::NamespaceResult::*;
40 use self::NameDefinition::*;
41 use self::ResolveResult::*;
42 use self::FallbackSuggestion::*;
43 use self::TypeParameters::*;
45 use self::UseLexicalScopeFlag::*;
46 use self::ModulePrefixResult::*;
47 use self::AssocItemResolveResult::*;
48 use self::NameSearchType::*;
49 use self::BareIdentifierPatternResolution::*;
50 use self::ParentLink::*;
51 use self::ModuleKind::*;
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, DlField, DlImpl};
59 use rustc::middle::def::*;
60 use rustc::middle::def_id::DefId;
61 use rustc::middle::pat_util::pat_bindings;
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::{Ident, Name, NodeId, CrateNum};
70 use syntax::attr::AttrMetaMethods;
71 use syntax::ext::mtwt;
72 use syntax::parse::token::{self, special_names, special_idents};
74 use syntax::codemap::{self, Span, Pos};
76 use rustc_front::visit::{self, FnKind, Visitor};
78 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
79 use rustc_front::hir::{ConstImplItem, Crate};
80 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprField};
81 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
82 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
83 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
84 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
85 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
86 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
87 use rustc_front::hir::{Local, MethodImplItem};
88 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
89 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
90 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyF32};
91 use rustc_front::hir::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt};
92 use rustc_front::hir::{TyPath, TyPtr};
93 use rustc_front::hir::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
94 use rustc_front::hir::TypeImplItem;
95 use rustc_front::util::walk_pat;
97 use std::collections::{HashMap, HashSet};
98 use std::cell::{Cell, RefCell};
100 use std::mem::replace;
101 use std::rc::{Rc, Weak};
104 use resolve_imports::{Target, ImportDirective, ImportResolution};
105 use resolve_imports::Shadowable;
107 // NB: This module needs to be declared first so diagnostics are
108 // registered before they are used.
113 mod build_reduced_graph;
116 // Perform the callback, not walking deeper if the return is true
117 macro_rules! execute_callback {
118 ($node: expr, $walker: expr) => (
119 if let Some(ref callback) = $walker.callback {
120 if callback($node, &mut $walker.resolved) {
127 pub enum ResolutionError<'a> {
128 /// error E0401: can't use type parameters from outer function
129 TypeParametersFromOuterFunction,
130 /// error E0402: cannot use an outer type parameter in this context
131 OuterTypeParameterContext,
132 /// error E0403: the name is already used for a type parameter in this type parameter list
133 NameAlreadyUsedInTypeParameterList(Name),
134 /// error E0404: is not a trait
135 IsNotATrait(&'a str),
136 /// error E0405: use of undeclared trait name
137 UndeclaredTraitName(&'a str),
138 /// error E0406: undeclared associated type
139 UndeclaredAssociatedType,
140 /// error E0407: method is not a member of trait
141 MethodNotMemberOfTrait(Name, &'a str),
142 /// error E0437: type is not a member of trait
143 TypeNotMemberOfTrait(Name, &'a str),
144 /// error E0438: const is not a member of trait
145 ConstNotMemberOfTrait(Name, &'a str),
146 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
147 VariableNotBoundInPattern(Name, usize),
148 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
149 VariableBoundWithDifferentMode(Name, usize),
150 /// error E0410: variable from pattern is not bound in pattern #1
151 VariableNotBoundInParentPattern(Name, usize),
152 /// error E0411: use of `Self` outside of an impl or trait
153 SelfUsedOutsideImplOrTrait,
154 /// error E0412: use of undeclared
155 UseOfUndeclared(&'a str, &'a str),
156 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
157 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
158 /// error E0414: only irrefutable patterns allowed here
159 OnlyIrrefutablePatternsAllowedHere,
160 /// error E0415: identifier is bound more than once in this parameter list
161 IdentifierBoundMoreThanOnceInParameterList(&'a str),
162 /// error E0416: identifier is bound more than once in the same pattern
163 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
164 /// error E0417: static variables cannot be referenced in a pattern
165 StaticVariableReference,
166 /// error E0418: is not an enum variant, struct or const
167 NotAnEnumVariantStructOrConst(&'a str),
168 /// error E0419: unresolved enum variant, struct or const
169 UnresolvedEnumVariantStructOrConst(&'a str),
170 /// error E0420: is not an associated const
171 NotAnAssociatedConst(&'a str),
172 /// error E0421: unresolved associated const
173 UnresolvedAssociatedConst(&'a str),
174 /// error E0422: does not name a struct
175 DoesNotNameAStruct(&'a str),
176 /// error E0423: is a struct variant name, but this expression uses it like a function name
177 StructVariantUsedAsFunction(&'a str),
178 /// error E0424: `self` is not available in a static method
179 SelfNotAvailableInStaticMethod,
180 /// error E0425: unresolved name
181 UnresolvedName(&'a str, &'a str),
182 /// error E0426: use of undeclared label
183 UndeclaredLabel(&'a str),
184 /// error E0427: cannot use `ref` binding mode with ...
185 CannotUseRefBindingModeWith(&'a str),
186 /// error E0428: duplicate definition
187 DuplicateDefinition(&'a str, Name),
188 /// error E0429: `self` imports are only allowed within a { } list
189 SelfImportsOnlyAllowedWithin,
190 /// error E0430: `self` import can only appear once in the list
191 SelfImportCanOnlyAppearOnceInTheList,
192 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
193 SelfImportOnlyInImportListWithNonEmptyPrefix,
194 /// error E0432: unresolved import
195 UnresolvedImport(Option<(&'a str, &'a str)>),
196 /// error E0433: failed to resolve
197 FailedToResolve(&'a str),
198 /// error E0434: can't capture dynamic environment in a fn item
199 CannotCaptureDynamicEnvironmentInFnItem,
200 /// error E0435: attempt to use a non-constant value in a constant
201 AttemptToUseNonConstantValueInConstant,
204 fn resolve_error<'b, 'a:'b, 'tcx:'a>(resolver: &'b Resolver<'a, 'tcx>, 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, span, E0401, "can't use type parameters from \
212 outer function; try using a local \
213 type parameter instead");
215 ResolutionError::OuterTypeParameterContext => {
216 span_err!(resolver.session, span, E0402,
217 "cannot use an outer type parameter in this context");
219 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
220 span_err!(resolver.session, span, E0403,
221 "the name `{}` is already used for a type \
222 parameter in this type parameter list", name);
224 ResolutionError::IsNotATrait(name) => {
225 span_err!(resolver.session, span, E0404,
226 "`{}` is not a trait",
229 ResolutionError::UndeclaredTraitName(name) => {
230 span_err!(resolver.session, span, E0405,
231 "use of undeclared trait name `{}`",
234 ResolutionError::UndeclaredAssociatedType => {
235 span_err!(resolver.session, span, E0406, "undeclared associated type");
237 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
238 span_err!(resolver.session, span, E0407,
239 "method `{}` is not a member of trait `{}`",
243 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
244 span_err!(resolver.session, span, E0437,
245 "type `{}` is not a member of trait `{}`",
249 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
250 span_err!(resolver.session, span, E0438,
251 "const `{}` is not a member of trait `{}`",
255 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
256 span_err!(resolver.session, span, E0408,
257 "variable `{}` from pattern #1 is not bound in pattern #{}",
261 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
262 span_err!(resolver.session, span, E0409,
263 "variable `{}` is bound with different \
264 mode in pattern #{} than in pattern #1",
268 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
269 span_err!(resolver.session, span, E0410,
270 "variable `{}` from pattern #{} is not bound in pattern #1",
274 ResolutionError::SelfUsedOutsideImplOrTrait => {
275 span_err!(resolver.session, span, E0411, "use of `Self` outside of an impl or trait");
277 ResolutionError::UseOfUndeclared(kind, name) => {
278 span_err!(resolver.session, span, E0412,
279 "use of undeclared {} `{}`",
283 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
284 span_err!(resolver.session, span, E0413,
285 "declaration of `{}` shadows an enum variant or unit-like struct in \
289 ResolutionError::OnlyIrrefutablePatternsAllowedHere => {
290 span_err!(resolver.session, span, E0414, "only irrefutable patterns allowed here");
292 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
293 span_err!(resolver.session, span, E0415,
294 "identifier `{}` is bound more than once in this parameter list",
297 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
298 span_err!(resolver.session, span, E0416,
299 "identifier `{}` is bound more than once in the same pattern",
302 ResolutionError::StaticVariableReference => {
303 span_err!(resolver.session, span, E0417, "static variables cannot be \
304 referenced in a pattern, \
305 use a `const` instead");
307 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
308 span_err!(resolver.session, span, E0418,
309 "`{}` is not an enum variant, struct or const",
312 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
313 span_err!(resolver.session, span, E0419,
314 "unresolved enum variant, struct or const `{}`",
317 ResolutionError::NotAnAssociatedConst(name) => {
318 span_err!(resolver.session, span, E0420,
319 "`{}` is not an associated const",
322 ResolutionError::UnresolvedAssociatedConst(name) => {
323 span_err!(resolver.session, span, E0421,
324 "unresolved associated const `{}`",
327 ResolutionError::DoesNotNameAStruct(name) => {
328 span_err!(resolver.session, span, E0422, "`{}` does not name a structure", name);
330 ResolutionError::StructVariantUsedAsFunction(path_name) => {
331 span_err!(resolver.session, span, E0423,
332 "`{}` is the name of a struct or struct variant, \
333 but this expression \
334 uses it like a function name",
337 ResolutionError::SelfNotAvailableInStaticMethod => {
338 span_err!(resolver.session, span, E0424, "`self` is not available in a static method. \
339 Maybe a `self` argument is missing?");
341 ResolutionError::UnresolvedName(path, name) => {
342 span_err!(resolver.session, span, E0425,
343 "unresolved name `{}`{}",
347 ResolutionError::UndeclaredLabel(name) => {
348 span_err!(resolver.session, span, E0426,
349 "use of undeclared label `{}`",
352 ResolutionError::CannotUseRefBindingModeWith(descr) => {
353 span_err!(resolver.session, span, E0427,
354 "cannot use `ref` binding mode with {}",
357 ResolutionError::DuplicateDefinition(namespace, name) => {
358 span_err!(resolver.session, span, E0428,
359 "duplicate definition of {} `{}`",
363 ResolutionError::SelfImportsOnlyAllowedWithin => {
364 span_err!(resolver.session, span, E0429, "{}",
365 "`self` imports are only allowed within a { } list");
367 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
368 span_err!(resolver.session, span, E0430,
369 "`self` import can only appear once in the list");
371 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
372 span_err!(resolver.session, span, E0431,
373 "`self` import can only appear in an import list with a \
376 ResolutionError::UnresolvedImport(name) => {
377 let msg = match name {
378 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
379 None => "unresolved import".to_owned()
381 span_err!(resolver.session, span, E0432, "{}", msg);
383 ResolutionError::FailedToResolve(msg) => {
384 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
386 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
387 span_err!(resolver.session, span, E0434, "{}",
388 "can't capture dynamic environment in a fn item; \
389 use the || { ... } closure form instead");
391 ResolutionError::AttemptToUseNonConstantValueInConstant =>{
392 span_err!(resolver.session, span, E0435,
393 "attempt to use a non-constant value in a constant");
398 #[derive(Copy, Clone)]
401 binding_mode: BindingMode,
404 // Map from the name in a pattern to its binding mode.
405 type BindingMap = HashMap<Name, BindingInfo>;
407 #[derive(Copy, Clone, PartialEq)]
408 enum PatternBindingMode {
410 LocalIrrefutableMode,
411 ArgumentIrrefutableMode,
414 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
420 /// A NamespaceResult represents the result of resolving an import in
421 /// a particular namespace. The result is either definitely-resolved,
422 /// definitely- unresolved, or unknown.
424 enum NamespaceResult {
425 /// Means that resolve hasn't gathered enough information yet to determine
426 /// whether the name is bound in this namespace. (That is, it hasn't
427 /// resolved all `use` directives yet.)
429 /// Means that resolve has determined that the name is definitely
430 /// not bound in the namespace.
432 /// Means that resolve has determined that the name is bound in the Module
433 /// argument, and specified by the NameBindings argument.
434 BoundResult(Rc<Module>, Rc<NameBindings>)
437 impl NamespaceResult {
438 fn is_unknown(&self) -> bool {
440 UnknownResult => true,
444 fn is_unbound(&self) -> bool {
446 UnboundResult => true,
452 enum NameDefinition {
453 // The name was unbound.
455 // The name identifies an immediate child.
456 ChildNameDefinition(Def, LastPrivate),
457 // The name identifies an import.
458 ImportNameDefinition(Def, LastPrivate),
461 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
462 fn visit_item(&mut self, item: &Item) {
463 execute_callback!(hir_map::Node::NodeItem(item), self);
464 self.resolve_item(item);
466 fn visit_arm(&mut self, arm: &Arm) {
467 self.resolve_arm(arm);
469 fn visit_block(&mut self, block: &Block) {
470 execute_callback!(hir_map::Node::NodeBlock(block), self);
471 self.resolve_block(block);
473 fn visit_expr(&mut self, expr: &Expr) {
474 execute_callback!(hir_map::Node::NodeExpr(expr), self);
475 self.resolve_expr(expr);
477 fn visit_local(&mut self, local: &Local) {
478 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
479 self.resolve_local(local);
481 fn visit_ty(&mut self, ty: &Ty) {
482 self.resolve_type(ty);
484 fn visit_generics(&mut self, generics: &Generics) {
485 self.resolve_generics(generics);
487 fn visit_poly_trait_ref(&mut self,
488 tref: &hir::PolyTraitRef,
489 m: &hir::TraitBoundModifier) {
490 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
491 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
492 Err(_) => { /* error already reported */ }
494 visit::walk_poly_trait_ref(self, tref, m);
496 fn visit_variant(&mut self, variant: &hir::Variant, generics: &Generics) {
497 execute_callback!(hir_map::Node::NodeVariant(variant), self);
498 if let Some(ref dis_expr) = variant.node.disr_expr {
499 // resolve the discriminator expr as a constant
500 self.with_constant_rib(|this| {
501 this.visit_expr(&**dis_expr);
505 // `visit::walk_variant` without the discriminant expression.
506 match variant.node.kind {
507 hir::TupleVariantKind(ref variant_arguments) => {
508 for variant_argument in variant_arguments {
509 self.visit_ty(&*variant_argument.ty);
512 hir::StructVariantKind(ref struct_definition) => {
513 self.visit_struct_def(&**struct_definition,
520 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
521 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
522 let type_parameters = match foreign_item.node {
523 ForeignItemFn(_, ref generics) => {
524 HasTypeParameters(generics, FnSpace, ItemRibKind)
526 ForeignItemStatic(..) => NoTypeParameters
528 self.with_type_parameter_rib(type_parameters, |this| {
529 visit::walk_foreign_item(this, foreign_item);
532 fn visit_fn(&mut self,
533 function_kind: FnKind<'v>,
534 declaration: &'v FnDecl,
538 let rib_kind = match function_kind {
539 FnKind::ItemFn(_, generics, _, _, _, _) => {
540 self.visit_generics(generics);
543 FnKind::Method(_, sig, _) => {
544 self.visit_generics(&sig.generics);
545 self.visit_explicit_self(&sig.explicit_self);
548 FnKind::Closure(..) => ClosureRibKind(node_id)
550 self.resolve_function(rib_kind, declaration, block);
554 type ErrorMessage = Option<(Span, String)>;
556 enum ResolveResult<T> {
557 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
558 Indeterminate, // Couldn't determine due to unresolved globs.
559 Success(T) // Successfully resolved the import.
562 impl<T> ResolveResult<T> {
563 fn success(&self) -> bool {
564 match *self { Success(_) => true, _ => false }
568 enum FallbackSuggestion {
573 StaticMethod(String),
577 #[derive(Copy, Clone)]
578 enum TypeParameters<'a> {
584 // Identifies the things that these parameters
585 // were declared on (type, fn, etc)
588 // The kind of the rib used for type parameters.
592 // The rib kind controls the translation of local
593 // definitions (`DefLocal`) to upvars (`DefUpvar`).
594 #[derive(Copy, Clone, Debug)]
596 // No translation needs to be applied.
599 // We passed through a closure scope at the given node ID.
600 // Translate upvars as appropriate.
601 ClosureRibKind(NodeId /* func id */),
603 // We passed through an impl or trait and are now in one of its
604 // methods. Allow references to ty params that impl or trait
605 // binds. Disallow any other upvars (including other ty params that are
609 // We passed through an item scope. Disallow upvars.
612 // We're in a constant item. Can't refer to dynamic stuff.
616 #[derive(Copy, Clone)]
617 enum UseLexicalScopeFlag {
622 enum ModulePrefixResult {
624 PrefixFound(Rc<Module>, usize)
627 #[derive(Copy, Clone)]
628 enum AssocItemResolveResult {
629 /// Syntax such as `<T>::item`, which can't be resolved until type
632 /// We should have been able to resolve the associated item.
633 ResolveAttempt(Option<PathResolution>),
636 #[derive(Copy, Clone, PartialEq)]
637 enum NameSearchType {
638 /// We're doing a name search in order to resolve a `use` directive.
641 /// We're doing a name search in order to resolve a path type, a path
642 /// expression, or a path pattern.
646 #[derive(Copy, Clone)]
647 enum BareIdentifierPatternResolution {
648 FoundStructOrEnumVariant(Def, LastPrivate),
649 FoundConst(Def, LastPrivate),
650 BareIdentifierPatternUnresolved
656 bindings: HashMap<Name, DefLike>,
661 fn new(kind: RibKind) -> Rib {
663 bindings: HashMap::new(),
669 /// The link from a module up to its nearest parent node.
670 #[derive(Clone,Debug)]
673 ModuleParentLink(Weak<Module>, Name),
674 BlockParentLink(Weak<Module>, NodeId)
677 /// The type of module this is.
678 #[derive(Copy, Clone, PartialEq, Debug)]
687 /// One node in the tree of modules.
689 parent_link: ParentLink,
690 def_id: Cell<Option<DefId>>,
691 kind: Cell<ModuleKind>,
694 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
695 imports: RefCell<Vec<ImportDirective>>,
697 // The external module children of this node that were declared with
699 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
701 // The anonymous children of this node. Anonymous children are pseudo-
702 // modules that are implicitly created around items contained within
705 // For example, if we have this:
713 // There will be an anonymous module created around `g` with the ID of the
714 // entry block for `f`.
715 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
717 // The status of resolving each import in this module.
718 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
720 // The number of unresolved globs that this module exports.
721 glob_count: Cell<usize>,
723 // The number of unresolved pub imports (both regular and globs) in this module
724 pub_count: Cell<usize>,
726 // The number of unresolved pub glob imports in this module
727 pub_glob_count: Cell<usize>,
729 // The index of the import we're resolving.
730 resolved_import_count: Cell<usize>,
732 // Whether this module is populated. If not populated, any attempt to
733 // access the children must be preceded with a
734 // `populate_module_if_necessary` call.
735 populated: Cell<bool>,
739 fn new(parent_link: ParentLink,
740 def_id: Option<DefId>,
746 parent_link: parent_link,
747 def_id: Cell::new(def_id),
748 kind: Cell::new(kind),
749 is_public: is_public,
750 children: RefCell::new(HashMap::new()),
751 imports: RefCell::new(Vec::new()),
752 external_module_children: RefCell::new(HashMap::new()),
753 anonymous_children: RefCell::new(NodeMap()),
754 import_resolutions: RefCell::new(HashMap::new()),
755 glob_count: Cell::new(0),
756 pub_count: Cell::new(0),
757 pub_glob_count: Cell::new(0),
758 resolved_import_count: Cell::new(0),
759 populated: Cell::new(!external),
763 fn all_imports_resolved(&self) -> bool {
764 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
765 // it is currently being resolved ! so nope
768 self.imports.borrow().len() == self.resolved_import_count.get()
774 pub fn inc_glob_count(&self) {
775 self.glob_count.set(self.glob_count.get() + 1);
777 pub fn dec_glob_count(&self) {
778 assert!(self.glob_count.get() > 0);
779 self.glob_count.set(self.glob_count.get() - 1);
781 pub fn inc_pub_count(&self) {
782 self.pub_count.set(self.pub_count.get() + 1);
784 pub fn dec_pub_count(&self) {
785 assert!(self.pub_count.get() > 0);
786 self.pub_count.set(self.pub_count.get() - 1);
788 pub fn inc_pub_glob_count(&self) {
789 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
791 pub fn dec_pub_glob_count(&self) {
792 assert!(self.pub_glob_count.get() > 0);
793 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
797 impl fmt::Debug for Module {
798 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
799 write!(f, "{:?}, kind: {:?}, {}",
802 if self.is_public { "public" } else { "private" } )
808 flags DefModifiers: u8 {
809 const PUBLIC = 1 << 0,
810 const IMPORTABLE = 1 << 1,
814 // Records a possibly-private type definition.
815 #[derive(Clone,Debug)]
817 modifiers: DefModifiers, // see note in ImportResolution about how to use this
818 module_def: Option<Rc<Module>>,
819 type_def: Option<Def>,
820 type_span: Option<Span>
823 // Records a possibly-private value definition.
824 #[derive(Clone, Copy, Debug)]
826 modifiers: DefModifiers, // see note in ImportResolution about how to use this
828 value_span: Option<Span>,
831 // Records the definitions (at most one for each namespace) that a name is
834 pub struct NameBindings {
835 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
836 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
840 fn new() -> NameBindings {
842 type_def: RefCell::new(None),
843 value_def: RefCell::new(None),
847 /// Creates a new module in this set of name bindings.
848 fn define_module(&self,
849 parent_link: ParentLink,
850 def_id: Option<DefId>,
855 // Merges the module with the existing type def or creates a new one.
856 let modifiers = if is_public {
859 DefModifiers::empty()
860 } | DefModifiers::IMPORTABLE;
861 let module_ = Rc::new(Module::new(parent_link,
866 let type_def = self.type_def.borrow().clone();
869 *self.type_def.borrow_mut() = Some(TypeNsDef {
870 modifiers: modifiers,
871 module_def: Some(module_),
877 *self.type_def.borrow_mut() = Some(TypeNsDef {
878 modifiers: modifiers,
879 module_def: Some(module_),
881 type_def: type_def.type_def
887 /// Sets the kind of the module, creating a new one if necessary.
888 fn set_module_kind(&self,
889 parent_link: ParentLink,
890 def_id: Option<DefId>,
895 let modifiers = if is_public {
898 DefModifiers::empty()
899 } | DefModifiers::IMPORTABLE;
900 let type_def = self.type_def.borrow().clone();
903 let module = Module::new(parent_link,
908 *self.type_def.borrow_mut() = Some(TypeNsDef {
909 modifiers: modifiers,
910 module_def: Some(Rc::new(module)),
916 match type_def.module_def {
918 let module = Module::new(parent_link,
923 *self.type_def.borrow_mut() = Some(TypeNsDef {
924 modifiers: modifiers,
925 module_def: Some(Rc::new(module)),
926 type_def: type_def.type_def,
930 Some(module_def) => module_def.kind.set(kind),
936 /// Records a type definition.
937 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
938 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
939 // Merges the type with the existing type def or creates a new one.
940 let type_def = self.type_def.borrow().clone();
943 *self.type_def.borrow_mut() = Some(TypeNsDef {
947 modifiers: modifiers,
951 *self.type_def.borrow_mut() = Some(TypeNsDef {
952 module_def: type_def.module_def,
955 modifiers: modifiers,
961 /// Records a value definition.
962 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
963 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
964 *self.value_def.borrow_mut() = Some(ValueNsDef {
966 value_span: Some(sp),
967 modifiers: modifiers,
971 /// Returns the module node if applicable.
972 fn get_module_if_available(&self) -> Option<Rc<Module>> {
973 match *self.type_def.borrow() {
974 Some(ref type_def) => type_def.module_def.clone(),
979 /// Returns the module node. Panics if this node does not have a module
981 fn get_module(&self) -> Rc<Module> {
982 match self.get_module_if_available() {
984 panic!("get_module called on a node with no module \
987 Some(module_def) => module_def
991 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
993 TypeNS => return self.type_def.borrow().is_some(),
994 ValueNS => return self.value_def.borrow().is_some()
998 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
999 self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
1002 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
1004 TypeNS => match *self.type_def.borrow() {
1005 Some(ref def) => def.modifiers.contains(modifiers), None => false
1007 ValueNS => match *self.value_def.borrow() {
1008 Some(ref def) => def.modifiers.contains(modifiers), None => false
1013 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
1016 match *self.type_def.borrow() {
1018 Some(ref type_def) => {
1019 match type_def.type_def {
1020 Some(type_def) => Some(type_def),
1022 match type_def.module_def {
1023 Some(ref module) => {
1024 match module.def_id.get() {
1025 Some(did) => Some(DefMod(did)),
1037 match *self.value_def.borrow() {
1039 Some(value_def) => Some(value_def.def)
1045 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
1046 if self.defined_in_namespace(namespace) {
1049 match *self.type_def.borrow() {
1051 Some(ref type_def) => type_def.type_span
1055 match *self.value_def.borrow() {
1057 Some(ref value_def) => value_def.value_span
1066 fn is_public(&self, namespace: Namespace) -> bool {
1069 let type_def = self.type_def.borrow();
1070 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
1073 let value_def = self.value_def.borrow();
1074 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
1080 /// Interns the names of the primitive types.
1081 struct PrimitiveTypeTable {
1082 primitive_types: HashMap<Name, PrimTy>,
1085 impl PrimitiveTypeTable {
1086 fn new() -> PrimitiveTypeTable {
1087 let mut table = PrimitiveTypeTable {
1088 primitive_types: HashMap::new()
1091 table.intern("bool", TyBool);
1092 table.intern("char", TyChar);
1093 table.intern("f32", TyFloat(TyF32));
1094 table.intern("f64", TyFloat(TyF64));
1095 table.intern("isize", TyInt(TyIs));
1096 table.intern("i8", TyInt(TyI8));
1097 table.intern("i16", TyInt(TyI16));
1098 table.intern("i32", TyInt(TyI32));
1099 table.intern("i64", TyInt(TyI64));
1100 table.intern("str", TyStr);
1101 table.intern("usize", TyUint(TyUs));
1102 table.intern("u8", TyUint(TyU8));
1103 table.intern("u16", TyUint(TyU16));
1104 table.intern("u32", TyUint(TyU32));
1105 table.intern("u64", TyUint(TyU64));
1110 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1111 self.primitive_types.insert(token::intern(string), primitive_type);
1115 /// The main resolver class.
1116 pub struct Resolver<'a, 'tcx:'a> {
1117 session: &'a Session,
1119 ast_map: &'a hir_map::Map<'tcx>,
1121 graph_root: NameBindings,
1123 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1125 structs: FnvHashMap<DefId, Vec<Name>>,
1127 // The number of imports that are currently unresolved.
1128 unresolved_imports: usize,
1130 // The module that represents the current item scope.
1131 current_module: Rc<Module>,
1133 // The current set of local scopes, for values.
1134 // FIXME #4948: Reuse ribs to avoid allocation.
1135 value_ribs: Vec<Rib>,
1137 // The current set of local scopes, for types.
1138 type_ribs: Vec<Rib>,
1140 // The current set of local scopes, for labels.
1141 label_ribs: Vec<Rib>,
1143 // The trait that the current context can refer to.
1144 current_trait_ref: Option<(DefId, TraitRef)>,
1146 // The current self type if inside an impl (used for better errors).
1147 current_self_type: Option<Ty>,
1149 // The idents for the primitive types.
1150 primitive_type_table: PrimitiveTypeTable,
1153 freevars: RefCell<FreevarMap>,
1154 freevars_seen: RefCell<NodeMap<NodeMap<usize>>>,
1155 export_map: ExportMap,
1156 trait_map: TraitMap,
1157 external_exports: ExternalExports,
1159 // Whether or not to print error messages. Can be set to true
1160 // when getting additional info for error message suggestions,
1161 // so as to avoid printing duplicate errors
1164 make_glob_map: bool,
1165 // Maps imports to the names of items actually imported (this actually maps
1166 // all imports, but only glob imports are actually interesting).
1169 used_imports: HashSet<(NodeId, Namespace)>,
1170 used_crates: HashSet<CrateNum>,
1172 // Callback function for intercepting walks
1173 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1174 // The intention is that the callback modifies this flag.
1175 // Once set, the resolver falls out of the walk, preserving the ribs.
1180 #[derive(PartialEq)]
1181 enum FallbackChecks {
1186 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1187 fn new(session: &'a Session,
1188 ast_map: &'a hir_map::Map<'tcx>,
1190 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
1191 let graph_root = NameBindings::new();
1193 graph_root.define_module(NoParentLink,
1194 Some(DefId { krate: 0, node: 0 }),
1200 let current_module = graph_root.get_module();
1207 // The outermost module has def ID 0; this is not reflected in the
1210 graph_root: graph_root,
1212 trait_item_map: FnvHashMap(),
1213 structs: FnvHashMap(),
1215 unresolved_imports: 0,
1217 current_module: current_module,
1218 value_ribs: Vec::new(),
1219 type_ribs: Vec::new(),
1220 label_ribs: Vec::new(),
1222 current_trait_ref: None,
1223 current_self_type: None,
1225 primitive_type_table: PrimitiveTypeTable::new(),
1227 def_map: RefCell::new(NodeMap()),
1228 freevars: RefCell::new(NodeMap()),
1229 freevars_seen: RefCell::new(NodeMap()),
1230 export_map: NodeMap(),
1231 trait_map: NodeMap(),
1232 used_imports: HashSet::new(),
1233 used_crates: HashSet::new(),
1234 external_exports: DefIdSet(),
1237 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1238 glob_map: HashMap::new(),
1247 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1248 if !self.make_glob_map {
1251 if self.glob_map.contains_key(&import_id) {
1252 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1256 let mut new_set = HashSet::new();
1257 new_set.insert(name);
1258 self.glob_map.insert(import_id, new_set);
1261 fn get_trait_name(&self, did: DefId) -> Name {
1263 self.ast_map.expect_item(did.node).ident.name
1265 csearch::get_trait_name(&self.session.cstore, did)
1269 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1271 type_def: RefCell::new(Some(TypeNsDef {
1272 modifiers: DefModifiers::IMPORTABLE,
1273 module_def: Some(module),
1277 value_def: RefCell::new(None),
1281 /// Checks that the names of external crates don't collide with other
1282 /// external crates.
1283 fn check_for_conflicts_between_external_crates(&self,
1287 if module.external_module_children.borrow().contains_key(&name) {
1288 span_err!(self.session, span, E0259,
1289 "an external crate named `{}` has already \
1290 been imported into this module",
1295 /// Checks that the names of items don't collide with external crates.
1296 fn check_for_conflicts_between_external_crates_and_items(&self,
1300 if module.external_module_children.borrow().contains_key(&name) {
1301 span_err!(self.session, span, E0260,
1302 "the name `{}` conflicts with an external \
1303 crate that has been imported into this \
1309 /// Resolves the given module path from the given root `module_`.
1310 fn resolve_module_path_from_root(&mut self,
1311 module_: Rc<Module>,
1312 module_path: &[Name],
1315 name_search_type: NameSearchType,
1317 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1318 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1319 -> Option<Rc<Module>> {
1320 match module.external_module_children.borrow().get(&needle) {
1321 Some(_) => Some(module.clone()),
1322 None => match module.parent_link {
1323 ModuleParentLink(ref parent, _) => {
1324 search_parent_externals(needle, &parent.upgrade().unwrap())
1331 let mut search_module = module_;
1332 let mut index = index;
1333 let module_path_len = module_path.len();
1334 let mut closest_private = lp;
1336 // Resolve the module part of the path. This does not involve looking
1337 // upward though scope chains; we simply resolve names directly in
1338 // modules as we go.
1339 while index < module_path_len {
1340 let name = module_path[index];
1341 match self.resolve_name_in_module(search_module.clone(),
1347 let segment_name = name.as_str();
1348 let module_name = module_to_string(&*search_module);
1349 let mut span = span;
1350 let msg = if "???" == &module_name[..] {
1351 span.hi = span.lo + Pos::from_usize(segment_name.len());
1353 match search_parent_externals(name,
1354 &self.current_module) {
1356 let path_str = names_to_string(module_path);
1357 let target_mod_str = module_to_string(&*module);
1358 let current_mod_str =
1359 module_to_string(&*self.current_module);
1361 let prefix = if target_mod_str == current_mod_str {
1362 "self::".to_string()
1364 format!("{}::", target_mod_str)
1367 format!("Did you mean `{}{}`?", prefix, path_str)
1369 None => format!("Maybe a missing `extern crate {}`?",
1373 format!("Could not find `{}` in `{}`",
1378 return Failed(Some((span, msg)));
1380 Failed(err) => return Failed(err),
1382 debug!("(resolving module path for import) module \
1383 resolution is indeterminate: {}",
1385 return Indeterminate;
1387 Success((target, used_proxy)) => {
1388 // Check to see whether there are type bindings, and, if
1389 // so, whether there is a module within.
1390 match *target.bindings.type_def.borrow() {
1391 Some(ref type_def) => {
1392 match type_def.module_def {
1394 let msg = format!("Not a module `{}`",
1397 return Failed(Some((span, msg)));
1399 Some(ref module_def) => {
1400 search_module = module_def.clone();
1402 // track extern crates for unused_extern_crate lint
1403 if let Some(did) = module_def.def_id.get() {
1404 self.used_crates.insert(did.krate);
1407 // Keep track of the closest
1408 // private module used when
1409 // resolving this import chain.
1410 if !used_proxy && !search_module.is_public {
1411 if let Some(did) = search_module.def_id.get() {
1412 closest_private = LastMod(DependsOn(did));
1419 // There are no type bindings at all.
1420 let msg = format!("Not a module `{}`",
1422 return Failed(Some((span, msg)));
1431 return Success((search_module, closest_private));
1434 /// Attempts to resolve the module part of an import directive or path
1435 /// rooted at the given module.
1437 /// On success, returns the resolved module, and the closest *private*
1438 /// module found to the destination when resolving this path.
1439 fn resolve_module_path(&mut self,
1440 module_: Rc<Module>,
1441 module_path: &[Name],
1442 use_lexical_scope: UseLexicalScopeFlag,
1444 name_search_type: NameSearchType)
1445 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1446 let module_path_len = module_path.len();
1447 assert!(module_path_len > 0);
1449 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1450 names_to_string(module_path),
1451 module_to_string(&*module_));
1453 // Resolve the module prefix, if any.
1454 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1460 match module_prefix_result {
1462 let mpath = names_to_string(module_path);
1463 let mpath = &mpath[..];
1464 match mpath.rfind(':') {
1466 let msg = format!("Could not find `{}` in `{}`",
1467 // idx +- 1 to account for the
1468 // colons on either side
1471 return Failed(Some((span, msg)));
1478 Failed(err) => return Failed(err),
1480 debug!("(resolving module path for import) indeterminate; \
1482 return Indeterminate;
1484 Success(NoPrefixFound) => {
1485 // There was no prefix, so we're considering the first element
1486 // of the path. How we handle this depends on whether we were
1487 // instructed to use lexical scope or not.
1488 match use_lexical_scope {
1489 DontUseLexicalScope => {
1490 // This is a crate-relative path. We will start the
1491 // resolution process at index zero.
1492 search_module = self.graph_root.get_module();
1494 last_private = LastMod(AllPublic);
1496 UseLexicalScope => {
1497 // This is not a crate-relative path. We resolve the
1498 // first component of the path in the current lexical
1499 // scope and then proceed to resolve below that.
1500 match self.resolve_module_in_lexical_scope(module_,
1502 Failed(err) => return Failed(err),
1504 debug!("(resolving module path for import) \
1505 indeterminate; bailing");
1506 return Indeterminate;
1508 Success(containing_module) => {
1509 search_module = containing_module;
1511 last_private = LastMod(AllPublic);
1517 Success(PrefixFound(ref containing_module, index)) => {
1518 search_module = containing_module.clone();
1519 start_index = index;
1520 last_private = LastMod(DependsOn(containing_module.def_id
1526 self.resolve_module_path_from_root(search_module,
1534 /// Invariant: This must only be called during main resolution, not during
1535 /// import resolution.
1536 fn resolve_item_in_lexical_scope(&mut self,
1537 module_: Rc<Module>,
1539 namespace: Namespace)
1540 -> ResolveResult<(Target, bool)> {
1541 debug!("(resolving item in lexical scope) resolving `{}` in \
1542 namespace {:?} in `{}`",
1545 module_to_string(&*module_));
1547 // The current module node is handled specially. First, check for
1548 // its immediate children.
1549 build_reduced_graph::populate_module_if_necessary(self, &module_);
1551 match module_.children.borrow().get(&name) {
1553 if name_bindings.defined_in_namespace(namespace) => {
1554 debug!("top name bindings succeeded");
1555 return Success((Target::new(module_.clone(),
1556 name_bindings.clone(),
1560 Some(_) | None => { /* Not found; continue. */ }
1563 // Now check for its import directives. We don't have to have resolved
1564 // all its imports in the usual way; this is because chains of
1565 // adjacent import statements are processed as though they mutated the
1567 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1568 match (*import_resolution).target_for_namespace(namespace) {
1570 // Not found; continue.
1571 debug!("(resolving item in lexical scope) found \
1572 import resolution, but not in namespace {:?}",
1576 debug!("(resolving item in lexical scope) using \
1577 import resolution");
1578 // track used imports and extern crates as well
1579 let id = import_resolution.id(namespace);
1580 self.used_imports.insert((id, namespace));
1581 self.record_import_use(id, name);
1582 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1583 self.used_crates.insert(kid);
1585 return Success((target, false));
1590 // Search for external modules.
1591 if namespace == TypeNS {
1592 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1593 let child = module_.external_module_children.borrow().get(&name).cloned();
1594 if let Some(module) = child {
1596 Rc::new(Resolver::create_name_bindings_from_module(module));
1597 debug!("lower name bindings succeeded");
1598 return Success((Target::new(module_,
1605 // Finally, proceed up the scope chain looking for parent modules.
1606 let mut search_module = module_;
1608 // Go to the next parent.
1609 match search_module.parent_link.clone() {
1611 // No more parents. This module was unresolved.
1612 debug!("(resolving item in lexical scope) unresolved \
1614 return Failed(None);
1616 ModuleParentLink(parent_module_node, _) => {
1617 match search_module.kind.get() {
1618 NormalModuleKind => {
1619 // We stop the search here.
1620 debug!("(resolving item in lexical \
1621 scope) unresolved module: not \
1622 searching through module \
1624 return Failed(None);
1629 AnonymousModuleKind => {
1630 search_module = parent_module_node.upgrade().unwrap();
1634 BlockParentLink(ref parent_module_node, _) => {
1635 search_module = parent_module_node.upgrade().unwrap();
1639 // Resolve the name in the parent module.
1640 match self.resolve_name_in_module(search_module.clone(),
1645 Failed(Some((span, msg))) => {
1646 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1648 Failed(None) => (), // Continue up the search chain.
1650 // We couldn't see through the higher scope because of an
1651 // unresolved import higher up. Bail.
1653 debug!("(resolving item in lexical scope) indeterminate \
1654 higher scope; bailing");
1655 return Indeterminate;
1657 Success((target, used_reexport)) => {
1658 // We found the module.
1659 debug!("(resolving item in lexical scope) found name \
1661 return Success((target, used_reexport));
1667 /// Resolves a module name in the current lexical scope.
1668 fn resolve_module_in_lexical_scope(&mut self,
1669 module_: Rc<Module>,
1671 -> ResolveResult<Rc<Module>> {
1672 // If this module is an anonymous module, resolve the item in the
1673 // lexical scope. Otherwise, resolve the item from the crate root.
1674 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1675 match resolve_result {
1676 Success((target, _)) => {
1677 let bindings = &*target.bindings;
1678 match *bindings.type_def.borrow() {
1679 Some(ref type_def) => {
1680 match type_def.module_def {
1682 debug!("!!! (resolving module in lexical \
1683 scope) module wasn't actually a \
1685 return Failed(None);
1687 Some(ref module_def) => {
1688 return Success(module_def.clone());
1693 debug!("!!! (resolving module in lexical scope) module
1694 wasn't actually a module!");
1695 return Failed(None);
1700 debug!("(resolving module in lexical scope) indeterminate; \
1702 return Indeterminate;
1705 debug!("(resolving module in lexical scope) failed to resolve");
1711 /// Returns the nearest normal module parent of the given module.
1712 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1713 -> Option<Rc<Module>> {
1714 let mut module_ = module_;
1716 match module_.parent_link.clone() {
1717 NoParentLink => return None,
1718 ModuleParentLink(new_module, _) |
1719 BlockParentLink(new_module, _) => {
1720 let new_module = new_module.upgrade().unwrap();
1721 match new_module.kind.get() {
1722 NormalModuleKind => return Some(new_module),
1726 AnonymousModuleKind => module_ = new_module,
1733 /// Returns the nearest normal module parent of the given module, or the
1734 /// module itself if it is a normal module.
1735 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1737 match module_.kind.get() {
1738 NormalModuleKind => return module_,
1742 AnonymousModuleKind => {
1743 match self.get_nearest_normal_module_parent(module_.clone()) {
1745 Some(new_module) => new_module
1751 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1752 /// (b) some chain of `super::`.
1753 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1754 fn resolve_module_prefix(&mut self,
1755 module_: Rc<Module>,
1756 module_path: &[Name])
1757 -> ResolveResult<ModulePrefixResult> {
1758 // Start at the current module if we see `self` or `super`, or at the
1759 // top of the crate otherwise.
1760 let mut i = match &*module_path[0].as_str() {
1763 _ => return Success(NoPrefixFound),
1765 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1767 // Now loop through all the `super`s we find.
1768 while i < module_path.len() && "super" == module_path[i].as_str() {
1769 debug!("(resolving module prefix) resolving `super` at {}",
1770 module_to_string(&*containing_module));
1771 match self.get_nearest_normal_module_parent(containing_module) {
1772 None => return Failed(None),
1773 Some(new_module) => {
1774 containing_module = new_module;
1780 debug!("(resolving module prefix) finished resolving prefix at {}",
1781 module_to_string(&*containing_module));
1783 return Success(PrefixFound(containing_module, i));
1786 /// Attempts to resolve the supplied name in the given module for the
1787 /// given namespace. If successful, returns the target corresponding to
1790 /// The boolean returned on success is an indicator of whether this lookup
1791 /// passed through a public re-export proxy.
1792 fn resolve_name_in_module(&mut self,
1793 module_: Rc<Module>,
1795 namespace: Namespace,
1796 name_search_type: NameSearchType,
1797 allow_private_imports: bool)
1798 -> ResolveResult<(Target, bool)> {
1799 debug!("(resolving name in module) resolving `{}` in `{}`",
1801 module_to_string(&*module_));
1803 // First, check the direct children of the module.
1804 build_reduced_graph::populate_module_if_necessary(self, &module_);
1806 match module_.children.borrow().get(&name) {
1808 if name_bindings.defined_in_namespace(namespace) => {
1809 debug!("(resolving name in module) found node as child");
1810 return Success((Target::new(module_.clone(),
1811 name_bindings.clone(),
1820 // Next, check the module's imports if necessary.
1822 // If this is a search of all imports, we should be done with glob
1823 // resolution at this point.
1824 if name_search_type == PathSearch {
1825 assert_eq!(module_.glob_count.get(), 0);
1828 // Check the list of resolved imports.
1829 match module_.import_resolutions.borrow().get(&name) {
1830 Some(import_resolution) if allow_private_imports ||
1831 import_resolution.is_public => {
1833 if import_resolution.is_public &&
1834 import_resolution.outstanding_references != 0 {
1835 debug!("(resolving name in module) import \
1836 unresolved; bailing out");
1837 return Indeterminate;
1839 match import_resolution.target_for_namespace(namespace) {
1841 debug!("(resolving name in module) name found, \
1842 but not in namespace {:?}",
1846 debug!("(resolving name in module) resolved to \
1848 // track used imports and extern crates as well
1849 let id = import_resolution.id(namespace);
1850 self.used_imports.insert((id, namespace));
1851 self.record_import_use(id, name);
1852 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1853 self.used_crates.insert(kid);
1855 return Success((target, true));
1859 Some(..) | None => {} // Continue.
1862 // Finally, search through external children.
1863 if namespace == TypeNS {
1864 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1865 let child = module_.external_module_children.borrow().get(&name).cloned();
1866 if let Some(module) = child {
1868 Rc::new(Resolver::create_name_bindings_from_module(module));
1869 return Success((Target::new(module_,
1876 // We're out of luck.
1877 debug!("(resolving name in module) failed to resolve `{}`",
1879 return Failed(None);
1882 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1883 let index = module_.resolved_import_count.get();
1884 let imports = module_.imports.borrow();
1885 let import_count = imports.len();
1886 if index != import_count {
1888 (*imports)[index].span,
1889 ResolutionError::UnresolvedImport(None));
1892 // Descend into children and anonymous children.
1893 build_reduced_graph::populate_module_if_necessary(self, &module_);
1895 for (_, child_node) in module_.children.borrow().iter() {
1896 match child_node.get_module_if_available() {
1900 Some(child_module) => {
1901 self.report_unresolved_imports(child_module);
1906 for (_, module_) in module_.anonymous_children.borrow().iter() {
1907 self.report_unresolved_imports(module_.clone());
1913 // We maintain a list of value ribs and type ribs.
1915 // Simultaneously, we keep track of the current position in the module
1916 // graph in the `current_module` pointer. When we go to resolve a name in
1917 // the value or type namespaces, we first look through all the ribs and
1918 // then query the module graph. When we resolve a name in the module
1919 // namespace, we can skip all the ribs (since nested modules are not
1920 // allowed within blocks in Rust) and jump straight to the current module
1923 // Named implementations are handled separately. When we find a method
1924 // call, we consult the module node to find all of the implementations in
1925 // scope. This information is lazily cached in the module node. We then
1926 // generate a fake "implementation scope" containing all the
1927 // implementations thus found, for compatibility with old resolve pass.
1929 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1930 F: FnOnce(&mut Resolver),
1932 let orig_module = self.current_module.clone();
1934 // Move down in the graph.
1940 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1942 match orig_module.children.borrow().get(&name) {
1944 debug!("!!! (with scope) didn't find `{}` in `{}`",
1946 module_to_string(&*orig_module));
1948 Some(name_bindings) => {
1949 match (*name_bindings).get_module_if_available() {
1951 debug!("!!! (with scope) didn't find module \
1954 module_to_string(&*orig_module));
1957 self.current_module = module_;
1967 self.current_module = orig_module;
1970 /// Wraps the given definition in the appropriate number of `DefUpvar`
1976 -> Option<DefLike> {
1977 let mut def = match def_like {
1979 _ => return Some(def_like)
1983 self.session.span_bug(span,
1984 &format!("unexpected {:?} in bindings", def))
1986 DefLocal(node_id) => {
1990 // Nothing to do. Continue.
1992 ClosureRibKind(function_id) => {
1995 let mut seen = self.freevars_seen.borrow_mut();
1996 let seen = seen.entry(function_id).or_insert_with(|| NodeMap());
1997 if let Some(&index) = seen.get(&node_id) {
1998 def = DefUpvar(node_id, index, function_id);
2001 let mut freevars = self.freevars.borrow_mut();
2002 let vec = freevars.entry(function_id)
2003 .or_insert_with(|| vec![]);
2004 let depth = vec.len();
2005 vec.push(Freevar { def: prev_def, span: span });
2007 def = DefUpvar(node_id, depth, function_id);
2008 seen.insert(node_id, depth);
2010 ItemRibKind | MethodRibKind => {
2011 // This was an attempt to access an upvar inside a
2012 // named function item. This is not allowed, so we
2017 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem
2021 ConstantItemRibKind => {
2022 // Still doesn't deal with upvars
2026 ResolutionError::AttemptToUseNonConstantValueInConstant
2033 DefTyParam(..) | DefSelfTy(..) => {
2036 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
2037 // Nothing to do. Continue.
2040 // This was an attempt to use a type parameter outside
2045 ResolutionError::TypeParametersFromOuterFunction);
2048 ConstantItemRibKind => {
2050 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2061 /// Searches the current set of local scopes and
2062 /// applies translations for closures.
2063 fn search_ribs(&self,
2067 -> Option<DefLike> {
2068 // FIXME #4950: Try caching?
2070 for (i, rib) in ribs.iter().enumerate().rev() {
2071 if let Some(def_like) = rib.bindings.get(&name).cloned() {
2072 return self.upvarify(&ribs[i + 1..], def_like, span);
2079 /// Searches the current set of local scopes for labels.
2080 /// Stops after meeting a closure.
2081 fn search_label(&self, name: Name) -> Option<DefLike> {
2082 for rib in self.label_ribs.iter().rev() {
2088 // Do not resolve labels across function boundary
2092 let result = rib.bindings.get(&name).cloned();
2093 if result.is_some() {
2100 fn resolve_crate(&mut self, krate: &hir::Crate) {
2101 debug!("(resolving crate) starting");
2103 visit::walk_crate(self, krate);
2106 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
2107 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
2108 span_err!(self.session, span, E0317,
2109 "user-defined types or type parameters cannot shadow the primitive types");
2113 fn resolve_item(&mut self, item: &Item) {
2114 let name = item.ident.name;
2116 debug!("(resolving item) resolving {}",
2120 ItemEnum(_, ref generics) |
2121 ItemTy(_, ref generics) |
2122 ItemStruct(_, ref generics) => {
2123 self.check_if_primitive_type_name(name, item.span);
2125 self.with_type_parameter_rib(HasTypeParameters(generics,
2128 |this| visit::walk_item(this, item));
2130 ItemFn(_, _, _, _, ref generics, _) => {
2131 self.with_type_parameter_rib(HasTypeParameters(generics,
2134 |this| visit::walk_item(this, item));
2137 ItemDefaultImpl(_, ref trait_ref) => {
2138 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
2145 ref impl_items) => {
2146 self.resolve_implementation(generics,
2153 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2154 self.check_if_primitive_type_name(name, item.span);
2156 // Create a new rib for the trait-wide type parameters.
2157 self.with_type_parameter_rib(HasTypeParameters(generics,
2161 this.with_self_rib(DefSelfTy(Some(DefId::local(item.id)), None), |this| {
2162 this.visit_generics(generics);
2163 visit::walk_ty_param_bounds_helper(this, bounds);
2165 for trait_item in trait_items {
2166 match trait_item.node {
2167 hir::ConstTraitItem(_, ref default) => {
2168 // Only impose the restrictions of
2169 // ConstRibKind if there's an actual constant
2170 // expression in a provided default.
2171 if default.is_some() {
2172 this.with_constant_rib(|this| {
2173 visit::walk_trait_item(this, trait_item)
2176 visit::walk_trait_item(this, trait_item)
2179 hir::MethodTraitItem(ref sig, _) => {
2180 let type_parameters =
2181 HasTypeParameters(&sig.generics,
2184 this.with_type_parameter_rib(type_parameters, |this| {
2185 visit::walk_trait_item(this, trait_item)
2188 hir::TypeTraitItem(..) => {
2189 this.check_if_primitive_type_name(trait_item.ident.name,
2191 this.with_type_parameter_rib(NoTypeParameters, |this| {
2192 visit::walk_trait_item(this, trait_item)
2201 ItemMod(_) | ItemForeignMod(_) => {
2202 self.with_scope(Some(name), |this| {
2203 visit::walk_item(this, item);
2207 ItemConst(..) | ItemStatic(..) => {
2208 self.with_constant_rib(|this| {
2209 visit::walk_item(this, item);
2213 ItemUse(ref view_path) => {
2214 // check for imports shadowing primitive types
2215 if let hir::ViewPathSimple(ident, _) = view_path.node {
2216 match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
2217 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2218 self.check_if_primitive_type_name(ident.name, item.span);
2225 ItemExternCrate(_) => {
2226 // do nothing, these are just around to be encoded
2231 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2232 F: FnOnce(&mut Resolver),
2234 match type_parameters {
2235 HasTypeParameters(generics, space, rib_kind) => {
2236 let mut function_type_rib = Rib::new(rib_kind);
2237 let mut seen_bindings = HashSet::new();
2238 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2239 let name = type_parameter.ident.name;
2240 debug!("with_type_parameter_rib: {}", type_parameter.id);
2242 if seen_bindings.contains(&name) {
2244 type_parameter.span,
2245 ResolutionError::NameAlreadyUsedInTypeParameterList(
2249 seen_bindings.insert(name);
2251 // plain insert (no renaming)
2252 function_type_rib.bindings.insert(name,
2253 DlDef(DefTyParam(space,
2255 DefId::local(type_parameter.id),
2258 self.type_ribs.push(function_type_rib);
2261 NoTypeParameters => {
2268 match type_parameters {
2269 HasTypeParameters(..) => { if !self.resolved { self.type_ribs.pop(); } }
2270 NoTypeParameters => { }
2274 fn with_label_rib<F>(&mut self, f: F) where
2275 F: FnOnce(&mut Resolver),
2277 self.label_ribs.push(Rib::new(NormalRibKind));
2280 self.label_ribs.pop();
2284 fn with_constant_rib<F>(&mut self, f: F) where
2285 F: FnOnce(&mut Resolver),
2287 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2288 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2291 self.type_ribs.pop();
2292 self.value_ribs.pop();
2296 fn resolve_function(&mut self,
2298 declaration: &FnDecl,
2300 // Create a value rib for the function.
2301 self.value_ribs.push(Rib::new(rib_kind));
2303 // Create a label rib for the function.
2304 self.label_ribs.push(Rib::new(rib_kind));
2306 // Add each argument to the rib.
2307 let mut bindings_list = HashMap::new();
2308 for argument in &declaration.inputs {
2309 self.resolve_pattern(&*argument.pat,
2310 ArgumentIrrefutableMode,
2311 &mut bindings_list);
2313 self.visit_ty(&*argument.ty);
2315 debug!("(resolving function) recorded argument");
2317 visit::walk_fn_ret_ty(self, &declaration.output);
2319 // Resolve the function body.
2320 self.visit_block(&*block);
2322 debug!("(resolving function) leaving function");
2325 self.label_ribs.pop();
2326 self.value_ribs.pop();
2330 fn resolve_trait_reference(&mut self,
2334 -> Result<PathResolution, ()> {
2335 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2336 if let DefTrait(_) = path_res.base_def {
2337 debug!("(resolving trait) found trait def: {:?}", path_res);
2342 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2346 // If it's a typedef, give a note
2347 if let DefTy(..) = path_res.base_def {
2348 self.session.span_note(trait_path.span,
2349 "`type` aliases cannot be used for traits");
2356 ResolutionError::UndeclaredTraitName(
2357 &*path_names_to_string(trait_path, path_depth))
2363 fn resolve_generics(&mut self, generics: &Generics) {
2364 for type_parameter in generics.ty_params.iter() {
2365 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2367 for predicate in &generics.where_clause.predicates {
2369 &hir::WherePredicate::BoundPredicate(_) |
2370 &hir::WherePredicate::RegionPredicate(_) => {}
2371 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2372 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2373 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2374 self.record_def(eq_pred.id, path_res.unwrap());
2378 ResolutionError::UndeclaredAssociatedType);
2383 visit::walk_generics(self, generics);
2386 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2387 where F: FnOnce(&mut Resolver) -> T
2389 // Handle nested impls (inside fn bodies)
2390 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2391 let result = f(self);
2392 self.current_self_type = previous_value;
2396 fn with_optional_trait_ref<T, F>(&mut self,
2397 opt_trait_ref: Option<&TraitRef>,
2400 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2402 let mut new_val = None;
2403 let mut new_id = None;
2404 if let Some(trait_ref) = opt_trait_ref {
2405 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2406 &trait_ref.path, 0) {
2407 assert!(path_res.depth == 0);
2408 self.record_def(trait_ref.ref_id, path_res);
2409 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2410 new_id = Some(path_res.base_def.def_id());
2412 visit::walk_trait_ref(self, trait_ref);
2414 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2415 let result = f(self, new_id);
2416 self.current_trait_ref = original_trait_ref;
2420 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2421 where F: FnOnce(&mut Resolver)
2423 let mut self_type_rib = Rib::new(NormalRibKind);
2425 // plain insert (no renaming, types are not currently hygienic....)
2426 let name = special_names::type_self;
2427 self_type_rib.bindings.insert(name, DlDef(self_def));
2428 self.type_ribs.push(self_type_rib);
2431 self.type_ribs.pop();
2435 fn resolve_implementation(&mut self,
2436 generics: &Generics,
2437 opt_trait_reference: &Option<TraitRef>,
2440 impl_items: &[P<ImplItem>]) {
2441 // If applicable, create a rib for the type parameters.
2442 self.with_type_parameter_rib(HasTypeParameters(generics,
2446 // Resolve the type parameters.
2447 this.visit_generics(generics);
2449 // Resolve the trait reference, if necessary.
2450 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2451 // Resolve the self type.
2452 this.visit_ty(self_type);
2454 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2455 this.with_current_self_type(self_type, |this| {
2456 for impl_item in impl_items {
2457 match impl_item.node {
2458 ConstImplItem(..) => {
2459 // If this is a trait impl, ensure the const
2461 this.check_trait_item(impl_item.ident.name,
2463 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2464 this.with_constant_rib(|this| {
2465 visit::walk_impl_item(this, impl_item);
2468 MethodImplItem(ref sig, _) => {
2469 // If this is a trait impl, ensure the method
2471 this.check_trait_item(impl_item.ident.name,
2473 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2475 // We also need a new scope for the method-
2476 // specific type parameters.
2477 let type_parameters =
2478 HasTypeParameters(&sig.generics,
2481 this.with_type_parameter_rib(type_parameters, |this| {
2482 visit::walk_impl_item(this, impl_item);
2485 TypeImplItem(ref ty) => {
2486 // If this is a trait impl, ensure the type
2488 this.check_trait_item(impl_item.ident.name,
2490 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2502 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2503 where F: FnOnce(Name, &str) -> ResolutionError {
2504 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2505 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2506 if !self.trait_item_map.contains_key(&(name, did)) {
2507 let path_str = path_names_to_string(&trait_ref.path, 0);
2510 err(name, &*path_str));
2515 fn resolve_local(&mut self, local: &Local) {
2516 // Resolve the type.
2517 visit::walk_ty_opt(self, &local.ty);
2519 // Resolve the initializer.
2520 visit::walk_expr_opt(self, &local.init);
2522 // Resolve the pattern.
2523 self.resolve_pattern(&*local.pat,
2524 LocalIrrefutableMode,
2525 &mut HashMap::new());
2528 // build a map from pattern identifiers to binding-info's.
2529 // this is done hygienically. This could arise for a macro
2530 // that expands into an or-pattern where one 'x' was from the
2531 // user and one 'x' came from the macro.
2532 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2533 let mut result = HashMap::new();
2534 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2535 let name = mtwt::resolve(path1.node);
2536 result.insert(name, BindingInfo {
2538 binding_mode: binding_mode
2544 // check that all of the arms in an or-pattern have exactly the
2545 // same set of bindings, with the same binding modes for each.
2546 fn check_consistent_bindings(&mut self, arm: &Arm) {
2547 if arm.pats.is_empty() {
2550 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2551 for (i, p) in arm.pats.iter().enumerate() {
2552 let map_i = self.binding_mode_map(&**p);
2554 for (&key, &binding_0) in &map_0 {
2555 match map_i.get(&key) {
2559 ResolutionError::VariableNotBoundInPattern(key,
2562 Some(binding_i) => {
2563 if binding_0.binding_mode != binding_i.binding_mode {
2566 ResolutionError::VariableBoundWithDifferentMode(key,
2574 for (&key, &binding) in &map_i {
2575 if !map_0.contains_key(&key) {
2578 ResolutionError::VariableNotBoundInParentPattern(key,
2585 fn resolve_arm(&mut self, arm: &Arm) {
2586 self.value_ribs.push(Rib::new(NormalRibKind));
2588 let mut bindings_list = HashMap::new();
2589 for pattern in &arm.pats {
2590 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2593 // This has to happen *after* we determine which
2594 // pat_idents are variants
2595 self.check_consistent_bindings(arm);
2597 visit::walk_expr_opt(self, &arm.guard);
2598 self.visit_expr(&*arm.body);
2601 self.value_ribs.pop();
2605 fn resolve_block(&mut self, block: &Block) {
2606 debug!("(resolving block) entering block");
2607 self.value_ribs.push(Rib::new(NormalRibKind));
2609 // Move down in the graph, if there's an anonymous module rooted here.
2610 let orig_module = self.current_module.clone();
2611 match orig_module.anonymous_children.borrow().get(&block.id) {
2612 None => { /* Nothing to do. */ }
2613 Some(anonymous_module) => {
2614 debug!("(resolving block) found anonymous module, moving \
2616 self.current_module = anonymous_module.clone();
2620 // Check for imports appearing after non-item statements.
2621 let mut found_non_item = false;
2622 for statement in &block.stmts {
2623 if let hir::StmtDecl(ref declaration, _) = statement.node {
2624 if let hir::DeclItem(ref i) = declaration.node {
2626 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2627 span_err!(self.session, i.span, E0154,
2628 "imports are not allowed after non-item statements");
2633 found_non_item = true
2636 found_non_item = true;
2640 // Descend into the block.
2641 visit::walk_block(self, block);
2645 self.current_module = orig_module;
2646 self.value_ribs.pop();
2648 debug!("(resolving block) leaving block");
2651 fn resolve_type(&mut self, ty: &Ty) {
2653 TyPath(ref maybe_qself, ref path) => {
2655 match self.resolve_possibly_assoc_item(ty.id,
2656 maybe_qself.as_ref(),
2660 // `<T>::a::b::c` is resolved by typeck alone.
2661 TypecheckRequired => {
2662 // Resolve embedded types.
2663 visit::walk_ty(self, ty);
2666 ResolveAttempt(resolution) => resolution,
2669 // This is a path in the type namespace. Walk through scopes
2673 // Write the result into the def map.
2674 debug!("(resolving type) writing resolution for `{}` \
2676 path_names_to_string(path, 0),
2678 self.record_def(ty.id, def);
2681 // Keep reporting some errors even if they're ignored above.
2682 self.resolve_path(ty.id, path, 0, TypeNS, true);
2684 let kind = if maybe_qself.is_some() {
2690 let self_type_name = special_idents::type_self.name;
2691 let is_invalid_self_type_name =
2692 path.segments.len() > 0 &&
2693 maybe_qself.is_none() &&
2694 path.segments[0].identifier.name == self_type_name;
2695 if is_invalid_self_type_name {
2698 ResolutionError::SelfUsedOutsideImplOrTrait);
2702 ResolutionError::UseOfUndeclared(
2704 &*path_names_to_string(path,
2713 // Resolve embedded types.
2714 visit::walk_ty(self, ty);
2717 fn resolve_pattern(&mut self,
2719 mode: PatternBindingMode,
2720 // Maps idents to the node ID for the (outermost)
2721 // pattern that binds them
2722 bindings_list: &mut HashMap<Name, NodeId>) {
2723 let pat_id = pattern.id;
2724 walk_pat(pattern, |pattern| {
2725 match pattern.node {
2726 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2727 // The meaning of PatIdent with no type parameters
2728 // depends on whether an enum variant or unit-like struct
2729 // with that name is in scope. The probing lookup has to
2730 // be careful not to emit spurious errors. Only matching
2731 // patterns (match) can match nullary variants or
2732 // unit-like structs. For binding patterns (let
2733 // and the LHS of @-patterns), matching such a value is
2734 // simply disallowed (since it's rarely what you want).
2735 let const_ok = mode == RefutableMode && at_rhs.is_none();
2737 let ident = path1.node;
2738 let renamed = mtwt::resolve(ident);
2740 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2741 FoundStructOrEnumVariant(def, lp) if const_ok => {
2742 debug!("(resolving pattern) resolving `{}` to \
2743 struct or enum variant",
2746 self.enforce_default_binding_mode(
2750 self.record_def(pattern.id, PathResolution {
2756 FoundStructOrEnumVariant(..) => {
2760 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2764 FoundConst(def, lp) if const_ok => {
2765 debug!("(resolving pattern) resolving `{}` to \
2769 self.enforce_default_binding_mode(
2773 self.record_def(pattern.id, PathResolution {
2783 ResolutionError::OnlyIrrefutablePatternsAllowedHere
2786 BareIdentifierPatternUnresolved => {
2787 debug!("(resolving pattern) binding `{}`",
2790 let def = DefLocal(pattern.id);
2792 // Record the definition so that later passes
2793 // will be able to distinguish variants from
2794 // locals in patterns.
2796 self.record_def(pattern.id, PathResolution {
2798 last_private: LastMod(AllPublic),
2802 // Add the binding to the local ribs, if it
2803 // doesn't already exist in the bindings list. (We
2804 // must not add it if it's in the bindings list
2805 // because that breaks the assumptions later
2806 // passes make about or-patterns.)
2807 if !bindings_list.contains_key(&renamed) {
2808 let this = &mut *self;
2809 let last_rib = this.value_ribs.last_mut().unwrap();
2810 last_rib.bindings.insert(renamed, DlDef(def));
2811 bindings_list.insert(renamed, pat_id);
2812 } else if mode == ArgumentIrrefutableMode &&
2813 bindings_list.contains_key(&renamed) {
2814 // Forbid duplicate bindings in the same
2819 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2820 &ident.name.as_str())
2822 } else if bindings_list.get(&renamed) ==
2824 // Then this is a duplicate variable in the
2825 // same disjunction, which is an error.
2829 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2830 &ident.name.as_str())
2833 // Else, not bound in the same pattern: do
2839 PatEnum(ref path, _) => {
2840 // This must be an enum variant, struct or const.
2842 match self.resolve_possibly_assoc_item(pat_id, None,
2845 // The below shouldn't happen because all
2846 // qualified paths should be in PatQPath.
2847 TypecheckRequired =>
2848 self.session.span_bug(
2850 "resolve_possibly_assoc_item claimed
2851 that a path in PatEnum requires typecheck
2852 to resolve, but qualified paths should be
2854 ResolveAttempt(resolution) => resolution,
2856 if let Some(path_res) = resolution {
2857 match path_res.base_def {
2858 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2859 self.record_def(pattern.id, path_res);
2862 resolve_error(&self,
2864 ResolutionError::StaticVariableReference);
2867 // If anything ends up here entirely resolved,
2868 // it's an error. If anything ends up here
2869 // partially resolved, that's OK, because it may
2870 // be a `T::CONST` that typeck will resolve.
2871 if path_res.depth == 0 {
2875 ResolutionError::NotAnEnumVariantStructOrConst(
2884 let const_name = path.segments.last().unwrap()
2886 let traits = self.get_traits_containing_item(const_name);
2887 self.trait_map.insert(pattern.id, traits);
2888 self.record_def(pattern.id, path_res);
2896 ResolutionError::UnresolvedEnumVariantStructOrConst(
2897 &path.segments.last().unwrap().identifier.name.as_str())
2900 visit::walk_path(self, path);
2903 PatQPath(ref qself, ref path) => {
2904 // Associated constants only.
2906 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2909 TypecheckRequired => {
2910 // All `<T>::CONST` should end up here, and will
2911 // require use of the trait map to resolve
2912 // during typechecking.
2913 let const_name = path.segments.last().unwrap()
2915 let traits = self.get_traits_containing_item(const_name);
2916 self.trait_map.insert(pattern.id, traits);
2917 visit::walk_pat(self, pattern);
2920 ResolveAttempt(resolution) => resolution,
2922 if let Some(path_res) = resolution {
2923 match path_res.base_def {
2924 // All `<T as Trait>::CONST` should end up here, and
2925 // have the trait already selected.
2926 DefAssociatedConst(..) => {
2927 self.record_def(pattern.id, path_res);
2933 ResolutionError::NotAnAssociatedConst(
2934 &path.segments.last().unwrap().identifier.name.as_str()
2943 ResolutionError::UnresolvedAssociatedConst(
2944 &path.segments.last().unwrap().identifier.name.as_str()
2948 visit::walk_pat(self, pattern);
2951 PatStruct(ref path, _, _) => {
2952 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2953 Some(definition) => {
2954 self.record_def(pattern.id, definition);
2957 debug!("(resolving pattern) didn't find struct \
2958 def: {:?}", result);
2962 ResolutionError::DoesNotNameAStruct(
2963 &*path_names_to_string(path, 0))
2967 visit::walk_path(self, path);
2970 PatLit(_) | PatRange(..) => {
2971 visit::walk_pat(self, pattern);
2982 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2983 -> BareIdentifierPatternResolution {
2984 let module = self.current_module.clone();
2985 match self.resolve_item_in_lexical_scope(module,
2988 Success((target, _)) => {
2989 debug!("(resolve bare identifier pattern) succeeded in \
2990 finding {} at {:?}",
2992 target.bindings.value_def.borrow());
2993 match *target.bindings.value_def.borrow() {
2995 panic!("resolved name in the value namespace to a \
2996 set of name bindings with no def?!");
2999 // For the two success cases, this lookup can be
3000 // considered as not having a private component because
3001 // the lookup happened only within the current module.
3003 def @ DefVariant(..) | def @ DefStruct(..) => {
3004 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3006 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
3007 return FoundConst(def, LastMod(AllPublic));
3012 ResolutionError::StaticVariableReference);
3013 return BareIdentifierPatternUnresolved;
3016 return BareIdentifierPatternUnresolved;
3024 panic!("unexpected indeterminate result");
3028 Some((span, msg)) => {
3029 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3034 debug!("(resolve bare identifier pattern) failed to find {}",
3036 return BareIdentifierPatternUnresolved;
3041 /// Handles paths that may refer to associated items
3042 fn resolve_possibly_assoc_item(&mut self,
3044 maybe_qself: Option<&hir::QSelf>,
3046 namespace: Namespace,
3048 -> AssocItemResolveResult
3050 let max_assoc_types;
3054 if qself.position == 0 {
3055 return TypecheckRequired;
3057 max_assoc_types = path.segments.len() - qself.position;
3058 // Make sure the trait is valid.
3059 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
3062 max_assoc_types = path.segments.len();
3066 let mut resolution = self.with_no_errors(|this| {
3067 this.resolve_path(id, path, 0, namespace, check_ribs)
3069 for depth in 1..max_assoc_types {
3070 if resolution.is_some() {
3073 self.with_no_errors(|this| {
3074 resolution = this.resolve_path(id, path, depth,
3078 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
3079 // A module is not a valid type or value.
3082 ResolveAttempt(resolution)
3085 /// If `check_ribs` is true, checks the local definitions first; i.e.
3086 /// doesn't skip straight to the containing module.
3087 /// Skips `path_depth` trailing segments, which is also reflected in the
3088 /// returned value. See `middle::def::PathResolution` for more info.
3089 pub fn resolve_path(&mut self,
3093 namespace: Namespace,
3094 check_ribs: bool) -> Option<PathResolution> {
3095 let span = path.span;
3096 let segments = &path.segments[..path.segments.len()-path_depth];
3098 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
3101 let def = self.resolve_crate_relative_path(span, segments, namespace);
3102 return def.map(mk_res);
3105 // Try to find a path to an item in a module.
3106 let unqualified_def =
3107 self.resolve_identifier(segments.last().unwrap().identifier,
3112 if segments.len() <= 1 {
3113 return unqualified_def.map(mk_res);
3116 let def = self.resolve_module_relative_path(span, segments, namespace);
3117 match (def, unqualified_def) {
3118 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3120 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3122 "unnecessary qualification".to_string());
3130 // Resolve a single identifier.
3131 fn resolve_identifier(&mut self,
3133 namespace: Namespace,
3136 -> Option<(Def, LastPrivate)> {
3137 // First, check to see whether the name is a primitive type.
3138 if namespace == TypeNS {
3139 if let Some(&prim_ty) = self.primitive_type_table
3141 .get(&identifier.name) {
3142 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
3147 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
3150 return Some((def, LastMod(AllPublic)));
3154 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
3157 // FIXME #4952: Merge me with resolve_name_in_module?
3158 fn resolve_definition_of_name_in_module(&mut self,
3159 containing_module: Rc<Module>,
3161 namespace: Namespace)
3163 // First, search children.
3164 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3166 match containing_module.children.borrow().get(&name) {
3167 Some(child_name_bindings) => {
3168 match child_name_bindings.def_for_namespace(namespace) {
3170 // Found it. Stop the search here.
3171 let p = child_name_bindings.defined_in_public_namespace(namespace);
3172 let lp = if p {LastMod(AllPublic)} else {
3173 LastMod(DependsOn(def.def_id()))
3175 return ChildNameDefinition(def, lp);
3183 // Next, search import resolutions.
3184 match containing_module.import_resolutions.borrow().get(&name) {
3185 Some(import_resolution) if import_resolution.is_public => {
3186 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3187 match target.bindings.def_for_namespace(namespace) {
3190 let id = import_resolution.id(namespace);
3191 // track imports and extern crates as well
3192 self.used_imports.insert((id, namespace));
3193 self.record_import_use(id, name);
3194 match target.target_module.def_id.get() {
3195 Some(DefId{krate: kid, ..}) => {
3196 self.used_crates.insert(kid);
3200 return ImportNameDefinition(def, LastMod(AllPublic));
3203 // This can happen with external impls, due to
3204 // the imperfect way we read the metadata.
3209 Some(..) | None => {} // Continue.
3212 // Finally, search through external children.
3213 if namespace == TypeNS {
3214 if let Some(module) = containing_module.external_module_children.borrow()
3215 .get(&name).cloned() {
3216 if let Some(def_id) = module.def_id.get() {
3217 // track used crates
3218 self.used_crates.insert(def_id.krate);
3219 let lp = if module.is_public {LastMod(AllPublic)} else {
3220 LastMod(DependsOn(def_id))
3222 return ChildNameDefinition(DefMod(def_id), lp);
3227 return NoNameDefinition;
3230 // resolve a "module-relative" path, e.g. a::b::c
3231 fn resolve_module_relative_path(&mut self,
3233 segments: &[hir::PathSegment],
3234 namespace: Namespace)
3235 -> Option<(Def, LastPrivate)> {
3236 let module_path = segments.split_last().unwrap().1.iter()
3237 .map(|ps| ps.identifier.name)
3238 .collect::<Vec<_>>();
3240 let containing_module;
3242 let current_module = self.current_module.clone();
3243 match self.resolve_module_path(current_module,
3249 let (span, msg) = match err {
3250 Some((span, msg)) => (span, msg),
3252 let msg = format!("Use of undeclared type or module `{}`",
3253 names_to_string(&module_path));
3258 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3261 Indeterminate => panic!("indeterminate unexpected"),
3262 Success((resulting_module, resulting_last_private)) => {
3263 containing_module = resulting_module;
3264 last_private = resulting_last_private;
3268 let name = segments.last().unwrap().identifier.name;
3269 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
3272 NoNameDefinition => {
3273 // We failed to resolve the name. Report an error.
3276 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3277 (def, last_private.or(lp))
3280 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
3281 self.used_crates.insert(kid);
3286 /// Invariant: This must be called only during main resolution, not during
3287 /// import resolution.
3288 fn resolve_crate_relative_path(&mut self,
3290 segments: &[hir::PathSegment],
3291 namespace: Namespace)
3292 -> Option<(Def, LastPrivate)> {
3293 let module_path = segments.split_last().unwrap().1.iter()
3294 .map(|ps| ps.identifier.name)
3295 .collect::<Vec<_>>();
3297 let root_module = self.graph_root.get_module();
3299 let containing_module;
3301 match self.resolve_module_path_from_root(root_module,
3306 LastMod(AllPublic)) {
3308 let (span, msg) = match err {
3309 Some((span, msg)) => (span, msg),
3311 let msg = format!("Use of undeclared module `::{}`",
3312 names_to_string(&module_path[..]));
3317 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3322 panic!("indeterminate unexpected");
3325 Success((resulting_module, resulting_last_private)) => {
3326 containing_module = resulting_module;
3327 last_private = resulting_last_private;
3331 let name = segments.last().unwrap().identifier.name;
3332 match self.resolve_definition_of_name_in_module(containing_module,
3335 NoNameDefinition => {
3336 // We failed to resolve the name. Report an error.
3339 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3340 return Some((def, last_private.or(lp)));
3345 fn resolve_identifier_in_local_ribs(&mut self,
3347 namespace: Namespace,
3350 // Check the local set of ribs.
3351 let search_result = match namespace {
3353 let renamed = mtwt::resolve(ident);
3354 self.search_ribs(&self.value_ribs, renamed, span)
3357 let name = ident.name;
3358 self.search_ribs(&self.type_ribs, name, span)
3362 match search_result {
3363 Some(DlDef(def)) => {
3364 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3369 Some(DlField) | Some(DlImpl(_)) | None => {
3375 fn resolve_item_by_name_in_lexical_scope(&mut self,
3377 namespace: Namespace)
3378 -> Option<(Def, LastPrivate)> {
3380 let module = self.current_module.clone();
3381 match self.resolve_item_in_lexical_scope(module,
3384 Success((target, _)) => {
3385 match (*target.bindings).def_for_namespace(namespace) {
3387 // This can happen if we were looking for a type and
3388 // found a module instead. Modules don't have defs.
3389 debug!("(resolving item path by identifier in lexical \
3390 scope) failed to resolve {} after success...",
3395 debug!("(resolving item path in lexical scope) \
3396 resolved `{}` to item",
3398 // This lookup is "all public" because it only searched
3399 // for one identifier in the current module (couldn't
3400 // have passed through reexports or anything like that.
3401 return Some((def, LastMod(AllPublic)));
3406 panic!("unexpected indeterminate result");
3409 debug!("(resolving item path by identifier in lexical scope) \
3410 failed to resolve {}", name);
3412 if let Some((span, msg)) = err {
3413 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3421 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3422 F: FnOnce(&mut Resolver) -> T,
3424 self.emit_errors = false;
3426 self.emit_errors = true;
3430 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3431 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3432 -> Option<(Path, NodeId, FallbackChecks)> {
3434 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3435 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3436 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3437 // This doesn't handle the remaining `Ty` variants as they are not
3438 // that commonly the self_type, it might be interesting to provide
3439 // support for those in future.
3444 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3445 -> Option<Rc<Module>> {
3446 let root = this.current_module.clone();
3447 let last_name = name_path.last().unwrap();
3449 if name_path.len() == 1 {
3450 match this.primitive_type_table.primitive_types.get(last_name) {
3453 match this.current_module.children.borrow().get(last_name) {
3454 Some(child) => child.get_module_if_available(),
3460 match this.resolve_module_path(root,
3465 Success((module, _)) => Some(module),
3471 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3473 let sig = match this.ast_map.get(did.node) {
3474 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3475 hir::MethodTraitItem(ref sig, _) => sig,
3478 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3479 hir::MethodImplItem(ref sig, _) => sig,
3484 sig.explicit_self.node == hir::SelfStatic
3486 csearch::is_static_method(&this.session.cstore, did)
3490 let (path, node_id, allowed) = match self.current_self_type {
3491 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3493 None => return NoSuggestion,
3495 None => return NoSuggestion,
3498 if allowed == Everything {
3499 // Look for a field with the same name in the current self_type.
3500 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3501 Some(DefTy(did, _)) |
3502 Some(DefStruct(did)) |
3503 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3506 if fields.iter().any(|&field_name| name == field_name) {
3511 _ => {} // Self type didn't resolve properly
3515 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3517 // Look for a method in the current self type's impl module.
3518 if let Some(module) = get_module(self, path.span, &name_path) {
3519 if let Some(binding) = module.children.borrow().get(&name) {
3520 if let Some(DefMethod(did)) = binding.def_for_namespace(ValueNS) {
3521 if is_static_method(self, did) {
3522 return StaticMethod(path_names_to_string(&path, 0))
3524 if self.current_trait_ref.is_some() {
3526 } else if allowed == Everything {
3533 // Look for a method in the current trait.
3534 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3535 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3536 if is_static_method(self, did) {
3537 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3547 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3548 let mut maybes: Vec<token::InternedString> = Vec::new();
3549 let mut values: Vec<usize> = Vec::new();
3551 for rib in self.value_ribs.iter().rev() {
3552 for (&k, _) in &rib.bindings {
3553 maybes.push(k.as_str());
3554 values.push(usize::MAX);
3558 let mut smallest = 0;
3559 for (i, other) in maybes.iter().enumerate() {
3560 values[i] = lev_distance(name, &other);
3562 if values[i] <= values[smallest] {
3567 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3568 // maximum edit distance we will accept for a suggestion to one third of
3569 // the typo'd name's length.
3570 let max_distance = std::cmp::max(name.len(), 3) / 3;
3572 if !values.is_empty() &&
3573 values[smallest] <= max_distance &&
3574 name != &maybes[smallest][..] {
3576 Some(maybes[smallest].to_string())
3583 fn resolve_expr(&mut self, expr: &Expr) {
3584 // First, record candidate traits for this expression if it could
3585 // result in the invocation of a method call.
3587 self.record_candidate_traits_for_expr_if_necessary(expr);
3589 // Next, resolve the node.
3591 ExprPath(ref maybe_qself, ref path) => {
3593 match self.resolve_possibly_assoc_item(expr.id,
3594 maybe_qself.as_ref(),
3598 // `<T>::a::b::c` is resolved by typeck alone.
3599 TypecheckRequired => {
3600 let method_name = path.segments.last().unwrap().identifier.name;
3601 let traits = self.get_traits_containing_item(method_name);
3602 self.trait_map.insert(expr.id, traits);
3603 visit::walk_expr(self, expr);
3606 ResolveAttempt(resolution) => resolution,
3609 // This is a local path in the value namespace. Walk through
3610 // scopes looking for it.
3611 if let Some(path_res) = resolution {
3612 // Check if struct variant
3613 if let DefVariant(_, _, true) = path_res.base_def {
3614 let path_name = path_names_to_string(path, 0);
3618 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3620 let msg = format!("did you mean to write: \
3621 `{} {{ /* fields */ }}`?",
3623 if self.emit_errors {
3624 self.session.fileline_help(expr.span, &msg);
3626 self.session.span_help(expr.span, &msg);
3629 // Write the result into the def map.
3630 debug!("(resolving expr) resolved `{}`",
3631 path_names_to_string(path, 0));
3633 // Partial resolutions will need the set of traits in scope,
3634 // so they can be completed during typeck.
3635 if path_res.depth != 0 {
3636 let method_name = path.segments.last().unwrap().identifier.name;
3637 let traits = self.get_traits_containing_item(method_name);
3638 self.trait_map.insert(expr.id, traits);
3641 self.record_def(expr.id, path_res);
3644 // Be helpful if the name refers to a struct
3645 // (The pattern matching def_tys where the id is in self.structs
3646 // matches on regular structs while excluding tuple- and enum-like
3647 // structs, which wouldn't result in this error.)
3648 let path_name = path_names_to_string(path, 0);
3649 let type_res = self.with_no_errors(|this| {
3650 this.resolve_path(expr.id, path, 0, TypeNS, false)
3652 match type_res.map(|r| r.base_def) {
3653 Some(DefTy(struct_id, _))
3654 if self.structs.contains_key(&struct_id) => {
3658 ResolutionError::StructVariantUsedAsFunction(
3662 let msg = format!("did you mean to write: \
3663 `{} {{ /* fields */ }}`?",
3665 if self.emit_errors {
3666 self.session.fileline_help(expr.span, &msg);
3668 self.session.span_help(expr.span, &msg);
3672 // Keep reporting some errors even if they're ignored above.
3673 self.resolve_path(expr.id, path, 0, ValueNS, true);
3675 let mut method_scope = false;
3676 self.value_ribs.iter().rev().all(|rib| {
3677 method_scope = match rib.kind {
3678 MethodRibKind => true,
3679 ItemRibKind | ConstantItemRibKind => false,
3680 _ => return true, // Keep advancing
3682 false // Stop advancing
3685 if method_scope && special_names::self_ == path_name {
3689 ResolutionError::SelfNotAvailableInStaticMethod
3692 let last_name = path.segments.last().unwrap().identifier.name;
3693 let mut msg = match self.find_fallback_in_self_type(last_name) {
3695 // limit search to 5 to reduce the number
3696 // of stupid suggestions
3697 self.find_best_match_for_name(&path_name)
3698 .map_or("".to_string(),
3699 |x| format!("`{}`", x))
3701 Field => format!("`self.{}`", path_name),
3704 format!("to call `self.{}`", path_name),
3705 TraitMethod(path_str) |
3706 StaticMethod(path_str) =>
3707 format!("to call `{}::{}`", path_str, path_name)
3710 if !msg.is_empty() {
3711 msg = format!(". Did you mean {}?", msg)
3716 ResolutionError::UnresolvedName(&*path_name,
3723 visit::walk_expr(self, expr);
3726 ExprStruct(ref path, _, _) => {
3727 // Resolve the path to the structure it goes to. We don't
3728 // check to ensure that the path is actually a structure; that
3729 // is checked later during typeck.
3730 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3731 Some(definition) => self.record_def(expr.id, definition),
3733 debug!("(resolving expression) didn't find struct def",);
3737 ResolutionError::DoesNotNameAStruct(
3738 &*path_names_to_string(path, 0))
3743 visit::walk_expr(self, expr);
3746 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3747 self.with_label_rib(|this| {
3748 let def_like = DlDef(DefLabel(expr.id));
3751 let rib = this.label_ribs.last_mut().unwrap();
3752 let renamed = mtwt::resolve(label);
3753 rib.bindings.insert(renamed, def_like);
3756 visit::walk_expr(this, expr);
3760 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3761 let renamed = mtwt::resolve(label.node);
3762 match self.search_label(renamed) {
3766 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3768 Some(DlDef(def @ DefLabel(_))) => {
3769 // Since this def is a label, it is never read.
3770 self.record_def(expr.id, PathResolution {
3772 last_private: LastMod(AllPublic),
3777 self.session.span_bug(expr.span,
3778 "label wasn't mapped to a \
3785 visit::walk_expr(self, expr);
3790 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3792 ExprField(_, ident) => {
3793 // FIXME(#6890): Even though you can't treat a method like a
3794 // field, we need to add any trait methods we find that match
3795 // the field name so that we can do some nice error reporting
3796 // later on in typeck.
3797 let traits = self.get_traits_containing_item(ident.node.name);
3798 self.trait_map.insert(expr.id, traits);
3800 ExprMethodCall(ident, _, _) => {
3801 debug!("(recording candidate traits for expr) recording \
3804 let traits = self.get_traits_containing_item(ident.node.name);
3805 self.trait_map.insert(expr.id, traits);
3813 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3814 debug!("(getting traits containing item) looking for '{}'",
3817 fn add_trait_info(found_traits: &mut Vec<DefId>,
3818 trait_def_id: DefId,
3820 debug!("(adding trait info) found trait {}:{} for method '{}'",
3824 found_traits.push(trait_def_id);
3827 let mut found_traits = Vec::new();
3828 let mut search_module = self.current_module.clone();
3830 // Look for the current trait.
3831 match self.current_trait_ref {
3832 Some((trait_def_id, _)) => {
3833 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3834 add_trait_info(&mut found_traits, trait_def_id, name);
3837 None => {} // Nothing to do.
3840 // Look for trait children.
3841 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3844 for (_, child_names) in search_module.children.borrow().iter() {
3845 let def = match child_names.def_for_namespace(TypeNS) {
3849 let trait_def_id = match def {
3850 DefTrait(trait_def_id) => trait_def_id,
3853 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3854 add_trait_info(&mut found_traits, trait_def_id, name);
3859 // Look for imports.
3860 for (_, import) in search_module.import_resolutions.borrow().iter() {
3861 let target = match import.target_for_namespace(TypeNS) {
3863 Some(target) => target,
3865 let did = match target.bindings.def_for_namespace(TypeNS) {
3866 Some(DefTrait(trait_def_id)) => trait_def_id,
3867 Some(..) | None => continue,
3869 if self.trait_item_map.contains_key(&(name, did)) {
3870 add_trait_info(&mut found_traits, did, name);
3871 let id = import.type_id;
3872 self.used_imports.insert((id, TypeNS));
3873 let trait_name = self.get_trait_name(did);
3874 self.record_import_use(id, trait_name);
3875 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3876 self.used_crates.insert(kid);
3881 match search_module.parent_link.clone() {
3882 NoParentLink | ModuleParentLink(..) => break,
3883 BlockParentLink(parent_module, _) => {
3884 search_module = parent_module.upgrade().unwrap();
3892 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3893 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3894 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3895 "Import should only be used for `use` directives");
3897 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3898 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3899 self.session.span_bug(span, &format!("path resolved multiple times \
3900 ({:?} before, {:?} now)",
3901 prev_res, resolution));
3905 fn enforce_default_binding_mode(&mut self,
3907 pat_binding_mode: BindingMode,
3909 match pat_binding_mode {
3910 BindByValue(_) => {}
3914 ResolutionError::CannotUseRefBindingModeWith(descr));
3922 // Diagnostics are not particularly efficient, because they're rarely
3926 #[allow(dead_code)] // useful for debugging
3927 fn dump_module(&mut self, module_: Rc<Module>) {
3928 debug!("Dump of module `{}`:", module_to_string(&*module_));
3930 debug!("Children:");
3931 build_reduced_graph::populate_module_if_necessary(self, &module_);
3932 for (&name, _) in module_.children.borrow().iter() {
3933 debug!("* {}", name);
3936 debug!("Import resolutions:");
3937 let import_resolutions = module_.import_resolutions.borrow();
3938 for (&name, import_resolution) in import_resolutions.iter() {
3940 match import_resolution.target_for_namespace(ValueNS) {
3941 None => { value_repr = "".to_string(); }
3943 value_repr = " value:?".to_string();
3949 match import_resolution.target_for_namespace(TypeNS) {
3950 None => { type_repr = "".to_string(); }
3952 type_repr = " type:?".to_string();
3957 debug!("* {}:{}{}", name, value_repr, type_repr);
3963 fn names_to_string(names: &[Name]) -> String {
3964 let mut first = true;
3965 let mut result = String::new();
3970 result.push_str("::")
3972 result.push_str(&name.as_str());
3977 fn path_names_to_string(path: &Path, depth: usize) -> String {
3978 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3980 .map(|seg| seg.identifier.name)
3982 names_to_string(&names[..])
3985 /// A somewhat inefficient routine to obtain the name of a module.
3986 fn module_to_string(module: &Module) -> String {
3987 let mut names = Vec::new();
3989 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3990 match module.parent_link {
3992 ModuleParentLink(ref module, name) => {
3994 collect_mod(names, &*module.upgrade().unwrap());
3996 BlockParentLink(ref module, _) => {
3997 // danger, shouldn't be ident?
3998 names.push(special_idents::opaque.name);
3999 collect_mod(names, &*module.upgrade().unwrap());
4003 collect_mod(&mut names, module);
4005 if names.is_empty() {
4006 return "???".to_string();
4008 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
4012 pub struct CrateMap {
4013 pub def_map: DefMap,
4014 pub freevars: RefCell<FreevarMap>,
4015 pub export_map: ExportMap,
4016 pub trait_map: TraitMap,
4017 pub external_exports: ExternalExports,
4018 pub glob_map: Option<GlobMap>
4021 #[derive(PartialEq,Copy, Clone)]
4022 pub enum MakeGlobMap {
4027 /// Entry point to crate resolution.
4028 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4029 ast_map: &'a hir_map::Map<'tcx>,
4030 make_glob_map: MakeGlobMap)
4032 let krate = ast_map.krate();
4033 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
4035 resolver.resolve_crate(krate);
4036 session.abort_if_errors();
4038 check_unused::check_crate(&mut resolver, krate);
4041 def_map: resolver.def_map,
4042 freevars: resolver.freevars,
4043 export_map: resolver.export_map,
4044 trait_map: resolver.trait_map,
4045 external_exports: resolver.external_exports,
4046 glob_map: if resolver.make_glob_map {
4047 Some(resolver.glob_map)
4054 /// Builds a name resolution walker to be used within this module,
4055 /// or used externally, with an optional callback function.
4057 /// The callback takes a &mut bool which allows callbacks to end a
4058 /// walk when set to true, passing through the rest of the walk, while
4059 /// preserving the ribs + current module. This allows resolve_path
4060 /// calls to be made with the correct scope info. The node in the
4061 /// callback corresponds to the current node in the walk.
4062 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
4063 ast_map: &'a hir_map::Map<'tcx>,
4065 make_glob_map: MakeGlobMap,
4066 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
4067 -> Resolver<'a, 'tcx> {
4068 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4070 resolver.callback = callback;
4072 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4073 session.abort_if_errors();
4075 resolve_imports::resolve_imports(&mut resolver);
4076 session.abort_if_errors();
4078 record_exports::record(&mut resolver);
4079 session.abort_if_errors();
4084 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }