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;
36 use self::PatternBindingMode::*;
37 use self::Namespace::*;
38 use self::NamespaceResult::*;
39 use self::NameDefinition::*;
40 use self::ResolveResult::*;
41 use self::FallbackSuggestion::*;
42 use self::TypeParameters::*;
44 use self::UseLexicalScopeFlag::*;
45 use self::ModulePrefixResult::*;
46 use self::AssocItemResolveResult::*;
47 use self::NameSearchType::*;
48 use self::BareIdentifierPatternResolution::*;
49 use self::ParentLink::*;
50 use self::ModuleKind::*;
51 use self::FallbackChecks::*;
54 use rustc::session::Session;
56 use rustc::metadata::csearch;
57 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
58 use rustc::middle::def::*;
59 use rustc::middle::pat_util::pat_bindings;
60 use rustc::middle::privacy::*;
61 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
62 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
63 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
64 use rustc::util::lev_distance::lev_distance;
66 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block};
67 use syntax::ast::{ConstImplItem, Crate, CrateNum};
68 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
69 use syntax::ast::{ExprLoop, ExprWhile, ExprMethodCall};
70 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
71 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
72 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
73 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
74 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
75 use syntax::ast::{Local, MethodImplItem, Name, NodeId};
76 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
77 use syntax::ast::{PatRange, PatStruct, Path, PrimTy};
78 use syntax::ast::{TraitRef, Ty, TyBool, TyChar, TyF32};
79 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt};
80 use syntax::ast::{TyPath, TyPtr};
81 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
82 use syntax::ast::TypeImplItem;
84 use syntax::ast_util::{local_def, walk_pat};
85 use syntax::attr::AttrMetaMethods;
86 use syntax::ext::mtwt;
87 use syntax::parse::token::{self, special_names, special_idents};
89 use syntax::codemap::{self, Span, Pos};
90 use syntax::visit::{self, Visitor};
92 use std::collections::{HashMap, HashSet};
93 use std::collections::hash_map::Entry::{Occupied, Vacant};
94 use std::cell::{Cell, RefCell};
96 use std::mem::replace;
97 use std::rc::{Rc, Weak};
100 use resolve_imports::{Target, ImportDirective, ImportResolution};
101 use resolve_imports::Shadowable;
103 // NB: This module needs to be declared first so diagnostics are
104 // registered before they are used.
109 mod build_reduced_graph;
112 // Perform the callback, not walking deeper if the return is true
113 macro_rules! execute_callback {
114 ($node: expr, $walker: expr) => (
115 if let Some(ref callback) = $walker.callback {
116 if callback($node, &mut $walker.resolved) {
123 pub enum ResolutionError<'a> {
124 /// error E0401: can't use type parameters from outer function
125 TypeParametersFromOuterFunction,
126 /// error E0402: cannot use an outer type parameter in this context
127 OuterTypeParameterContext,
128 /// error E0403: the name is already used for a type parameter in this type parameter list
129 NameAlreadyUsedInTypeParameterList(Name),
130 /// error E0404: is not a trait
131 IsNotATrait(&'a str),
132 /// error E0405: use of undeclared trait name
133 UndeclaredTraitName(&'a str),
134 /// error E0406: undeclared associated type
135 UndeclaredAssociatedType,
136 /// error E0407: method is not a member of trait
137 MethodNotMemberOfTrait(Name, &'a str),
138 /// error E0437: type is not a member of trait
139 TypeNotMemberOfTrait(Name, &'a str),
140 /// error E0438: const is not a member of trait
141 ConstNotMemberOfTrait(Name, &'a str),
142 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
143 VariableNotBoundInPattern(Name, usize),
144 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
145 VariableBoundWithDifferentMode(Name, usize),
146 /// error E0410: variable from pattern is not bound in pattern #1
147 VariableNotBoundInParentPattern(Name, usize),
148 /// error E0411: use of `Self` outside of an impl or trait
149 SelfUsedOutsideImplOrTrait,
150 /// error E0412: use of undeclared
151 UseOfUndeclared(&'a str, &'a str),
152 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
153 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
154 /// error E0414: only irrefutable patterns allowed here
155 OnlyIrrefutablePatternsAllowedHere,
156 /// error E0415: identifier is bound more than once in this parameter list
157 IdentifierBoundMoreThanOnceInParameterList(&'a str),
158 /// error E0416: identifier is bound more than once in the same pattern
159 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
160 /// error E0417: static variables cannot be referenced in a pattern
161 StaticVariableReference,
162 /// error E0418: is not an enum variant, struct or const
163 NotAnEnumVariantStructOrConst(&'a str),
164 /// error E0419: unresolved enum variant, struct or const
165 UnresolvedEnumVariantStructOrConst(&'a str),
166 /// error E0420: is not an associated const
167 NotAnAssociatedConst(&'a str),
168 /// error E0421: unresolved associated const
169 UnresolvedAssociatedConst(&'a str),
170 /// error E0422: does not name a struct
171 DoesNotNameAStruct(&'a str),
172 /// error E0423: is a struct variant name, but this expression uses it like a function name
173 StructVariantUsedAsFunction(&'a str),
174 /// error E0424: `self` is not available in a static method
175 SelfNotAvailableInStaticMethod,
176 /// error E0425: unresolved name
177 UnresolvedName(&'a str, &'a str),
178 /// error E0426: use of undeclared label
179 UndeclaredLabel(&'a str),
180 /// error E0427: cannot use `ref` binding mode with ...
181 CannotUseRefBindingModeWith(&'a str),
182 /// error E0428: duplicate definition
183 DuplicateDefinition(&'a str, Name),
184 /// error E0429: `self` imports are only allowed within a { } list
185 SelfImportsOnlyAllowedWithin,
186 /// error E0430: `self` import can only appear once in the list
187 SelfImportCanOnlyAppearOnceInTheList,
188 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
189 SelfImportOnlyInImportListWithNonEmptyPrefix,
190 /// error E0432: unresolved import
191 UnresolvedImport(Option<(&'a str, &'a str)>),
192 /// error E0433: failed to resolve
193 FailedToResolve(&'a str),
194 /// error E0434: can't capture dynamic environment in a fn item
195 CannotCaptureDynamicEnvironmentInFnItem,
196 /// error E0435: attempt to use a non-constant value in a constant
197 AttemptToUseNonConstantValueInConstant,
200 fn resolve_error<'b, 'a:'b, 'tcx:'a>(resolver: &'b Resolver<'a, 'tcx>, span: syntax::codemap::Span,
201 resolution_error: ResolutionError<'b>) {
202 if !resolver.emit_errors {
205 match resolution_error {
206 ResolutionError::TypeParametersFromOuterFunction => {
207 span_err!(resolver.session, span, E0401, "can't use type parameters from \
208 outer function; try using a local \
209 type parameter instead");
211 ResolutionError::OuterTypeParameterContext => {
212 span_err!(resolver.session, span, E0402,
213 "cannot use an outer type parameter in this context");
215 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
216 span_err!(resolver.session, span, E0403,
217 "the name `{}` is already used for a type \
218 parameter in this type parameter list", name);
220 ResolutionError::IsNotATrait(name) => {
221 span_err!(resolver.session, span, E0404,
222 "`{}` is not a trait",
225 ResolutionError::UndeclaredTraitName(name) => {
226 span_err!(resolver.session, span, E0405,
227 "use of undeclared trait name `{}`",
230 ResolutionError::UndeclaredAssociatedType => {
231 span_err!(resolver.session, span, E0406, "undeclared associated type");
233 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
234 span_err!(resolver.session, span, E0407,
235 "method `{}` is not a member of trait `{}`",
239 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
240 span_err!(resolver.session, span, E0437,
241 "type `{}` is not a member of trait `{}`",
245 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
246 span_err!(resolver.session, span, E0438,
247 "const `{}` is not a member of trait `{}`",
251 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
252 span_err!(resolver.session, span, E0408,
253 "variable `{}` from pattern #1 is not bound in pattern #{}",
257 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
258 span_err!(resolver.session, span, E0409,
259 "variable `{}` is bound with different \
260 mode in pattern #{} than in pattern #1",
264 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
265 span_err!(resolver.session, span, E0410,
266 "variable `{}` from pattern #{} is not bound in pattern #1",
270 ResolutionError::SelfUsedOutsideImplOrTrait => {
271 span_err!(resolver.session, span, E0411, "use of `Self` outside of an impl or trait");
273 ResolutionError::UseOfUndeclared(kind, name) => {
274 span_err!(resolver.session, span, E0412,
275 "use of undeclared {} `{}`",
279 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
280 span_err!(resolver.session, span, E0413,
281 "declaration of `{}` shadows an enum variant or unit-like struct in \
285 ResolutionError::OnlyIrrefutablePatternsAllowedHere => {
286 span_err!(resolver.session, span, E0414, "only irrefutable patterns allowed here");
288 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
289 span_err!(resolver.session, span, E0415,
290 "identifier `{}` is bound more than once in this parameter list",
293 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
294 span_err!(resolver.session, span, E0416,
295 "identifier `{}` is bound more than once in the same pattern",
298 ResolutionError::StaticVariableReference => {
299 span_err!(resolver.session, span, E0417, "static variables cannot be \
300 referenced in a pattern, \
301 use a `const` instead");
303 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
304 span_err!(resolver.session, span, E0418,
305 "`{}` is not an enum variant, struct or const",
308 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
309 span_err!(resolver.session, span, E0419,
310 "unresolved enum variant, struct or const `{}`",
313 ResolutionError::NotAnAssociatedConst(name) => {
314 span_err!(resolver.session, span, E0420,
315 "`{}` is not an associated const",
318 ResolutionError::UnresolvedAssociatedConst(name) => {
319 span_err!(resolver.session, span, E0421,
320 "unresolved associated const `{}`",
323 ResolutionError::DoesNotNameAStruct(name) => {
324 span_err!(resolver.session, span, E0422, "`{}` does not name a structure", name);
326 ResolutionError::StructVariantUsedAsFunction(path_name) => {
327 span_err!(resolver.session, span, E0423,
328 "`{}` is the name of a struct or struct variant, \
329 but this expression \
330 uses it like a function name",
333 ResolutionError::SelfNotAvailableInStaticMethod => {
334 span_err!(resolver.session, span, E0424, "`self` is not available in a static method. \
335 Maybe a `self` argument is missing?");
337 ResolutionError::UnresolvedName(path, name) => {
338 span_err!(resolver.session, span, E0425,
339 "unresolved name `{}`{}",
343 ResolutionError::UndeclaredLabel(name) => {
344 span_err!(resolver.session, span, E0426,
345 "use of undeclared label `{}`",
348 ResolutionError::CannotUseRefBindingModeWith(descr) => {
349 span_err!(resolver.session, span, E0427,
350 "cannot use `ref` binding mode with {}",
353 ResolutionError::DuplicateDefinition(namespace, name) => {
354 span_err!(resolver.session, span, E0428,
355 "duplicate definition of {} `{}`",
359 ResolutionError::SelfImportsOnlyAllowedWithin => {
360 span_err!(resolver.session, span, E0429, "{}",
361 "`self` imports are only allowed within a { } list");
363 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
364 span_err!(resolver.session, span, E0430,
365 "`self` import can only appear once in the list");
367 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
368 span_err!(resolver.session, span, E0431,
369 "`self` import can only appear in an import list with a \
372 ResolutionError::UnresolvedImport(name) => {
373 let msg = match name {
374 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
375 None => "unresolved import".to_owned()
377 span_err!(resolver.session, span, E0432, "{}", msg);
379 ResolutionError::FailedToResolve(msg) => {
380 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
382 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
383 span_err!(resolver.session, span, E0434, "{}",
384 "can't capture dynamic environment in a fn item; \
385 use the || { ... } closure form instead");
387 ResolutionError::AttemptToUseNonConstantValueInConstant =>{
388 span_err!(resolver.session, span, E0435,
389 "attempt to use a non-constant value in a constant");
394 #[derive(Copy, Clone)]
397 binding_mode: BindingMode,
400 // Map from the name in a pattern to its binding mode.
401 type BindingMap = HashMap<Name, BindingInfo>;
403 #[derive(Copy, Clone, PartialEq)]
404 enum PatternBindingMode {
406 LocalIrrefutableMode,
407 ArgumentIrrefutableMode,
410 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
416 /// A NamespaceResult represents the result of resolving an import in
417 /// a particular namespace. The result is either definitely-resolved,
418 /// definitely- unresolved, or unknown.
420 enum NamespaceResult {
421 /// Means that resolve hasn't gathered enough information yet to determine
422 /// whether the name is bound in this namespace. (That is, it hasn't
423 /// resolved all `use` directives yet.)
425 /// Means that resolve has determined that the name is definitely
426 /// not bound in the namespace.
428 /// Means that resolve has determined that the name is bound in the Module
429 /// argument, and specified by the NameBindings argument.
430 BoundResult(Rc<Module>, Rc<NameBindings>)
433 impl NamespaceResult {
434 fn is_unknown(&self) -> bool {
436 UnknownResult => true,
440 fn is_unbound(&self) -> bool {
442 UnboundResult => true,
448 enum NameDefinition {
449 // The name was unbound.
451 // The name identifies an immediate child.
452 ChildNameDefinition(Def, LastPrivate),
453 // The name identifies an import.
454 ImportNameDefinition(Def, LastPrivate),
457 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
458 fn visit_item(&mut self, item: &Item) {
459 execute_callback!(ast_map::Node::NodeItem(item), self);
460 self.resolve_item(item);
462 fn visit_arm(&mut self, arm: &Arm) {
463 self.resolve_arm(arm);
465 fn visit_block(&mut self, block: &Block) {
466 execute_callback!(ast_map::Node::NodeBlock(block), self);
467 self.resolve_block(block);
469 fn visit_expr(&mut self, expr: &Expr) {
470 execute_callback!(ast_map::Node::NodeExpr(expr), self);
471 self.resolve_expr(expr);
473 fn visit_local(&mut self, local: &Local) {
474 execute_callback!(ast_map::Node::NodeLocal(&*local.pat), self);
475 self.resolve_local(local);
477 fn visit_ty(&mut self, ty: &Ty) {
478 self.resolve_type(ty);
480 fn visit_generics(&mut self, generics: &Generics) {
481 self.resolve_generics(generics);
483 fn visit_poly_trait_ref(&mut self,
484 tref: &ast::PolyTraitRef,
485 m: &ast::TraitBoundModifier) {
486 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
487 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
488 Err(_) => { /* error already reported */ }
490 visit::walk_poly_trait_ref(self, tref, m);
492 fn visit_variant(&mut self, variant: &ast::Variant, generics: &Generics) {
493 execute_callback!(ast_map::Node::NodeVariant(variant), self);
494 if let Some(ref dis_expr) = variant.node.disr_expr {
495 // resolve the discriminator expr as a constant
496 self.with_constant_rib(|this| {
497 this.visit_expr(&**dis_expr);
501 // `visit::walk_variant` without the discriminant expression.
502 match variant.node.kind {
503 ast::TupleVariantKind(ref variant_arguments) => {
504 for variant_argument in variant_arguments {
505 self.visit_ty(&*variant_argument.ty);
508 ast::StructVariantKind(ref struct_definition) => {
509 self.visit_struct_def(&**struct_definition,
516 fn visit_foreign_item(&mut self, foreign_item: &ast::ForeignItem) {
517 execute_callback!(ast_map::Node::NodeForeignItem(foreign_item), self);
518 let type_parameters = match foreign_item.node {
519 ForeignItemFn(_, ref generics) => {
520 HasTypeParameters(generics, FnSpace, ItemRibKind)
522 ForeignItemStatic(..) => NoTypeParameters
524 self.with_type_parameter_rib(type_parameters, |this| {
525 visit::walk_foreign_item(this, foreign_item);
528 fn visit_fn(&mut self,
529 function_kind: visit::FnKind<'v>,
530 declaration: &'v FnDecl,
534 let rib_kind = match function_kind {
535 visit::FkItemFn(_, generics, _, _, _, _) => {
536 self.visit_generics(generics);
539 visit::FkMethod(_, sig, _) => {
540 self.visit_generics(&sig.generics);
541 self.visit_explicit_self(&sig.explicit_self);
544 visit::FkFnBlock(..) => ClosureRibKind(node_id)
546 self.resolve_function(rib_kind, declaration, block);
550 type ErrorMessage = Option<(Span, String)>;
552 enum ResolveResult<T> {
553 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
554 Indeterminate, // Couldn't determine due to unresolved globs.
555 Success(T) // Successfully resolved the import.
558 impl<T> ResolveResult<T> {
559 fn success(&self) -> bool {
560 match *self { Success(_) => true, _ => false }
564 enum FallbackSuggestion {
569 StaticMethod(String),
573 #[derive(Copy, Clone)]
574 enum TypeParameters<'a> {
580 // Identifies the things that these parameters
581 // were declared on (type, fn, etc)
584 // The kind of the rib used for type parameters.
588 // The rib kind controls the translation of local
589 // definitions (`DefLocal`) to upvars (`DefUpvar`).
590 #[derive(Copy, Clone, Debug)]
592 // No translation needs to be applied.
595 // We passed through a closure scope at the given node ID.
596 // Translate upvars as appropriate.
597 ClosureRibKind(NodeId /* func id */),
599 // We passed through an impl or trait and are now in one of its
600 // methods. Allow references to ty params that impl or trait
601 // binds. Disallow any other upvars (including other ty params that are
605 // We passed through an item scope. Disallow upvars.
608 // We're in a constant item. Can't refer to dynamic stuff.
612 #[derive(Copy, Clone)]
613 enum UseLexicalScopeFlag {
618 enum ModulePrefixResult {
620 PrefixFound(Rc<Module>, usize)
623 #[derive(Copy, Clone)]
624 enum AssocItemResolveResult {
625 /// Syntax such as `<T>::item`, which can't be resolved until type
628 /// We should have been able to resolve the associated item.
629 ResolveAttempt(Option<PathResolution>),
632 #[derive(Copy, Clone, PartialEq)]
633 enum NameSearchType {
634 /// We're doing a name search in order to resolve a `use` directive.
637 /// We're doing a name search in order to resolve a path type, a path
638 /// expression, or a path pattern.
642 #[derive(Copy, Clone)]
643 enum BareIdentifierPatternResolution {
644 FoundStructOrEnumVariant(Def, LastPrivate),
645 FoundConst(Def, LastPrivate),
646 BareIdentifierPatternUnresolved
652 bindings: HashMap<Name, DefLike>,
657 fn new(kind: RibKind) -> Rib {
659 bindings: HashMap::new(),
665 /// The link from a module up to its nearest parent node.
666 #[derive(Clone,Debug)]
669 ModuleParentLink(Weak<Module>, Name),
670 BlockParentLink(Weak<Module>, NodeId)
673 /// The type of module this is.
674 #[derive(Copy, Clone, PartialEq, Debug)]
683 /// One node in the tree of modules.
685 parent_link: ParentLink,
686 def_id: Cell<Option<DefId>>,
687 kind: Cell<ModuleKind>,
690 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
691 imports: RefCell<Vec<ImportDirective>>,
693 // The external module children of this node that were declared with
695 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
697 // The anonymous children of this node. Anonymous children are pseudo-
698 // modules that are implicitly created around items contained within
701 // For example, if we have this:
709 // There will be an anonymous module created around `g` with the ID of the
710 // entry block for `f`.
711 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
713 // The status of resolving each import in this module.
714 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
716 // The number of unresolved globs that this module exports.
717 glob_count: Cell<usize>,
719 // The number of unresolved pub imports (both regular and globs) in this module
720 pub_count: Cell<usize>,
722 // The number of unresolved pub glob imports in this module
723 pub_glob_count: Cell<usize>,
725 // The index of the import we're resolving.
726 resolved_import_count: Cell<usize>,
728 // Whether this module is populated. If not populated, any attempt to
729 // access the children must be preceded with a
730 // `populate_module_if_necessary` call.
731 populated: Cell<bool>,
735 fn new(parent_link: ParentLink,
736 def_id: Option<DefId>,
742 parent_link: parent_link,
743 def_id: Cell::new(def_id),
744 kind: Cell::new(kind),
745 is_public: is_public,
746 children: RefCell::new(HashMap::new()),
747 imports: RefCell::new(Vec::new()),
748 external_module_children: RefCell::new(HashMap::new()),
749 anonymous_children: RefCell::new(NodeMap()),
750 import_resolutions: RefCell::new(HashMap::new()),
751 glob_count: Cell::new(0),
752 pub_count: Cell::new(0),
753 pub_glob_count: Cell::new(0),
754 resolved_import_count: Cell::new(0),
755 populated: Cell::new(!external),
759 fn all_imports_resolved(&self) -> bool {
760 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
761 // it is currently being resolved ! so nope
764 self.imports.borrow().len() == self.resolved_import_count.get()
770 pub fn inc_glob_count(&self) {
771 self.glob_count.set(self.glob_count.get() + 1);
773 pub fn dec_glob_count(&self) {
774 assert!(self.glob_count.get() > 0);
775 self.glob_count.set(self.glob_count.get() - 1);
777 pub fn inc_pub_count(&self) {
778 self.pub_count.set(self.pub_count.get() + 1);
780 pub fn dec_pub_count(&self) {
781 assert!(self.pub_count.get() > 0);
782 self.pub_count.set(self.pub_count.get() - 1);
784 pub fn inc_pub_glob_count(&self) {
785 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
787 pub fn dec_pub_glob_count(&self) {
788 assert!(self.pub_glob_count.get() > 0);
789 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
793 impl fmt::Debug for Module {
794 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
795 write!(f, "{:?}, kind: {:?}, {}",
798 if self.is_public { "public" } else { "private" } )
804 flags DefModifiers: u8 {
805 const PUBLIC = 1 << 0,
806 const IMPORTABLE = 1 << 1,
810 // Records a possibly-private type definition.
811 #[derive(Clone,Debug)]
813 modifiers: DefModifiers, // see note in ImportResolution about how to use this
814 module_def: Option<Rc<Module>>,
815 type_def: Option<Def>,
816 type_span: Option<Span>
819 // Records a possibly-private value definition.
820 #[derive(Clone, Copy, Debug)]
822 modifiers: DefModifiers, // see note in ImportResolution about how to use this
824 value_span: Option<Span>,
827 // Records the definitions (at most one for each namespace) that a name is
830 pub struct NameBindings {
831 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
832 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
836 fn new() -> NameBindings {
838 type_def: RefCell::new(None),
839 value_def: RefCell::new(None),
843 /// Creates a new module in this set of name bindings.
844 fn define_module(&self,
845 parent_link: ParentLink,
846 def_id: Option<DefId>,
851 // Merges the module with the existing type def or creates a new one.
852 let modifiers = if is_public {
855 DefModifiers::empty()
856 } | DefModifiers::IMPORTABLE;
857 let module_ = Rc::new(Module::new(parent_link,
862 let type_def = self.type_def.borrow().clone();
865 *self.type_def.borrow_mut() = Some(TypeNsDef {
866 modifiers: modifiers,
867 module_def: Some(module_),
873 *self.type_def.borrow_mut() = Some(TypeNsDef {
874 modifiers: modifiers,
875 module_def: Some(module_),
877 type_def: type_def.type_def
883 /// Sets the kind of the module, creating a new one if necessary.
884 fn set_module_kind(&self,
885 parent_link: ParentLink,
886 def_id: Option<DefId>,
891 let modifiers = if is_public {
894 DefModifiers::empty()
895 } | DefModifiers::IMPORTABLE;
896 let type_def = self.type_def.borrow().clone();
899 let module = Module::new(parent_link,
904 *self.type_def.borrow_mut() = Some(TypeNsDef {
905 modifiers: modifiers,
906 module_def: Some(Rc::new(module)),
912 match type_def.module_def {
914 let module = Module::new(parent_link,
919 *self.type_def.borrow_mut() = Some(TypeNsDef {
920 modifiers: modifiers,
921 module_def: Some(Rc::new(module)),
922 type_def: type_def.type_def,
926 Some(module_def) => module_def.kind.set(kind),
932 /// Records a type definition.
933 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
934 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
935 // Merges the type with the existing type def or creates a new one.
936 let type_def = self.type_def.borrow().clone();
939 *self.type_def.borrow_mut() = Some(TypeNsDef {
943 modifiers: modifiers,
947 *self.type_def.borrow_mut() = Some(TypeNsDef {
948 module_def: type_def.module_def,
951 modifiers: modifiers,
957 /// Records a value definition.
958 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
959 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
960 *self.value_def.borrow_mut() = Some(ValueNsDef {
962 value_span: Some(sp),
963 modifiers: modifiers,
967 /// Returns the module node if applicable.
968 fn get_module_if_available(&self) -> Option<Rc<Module>> {
969 match *self.type_def.borrow() {
970 Some(ref type_def) => type_def.module_def.clone(),
975 /// Returns the module node. Panics if this node does not have a module
977 fn get_module(&self) -> Rc<Module> {
978 match self.get_module_if_available() {
980 panic!("get_module called on a node with no module \
983 Some(module_def) => module_def
987 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
989 TypeNS => return self.type_def.borrow().is_some(),
990 ValueNS => return self.value_def.borrow().is_some()
994 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
995 self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
998 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
1000 TypeNS => match *self.type_def.borrow() {
1001 Some(ref def) => def.modifiers.contains(modifiers), None => false
1003 ValueNS => match *self.value_def.borrow() {
1004 Some(ref def) => def.modifiers.contains(modifiers), None => false
1009 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
1012 match *self.type_def.borrow() {
1014 Some(ref type_def) => {
1015 match type_def.type_def {
1016 Some(type_def) => Some(type_def),
1018 match type_def.module_def {
1019 Some(ref module) => {
1020 match module.def_id.get() {
1021 Some(did) => Some(DefMod(did)),
1033 match *self.value_def.borrow() {
1035 Some(value_def) => Some(value_def.def)
1041 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
1042 if self.defined_in_namespace(namespace) {
1045 match *self.type_def.borrow() {
1047 Some(ref type_def) => type_def.type_span
1051 match *self.value_def.borrow() {
1053 Some(ref value_def) => value_def.value_span
1062 fn is_public(&self, namespace: Namespace) -> bool {
1065 let type_def = self.type_def.borrow();
1066 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
1069 let value_def = self.value_def.borrow();
1070 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
1076 /// Interns the names of the primitive types.
1077 struct PrimitiveTypeTable {
1078 primitive_types: HashMap<Name, PrimTy>,
1081 impl PrimitiveTypeTable {
1082 fn new() -> PrimitiveTypeTable {
1083 let mut table = PrimitiveTypeTable {
1084 primitive_types: HashMap::new()
1087 table.intern("bool", TyBool);
1088 table.intern("char", TyChar);
1089 table.intern("f32", TyFloat(TyF32));
1090 table.intern("f64", TyFloat(TyF64));
1091 table.intern("isize", TyInt(TyIs));
1092 table.intern("i8", TyInt(TyI8));
1093 table.intern("i16", TyInt(TyI16));
1094 table.intern("i32", TyInt(TyI32));
1095 table.intern("i64", TyInt(TyI64));
1096 table.intern("str", TyStr);
1097 table.intern("usize", TyUint(TyUs));
1098 table.intern("u8", TyUint(TyU8));
1099 table.intern("u16", TyUint(TyU16));
1100 table.intern("u32", TyUint(TyU32));
1101 table.intern("u64", TyUint(TyU64));
1106 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1107 self.primitive_types.insert(token::intern(string), primitive_type);
1111 /// The main resolver class.
1112 pub struct Resolver<'a, 'tcx:'a> {
1113 session: &'a Session,
1115 ast_map: &'a ast_map::Map<'tcx>,
1117 graph_root: NameBindings,
1119 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1121 structs: FnvHashMap<DefId, Vec<Name>>,
1123 // The number of imports that are currently unresolved.
1124 unresolved_imports: usize,
1126 // The module that represents the current item scope.
1127 current_module: Rc<Module>,
1129 // The current set of local scopes, for values.
1130 // FIXME #4948: Reuse ribs to avoid allocation.
1131 value_ribs: Vec<Rib>,
1133 // The current set of local scopes, for types.
1134 type_ribs: Vec<Rib>,
1136 // The current set of local scopes, for labels.
1137 label_ribs: Vec<Rib>,
1139 // The trait that the current context can refer to.
1140 current_trait_ref: Option<(DefId, TraitRef)>,
1142 // The current self type if inside an impl (used for better errors).
1143 current_self_type: Option<Ty>,
1145 // The idents for the primitive types.
1146 primitive_type_table: PrimitiveTypeTable,
1149 freevars: RefCell<FreevarMap>,
1150 freevars_seen: RefCell<NodeMap<NodeSet>>,
1151 export_map: ExportMap,
1152 trait_map: TraitMap,
1153 external_exports: ExternalExports,
1155 // Whether or not to print error messages. Can be set to true
1156 // when getting additional info for error message suggestions,
1157 // so as to avoid printing duplicate errors
1160 make_glob_map: bool,
1161 // Maps imports to the names of items actually imported (this actually maps
1162 // all imports, but only glob imports are actually interesting).
1165 used_imports: HashSet<(NodeId, Namespace)>,
1166 used_crates: HashSet<CrateNum>,
1168 // Callback function for intercepting walks
1169 callback: Option<Box<Fn(ast_map::Node, &mut bool) -> bool>>,
1170 // The intention is that the callback modifies this flag.
1171 // Once set, the resolver falls out of the walk, preserving the ribs.
1176 #[derive(PartialEq)]
1177 enum FallbackChecks {
1182 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1183 fn new(session: &'a Session,
1184 ast_map: &'a ast_map::Map<'tcx>,
1186 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
1187 let graph_root = NameBindings::new();
1189 graph_root.define_module(NoParentLink,
1190 Some(DefId { krate: 0, node: 0 }),
1196 let current_module = graph_root.get_module();
1203 // The outermost module has def ID 0; this is not reflected in the
1206 graph_root: graph_root,
1208 trait_item_map: FnvHashMap(),
1209 structs: FnvHashMap(),
1211 unresolved_imports: 0,
1213 current_module: current_module,
1214 value_ribs: Vec::new(),
1215 type_ribs: Vec::new(),
1216 label_ribs: Vec::new(),
1218 current_trait_ref: None,
1219 current_self_type: None,
1221 primitive_type_table: PrimitiveTypeTable::new(),
1223 def_map: RefCell::new(NodeMap()),
1224 freevars: RefCell::new(NodeMap()),
1225 freevars_seen: RefCell::new(NodeMap()),
1226 export_map: NodeMap(),
1227 trait_map: NodeMap(),
1228 used_imports: HashSet::new(),
1229 used_crates: HashSet::new(),
1230 external_exports: DefIdSet(),
1233 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1234 glob_map: HashMap::new(),
1243 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1244 if !self.make_glob_map {
1247 if self.glob_map.contains_key(&import_id) {
1248 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1252 let mut new_set = HashSet::new();
1253 new_set.insert(name);
1254 self.glob_map.insert(import_id, new_set);
1257 fn get_trait_name(&self, did: DefId) -> Name {
1258 if did.krate == ast::LOCAL_CRATE {
1259 self.ast_map.expect_item(did.node).ident.name
1261 csearch::get_trait_name(&self.session.cstore, did)
1265 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1267 type_def: RefCell::new(Some(TypeNsDef {
1268 modifiers: DefModifiers::IMPORTABLE,
1269 module_def: Some(module),
1273 value_def: RefCell::new(None),
1277 /// Checks that the names of external crates don't collide with other
1278 /// external crates.
1279 fn check_for_conflicts_between_external_crates(&self,
1283 if module.external_module_children.borrow().contains_key(&name) {
1284 span_err!(self.session, span, E0259,
1285 "an external crate named `{}` has already \
1286 been imported into this module",
1291 /// Checks that the names of items don't collide with external crates.
1292 fn check_for_conflicts_between_external_crates_and_items(&self,
1296 if module.external_module_children.borrow().contains_key(&name) {
1297 span_err!(self.session, span, E0260,
1298 "the name `{}` conflicts with an external \
1299 crate that has been imported into this \
1305 /// Resolves the given module path from the given root `module_`.
1306 fn resolve_module_path_from_root(&mut self,
1307 module_: Rc<Module>,
1308 module_path: &[Name],
1311 name_search_type: NameSearchType,
1313 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1314 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1315 -> Option<Rc<Module>> {
1316 match module.external_module_children.borrow().get(&needle) {
1317 Some(_) => Some(module.clone()),
1318 None => match module.parent_link {
1319 ModuleParentLink(ref parent, _) => {
1320 search_parent_externals(needle, &parent.upgrade().unwrap())
1327 let mut search_module = module_;
1328 let mut index = index;
1329 let module_path_len = module_path.len();
1330 let mut closest_private = lp;
1332 // Resolve the module part of the path. This does not involve looking
1333 // upward though scope chains; we simply resolve names directly in
1334 // modules as we go.
1335 while index < module_path_len {
1336 let name = module_path[index];
1337 match self.resolve_name_in_module(search_module.clone(),
1343 let segment_name = name.as_str();
1344 let module_name = module_to_string(&*search_module);
1345 let mut span = span;
1346 let msg = if "???" == &module_name[..] {
1347 span.hi = span.lo + Pos::from_usize(segment_name.len());
1349 match search_parent_externals(name,
1350 &self.current_module) {
1352 let path_str = names_to_string(module_path);
1353 let target_mod_str = module_to_string(&*module);
1354 let current_mod_str =
1355 module_to_string(&*self.current_module);
1357 let prefix = if target_mod_str == current_mod_str {
1358 "self::".to_string()
1360 format!("{}::", target_mod_str)
1363 format!("Did you mean `{}{}`?", prefix, path_str)
1365 None => format!("Maybe a missing `extern crate {}`?",
1369 format!("Could not find `{}` in `{}`",
1374 return Failed(Some((span, msg)));
1376 Failed(err) => return Failed(err),
1378 debug!("(resolving module path for import) module \
1379 resolution is indeterminate: {}",
1381 return Indeterminate;
1383 Success((target, used_proxy)) => {
1384 // Check to see whether there are type bindings, and, if
1385 // so, whether there is a module within.
1386 match *target.bindings.type_def.borrow() {
1387 Some(ref type_def) => {
1388 match type_def.module_def {
1390 let msg = format!("Not a module `{}`",
1393 return Failed(Some((span, msg)));
1395 Some(ref module_def) => {
1396 search_module = module_def.clone();
1398 // track extern crates for unused_extern_crate lint
1399 if let Some(did) = module_def.def_id.get() {
1400 self.used_crates.insert(did.krate);
1403 // Keep track of the closest
1404 // private module used when
1405 // resolving this import chain.
1406 if !used_proxy && !search_module.is_public {
1407 if let Some(did) = search_module.def_id.get() {
1408 closest_private = LastMod(DependsOn(did));
1415 // There are no type bindings at all.
1416 let msg = format!("Not a module `{}`",
1418 return Failed(Some((span, msg)));
1427 return Success((search_module, closest_private));
1430 /// Attempts to resolve the module part of an import directive or path
1431 /// rooted at the given module.
1433 /// On success, returns the resolved module, and the closest *private*
1434 /// module found to the destination when resolving this path.
1435 fn resolve_module_path(&mut self,
1436 module_: Rc<Module>,
1437 module_path: &[Name],
1438 use_lexical_scope: UseLexicalScopeFlag,
1440 name_search_type: NameSearchType)
1441 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1442 let module_path_len = module_path.len();
1443 assert!(module_path_len > 0);
1445 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1446 names_to_string(module_path),
1447 module_to_string(&*module_));
1449 // Resolve the module prefix, if any.
1450 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1456 match module_prefix_result {
1458 let mpath = names_to_string(module_path);
1459 let mpath = &mpath[..];
1460 match mpath.rfind(':') {
1462 let msg = format!("Could not find `{}` in `{}`",
1463 // idx +- 1 to account for the
1464 // colons on either side
1467 return Failed(Some((span, msg)));
1474 Failed(err) => return Failed(err),
1476 debug!("(resolving module path for import) indeterminate; \
1478 return Indeterminate;
1480 Success(NoPrefixFound) => {
1481 // There was no prefix, so we're considering the first element
1482 // of the path. How we handle this depends on whether we were
1483 // instructed to use lexical scope or not.
1484 match use_lexical_scope {
1485 DontUseLexicalScope => {
1486 // This is a crate-relative path. We will start the
1487 // resolution process at index zero.
1488 search_module = self.graph_root.get_module();
1490 last_private = LastMod(AllPublic);
1492 UseLexicalScope => {
1493 // This is not a crate-relative path. We resolve the
1494 // first component of the path in the current lexical
1495 // scope and then proceed to resolve below that.
1496 match self.resolve_module_in_lexical_scope(module_,
1498 Failed(err) => return Failed(err),
1500 debug!("(resolving module path for import) \
1501 indeterminate; bailing");
1502 return Indeterminate;
1504 Success(containing_module) => {
1505 search_module = containing_module;
1507 last_private = LastMod(AllPublic);
1513 Success(PrefixFound(ref containing_module, index)) => {
1514 search_module = containing_module.clone();
1515 start_index = index;
1516 last_private = LastMod(DependsOn(containing_module.def_id
1522 self.resolve_module_path_from_root(search_module,
1530 /// Invariant: This must only be called during main resolution, not during
1531 /// import resolution.
1532 fn resolve_item_in_lexical_scope(&mut self,
1533 module_: Rc<Module>,
1535 namespace: Namespace)
1536 -> ResolveResult<(Target, bool)> {
1537 debug!("(resolving item in lexical scope) resolving `{}` in \
1538 namespace {:?} in `{}`",
1541 module_to_string(&*module_));
1543 // The current module node is handled specially. First, check for
1544 // its immediate children.
1545 build_reduced_graph::populate_module_if_necessary(self, &module_);
1547 match module_.children.borrow().get(&name) {
1549 if name_bindings.defined_in_namespace(namespace) => {
1550 debug!("top name bindings succeeded");
1551 return Success((Target::new(module_.clone(),
1552 name_bindings.clone(),
1556 Some(_) | None => { /* Not found; continue. */ }
1559 // Now check for its import directives. We don't have to have resolved
1560 // all its imports in the usual way; this is because chains of
1561 // adjacent import statements are processed as though they mutated the
1563 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1564 match (*import_resolution).target_for_namespace(namespace) {
1566 // Not found; continue.
1567 debug!("(resolving item in lexical scope) found \
1568 import resolution, but not in namespace {:?}",
1572 debug!("(resolving item in lexical scope) using \
1573 import resolution");
1574 // track used imports and extern crates as well
1575 let id = import_resolution.id(namespace);
1576 self.used_imports.insert((id, namespace));
1577 self.record_import_use(id, name);
1578 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1579 self.used_crates.insert(kid);
1581 return Success((target, false));
1586 // Search for external modules.
1587 if namespace == TypeNS {
1588 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1589 let child = module_.external_module_children.borrow().get(&name).cloned();
1590 if let Some(module) = child {
1592 Rc::new(Resolver::create_name_bindings_from_module(module));
1593 debug!("lower name bindings succeeded");
1594 return Success((Target::new(module_,
1601 // Finally, proceed up the scope chain looking for parent modules.
1602 let mut search_module = module_;
1604 // Go to the next parent.
1605 match search_module.parent_link.clone() {
1607 // No more parents. This module was unresolved.
1608 debug!("(resolving item in lexical scope) unresolved \
1610 return Failed(None);
1612 ModuleParentLink(parent_module_node, _) => {
1613 match search_module.kind.get() {
1614 NormalModuleKind => {
1615 // We stop the search here.
1616 debug!("(resolving item in lexical \
1617 scope) unresolved module: not \
1618 searching through module \
1620 return Failed(None);
1625 AnonymousModuleKind => {
1626 search_module = parent_module_node.upgrade().unwrap();
1630 BlockParentLink(ref parent_module_node, _) => {
1631 search_module = parent_module_node.upgrade().unwrap();
1635 // Resolve the name in the parent module.
1636 match self.resolve_name_in_module(search_module.clone(),
1641 Failed(Some((span, msg))) => {
1642 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1644 Failed(None) => (), // Continue up the search chain.
1646 // We couldn't see through the higher scope because of an
1647 // unresolved import higher up. Bail.
1649 debug!("(resolving item in lexical scope) indeterminate \
1650 higher scope; bailing");
1651 return Indeterminate;
1653 Success((target, used_reexport)) => {
1654 // We found the module.
1655 debug!("(resolving item in lexical scope) found name \
1657 return Success((target, used_reexport));
1663 /// Resolves a module name in the current lexical scope.
1664 fn resolve_module_in_lexical_scope(&mut self,
1665 module_: Rc<Module>,
1667 -> ResolveResult<Rc<Module>> {
1668 // If this module is an anonymous module, resolve the item in the
1669 // lexical scope. Otherwise, resolve the item from the crate root.
1670 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1671 match resolve_result {
1672 Success((target, _)) => {
1673 let bindings = &*target.bindings;
1674 match *bindings.type_def.borrow() {
1675 Some(ref type_def) => {
1676 match type_def.module_def {
1678 debug!("!!! (resolving module in lexical \
1679 scope) module wasn't actually a \
1681 return Failed(None);
1683 Some(ref module_def) => {
1684 return Success(module_def.clone());
1689 debug!("!!! (resolving module in lexical scope) module
1690 wasn't actually a module!");
1691 return Failed(None);
1696 debug!("(resolving module in lexical scope) indeterminate; \
1698 return Indeterminate;
1701 debug!("(resolving module in lexical scope) failed to resolve");
1707 /// Returns the nearest normal module parent of the given module.
1708 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1709 -> Option<Rc<Module>> {
1710 let mut module_ = module_;
1712 match module_.parent_link.clone() {
1713 NoParentLink => return None,
1714 ModuleParentLink(new_module, _) |
1715 BlockParentLink(new_module, _) => {
1716 let new_module = new_module.upgrade().unwrap();
1717 match new_module.kind.get() {
1718 NormalModuleKind => return Some(new_module),
1722 AnonymousModuleKind => module_ = new_module,
1729 /// Returns the nearest normal module parent of the given module, or the
1730 /// module itself if it is a normal module.
1731 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1733 match module_.kind.get() {
1734 NormalModuleKind => return module_,
1738 AnonymousModuleKind => {
1739 match self.get_nearest_normal_module_parent(module_.clone()) {
1741 Some(new_module) => new_module
1747 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1748 /// (b) some chain of `super::`.
1749 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1750 fn resolve_module_prefix(&mut self,
1751 module_: Rc<Module>,
1752 module_path: &[Name])
1753 -> ResolveResult<ModulePrefixResult> {
1754 // Start at the current module if we see `self` or `super`, or at the
1755 // top of the crate otherwise.
1756 let mut i = match &*module_path[0].as_str() {
1759 _ => return Success(NoPrefixFound),
1761 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1763 // Now loop through all the `super`s we find.
1764 while i < module_path.len() && "super" == module_path[i].as_str() {
1765 debug!("(resolving module prefix) resolving `super` at {}",
1766 module_to_string(&*containing_module));
1767 match self.get_nearest_normal_module_parent(containing_module) {
1768 None => return Failed(None),
1769 Some(new_module) => {
1770 containing_module = new_module;
1776 debug!("(resolving module prefix) finished resolving prefix at {}",
1777 module_to_string(&*containing_module));
1779 return Success(PrefixFound(containing_module, i));
1782 /// Attempts to resolve the supplied name in the given module for the
1783 /// given namespace. If successful, returns the target corresponding to
1786 /// The boolean returned on success is an indicator of whether this lookup
1787 /// passed through a public re-export proxy.
1788 fn resolve_name_in_module(&mut self,
1789 module_: Rc<Module>,
1791 namespace: Namespace,
1792 name_search_type: NameSearchType,
1793 allow_private_imports: bool)
1794 -> ResolveResult<(Target, bool)> {
1795 debug!("(resolving name in module) resolving `{}` in `{}`",
1797 module_to_string(&*module_));
1799 // First, check the direct children of the module.
1800 build_reduced_graph::populate_module_if_necessary(self, &module_);
1802 match module_.children.borrow().get(&name) {
1804 if name_bindings.defined_in_namespace(namespace) => {
1805 debug!("(resolving name in module) found node as child");
1806 return Success((Target::new(module_.clone(),
1807 name_bindings.clone(),
1816 // Next, check the module's imports if necessary.
1818 // If this is a search of all imports, we should be done with glob
1819 // resolution at this point.
1820 if name_search_type == PathSearch {
1821 assert_eq!(module_.glob_count.get(), 0);
1824 // Check the list of resolved imports.
1825 match module_.import_resolutions.borrow().get(&name) {
1826 Some(import_resolution) if allow_private_imports ||
1827 import_resolution.is_public => {
1829 if import_resolution.is_public &&
1830 import_resolution.outstanding_references != 0 {
1831 debug!("(resolving name in module) import \
1832 unresolved; bailing out");
1833 return Indeterminate;
1835 match import_resolution.target_for_namespace(namespace) {
1837 debug!("(resolving name in module) name found, \
1838 but not in namespace {:?}",
1842 debug!("(resolving name in module) resolved to \
1844 // track used imports and extern crates as well
1845 let id = import_resolution.id(namespace);
1846 self.used_imports.insert((id, namespace));
1847 self.record_import_use(id, name);
1848 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1849 self.used_crates.insert(kid);
1851 return Success((target, true));
1855 Some(..) | None => {} // Continue.
1858 // Finally, search through external children.
1859 if namespace == TypeNS {
1860 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1861 let child = module_.external_module_children.borrow().get(&name).cloned();
1862 if let Some(module) = child {
1864 Rc::new(Resolver::create_name_bindings_from_module(module));
1865 return Success((Target::new(module_,
1872 // We're out of luck.
1873 debug!("(resolving name in module) failed to resolve `{}`",
1875 return Failed(None);
1878 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1879 let index = module_.resolved_import_count.get();
1880 let imports = module_.imports.borrow();
1881 let import_count = imports.len();
1882 if index != import_count {
1884 (*imports)[index].span,
1885 ResolutionError::UnresolvedImport(None));
1888 // Descend into children and anonymous children.
1889 build_reduced_graph::populate_module_if_necessary(self, &module_);
1891 for (_, child_node) in module_.children.borrow().iter() {
1892 match child_node.get_module_if_available() {
1896 Some(child_module) => {
1897 self.report_unresolved_imports(child_module);
1902 for (_, module_) in module_.anonymous_children.borrow().iter() {
1903 self.report_unresolved_imports(module_.clone());
1909 // We maintain a list of value ribs and type ribs.
1911 // Simultaneously, we keep track of the current position in the module
1912 // graph in the `current_module` pointer. When we go to resolve a name in
1913 // the value or type namespaces, we first look through all the ribs and
1914 // then query the module graph. When we resolve a name in the module
1915 // namespace, we can skip all the ribs (since nested modules are not
1916 // allowed within blocks in Rust) and jump straight to the current module
1919 // Named implementations are handled separately. When we find a method
1920 // call, we consult the module node to find all of the implementations in
1921 // scope. This information is lazily cached in the module node. We then
1922 // generate a fake "implementation scope" containing all the
1923 // implementations thus found, for compatibility with old resolve pass.
1925 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1926 F: FnOnce(&mut Resolver),
1928 let orig_module = self.current_module.clone();
1930 // Move down in the graph.
1936 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1938 match orig_module.children.borrow().get(&name) {
1940 debug!("!!! (with scope) didn't find `{}` in `{}`",
1942 module_to_string(&*orig_module));
1944 Some(name_bindings) => {
1945 match (*name_bindings).get_module_if_available() {
1947 debug!("!!! (with scope) didn't find module \
1950 module_to_string(&*orig_module));
1953 self.current_module = module_;
1963 self.current_module = orig_module;
1966 /// Wraps the given definition in the appropriate number of `DefUpvar`
1972 -> Option<DefLike> {
1973 let mut def = match def_like {
1975 _ => return Some(def_like)
1979 self.session.span_bug(span,
1980 &format!("unexpected {:?} in bindings", def))
1982 DefLocal(node_id) => {
1986 // Nothing to do. Continue.
1988 ClosureRibKind(function_id) => {
1990 def = DefUpvar(node_id, function_id);
1992 let mut seen = self.freevars_seen.borrow_mut();
1993 let seen = match seen.entry(function_id) {
1994 Occupied(v) => v.into_mut(),
1995 Vacant(v) => v.insert(NodeSet()),
1997 if seen.contains(&node_id) {
2000 match self.freevars.borrow_mut().entry(function_id) {
2001 Occupied(v) => v.into_mut(),
2002 Vacant(v) => v.insert(vec![]),
2003 }.push(Freevar { def: prev_def, span: span });
2004 seen.insert(node_id);
2006 ItemRibKind | MethodRibKind => {
2007 // This was an attempt to access an upvar inside a
2008 // named function item. This is not allowed, so we
2013 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem
2017 ConstantItemRibKind => {
2018 // Still doesn't deal with upvars
2022 ResolutionError::AttemptToUseNonConstantValueInConstant
2029 DefTyParam(..) | DefSelfTy(..) => {
2032 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
2033 // Nothing to do. Continue.
2036 // This was an attempt to use a type parameter outside
2041 ResolutionError::TypeParametersFromOuterFunction);
2044 ConstantItemRibKind => {
2046 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2057 /// Searches the current set of local scopes and
2058 /// applies translations for closures.
2059 fn search_ribs(&self,
2063 -> Option<DefLike> {
2064 // FIXME #4950: Try caching?
2066 for (i, rib) in ribs.iter().enumerate().rev() {
2067 if let Some(def_like) = rib.bindings.get(&name).cloned() {
2068 return self.upvarify(&ribs[i + 1..], def_like, span);
2075 /// Searches the current set of local scopes for labels.
2076 /// Stops after meeting a closure.
2077 fn search_label(&self, name: Name) -> Option<DefLike> {
2078 for rib in self.label_ribs.iter().rev() {
2084 // Do not resolve labels across function boundary
2088 let result = rib.bindings.get(&name).cloned();
2089 if result.is_some() {
2096 fn resolve_crate(&mut self, krate: &ast::Crate) {
2097 debug!("(resolving crate) starting");
2099 visit::walk_crate(self, krate);
2102 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
2103 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
2104 span_err!(self.session, span, E0317,
2105 "user-defined types or type parameters cannot shadow the primitive types");
2109 fn resolve_item(&mut self, item: &Item) {
2110 let name = item.ident.name;
2112 debug!("(resolving item) resolving {}",
2116 ItemEnum(_, ref generics) |
2117 ItemTy(_, ref generics) |
2118 ItemStruct(_, ref generics) => {
2119 self.check_if_primitive_type_name(name, item.span);
2121 self.with_type_parameter_rib(HasTypeParameters(generics,
2124 |this| visit::walk_item(this, item));
2126 ItemFn(_, _, _, _, ref generics, _) => {
2127 self.with_type_parameter_rib(HasTypeParameters(generics,
2130 |this| visit::walk_item(this, item));
2133 ItemDefaultImpl(_, ref trait_ref) => {
2134 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
2141 ref impl_items) => {
2142 self.resolve_implementation(generics,
2149 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2150 self.check_if_primitive_type_name(name, item.span);
2152 // Create a new rib for the trait-wide type parameters.
2153 self.with_type_parameter_rib(HasTypeParameters(generics,
2157 this.with_self_rib(DefSelfTy(Some(local_def(item.id)), None), |this| {
2158 this.visit_generics(generics);
2159 visit::walk_ty_param_bounds_helper(this, bounds);
2161 for trait_item in trait_items {
2162 match trait_item.node {
2163 ast::ConstTraitItem(_, ref default) => {
2164 // Only impose the restrictions of
2165 // ConstRibKind if there's an actual constant
2166 // expression in a provided default.
2167 if default.is_some() {
2168 this.with_constant_rib(|this| {
2169 visit::walk_trait_item(this, trait_item)
2172 visit::walk_trait_item(this, trait_item)
2175 ast::MethodTraitItem(ref sig, _) => {
2176 let type_parameters =
2177 HasTypeParameters(&sig.generics,
2180 this.with_type_parameter_rib(type_parameters, |this| {
2181 visit::walk_trait_item(this, trait_item)
2184 ast::TypeTraitItem(..) => {
2185 this.check_if_primitive_type_name(trait_item.ident.name,
2187 this.with_type_parameter_rib(NoTypeParameters, |this| {
2188 visit::walk_trait_item(this, trait_item)
2197 ItemMod(_) | ItemForeignMod(_) => {
2198 self.with_scope(Some(name), |this| {
2199 visit::walk_item(this, item);
2203 ItemConst(..) | ItemStatic(..) => {
2204 self.with_constant_rib(|this| {
2205 visit::walk_item(this, item);
2209 ItemUse(ref view_path) => {
2210 // check for imports shadowing primitive types
2211 if let ast::ViewPathSimple(ident, _) = view_path.node {
2212 match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
2213 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2214 self.check_if_primitive_type_name(ident.name, item.span);
2221 ItemExternCrate(_) | ItemMac(..) => {
2222 // do nothing, these are just around to be encoded
2227 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2228 F: FnOnce(&mut Resolver),
2230 match type_parameters {
2231 HasTypeParameters(generics, space, rib_kind) => {
2232 let mut function_type_rib = Rib::new(rib_kind);
2233 let mut seen_bindings = HashSet::new();
2234 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2235 let name = type_parameter.ident.name;
2236 debug!("with_type_parameter_rib: {}", type_parameter.id);
2238 if seen_bindings.contains(&name) {
2240 type_parameter.span,
2241 ResolutionError::NameAlreadyUsedInTypeParameterList(
2245 seen_bindings.insert(name);
2247 // plain insert (no renaming)
2248 function_type_rib.bindings.insert(name,
2249 DlDef(DefTyParam(space,
2251 local_def(type_parameter.id),
2254 self.type_ribs.push(function_type_rib);
2257 NoTypeParameters => {
2264 match type_parameters {
2265 HasTypeParameters(..) => { if !self.resolved { self.type_ribs.pop(); } }
2266 NoTypeParameters => { }
2270 fn with_label_rib<F>(&mut self, f: F) where
2271 F: FnOnce(&mut Resolver),
2273 self.label_ribs.push(Rib::new(NormalRibKind));
2276 self.label_ribs.pop();
2280 fn with_constant_rib<F>(&mut self, f: F) where
2281 F: FnOnce(&mut Resolver),
2283 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2284 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2287 self.type_ribs.pop();
2288 self.value_ribs.pop();
2292 fn resolve_function(&mut self,
2294 declaration: &FnDecl,
2296 // Create a value rib for the function.
2297 self.value_ribs.push(Rib::new(rib_kind));
2299 // Create a label rib for the function.
2300 self.label_ribs.push(Rib::new(rib_kind));
2302 // Add each argument to the rib.
2303 let mut bindings_list = HashMap::new();
2304 for argument in &declaration.inputs {
2305 self.resolve_pattern(&*argument.pat,
2306 ArgumentIrrefutableMode,
2307 &mut bindings_list);
2309 self.visit_ty(&*argument.ty);
2311 debug!("(resolving function) recorded argument");
2313 visit::walk_fn_ret_ty(self, &declaration.output);
2315 // Resolve the function body.
2316 self.visit_block(&*block);
2318 debug!("(resolving function) leaving function");
2321 self.label_ribs.pop();
2322 self.value_ribs.pop();
2326 fn resolve_trait_reference(&mut self,
2330 -> Result<PathResolution, ()> {
2331 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2332 if let DefTrait(_) = path_res.base_def {
2333 debug!("(resolving trait) found trait def: {:?}", path_res);
2338 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2342 // If it's a typedef, give a note
2343 if let DefTy(..) = path_res.base_def {
2344 self.session.span_note(trait_path.span,
2345 "`type` aliases cannot be used for traits");
2352 ResolutionError::UndeclaredTraitName(
2353 &*path_names_to_string(trait_path, path_depth))
2359 fn resolve_generics(&mut self, generics: &Generics) {
2360 for type_parameter in generics.ty_params.iter() {
2361 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2363 for predicate in &generics.where_clause.predicates {
2365 &ast::WherePredicate::BoundPredicate(_) |
2366 &ast::WherePredicate::RegionPredicate(_) => {}
2367 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
2368 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2369 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2370 self.record_def(eq_pred.id, path_res.unwrap());
2374 ResolutionError::UndeclaredAssociatedType);
2379 visit::walk_generics(self, generics);
2382 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2383 where F: FnOnce(&mut Resolver) -> T
2385 // Handle nested impls (inside fn bodies)
2386 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2387 let result = f(self);
2388 self.current_self_type = previous_value;
2392 fn with_optional_trait_ref<T, F>(&mut self,
2393 opt_trait_ref: Option<&TraitRef>,
2396 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2398 let mut new_val = None;
2399 let mut new_id = None;
2400 if let Some(trait_ref) = opt_trait_ref {
2401 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2402 &trait_ref.path, 0) {
2403 assert!(path_res.depth == 0);
2404 self.record_def(trait_ref.ref_id, path_res);
2405 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2406 new_id = Some(path_res.base_def.def_id());
2408 visit::walk_trait_ref(self, trait_ref);
2410 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2411 let result = f(self, new_id);
2412 self.current_trait_ref = original_trait_ref;
2416 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2417 where F: FnOnce(&mut Resolver)
2419 let mut self_type_rib = Rib::new(NormalRibKind);
2421 // plain insert (no renaming, types are not currently hygienic....)
2422 let name = special_names::type_self;
2423 self_type_rib.bindings.insert(name, DlDef(self_def));
2424 self.type_ribs.push(self_type_rib);
2427 self.type_ribs.pop();
2431 fn resolve_implementation(&mut self,
2432 generics: &Generics,
2433 opt_trait_reference: &Option<TraitRef>,
2436 impl_items: &[P<ImplItem>]) {
2437 // If applicable, create a rib for the type parameters.
2438 self.with_type_parameter_rib(HasTypeParameters(generics,
2442 // Resolve the type parameters.
2443 this.visit_generics(generics);
2445 // Resolve the trait reference, if necessary.
2446 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2447 // Resolve the self type.
2448 this.visit_ty(self_type);
2450 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2451 this.with_current_self_type(self_type, |this| {
2452 for impl_item in impl_items {
2453 match impl_item.node {
2454 ConstImplItem(..) => {
2455 // If this is a trait impl, ensure the const
2457 this.check_trait_item(impl_item.ident.name,
2459 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2460 this.with_constant_rib(|this| {
2461 visit::walk_impl_item(this, impl_item);
2464 MethodImplItem(ref sig, _) => {
2465 // If this is a trait impl, ensure the method
2467 this.check_trait_item(impl_item.ident.name,
2469 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2471 // We also need a new scope for the method-
2472 // specific type parameters.
2473 let type_parameters =
2474 HasTypeParameters(&sig.generics,
2477 this.with_type_parameter_rib(type_parameters, |this| {
2478 visit::walk_impl_item(this, impl_item);
2481 TypeImplItem(ref ty) => {
2482 // If this is a trait impl, ensure the type
2484 this.check_trait_item(impl_item.ident.name,
2486 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2490 ast::MacImplItem(_) => {}
2499 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2500 where F: FnOnce(Name, &str) -> ResolutionError {
2501 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2502 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2503 if !self.trait_item_map.contains_key(&(name, did)) {
2504 let path_str = path_names_to_string(&trait_ref.path, 0);
2507 err(name, &*path_str));
2512 fn resolve_local(&mut self, local: &Local) {
2513 // Resolve the type.
2514 visit::walk_ty_opt(self, &local.ty);
2516 // Resolve the initializer.
2517 visit::walk_expr_opt(self, &local.init);
2519 // Resolve the pattern.
2520 self.resolve_pattern(&*local.pat,
2521 LocalIrrefutableMode,
2522 &mut HashMap::new());
2525 // build a map from pattern identifiers to binding-info's.
2526 // this is done hygienically. This could arise for a macro
2527 // that expands into an or-pattern where one 'x' was from the
2528 // user and one 'x' came from the macro.
2529 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2530 let mut result = HashMap::new();
2531 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2532 let name = mtwt::resolve(path1.node);
2533 result.insert(name, BindingInfo {
2535 binding_mode: binding_mode
2541 // check that all of the arms in an or-pattern have exactly the
2542 // same set of bindings, with the same binding modes for each.
2543 fn check_consistent_bindings(&mut self, arm: &Arm) {
2544 if arm.pats.is_empty() {
2547 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2548 for (i, p) in arm.pats.iter().enumerate() {
2549 let map_i = self.binding_mode_map(&**p);
2551 for (&key, &binding_0) in &map_0 {
2552 match map_i.get(&key) {
2556 ResolutionError::VariableNotBoundInPattern(key,
2559 Some(binding_i) => {
2560 if binding_0.binding_mode != binding_i.binding_mode {
2563 ResolutionError::VariableBoundWithDifferentMode(key,
2571 for (&key, &binding) in &map_i {
2572 if !map_0.contains_key(&key) {
2575 ResolutionError::VariableNotBoundInParentPattern(key,
2582 fn resolve_arm(&mut self, arm: &Arm) {
2583 self.value_ribs.push(Rib::new(NormalRibKind));
2585 let mut bindings_list = HashMap::new();
2586 for pattern in &arm.pats {
2587 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2590 // This has to happen *after* we determine which
2591 // pat_idents are variants
2592 self.check_consistent_bindings(arm);
2594 visit::walk_expr_opt(self, &arm.guard);
2595 self.visit_expr(&*arm.body);
2598 self.value_ribs.pop();
2602 fn resolve_block(&mut self, block: &Block) {
2603 debug!("(resolving block) entering block");
2604 self.value_ribs.push(Rib::new(NormalRibKind));
2606 // Move down in the graph, if there's an anonymous module rooted here.
2607 let orig_module = self.current_module.clone();
2608 match orig_module.anonymous_children.borrow().get(&block.id) {
2609 None => { /* Nothing to do. */ }
2610 Some(anonymous_module) => {
2611 debug!("(resolving block) found anonymous module, moving \
2613 self.current_module = anonymous_module.clone();
2617 // Check for imports appearing after non-item statements.
2618 let mut found_non_item = false;
2619 for statement in &block.stmts {
2620 if let ast::StmtDecl(ref declaration, _) = statement.node {
2621 if let ast::DeclItem(ref i) = declaration.node {
2623 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2624 span_err!(self.session, i.span, E0154,
2625 "imports are not allowed after non-item statements");
2630 found_non_item = true
2633 found_non_item = true;
2637 // Descend into the block.
2638 visit::walk_block(self, block);
2642 self.current_module = orig_module;
2643 self.value_ribs.pop();
2645 debug!("(resolving block) leaving block");
2648 fn resolve_type(&mut self, ty: &Ty) {
2650 TyPath(ref maybe_qself, ref path) => {
2652 match self.resolve_possibly_assoc_item(ty.id,
2653 maybe_qself.as_ref(),
2657 // `<T>::a::b::c` is resolved by typeck alone.
2658 TypecheckRequired => {
2659 // Resolve embedded types.
2660 visit::walk_ty(self, ty);
2663 ResolveAttempt(resolution) => resolution,
2666 // This is a path in the type namespace. Walk through scopes
2670 // Write the result into the def map.
2671 debug!("(resolving type) writing resolution for `{}` \
2673 path_names_to_string(path, 0),
2675 self.record_def(ty.id, def);
2678 // Keep reporting some errors even if they're ignored above.
2679 self.resolve_path(ty.id, path, 0, TypeNS, true);
2681 let kind = if maybe_qself.is_some() {
2687 let self_type_name = special_idents::type_self.name;
2688 let is_invalid_self_type_name =
2689 path.segments.len() > 0 &&
2690 maybe_qself.is_none() &&
2691 path.segments[0].identifier.name == self_type_name;
2692 if is_invalid_self_type_name {
2695 ResolutionError::SelfUsedOutsideImplOrTrait);
2699 ResolutionError::UseOfUndeclared(
2701 &*path_names_to_string(path,
2710 // Resolve embedded types.
2711 visit::walk_ty(self, ty);
2714 fn resolve_pattern(&mut self,
2716 mode: PatternBindingMode,
2717 // Maps idents to the node ID for the (outermost)
2718 // pattern that binds them
2719 bindings_list: &mut HashMap<Name, NodeId>) {
2720 let pat_id = pattern.id;
2721 walk_pat(pattern, |pattern| {
2722 match pattern.node {
2723 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2724 // The meaning of PatIdent with no type parameters
2725 // depends on whether an enum variant or unit-like struct
2726 // with that name is in scope. The probing lookup has to
2727 // be careful not to emit spurious errors. Only matching
2728 // patterns (match) can match nullary variants or
2729 // unit-like structs. For binding patterns (let
2730 // and the LHS of @-patterns), matching such a value is
2731 // simply disallowed (since it's rarely what you want).
2732 let const_ok = mode == RefutableMode && at_rhs.is_none();
2734 let ident = path1.node;
2735 let renamed = mtwt::resolve(ident);
2737 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2738 FoundStructOrEnumVariant(def, lp) if const_ok => {
2739 debug!("(resolving pattern) resolving `{}` to \
2740 struct or enum variant",
2743 self.enforce_default_binding_mode(
2747 self.record_def(pattern.id, PathResolution {
2753 FoundStructOrEnumVariant(..) => {
2757 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2761 FoundConst(def, lp) if const_ok => {
2762 debug!("(resolving pattern) resolving `{}` to \
2766 self.enforce_default_binding_mode(
2770 self.record_def(pattern.id, PathResolution {
2780 ResolutionError::OnlyIrrefutablePatternsAllowedHere
2783 BareIdentifierPatternUnresolved => {
2784 debug!("(resolving pattern) binding `{}`",
2787 let def = DefLocal(pattern.id);
2789 // Record the definition so that later passes
2790 // will be able to distinguish variants from
2791 // locals in patterns.
2793 self.record_def(pattern.id, PathResolution {
2795 last_private: LastMod(AllPublic),
2799 // Add the binding to the local ribs, if it
2800 // doesn't already exist in the bindings list. (We
2801 // must not add it if it's in the bindings list
2802 // because that breaks the assumptions later
2803 // passes make about or-patterns.)
2804 if !bindings_list.contains_key(&renamed) {
2805 let this = &mut *self;
2806 let last_rib = this.value_ribs.last_mut().unwrap();
2807 last_rib.bindings.insert(renamed, DlDef(def));
2808 bindings_list.insert(renamed, pat_id);
2809 } else if mode == ArgumentIrrefutableMode &&
2810 bindings_list.contains_key(&renamed) {
2811 // Forbid duplicate bindings in the same
2816 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2817 &ident.name.as_str())
2819 } else if bindings_list.get(&renamed) ==
2821 // Then this is a duplicate variable in the
2822 // same disjunction, which is an error.
2826 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2827 &ident.name.as_str())
2830 // Else, not bound in the same pattern: do
2836 PatEnum(ref path, _) => {
2837 // This must be an enum variant, struct or const.
2839 match self.resolve_possibly_assoc_item(pat_id, None,
2842 // The below shouldn't happen because all
2843 // qualified paths should be in PatQPath.
2844 TypecheckRequired =>
2845 self.session.span_bug(
2847 "resolve_possibly_assoc_item claimed
2848 that a path in PatEnum requires typecheck
2849 to resolve, but qualified paths should be
2851 ResolveAttempt(resolution) => resolution,
2853 if let Some(path_res) = resolution {
2854 match path_res.base_def {
2855 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2856 self.record_def(pattern.id, path_res);
2859 resolve_error(&self,
2861 ResolutionError::StaticVariableReference);
2864 // If anything ends up here entirely resolved,
2865 // it's an error. If anything ends up here
2866 // partially resolved, that's OK, because it may
2867 // be a `T::CONST` that typeck will resolve.
2868 if path_res.depth == 0 {
2872 ResolutionError::NotAnEnumVariantStructOrConst(
2881 let const_name = path.segments.last().unwrap()
2883 let traits = self.get_traits_containing_item(const_name);
2884 self.trait_map.insert(pattern.id, traits);
2885 self.record_def(pattern.id, path_res);
2893 ResolutionError::UnresolvedEnumVariantStructOrConst(
2894 &path.segments.last().unwrap().identifier.name.as_str())
2897 visit::walk_path(self, path);
2900 PatQPath(ref qself, ref path) => {
2901 // Associated constants only.
2903 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2906 TypecheckRequired => {
2907 // All `<T>::CONST` should end up here, and will
2908 // require use of the trait map to resolve
2909 // during typechecking.
2910 let const_name = path.segments.last().unwrap()
2912 let traits = self.get_traits_containing_item(const_name);
2913 self.trait_map.insert(pattern.id, traits);
2914 visit::walk_pat(self, pattern);
2917 ResolveAttempt(resolution) => resolution,
2919 if let Some(path_res) = resolution {
2920 match path_res.base_def {
2921 // All `<T as Trait>::CONST` should end up here, and
2922 // have the trait already selected.
2923 DefAssociatedConst(..) => {
2924 self.record_def(pattern.id, path_res);
2930 ResolutionError::NotAnAssociatedConst(
2931 &path.segments.last().unwrap().identifier.name.as_str()
2940 ResolutionError::UnresolvedAssociatedConst(
2941 &path.segments.last().unwrap().identifier.name.as_str()
2945 visit::walk_pat(self, pattern);
2948 PatStruct(ref path, _, _) => {
2949 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2950 Some(definition) => {
2951 self.record_def(pattern.id, definition);
2954 debug!("(resolving pattern) didn't find struct \
2955 def: {:?}", result);
2959 ResolutionError::DoesNotNameAStruct(
2960 &*path_names_to_string(path, 0))
2964 visit::walk_path(self, path);
2967 PatLit(_) | PatRange(..) => {
2968 visit::walk_pat(self, pattern);
2979 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2980 -> BareIdentifierPatternResolution {
2981 let module = self.current_module.clone();
2982 match self.resolve_item_in_lexical_scope(module,
2985 Success((target, _)) => {
2986 debug!("(resolve bare identifier pattern) succeeded in \
2987 finding {} at {:?}",
2989 target.bindings.value_def.borrow());
2990 match *target.bindings.value_def.borrow() {
2992 panic!("resolved name in the value namespace to a \
2993 set of name bindings with no def?!");
2996 // For the two success cases, this lookup can be
2997 // considered as not having a private component because
2998 // the lookup happened only within the current module.
3000 def @ DefVariant(..) | def @ DefStruct(..) => {
3001 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3003 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
3004 return FoundConst(def, LastMod(AllPublic));
3009 ResolutionError::StaticVariableReference);
3010 return BareIdentifierPatternUnresolved;
3013 return BareIdentifierPatternUnresolved;
3021 panic!("unexpected indeterminate result");
3025 Some((span, msg)) => {
3026 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3031 debug!("(resolve bare identifier pattern) failed to find {}",
3033 return BareIdentifierPatternUnresolved;
3038 /// Handles paths that may refer to associated items
3039 fn resolve_possibly_assoc_item(&mut self,
3041 maybe_qself: Option<&ast::QSelf>,
3043 namespace: Namespace,
3045 -> AssocItemResolveResult
3047 let max_assoc_types;
3051 if qself.position == 0 {
3052 return TypecheckRequired;
3054 max_assoc_types = path.segments.len() - qself.position;
3055 // Make sure the trait is valid.
3056 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
3059 max_assoc_types = path.segments.len();
3063 let mut resolution = self.with_no_errors(|this| {
3064 this.resolve_path(id, path, 0, namespace, check_ribs)
3066 for depth in 1..max_assoc_types {
3067 if resolution.is_some() {
3070 self.with_no_errors(|this| {
3071 resolution = this.resolve_path(id, path, depth,
3075 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
3076 // A module is not a valid type or value.
3079 ResolveAttempt(resolution)
3082 /// If `check_ribs` is true, checks the local definitions first; i.e.
3083 /// doesn't skip straight to the containing module.
3084 /// Skips `path_depth` trailing segments, which is also reflected in the
3085 /// returned value. See `middle::def::PathResolution` for more info.
3086 pub fn resolve_path(&mut self,
3090 namespace: Namespace,
3091 check_ribs: bool) -> Option<PathResolution> {
3092 let span = path.span;
3093 let segments = &path.segments[..path.segments.len()-path_depth];
3095 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
3098 let def = self.resolve_crate_relative_path(span, segments, namespace);
3099 return def.map(mk_res);
3102 // Try to find a path to an item in a module.
3103 let unqualified_def =
3104 self.resolve_identifier(segments.last().unwrap().identifier,
3109 if segments.len() <= 1 {
3110 return unqualified_def.map(mk_res);
3113 let def = self.resolve_module_relative_path(span, segments, namespace);
3114 match (def, unqualified_def) {
3115 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3117 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3119 "unnecessary qualification".to_string());
3127 // Resolve a single identifier.
3128 fn resolve_identifier(&mut self,
3130 namespace: Namespace,
3133 -> Option<(Def, LastPrivate)> {
3134 // First, check to see whether the name is a primitive type.
3135 if namespace == TypeNS {
3136 if let Some(&prim_ty) = self.primitive_type_table
3138 .get(&identifier.name) {
3139 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
3144 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
3147 return Some((def, LastMod(AllPublic)));
3151 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
3154 // FIXME #4952: Merge me with resolve_name_in_module?
3155 fn resolve_definition_of_name_in_module(&mut self,
3156 containing_module: Rc<Module>,
3158 namespace: Namespace)
3160 // First, search children.
3161 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3163 match containing_module.children.borrow().get(&name) {
3164 Some(child_name_bindings) => {
3165 match child_name_bindings.def_for_namespace(namespace) {
3167 // Found it. Stop the search here.
3168 let p = child_name_bindings.defined_in_public_namespace(namespace);
3169 let lp = if p {LastMod(AllPublic)} else {
3170 LastMod(DependsOn(def.def_id()))
3172 return ChildNameDefinition(def, lp);
3180 // Next, search import resolutions.
3181 match containing_module.import_resolutions.borrow().get(&name) {
3182 Some(import_resolution) if import_resolution.is_public => {
3183 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3184 match target.bindings.def_for_namespace(namespace) {
3187 let id = import_resolution.id(namespace);
3188 // track imports and extern crates as well
3189 self.used_imports.insert((id, namespace));
3190 self.record_import_use(id, name);
3191 match target.target_module.def_id.get() {
3192 Some(DefId{krate: kid, ..}) => {
3193 self.used_crates.insert(kid);
3197 return ImportNameDefinition(def, LastMod(AllPublic));
3200 // This can happen with external impls, due to
3201 // the imperfect way we read the metadata.
3206 Some(..) | None => {} // Continue.
3209 // Finally, search through external children.
3210 if namespace == TypeNS {
3211 if let Some(module) = containing_module.external_module_children.borrow()
3212 .get(&name).cloned() {
3213 if let Some(def_id) = module.def_id.get() {
3214 // track used crates
3215 self.used_crates.insert(def_id.krate);
3216 let lp = if module.is_public {LastMod(AllPublic)} else {
3217 LastMod(DependsOn(def_id))
3219 return ChildNameDefinition(DefMod(def_id), lp);
3224 return NoNameDefinition;
3227 // resolve a "module-relative" path, e.g. a::b::c
3228 fn resolve_module_relative_path(&mut self,
3230 segments: &[ast::PathSegment],
3231 namespace: Namespace)
3232 -> Option<(Def, LastPrivate)> {
3233 let module_path = segments.split_last().unwrap().1.iter()
3234 .map(|ps| ps.identifier.name)
3235 .collect::<Vec<_>>();
3237 let containing_module;
3239 let current_module = self.current_module.clone();
3240 match self.resolve_module_path(current_module,
3246 let (span, msg) = match err {
3247 Some((span, msg)) => (span, msg),
3249 let msg = format!("Use of undeclared type or module `{}`",
3250 names_to_string(&module_path));
3255 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3258 Indeterminate => panic!("indeterminate unexpected"),
3259 Success((resulting_module, resulting_last_private)) => {
3260 containing_module = resulting_module;
3261 last_private = resulting_last_private;
3265 let name = segments.last().unwrap().identifier.name;
3266 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
3269 NoNameDefinition => {
3270 // We failed to resolve the name. Report an error.
3273 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3274 (def, last_private.or(lp))
3277 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
3278 self.used_crates.insert(kid);
3283 /// Invariant: This must be called only during main resolution, not during
3284 /// import resolution.
3285 fn resolve_crate_relative_path(&mut self,
3287 segments: &[ast::PathSegment],
3288 namespace: Namespace)
3289 -> Option<(Def, LastPrivate)> {
3290 let module_path = segments.split_last().unwrap().1.iter()
3291 .map(|ps| ps.identifier.name)
3292 .collect::<Vec<_>>();
3294 let root_module = self.graph_root.get_module();
3296 let containing_module;
3298 match self.resolve_module_path_from_root(root_module,
3303 LastMod(AllPublic)) {
3305 let (span, msg) = match err {
3306 Some((span, msg)) => (span, msg),
3308 let msg = format!("Use of undeclared module `::{}`",
3309 names_to_string(&module_path[..]));
3314 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3319 panic!("indeterminate unexpected");
3322 Success((resulting_module, resulting_last_private)) => {
3323 containing_module = resulting_module;
3324 last_private = resulting_last_private;
3328 let name = segments.last().unwrap().identifier.name;
3329 match self.resolve_definition_of_name_in_module(containing_module,
3332 NoNameDefinition => {
3333 // We failed to resolve the name. Report an error.
3336 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3337 return Some((def, last_private.or(lp)));
3342 fn resolve_identifier_in_local_ribs(&mut self,
3344 namespace: Namespace,
3347 // Check the local set of ribs.
3348 let search_result = match namespace {
3350 let renamed = mtwt::resolve(ident);
3351 self.search_ribs(&self.value_ribs, renamed, span)
3354 let name = ident.name;
3355 self.search_ribs(&self.type_ribs, name, span)
3359 match search_result {
3360 Some(DlDef(def)) => {
3361 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3366 Some(DlField) | Some(DlImpl(_)) | None => {
3372 fn resolve_item_by_name_in_lexical_scope(&mut self,
3374 namespace: Namespace)
3375 -> Option<(Def, LastPrivate)> {
3377 let module = self.current_module.clone();
3378 match self.resolve_item_in_lexical_scope(module,
3381 Success((target, _)) => {
3382 match (*target.bindings).def_for_namespace(namespace) {
3384 // This can happen if we were looking for a type and
3385 // found a module instead. Modules don't have defs.
3386 debug!("(resolving item path by identifier in lexical \
3387 scope) failed to resolve {} after success...",
3392 debug!("(resolving item path in lexical scope) \
3393 resolved `{}` to item",
3395 // This lookup is "all public" because it only searched
3396 // for one identifier in the current module (couldn't
3397 // have passed through reexports or anything like that.
3398 return Some((def, LastMod(AllPublic)));
3403 panic!("unexpected indeterminate result");
3406 debug!("(resolving item path by identifier in lexical scope) \
3407 failed to resolve {}", name);
3409 if let Some((span, msg)) = err {
3410 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3418 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3419 F: FnOnce(&mut Resolver) -> T,
3421 self.emit_errors = false;
3423 self.emit_errors = true;
3427 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3428 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3429 -> Option<(Path, NodeId, FallbackChecks)> {
3431 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3432 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3433 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3434 // This doesn't handle the remaining `Ty` variants as they are not
3435 // that commonly the self_type, it might be interesting to provide
3436 // support for those in future.
3441 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3442 -> Option<Rc<Module>> {
3443 let root = this.current_module.clone();
3444 let last_name = name_path.last().unwrap();
3446 if name_path.len() == 1 {
3447 match this.primitive_type_table.primitive_types.get(last_name) {
3450 match this.current_module.children.borrow().get(last_name) {
3451 Some(child) => child.get_module_if_available(),
3457 match this.resolve_module_path(root,
3462 Success((module, _)) => Some(module),
3468 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3469 if did.krate == ast::LOCAL_CRATE {
3470 let sig = match this.ast_map.get(did.node) {
3471 ast_map::NodeTraitItem(trait_item) => match trait_item.node {
3472 ast::MethodTraitItem(ref sig, _) => sig,
3475 ast_map::NodeImplItem(impl_item) => match impl_item.node {
3476 ast::MethodImplItem(ref sig, _) => sig,
3481 sig.explicit_self.node == ast::SelfStatic
3483 csearch::is_static_method(&this.session.cstore, did)
3487 let (path, node_id, allowed) = match self.current_self_type {
3488 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3490 None => return NoSuggestion,
3492 None => return NoSuggestion,
3495 if allowed == Everything {
3496 // Look for a field with the same name in the current self_type.
3497 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3498 Some(DefTy(did, _)) |
3499 Some(DefStruct(did)) |
3500 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3503 if fields.iter().any(|&field_name| name == field_name) {
3508 _ => {} // Self type didn't resolve properly
3512 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3514 // Look for a method in the current self type's impl module.
3515 if let Some(module) = get_module(self, path.span, &name_path) {
3516 if let Some(binding) = module.children.borrow().get(&name) {
3517 if let Some(DefMethod(did)) = binding.def_for_namespace(ValueNS) {
3518 if is_static_method(self, did) {
3519 return StaticMethod(path_names_to_string(&path, 0))
3521 if self.current_trait_ref.is_some() {
3523 } else if allowed == Everything {
3530 // Look for a method in the current trait.
3531 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3532 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3533 if is_static_method(self, did) {
3534 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3544 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3545 let mut maybes: Vec<token::InternedString> = Vec::new();
3546 let mut values: Vec<usize> = Vec::new();
3548 for rib in self.value_ribs.iter().rev() {
3549 for (&k, _) in &rib.bindings {
3550 maybes.push(k.as_str());
3551 values.push(usize::MAX);
3555 let mut smallest = 0;
3556 for (i, other) in maybes.iter().enumerate() {
3557 values[i] = lev_distance(name, &other);
3559 if values[i] <= values[smallest] {
3564 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3565 // maximum edit distance we will accept for a suggestion to one third of
3566 // the typo'd name's length.
3567 let max_distance = std::cmp::max(name.len(), 3) / 3;
3569 if !values.is_empty() &&
3570 values[smallest] <= max_distance &&
3571 name != &maybes[smallest][..] {
3573 Some(maybes[smallest].to_string())
3580 fn resolve_expr(&mut self, expr: &Expr) {
3581 // First, record candidate traits for this expression if it could
3582 // result in the invocation of a method call.
3584 self.record_candidate_traits_for_expr_if_necessary(expr);
3586 // Next, resolve the node.
3588 ExprPath(ref maybe_qself, ref path) => {
3590 match self.resolve_possibly_assoc_item(expr.id,
3591 maybe_qself.as_ref(),
3595 // `<T>::a::b::c` is resolved by typeck alone.
3596 TypecheckRequired => {
3597 let method_name = path.segments.last().unwrap().identifier.name;
3598 let traits = self.get_traits_containing_item(method_name);
3599 self.trait_map.insert(expr.id, traits);
3600 visit::walk_expr(self, expr);
3603 ResolveAttempt(resolution) => resolution,
3606 // This is a local path in the value namespace. Walk through
3607 // scopes looking for it.
3608 if let Some(path_res) = resolution {
3609 // Check if struct variant
3610 if let DefVariant(_, _, true) = path_res.base_def {
3611 let path_name = path_names_to_string(path, 0);
3615 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3617 let msg = format!("did you mean to write: \
3618 `{} {{ /* fields */ }}`?",
3620 if self.emit_errors {
3621 self.session.fileline_help(expr.span, &msg);
3623 self.session.span_help(expr.span, &msg);
3626 // Write the result into the def map.
3627 debug!("(resolving expr) resolved `{}`",
3628 path_names_to_string(path, 0));
3630 // Partial resolutions will need the set of traits in scope,
3631 // so they can be completed during typeck.
3632 if path_res.depth != 0 {
3633 let method_name = path.segments.last().unwrap().identifier.name;
3634 let traits = self.get_traits_containing_item(method_name);
3635 self.trait_map.insert(expr.id, traits);
3638 self.record_def(expr.id, path_res);
3641 // Be helpful if the name refers to a struct
3642 // (The pattern matching def_tys where the id is in self.structs
3643 // matches on regular structs while excluding tuple- and enum-like
3644 // structs, which wouldn't result in this error.)
3645 let path_name = path_names_to_string(path, 0);
3646 let type_res = self.with_no_errors(|this| {
3647 this.resolve_path(expr.id, path, 0, TypeNS, false)
3649 match type_res.map(|r| r.base_def) {
3650 Some(DefTy(struct_id, _))
3651 if self.structs.contains_key(&struct_id) => {
3655 ResolutionError::StructVariantUsedAsFunction(
3659 let msg = format!("did you mean to write: \
3660 `{} {{ /* fields */ }}`?",
3662 if self.emit_errors {
3663 self.session.fileline_help(expr.span, &msg);
3665 self.session.span_help(expr.span, &msg);
3669 // Keep reporting some errors even if they're ignored above.
3670 self.resolve_path(expr.id, path, 0, ValueNS, true);
3672 let mut method_scope = false;
3673 self.value_ribs.iter().rev().all(|rib| {
3674 method_scope = match rib.kind {
3675 MethodRibKind => true,
3676 ItemRibKind | ConstantItemRibKind => false,
3677 _ => return true, // Keep advancing
3679 false // Stop advancing
3682 if method_scope && special_names::self_ == path_name {
3686 ResolutionError::SelfNotAvailableInStaticMethod
3689 let last_name = path.segments.last().unwrap().identifier.name;
3690 let mut msg = match self.find_fallback_in_self_type(last_name) {
3692 // limit search to 5 to reduce the number
3693 // of stupid suggestions
3694 self.find_best_match_for_name(&path_name)
3695 .map_or("".to_string(),
3696 |x| format!("`{}`", x))
3698 Field => format!("`self.{}`", path_name),
3701 format!("to call `self.{}`", path_name),
3702 TraitMethod(path_str) |
3703 StaticMethod(path_str) =>
3704 format!("to call `{}::{}`", path_str, path_name)
3707 if !msg.is_empty() {
3708 msg = format!(". Did you mean {}?", msg)
3713 ResolutionError::UnresolvedName(&*path_name,
3720 visit::walk_expr(self, expr);
3723 ExprStruct(ref path, _, _) => {
3724 // Resolve the path to the structure it goes to. We don't
3725 // check to ensure that the path is actually a structure; that
3726 // is checked later during typeck.
3727 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3728 Some(definition) => self.record_def(expr.id, definition),
3730 debug!("(resolving expression) didn't find struct def",);
3734 ResolutionError::DoesNotNameAStruct(
3735 &*path_names_to_string(path, 0))
3740 visit::walk_expr(self, expr);
3743 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3744 self.with_label_rib(|this| {
3745 let def_like = DlDef(DefLabel(expr.id));
3748 let rib = this.label_ribs.last_mut().unwrap();
3749 let renamed = mtwt::resolve(label);
3750 rib.bindings.insert(renamed, def_like);
3753 visit::walk_expr(this, expr);
3757 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3758 let renamed = mtwt::resolve(label);
3759 match self.search_label(renamed) {
3763 ResolutionError::UndeclaredLabel(&label.name.as_str()))
3765 Some(DlDef(def @ DefLabel(_))) => {
3766 // Since this def is a label, it is never read.
3767 self.record_def(expr.id, PathResolution {
3769 last_private: LastMod(AllPublic),
3774 self.session.span_bug(expr.span,
3775 "label wasn't mapped to a \
3782 visit::walk_expr(self, expr);
3787 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3789 ExprField(_, ident) => {
3790 // FIXME(#6890): Even though you can't treat a method like a
3791 // field, we need to add any trait methods we find that match
3792 // the field name so that we can do some nice error reporting
3793 // later on in typeck.
3794 let traits = self.get_traits_containing_item(ident.node.name);
3795 self.trait_map.insert(expr.id, traits);
3797 ExprMethodCall(ident, _, _) => {
3798 debug!("(recording candidate traits for expr) recording \
3801 let traits = self.get_traits_containing_item(ident.node.name);
3802 self.trait_map.insert(expr.id, traits);
3810 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3811 debug!("(getting traits containing item) looking for '{}'",
3814 fn add_trait_info(found_traits: &mut Vec<DefId>,
3815 trait_def_id: DefId,
3817 debug!("(adding trait info) found trait {}:{} for method '{}'",
3821 found_traits.push(trait_def_id);
3824 let mut found_traits = Vec::new();
3825 let mut search_module = self.current_module.clone();
3827 // Look for the current trait.
3828 match self.current_trait_ref {
3829 Some((trait_def_id, _)) => {
3830 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3831 add_trait_info(&mut found_traits, trait_def_id, name);
3834 None => {} // Nothing to do.
3837 // Look for trait children.
3838 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3841 for (_, child_names) in search_module.children.borrow().iter() {
3842 let def = match child_names.def_for_namespace(TypeNS) {
3846 let trait_def_id = match def {
3847 DefTrait(trait_def_id) => trait_def_id,
3850 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3851 add_trait_info(&mut found_traits, trait_def_id, name);
3856 // Look for imports.
3857 for (_, import) in search_module.import_resolutions.borrow().iter() {
3858 let target = match import.target_for_namespace(TypeNS) {
3860 Some(target) => target,
3862 let did = match target.bindings.def_for_namespace(TypeNS) {
3863 Some(DefTrait(trait_def_id)) => trait_def_id,
3864 Some(..) | None => continue,
3866 if self.trait_item_map.contains_key(&(name, did)) {
3867 add_trait_info(&mut found_traits, did, name);
3868 let id = import.type_id;
3869 self.used_imports.insert((id, TypeNS));
3870 let trait_name = self.get_trait_name(did);
3871 self.record_import_use(id, trait_name);
3872 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3873 self.used_crates.insert(kid);
3878 match search_module.parent_link.clone() {
3879 NoParentLink | ModuleParentLink(..) => break,
3880 BlockParentLink(parent_module, _) => {
3881 search_module = parent_module.upgrade().unwrap();
3889 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3890 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3891 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3892 "Import should only be used for `use` directives");
3894 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3895 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3896 self.session.span_bug(span, &format!("path resolved multiple times \
3897 ({:?} before, {:?} now)",
3898 prev_res, resolution));
3902 fn enforce_default_binding_mode(&mut self,
3904 pat_binding_mode: BindingMode,
3906 match pat_binding_mode {
3907 BindByValue(_) => {}
3911 ResolutionError::CannotUseRefBindingModeWith(descr));
3919 // Diagnostics are not particularly efficient, because they're rarely
3923 #[allow(dead_code)] // useful for debugging
3924 fn dump_module(&mut self, module_: Rc<Module>) {
3925 debug!("Dump of module `{}`:", module_to_string(&*module_));
3927 debug!("Children:");
3928 build_reduced_graph::populate_module_if_necessary(self, &module_);
3929 for (&name, _) in module_.children.borrow().iter() {
3930 debug!("* {}", name);
3933 debug!("Import resolutions:");
3934 let import_resolutions = module_.import_resolutions.borrow();
3935 for (&name, import_resolution) in import_resolutions.iter() {
3937 match import_resolution.target_for_namespace(ValueNS) {
3938 None => { value_repr = "".to_string(); }
3940 value_repr = " value:?".to_string();
3946 match import_resolution.target_for_namespace(TypeNS) {
3947 None => { type_repr = "".to_string(); }
3949 type_repr = " type:?".to_string();
3954 debug!("* {}:{}{}", name, value_repr, type_repr);
3960 fn names_to_string(names: &[Name]) -> String {
3961 let mut first = true;
3962 let mut result = String::new();
3967 result.push_str("::")
3969 result.push_str(&name.as_str());
3974 fn path_names_to_string(path: &Path, depth: usize) -> String {
3975 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3977 .map(|seg| seg.identifier.name)
3979 names_to_string(&names[..])
3982 /// A somewhat inefficient routine to obtain the name of a module.
3983 fn module_to_string(module: &Module) -> String {
3984 let mut names = Vec::new();
3986 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3987 match module.parent_link {
3989 ModuleParentLink(ref module, name) => {
3991 collect_mod(names, &*module.upgrade().unwrap());
3993 BlockParentLink(ref module, _) => {
3994 // danger, shouldn't be ident?
3995 names.push(special_idents::opaque.name);
3996 collect_mod(names, &*module.upgrade().unwrap());
4000 collect_mod(&mut names, module);
4002 if names.is_empty() {
4003 return "???".to_string();
4005 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
4009 pub struct CrateMap {
4010 pub def_map: DefMap,
4011 pub freevars: RefCell<FreevarMap>,
4012 pub export_map: ExportMap,
4013 pub trait_map: TraitMap,
4014 pub external_exports: ExternalExports,
4015 pub glob_map: Option<GlobMap>
4018 #[derive(PartialEq,Copy, Clone)]
4019 pub enum MakeGlobMap {
4024 /// Entry point to crate resolution.
4025 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4026 ast_map: &'a ast_map::Map<'tcx>,
4027 make_glob_map: MakeGlobMap)
4029 let krate = ast_map.krate();
4030 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
4032 resolver.resolve_crate(krate);
4033 session.abort_if_errors();
4035 check_unused::check_crate(&mut resolver, krate);
4038 def_map: resolver.def_map,
4039 freevars: resolver.freevars,
4040 export_map: resolver.export_map,
4041 trait_map: resolver.trait_map,
4042 external_exports: resolver.external_exports,
4043 glob_map: if resolver.make_glob_map {
4044 Some(resolver.glob_map)
4051 /// Builds a name resolution walker to be used within this module,
4052 /// or used externally, with an optional callback function.
4054 /// The callback takes a &mut bool which allows callbacks to end a
4055 /// walk when set to true, passing through the rest of the walk, while
4056 /// preserving the ribs + current module. This allows resolve_path
4057 /// calls to be made with the correct scope info. The node in the
4058 /// callback corresponds to the current node in the walk.
4059 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
4060 ast_map: &'a ast_map::Map<'tcx>,
4062 make_glob_map: MakeGlobMap,
4063 callback: Option<Box<Fn(ast_map::Node, &mut bool) -> bool>>)
4064 -> Resolver<'a, 'tcx> {
4065 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4067 resolver.callback = callback;
4069 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4070 session.abort_if_errors();
4072 resolve_imports::resolve_imports(&mut resolver);
4073 session.abort_if_errors();
4075 record_exports::record(&mut resolver);
4076 session.abort_if_errors();
4081 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }