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 let check_rename = |id, ident: Ident| {
2216 match self.def_map.borrow().get(&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);
2224 match view_path.node {
2225 hir::ViewPathSimple(ident, _) => {
2226 check_rename(item.id, ident);
2228 hir::ViewPathList(_, ref items) => {
2230 if let Some(ident) = item.node.rename() {
2231 check_rename(item.node.id(), ident);
2239 ItemExternCrate(_) => {
2240 // do nothing, these are just around to be encoded
2245 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2246 F: FnOnce(&mut Resolver),
2248 match type_parameters {
2249 HasTypeParameters(generics, space, rib_kind) => {
2250 let mut function_type_rib = Rib::new(rib_kind);
2251 let mut seen_bindings = HashSet::new();
2252 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2253 let name = type_parameter.ident.name;
2254 debug!("with_type_parameter_rib: {}", type_parameter.id);
2256 if seen_bindings.contains(&name) {
2258 type_parameter.span,
2259 ResolutionError::NameAlreadyUsedInTypeParameterList(
2263 seen_bindings.insert(name);
2265 // plain insert (no renaming)
2266 function_type_rib.bindings.insert(name,
2267 DlDef(DefTyParam(space,
2269 DefId::local(type_parameter.id),
2272 self.type_ribs.push(function_type_rib);
2275 NoTypeParameters => {
2282 match type_parameters {
2283 HasTypeParameters(..) => { if !self.resolved { self.type_ribs.pop(); } }
2284 NoTypeParameters => { }
2288 fn with_label_rib<F>(&mut self, f: F) where
2289 F: FnOnce(&mut Resolver),
2291 self.label_ribs.push(Rib::new(NormalRibKind));
2294 self.label_ribs.pop();
2298 fn with_constant_rib<F>(&mut self, f: F) where
2299 F: FnOnce(&mut Resolver),
2301 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2302 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2305 self.type_ribs.pop();
2306 self.value_ribs.pop();
2310 fn resolve_function(&mut self,
2312 declaration: &FnDecl,
2314 // Create a value rib for the function.
2315 self.value_ribs.push(Rib::new(rib_kind));
2317 // Create a label rib for the function.
2318 self.label_ribs.push(Rib::new(rib_kind));
2320 // Add each argument to the rib.
2321 let mut bindings_list = HashMap::new();
2322 for argument in &declaration.inputs {
2323 self.resolve_pattern(&*argument.pat,
2324 ArgumentIrrefutableMode,
2325 &mut bindings_list);
2327 self.visit_ty(&*argument.ty);
2329 debug!("(resolving function) recorded argument");
2331 visit::walk_fn_ret_ty(self, &declaration.output);
2333 // Resolve the function body.
2334 self.visit_block(&*block);
2336 debug!("(resolving function) leaving function");
2339 self.label_ribs.pop();
2340 self.value_ribs.pop();
2344 fn resolve_trait_reference(&mut self,
2348 -> Result<PathResolution, ()> {
2349 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2350 if let DefTrait(_) = path_res.base_def {
2351 debug!("(resolving trait) found trait def: {:?}", path_res);
2356 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2360 // If it's a typedef, give a note
2361 if let DefTy(..) = path_res.base_def {
2362 self.session.span_note(trait_path.span,
2363 "`type` aliases cannot be used for traits");
2370 ResolutionError::UndeclaredTraitName(
2371 &*path_names_to_string(trait_path, path_depth))
2377 fn resolve_generics(&mut self, generics: &Generics) {
2378 for type_parameter in generics.ty_params.iter() {
2379 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2381 for predicate in &generics.where_clause.predicates {
2383 &hir::WherePredicate::BoundPredicate(_) |
2384 &hir::WherePredicate::RegionPredicate(_) => {}
2385 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2386 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2387 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2388 self.record_def(eq_pred.id, path_res.unwrap());
2392 ResolutionError::UndeclaredAssociatedType);
2397 visit::walk_generics(self, generics);
2400 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2401 where F: FnOnce(&mut Resolver) -> T
2403 // Handle nested impls (inside fn bodies)
2404 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2405 let result = f(self);
2406 self.current_self_type = previous_value;
2410 fn with_optional_trait_ref<T, F>(&mut self,
2411 opt_trait_ref: Option<&TraitRef>,
2414 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2416 let mut new_val = None;
2417 let mut new_id = None;
2418 if let Some(trait_ref) = opt_trait_ref {
2419 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2420 &trait_ref.path, 0) {
2421 assert!(path_res.depth == 0);
2422 self.record_def(trait_ref.ref_id, path_res);
2423 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2424 new_id = Some(path_res.base_def.def_id());
2426 visit::walk_trait_ref(self, trait_ref);
2428 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2429 let result = f(self, new_id);
2430 self.current_trait_ref = original_trait_ref;
2434 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2435 where F: FnOnce(&mut Resolver)
2437 let mut self_type_rib = Rib::new(NormalRibKind);
2439 // plain insert (no renaming, types are not currently hygienic....)
2440 let name = special_names::type_self;
2441 self_type_rib.bindings.insert(name, DlDef(self_def));
2442 self.type_ribs.push(self_type_rib);
2445 self.type_ribs.pop();
2449 fn resolve_implementation(&mut self,
2450 generics: &Generics,
2451 opt_trait_reference: &Option<TraitRef>,
2454 impl_items: &[P<ImplItem>]) {
2455 // If applicable, create a rib for the type parameters.
2456 self.with_type_parameter_rib(HasTypeParameters(generics,
2460 // Resolve the type parameters.
2461 this.visit_generics(generics);
2463 // Resolve the trait reference, if necessary.
2464 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2465 // Resolve the self type.
2466 this.visit_ty(self_type);
2468 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2469 this.with_current_self_type(self_type, |this| {
2470 for impl_item in impl_items {
2471 match impl_item.node {
2472 ConstImplItem(..) => {
2473 // If this is a trait impl, ensure the const
2475 this.check_trait_item(impl_item.ident.name,
2477 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2478 this.with_constant_rib(|this| {
2479 visit::walk_impl_item(this, impl_item);
2482 MethodImplItem(ref sig, _) => {
2483 // If this is a trait impl, ensure the method
2485 this.check_trait_item(impl_item.ident.name,
2487 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2489 // We also need a new scope for the method-
2490 // specific type parameters.
2491 let type_parameters =
2492 HasTypeParameters(&sig.generics,
2495 this.with_type_parameter_rib(type_parameters, |this| {
2496 visit::walk_impl_item(this, impl_item);
2499 TypeImplItem(ref ty) => {
2500 // If this is a trait impl, ensure the type
2502 this.check_trait_item(impl_item.ident.name,
2504 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2516 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2517 where F: FnOnce(Name, &str) -> ResolutionError {
2518 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2519 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2520 if !self.trait_item_map.contains_key(&(name, did)) {
2521 let path_str = path_names_to_string(&trait_ref.path, 0);
2524 err(name, &*path_str));
2529 fn resolve_local(&mut self, local: &Local) {
2530 // Resolve the type.
2531 visit::walk_ty_opt(self, &local.ty);
2533 // Resolve the initializer.
2534 visit::walk_expr_opt(self, &local.init);
2536 // Resolve the pattern.
2537 self.resolve_pattern(&*local.pat,
2538 LocalIrrefutableMode,
2539 &mut HashMap::new());
2542 // build a map from pattern identifiers to binding-info's.
2543 // this is done hygienically. This could arise for a macro
2544 // that expands into an or-pattern where one 'x' was from the
2545 // user and one 'x' came from the macro.
2546 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2547 let mut result = HashMap::new();
2548 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2549 let name = mtwt::resolve(path1.node);
2550 result.insert(name, BindingInfo {
2552 binding_mode: binding_mode
2558 // check that all of the arms in an or-pattern have exactly the
2559 // same set of bindings, with the same binding modes for each.
2560 fn check_consistent_bindings(&mut self, arm: &Arm) {
2561 if arm.pats.is_empty() {
2564 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2565 for (i, p) in arm.pats.iter().enumerate() {
2566 let map_i = self.binding_mode_map(&**p);
2568 for (&key, &binding_0) in &map_0 {
2569 match map_i.get(&key) {
2573 ResolutionError::VariableNotBoundInPattern(key,
2576 Some(binding_i) => {
2577 if binding_0.binding_mode != binding_i.binding_mode {
2580 ResolutionError::VariableBoundWithDifferentMode(key,
2588 for (&key, &binding) in &map_i {
2589 if !map_0.contains_key(&key) {
2592 ResolutionError::VariableNotBoundInParentPattern(key,
2599 fn resolve_arm(&mut self, arm: &Arm) {
2600 self.value_ribs.push(Rib::new(NormalRibKind));
2602 let mut bindings_list = HashMap::new();
2603 for pattern in &arm.pats {
2604 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2607 // This has to happen *after* we determine which
2608 // pat_idents are variants
2609 self.check_consistent_bindings(arm);
2611 visit::walk_expr_opt(self, &arm.guard);
2612 self.visit_expr(&*arm.body);
2615 self.value_ribs.pop();
2619 fn resolve_block(&mut self, block: &Block) {
2620 debug!("(resolving block) entering block");
2621 self.value_ribs.push(Rib::new(NormalRibKind));
2623 // Move down in the graph, if there's an anonymous module rooted here.
2624 let orig_module = self.current_module.clone();
2625 match orig_module.anonymous_children.borrow().get(&block.id) {
2626 None => { /* Nothing to do. */ }
2627 Some(anonymous_module) => {
2628 debug!("(resolving block) found anonymous module, moving \
2630 self.current_module = anonymous_module.clone();
2634 // Check for imports appearing after non-item statements.
2635 let mut found_non_item = false;
2636 for statement in &block.stmts {
2637 if let hir::StmtDecl(ref declaration, _) = statement.node {
2638 if let hir::DeclItem(ref i) = declaration.node {
2640 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2641 span_err!(self.session, i.span, E0154,
2642 "imports are not allowed after non-item statements");
2647 found_non_item = true
2650 found_non_item = true;
2654 // Descend into the block.
2655 visit::walk_block(self, block);
2659 self.current_module = orig_module;
2660 self.value_ribs.pop();
2662 debug!("(resolving block) leaving block");
2665 fn resolve_type(&mut self, ty: &Ty) {
2667 TyPath(ref maybe_qself, ref path) => {
2669 match self.resolve_possibly_assoc_item(ty.id,
2670 maybe_qself.as_ref(),
2674 // `<T>::a::b::c` is resolved by typeck alone.
2675 TypecheckRequired => {
2676 // Resolve embedded types.
2677 visit::walk_ty(self, ty);
2680 ResolveAttempt(resolution) => resolution,
2683 // This is a path in the type namespace. Walk through scopes
2687 // Write the result into the def map.
2688 debug!("(resolving type) writing resolution for `{}` \
2690 path_names_to_string(path, 0),
2692 self.record_def(ty.id, def);
2695 // Keep reporting some errors even if they're ignored above.
2696 self.resolve_path(ty.id, path, 0, TypeNS, true);
2698 let kind = if maybe_qself.is_some() {
2704 let self_type_name = special_idents::type_self.name;
2705 let is_invalid_self_type_name =
2706 path.segments.len() > 0 &&
2707 maybe_qself.is_none() &&
2708 path.segments[0].identifier.name == self_type_name;
2709 if is_invalid_self_type_name {
2712 ResolutionError::SelfUsedOutsideImplOrTrait);
2716 ResolutionError::UseOfUndeclared(
2718 &*path_names_to_string(path,
2727 // Resolve embedded types.
2728 visit::walk_ty(self, ty);
2731 fn resolve_pattern(&mut self,
2733 mode: PatternBindingMode,
2734 // Maps idents to the node ID for the (outermost)
2735 // pattern that binds them
2736 bindings_list: &mut HashMap<Name, NodeId>) {
2737 let pat_id = pattern.id;
2738 walk_pat(pattern, |pattern| {
2739 match pattern.node {
2740 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2741 // The meaning of PatIdent with no type parameters
2742 // depends on whether an enum variant or unit-like struct
2743 // with that name is in scope. The probing lookup has to
2744 // be careful not to emit spurious errors. Only matching
2745 // patterns (match) can match nullary variants or
2746 // unit-like structs. For binding patterns (let
2747 // and the LHS of @-patterns), matching such a value is
2748 // simply disallowed (since it's rarely what you want).
2749 let const_ok = mode == RefutableMode && at_rhs.is_none();
2751 let ident = path1.node;
2752 let renamed = mtwt::resolve(ident);
2754 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2755 FoundStructOrEnumVariant(def, lp) if const_ok => {
2756 debug!("(resolving pattern) resolving `{}` to \
2757 struct or enum variant",
2760 self.enforce_default_binding_mode(
2764 self.record_def(pattern.id, PathResolution {
2770 FoundStructOrEnumVariant(..) => {
2774 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2778 FoundConst(def, lp) if const_ok => {
2779 debug!("(resolving pattern) resolving `{}` to \
2783 self.enforce_default_binding_mode(
2787 self.record_def(pattern.id, PathResolution {
2797 ResolutionError::OnlyIrrefutablePatternsAllowedHere
2800 BareIdentifierPatternUnresolved => {
2801 debug!("(resolving pattern) binding `{}`",
2804 let def = DefLocal(pattern.id);
2806 // Record the definition so that later passes
2807 // will be able to distinguish variants from
2808 // locals in patterns.
2810 self.record_def(pattern.id, PathResolution {
2812 last_private: LastMod(AllPublic),
2816 // Add the binding to the local ribs, if it
2817 // doesn't already exist in the bindings list. (We
2818 // must not add it if it's in the bindings list
2819 // because that breaks the assumptions later
2820 // passes make about or-patterns.)
2821 if !bindings_list.contains_key(&renamed) {
2822 let this = &mut *self;
2823 let last_rib = this.value_ribs.last_mut().unwrap();
2824 last_rib.bindings.insert(renamed, DlDef(def));
2825 bindings_list.insert(renamed, pat_id);
2826 } else if mode == ArgumentIrrefutableMode &&
2827 bindings_list.contains_key(&renamed) {
2828 // Forbid duplicate bindings in the same
2833 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2834 &ident.name.as_str())
2836 } else if bindings_list.get(&renamed) ==
2838 // Then this is a duplicate variable in the
2839 // same disjunction, which is an error.
2843 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2844 &ident.name.as_str())
2847 // Else, not bound in the same pattern: do
2853 PatEnum(ref path, _) => {
2854 // This must be an enum variant, struct or const.
2856 match self.resolve_possibly_assoc_item(pat_id, None,
2859 // The below shouldn't happen because all
2860 // qualified paths should be in PatQPath.
2861 TypecheckRequired =>
2862 self.session.span_bug(
2864 "resolve_possibly_assoc_item claimed
2865 that a path in PatEnum requires typecheck
2866 to resolve, but qualified paths should be
2868 ResolveAttempt(resolution) => resolution,
2870 if let Some(path_res) = resolution {
2871 match path_res.base_def {
2872 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2873 self.record_def(pattern.id, path_res);
2876 resolve_error(&self,
2878 ResolutionError::StaticVariableReference);
2881 // If anything ends up here entirely resolved,
2882 // it's an error. If anything ends up here
2883 // partially resolved, that's OK, because it may
2884 // be a `T::CONST` that typeck will resolve.
2885 if path_res.depth == 0 {
2889 ResolutionError::NotAnEnumVariantStructOrConst(
2898 let const_name = path.segments.last().unwrap()
2900 let traits = self.get_traits_containing_item(const_name);
2901 self.trait_map.insert(pattern.id, traits);
2902 self.record_def(pattern.id, path_res);
2910 ResolutionError::UnresolvedEnumVariantStructOrConst(
2911 &path.segments.last().unwrap().identifier.name.as_str())
2914 visit::walk_path(self, path);
2917 PatQPath(ref qself, ref path) => {
2918 // Associated constants only.
2920 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2923 TypecheckRequired => {
2924 // All `<T>::CONST` should end up here, and will
2925 // require use of the trait map to resolve
2926 // during typechecking.
2927 let const_name = path.segments.last().unwrap()
2929 let traits = self.get_traits_containing_item(const_name);
2930 self.trait_map.insert(pattern.id, traits);
2931 visit::walk_pat(self, pattern);
2934 ResolveAttempt(resolution) => resolution,
2936 if let Some(path_res) = resolution {
2937 match path_res.base_def {
2938 // All `<T as Trait>::CONST` should end up here, and
2939 // have the trait already selected.
2940 DefAssociatedConst(..) => {
2941 self.record_def(pattern.id, path_res);
2947 ResolutionError::NotAnAssociatedConst(
2948 &path.segments.last().unwrap().identifier.name.as_str()
2957 ResolutionError::UnresolvedAssociatedConst(
2958 &path.segments.last().unwrap().identifier.name.as_str()
2962 visit::walk_pat(self, pattern);
2965 PatStruct(ref path, _, _) => {
2966 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2967 Some(definition) => {
2968 self.record_def(pattern.id, definition);
2971 debug!("(resolving pattern) didn't find struct \
2972 def: {:?}", result);
2976 ResolutionError::DoesNotNameAStruct(
2977 &*path_names_to_string(path, 0))
2981 visit::walk_path(self, path);
2984 PatLit(_) | PatRange(..) => {
2985 visit::walk_pat(self, pattern);
2996 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2997 -> BareIdentifierPatternResolution {
2998 let module = self.current_module.clone();
2999 match self.resolve_item_in_lexical_scope(module,
3002 Success((target, _)) => {
3003 debug!("(resolve bare identifier pattern) succeeded in \
3004 finding {} at {:?}",
3006 target.bindings.value_def.borrow());
3007 match *target.bindings.value_def.borrow() {
3009 panic!("resolved name in the value namespace to a \
3010 set of name bindings with no def?!");
3013 // For the two success cases, this lookup can be
3014 // considered as not having a private component because
3015 // the lookup happened only within the current module.
3017 def @ DefVariant(..) | def @ DefStruct(..) => {
3018 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3020 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
3021 return FoundConst(def, LastMod(AllPublic));
3026 ResolutionError::StaticVariableReference);
3027 return BareIdentifierPatternUnresolved;
3030 return BareIdentifierPatternUnresolved;
3038 panic!("unexpected indeterminate result");
3042 Some((span, msg)) => {
3043 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3048 debug!("(resolve bare identifier pattern) failed to find {}",
3050 return BareIdentifierPatternUnresolved;
3055 /// Handles paths that may refer to associated items
3056 fn resolve_possibly_assoc_item(&mut self,
3058 maybe_qself: Option<&hir::QSelf>,
3060 namespace: Namespace,
3062 -> AssocItemResolveResult
3064 let max_assoc_types;
3068 if qself.position == 0 {
3069 return TypecheckRequired;
3071 max_assoc_types = path.segments.len() - qself.position;
3072 // Make sure the trait is valid.
3073 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
3076 max_assoc_types = path.segments.len();
3080 let mut resolution = self.with_no_errors(|this| {
3081 this.resolve_path(id, path, 0, namespace, check_ribs)
3083 for depth in 1..max_assoc_types {
3084 if resolution.is_some() {
3087 self.with_no_errors(|this| {
3088 resolution = this.resolve_path(id, path, depth,
3092 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
3093 // A module is not a valid type or value.
3096 ResolveAttempt(resolution)
3099 /// If `check_ribs` is true, checks the local definitions first; i.e.
3100 /// doesn't skip straight to the containing module.
3101 /// Skips `path_depth` trailing segments, which is also reflected in the
3102 /// returned value. See `middle::def::PathResolution` for more info.
3103 pub fn resolve_path(&mut self,
3107 namespace: Namespace,
3108 check_ribs: bool) -> Option<PathResolution> {
3109 let span = path.span;
3110 let segments = &path.segments[..path.segments.len()-path_depth];
3112 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
3115 let def = self.resolve_crate_relative_path(span, segments, namespace);
3116 return def.map(mk_res);
3119 // Try to find a path to an item in a module.
3120 let unqualified_def =
3121 self.resolve_identifier(segments.last().unwrap().identifier,
3126 if segments.len() <= 1 {
3127 return unqualified_def.map(mk_res);
3130 let def = self.resolve_module_relative_path(span, segments, namespace);
3131 match (def, unqualified_def) {
3132 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3134 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3136 "unnecessary qualification".to_string());
3144 // Resolve a single identifier.
3145 fn resolve_identifier(&mut self,
3147 namespace: Namespace,
3150 -> Option<(Def, LastPrivate)> {
3151 // First, check to see whether the name is a primitive type.
3152 if namespace == TypeNS {
3153 if let Some(&prim_ty) = self.primitive_type_table
3155 .get(&identifier.name) {
3156 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
3161 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
3164 return Some((def, LastMod(AllPublic)));
3168 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
3171 // FIXME #4952: Merge me with resolve_name_in_module?
3172 fn resolve_definition_of_name_in_module(&mut self,
3173 containing_module: Rc<Module>,
3175 namespace: Namespace)
3177 // First, search children.
3178 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3180 match containing_module.children.borrow().get(&name) {
3181 Some(child_name_bindings) => {
3182 match child_name_bindings.def_for_namespace(namespace) {
3184 // Found it. Stop the search here.
3185 let p = child_name_bindings.defined_in_public_namespace(namespace);
3186 let lp = if p {LastMod(AllPublic)} else {
3187 LastMod(DependsOn(def.def_id()))
3189 return ChildNameDefinition(def, lp);
3197 // Next, search import resolutions.
3198 match containing_module.import_resolutions.borrow().get(&name) {
3199 Some(import_resolution) if import_resolution.is_public => {
3200 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3201 match target.bindings.def_for_namespace(namespace) {
3204 let id = import_resolution.id(namespace);
3205 // track imports and extern crates as well
3206 self.used_imports.insert((id, namespace));
3207 self.record_import_use(id, name);
3208 match target.target_module.def_id.get() {
3209 Some(DefId{krate: kid, ..}) => {
3210 self.used_crates.insert(kid);
3214 return ImportNameDefinition(def, LastMod(AllPublic));
3217 // This can happen with external impls, due to
3218 // the imperfect way we read the metadata.
3223 Some(..) | None => {} // Continue.
3226 // Finally, search through external children.
3227 if namespace == TypeNS {
3228 if let Some(module) = containing_module.external_module_children.borrow()
3229 .get(&name).cloned() {
3230 if let Some(def_id) = module.def_id.get() {
3231 // track used crates
3232 self.used_crates.insert(def_id.krate);
3233 let lp = if module.is_public {LastMod(AllPublic)} else {
3234 LastMod(DependsOn(def_id))
3236 return ChildNameDefinition(DefMod(def_id), lp);
3241 return NoNameDefinition;
3244 // resolve a "module-relative" path, e.g. a::b::c
3245 fn resolve_module_relative_path(&mut self,
3247 segments: &[hir::PathSegment],
3248 namespace: Namespace)
3249 -> Option<(Def, LastPrivate)> {
3250 let module_path = segments.split_last().unwrap().1.iter()
3251 .map(|ps| ps.identifier.name)
3252 .collect::<Vec<_>>();
3254 let containing_module;
3256 let current_module = self.current_module.clone();
3257 match self.resolve_module_path(current_module,
3263 let (span, msg) = match err {
3264 Some((span, msg)) => (span, msg),
3266 let msg = format!("Use of undeclared type or module `{}`",
3267 names_to_string(&module_path));
3272 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3275 Indeterminate => panic!("indeterminate unexpected"),
3276 Success((resulting_module, resulting_last_private)) => {
3277 containing_module = resulting_module;
3278 last_private = resulting_last_private;
3282 let name = segments.last().unwrap().identifier.name;
3283 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
3286 NoNameDefinition => {
3287 // We failed to resolve the name. Report an error.
3290 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3291 (def, last_private.or(lp))
3294 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
3295 self.used_crates.insert(kid);
3300 /// Invariant: This must be called only during main resolution, not during
3301 /// import resolution.
3302 fn resolve_crate_relative_path(&mut self,
3304 segments: &[hir::PathSegment],
3305 namespace: Namespace)
3306 -> Option<(Def, LastPrivate)> {
3307 let module_path = segments.split_last().unwrap().1.iter()
3308 .map(|ps| ps.identifier.name)
3309 .collect::<Vec<_>>();
3311 let root_module = self.graph_root.get_module();
3313 let containing_module;
3315 match self.resolve_module_path_from_root(root_module,
3320 LastMod(AllPublic)) {
3322 let (span, msg) = match err {
3323 Some((span, msg)) => (span, msg),
3325 let msg = format!("Use of undeclared module `::{}`",
3326 names_to_string(&module_path[..]));
3331 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3336 panic!("indeterminate unexpected");
3339 Success((resulting_module, resulting_last_private)) => {
3340 containing_module = resulting_module;
3341 last_private = resulting_last_private;
3345 let name = segments.last().unwrap().identifier.name;
3346 match self.resolve_definition_of_name_in_module(containing_module,
3349 NoNameDefinition => {
3350 // We failed to resolve the name. Report an error.
3353 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3354 return Some((def, last_private.or(lp)));
3359 fn resolve_identifier_in_local_ribs(&mut self,
3361 namespace: Namespace,
3364 // Check the local set of ribs.
3365 let search_result = match namespace {
3367 let renamed = mtwt::resolve(ident);
3368 self.search_ribs(&self.value_ribs, renamed, span)
3371 let name = ident.name;
3372 self.search_ribs(&self.type_ribs, name, span)
3376 match search_result {
3377 Some(DlDef(def)) => {
3378 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3383 Some(DlField) | Some(DlImpl(_)) | None => {
3389 fn resolve_item_by_name_in_lexical_scope(&mut self,
3391 namespace: Namespace)
3392 -> Option<(Def, LastPrivate)> {
3394 let module = self.current_module.clone();
3395 match self.resolve_item_in_lexical_scope(module,
3398 Success((target, _)) => {
3399 match (*target.bindings).def_for_namespace(namespace) {
3401 // This can happen if we were looking for a type and
3402 // found a module instead. Modules don't have defs.
3403 debug!("(resolving item path by identifier in lexical \
3404 scope) failed to resolve {} after success...",
3409 debug!("(resolving item path in lexical scope) \
3410 resolved `{}` to item",
3412 // This lookup is "all public" because it only searched
3413 // for one identifier in the current module (couldn't
3414 // have passed through reexports or anything like that.
3415 return Some((def, LastMod(AllPublic)));
3420 panic!("unexpected indeterminate result");
3423 debug!("(resolving item path by identifier in lexical scope) \
3424 failed to resolve {}", name);
3426 if let Some((span, msg)) = err {
3427 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3435 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3436 F: FnOnce(&mut Resolver) -> T,
3438 self.emit_errors = false;
3440 self.emit_errors = true;
3444 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3445 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3446 -> Option<(Path, NodeId, FallbackChecks)> {
3448 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3449 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3450 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3451 // This doesn't handle the remaining `Ty` variants as they are not
3452 // that commonly the self_type, it might be interesting to provide
3453 // support for those in future.
3458 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3459 -> Option<Rc<Module>> {
3460 let root = this.current_module.clone();
3461 let last_name = name_path.last().unwrap();
3463 if name_path.len() == 1 {
3464 match this.primitive_type_table.primitive_types.get(last_name) {
3467 match this.current_module.children.borrow().get(last_name) {
3468 Some(child) => child.get_module_if_available(),
3474 match this.resolve_module_path(root,
3479 Success((module, _)) => Some(module),
3485 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3487 let sig = match this.ast_map.get(did.node) {
3488 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3489 hir::MethodTraitItem(ref sig, _) => sig,
3492 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3493 hir::MethodImplItem(ref sig, _) => sig,
3498 sig.explicit_self.node == hir::SelfStatic
3500 csearch::is_static_method(&this.session.cstore, did)
3504 let (path, node_id, allowed) = match self.current_self_type {
3505 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3507 None => return NoSuggestion,
3509 None => return NoSuggestion,
3512 if allowed == Everything {
3513 // Look for a field with the same name in the current self_type.
3514 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3515 Some(DefTy(did, _)) |
3516 Some(DefStruct(did)) |
3517 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3520 if fields.iter().any(|&field_name| name == field_name) {
3525 _ => {} // Self type didn't resolve properly
3529 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3531 // Look for a method in the current self type's impl module.
3532 if let Some(module) = get_module(self, path.span, &name_path) {
3533 if let Some(binding) = module.children.borrow().get(&name) {
3534 if let Some(DefMethod(did)) = binding.def_for_namespace(ValueNS) {
3535 if is_static_method(self, did) {
3536 return StaticMethod(path_names_to_string(&path, 0))
3538 if self.current_trait_ref.is_some() {
3540 } else if allowed == Everything {
3547 // Look for a method in the current trait.
3548 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3549 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3550 if is_static_method(self, did) {
3551 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3561 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3562 let mut maybes: Vec<token::InternedString> = Vec::new();
3563 let mut values: Vec<usize> = Vec::new();
3565 for rib in self.value_ribs.iter().rev() {
3566 for (&k, _) in &rib.bindings {
3567 maybes.push(k.as_str());
3568 values.push(usize::MAX);
3572 let mut smallest = 0;
3573 for (i, other) in maybes.iter().enumerate() {
3574 values[i] = lev_distance(name, &other);
3576 if values[i] <= values[smallest] {
3581 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3582 // maximum edit distance we will accept for a suggestion to one third of
3583 // the typo'd name's length.
3584 let max_distance = std::cmp::max(name.len(), 3) / 3;
3586 if !values.is_empty() &&
3587 values[smallest] <= max_distance &&
3588 name != &maybes[smallest][..] {
3590 Some(maybes[smallest].to_string())
3597 fn resolve_expr(&mut self, expr: &Expr) {
3598 // First, record candidate traits for this expression if it could
3599 // result in the invocation of a method call.
3601 self.record_candidate_traits_for_expr_if_necessary(expr);
3603 // Next, resolve the node.
3605 ExprPath(ref maybe_qself, ref path) => {
3607 match self.resolve_possibly_assoc_item(expr.id,
3608 maybe_qself.as_ref(),
3612 // `<T>::a::b::c` is resolved by typeck alone.
3613 TypecheckRequired => {
3614 let method_name = path.segments.last().unwrap().identifier.name;
3615 let traits = self.get_traits_containing_item(method_name);
3616 self.trait_map.insert(expr.id, traits);
3617 visit::walk_expr(self, expr);
3620 ResolveAttempt(resolution) => resolution,
3623 // This is a local path in the value namespace. Walk through
3624 // scopes looking for it.
3625 if let Some(path_res) = resolution {
3626 // Check if struct variant
3627 if let DefVariant(_, _, true) = path_res.base_def {
3628 let path_name = path_names_to_string(path, 0);
3632 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3634 let msg = format!("did you mean to write: \
3635 `{} {{ /* fields */ }}`?",
3637 if self.emit_errors {
3638 self.session.fileline_help(expr.span, &msg);
3640 self.session.span_help(expr.span, &msg);
3643 // Write the result into the def map.
3644 debug!("(resolving expr) resolved `{}`",
3645 path_names_to_string(path, 0));
3647 // Partial resolutions will need the set of traits in scope,
3648 // so they can be completed during typeck.
3649 if path_res.depth != 0 {
3650 let method_name = path.segments.last().unwrap().identifier.name;
3651 let traits = self.get_traits_containing_item(method_name);
3652 self.trait_map.insert(expr.id, traits);
3655 self.record_def(expr.id, path_res);
3658 // Be helpful if the name refers to a struct
3659 // (The pattern matching def_tys where the id is in self.structs
3660 // matches on regular structs while excluding tuple- and enum-like
3661 // structs, which wouldn't result in this error.)
3662 let path_name = path_names_to_string(path, 0);
3663 let type_res = self.with_no_errors(|this| {
3664 this.resolve_path(expr.id, path, 0, TypeNS, false)
3666 match type_res.map(|r| r.base_def) {
3667 Some(DefTy(struct_id, _))
3668 if self.structs.contains_key(&struct_id) => {
3672 ResolutionError::StructVariantUsedAsFunction(
3676 let msg = format!("did you mean to write: \
3677 `{} {{ /* fields */ }}`?",
3679 if self.emit_errors {
3680 self.session.fileline_help(expr.span, &msg);
3682 self.session.span_help(expr.span, &msg);
3686 // Keep reporting some errors even if they're ignored above.
3687 self.resolve_path(expr.id, path, 0, ValueNS, true);
3689 let mut method_scope = false;
3690 self.value_ribs.iter().rev().all(|rib| {
3691 method_scope = match rib.kind {
3692 MethodRibKind => true,
3693 ItemRibKind | ConstantItemRibKind => false,
3694 _ => return true, // Keep advancing
3696 false // Stop advancing
3699 if method_scope && special_names::self_ == path_name {
3703 ResolutionError::SelfNotAvailableInStaticMethod
3706 let last_name = path.segments.last().unwrap().identifier.name;
3707 let mut msg = match self.find_fallback_in_self_type(last_name) {
3709 // limit search to 5 to reduce the number
3710 // of stupid suggestions
3711 self.find_best_match_for_name(&path_name)
3712 .map_or("".to_string(),
3713 |x| format!("`{}`", x))
3715 Field => format!("`self.{}`", path_name),
3718 format!("to call `self.{}`", path_name),
3719 TraitMethod(path_str) |
3720 StaticMethod(path_str) =>
3721 format!("to call `{}::{}`", path_str, path_name)
3724 if !msg.is_empty() {
3725 msg = format!(". Did you mean {}?", msg)
3730 ResolutionError::UnresolvedName(&*path_name,
3737 visit::walk_expr(self, expr);
3740 ExprStruct(ref path, _, _) => {
3741 // Resolve the path to the structure it goes to. We don't
3742 // check to ensure that the path is actually a structure; that
3743 // is checked later during typeck.
3744 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3745 Some(definition) => self.record_def(expr.id, definition),
3747 debug!("(resolving expression) didn't find struct def",);
3751 ResolutionError::DoesNotNameAStruct(
3752 &*path_names_to_string(path, 0))
3757 visit::walk_expr(self, expr);
3760 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3761 self.with_label_rib(|this| {
3762 let def_like = DlDef(DefLabel(expr.id));
3765 let rib = this.label_ribs.last_mut().unwrap();
3766 let renamed = mtwt::resolve(label);
3767 rib.bindings.insert(renamed, def_like);
3770 visit::walk_expr(this, expr);
3774 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3775 let renamed = mtwt::resolve(label.node);
3776 match self.search_label(renamed) {
3780 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3782 Some(DlDef(def @ DefLabel(_))) => {
3783 // Since this def is a label, it is never read.
3784 self.record_def(expr.id, PathResolution {
3786 last_private: LastMod(AllPublic),
3791 self.session.span_bug(expr.span,
3792 "label wasn't mapped to a \
3799 visit::walk_expr(self, expr);
3804 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3806 ExprField(_, ident) => {
3807 // FIXME(#6890): Even though you can't treat a method like a
3808 // field, we need to add any trait methods we find that match
3809 // the field name so that we can do some nice error reporting
3810 // later on in typeck.
3811 let traits = self.get_traits_containing_item(ident.node.name);
3812 self.trait_map.insert(expr.id, traits);
3814 ExprMethodCall(ident, _, _) => {
3815 debug!("(recording candidate traits for expr) recording \
3818 let traits = self.get_traits_containing_item(ident.node.name);
3819 self.trait_map.insert(expr.id, traits);
3827 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3828 debug!("(getting traits containing item) looking for '{}'",
3831 fn add_trait_info(found_traits: &mut Vec<DefId>,
3832 trait_def_id: DefId,
3834 debug!("(adding trait info) found trait {}:{} for method '{}'",
3838 found_traits.push(trait_def_id);
3841 let mut found_traits = Vec::new();
3842 let mut search_module = self.current_module.clone();
3844 // Look for the current trait.
3845 match self.current_trait_ref {
3846 Some((trait_def_id, _)) => {
3847 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3848 add_trait_info(&mut found_traits, trait_def_id, name);
3851 None => {} // Nothing to do.
3854 // Look for trait children.
3855 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3858 for (_, child_names) in search_module.children.borrow().iter() {
3859 let def = match child_names.def_for_namespace(TypeNS) {
3863 let trait_def_id = match def {
3864 DefTrait(trait_def_id) => trait_def_id,
3867 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3868 add_trait_info(&mut found_traits, trait_def_id, name);
3873 // Look for imports.
3874 for (_, import) in search_module.import_resolutions.borrow().iter() {
3875 let target = match import.target_for_namespace(TypeNS) {
3877 Some(target) => target,
3879 let did = match target.bindings.def_for_namespace(TypeNS) {
3880 Some(DefTrait(trait_def_id)) => trait_def_id,
3881 Some(..) | None => continue,
3883 if self.trait_item_map.contains_key(&(name, did)) {
3884 add_trait_info(&mut found_traits, did, name);
3885 let id = import.type_id;
3886 self.used_imports.insert((id, TypeNS));
3887 let trait_name = self.get_trait_name(did);
3888 self.record_import_use(id, trait_name);
3889 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3890 self.used_crates.insert(kid);
3895 match search_module.parent_link.clone() {
3896 NoParentLink | ModuleParentLink(..) => break,
3897 BlockParentLink(parent_module, _) => {
3898 search_module = parent_module.upgrade().unwrap();
3906 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3907 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3908 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3909 "Import should only be used for `use` directives");
3911 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3912 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3913 self.session.span_bug(span, &format!("path resolved multiple times \
3914 ({:?} before, {:?} now)",
3915 prev_res, resolution));
3919 fn enforce_default_binding_mode(&mut self,
3921 pat_binding_mode: BindingMode,
3923 match pat_binding_mode {
3924 BindByValue(_) => {}
3928 ResolutionError::CannotUseRefBindingModeWith(descr));
3936 // Diagnostics are not particularly efficient, because they're rarely
3940 #[allow(dead_code)] // useful for debugging
3941 fn dump_module(&mut self, module_: Rc<Module>) {
3942 debug!("Dump of module `{}`:", module_to_string(&*module_));
3944 debug!("Children:");
3945 build_reduced_graph::populate_module_if_necessary(self, &module_);
3946 for (&name, _) in module_.children.borrow().iter() {
3947 debug!("* {}", name);
3950 debug!("Import resolutions:");
3951 let import_resolutions = module_.import_resolutions.borrow();
3952 for (&name, import_resolution) in import_resolutions.iter() {
3954 match import_resolution.target_for_namespace(ValueNS) {
3955 None => { value_repr = "".to_string(); }
3957 value_repr = " value:?".to_string();
3963 match import_resolution.target_for_namespace(TypeNS) {
3964 None => { type_repr = "".to_string(); }
3966 type_repr = " type:?".to_string();
3971 debug!("* {}:{}{}", name, value_repr, type_repr);
3977 fn names_to_string(names: &[Name]) -> String {
3978 let mut first = true;
3979 let mut result = String::new();
3984 result.push_str("::")
3986 result.push_str(&name.as_str());
3991 fn path_names_to_string(path: &Path, depth: usize) -> String {
3992 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3994 .map(|seg| seg.identifier.name)
3996 names_to_string(&names[..])
3999 /// A somewhat inefficient routine to obtain the name of a module.
4000 fn module_to_string(module: &Module) -> String {
4001 let mut names = Vec::new();
4003 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4004 match module.parent_link {
4006 ModuleParentLink(ref module, name) => {
4008 collect_mod(names, &*module.upgrade().unwrap());
4010 BlockParentLink(ref module, _) => {
4011 // danger, shouldn't be ident?
4012 names.push(special_idents::opaque.name);
4013 collect_mod(names, &*module.upgrade().unwrap());
4017 collect_mod(&mut names, module);
4019 if names.is_empty() {
4020 return "???".to_string();
4022 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
4026 pub struct CrateMap {
4027 pub def_map: DefMap,
4028 pub freevars: RefCell<FreevarMap>,
4029 pub export_map: ExportMap,
4030 pub trait_map: TraitMap,
4031 pub external_exports: ExternalExports,
4032 pub glob_map: Option<GlobMap>
4035 #[derive(PartialEq,Copy, Clone)]
4036 pub enum MakeGlobMap {
4041 /// Entry point to crate resolution.
4042 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4043 ast_map: &'a hir_map::Map<'tcx>,
4044 make_glob_map: MakeGlobMap)
4046 let krate = ast_map.krate();
4047 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
4049 resolver.resolve_crate(krate);
4050 session.abort_if_errors();
4052 check_unused::check_crate(&mut resolver, krate);
4055 def_map: resolver.def_map,
4056 freevars: resolver.freevars,
4057 export_map: resolver.export_map,
4058 trait_map: resolver.trait_map,
4059 external_exports: resolver.external_exports,
4060 glob_map: if resolver.make_glob_map {
4061 Some(resolver.glob_map)
4068 /// Builds a name resolution walker to be used within this module,
4069 /// or used externally, with an optional callback function.
4071 /// The callback takes a &mut bool which allows callbacks to end a
4072 /// walk when set to true, passing through the rest of the walk, while
4073 /// preserving the ribs + current module. This allows resolve_path
4074 /// calls to be made with the correct scope info. The node in the
4075 /// callback corresponds to the current node in the walk.
4076 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
4077 ast_map: &'a hir_map::Map<'tcx>,
4079 make_glob_map: MakeGlobMap,
4080 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
4081 -> Resolver<'a, 'tcx> {
4082 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4084 resolver.callback = callback;
4086 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4087 session.abort_if_errors();
4089 resolve_imports::resolve_imports(&mut resolver);
4090 session.abort_if_errors();
4092 record_exports::record(&mut resolver);
4093 session.abort_if_errors();
4098 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }