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")]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "http://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 = "http://doc.rust-lang.org/nightly/")]
22 #![feature(associated_consts)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(slice_splits)]
27 #![feature(staged_api)]
29 #[macro_use] extern crate log;
30 #[macro_use] extern crate syntax;
31 #[macro_use] #[no_link] extern crate rustc_bitflags;
35 use self::PatternBindingMode::*;
36 use self::Namespace::*;
37 use self::NamespaceResult::*;
38 use self::NameDefinition::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::NameSearchType::*;
47 use self::BareIdentifierPatternResolution::*;
48 use self::ParentLink::*;
49 use self::ModuleKind::*;
50 use self::FallbackChecks::*;
53 use rustc::session::Session;
55 use rustc::metadata::csearch;
56 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
57 use rustc::middle::def::*;
58 use rustc::middle::pat_util::pat_bindings;
59 use rustc::middle::privacy::*;
60 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
61 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
62 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
63 use rustc::util::lev_distance::lev_distance;
65 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block};
66 use syntax::ast::{ConstImplItem, Crate, CrateNum};
67 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
68 use syntax::ast::{ExprLoop, ExprWhile, ExprMethodCall};
69 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
70 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
71 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
72 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
73 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
74 use syntax::ast::{Local, MethodImplItem, Name, NodeId};
75 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
76 use syntax::ast::{PatRange, PatStruct, Path, PrimTy};
77 use syntax::ast::{TraitRef, Ty, TyBool, TyChar, TyF32};
78 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt};
79 use syntax::ast::{TyPath, TyPtr};
80 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
81 use syntax::ast::TypeImplItem;
83 use syntax::ast_util::{local_def, walk_pat};
84 use syntax::attr::AttrMetaMethods;
85 use syntax::ext::mtwt;
86 use syntax::parse::token::{self, special_names, special_idents};
88 use syntax::codemap::{self, Span, Pos};
89 use syntax::visit::{self, Visitor};
91 use std::collections::{HashMap, HashSet};
92 use std::collections::hash_map::Entry::{Occupied, Vacant};
93 use std::cell::{Cell, RefCell};
95 use std::mem::replace;
96 use std::rc::{Rc, Weak};
99 use resolve_imports::{Target, ImportDirective, ImportResolution};
100 use resolve_imports::Shadowable;
102 // NB: This module needs to be declared first so diagnostics are
103 // registered before they are used.
108 mod build_reduced_graph;
111 pub enum ResolutionError<'a> {
112 /// error E0401: can't use type parameters from outer function
113 TypeParametersFromOuterFunction,
114 /// error E0402: cannot use an outer type parameter in this context
115 OuterTypeParameterContext,
116 /// error E0403: the name is already used for a type parameter in this type parameter list
117 NameAlreadyUsedInTypeParameterList(Name),
118 /// error E0404: is not a trait
119 IsNotATrait(&'a str),
120 /// error E0405: use of undeclared trait name
121 UndeclaredTraitName(&'a str),
122 /// error E0406: undeclared associated type
123 UndeclaredAssociatedType,
124 /// error E0407: method is not a member of trait
125 MethodNotMemberOfTrait(Name, &'a str),
126 /// error E0437: type is not a member of trait
127 TypeNotMemberOfTrait(Name, &'a str),
128 /// error E0438: const is not a member of trait
129 ConstNotMemberOfTrait(Name, &'a str),
130 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
131 VariableNotBoundInPattern(Name, usize),
132 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
133 VariableBoundWithDifferentMode(Name, usize),
134 /// error E0410: variable from pattern is not bound in pattern #1
135 VariableNotBoundInParentPattern(Name, usize),
136 /// error E0411: use of `Self` outside of an impl or trait
137 SelfUsedOutsideImplOrTrait,
138 /// error E0412: use of undeclared
139 UseOfUndeclared(&'a str, &'a str),
140 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
141 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
142 /// error E0414: only irrefutable patterns allowed here
143 OnlyIrrefutablePatternsAllowedHere,
144 /// error E0415: identifier is bound more than once in this parameter list
145 IdentifierBoundMoreThanOnceInParameterList(&'a str),
146 /// error E0416: identifier is bound more than once in the same pattern
147 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
148 /// error E0417: static variables cannot be referenced in a pattern
149 StaticVariableReference,
150 /// error E0418: is not an enum variant, struct or const
151 NotAnEnumVariantStructOrConst(&'a str),
152 /// error E0419: unresolved enum variant, struct or const
153 UnresolvedEnumVariantStructOrConst(&'a str),
154 /// error E0420: is not an associated const
155 NotAnAssociatedConst(&'a str),
156 /// error E0421: unresolved associated const
157 UnresolvedAssociatedConst(&'a str),
158 /// error E0422: does not name a struct
159 DoesNotNameAStruct(&'a str),
160 /// error E0423: is a struct variant name, but this expression uses it like a function name
161 StructVariantUsedAsFunction(&'a str),
162 /// error E0424: `self` is not available in a static method
163 SelfNotAvailableInStaticMethod,
164 /// error E0425: unresolved name
165 UnresolvedName(&'a str, &'a str),
166 /// error E0426: use of undeclared label
167 UndeclaredLabel(&'a str),
168 /// error E0427: cannot use `ref` binding mode with ...
169 CannotUseRefBindingModeWith(&'a str),
170 /// error E0428: duplicate definition
171 DuplicateDefinition(&'a str, Name),
172 /// error E0429: `self` imports are only allowed within a { } list
173 SelfImportsOnlyAllowedWithin,
174 /// error E0430: `self` import can only appear once in the list
175 SelfImportCanOnlyAppearOnceInTheList,
176 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
177 SelfImportOnlyInImportListWithNonEmptyPrefix,
178 /// error E0432: unresolved import
179 UnresolvedImport(Option<(&'a str, Option<&'a str>)>),
180 /// error E0433: failed to resolve
181 FailedToResolve(&'a str),
182 /// error E0434: can't capture dynamic environment in a fn item
183 CannotCaptureDynamicEnvironmentInFnItem,
184 /// error E0435: attempt to use a non-constant value in a constant
185 AttemptToUseNonConstantValueInConstant,
188 fn resolve_error<'b, 'a:'b, 'tcx:'a>(resolver: &'b Resolver<'a, 'tcx>, span: syntax::codemap::Span,
189 resolution_error: ResolutionError<'b>) {
190 if !resolver.emit_errors {
193 match resolution_error {
194 ResolutionError::TypeParametersFromOuterFunction => {
195 span_err!(resolver.session, span, E0401, "can't use type parameters from \
196 outer function; try using a local \
197 type parameter instead");
199 ResolutionError::OuterTypeParameterContext => {
200 span_err!(resolver.session, span, E0402,
201 "cannot use an outer type parameter in this context");
203 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
204 span_err!(resolver.session, span, E0403,
205 "the name `{}` is already used for a type \
206 parameter in this type parameter list", name);
208 ResolutionError::IsNotATrait(name) => {
209 span_err!(resolver.session, span, E0404,
210 "`{}` is not a trait",
213 ResolutionError::UndeclaredTraitName(name) => {
214 span_err!(resolver.session, span, E0405,
215 "use of undeclared trait name `{}`",
218 ResolutionError::UndeclaredAssociatedType => {
219 span_err!(resolver.session, span, E0406, "undeclared associated type");
221 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
222 span_err!(resolver.session, span, E0407,
223 "method `{}` is not a member of trait `{}`",
227 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
228 span_err!(resolver.session, span, E0437,
229 "type `{}` is not a member of trait `{}`",
233 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
234 span_err!(resolver.session, span, E0438,
235 "const `{}` is not a member of trait `{}`",
239 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
240 span_err!(resolver.session, span, E0408,
241 "variable `{}` from pattern #1 is not bound in pattern #{}",
245 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
246 span_err!(resolver.session, span, E0409,
247 "variable `{}` is bound with different \
248 mode in pattern #{} than in pattern #1",
252 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
253 span_err!(resolver.session, span, E0410,
254 "variable `{}` from pattern #{} is not bound in pattern #1",
258 ResolutionError::SelfUsedOutsideImplOrTrait => {
259 span_err!(resolver.session, span, E0411, "use of `Self` outside of an impl or trait");
261 ResolutionError::UseOfUndeclared(kind, name) => {
262 span_err!(resolver.session, span, E0412,
263 "use of undeclared {} `{}`",
267 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
268 span_err!(resolver.session, span, E0413,
269 "declaration of `{}` shadows an enum variant or unit-like struct in \
273 ResolutionError::OnlyIrrefutablePatternsAllowedHere => {
274 span_err!(resolver.session, span, E0414, "only irrefutable patterns allowed here");
276 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
277 span_err!(resolver.session, span, E0415,
278 "identifier `{}` is bound more than once in this parameter list",
281 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
282 span_err!(resolver.session, span, E0416,
283 "identifier `{}` is bound more than once in the same pattern",
286 ResolutionError::StaticVariableReference => {
287 span_err!(resolver.session, span, E0417, "static variables cannot be \
288 referenced in a pattern, \
289 use a `const` instead");
291 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
292 span_err!(resolver.session, span, E0418,
293 "`{}` is not an enum variant, struct or const",
296 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
297 span_err!(resolver.session, span, E0419,
298 "unresolved enum variant, struct or const `{}`",
301 ResolutionError::NotAnAssociatedConst(name) => {
302 span_err!(resolver.session, span, E0420,
303 "`{}` is not an associated const",
306 ResolutionError::UnresolvedAssociatedConst(name) => {
307 span_err!(resolver.session, span, E0421,
308 "unresolved associated const `{}`",
311 ResolutionError::DoesNotNameAStruct(name) => {
312 span_err!(resolver.session, span, E0422, "`{}` does not name a structure", name);
314 ResolutionError::StructVariantUsedAsFunction(path_name) => {
315 span_err!(resolver.session, span, E0423,
316 "`{}` is a struct variant name, but \
318 uses it like a function name",
321 ResolutionError::SelfNotAvailableInStaticMethod => {
322 span_err!(resolver.session, span, E0424, "`self` is not available in a static method. \
323 Maybe a `self` argument is missing?");
325 ResolutionError::UnresolvedName(path, name) => {
326 span_err!(resolver.session, span, E0425,
327 "unresolved name `{}`{}",
331 ResolutionError::UndeclaredLabel(name) => {
332 span_err!(resolver.session, span, E0426,
333 "use of undeclared label `{}`",
336 ResolutionError::CannotUseRefBindingModeWith(descr) => {
337 span_err!(resolver.session, span, E0427,
338 "cannot use `ref` binding mode with {}",
341 ResolutionError::DuplicateDefinition(namespace, name) => {
342 span_err!(resolver.session, span, E0428,
343 "duplicate definition of {} `{}`",
347 ResolutionError::SelfImportsOnlyAllowedWithin => {
348 span_err!(resolver.session, span, E0429, "{}",
349 "`self` imports are only allowed within a { } list");
351 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
352 span_err!(resolver.session, span, E0430,
353 "`self` import can only appear once in the list");
355 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
356 span_err!(resolver.session, span, E0431,
357 "`self` import can only appear in an import list with a \
360 ResolutionError::UnresolvedImport(name) => {
361 let msg = match name {
362 Some((n, Some(p))) => format!("unresolved import `{}`{}", n, p),
363 Some((n, None)) => format!("unresolved import (maybe you meant `{}::*`?)", n),
364 None => "unresolved import".to_owned()
366 span_err!(resolver.session, span, E0432, "{}", msg);
368 ResolutionError::FailedToResolve(msg) => {
369 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
371 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
372 span_err!(resolver.session, span, E0434, "{}",
373 "can't capture dynamic environment in a fn item; \
374 use the || { ... } closure form instead");
376 ResolutionError::AttemptToUseNonConstantValueInConstant =>{
377 span_err!(resolver.session, span, E0435,
378 "attempt to use a non-constant value in a constant");
383 #[derive(Copy, Clone)]
386 binding_mode: BindingMode,
389 // Map from the name in a pattern to its binding mode.
390 type BindingMap = HashMap<Name, BindingInfo>;
392 #[derive(Copy, Clone, PartialEq)]
393 enum PatternBindingMode {
395 LocalIrrefutableMode,
396 ArgumentIrrefutableMode,
399 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
405 /// A NamespaceResult represents the result of resolving an import in
406 /// a particular namespace. The result is either definitely-resolved,
407 /// definitely- unresolved, or unknown.
409 enum NamespaceResult {
410 /// Means that resolve hasn't gathered enough information yet to determine
411 /// whether the name is bound in this namespace. (That is, it hasn't
412 /// resolved all `use` directives yet.)
414 /// Means that resolve has determined that the name is definitely
415 /// not bound in the namespace.
417 /// Means that resolve has determined that the name is bound in the Module
418 /// argument, and specified by the NameBindings argument.
419 BoundResult(Rc<Module>, Rc<NameBindings>)
422 impl NamespaceResult {
423 fn is_unknown(&self) -> bool {
425 UnknownResult => true,
429 fn is_unbound(&self) -> bool {
431 UnboundResult => true,
437 enum NameDefinition {
438 // The name was unbound.
440 // The name identifies an immediate child.
441 ChildNameDefinition(Def, LastPrivate),
442 // The name identifies an import.
443 ImportNameDefinition(Def, LastPrivate),
446 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
447 fn visit_item(&mut self, item: &Item) {
448 self.resolve_item(item);
450 fn visit_arm(&mut self, arm: &Arm) {
451 self.resolve_arm(arm);
453 fn visit_block(&mut self, block: &Block) {
454 self.resolve_block(block);
456 fn visit_expr(&mut self, expr: &Expr) {
457 self.resolve_expr(expr);
459 fn visit_local(&mut self, local: &Local) {
460 self.resolve_local(local);
462 fn visit_ty(&mut self, ty: &Ty) {
463 self.resolve_type(ty);
465 fn visit_generics(&mut self, generics: &Generics) {
466 self.resolve_generics(generics);
468 fn visit_poly_trait_ref(&mut self,
469 tref: &ast::PolyTraitRef,
470 m: &ast::TraitBoundModifier) {
471 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
472 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
473 Err(_) => { /* error already reported */ }
475 visit::walk_poly_trait_ref(self, tref, m);
477 fn visit_variant(&mut self, variant: &ast::Variant, generics: &Generics) {
478 if let Some(ref dis_expr) = variant.node.disr_expr {
479 // resolve the discriminator expr as a constant
480 self.with_constant_rib(|this| {
481 this.visit_expr(&**dis_expr);
485 // `visit::walk_variant` without the discriminant expression.
486 match variant.node.kind {
487 ast::TupleVariantKind(ref variant_arguments) => {
488 for variant_argument in variant_arguments {
489 self.visit_ty(&*variant_argument.ty);
492 ast::StructVariantKind(ref struct_definition) => {
493 self.visit_struct_def(&**struct_definition,
500 fn visit_foreign_item(&mut self, foreign_item: &ast::ForeignItem) {
501 let type_parameters = match foreign_item.node {
502 ForeignItemFn(_, ref generics) => {
503 HasTypeParameters(generics, FnSpace, ItemRibKind)
505 ForeignItemStatic(..) => NoTypeParameters
507 self.with_type_parameter_rib(type_parameters, |this| {
508 visit::walk_foreign_item(this, foreign_item);
511 fn visit_fn(&mut self,
512 function_kind: visit::FnKind<'v>,
513 declaration: &'v FnDecl,
517 let rib_kind = match function_kind {
518 visit::FkItemFn(_, generics, _, _, _, _) => {
519 self.visit_generics(generics);
522 visit::FkMethod(_, sig, _) => {
523 self.visit_generics(&sig.generics);
524 self.visit_explicit_self(&sig.explicit_self);
527 visit::FkFnBlock(..) => ClosureRibKind(node_id)
529 self.resolve_function(rib_kind, declaration, block);
533 type ErrorMessage = Option<(Span, String)>;
535 enum ResolveResult<T> {
536 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
537 Indeterminate, // Couldn't determine due to unresolved globs.
538 Success(T) // Successfully resolved the import.
541 impl<T> ResolveResult<T> {
542 fn indeterminate(&self) -> bool {
543 match *self { Indeterminate => true, _ => false }
547 enum FallbackSuggestion {
552 StaticMethod(String),
556 #[derive(Copy, Clone)]
557 enum TypeParameters<'a> {
563 // Identifies the things that these parameters
564 // were declared on (type, fn, etc)
567 // The kind of the rib used for type parameters.
571 // The rib kind controls the translation of local
572 // definitions (`DefLocal`) to upvars (`DefUpvar`).
573 #[derive(Copy, Clone, Debug)]
575 // No translation needs to be applied.
578 // We passed through a closure scope at the given node ID.
579 // Translate upvars as appropriate.
580 ClosureRibKind(NodeId /* func id */),
582 // We passed through an impl or trait and are now in one of its
583 // methods. Allow references to ty params that impl or trait
584 // binds. Disallow any other upvars (including other ty params that are
588 // We passed through an item scope. Disallow upvars.
591 // We're in a constant item. Can't refer to dynamic stuff.
595 #[derive(Copy, Clone)]
596 enum UseLexicalScopeFlag {
601 enum ModulePrefixResult {
603 PrefixFound(Rc<Module>, usize)
606 #[derive(Copy, Clone)]
607 enum AssocItemResolveResult {
608 /// Syntax such as `<T>::item`, which can't be resolved until type
611 /// We should have been able to resolve the associated item.
612 ResolveAttempt(Option<PathResolution>),
615 #[derive(Copy, Clone, PartialEq)]
616 enum NameSearchType {
617 /// We're doing a name search in order to resolve a `use` directive.
620 /// We're doing a name search in order to resolve a path type, a path
621 /// expression, or a path pattern.
625 #[derive(Copy, Clone)]
626 enum BareIdentifierPatternResolution {
627 FoundStructOrEnumVariant(Def, LastPrivate),
628 FoundConst(Def, LastPrivate),
629 BareIdentifierPatternUnresolved
635 bindings: HashMap<Name, DefLike>,
640 fn new(kind: RibKind) -> Rib {
642 bindings: HashMap::new(),
648 /// The link from a module up to its nearest parent node.
649 #[derive(Clone,Debug)]
652 ModuleParentLink(Weak<Module>, Name),
653 BlockParentLink(Weak<Module>, NodeId)
656 /// The type of module this is.
657 #[derive(Copy, Clone, PartialEq, Debug)]
666 /// One node in the tree of modules.
668 parent_link: ParentLink,
669 def_id: Cell<Option<DefId>>,
670 kind: Cell<ModuleKind>,
673 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
674 imports: RefCell<Vec<ImportDirective>>,
676 // The external module children of this node that were declared with
678 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
680 // The anonymous children of this node. Anonymous children are pseudo-
681 // modules that are implicitly created around items contained within
684 // For example, if we have this:
692 // There will be an anonymous module created around `g` with the ID of the
693 // entry block for `f`.
694 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
696 // The status of resolving each import in this module.
697 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
699 // The number of unresolved globs that this module exports.
700 glob_count: Cell<usize>,
702 // The index of the import we're resolving.
703 resolved_import_count: Cell<usize>,
705 // Whether this module is populated. If not populated, any attempt to
706 // access the children must be preceded with a
707 // `populate_module_if_necessary` call.
708 populated: Cell<bool>,
712 fn new(parent_link: ParentLink,
713 def_id: Option<DefId>,
719 parent_link: parent_link,
720 def_id: Cell::new(def_id),
721 kind: Cell::new(kind),
722 is_public: is_public,
723 children: RefCell::new(HashMap::new()),
724 imports: RefCell::new(Vec::new()),
725 external_module_children: RefCell::new(HashMap::new()),
726 anonymous_children: RefCell::new(NodeMap()),
727 import_resolutions: RefCell::new(HashMap::new()),
728 glob_count: Cell::new(0),
729 resolved_import_count: Cell::new(0),
730 populated: Cell::new(!external),
734 fn all_imports_resolved(&self) -> bool {
735 self.imports.borrow().len() == self.resolved_import_count.get()
739 impl fmt::Debug for Module {
740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
741 write!(f, "{:?}, kind: {:?}, {}",
744 if self.is_public { "public" } else { "private" } )
750 flags DefModifiers: u8 {
751 const PUBLIC = 1 << 0,
752 const IMPORTABLE = 1 << 1,
756 // Records a possibly-private type definition.
757 #[derive(Clone,Debug)]
759 modifiers: DefModifiers, // see note in ImportResolution about how to use this
760 module_def: Option<Rc<Module>>,
761 type_def: Option<Def>,
762 type_span: Option<Span>
765 // Records a possibly-private value definition.
766 #[derive(Clone, Copy, Debug)]
768 modifiers: DefModifiers, // see note in ImportResolution about how to use this
770 value_span: Option<Span>,
773 // Records the definitions (at most one for each namespace) that a name is
776 pub struct NameBindings {
777 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
778 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
782 fn new() -> NameBindings {
784 type_def: RefCell::new(None),
785 value_def: RefCell::new(None),
789 /// Creates a new module in this set of name bindings.
790 fn define_module(&self,
791 parent_link: ParentLink,
792 def_id: Option<DefId>,
797 // Merges the module with the existing type def or creates a new one.
798 let modifiers = if is_public {
801 DefModifiers::empty()
802 } | DefModifiers::IMPORTABLE;
803 let module_ = Rc::new(Module::new(parent_link,
808 let type_def = self.type_def.borrow().clone();
811 *self.type_def.borrow_mut() = Some(TypeNsDef {
812 modifiers: modifiers,
813 module_def: Some(module_),
819 *self.type_def.borrow_mut() = Some(TypeNsDef {
820 modifiers: modifiers,
821 module_def: Some(module_),
823 type_def: type_def.type_def
829 /// Sets the kind of the module, creating a new one if necessary.
830 fn set_module_kind(&self,
831 parent_link: ParentLink,
832 def_id: Option<DefId>,
837 let modifiers = if is_public {
840 DefModifiers::empty()
841 } | DefModifiers::IMPORTABLE;
842 let type_def = self.type_def.borrow().clone();
845 let module = Module::new(parent_link,
850 *self.type_def.borrow_mut() = Some(TypeNsDef {
851 modifiers: modifiers,
852 module_def: Some(Rc::new(module)),
858 match type_def.module_def {
860 let module = Module::new(parent_link,
865 *self.type_def.borrow_mut() = Some(TypeNsDef {
866 modifiers: modifiers,
867 module_def: Some(Rc::new(module)),
868 type_def: type_def.type_def,
872 Some(module_def) => module_def.kind.set(kind),
878 /// Records a type definition.
879 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
880 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
881 // Merges the type with the existing type def or creates a new one.
882 let type_def = self.type_def.borrow().clone();
885 *self.type_def.borrow_mut() = Some(TypeNsDef {
889 modifiers: modifiers,
893 *self.type_def.borrow_mut() = Some(TypeNsDef {
894 module_def: type_def.module_def,
897 modifiers: modifiers,
903 /// Records a value definition.
904 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
905 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
906 *self.value_def.borrow_mut() = Some(ValueNsDef {
908 value_span: Some(sp),
909 modifiers: modifiers,
913 /// Returns the module node if applicable.
914 fn get_module_if_available(&self) -> Option<Rc<Module>> {
915 match *self.type_def.borrow() {
916 Some(ref type_def) => type_def.module_def.clone(),
921 /// Returns the module node. Panics if this node does not have a module
923 fn get_module(&self) -> Rc<Module> {
924 match self.get_module_if_available() {
926 panic!("get_module called on a node with no module \
929 Some(module_def) => module_def
933 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
935 TypeNS => return self.type_def.borrow().is_some(),
936 ValueNS => return self.value_def.borrow().is_some()
940 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
941 self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
944 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
946 TypeNS => match *self.type_def.borrow() {
947 Some(ref def) => def.modifiers.contains(modifiers), None => false
949 ValueNS => match *self.value_def.borrow() {
950 Some(ref def) => def.modifiers.contains(modifiers), None => false
955 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
958 match *self.type_def.borrow() {
960 Some(ref type_def) => {
961 match type_def.type_def {
962 Some(type_def) => Some(type_def),
964 match type_def.module_def {
965 Some(ref module) => {
966 match module.def_id.get() {
967 Some(did) => Some(DefMod(did)),
979 match *self.value_def.borrow() {
981 Some(value_def) => Some(value_def.def)
987 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
988 if self.defined_in_namespace(namespace) {
991 match *self.type_def.borrow() {
993 Some(ref type_def) => type_def.type_span
997 match *self.value_def.borrow() {
999 Some(ref value_def) => value_def.value_span
1008 fn is_public(&self, namespace: Namespace) -> bool {
1011 let type_def = self.type_def.borrow();
1012 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
1015 let value_def = self.value_def.borrow();
1016 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
1022 /// Interns the names of the primitive types.
1023 struct PrimitiveTypeTable {
1024 primitive_types: HashMap<Name, PrimTy>,
1027 impl PrimitiveTypeTable {
1028 fn new() -> PrimitiveTypeTable {
1029 let mut table = PrimitiveTypeTable {
1030 primitive_types: HashMap::new()
1033 table.intern("bool", TyBool);
1034 table.intern("char", TyChar);
1035 table.intern("f32", TyFloat(TyF32));
1036 table.intern("f64", TyFloat(TyF64));
1037 table.intern("isize", TyInt(TyIs));
1038 table.intern("i8", TyInt(TyI8));
1039 table.intern("i16", TyInt(TyI16));
1040 table.intern("i32", TyInt(TyI32));
1041 table.intern("i64", TyInt(TyI64));
1042 table.intern("str", TyStr);
1043 table.intern("usize", TyUint(TyUs));
1044 table.intern("u8", TyUint(TyU8));
1045 table.intern("u16", TyUint(TyU16));
1046 table.intern("u32", TyUint(TyU32));
1047 table.intern("u64", TyUint(TyU64));
1052 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1053 self.primitive_types.insert(token::intern(string), primitive_type);
1057 /// The main resolver class.
1058 pub struct Resolver<'a, 'tcx:'a> {
1059 session: &'a Session,
1061 ast_map: &'a ast_map::Map<'tcx>,
1063 graph_root: NameBindings,
1065 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1067 structs: FnvHashMap<DefId, Vec<Name>>,
1069 // The number of imports that are currently unresolved.
1070 unresolved_imports: usize,
1072 // The module that represents the current item scope.
1073 current_module: Rc<Module>,
1075 // The current set of local scopes, for values.
1076 // FIXME #4948: Reuse ribs to avoid allocation.
1077 value_ribs: Vec<Rib>,
1079 // The current set of local scopes, for types.
1080 type_ribs: Vec<Rib>,
1082 // The current set of local scopes, for labels.
1083 label_ribs: Vec<Rib>,
1085 // The trait that the current context can refer to.
1086 current_trait_ref: Option<(DefId, TraitRef)>,
1088 // The current self type if inside an impl (used for better errors).
1089 current_self_type: Option<Ty>,
1091 // The idents for the primitive types.
1092 primitive_type_table: PrimitiveTypeTable,
1095 freevars: RefCell<FreevarMap>,
1096 freevars_seen: RefCell<NodeMap<NodeSet>>,
1097 export_map: ExportMap,
1098 trait_map: TraitMap,
1099 external_exports: ExternalExports,
1101 // Whether or not to print error messages. Can be set to true
1102 // when getting additional info for error message suggestions,
1103 // so as to avoid printing duplicate errors
1106 make_glob_map: bool,
1107 // Maps imports to the names of items actually imported (this actually maps
1108 // all imports, but only glob imports are actually interesting).
1111 used_imports: HashSet<(NodeId, Namespace)>,
1112 used_crates: HashSet<CrateNum>,
1115 #[derive(PartialEq)]
1116 enum FallbackChecks {
1121 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1122 fn new(session: &'a Session,
1123 ast_map: &'a ast_map::Map<'tcx>,
1125 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
1126 let graph_root = NameBindings::new();
1128 graph_root.define_module(NoParentLink,
1129 Some(DefId { krate: 0, node: 0 }),
1135 let current_module = graph_root.get_module();
1142 // The outermost module has def ID 0; this is not reflected in the
1145 graph_root: graph_root,
1147 trait_item_map: FnvHashMap(),
1148 structs: FnvHashMap(),
1150 unresolved_imports: 0,
1152 current_module: current_module,
1153 value_ribs: Vec::new(),
1154 type_ribs: Vec::new(),
1155 label_ribs: Vec::new(),
1157 current_trait_ref: None,
1158 current_self_type: None,
1160 primitive_type_table: PrimitiveTypeTable::new(),
1162 def_map: RefCell::new(NodeMap()),
1163 freevars: RefCell::new(NodeMap()),
1164 freevars_seen: RefCell::new(NodeMap()),
1165 export_map: NodeMap(),
1166 trait_map: NodeMap(),
1167 used_imports: HashSet::new(),
1168 used_crates: HashSet::new(),
1169 external_exports: DefIdSet(),
1172 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1173 glob_map: HashMap::new(),
1178 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1179 if !self.make_glob_map {
1182 if self.glob_map.contains_key(&import_id) {
1183 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1187 let mut new_set = HashSet::new();
1188 new_set.insert(name);
1189 self.glob_map.insert(import_id, new_set);
1192 fn get_trait_name(&self, did: DefId) -> Name {
1193 if did.krate == ast::LOCAL_CRATE {
1194 self.ast_map.expect_item(did.node).ident.name
1196 csearch::get_trait_name(&self.session.cstore, did)
1200 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1202 type_def: RefCell::new(Some(TypeNsDef {
1203 modifiers: DefModifiers::IMPORTABLE,
1204 module_def: Some(module),
1208 value_def: RefCell::new(None),
1212 /// Checks that the names of external crates don't collide with other
1213 /// external crates.
1214 fn check_for_conflicts_between_external_crates(&self,
1218 if module.external_module_children.borrow().contains_key(&name) {
1219 span_err!(self.session, span, E0259,
1220 "an external crate named `{}` has already \
1221 been imported into this module",
1226 /// Checks that the names of items don't collide with external crates.
1227 fn check_for_conflicts_between_external_crates_and_items(&self,
1231 if module.external_module_children.borrow().contains_key(&name) {
1232 span_err!(self.session, span, E0260,
1233 "the name `{}` conflicts with an external \
1234 crate that has been imported into this \
1240 /// Resolves the given module path from the given root `module_`.
1241 fn resolve_module_path_from_root(&mut self,
1242 module_: Rc<Module>,
1243 module_path: &[Name],
1246 name_search_type: NameSearchType,
1248 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1249 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1250 -> Option<Rc<Module>> {
1251 match module.external_module_children.borrow().get(&needle) {
1252 Some(_) => Some(module.clone()),
1253 None => match module.parent_link {
1254 ModuleParentLink(ref parent, _) => {
1255 search_parent_externals(needle, &parent.upgrade().unwrap())
1262 let mut search_module = module_;
1263 let mut index = index;
1264 let module_path_len = module_path.len();
1265 let mut closest_private = lp;
1267 // Resolve the module part of the path. This does not involve looking
1268 // upward though scope chains; we simply resolve names directly in
1269 // modules as we go.
1270 while index < module_path_len {
1271 let name = module_path[index];
1272 match self.resolve_name_in_module(search_module.clone(),
1278 let segment_name = name.as_str();
1279 let module_name = module_to_string(&*search_module);
1280 let mut span = span;
1281 let msg = if "???" == &module_name[..] {
1282 span.hi = span.lo + Pos::from_usize(segment_name.len());
1284 match search_parent_externals(name,
1285 &self.current_module) {
1287 let path_str = names_to_string(module_path);
1288 let target_mod_str = module_to_string(&*module);
1289 let current_mod_str =
1290 module_to_string(&*self.current_module);
1292 let prefix = if target_mod_str == current_mod_str {
1293 "self::".to_string()
1295 format!("{}::", target_mod_str)
1298 format!("Did you mean `{}{}`?", prefix, path_str)
1300 None => format!("Maybe a missing `extern crate {}`?",
1304 format!("Could not find `{}` in `{}`",
1309 return Failed(Some((span, msg)));
1311 Failed(err) => return Failed(err),
1313 debug!("(resolving module path for import) module \
1314 resolution is indeterminate: {}",
1316 return Indeterminate;
1318 Success((target, used_proxy)) => {
1319 // Check to see whether there are type bindings, and, if
1320 // so, whether there is a module within.
1321 match *target.bindings.type_def.borrow() {
1322 Some(ref type_def) => {
1323 match type_def.module_def {
1325 let msg = format!("Not a module `{}`",
1328 return Failed(Some((span, msg)));
1330 Some(ref module_def) => {
1331 search_module = module_def.clone();
1333 // track extern crates for unused_extern_crate lint
1334 if let Some(did) = module_def.def_id.get() {
1335 self.used_crates.insert(did.krate);
1338 // Keep track of the closest
1339 // private module used when
1340 // resolving this import chain.
1341 if !used_proxy && !search_module.is_public {
1342 if let Some(did) = search_module.def_id.get() {
1343 closest_private = LastMod(DependsOn(did));
1350 // There are no type bindings at all.
1351 let msg = format!("Not a module `{}`",
1353 return Failed(Some((span, msg)));
1362 return Success((search_module, closest_private));
1365 /// Attempts to resolve the module part of an import directive or path
1366 /// rooted at the given module.
1368 /// On success, returns the resolved module, and the closest *private*
1369 /// module found to the destination when resolving this path.
1370 fn resolve_module_path(&mut self,
1371 module_: Rc<Module>,
1372 module_path: &[Name],
1373 use_lexical_scope: UseLexicalScopeFlag,
1375 name_search_type: NameSearchType)
1376 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1377 let module_path_len = module_path.len();
1378 assert!(module_path_len > 0);
1380 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1381 names_to_string(module_path),
1382 module_to_string(&*module_));
1384 // Resolve the module prefix, if any.
1385 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1391 match module_prefix_result {
1393 let mpath = names_to_string(module_path);
1394 let mpath = &mpath[..];
1395 match mpath.rfind(':') {
1397 let msg = format!("Could not find `{}` in `{}`",
1398 // idx +- 1 to account for the
1399 // colons on either side
1402 return Failed(Some((span, msg)));
1409 Failed(err) => return Failed(err),
1411 debug!("(resolving module path for import) indeterminate; \
1413 return Indeterminate;
1415 Success(NoPrefixFound) => {
1416 // There was no prefix, so we're considering the first element
1417 // of the path. How we handle this depends on whether we were
1418 // instructed to use lexical scope or not.
1419 match use_lexical_scope {
1420 DontUseLexicalScope => {
1421 // This is a crate-relative path. We will start the
1422 // resolution process at index zero.
1423 search_module = self.graph_root.get_module();
1425 last_private = LastMod(AllPublic);
1427 UseLexicalScope => {
1428 // This is not a crate-relative path. We resolve the
1429 // first component of the path in the current lexical
1430 // scope and then proceed to resolve below that.
1431 match self.resolve_module_in_lexical_scope(module_,
1433 Failed(err) => return Failed(err),
1435 debug!("(resolving module path for import) \
1436 indeterminate; bailing");
1437 return Indeterminate;
1439 Success(containing_module) => {
1440 search_module = containing_module;
1442 last_private = LastMod(AllPublic);
1448 Success(PrefixFound(ref containing_module, index)) => {
1449 search_module = containing_module.clone();
1450 start_index = index;
1451 last_private = LastMod(DependsOn(containing_module.def_id
1457 self.resolve_module_path_from_root(search_module,
1465 /// Invariant: This must only be called during main resolution, not during
1466 /// import resolution.
1467 fn resolve_item_in_lexical_scope(&mut self,
1468 module_: Rc<Module>,
1470 namespace: Namespace)
1471 -> ResolveResult<(Target, bool)> {
1472 debug!("(resolving item in lexical scope) resolving `{}` in \
1473 namespace {:?} in `{}`",
1476 module_to_string(&*module_));
1478 // The current module node is handled specially. First, check for
1479 // its immediate children.
1480 build_reduced_graph::populate_module_if_necessary(self, &module_);
1482 match module_.children.borrow().get(&name) {
1484 if name_bindings.defined_in_namespace(namespace) => {
1485 debug!("top name bindings succeeded");
1486 return Success((Target::new(module_.clone(),
1487 name_bindings.clone(),
1491 Some(_) | None => { /* Not found; continue. */ }
1494 // Now check for its import directives. We don't have to have resolved
1495 // all its imports in the usual way; this is because chains of
1496 // adjacent import statements are processed as though they mutated the
1498 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1499 match (*import_resolution).target_for_namespace(namespace) {
1501 // Not found; continue.
1502 debug!("(resolving item in lexical scope) found \
1503 import resolution, but not in namespace {:?}",
1507 debug!("(resolving item in lexical scope) using \
1508 import resolution");
1509 // track used imports and extern crates as well
1510 let id = import_resolution.id(namespace);
1511 self.used_imports.insert((id, namespace));
1512 self.record_import_use(id, name);
1513 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1514 self.used_crates.insert(kid);
1516 return Success((target, false));
1521 // Search for external modules.
1522 if namespace == TypeNS {
1523 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1524 let child = module_.external_module_children.borrow().get(&name).cloned();
1525 if let Some(module) = child {
1527 Rc::new(Resolver::create_name_bindings_from_module(module));
1528 debug!("lower name bindings succeeded");
1529 return Success((Target::new(module_,
1536 // Finally, proceed up the scope chain looking for parent modules.
1537 let mut search_module = module_;
1539 // Go to the next parent.
1540 match search_module.parent_link.clone() {
1542 // No more parents. This module was unresolved.
1543 debug!("(resolving item in lexical scope) unresolved \
1545 return Failed(None);
1547 ModuleParentLink(parent_module_node, _) => {
1548 match search_module.kind.get() {
1549 NormalModuleKind => {
1550 // We stop the search here.
1551 debug!("(resolving item in lexical \
1552 scope) unresolved module: not \
1553 searching through module \
1555 return Failed(None);
1560 AnonymousModuleKind => {
1561 search_module = parent_module_node.upgrade().unwrap();
1565 BlockParentLink(ref parent_module_node, _) => {
1566 search_module = parent_module_node.upgrade().unwrap();
1570 // Resolve the name in the parent module.
1571 match self.resolve_name_in_module(search_module.clone(),
1576 Failed(Some((span, msg))) => {
1577 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1579 Failed(None) => (), // Continue up the search chain.
1581 // We couldn't see through the higher scope because of an
1582 // unresolved import higher up. Bail.
1584 debug!("(resolving item in lexical scope) indeterminate \
1585 higher scope; bailing");
1586 return Indeterminate;
1588 Success((target, used_reexport)) => {
1589 // We found the module.
1590 debug!("(resolving item in lexical scope) found name \
1592 return Success((target, used_reexport));
1598 /// Resolves a module name in the current lexical scope.
1599 fn resolve_module_in_lexical_scope(&mut self,
1600 module_: Rc<Module>,
1602 -> ResolveResult<Rc<Module>> {
1603 // If this module is an anonymous module, resolve the item in the
1604 // lexical scope. Otherwise, resolve the item from the crate root.
1605 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1606 match resolve_result {
1607 Success((target, _)) => {
1608 let bindings = &*target.bindings;
1609 match *bindings.type_def.borrow() {
1610 Some(ref type_def) => {
1611 match type_def.module_def {
1613 debug!("!!! (resolving module in lexical \
1614 scope) module wasn't actually a \
1616 return Failed(None);
1618 Some(ref module_def) => {
1619 return Success(module_def.clone());
1624 debug!("!!! (resolving module in lexical scope) module
1625 wasn't actually a module!");
1626 return Failed(None);
1631 debug!("(resolving module in lexical scope) indeterminate; \
1633 return Indeterminate;
1636 debug!("(resolving module in lexical scope) failed to resolve");
1642 /// Returns the nearest normal module parent of the given module.
1643 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1644 -> Option<Rc<Module>> {
1645 let mut module_ = module_;
1647 match module_.parent_link.clone() {
1648 NoParentLink => return None,
1649 ModuleParentLink(new_module, _) |
1650 BlockParentLink(new_module, _) => {
1651 let new_module = new_module.upgrade().unwrap();
1652 match new_module.kind.get() {
1653 NormalModuleKind => return Some(new_module),
1657 AnonymousModuleKind => module_ = new_module,
1664 /// Returns the nearest normal module parent of the given module, or the
1665 /// module itself if it is a normal module.
1666 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1668 match module_.kind.get() {
1669 NormalModuleKind => return module_,
1673 AnonymousModuleKind => {
1674 match self.get_nearest_normal_module_parent(module_.clone()) {
1676 Some(new_module) => new_module
1682 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1683 /// (b) some chain of `super::`.
1684 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1685 fn resolve_module_prefix(&mut self,
1686 module_: Rc<Module>,
1687 module_path: &[Name])
1688 -> ResolveResult<ModulePrefixResult> {
1689 // Start at the current module if we see `self` or `super`, or at the
1690 // top of the crate otherwise.
1691 let mut i = match &*module_path[0].as_str() {
1694 _ => return Success(NoPrefixFound),
1696 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1698 // Now loop through all the `super`s we find.
1699 while i < module_path.len() && "super" == module_path[i].as_str() {
1700 debug!("(resolving module prefix) resolving `super` at {}",
1701 module_to_string(&*containing_module));
1702 match self.get_nearest_normal_module_parent(containing_module) {
1703 None => return Failed(None),
1704 Some(new_module) => {
1705 containing_module = new_module;
1711 debug!("(resolving module prefix) finished resolving prefix at {}",
1712 module_to_string(&*containing_module));
1714 return Success(PrefixFound(containing_module, i));
1717 /// Attempts to resolve the supplied name in the given module for the
1718 /// given namespace. If successful, returns the target corresponding to
1721 /// The boolean returned on success is an indicator of whether this lookup
1722 /// passed through a public re-export proxy.
1723 fn resolve_name_in_module(&mut self,
1724 module_: Rc<Module>,
1726 namespace: Namespace,
1727 name_search_type: NameSearchType,
1728 allow_private_imports: bool)
1729 -> ResolveResult<(Target, bool)> {
1730 debug!("(resolving name in module) resolving `{}` in `{}`",
1732 module_to_string(&*module_));
1734 // First, check the direct children of the module.
1735 build_reduced_graph::populate_module_if_necessary(self, &module_);
1737 match module_.children.borrow().get(&name) {
1739 if name_bindings.defined_in_namespace(namespace) => {
1740 debug!("(resolving name in module) found node as child");
1741 return Success((Target::new(module_.clone(),
1742 name_bindings.clone(),
1751 // Next, check the module's imports if necessary.
1753 // If this is a search of all imports, we should be done with glob
1754 // resolution at this point.
1755 if name_search_type == PathSearch {
1756 assert_eq!(module_.glob_count.get(), 0);
1759 // Check the list of resolved imports.
1760 match module_.import_resolutions.borrow().get(&name) {
1761 Some(import_resolution) if allow_private_imports ||
1762 import_resolution.is_public => {
1764 if import_resolution.is_public &&
1765 import_resolution.outstanding_references != 0 {
1766 debug!("(resolving name in module) import \
1767 unresolved; bailing out");
1768 return Indeterminate;
1770 match import_resolution.target_for_namespace(namespace) {
1772 debug!("(resolving name in module) name found, \
1773 but not in namespace {:?}",
1777 debug!("(resolving name in module) resolved to \
1779 // track used imports and extern crates as well
1780 let id = import_resolution.id(namespace);
1781 self.used_imports.insert((id, namespace));
1782 self.record_import_use(id, name);
1783 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1784 self.used_crates.insert(kid);
1786 return Success((target, true));
1790 Some(..) | None => {} // Continue.
1793 // Finally, search through external children.
1794 if namespace == TypeNS {
1795 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1796 let child = module_.external_module_children.borrow().get(&name).cloned();
1797 if let Some(module) = child {
1799 Rc::new(Resolver::create_name_bindings_from_module(module));
1800 return Success((Target::new(module_,
1807 // We're out of luck.
1808 debug!("(resolving name in module) failed to resolve `{}`",
1810 return Failed(None);
1813 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1814 let index = module_.resolved_import_count.get();
1815 let imports = module_.imports.borrow();
1816 let import_count = imports.len();
1817 if index != import_count {
1818 let sn = self.session
1820 .span_to_snippet((*imports)[index].span)
1822 if sn.contains("::") {
1824 (*imports)[index].span,
1825 ResolutionError::UnresolvedImport(None));
1828 (*imports)[index].span,
1829 ResolutionError::UnresolvedImport(Some((&*sn, None))));
1833 // Descend into children and anonymous children.
1834 build_reduced_graph::populate_module_if_necessary(self, &module_);
1836 for (_, child_node) in module_.children.borrow().iter() {
1837 match child_node.get_module_if_available() {
1841 Some(child_module) => {
1842 self.report_unresolved_imports(child_module);
1847 for (_, module_) in module_.anonymous_children.borrow().iter() {
1848 self.report_unresolved_imports(module_.clone());
1854 // We maintain a list of value ribs and type ribs.
1856 // Simultaneously, we keep track of the current position in the module
1857 // graph in the `current_module` pointer. When we go to resolve a name in
1858 // the value or type namespaces, we first look through all the ribs and
1859 // then query the module graph. When we resolve a name in the module
1860 // namespace, we can skip all the ribs (since nested modules are not
1861 // allowed within blocks in Rust) and jump straight to the current module
1864 // Named implementations are handled separately. When we find a method
1865 // call, we consult the module node to find all of the implementations in
1866 // scope. This information is lazily cached in the module node. We then
1867 // generate a fake "implementation scope" containing all the
1868 // implementations thus found, for compatibility with old resolve pass.
1870 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1871 F: FnOnce(&mut Resolver),
1873 let orig_module = self.current_module.clone();
1875 // Move down in the graph.
1881 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1883 match orig_module.children.borrow().get(&name) {
1885 debug!("!!! (with scope) didn't find `{}` in `{}`",
1887 module_to_string(&*orig_module));
1889 Some(name_bindings) => {
1890 match (*name_bindings).get_module_if_available() {
1892 debug!("!!! (with scope) didn't find module \
1895 module_to_string(&*orig_module));
1898 self.current_module = module_;
1908 self.current_module = orig_module;
1911 /// Wraps the given definition in the appropriate number of `DefUpvar`
1917 -> Option<DefLike> {
1918 let mut def = match def_like {
1920 _ => return Some(def_like)
1924 self.session.span_bug(span,
1925 &format!("unexpected {:?} in bindings", def))
1927 DefLocal(node_id) => {
1931 // Nothing to do. Continue.
1933 ClosureRibKind(function_id) => {
1935 def = DefUpvar(node_id, function_id);
1937 let mut seen = self.freevars_seen.borrow_mut();
1938 let seen = match seen.entry(function_id) {
1939 Occupied(v) => v.into_mut(),
1940 Vacant(v) => v.insert(NodeSet()),
1942 if seen.contains(&node_id) {
1945 match self.freevars.borrow_mut().entry(function_id) {
1946 Occupied(v) => v.into_mut(),
1947 Vacant(v) => v.insert(vec![]),
1948 }.push(Freevar { def: prev_def, span: span });
1949 seen.insert(node_id);
1951 ItemRibKind | MethodRibKind => {
1952 // This was an attempt to access an upvar inside a
1953 // named function item. This is not allowed, so we
1958 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem
1962 ConstantItemRibKind => {
1963 // Still doesn't deal with upvars
1967 ResolutionError::AttemptToUseNonConstantValueInConstant
1974 DefTyParam(..) | DefSelfTy(..) => {
1977 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
1978 // Nothing to do. Continue.
1981 // This was an attempt to use a type parameter outside
1986 ResolutionError::TypeParametersFromOuterFunction);
1989 ConstantItemRibKind => {
1991 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2002 /// Searches the current set of local scopes and
2003 /// applies translations for closures.
2004 fn search_ribs(&self,
2008 -> Option<DefLike> {
2009 // FIXME #4950: Try caching?
2011 for (i, rib) in ribs.iter().enumerate().rev() {
2012 if let Some(def_like) = rib.bindings.get(&name).cloned() {
2013 return self.upvarify(&ribs[i + 1..], def_like, span);
2020 /// Searches the current set of local scopes for labels.
2021 /// Stops after meeting a closure.
2022 fn search_label(&self, name: Name) -> Option<DefLike> {
2023 for rib in self.label_ribs.iter().rev() {
2029 // Do not resolve labels across function boundary
2033 let result = rib.bindings.get(&name).cloned();
2034 if result.is_some() {
2041 fn resolve_crate(&mut self, krate: &ast::Crate) {
2042 debug!("(resolving crate) starting");
2044 visit::walk_crate(self, krate);
2047 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
2048 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
2049 span_err!(self.session, span, E0317,
2050 "user-defined types or type parameters cannot shadow the primitive types");
2054 fn resolve_item(&mut self, item: &Item) {
2055 let name = item.ident.name;
2057 debug!("(resolving item) resolving {}",
2061 ItemEnum(_, ref generics) |
2062 ItemTy(_, ref generics) |
2063 ItemStruct(_, ref generics) => {
2064 self.check_if_primitive_type_name(name, item.span);
2066 self.with_type_parameter_rib(HasTypeParameters(generics,
2069 |this| visit::walk_item(this, item));
2071 ItemFn(_, _, _, _, ref generics, _) => {
2072 self.with_type_parameter_rib(HasTypeParameters(generics,
2075 |this| visit::walk_item(this, item));
2078 ItemDefaultImpl(_, ref trait_ref) => {
2079 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
2086 ref impl_items) => {
2087 self.resolve_implementation(generics,
2094 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2095 self.check_if_primitive_type_name(name, item.span);
2097 // Create a new rib for the trait-wide type parameters.
2098 self.with_type_parameter_rib(HasTypeParameters(generics,
2102 this.with_self_rib(DefSelfTy(Some(local_def(item.id)), None), |this| {
2103 this.visit_generics(generics);
2104 visit::walk_ty_param_bounds_helper(this, bounds);
2106 for trait_item in trait_items {
2107 match trait_item.node {
2108 ast::ConstTraitItem(_, ref default) => {
2109 // Only impose the restrictions of
2110 // ConstRibKind if there's an actual constant
2111 // expression in a provided default.
2112 if default.is_some() {
2113 this.with_constant_rib(|this| {
2114 visit::walk_trait_item(this, trait_item)
2117 visit::walk_trait_item(this, trait_item)
2120 ast::MethodTraitItem(ref sig, _) => {
2121 let type_parameters =
2122 HasTypeParameters(&sig.generics,
2125 this.with_type_parameter_rib(type_parameters, |this| {
2126 visit::walk_trait_item(this, trait_item)
2129 ast::TypeTraitItem(..) => {
2130 this.check_if_primitive_type_name(trait_item.ident.name,
2132 this.with_type_parameter_rib(NoTypeParameters, |this| {
2133 visit::walk_trait_item(this, trait_item)
2142 ItemMod(_) | ItemForeignMod(_) => {
2143 self.with_scope(Some(name), |this| {
2144 visit::walk_item(this, item);
2148 ItemConst(..) | ItemStatic(..) => {
2149 self.with_constant_rib(|this| {
2150 visit::walk_item(this, item);
2154 ItemUse(ref view_path) => {
2155 // check for imports shadowing primitive types
2156 if let ast::ViewPathSimple(ident, _) = view_path.node {
2157 match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
2158 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2159 self.check_if_primitive_type_name(ident.name, item.span);
2166 ItemExternCrate(_) | ItemMac(..) => {
2167 // do nothing, these are just around to be encoded
2172 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2173 F: FnOnce(&mut Resolver),
2175 match type_parameters {
2176 HasTypeParameters(generics, space, rib_kind) => {
2177 let mut function_type_rib = Rib::new(rib_kind);
2178 let mut seen_bindings = HashSet::new();
2179 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2180 let name = type_parameter.ident.name;
2181 debug!("with_type_parameter_rib: {}", type_parameter.id);
2183 if seen_bindings.contains(&name) {
2185 type_parameter.span,
2186 ResolutionError::NameAlreadyUsedInTypeParameterList(
2190 seen_bindings.insert(name);
2192 // plain insert (no renaming)
2193 function_type_rib.bindings.insert(name,
2194 DlDef(DefTyParam(space,
2196 local_def(type_parameter.id),
2199 self.type_ribs.push(function_type_rib);
2202 NoTypeParameters => {
2209 match type_parameters {
2210 HasTypeParameters(..) => { self.type_ribs.pop(); }
2211 NoTypeParameters => { }
2215 fn with_label_rib<F>(&mut self, f: F) where
2216 F: FnOnce(&mut Resolver),
2218 self.label_ribs.push(Rib::new(NormalRibKind));
2220 self.label_ribs.pop();
2223 fn with_constant_rib<F>(&mut self, f: F) where
2224 F: FnOnce(&mut Resolver),
2226 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2227 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2229 self.type_ribs.pop();
2230 self.value_ribs.pop();
2233 fn resolve_function(&mut self,
2235 declaration: &FnDecl,
2237 // Create a value rib for the function.
2238 self.value_ribs.push(Rib::new(rib_kind));
2240 // Create a label rib for the function.
2241 self.label_ribs.push(Rib::new(rib_kind));
2243 // Add each argument to the rib.
2244 let mut bindings_list = HashMap::new();
2245 for argument in &declaration.inputs {
2246 self.resolve_pattern(&*argument.pat,
2247 ArgumentIrrefutableMode,
2248 &mut bindings_list);
2250 self.visit_ty(&*argument.ty);
2252 debug!("(resolving function) recorded argument");
2254 visit::walk_fn_ret_ty(self, &declaration.output);
2256 // Resolve the function body.
2257 self.visit_block(&*block);
2259 debug!("(resolving function) leaving function");
2261 self.label_ribs.pop();
2262 self.value_ribs.pop();
2265 fn resolve_trait_reference(&mut self,
2269 -> Result<PathResolution, ()> {
2270 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2271 if let DefTrait(_) = path_res.base_def {
2272 debug!("(resolving trait) found trait def: {:?}", path_res);
2277 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2281 // If it's a typedef, give a note
2282 if let DefTy(..) = path_res.base_def {
2283 self.session.span_note(trait_path.span,
2284 "`type` aliases cannot be used for traits");
2291 ResolutionError::UndeclaredTraitName(
2292 &*path_names_to_string(trait_path, path_depth))
2298 fn resolve_generics(&mut self, generics: &Generics) {
2299 for type_parameter in generics.ty_params.iter() {
2300 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2302 for predicate in &generics.where_clause.predicates {
2304 &ast::WherePredicate::BoundPredicate(_) |
2305 &ast::WherePredicate::RegionPredicate(_) => {}
2306 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
2307 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2308 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2309 self.record_def(eq_pred.id, path_res.unwrap());
2313 ResolutionError::UndeclaredAssociatedType);
2318 visit::walk_generics(self, generics);
2321 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2322 where F: FnOnce(&mut Resolver) -> T
2324 // Handle nested impls (inside fn bodies)
2325 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2326 let result = f(self);
2327 self.current_self_type = previous_value;
2331 fn with_optional_trait_ref<T, F>(&mut self,
2332 opt_trait_ref: Option<&TraitRef>,
2335 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2337 let mut new_val = None;
2338 let mut new_id = None;
2339 if let Some(trait_ref) = opt_trait_ref {
2340 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2341 &trait_ref.path, 0) {
2342 assert!(path_res.depth == 0);
2343 self.record_def(trait_ref.ref_id, path_res);
2344 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2345 new_id = Some(path_res.base_def.def_id());
2347 visit::walk_trait_ref(self, trait_ref);
2349 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2350 let result = f(self, new_id);
2351 self.current_trait_ref = original_trait_ref;
2355 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2356 where F: FnOnce(&mut Resolver)
2358 let mut self_type_rib = Rib::new(NormalRibKind);
2360 // plain insert (no renaming, types are not currently hygienic....)
2361 let name = special_names::type_self;
2362 self_type_rib.bindings.insert(name, DlDef(self_def));
2363 self.type_ribs.push(self_type_rib);
2365 self.type_ribs.pop();
2368 fn resolve_implementation(&mut self,
2369 generics: &Generics,
2370 opt_trait_reference: &Option<TraitRef>,
2373 impl_items: &[P<ImplItem>]) {
2374 // If applicable, create a rib for the type parameters.
2375 self.with_type_parameter_rib(HasTypeParameters(generics,
2379 // Resolve the type parameters.
2380 this.visit_generics(generics);
2382 // Resolve the trait reference, if necessary.
2383 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2384 // Resolve the self type.
2385 this.visit_ty(self_type);
2387 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2388 this.with_current_self_type(self_type, |this| {
2389 for impl_item in impl_items {
2390 match impl_item.node {
2391 ConstImplItem(..) => {
2392 // If this is a trait impl, ensure the const
2394 this.check_trait_item(impl_item.ident.name,
2396 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2397 this.with_constant_rib(|this| {
2398 visit::walk_impl_item(this, impl_item);
2401 MethodImplItem(ref sig, _) => {
2402 // If this is a trait impl, ensure the method
2404 this.check_trait_item(impl_item.ident.name,
2406 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2408 // We also need a new scope for the method-
2409 // specific type parameters.
2410 let type_parameters =
2411 HasTypeParameters(&sig.generics,
2414 this.with_type_parameter_rib(type_parameters, |this| {
2415 visit::walk_impl_item(this, impl_item);
2418 TypeImplItem(ref ty) => {
2419 // If this is a trait impl, ensure the type
2421 this.check_trait_item(impl_item.ident.name,
2423 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2427 ast::MacImplItem(_) => {}
2436 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2437 where F: FnOnce(Name, &str) -> ResolutionError {
2438 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2439 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2440 if !self.trait_item_map.contains_key(&(name, did)) {
2441 let path_str = path_names_to_string(&trait_ref.path, 0);
2444 err(name, &*path_str));
2449 fn resolve_local(&mut self, local: &Local) {
2450 // Resolve the type.
2451 visit::walk_ty_opt(self, &local.ty);
2453 // Resolve the initializer.
2454 visit::walk_expr_opt(self, &local.init);
2456 // Resolve the pattern.
2457 self.resolve_pattern(&*local.pat,
2458 LocalIrrefutableMode,
2459 &mut HashMap::new());
2462 // build a map from pattern identifiers to binding-info's.
2463 // this is done hygienically. This could arise for a macro
2464 // that expands into an or-pattern where one 'x' was from the
2465 // user and one 'x' came from the macro.
2466 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2467 let mut result = HashMap::new();
2468 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2469 let name = mtwt::resolve(path1.node);
2470 result.insert(name, BindingInfo {
2472 binding_mode: binding_mode
2478 // check that all of the arms in an or-pattern have exactly the
2479 // same set of bindings, with the same binding modes for each.
2480 fn check_consistent_bindings(&mut self, arm: &Arm) {
2481 if arm.pats.is_empty() {
2484 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2485 for (i, p) in arm.pats.iter().enumerate() {
2486 let map_i = self.binding_mode_map(&**p);
2488 for (&key, &binding_0) in &map_0 {
2489 match map_i.get(&key) {
2493 ResolutionError::VariableNotBoundInPattern(key,
2496 Some(binding_i) => {
2497 if binding_0.binding_mode != binding_i.binding_mode {
2500 ResolutionError::VariableBoundWithDifferentMode(key,
2508 for (&key, &binding) in &map_i {
2509 if !map_0.contains_key(&key) {
2512 ResolutionError::VariableNotBoundInParentPattern(key,
2519 fn resolve_arm(&mut self, arm: &Arm) {
2520 self.value_ribs.push(Rib::new(NormalRibKind));
2522 let mut bindings_list = HashMap::new();
2523 for pattern in &arm.pats {
2524 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2527 // This has to happen *after* we determine which
2528 // pat_idents are variants
2529 self.check_consistent_bindings(arm);
2531 visit::walk_expr_opt(self, &arm.guard);
2532 self.visit_expr(&*arm.body);
2534 self.value_ribs.pop();
2537 fn resolve_block(&mut self, block: &Block) {
2538 debug!("(resolving block) entering block");
2539 self.value_ribs.push(Rib::new(NormalRibKind));
2541 // Move down in the graph, if there's an anonymous module rooted here.
2542 let orig_module = self.current_module.clone();
2543 match orig_module.anonymous_children.borrow().get(&block.id) {
2544 None => { /* Nothing to do. */ }
2545 Some(anonymous_module) => {
2546 debug!("(resolving block) found anonymous module, moving \
2548 self.current_module = anonymous_module.clone();
2552 // Check for imports appearing after non-item statements.
2553 let mut found_non_item = false;
2554 for statement in &block.stmts {
2555 if let ast::StmtDecl(ref declaration, _) = statement.node {
2556 if let ast::DeclItem(ref i) = declaration.node {
2558 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2559 span_err!(self.session, i.span, E0154,
2560 "imports are not allowed after non-item statements");
2565 found_non_item = true
2568 found_non_item = true;
2572 // Descend into the block.
2573 visit::walk_block(self, block);
2576 self.current_module = orig_module;
2578 self.value_ribs.pop();
2579 debug!("(resolving block) leaving block");
2582 fn resolve_type(&mut self, ty: &Ty) {
2584 TyPath(ref maybe_qself, ref path) => {
2586 match self.resolve_possibly_assoc_item(ty.id,
2587 maybe_qself.as_ref(),
2591 // `<T>::a::b::c` is resolved by typeck alone.
2592 TypecheckRequired => {
2593 // Resolve embedded types.
2594 visit::walk_ty(self, ty);
2597 ResolveAttempt(resolution) => resolution,
2600 // This is a path in the type namespace. Walk through scopes
2604 // Write the result into the def map.
2605 debug!("(resolving type) writing resolution for `{}` \
2607 path_names_to_string(path, 0),
2609 self.record_def(ty.id, def);
2612 // Keep reporting some errors even if they're ignored above.
2613 self.resolve_path(ty.id, path, 0, TypeNS, true);
2615 let kind = if maybe_qself.is_some() {
2621 let self_type_name = special_idents::type_self.name;
2622 let is_invalid_self_type_name =
2623 path.segments.len() > 0 &&
2624 maybe_qself.is_none() &&
2625 path.segments[0].identifier.name == self_type_name;
2626 if is_invalid_self_type_name {
2629 ResolutionError::SelfUsedOutsideImplOrTrait);
2633 ResolutionError::UseOfUndeclared(
2635 &*path_names_to_string(path,
2644 // Resolve embedded types.
2645 visit::walk_ty(self, ty);
2648 fn resolve_pattern(&mut self,
2650 mode: PatternBindingMode,
2651 // Maps idents to the node ID for the (outermost)
2652 // pattern that binds them
2653 bindings_list: &mut HashMap<Name, NodeId>) {
2654 let pat_id = pattern.id;
2655 walk_pat(pattern, |pattern| {
2656 match pattern.node {
2657 PatIdent(binding_mode, ref path1, _) => {
2659 // The meaning of pat_ident with no type parameters
2660 // depends on whether an enum variant or unit-like struct
2661 // with that name is in scope. The probing lookup has to
2662 // be careful not to emit spurious errors. Only matching
2663 // patterns (match) can match nullary variants or
2664 // unit-like structs. For binding patterns (let), matching
2665 // such a value is simply disallowed (since it's rarely
2668 let ident = path1.node;
2669 let renamed = mtwt::resolve(ident);
2671 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2672 FoundStructOrEnumVariant(def, lp)
2673 if mode == RefutableMode => {
2674 debug!("(resolving pattern) resolving `{}` to \
2675 struct or enum variant",
2678 self.enforce_default_binding_mode(
2682 self.record_def(pattern.id, PathResolution {
2688 FoundStructOrEnumVariant(..) => {
2692 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2696 FoundConst(def, lp) if mode == RefutableMode => {
2697 debug!("(resolving pattern) resolving `{}` to \
2701 self.enforce_default_binding_mode(
2705 self.record_def(pattern.id, PathResolution {
2715 ResolutionError::OnlyIrrefutablePatternsAllowedHere
2718 BareIdentifierPatternUnresolved => {
2719 debug!("(resolving pattern) binding `{}`",
2722 let def = DefLocal(pattern.id);
2724 // Record the definition so that later passes
2725 // will be able to distinguish variants from
2726 // locals in patterns.
2728 self.record_def(pattern.id, PathResolution {
2730 last_private: LastMod(AllPublic),
2734 // Add the binding to the local ribs, if it
2735 // doesn't already exist in the bindings list. (We
2736 // must not add it if it's in the bindings list
2737 // because that breaks the assumptions later
2738 // passes make about or-patterns.)
2739 if !bindings_list.contains_key(&renamed) {
2740 let this = &mut *self;
2741 let last_rib = this.value_ribs.last_mut().unwrap();
2742 last_rib.bindings.insert(renamed, DlDef(def));
2743 bindings_list.insert(renamed, pat_id);
2744 } else if mode == ArgumentIrrefutableMode &&
2745 bindings_list.contains_key(&renamed) {
2746 // Forbid duplicate bindings in the same
2751 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2752 &ident.name.as_str())
2754 } else if bindings_list.get(&renamed) ==
2756 // Then this is a duplicate variable in the
2757 // same disjunction, which is an error.
2761 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2762 &ident.name.as_str())
2765 // Else, not bound in the same pattern: do
2771 PatEnum(ref path, _) => {
2772 // This must be an enum variant, struct or const.
2774 match self.resolve_possibly_assoc_item(pat_id, None,
2777 // The below shouldn't happen because all
2778 // qualified paths should be in PatQPath.
2779 TypecheckRequired =>
2780 self.session.span_bug(
2782 "resolve_possibly_assoc_item claimed
2783 that a path in PatEnum requires typecheck
2784 to resolve, but qualified paths should be
2786 ResolveAttempt(resolution) => resolution,
2788 if let Some(path_res) = resolution {
2789 match path_res.base_def {
2790 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2791 self.record_def(pattern.id, path_res);
2794 resolve_error(&self,
2796 ResolutionError::StaticVariableReference);
2799 // If anything ends up here entirely resolved,
2800 // it's an error. If anything ends up here
2801 // partially resolved, that's OK, because it may
2802 // be a `T::CONST` that typeck will resolve.
2803 if path_res.depth == 0 {
2807 ResolutionError::NotAnEnumVariantStructOrConst(
2816 let const_name = path.segments.last().unwrap()
2818 let traits = self.get_traits_containing_item(const_name);
2819 self.trait_map.insert(pattern.id, traits);
2820 self.record_def(pattern.id, path_res);
2828 ResolutionError::UnresolvedEnumVariantStructOrConst(
2829 &path.segments.last().unwrap().identifier.name.as_str())
2832 visit::walk_path(self, path);
2835 PatQPath(ref qself, ref path) => {
2836 // Associated constants only.
2838 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2841 TypecheckRequired => {
2842 // All `<T>::CONST` should end up here, and will
2843 // require use of the trait map to resolve
2844 // during typechecking.
2845 let const_name = path.segments.last().unwrap()
2847 let traits = self.get_traits_containing_item(const_name);
2848 self.trait_map.insert(pattern.id, traits);
2849 visit::walk_pat(self, pattern);
2852 ResolveAttempt(resolution) => resolution,
2854 if let Some(path_res) = resolution {
2855 match path_res.base_def {
2856 // All `<T as Trait>::CONST` should end up here, and
2857 // have the trait already selected.
2858 DefAssociatedConst(..) => {
2859 self.record_def(pattern.id, path_res);
2865 ResolutionError::NotAnAssociatedConst(
2866 &path.segments.last().unwrap().identifier.name.as_str()
2875 ResolutionError::UnresolvedAssociatedConst(
2876 &path.segments.last().unwrap().identifier.name.as_str()
2880 visit::walk_pat(self, pattern);
2883 PatStruct(ref path, _, _) => {
2884 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2885 Some(definition) => {
2886 self.record_def(pattern.id, definition);
2889 debug!("(resolving pattern) didn't find struct \
2890 def: {:?}", result);
2894 ResolutionError::DoesNotNameAStruct(
2895 &*path_names_to_string(path, 0))
2899 visit::walk_path(self, path);
2902 PatLit(_) | PatRange(..) => {
2903 visit::walk_pat(self, pattern);
2914 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2915 -> BareIdentifierPatternResolution {
2916 let module = self.current_module.clone();
2917 match self.resolve_item_in_lexical_scope(module,
2920 Success((target, _)) => {
2921 debug!("(resolve bare identifier pattern) succeeded in \
2922 finding {} at {:?}",
2924 target.bindings.value_def.borrow());
2925 match *target.bindings.value_def.borrow() {
2927 panic!("resolved name in the value namespace to a \
2928 set of name bindings with no def?!");
2931 // For the two success cases, this lookup can be
2932 // considered as not having a private component because
2933 // the lookup happened only within the current module.
2935 def @ DefVariant(..) | def @ DefStruct(..) => {
2936 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2938 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
2939 return FoundConst(def, LastMod(AllPublic));
2944 ResolutionError::StaticVariableReference);
2945 return BareIdentifierPatternUnresolved;
2948 return BareIdentifierPatternUnresolved;
2956 panic!("unexpected indeterminate result");
2960 Some((span, msg)) => {
2961 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2966 debug!("(resolve bare identifier pattern) failed to find {}",
2968 return BareIdentifierPatternUnresolved;
2973 /// Handles paths that may refer to associated items
2974 fn resolve_possibly_assoc_item(&mut self,
2976 maybe_qself: Option<&ast::QSelf>,
2978 namespace: Namespace,
2980 -> AssocItemResolveResult
2982 let max_assoc_types;
2986 if qself.position == 0 {
2987 return TypecheckRequired;
2989 max_assoc_types = path.segments.len() - qself.position;
2990 // Make sure the trait is valid.
2991 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2994 max_assoc_types = path.segments.len();
2998 let mut resolution = self.with_no_errors(|this| {
2999 this.resolve_path(id, path, 0, namespace, check_ribs)
3001 for depth in 1..max_assoc_types {
3002 if resolution.is_some() {
3005 self.with_no_errors(|this| {
3006 resolution = this.resolve_path(id, path, depth,
3010 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
3011 // A module is not a valid type or value.
3014 ResolveAttempt(resolution)
3017 /// If `check_ribs` is true, checks the local definitions first; i.e.
3018 /// doesn't skip straight to the containing module.
3019 /// Skips `path_depth` trailing segments, which is also reflected in the
3020 /// returned value. See `middle::def::PathResolution` for more info.
3021 fn resolve_path(&mut self,
3025 namespace: Namespace,
3026 check_ribs: bool) -> Option<PathResolution> {
3027 let span = path.span;
3028 let segments = &path.segments[..path.segments.len()-path_depth];
3030 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
3033 let def = self.resolve_crate_relative_path(span, segments, namespace);
3034 return def.map(mk_res);
3037 // Try to find a path to an item in a module.
3038 let unqualified_def =
3039 self.resolve_identifier(segments.last().unwrap().identifier,
3044 if segments.len() <= 1 {
3045 return unqualified_def.map(mk_res);
3048 let def = self.resolve_module_relative_path(span, segments, namespace);
3049 match (def, unqualified_def) {
3050 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3052 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3054 "unnecessary qualification".to_string());
3062 // Resolve a single identifier.
3063 fn resolve_identifier(&mut self,
3065 namespace: Namespace,
3068 -> Option<(Def, LastPrivate)> {
3069 // First, check to see whether the name is a primitive type.
3070 if namespace == TypeNS {
3071 if let Some(&prim_ty) = self.primitive_type_table
3073 .get(&identifier.name) {
3074 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
3079 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
3082 return Some((def, LastMod(AllPublic)));
3086 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
3089 // FIXME #4952: Merge me with resolve_name_in_module?
3090 fn resolve_definition_of_name_in_module(&mut self,
3091 containing_module: Rc<Module>,
3093 namespace: Namespace)
3095 // First, search children.
3096 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3098 match containing_module.children.borrow().get(&name) {
3099 Some(child_name_bindings) => {
3100 match child_name_bindings.def_for_namespace(namespace) {
3102 // Found it. Stop the search here.
3103 let p = child_name_bindings.defined_in_public_namespace(namespace);
3104 let lp = if p {LastMod(AllPublic)} else {
3105 LastMod(DependsOn(def.def_id()))
3107 return ChildNameDefinition(def, lp);
3115 // Next, search import resolutions.
3116 match containing_module.import_resolutions.borrow().get(&name) {
3117 Some(import_resolution) if import_resolution.is_public => {
3118 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3119 match target.bindings.def_for_namespace(namespace) {
3122 let id = import_resolution.id(namespace);
3123 // track imports and extern crates as well
3124 self.used_imports.insert((id, namespace));
3125 self.record_import_use(id, name);
3126 match target.target_module.def_id.get() {
3127 Some(DefId{krate: kid, ..}) => {
3128 self.used_crates.insert(kid);
3132 return ImportNameDefinition(def, LastMod(AllPublic));
3135 // This can happen with external impls, due to
3136 // the imperfect way we read the metadata.
3141 Some(..) | None => {} // Continue.
3144 // Finally, search through external children.
3145 if namespace == TypeNS {
3146 if let Some(module) = containing_module.external_module_children.borrow()
3147 .get(&name).cloned() {
3148 if let Some(def_id) = module.def_id.get() {
3149 // track used crates
3150 self.used_crates.insert(def_id.krate);
3151 let lp = if module.is_public {LastMod(AllPublic)} else {
3152 LastMod(DependsOn(def_id))
3154 return ChildNameDefinition(DefMod(def_id), lp);
3159 return NoNameDefinition;
3162 // resolve a "module-relative" path, e.g. a::b::c
3163 fn resolve_module_relative_path(&mut self,
3165 segments: &[ast::PathSegment],
3166 namespace: Namespace)
3167 -> Option<(Def, LastPrivate)> {
3168 let module_path = segments.split_last().unwrap().1.iter()
3169 .map(|ps| ps.identifier.name)
3170 .collect::<Vec<_>>();
3172 let containing_module;
3174 let current_module = self.current_module.clone();
3175 match self.resolve_module_path(current_module,
3181 let (span, msg) = match err {
3182 Some((span, msg)) => (span, msg),
3184 let msg = format!("Use of undeclared type or module `{}`",
3185 names_to_string(&module_path));
3190 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3193 Indeterminate => panic!("indeterminate unexpected"),
3194 Success((resulting_module, resulting_last_private)) => {
3195 containing_module = resulting_module;
3196 last_private = resulting_last_private;
3200 let name = segments.last().unwrap().identifier.name;
3201 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
3204 NoNameDefinition => {
3205 // We failed to resolve the name. Report an error.
3208 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3209 (def, last_private.or(lp))
3212 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
3213 self.used_crates.insert(kid);
3218 /// Invariant: This must be called only during main resolution, not during
3219 /// import resolution.
3220 fn resolve_crate_relative_path(&mut self,
3222 segments: &[ast::PathSegment],
3223 namespace: Namespace)
3224 -> Option<(Def, LastPrivate)> {
3225 let module_path = segments.split_last().unwrap().1.iter()
3226 .map(|ps| ps.identifier.name)
3227 .collect::<Vec<_>>();
3229 let root_module = self.graph_root.get_module();
3231 let containing_module;
3233 match self.resolve_module_path_from_root(root_module,
3238 LastMod(AllPublic)) {
3240 let (span, msg) = match err {
3241 Some((span, msg)) => (span, msg),
3243 let msg = format!("Use of undeclared module `::{}`",
3244 names_to_string(&module_path[..]));
3249 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3254 panic!("indeterminate unexpected");
3257 Success((resulting_module, resulting_last_private)) => {
3258 containing_module = resulting_module;
3259 last_private = resulting_last_private;
3263 let name = segments.last().unwrap().identifier.name;
3264 match self.resolve_definition_of_name_in_module(containing_module,
3267 NoNameDefinition => {
3268 // We failed to resolve the name. Report an error.
3271 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3272 return Some((def, last_private.or(lp)));
3277 fn resolve_identifier_in_local_ribs(&mut self,
3279 namespace: Namespace,
3282 // Check the local set of ribs.
3283 let search_result = match namespace {
3285 let renamed = mtwt::resolve(ident);
3286 self.search_ribs(&self.value_ribs, renamed, span)
3289 let name = ident.name;
3290 self.search_ribs(&self.type_ribs, name, span)
3294 match search_result {
3295 Some(DlDef(def)) => {
3296 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3301 Some(DlField) | Some(DlImpl(_)) | None => {
3307 fn resolve_item_by_name_in_lexical_scope(&mut self,
3309 namespace: Namespace)
3310 -> Option<(Def, LastPrivate)> {
3312 let module = self.current_module.clone();
3313 match self.resolve_item_in_lexical_scope(module,
3316 Success((target, _)) => {
3317 match (*target.bindings).def_for_namespace(namespace) {
3319 // This can happen if we were looking for a type and
3320 // found a module instead. Modules don't have defs.
3321 debug!("(resolving item path by identifier in lexical \
3322 scope) failed to resolve {} after success...",
3327 debug!("(resolving item path in lexical scope) \
3328 resolved `{}` to item",
3330 // This lookup is "all public" because it only searched
3331 // for one identifier in the current module (couldn't
3332 // have passed through reexports or anything like that.
3333 return Some((def, LastMod(AllPublic)));
3338 panic!("unexpected indeterminate result");
3341 debug!("(resolving item path by identifier in lexical scope) \
3342 failed to resolve {}", name);
3344 if let Some((span, msg)) = err {
3345 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3353 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3354 F: FnOnce(&mut Resolver) -> T,
3356 self.emit_errors = false;
3358 self.emit_errors = true;
3362 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3363 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3364 -> Option<(Path, NodeId, FallbackChecks)> {
3366 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3367 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3368 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3369 // This doesn't handle the remaining `Ty` variants as they are not
3370 // that commonly the self_type, it might be interesting to provide
3371 // support for those in future.
3376 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3377 -> Option<Rc<Module>> {
3378 let root = this.current_module.clone();
3379 let last_name = name_path.last().unwrap();
3381 if name_path.len() == 1 {
3382 match this.primitive_type_table.primitive_types.get(last_name) {
3385 match this.current_module.children.borrow().get(last_name) {
3386 Some(child) => child.get_module_if_available(),
3392 match this.resolve_module_path(root,
3397 Success((module, _)) => Some(module),
3403 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3404 if did.krate == ast::LOCAL_CRATE {
3405 let sig = match this.ast_map.get(did.node) {
3406 ast_map::NodeTraitItem(trait_item) => match trait_item.node {
3407 ast::MethodTraitItem(ref sig, _) => sig,
3410 ast_map::NodeImplItem(impl_item) => match impl_item.node {
3411 ast::MethodImplItem(ref sig, _) => sig,
3416 sig.explicit_self.node == ast::SelfStatic
3418 csearch::is_static_method(&this.session.cstore, did)
3422 let (path, node_id, allowed) = match self.current_self_type {
3423 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3425 None => return NoSuggestion,
3427 None => return NoSuggestion,
3430 if allowed == Everything {
3431 // Look for a field with the same name in the current self_type.
3432 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3433 Some(DefTy(did, _)) |
3434 Some(DefStruct(did)) |
3435 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3438 if fields.iter().any(|&field_name| name == field_name) {
3443 _ => {} // Self type didn't resolve properly
3447 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3449 // Look for a method in the current self type's impl module.
3450 if let Some(module) = get_module(self, path.span, &name_path) {
3451 if let Some(binding) = module.children.borrow().get(&name) {
3452 if let Some(DefMethod(did, _)) = binding.def_for_namespace(ValueNS) {
3453 if is_static_method(self, did) {
3454 return StaticMethod(path_names_to_string(&path, 0))
3456 if self.current_trait_ref.is_some() {
3458 } else if allowed == Everything {
3465 // Look for a method in the current trait.
3466 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3467 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3468 if is_static_method(self, did) {
3469 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3479 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3480 let mut maybes: Vec<token::InternedString> = Vec::new();
3481 let mut values: Vec<usize> = Vec::new();
3483 for rib in self.value_ribs.iter().rev() {
3484 for (&k, _) in &rib.bindings {
3485 maybes.push(k.as_str());
3486 values.push(usize::MAX);
3490 let mut smallest = 0;
3491 for (i, other) in maybes.iter().enumerate() {
3492 values[i] = lev_distance(name, &other);
3494 if values[i] <= values[smallest] {
3499 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3500 // maximum edit distance we will accept for a suggestion to one third of
3501 // the typo'd name's length.
3502 let max_distance = std::cmp::max(name.len(), 3) / 3;
3504 if !values.is_empty() &&
3505 values[smallest] <= max_distance &&
3506 name != &maybes[smallest][..] {
3508 Some(maybes[smallest].to_string())
3515 fn resolve_expr(&mut self, expr: &Expr) {
3516 // First, record candidate traits for this expression if it could
3517 // result in the invocation of a method call.
3519 self.record_candidate_traits_for_expr_if_necessary(expr);
3521 // Next, resolve the node.
3523 ExprPath(ref maybe_qself, ref path) => {
3525 match self.resolve_possibly_assoc_item(expr.id,
3526 maybe_qself.as_ref(),
3530 // `<T>::a::b::c` is resolved by typeck alone.
3531 TypecheckRequired => {
3532 let method_name = path.segments.last().unwrap().identifier.name;
3533 let traits = self.get_traits_containing_item(method_name);
3534 self.trait_map.insert(expr.id, traits);
3535 visit::walk_expr(self, expr);
3538 ResolveAttempt(resolution) => resolution,
3541 // This is a local path in the value namespace. Walk through
3542 // scopes looking for it.
3543 if let Some(path_res) = resolution {
3544 // Check if struct variant
3545 if let DefVariant(_, _, true) = path_res.base_def {
3546 let path_name = path_names_to_string(path, 0);
3550 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3552 let msg = format!("did you mean to write: \
3553 `{} {{ /* fields */ }}`?",
3555 if self.emit_errors {
3556 self.session.fileline_help(expr.span, &msg);
3558 self.session.span_help(expr.span, &msg);
3561 // Write the result into the def map.
3562 debug!("(resolving expr) resolved `{}`",
3563 path_names_to_string(path, 0));
3565 // Partial resolutions will need the set of traits in scope,
3566 // so they can be completed during typeck.
3567 if path_res.depth != 0 {
3568 let method_name = path.segments.last().unwrap().identifier.name;
3569 let traits = self.get_traits_containing_item(method_name);
3570 self.trait_map.insert(expr.id, traits);
3573 self.record_def(expr.id, path_res);
3576 // Be helpful if the name refers to a struct
3577 // (The pattern matching def_tys where the id is in self.structs
3578 // matches on regular structs while excluding tuple- and enum-like
3579 // structs, which wouldn't result in this error.)
3580 let path_name = path_names_to_string(path, 0);
3581 let type_res = self.with_no_errors(|this| {
3582 this.resolve_path(expr.id, path, 0, TypeNS, false)
3584 match type_res.map(|r| r.base_def) {
3585 Some(DefTy(struct_id, _))
3586 if self.structs.contains_key(&struct_id) => {
3590 ResolutionError::StructVariantUsedAsFunction(
3594 let msg = format!("did you mean to write: \
3595 `{} {{ /* fields */ }}`?",
3597 if self.emit_errors {
3598 self.session.fileline_help(expr.span, &msg);
3600 self.session.span_help(expr.span, &msg);
3604 // Keep reporting some errors even if they're ignored above.
3605 self.resolve_path(expr.id, path, 0, ValueNS, true);
3607 let mut method_scope = false;
3608 self.value_ribs.iter().rev().all(|rib| {
3609 method_scope = match rib.kind {
3610 MethodRibKind => true,
3611 ItemRibKind | ConstantItemRibKind => false,
3612 _ => return true, // Keep advancing
3614 false // Stop advancing
3617 if method_scope && special_names::self_ == path_name {
3621 ResolutionError::SelfNotAvailableInStaticMethod
3624 let last_name = path.segments.last().unwrap().identifier.name;
3625 let mut msg = match self.find_fallback_in_self_type(last_name) {
3627 // limit search to 5 to reduce the number
3628 // of stupid suggestions
3629 self.find_best_match_for_name(&path_name)
3630 .map_or("".to_string(),
3631 |x| format!("`{}`", x))
3633 Field => format!("`self.{}`", path_name),
3636 format!("to call `self.{}`", path_name),
3637 TraitMethod(path_str) |
3638 StaticMethod(path_str) =>
3639 format!("to call `{}::{}`", path_str, path_name)
3642 if !msg.is_empty() {
3643 msg = format!(". Did you mean {}?", msg)
3648 ResolutionError::UnresolvedName(&*path_name,
3655 visit::walk_expr(self, expr);
3658 ExprStruct(ref path, _, _) => {
3659 // Resolve the path to the structure it goes to. We don't
3660 // check to ensure that the path is actually a structure; that
3661 // is checked later during typeck.
3662 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3663 Some(definition) => self.record_def(expr.id, definition),
3665 debug!("(resolving expression) didn't find struct def",);
3669 ResolutionError::DoesNotNameAStruct(
3670 &*path_names_to_string(path, 0))
3675 visit::walk_expr(self, expr);
3678 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3679 self.with_label_rib(|this| {
3680 let def_like = DlDef(DefLabel(expr.id));
3683 let rib = this.label_ribs.last_mut().unwrap();
3684 let renamed = mtwt::resolve(label);
3685 rib.bindings.insert(renamed, def_like);
3688 visit::walk_expr(this, expr);
3692 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3693 let renamed = mtwt::resolve(label);
3694 match self.search_label(renamed) {
3698 ResolutionError::UndeclaredLabel(&label.name.as_str()))
3700 Some(DlDef(def @ DefLabel(_))) => {
3701 // Since this def is a label, it is never read.
3702 self.record_def(expr.id, PathResolution {
3704 last_private: LastMod(AllPublic),
3709 self.session.span_bug(expr.span,
3710 "label wasn't mapped to a \
3717 visit::walk_expr(self, expr);
3722 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3724 ExprField(_, ident) => {
3725 // FIXME(#6890): Even though you can't treat a method like a
3726 // field, we need to add any trait methods we find that match
3727 // the field name so that we can do some nice error reporting
3728 // later on in typeck.
3729 let traits = self.get_traits_containing_item(ident.node.name);
3730 self.trait_map.insert(expr.id, traits);
3732 ExprMethodCall(ident, _, _) => {
3733 debug!("(recording candidate traits for expr) recording \
3736 let traits = self.get_traits_containing_item(ident.node.name);
3737 self.trait_map.insert(expr.id, traits);
3745 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3746 debug!("(getting traits containing item) looking for '{}'",
3749 fn add_trait_info(found_traits: &mut Vec<DefId>,
3750 trait_def_id: DefId,
3752 debug!("(adding trait info) found trait {}:{} for method '{}'",
3756 found_traits.push(trait_def_id);
3759 let mut found_traits = Vec::new();
3760 let mut search_module = self.current_module.clone();
3762 // Look for the current trait.
3763 match self.current_trait_ref {
3764 Some((trait_def_id, _)) => {
3765 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3766 add_trait_info(&mut found_traits, trait_def_id, name);
3769 None => {} // Nothing to do.
3772 // Look for trait children.
3773 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3776 for (_, child_names) in search_module.children.borrow().iter() {
3777 let def = match child_names.def_for_namespace(TypeNS) {
3781 let trait_def_id = match def {
3782 DefTrait(trait_def_id) => trait_def_id,
3785 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3786 add_trait_info(&mut found_traits, trait_def_id, name);
3791 // Look for imports.
3792 for (_, import) in search_module.import_resolutions.borrow().iter() {
3793 let target = match import.target_for_namespace(TypeNS) {
3795 Some(target) => target,
3797 let did = match target.bindings.def_for_namespace(TypeNS) {
3798 Some(DefTrait(trait_def_id)) => trait_def_id,
3799 Some(..) | None => continue,
3801 if self.trait_item_map.contains_key(&(name, did)) {
3802 add_trait_info(&mut found_traits, did, name);
3803 let id = import.type_id;
3804 self.used_imports.insert((id, TypeNS));
3805 let trait_name = self.get_trait_name(did);
3806 self.record_import_use(id, trait_name);
3807 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3808 self.used_crates.insert(kid);
3813 match search_module.parent_link.clone() {
3814 NoParentLink | ModuleParentLink(..) => break,
3815 BlockParentLink(parent_module, _) => {
3816 search_module = parent_module.upgrade().unwrap();
3824 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3825 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3826 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3827 "Import should only be used for `use` directives");
3829 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3830 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3831 self.session.span_bug(span, &format!("path resolved multiple times \
3832 ({:?} before, {:?} now)",
3833 prev_res, resolution));
3837 fn enforce_default_binding_mode(&mut self,
3839 pat_binding_mode: BindingMode,
3841 match pat_binding_mode {
3842 BindByValue(_) => {}
3846 ResolutionError::CannotUseRefBindingModeWith(descr));
3854 // Diagnostics are not particularly efficient, because they're rarely
3858 #[allow(dead_code)] // useful for debugging
3859 fn dump_module(&mut self, module_: Rc<Module>) {
3860 debug!("Dump of module `{}`:", module_to_string(&*module_));
3862 debug!("Children:");
3863 build_reduced_graph::populate_module_if_necessary(self, &module_);
3864 for (&name, _) in module_.children.borrow().iter() {
3865 debug!("* {}", name);
3868 debug!("Import resolutions:");
3869 let import_resolutions = module_.import_resolutions.borrow();
3870 for (&name, import_resolution) in import_resolutions.iter() {
3872 match import_resolution.target_for_namespace(ValueNS) {
3873 None => { value_repr = "".to_string(); }
3875 value_repr = " value:?".to_string();
3881 match import_resolution.target_for_namespace(TypeNS) {
3882 None => { type_repr = "".to_string(); }
3884 type_repr = " type:?".to_string();
3889 debug!("* {}:{}{}", name, value_repr, type_repr);
3895 fn names_to_string(names: &[Name]) -> String {
3896 let mut first = true;
3897 let mut result = String::new();
3902 result.push_str("::")
3904 result.push_str(&name.as_str());
3909 fn path_names_to_string(path: &Path, depth: usize) -> String {
3910 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3912 .map(|seg| seg.identifier.name)
3914 names_to_string(&names[..])
3917 /// A somewhat inefficient routine to obtain the name of a module.
3918 fn module_to_string(module: &Module) -> String {
3919 let mut names = Vec::new();
3921 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3922 match module.parent_link {
3924 ModuleParentLink(ref module, name) => {
3926 collect_mod(names, &*module.upgrade().unwrap());
3928 BlockParentLink(ref module, _) => {
3929 // danger, shouldn't be ident?
3930 names.push(special_idents::opaque.name);
3931 collect_mod(names, &*module.upgrade().unwrap());
3935 collect_mod(&mut names, module);
3937 if names.is_empty() {
3938 return "???".to_string();
3940 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3944 pub struct CrateMap {
3945 pub def_map: DefMap,
3946 pub freevars: RefCell<FreevarMap>,
3947 pub export_map: ExportMap,
3948 pub trait_map: TraitMap,
3949 pub external_exports: ExternalExports,
3950 pub glob_map: Option<GlobMap>
3953 #[derive(PartialEq,Copy, Clone)]
3954 pub enum MakeGlobMap {
3959 /// Entry point to crate resolution.
3960 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3961 ast_map: &'a ast_map::Map<'tcx>,
3962 make_glob_map: MakeGlobMap)
3964 let krate = ast_map.krate();
3965 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
3967 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3968 session.abort_if_errors();
3970 resolve_imports::resolve_imports(&mut resolver);
3971 session.abort_if_errors();
3973 record_exports::record(&mut resolver);
3974 session.abort_if_errors();
3976 resolver.resolve_crate(krate);
3977 session.abort_if_errors();
3979 check_unused::check_crate(&mut resolver, krate);
3982 def_map: resolver.def_map,
3983 freevars: resolver.freevars,
3984 export_map: resolver.export_map,
3985 trait_map: resolver.trait_map,
3986 external_exports: resolver.external_exports,
3987 glob_map: if resolver.make_glob_map {
3988 Some(resolver.glob_map)
3995 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }