1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_resolve"]
14 #![unstable(feature = "rustc_private", issue = "27812")]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20 html_root_url = "https://doc.rust-lang.org/nightly/")]
22 #![feature(associated_consts)]
23 #![feature(borrow_state)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(slice_splits)]
27 #![feature(staged_api)]
30 #[macro_use] extern crate log;
31 #[macro_use] extern crate syntax;
32 #[macro_use] #[no_link] extern crate rustc_bitflags;
33 extern crate rustc_front;
37 use self::PatternBindingMode::*;
38 use self::Namespace::*;
39 use self::NamespaceResult::*;
40 use self::NameDefinition::*;
41 use self::ResolveResult::*;
42 use self::FallbackSuggestion::*;
43 use self::TypeParameters::*;
45 use self::UseLexicalScopeFlag::*;
46 use self::ModulePrefixResult::*;
47 use self::AssocItemResolveResult::*;
48 use self::NameSearchType::*;
49 use self::BareIdentifierPatternResolution::*;
50 use self::ParentLink::*;
51 use self::ModuleKind::*;
52 use self::FallbackChecks::*;
54 use rustc::front::map as hir_map;
55 use rustc::session::Session;
57 use rustc::metadata::csearch;
58 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
59 use rustc::middle::def::*;
60 use rustc::middle::def_id::DefId;
61 use rustc::middle::pat_util::pat_bindings;
62 use rustc::middle::privacy::*;
63 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
64 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
65 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
66 use rustc::util::lev_distance::lev_distance;
69 use syntax::ast::{Ident, Name, NodeId, CrateNum};
70 use syntax::attr::AttrMetaMethods;
71 use syntax::ext::mtwt;
72 use syntax::parse::token::{self, special_names, special_idents};
74 use syntax::codemap::{self, Span, Pos};
76 use rustc_front::visit::{self, FnKind, Visitor};
78 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
79 use rustc_front::hir::{ConstImplItem, Crate};
80 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprField};
81 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
82 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
83 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
84 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
85 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
86 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
87 use rustc_front::hir::{Local, MethodImplItem};
88 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
89 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
90 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyF32};
91 use rustc_front::hir::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt};
92 use rustc_front::hir::{TyPath, TyPtr};
93 use rustc_front::hir::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
94 use rustc_front::hir::TypeImplItem;
95 use rustc_front::util::walk_pat;
97 use std::collections::{HashMap, HashSet};
98 use std::collections::hash_map::Entry::{Occupied, Vacant};
99 use std::cell::{Cell, RefCell};
101 use std::mem::replace;
102 use std::rc::{Rc, Weak};
105 use resolve_imports::{Target, ImportDirective, ImportResolution};
106 use resolve_imports::Shadowable;
108 // NB: This module needs to be declared first so diagnostics are
109 // registered before they are used.
114 mod build_reduced_graph;
117 // Perform the callback, not walking deeper if the return is true
118 macro_rules! execute_callback {
119 ($node: expr, $walker: expr) => (
120 if let Some(ref callback) = $walker.callback {
121 if callback($node, &mut $walker.resolved) {
128 pub enum ResolutionError<'a> {
129 /// error E0401: can't use type parameters from outer function
130 TypeParametersFromOuterFunction,
131 /// error E0402: cannot use an outer type parameter in this context
132 OuterTypeParameterContext,
133 /// error E0403: the name is already used for a type parameter in this type parameter list
134 NameAlreadyUsedInTypeParameterList(Name),
135 /// error E0404: is not a trait
136 IsNotATrait(&'a str),
137 /// error E0405: use of undeclared trait name
138 UndeclaredTraitName(&'a str),
139 /// error E0406: undeclared associated type
140 UndeclaredAssociatedType,
141 /// error E0407: method is not a member of trait
142 MethodNotMemberOfTrait(Name, &'a str),
143 /// error E0437: type is not a member of trait
144 TypeNotMemberOfTrait(Name, &'a str),
145 /// error E0438: const is not a member of trait
146 ConstNotMemberOfTrait(Name, &'a str),
147 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
148 VariableNotBoundInPattern(Name, usize),
149 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
150 VariableBoundWithDifferentMode(Name, usize),
151 /// error E0410: variable from pattern is not bound in pattern #1
152 VariableNotBoundInParentPattern(Name, usize),
153 /// error E0411: use of `Self` outside of an impl or trait
154 SelfUsedOutsideImplOrTrait,
155 /// error E0412: use of undeclared
156 UseOfUndeclared(&'a str, &'a str),
157 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
158 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
159 /// error E0414: only irrefutable patterns allowed here
160 OnlyIrrefutablePatternsAllowedHere,
161 /// error E0415: identifier is bound more than once in this parameter list
162 IdentifierBoundMoreThanOnceInParameterList(&'a str),
163 /// error E0416: identifier is bound more than once in the same pattern
164 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
165 /// error E0417: static variables cannot be referenced in a pattern
166 StaticVariableReference,
167 /// error E0418: is not an enum variant, struct or const
168 NotAnEnumVariantStructOrConst(&'a str),
169 /// error E0419: unresolved enum variant, struct or const
170 UnresolvedEnumVariantStructOrConst(&'a str),
171 /// error E0420: is not an associated const
172 NotAnAssociatedConst(&'a str),
173 /// error E0421: unresolved associated const
174 UnresolvedAssociatedConst(&'a str),
175 /// error E0422: does not name a struct
176 DoesNotNameAStruct(&'a str),
177 /// error E0423: is a struct variant name, but this expression uses it like a function name
178 StructVariantUsedAsFunction(&'a str),
179 /// error E0424: `self` is not available in a static method
180 SelfNotAvailableInStaticMethod,
181 /// error E0425: unresolved name
182 UnresolvedName(&'a str, &'a str),
183 /// error E0426: use of undeclared label
184 UndeclaredLabel(&'a str),
185 /// error E0427: cannot use `ref` binding mode with ...
186 CannotUseRefBindingModeWith(&'a str),
187 /// error E0428: duplicate definition
188 DuplicateDefinition(&'a str, Name),
189 /// error E0429: `self` imports are only allowed within a { } list
190 SelfImportsOnlyAllowedWithin,
191 /// error E0430: `self` import can only appear once in the list
192 SelfImportCanOnlyAppearOnceInTheList,
193 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
194 SelfImportOnlyInImportListWithNonEmptyPrefix,
195 /// error E0432: unresolved import
196 UnresolvedImport(Option<(&'a str, &'a str)>),
197 /// error E0433: failed to resolve
198 FailedToResolve(&'a str),
199 /// error E0434: can't capture dynamic environment in a fn item
200 CannotCaptureDynamicEnvironmentInFnItem,
201 /// error E0435: attempt to use a non-constant value in a constant
202 AttemptToUseNonConstantValueInConstant,
205 fn resolve_error<'b, 'a:'b, 'tcx:'a>(resolver: &'b Resolver<'a, 'tcx>, span: syntax::codemap::Span,
206 resolution_error: ResolutionError<'b>) {
207 if !resolver.emit_errors {
210 match resolution_error {
211 ResolutionError::TypeParametersFromOuterFunction => {
212 span_err!(resolver.session, span, E0401, "can't use type parameters from \
213 outer function; try using a local \
214 type parameter instead");
216 ResolutionError::OuterTypeParameterContext => {
217 span_err!(resolver.session, span, E0402,
218 "cannot use an outer type parameter in this context");
220 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
221 span_err!(resolver.session, span, E0403,
222 "the name `{}` is already used for a type \
223 parameter in this type parameter list", name);
225 ResolutionError::IsNotATrait(name) => {
226 span_err!(resolver.session, span, E0404,
227 "`{}` is not a trait",
230 ResolutionError::UndeclaredTraitName(name) => {
231 span_err!(resolver.session, span, E0405,
232 "use of undeclared trait name `{}`",
235 ResolutionError::UndeclaredAssociatedType => {
236 span_err!(resolver.session, span, E0406, "undeclared associated type");
238 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
239 span_err!(resolver.session, span, E0407,
240 "method `{}` is not a member of trait `{}`",
244 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
245 span_err!(resolver.session, span, E0437,
246 "type `{}` is not a member of trait `{}`",
250 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
251 span_err!(resolver.session, span, E0438,
252 "const `{}` is not a member of trait `{}`",
256 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
257 span_err!(resolver.session, span, E0408,
258 "variable `{}` from pattern #1 is not bound in pattern #{}",
262 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
263 span_err!(resolver.session, span, E0409,
264 "variable `{}` is bound with different \
265 mode in pattern #{} than in pattern #1",
269 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
270 span_err!(resolver.session, span, E0410,
271 "variable `{}` from pattern #{} is not bound in pattern #1",
275 ResolutionError::SelfUsedOutsideImplOrTrait => {
276 span_err!(resolver.session, span, E0411, "use of `Self` outside of an impl or trait");
278 ResolutionError::UseOfUndeclared(kind, name) => {
279 span_err!(resolver.session, span, E0412,
280 "use of undeclared {} `{}`",
284 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
285 span_err!(resolver.session, span, E0413,
286 "declaration of `{}` shadows an enum variant or unit-like struct in \
290 ResolutionError::OnlyIrrefutablePatternsAllowedHere => {
291 span_err!(resolver.session, span, E0414, "only irrefutable patterns allowed here");
293 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
294 span_err!(resolver.session, span, E0415,
295 "identifier `{}` is bound more than once in this parameter list",
298 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
299 span_err!(resolver.session, span, E0416,
300 "identifier `{}` is bound more than once in the same pattern",
303 ResolutionError::StaticVariableReference => {
304 span_err!(resolver.session, span, E0417, "static variables cannot be \
305 referenced in a pattern, \
306 use a `const` instead");
308 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
309 span_err!(resolver.session, span, E0418,
310 "`{}` is not an enum variant, struct or const",
313 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
314 span_err!(resolver.session, span, E0419,
315 "unresolved enum variant, struct or const `{}`",
318 ResolutionError::NotAnAssociatedConst(name) => {
319 span_err!(resolver.session, span, E0420,
320 "`{}` is not an associated const",
323 ResolutionError::UnresolvedAssociatedConst(name) => {
324 span_err!(resolver.session, span, E0421,
325 "unresolved associated const `{}`",
328 ResolutionError::DoesNotNameAStruct(name) => {
329 span_err!(resolver.session, span, E0422, "`{}` does not name a structure", name);
331 ResolutionError::StructVariantUsedAsFunction(path_name) => {
332 span_err!(resolver.session, span, E0423,
333 "`{}` is the name of a struct or struct variant, \
334 but this expression \
335 uses it like a function name",
338 ResolutionError::SelfNotAvailableInStaticMethod => {
339 span_err!(resolver.session, span, E0424, "`self` is not available in a static method. \
340 Maybe a `self` argument is missing?");
342 ResolutionError::UnresolvedName(path, name) => {
343 span_err!(resolver.session, span, E0425,
344 "unresolved name `{}`{}",
348 ResolutionError::UndeclaredLabel(name) => {
349 span_err!(resolver.session, span, E0426,
350 "use of undeclared label `{}`",
353 ResolutionError::CannotUseRefBindingModeWith(descr) => {
354 span_err!(resolver.session, span, E0427,
355 "cannot use `ref` binding mode with {}",
358 ResolutionError::DuplicateDefinition(namespace, name) => {
359 span_err!(resolver.session, span, E0428,
360 "duplicate definition of {} `{}`",
364 ResolutionError::SelfImportsOnlyAllowedWithin => {
365 span_err!(resolver.session, span, E0429, "{}",
366 "`self` imports are only allowed within a { } list");
368 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
369 span_err!(resolver.session, span, E0430,
370 "`self` import can only appear once in the list");
372 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
373 span_err!(resolver.session, span, E0431,
374 "`self` import can only appear in an import list with a \
377 ResolutionError::UnresolvedImport(name) => {
378 let msg = match name {
379 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
380 None => "unresolved import".to_owned()
382 span_err!(resolver.session, span, E0432, "{}", msg);
384 ResolutionError::FailedToResolve(msg) => {
385 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
387 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
388 span_err!(resolver.session, span, E0434, "{}",
389 "can't capture dynamic environment in a fn item; \
390 use the || { ... } closure form instead");
392 ResolutionError::AttemptToUseNonConstantValueInConstant =>{
393 span_err!(resolver.session, span, E0435,
394 "attempt to use a non-constant value in a constant");
399 #[derive(Copy, Clone)]
402 binding_mode: BindingMode,
405 // Map from the name in a pattern to its binding mode.
406 type BindingMap = HashMap<Name, BindingInfo>;
408 #[derive(Copy, Clone, PartialEq)]
409 enum PatternBindingMode {
411 LocalIrrefutableMode,
412 ArgumentIrrefutableMode,
415 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
421 /// A NamespaceResult represents the result of resolving an import in
422 /// a particular namespace. The result is either definitely-resolved,
423 /// definitely- unresolved, or unknown.
425 enum NamespaceResult {
426 /// Means that resolve hasn't gathered enough information yet to determine
427 /// whether the name is bound in this namespace. (That is, it hasn't
428 /// resolved all `use` directives yet.)
430 /// Means that resolve has determined that the name is definitely
431 /// not bound in the namespace.
433 /// Means that resolve has determined that the name is bound in the Module
434 /// argument, and specified by the NameBindings argument.
435 BoundResult(Rc<Module>, Rc<NameBindings>)
438 impl NamespaceResult {
439 fn is_unknown(&self) -> bool {
441 UnknownResult => true,
445 fn is_unbound(&self) -> bool {
447 UnboundResult => true,
453 enum NameDefinition {
454 // The name was unbound.
456 // The name identifies an immediate child.
457 ChildNameDefinition(Def, LastPrivate),
458 // The name identifies an import.
459 ImportNameDefinition(Def, LastPrivate),
462 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
463 fn visit_item(&mut self, item: &Item) {
464 execute_callback!(hir_map::Node::NodeItem(item), self);
465 self.resolve_item(item);
467 fn visit_arm(&mut self, arm: &Arm) {
468 self.resolve_arm(arm);
470 fn visit_block(&mut self, block: &Block) {
471 execute_callback!(hir_map::Node::NodeBlock(block), self);
472 self.resolve_block(block);
474 fn visit_expr(&mut self, expr: &Expr) {
475 execute_callback!(hir_map::Node::NodeExpr(expr), self);
476 self.resolve_expr(expr);
478 fn visit_local(&mut self, local: &Local) {
479 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
480 self.resolve_local(local);
482 fn visit_ty(&mut self, ty: &Ty) {
483 self.resolve_type(ty);
485 fn visit_generics(&mut self, generics: &Generics) {
486 self.resolve_generics(generics);
488 fn visit_poly_trait_ref(&mut self,
489 tref: &hir::PolyTraitRef,
490 m: &hir::TraitBoundModifier) {
491 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
492 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
493 Err(_) => { /* error already reported */ }
495 visit::walk_poly_trait_ref(self, tref, m);
497 fn visit_variant(&mut self, variant: &hir::Variant, generics: &Generics) {
498 execute_callback!(hir_map::Node::NodeVariant(variant), self);
499 if let Some(ref dis_expr) = variant.node.disr_expr {
500 // resolve the discriminator expr as a constant
501 self.with_constant_rib(|this| {
502 this.visit_expr(&**dis_expr);
506 // `visit::walk_variant` without the discriminant expression.
507 match variant.node.kind {
508 hir::TupleVariantKind(ref variant_arguments) => {
509 for variant_argument in variant_arguments {
510 self.visit_ty(&*variant_argument.ty);
513 hir::StructVariantKind(ref struct_definition) => {
514 self.visit_struct_def(&**struct_definition,
521 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
522 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
523 let type_parameters = match foreign_item.node {
524 ForeignItemFn(_, ref generics) => {
525 HasTypeParameters(generics, FnSpace, ItemRibKind)
527 ForeignItemStatic(..) => NoTypeParameters
529 self.with_type_parameter_rib(type_parameters, |this| {
530 visit::walk_foreign_item(this, foreign_item);
533 fn visit_fn(&mut self,
534 function_kind: FnKind<'v>,
535 declaration: &'v FnDecl,
539 let rib_kind = match function_kind {
540 FnKind::ItemFn(_, generics, _, _, _, _) => {
541 self.visit_generics(generics);
544 FnKind::Method(_, sig, _) => {
545 self.visit_generics(&sig.generics);
546 self.visit_explicit_self(&sig.explicit_self);
549 FnKind::Closure(..) => ClosureRibKind(node_id)
551 self.resolve_function(rib_kind, declaration, block);
555 type ErrorMessage = Option<(Span, String)>;
557 enum ResolveResult<T> {
558 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
559 Indeterminate, // Couldn't determine due to unresolved globs.
560 Success(T) // Successfully resolved the import.
563 impl<T> ResolveResult<T> {
564 fn success(&self) -> bool {
565 match *self { Success(_) => true, _ => false }
569 enum FallbackSuggestion {
574 StaticMethod(String),
578 #[derive(Copy, Clone)]
579 enum TypeParameters<'a> {
585 // Identifies the things that these parameters
586 // were declared on (type, fn, etc)
589 // The kind of the rib used for type parameters.
593 // The rib kind controls the translation of local
594 // definitions (`DefLocal`) to upvars (`DefUpvar`).
595 #[derive(Copy, Clone, Debug)]
597 // No translation needs to be applied.
600 // We passed through a closure scope at the given node ID.
601 // Translate upvars as appropriate.
602 ClosureRibKind(NodeId /* func id */),
604 // We passed through an impl or trait and are now in one of its
605 // methods. Allow references to ty params that impl or trait
606 // binds. Disallow any other upvars (including other ty params that are
610 // We passed through an item scope. Disallow upvars.
613 // We're in a constant item. Can't refer to dynamic stuff.
617 #[derive(Copy, Clone)]
618 enum UseLexicalScopeFlag {
623 enum ModulePrefixResult {
625 PrefixFound(Rc<Module>, usize)
628 #[derive(Copy, Clone)]
629 enum AssocItemResolveResult {
630 /// Syntax such as `<T>::item`, which can't be resolved until type
633 /// We should have been able to resolve the associated item.
634 ResolveAttempt(Option<PathResolution>),
637 #[derive(Copy, Clone, PartialEq)]
638 enum NameSearchType {
639 /// We're doing a name search in order to resolve a `use` directive.
642 /// We're doing a name search in order to resolve a path type, a path
643 /// expression, or a path pattern.
647 #[derive(Copy, Clone)]
648 enum BareIdentifierPatternResolution {
649 FoundStructOrEnumVariant(Def, LastPrivate),
650 FoundConst(Def, LastPrivate),
651 BareIdentifierPatternUnresolved
657 bindings: HashMap<Name, DefLike>,
662 fn new(kind: RibKind) -> Rib {
664 bindings: HashMap::new(),
670 /// The link from a module up to its nearest parent node.
671 #[derive(Clone,Debug)]
674 ModuleParentLink(Weak<Module>, Name),
675 BlockParentLink(Weak<Module>, NodeId)
678 /// The type of module this is.
679 #[derive(Copy, Clone, PartialEq, Debug)]
688 /// One node in the tree of modules.
690 parent_link: ParentLink,
691 def_id: Cell<Option<DefId>>,
692 kind: Cell<ModuleKind>,
695 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
696 imports: RefCell<Vec<ImportDirective>>,
698 // The external module children of this node that were declared with
700 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
702 // The anonymous children of this node. Anonymous children are pseudo-
703 // modules that are implicitly created around items contained within
706 // For example, if we have this:
714 // There will be an anonymous module created around `g` with the ID of the
715 // entry block for `f`.
716 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
718 // The status of resolving each import in this module.
719 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
721 // The number of unresolved globs that this module exports.
722 glob_count: Cell<usize>,
724 // The number of unresolved pub imports (both regular and globs) in this module
725 pub_count: Cell<usize>,
727 // The number of unresolved pub glob imports in this module
728 pub_glob_count: Cell<usize>,
730 // The index of the import we're resolving.
731 resolved_import_count: Cell<usize>,
733 // Whether this module is populated. If not populated, any attempt to
734 // access the children must be preceded with a
735 // `populate_module_if_necessary` call.
736 populated: Cell<bool>,
740 fn new(parent_link: ParentLink,
741 def_id: Option<DefId>,
747 parent_link: parent_link,
748 def_id: Cell::new(def_id),
749 kind: Cell::new(kind),
750 is_public: is_public,
751 children: RefCell::new(HashMap::new()),
752 imports: RefCell::new(Vec::new()),
753 external_module_children: RefCell::new(HashMap::new()),
754 anonymous_children: RefCell::new(NodeMap()),
755 import_resolutions: RefCell::new(HashMap::new()),
756 glob_count: Cell::new(0),
757 pub_count: Cell::new(0),
758 pub_glob_count: Cell::new(0),
759 resolved_import_count: Cell::new(0),
760 populated: Cell::new(!external),
764 fn all_imports_resolved(&self) -> bool {
765 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
766 // it is currently being resolved ! so nope
769 self.imports.borrow().len() == self.resolved_import_count.get()
775 pub fn inc_glob_count(&self) {
776 self.glob_count.set(self.glob_count.get() + 1);
778 pub fn dec_glob_count(&self) {
779 assert!(self.glob_count.get() > 0);
780 self.glob_count.set(self.glob_count.get() - 1);
782 pub fn inc_pub_count(&self) {
783 self.pub_count.set(self.pub_count.get() + 1);
785 pub fn dec_pub_count(&self) {
786 assert!(self.pub_count.get() > 0);
787 self.pub_count.set(self.pub_count.get() - 1);
789 pub fn inc_pub_glob_count(&self) {
790 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
792 pub fn dec_pub_glob_count(&self) {
793 assert!(self.pub_glob_count.get() > 0);
794 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
798 impl fmt::Debug for Module {
799 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
800 write!(f, "{:?}, kind: {:?}, {}",
803 if self.is_public { "public" } else { "private" } )
809 flags DefModifiers: u8 {
810 const PUBLIC = 1 << 0,
811 const IMPORTABLE = 1 << 1,
815 // Records a possibly-private type definition.
816 #[derive(Clone,Debug)]
818 modifiers: DefModifiers, // see note in ImportResolution about how to use this
819 module_def: Option<Rc<Module>>,
820 type_def: Option<Def>,
821 type_span: Option<Span>
824 // Records a possibly-private value definition.
825 #[derive(Clone, Copy, Debug)]
827 modifiers: DefModifiers, // see note in ImportResolution about how to use this
829 value_span: Option<Span>,
832 // Records the definitions (at most one for each namespace) that a name is
835 pub struct NameBindings {
836 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
837 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
841 fn new() -> NameBindings {
843 type_def: RefCell::new(None),
844 value_def: RefCell::new(None),
848 /// Creates a new module in this set of name bindings.
849 fn define_module(&self,
850 parent_link: ParentLink,
851 def_id: Option<DefId>,
856 // Merges the module with the existing type def or creates a new one.
857 let modifiers = if is_public {
860 DefModifiers::empty()
861 } | DefModifiers::IMPORTABLE;
862 let module_ = Rc::new(Module::new(parent_link,
867 let type_def = self.type_def.borrow().clone();
870 *self.type_def.borrow_mut() = Some(TypeNsDef {
871 modifiers: modifiers,
872 module_def: Some(module_),
878 *self.type_def.borrow_mut() = Some(TypeNsDef {
879 modifiers: modifiers,
880 module_def: Some(module_),
882 type_def: type_def.type_def
888 /// Sets the kind of the module, creating a new one if necessary.
889 fn set_module_kind(&self,
890 parent_link: ParentLink,
891 def_id: Option<DefId>,
896 let modifiers = if is_public {
899 DefModifiers::empty()
900 } | DefModifiers::IMPORTABLE;
901 let type_def = self.type_def.borrow().clone();
904 let module = Module::new(parent_link,
909 *self.type_def.borrow_mut() = Some(TypeNsDef {
910 modifiers: modifiers,
911 module_def: Some(Rc::new(module)),
917 match type_def.module_def {
919 let module = Module::new(parent_link,
924 *self.type_def.borrow_mut() = Some(TypeNsDef {
925 modifiers: modifiers,
926 module_def: Some(Rc::new(module)),
927 type_def: type_def.type_def,
931 Some(module_def) => module_def.kind.set(kind),
937 /// Records a type definition.
938 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
939 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
940 // Merges the type with the existing type def or creates a new one.
941 let type_def = self.type_def.borrow().clone();
944 *self.type_def.borrow_mut() = Some(TypeNsDef {
948 modifiers: modifiers,
952 *self.type_def.borrow_mut() = Some(TypeNsDef {
953 module_def: type_def.module_def,
956 modifiers: modifiers,
962 /// Records a value definition.
963 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
964 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
965 *self.value_def.borrow_mut() = Some(ValueNsDef {
967 value_span: Some(sp),
968 modifiers: modifiers,
972 /// Returns the module node if applicable.
973 fn get_module_if_available(&self) -> Option<Rc<Module>> {
974 match *self.type_def.borrow() {
975 Some(ref type_def) => type_def.module_def.clone(),
980 /// Returns the module node. Panics if this node does not have a module
982 fn get_module(&self) -> Rc<Module> {
983 match self.get_module_if_available() {
985 panic!("get_module called on a node with no module \
988 Some(module_def) => module_def
992 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
994 TypeNS => return self.type_def.borrow().is_some(),
995 ValueNS => return self.value_def.borrow().is_some()
999 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
1000 self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
1003 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
1005 TypeNS => match *self.type_def.borrow() {
1006 Some(ref def) => def.modifiers.contains(modifiers), None => false
1008 ValueNS => match *self.value_def.borrow() {
1009 Some(ref def) => def.modifiers.contains(modifiers), None => false
1014 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
1017 match *self.type_def.borrow() {
1019 Some(ref type_def) => {
1020 match type_def.type_def {
1021 Some(type_def) => Some(type_def),
1023 match type_def.module_def {
1024 Some(ref module) => {
1025 match module.def_id.get() {
1026 Some(did) => Some(DefMod(did)),
1038 match *self.value_def.borrow() {
1040 Some(value_def) => Some(value_def.def)
1046 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
1047 if self.defined_in_namespace(namespace) {
1050 match *self.type_def.borrow() {
1052 Some(ref type_def) => type_def.type_span
1056 match *self.value_def.borrow() {
1058 Some(ref value_def) => value_def.value_span
1067 fn is_public(&self, namespace: Namespace) -> bool {
1070 let type_def = self.type_def.borrow();
1071 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
1074 let value_def = self.value_def.borrow();
1075 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
1081 /// Interns the names of the primitive types.
1082 struct PrimitiveTypeTable {
1083 primitive_types: HashMap<Name, PrimTy>,
1086 impl PrimitiveTypeTable {
1087 fn new() -> PrimitiveTypeTable {
1088 let mut table = PrimitiveTypeTable {
1089 primitive_types: HashMap::new()
1092 table.intern("bool", TyBool);
1093 table.intern("char", TyChar);
1094 table.intern("f32", TyFloat(TyF32));
1095 table.intern("f64", TyFloat(TyF64));
1096 table.intern("isize", TyInt(TyIs));
1097 table.intern("i8", TyInt(TyI8));
1098 table.intern("i16", TyInt(TyI16));
1099 table.intern("i32", TyInt(TyI32));
1100 table.intern("i64", TyInt(TyI64));
1101 table.intern("str", TyStr);
1102 table.intern("usize", TyUint(TyUs));
1103 table.intern("u8", TyUint(TyU8));
1104 table.intern("u16", TyUint(TyU16));
1105 table.intern("u32", TyUint(TyU32));
1106 table.intern("u64", TyUint(TyU64));
1111 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1112 self.primitive_types.insert(token::intern(string), primitive_type);
1116 /// The main resolver class.
1117 pub struct Resolver<'a, 'tcx:'a> {
1118 session: &'a Session,
1120 ast_map: &'a hir_map::Map<'tcx>,
1122 graph_root: NameBindings,
1124 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1126 structs: FnvHashMap<DefId, Vec<Name>>,
1128 // The number of imports that are currently unresolved.
1129 unresolved_imports: usize,
1131 // The module that represents the current item scope.
1132 current_module: Rc<Module>,
1134 // The current set of local scopes, for values.
1135 // FIXME #4948: Reuse ribs to avoid allocation.
1136 value_ribs: Vec<Rib>,
1138 // The current set of local scopes, for types.
1139 type_ribs: Vec<Rib>,
1141 // The current set of local scopes, for labels.
1142 label_ribs: Vec<Rib>,
1144 // The trait that the current context can refer to.
1145 current_trait_ref: Option<(DefId, TraitRef)>,
1147 // The current self type if inside an impl (used for better errors).
1148 current_self_type: Option<Ty>,
1150 // The idents for the primitive types.
1151 primitive_type_table: PrimitiveTypeTable,
1154 freevars: RefCell<FreevarMap>,
1155 freevars_seen: RefCell<NodeMap<NodeSet>>,
1156 export_map: ExportMap,
1157 trait_map: TraitMap,
1158 external_exports: ExternalExports,
1160 // Whether or not to print error messages. Can be set to true
1161 // when getting additional info for error message suggestions,
1162 // so as to avoid printing duplicate errors
1165 make_glob_map: bool,
1166 // Maps imports to the names of items actually imported (this actually maps
1167 // all imports, but only glob imports are actually interesting).
1170 used_imports: HashSet<(NodeId, Namespace)>,
1171 used_crates: HashSet<CrateNum>,
1173 // Callback function for intercepting walks
1174 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1175 // The intention is that the callback modifies this flag.
1176 // Once set, the resolver falls out of the walk, preserving the ribs.
1181 #[derive(PartialEq)]
1182 enum FallbackChecks {
1187 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1188 fn new(session: &'a Session,
1189 ast_map: &'a hir_map::Map<'tcx>,
1191 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
1192 let graph_root = NameBindings::new();
1194 graph_root.define_module(NoParentLink,
1195 Some(DefId { krate: 0, node: 0 }),
1201 let current_module = graph_root.get_module();
1208 // The outermost module has def ID 0; this is not reflected in the
1211 graph_root: graph_root,
1213 trait_item_map: FnvHashMap(),
1214 structs: FnvHashMap(),
1216 unresolved_imports: 0,
1218 current_module: current_module,
1219 value_ribs: Vec::new(),
1220 type_ribs: Vec::new(),
1221 label_ribs: Vec::new(),
1223 current_trait_ref: None,
1224 current_self_type: None,
1226 primitive_type_table: PrimitiveTypeTable::new(),
1228 def_map: RefCell::new(NodeMap()),
1229 freevars: RefCell::new(NodeMap()),
1230 freevars_seen: RefCell::new(NodeMap()),
1231 export_map: NodeMap(),
1232 trait_map: NodeMap(),
1233 used_imports: HashSet::new(),
1234 used_crates: HashSet::new(),
1235 external_exports: DefIdSet(),
1238 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1239 glob_map: HashMap::new(),
1248 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1249 if !self.make_glob_map {
1252 if self.glob_map.contains_key(&import_id) {
1253 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1257 let mut new_set = HashSet::new();
1258 new_set.insert(name);
1259 self.glob_map.insert(import_id, new_set);
1262 fn get_trait_name(&self, did: DefId) -> Name {
1264 self.ast_map.expect_item(did.node).ident.name
1266 csearch::get_trait_name(&self.session.cstore, did)
1270 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1272 type_def: RefCell::new(Some(TypeNsDef {
1273 modifiers: DefModifiers::IMPORTABLE,
1274 module_def: Some(module),
1278 value_def: RefCell::new(None),
1282 /// Checks that the names of external crates don't collide with other
1283 /// external crates.
1284 fn check_for_conflicts_between_external_crates(&self,
1288 if module.external_module_children.borrow().contains_key(&name) {
1289 span_err!(self.session, span, E0259,
1290 "an external crate named `{}` has already \
1291 been imported into this module",
1296 /// Checks that the names of items don't collide with external crates.
1297 fn check_for_conflicts_between_external_crates_and_items(&self,
1301 if module.external_module_children.borrow().contains_key(&name) {
1302 span_err!(self.session, span, E0260,
1303 "the name `{}` conflicts with an external \
1304 crate that has been imported into this \
1310 /// Resolves the given module path from the given root `module_`.
1311 fn resolve_module_path_from_root(&mut self,
1312 module_: Rc<Module>,
1313 module_path: &[Name],
1316 name_search_type: NameSearchType,
1318 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1319 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1320 -> Option<Rc<Module>> {
1321 match module.external_module_children.borrow().get(&needle) {
1322 Some(_) => Some(module.clone()),
1323 None => match module.parent_link {
1324 ModuleParentLink(ref parent, _) => {
1325 search_parent_externals(needle, &parent.upgrade().unwrap())
1332 let mut search_module = module_;
1333 let mut index = index;
1334 let module_path_len = module_path.len();
1335 let mut closest_private = lp;
1337 // Resolve the module part of the path. This does not involve looking
1338 // upward though scope chains; we simply resolve names directly in
1339 // modules as we go.
1340 while index < module_path_len {
1341 let name = module_path[index];
1342 match self.resolve_name_in_module(search_module.clone(),
1348 let segment_name = name.as_str();
1349 let module_name = module_to_string(&*search_module);
1350 let mut span = span;
1351 let msg = if "???" == &module_name[..] {
1352 span.hi = span.lo + Pos::from_usize(segment_name.len());
1354 match search_parent_externals(name,
1355 &self.current_module) {
1357 let path_str = names_to_string(module_path);
1358 let target_mod_str = module_to_string(&*module);
1359 let current_mod_str =
1360 module_to_string(&*self.current_module);
1362 let prefix = if target_mod_str == current_mod_str {
1363 "self::".to_string()
1365 format!("{}::", target_mod_str)
1368 format!("Did you mean `{}{}`?", prefix, path_str)
1370 None => format!("Maybe a missing `extern crate {}`?",
1374 format!("Could not find `{}` in `{}`",
1379 return Failed(Some((span, msg)));
1381 Failed(err) => return Failed(err),
1383 debug!("(resolving module path for import) module \
1384 resolution is indeterminate: {}",
1386 return Indeterminate;
1388 Success((target, used_proxy)) => {
1389 // Check to see whether there are type bindings, and, if
1390 // so, whether there is a module within.
1391 match *target.bindings.type_def.borrow() {
1392 Some(ref type_def) => {
1393 match type_def.module_def {
1395 let msg = format!("Not a module `{}`",
1398 return Failed(Some((span, msg)));
1400 Some(ref module_def) => {
1401 search_module = module_def.clone();
1403 // track extern crates for unused_extern_crate lint
1404 if let Some(did) = module_def.def_id.get() {
1405 self.used_crates.insert(did.krate);
1408 // Keep track of the closest
1409 // private module used when
1410 // resolving this import chain.
1411 if !used_proxy && !search_module.is_public {
1412 if let Some(did) = search_module.def_id.get() {
1413 closest_private = LastMod(DependsOn(did));
1420 // There are no type bindings at all.
1421 let msg = format!("Not a module `{}`",
1423 return Failed(Some((span, msg)));
1432 return Success((search_module, closest_private));
1435 /// Attempts to resolve the module part of an import directive or path
1436 /// rooted at the given module.
1438 /// On success, returns the resolved module, and the closest *private*
1439 /// module found to the destination when resolving this path.
1440 fn resolve_module_path(&mut self,
1441 module_: Rc<Module>,
1442 module_path: &[Name],
1443 use_lexical_scope: UseLexicalScopeFlag,
1445 name_search_type: NameSearchType)
1446 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1447 let module_path_len = module_path.len();
1448 assert!(module_path_len > 0);
1450 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1451 names_to_string(module_path),
1452 module_to_string(&*module_));
1454 // Resolve the module prefix, if any.
1455 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1461 match module_prefix_result {
1463 let mpath = names_to_string(module_path);
1464 let mpath = &mpath[..];
1465 match mpath.rfind(':') {
1467 let msg = format!("Could not find `{}` in `{}`",
1468 // idx +- 1 to account for the
1469 // colons on either side
1472 return Failed(Some((span, msg)));
1479 Failed(err) => return Failed(err),
1481 debug!("(resolving module path for import) indeterminate; \
1483 return Indeterminate;
1485 Success(NoPrefixFound) => {
1486 // There was no prefix, so we're considering the first element
1487 // of the path. How we handle this depends on whether we were
1488 // instructed to use lexical scope or not.
1489 match use_lexical_scope {
1490 DontUseLexicalScope => {
1491 // This is a crate-relative path. We will start the
1492 // resolution process at index zero.
1493 search_module = self.graph_root.get_module();
1495 last_private = LastMod(AllPublic);
1497 UseLexicalScope => {
1498 // This is not a crate-relative path. We resolve the
1499 // first component of the path in the current lexical
1500 // scope and then proceed to resolve below that.
1501 match self.resolve_module_in_lexical_scope(module_,
1503 Failed(err) => return Failed(err),
1505 debug!("(resolving module path for import) \
1506 indeterminate; bailing");
1507 return Indeterminate;
1509 Success(containing_module) => {
1510 search_module = containing_module;
1512 last_private = LastMod(AllPublic);
1518 Success(PrefixFound(ref containing_module, index)) => {
1519 search_module = containing_module.clone();
1520 start_index = index;
1521 last_private = LastMod(DependsOn(containing_module.def_id
1527 self.resolve_module_path_from_root(search_module,
1535 /// Invariant: This must only be called during main resolution, not during
1536 /// import resolution.
1537 fn resolve_item_in_lexical_scope(&mut self,
1538 module_: Rc<Module>,
1540 namespace: Namespace)
1541 -> ResolveResult<(Target, bool)> {
1542 debug!("(resolving item in lexical scope) resolving `{}` in \
1543 namespace {:?} in `{}`",
1546 module_to_string(&*module_));
1548 // The current module node is handled specially. First, check for
1549 // its immediate children.
1550 build_reduced_graph::populate_module_if_necessary(self, &module_);
1552 match module_.children.borrow().get(&name) {
1554 if name_bindings.defined_in_namespace(namespace) => {
1555 debug!("top name bindings succeeded");
1556 return Success((Target::new(module_.clone(),
1557 name_bindings.clone(),
1561 Some(_) | None => { /* Not found; continue. */ }
1564 // Now check for its import directives. We don't have to have resolved
1565 // all its imports in the usual way; this is because chains of
1566 // adjacent import statements are processed as though they mutated the
1568 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1569 match (*import_resolution).target_for_namespace(namespace) {
1571 // Not found; continue.
1572 debug!("(resolving item in lexical scope) found \
1573 import resolution, but not in namespace {:?}",
1577 debug!("(resolving item in lexical scope) using \
1578 import resolution");
1579 // track used imports and extern crates as well
1580 let id = import_resolution.id(namespace);
1581 self.used_imports.insert((id, namespace));
1582 self.record_import_use(id, name);
1583 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1584 self.used_crates.insert(kid);
1586 return Success((target, false));
1591 // Search for external modules.
1592 if namespace == TypeNS {
1593 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1594 let child = module_.external_module_children.borrow().get(&name).cloned();
1595 if let Some(module) = child {
1597 Rc::new(Resolver::create_name_bindings_from_module(module));
1598 debug!("lower name bindings succeeded");
1599 return Success((Target::new(module_,
1606 // Finally, proceed up the scope chain looking for parent modules.
1607 let mut search_module = module_;
1609 // Go to the next parent.
1610 match search_module.parent_link.clone() {
1612 // No more parents. This module was unresolved.
1613 debug!("(resolving item in lexical scope) unresolved \
1615 return Failed(None);
1617 ModuleParentLink(parent_module_node, _) => {
1618 match search_module.kind.get() {
1619 NormalModuleKind => {
1620 // We stop the search here.
1621 debug!("(resolving item in lexical \
1622 scope) unresolved module: not \
1623 searching through module \
1625 return Failed(None);
1630 AnonymousModuleKind => {
1631 search_module = parent_module_node.upgrade().unwrap();
1635 BlockParentLink(ref parent_module_node, _) => {
1636 search_module = parent_module_node.upgrade().unwrap();
1640 // Resolve the name in the parent module.
1641 match self.resolve_name_in_module(search_module.clone(),
1646 Failed(Some((span, msg))) => {
1647 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1649 Failed(None) => (), // Continue up the search chain.
1651 // We couldn't see through the higher scope because of an
1652 // unresolved import higher up. Bail.
1654 debug!("(resolving item in lexical scope) indeterminate \
1655 higher scope; bailing");
1656 return Indeterminate;
1658 Success((target, used_reexport)) => {
1659 // We found the module.
1660 debug!("(resolving item in lexical scope) found name \
1662 return Success((target, used_reexport));
1668 /// Resolves a module name in the current lexical scope.
1669 fn resolve_module_in_lexical_scope(&mut self,
1670 module_: Rc<Module>,
1672 -> ResolveResult<Rc<Module>> {
1673 // If this module is an anonymous module, resolve the item in the
1674 // lexical scope. Otherwise, resolve the item from the crate root.
1675 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1676 match resolve_result {
1677 Success((target, _)) => {
1678 let bindings = &*target.bindings;
1679 match *bindings.type_def.borrow() {
1680 Some(ref type_def) => {
1681 match type_def.module_def {
1683 debug!("!!! (resolving module in lexical \
1684 scope) module wasn't actually a \
1686 return Failed(None);
1688 Some(ref module_def) => {
1689 return Success(module_def.clone());
1694 debug!("!!! (resolving module in lexical scope) module
1695 wasn't actually a module!");
1696 return Failed(None);
1701 debug!("(resolving module in lexical scope) indeterminate; \
1703 return Indeterminate;
1706 debug!("(resolving module in lexical scope) failed to resolve");
1712 /// Returns the nearest normal module parent of the given module.
1713 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1714 -> Option<Rc<Module>> {
1715 let mut module_ = module_;
1717 match module_.parent_link.clone() {
1718 NoParentLink => return None,
1719 ModuleParentLink(new_module, _) |
1720 BlockParentLink(new_module, _) => {
1721 let new_module = new_module.upgrade().unwrap();
1722 match new_module.kind.get() {
1723 NormalModuleKind => return Some(new_module),
1727 AnonymousModuleKind => module_ = new_module,
1734 /// Returns the nearest normal module parent of the given module, or the
1735 /// module itself if it is a normal module.
1736 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1738 match module_.kind.get() {
1739 NormalModuleKind => return module_,
1743 AnonymousModuleKind => {
1744 match self.get_nearest_normal_module_parent(module_.clone()) {
1746 Some(new_module) => new_module
1752 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1753 /// (b) some chain of `super::`.
1754 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1755 fn resolve_module_prefix(&mut self,
1756 module_: Rc<Module>,
1757 module_path: &[Name])
1758 -> ResolveResult<ModulePrefixResult> {
1759 // Start at the current module if we see `self` or `super`, or at the
1760 // top of the crate otherwise.
1761 let mut i = match &*module_path[0].as_str() {
1764 _ => return Success(NoPrefixFound),
1766 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1768 // Now loop through all the `super`s we find.
1769 while i < module_path.len() && "super" == module_path[i].as_str() {
1770 debug!("(resolving module prefix) resolving `super` at {}",
1771 module_to_string(&*containing_module));
1772 match self.get_nearest_normal_module_parent(containing_module) {
1773 None => return Failed(None),
1774 Some(new_module) => {
1775 containing_module = new_module;
1781 debug!("(resolving module prefix) finished resolving prefix at {}",
1782 module_to_string(&*containing_module));
1784 return Success(PrefixFound(containing_module, i));
1787 /// Attempts to resolve the supplied name in the given module for the
1788 /// given namespace. If successful, returns the target corresponding to
1791 /// The boolean returned on success is an indicator of whether this lookup
1792 /// passed through a public re-export proxy.
1793 fn resolve_name_in_module(&mut self,
1794 module_: Rc<Module>,
1796 namespace: Namespace,
1797 name_search_type: NameSearchType,
1798 allow_private_imports: bool)
1799 -> ResolveResult<(Target, bool)> {
1800 debug!("(resolving name in module) resolving `{}` in `{}`",
1802 module_to_string(&*module_));
1804 // First, check the direct children of the module.
1805 build_reduced_graph::populate_module_if_necessary(self, &module_);
1807 match module_.children.borrow().get(&name) {
1809 if name_bindings.defined_in_namespace(namespace) => {
1810 debug!("(resolving name in module) found node as child");
1811 return Success((Target::new(module_.clone(),
1812 name_bindings.clone(),
1821 // Next, check the module's imports if necessary.
1823 // If this is a search of all imports, we should be done with glob
1824 // resolution at this point.
1825 if name_search_type == PathSearch {
1826 assert_eq!(module_.glob_count.get(), 0);
1829 // Check the list of resolved imports.
1830 match module_.import_resolutions.borrow().get(&name) {
1831 Some(import_resolution) if allow_private_imports ||
1832 import_resolution.is_public => {
1834 if import_resolution.is_public &&
1835 import_resolution.outstanding_references != 0 {
1836 debug!("(resolving name in module) import \
1837 unresolved; bailing out");
1838 return Indeterminate;
1840 match import_resolution.target_for_namespace(namespace) {
1842 debug!("(resolving name in module) name found, \
1843 but not in namespace {:?}",
1847 debug!("(resolving name in module) resolved to \
1849 // track used imports and extern crates as well
1850 let id = import_resolution.id(namespace);
1851 self.used_imports.insert((id, namespace));
1852 self.record_import_use(id, name);
1853 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1854 self.used_crates.insert(kid);
1856 return Success((target, true));
1860 Some(..) | None => {} // Continue.
1863 // Finally, search through external children.
1864 if namespace == TypeNS {
1865 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1866 let child = module_.external_module_children.borrow().get(&name).cloned();
1867 if let Some(module) = child {
1869 Rc::new(Resolver::create_name_bindings_from_module(module));
1870 return Success((Target::new(module_,
1877 // We're out of luck.
1878 debug!("(resolving name in module) failed to resolve `{}`",
1880 return Failed(None);
1883 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1884 let index = module_.resolved_import_count.get();
1885 let imports = module_.imports.borrow();
1886 let import_count = imports.len();
1887 if index != import_count {
1889 (*imports)[index].span,
1890 ResolutionError::UnresolvedImport(None));
1893 // Descend into children and anonymous children.
1894 build_reduced_graph::populate_module_if_necessary(self, &module_);
1896 for (_, child_node) in module_.children.borrow().iter() {
1897 match child_node.get_module_if_available() {
1901 Some(child_module) => {
1902 self.report_unresolved_imports(child_module);
1907 for (_, module_) in module_.anonymous_children.borrow().iter() {
1908 self.report_unresolved_imports(module_.clone());
1914 // We maintain a list of value ribs and type ribs.
1916 // Simultaneously, we keep track of the current position in the module
1917 // graph in the `current_module` pointer. When we go to resolve a name in
1918 // the value or type namespaces, we first look through all the ribs and
1919 // then query the module graph. When we resolve a name in the module
1920 // namespace, we can skip all the ribs (since nested modules are not
1921 // allowed within blocks in Rust) and jump straight to the current module
1924 // Named implementations are handled separately. When we find a method
1925 // call, we consult the module node to find all of the implementations in
1926 // scope. This information is lazily cached in the module node. We then
1927 // generate a fake "implementation scope" containing all the
1928 // implementations thus found, for compatibility with old resolve pass.
1930 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1931 F: FnOnce(&mut Resolver),
1933 let orig_module = self.current_module.clone();
1935 // Move down in the graph.
1941 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1943 match orig_module.children.borrow().get(&name) {
1945 debug!("!!! (with scope) didn't find `{}` in `{}`",
1947 module_to_string(&*orig_module));
1949 Some(name_bindings) => {
1950 match (*name_bindings).get_module_if_available() {
1952 debug!("!!! (with scope) didn't find module \
1955 module_to_string(&*orig_module));
1958 self.current_module = module_;
1968 self.current_module = orig_module;
1971 /// Wraps the given definition in the appropriate number of `DefUpvar`
1977 -> Option<DefLike> {
1978 let mut def = match def_like {
1980 _ => return Some(def_like)
1984 self.session.span_bug(span,
1985 &format!("unexpected {:?} in bindings", def))
1987 DefLocal(node_id) => {
1991 // Nothing to do. Continue.
1993 ClosureRibKind(function_id) => {
1995 def = DefUpvar(node_id, function_id);
1997 let mut seen = self.freevars_seen.borrow_mut();
1998 let seen = match seen.entry(function_id) {
1999 Occupied(v) => v.into_mut(),
2000 Vacant(v) => v.insert(NodeSet()),
2002 if seen.contains(&node_id) {
2005 match self.freevars.borrow_mut().entry(function_id) {
2006 Occupied(v) => v.into_mut(),
2007 Vacant(v) => v.insert(vec![]),
2008 }.push(Freevar { def: prev_def, span: span });
2009 seen.insert(node_id);
2011 ItemRibKind | MethodRibKind => {
2012 // This was an attempt to access an upvar inside a
2013 // named function item. This is not allowed, so we
2018 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem
2022 ConstantItemRibKind => {
2023 // Still doesn't deal with upvars
2027 ResolutionError::AttemptToUseNonConstantValueInConstant
2034 DefTyParam(..) | DefSelfTy(..) => {
2037 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
2038 // Nothing to do. Continue.
2041 // This was an attempt to use a type parameter outside
2046 ResolutionError::TypeParametersFromOuterFunction);
2049 ConstantItemRibKind => {
2051 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2062 /// Searches the current set of local scopes and
2063 /// applies translations for closures.
2064 fn search_ribs(&self,
2068 -> Option<DefLike> {
2069 // FIXME #4950: Try caching?
2071 for (i, rib) in ribs.iter().enumerate().rev() {
2072 if let Some(def_like) = rib.bindings.get(&name).cloned() {
2073 return self.upvarify(&ribs[i + 1..], def_like, span);
2080 /// Searches the current set of local scopes for labels.
2081 /// Stops after meeting a closure.
2082 fn search_label(&self, name: Name) -> Option<DefLike> {
2083 for rib in self.label_ribs.iter().rev() {
2089 // Do not resolve labels across function boundary
2093 let result = rib.bindings.get(&name).cloned();
2094 if result.is_some() {
2101 fn resolve_crate(&mut self, krate: &hir::Crate) {
2102 debug!("(resolving crate) starting");
2104 visit::walk_crate(self, krate);
2107 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
2108 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
2109 span_err!(self.session, span, E0317,
2110 "user-defined types or type parameters cannot shadow the primitive types");
2114 fn resolve_item(&mut self, item: &Item) {
2115 let name = item.ident.name;
2117 debug!("(resolving item) resolving {}",
2121 ItemEnum(_, ref generics) |
2122 ItemTy(_, ref generics) |
2123 ItemStruct(_, ref generics) => {
2124 self.check_if_primitive_type_name(name, item.span);
2126 self.with_type_parameter_rib(HasTypeParameters(generics,
2129 |this| visit::walk_item(this, item));
2131 ItemFn(_, _, _, _, ref generics, _) => {
2132 self.with_type_parameter_rib(HasTypeParameters(generics,
2135 |this| visit::walk_item(this, item));
2138 ItemDefaultImpl(_, ref trait_ref) => {
2139 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
2146 ref impl_items) => {
2147 self.resolve_implementation(generics,
2154 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2155 self.check_if_primitive_type_name(name, item.span);
2157 // Create a new rib for the trait-wide type parameters.
2158 self.with_type_parameter_rib(HasTypeParameters(generics,
2162 this.with_self_rib(DefSelfTy(Some(DefId::local(item.id)), None), |this| {
2163 this.visit_generics(generics);
2164 visit::walk_ty_param_bounds_helper(this, bounds);
2166 for trait_item in trait_items {
2167 match trait_item.node {
2168 hir::ConstTraitItem(_, ref default) => {
2169 // Only impose the restrictions of
2170 // ConstRibKind if there's an actual constant
2171 // expression in a provided default.
2172 if default.is_some() {
2173 this.with_constant_rib(|this| {
2174 visit::walk_trait_item(this, trait_item)
2177 visit::walk_trait_item(this, trait_item)
2180 hir::MethodTraitItem(ref sig, _) => {
2181 let type_parameters =
2182 HasTypeParameters(&sig.generics,
2185 this.with_type_parameter_rib(type_parameters, |this| {
2186 visit::walk_trait_item(this, trait_item)
2189 hir::TypeTraitItem(..) => {
2190 this.check_if_primitive_type_name(trait_item.ident.name,
2192 this.with_type_parameter_rib(NoTypeParameters, |this| {
2193 visit::walk_trait_item(this, trait_item)
2202 ItemMod(_) | ItemForeignMod(_) => {
2203 self.with_scope(Some(name), |this| {
2204 visit::walk_item(this, item);
2208 ItemConst(..) | ItemStatic(..) => {
2209 self.with_constant_rib(|this| {
2210 visit::walk_item(this, item);
2214 ItemUse(ref view_path) => {
2215 // check for imports shadowing primitive types
2216 if let hir::ViewPathSimple(ident, _) = view_path.node {
2217 match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
2218 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2219 self.check_if_primitive_type_name(ident.name, item.span);
2226 ItemExternCrate(_) => {
2227 // do nothing, these are just around to be encoded
2232 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2233 F: FnOnce(&mut Resolver),
2235 match type_parameters {
2236 HasTypeParameters(generics, space, rib_kind) => {
2237 let mut function_type_rib = Rib::new(rib_kind);
2238 let mut seen_bindings = HashSet::new();
2239 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2240 let name = type_parameter.ident.name;
2241 debug!("with_type_parameter_rib: {}", type_parameter.id);
2243 if seen_bindings.contains(&name) {
2245 type_parameter.span,
2246 ResolutionError::NameAlreadyUsedInTypeParameterList(
2250 seen_bindings.insert(name);
2252 // plain insert (no renaming)
2253 function_type_rib.bindings.insert(name,
2254 DlDef(DefTyParam(space,
2256 DefId::local(type_parameter.id),
2259 self.type_ribs.push(function_type_rib);
2262 NoTypeParameters => {
2269 match type_parameters {
2270 HasTypeParameters(..) => { if !self.resolved { self.type_ribs.pop(); } }
2271 NoTypeParameters => { }
2275 fn with_label_rib<F>(&mut self, f: F) where
2276 F: FnOnce(&mut Resolver),
2278 self.label_ribs.push(Rib::new(NormalRibKind));
2281 self.label_ribs.pop();
2285 fn with_constant_rib<F>(&mut self, f: F) where
2286 F: FnOnce(&mut Resolver),
2288 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2289 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2292 self.type_ribs.pop();
2293 self.value_ribs.pop();
2297 fn resolve_function(&mut self,
2299 declaration: &FnDecl,
2301 // Create a value rib for the function.
2302 self.value_ribs.push(Rib::new(rib_kind));
2304 // Create a label rib for the function.
2305 self.label_ribs.push(Rib::new(rib_kind));
2307 // Add each argument to the rib.
2308 let mut bindings_list = HashMap::new();
2309 for argument in &declaration.inputs {
2310 self.resolve_pattern(&*argument.pat,
2311 ArgumentIrrefutableMode,
2312 &mut bindings_list);
2314 self.visit_ty(&*argument.ty);
2316 debug!("(resolving function) recorded argument");
2318 visit::walk_fn_ret_ty(self, &declaration.output);
2320 // Resolve the function body.
2321 self.visit_block(&*block);
2323 debug!("(resolving function) leaving function");
2326 self.label_ribs.pop();
2327 self.value_ribs.pop();
2331 fn resolve_trait_reference(&mut self,
2335 -> Result<PathResolution, ()> {
2336 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2337 if let DefTrait(_) = path_res.base_def {
2338 debug!("(resolving trait) found trait def: {:?}", path_res);
2343 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2347 // If it's a typedef, give a note
2348 if let DefTy(..) = path_res.base_def {
2349 self.session.span_note(trait_path.span,
2350 "`type` aliases cannot be used for traits");
2357 ResolutionError::UndeclaredTraitName(
2358 &*path_names_to_string(trait_path, path_depth))
2364 fn resolve_generics(&mut self, generics: &Generics) {
2365 for type_parameter in generics.ty_params.iter() {
2366 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2368 for predicate in &generics.where_clause.predicates {
2370 &hir::WherePredicate::BoundPredicate(_) |
2371 &hir::WherePredicate::RegionPredicate(_) => {}
2372 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2373 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2374 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2375 self.record_def(eq_pred.id, path_res.unwrap());
2379 ResolutionError::UndeclaredAssociatedType);
2384 visit::walk_generics(self, generics);
2387 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2388 where F: FnOnce(&mut Resolver) -> T
2390 // Handle nested impls (inside fn bodies)
2391 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2392 let result = f(self);
2393 self.current_self_type = previous_value;
2397 fn with_optional_trait_ref<T, F>(&mut self,
2398 opt_trait_ref: Option<&TraitRef>,
2401 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2403 let mut new_val = None;
2404 let mut new_id = None;
2405 if let Some(trait_ref) = opt_trait_ref {
2406 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2407 &trait_ref.path, 0) {
2408 assert!(path_res.depth == 0);
2409 self.record_def(trait_ref.ref_id, path_res);
2410 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2411 new_id = Some(path_res.base_def.def_id());
2413 visit::walk_trait_ref(self, trait_ref);
2415 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2416 let result = f(self, new_id);
2417 self.current_trait_ref = original_trait_ref;
2421 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2422 where F: FnOnce(&mut Resolver)
2424 let mut self_type_rib = Rib::new(NormalRibKind);
2426 // plain insert (no renaming, types are not currently hygienic....)
2427 let name = special_names::type_self;
2428 self_type_rib.bindings.insert(name, DlDef(self_def));
2429 self.type_ribs.push(self_type_rib);
2432 self.type_ribs.pop();
2436 fn resolve_implementation(&mut self,
2437 generics: &Generics,
2438 opt_trait_reference: &Option<TraitRef>,
2441 impl_items: &[P<ImplItem>]) {
2442 // If applicable, create a rib for the type parameters.
2443 self.with_type_parameter_rib(HasTypeParameters(generics,
2447 // Resolve the type parameters.
2448 this.visit_generics(generics);
2450 // Resolve the trait reference, if necessary.
2451 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2452 // Resolve the self type.
2453 this.visit_ty(self_type);
2455 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2456 this.with_current_self_type(self_type, |this| {
2457 for impl_item in impl_items {
2458 match impl_item.node {
2459 ConstImplItem(..) => {
2460 // If this is a trait impl, ensure the const
2462 this.check_trait_item(impl_item.ident.name,
2464 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2465 this.with_constant_rib(|this| {
2466 visit::walk_impl_item(this, impl_item);
2469 MethodImplItem(ref sig, _) => {
2470 // If this is a trait impl, ensure the method
2472 this.check_trait_item(impl_item.ident.name,
2474 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2476 // We also need a new scope for the method-
2477 // specific type parameters.
2478 let type_parameters =
2479 HasTypeParameters(&sig.generics,
2482 this.with_type_parameter_rib(type_parameters, |this| {
2483 visit::walk_impl_item(this, impl_item);
2486 TypeImplItem(ref ty) => {
2487 // If this is a trait impl, ensure the type
2489 this.check_trait_item(impl_item.ident.name,
2491 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2503 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2504 where F: FnOnce(Name, &str) -> ResolutionError {
2505 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2506 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2507 if !self.trait_item_map.contains_key(&(name, did)) {
2508 let path_str = path_names_to_string(&trait_ref.path, 0);
2511 err(name, &*path_str));
2516 fn resolve_local(&mut self, local: &Local) {
2517 // Resolve the type.
2518 visit::walk_ty_opt(self, &local.ty);
2520 // Resolve the initializer.
2521 visit::walk_expr_opt(self, &local.init);
2523 // Resolve the pattern.
2524 self.resolve_pattern(&*local.pat,
2525 LocalIrrefutableMode,
2526 &mut HashMap::new());
2529 // build a map from pattern identifiers to binding-info's.
2530 // this is done hygienically. This could arise for a macro
2531 // that expands into an or-pattern where one 'x' was from the
2532 // user and one 'x' came from the macro.
2533 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2534 let mut result = HashMap::new();
2535 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2536 let name = mtwt::resolve(path1.node);
2537 result.insert(name, BindingInfo {
2539 binding_mode: binding_mode
2545 // check that all of the arms in an or-pattern have exactly the
2546 // same set of bindings, with the same binding modes for each.
2547 fn check_consistent_bindings(&mut self, arm: &Arm) {
2548 if arm.pats.is_empty() {
2551 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2552 for (i, p) in arm.pats.iter().enumerate() {
2553 let map_i = self.binding_mode_map(&**p);
2555 for (&key, &binding_0) in &map_0 {
2556 match map_i.get(&key) {
2560 ResolutionError::VariableNotBoundInPattern(key,
2563 Some(binding_i) => {
2564 if binding_0.binding_mode != binding_i.binding_mode {
2567 ResolutionError::VariableBoundWithDifferentMode(key,
2575 for (&key, &binding) in &map_i {
2576 if !map_0.contains_key(&key) {
2579 ResolutionError::VariableNotBoundInParentPattern(key,
2586 fn resolve_arm(&mut self, arm: &Arm) {
2587 self.value_ribs.push(Rib::new(NormalRibKind));
2589 let mut bindings_list = HashMap::new();
2590 for pattern in &arm.pats {
2591 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2594 // This has to happen *after* we determine which
2595 // pat_idents are variants
2596 self.check_consistent_bindings(arm);
2598 visit::walk_expr_opt(self, &arm.guard);
2599 self.visit_expr(&*arm.body);
2602 self.value_ribs.pop();
2606 fn resolve_block(&mut self, block: &Block) {
2607 debug!("(resolving block) entering block");
2608 self.value_ribs.push(Rib::new(NormalRibKind));
2610 // Move down in the graph, if there's an anonymous module rooted here.
2611 let orig_module = self.current_module.clone();
2612 match orig_module.anonymous_children.borrow().get(&block.id) {
2613 None => { /* Nothing to do. */ }
2614 Some(anonymous_module) => {
2615 debug!("(resolving block) found anonymous module, moving \
2617 self.current_module = anonymous_module.clone();
2621 // Check for imports appearing after non-item statements.
2622 let mut found_non_item = false;
2623 for statement in &block.stmts {
2624 if let hir::StmtDecl(ref declaration, _) = statement.node {
2625 if let hir::DeclItem(ref i) = declaration.node {
2627 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2628 span_err!(self.session, i.span, E0154,
2629 "imports are not allowed after non-item statements");
2634 found_non_item = true
2637 found_non_item = true;
2641 // Descend into the block.
2642 visit::walk_block(self, block);
2646 self.current_module = orig_module;
2647 self.value_ribs.pop();
2649 debug!("(resolving block) leaving block");
2652 fn resolve_type(&mut self, ty: &Ty) {
2654 TyPath(ref maybe_qself, ref path) => {
2656 match self.resolve_possibly_assoc_item(ty.id,
2657 maybe_qself.as_ref(),
2661 // `<T>::a::b::c` is resolved by typeck alone.
2662 TypecheckRequired => {
2663 // Resolve embedded types.
2664 visit::walk_ty(self, ty);
2667 ResolveAttempt(resolution) => resolution,
2670 // This is a path in the type namespace. Walk through scopes
2674 // Write the result into the def map.
2675 debug!("(resolving type) writing resolution for `{}` \
2677 path_names_to_string(path, 0),
2679 self.record_def(ty.id, def);
2682 // Keep reporting some errors even if they're ignored above.
2683 self.resolve_path(ty.id, path, 0, TypeNS, true);
2685 let kind = if maybe_qself.is_some() {
2691 let self_type_name = special_idents::type_self.name;
2692 let is_invalid_self_type_name =
2693 path.segments.len() > 0 &&
2694 maybe_qself.is_none() &&
2695 path.segments[0].identifier.name == self_type_name;
2696 if is_invalid_self_type_name {
2699 ResolutionError::SelfUsedOutsideImplOrTrait);
2703 ResolutionError::UseOfUndeclared(
2705 &*path_names_to_string(path,
2714 // Resolve embedded types.
2715 visit::walk_ty(self, ty);
2718 fn resolve_pattern(&mut self,
2720 mode: PatternBindingMode,
2721 // Maps idents to the node ID for the (outermost)
2722 // pattern that binds them
2723 bindings_list: &mut HashMap<Name, NodeId>) {
2724 let pat_id = pattern.id;
2725 walk_pat(pattern, |pattern| {
2726 match pattern.node {
2727 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2728 // The meaning of PatIdent with no type parameters
2729 // depends on whether an enum variant or unit-like struct
2730 // with that name is in scope. The probing lookup has to
2731 // be careful not to emit spurious errors. Only matching
2732 // patterns (match) can match nullary variants or
2733 // unit-like structs. For binding patterns (let
2734 // and the LHS of @-patterns), matching such a value is
2735 // simply disallowed (since it's rarely what you want).
2736 let const_ok = mode == RefutableMode && at_rhs.is_none();
2738 let ident = path1.node;
2739 let renamed = mtwt::resolve(ident);
2741 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2742 FoundStructOrEnumVariant(def, lp) if const_ok => {
2743 debug!("(resolving pattern) resolving `{}` to \
2744 struct or enum variant",
2747 self.enforce_default_binding_mode(
2751 self.record_def(pattern.id, PathResolution {
2757 FoundStructOrEnumVariant(..) => {
2761 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2765 FoundConst(def, lp) if const_ok => {
2766 debug!("(resolving pattern) resolving `{}` to \
2770 self.enforce_default_binding_mode(
2774 self.record_def(pattern.id, PathResolution {
2784 ResolutionError::OnlyIrrefutablePatternsAllowedHere
2787 BareIdentifierPatternUnresolved => {
2788 debug!("(resolving pattern) binding `{}`",
2791 let def = DefLocal(pattern.id);
2793 // Record the definition so that later passes
2794 // will be able to distinguish variants from
2795 // locals in patterns.
2797 self.record_def(pattern.id, PathResolution {
2799 last_private: LastMod(AllPublic),
2803 // Add the binding to the local ribs, if it
2804 // doesn't already exist in the bindings list. (We
2805 // must not add it if it's in the bindings list
2806 // because that breaks the assumptions later
2807 // passes make about or-patterns.)
2808 if !bindings_list.contains_key(&renamed) {
2809 let this = &mut *self;
2810 let last_rib = this.value_ribs.last_mut().unwrap();
2811 last_rib.bindings.insert(renamed, DlDef(def));
2812 bindings_list.insert(renamed, pat_id);
2813 } else if mode == ArgumentIrrefutableMode &&
2814 bindings_list.contains_key(&renamed) {
2815 // Forbid duplicate bindings in the same
2820 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2821 &ident.name.as_str())
2823 } else if bindings_list.get(&renamed) ==
2825 // Then this is a duplicate variable in the
2826 // same disjunction, which is an error.
2830 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2831 &ident.name.as_str())
2834 // Else, not bound in the same pattern: do
2840 PatEnum(ref path, _) => {
2841 // This must be an enum variant, struct or const.
2843 match self.resolve_possibly_assoc_item(pat_id, None,
2846 // The below shouldn't happen because all
2847 // qualified paths should be in PatQPath.
2848 TypecheckRequired =>
2849 self.session.span_bug(
2851 "resolve_possibly_assoc_item claimed
2852 that a path in PatEnum requires typecheck
2853 to resolve, but qualified paths should be
2855 ResolveAttempt(resolution) => resolution,
2857 if let Some(path_res) = resolution {
2858 match path_res.base_def {
2859 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2860 self.record_def(pattern.id, path_res);
2863 resolve_error(&self,
2865 ResolutionError::StaticVariableReference);
2868 // If anything ends up here entirely resolved,
2869 // it's an error. If anything ends up here
2870 // partially resolved, that's OK, because it may
2871 // be a `T::CONST` that typeck will resolve.
2872 if path_res.depth == 0 {
2876 ResolutionError::NotAnEnumVariantStructOrConst(
2885 let const_name = path.segments.last().unwrap()
2887 let traits = self.get_traits_containing_item(const_name);
2888 self.trait_map.insert(pattern.id, traits);
2889 self.record_def(pattern.id, path_res);
2897 ResolutionError::UnresolvedEnumVariantStructOrConst(
2898 &path.segments.last().unwrap().identifier.name.as_str())
2901 visit::walk_path(self, path);
2904 PatQPath(ref qself, ref path) => {
2905 // Associated constants only.
2907 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2910 TypecheckRequired => {
2911 // All `<T>::CONST` should end up here, and will
2912 // require use of the trait map to resolve
2913 // during typechecking.
2914 let const_name = path.segments.last().unwrap()
2916 let traits = self.get_traits_containing_item(const_name);
2917 self.trait_map.insert(pattern.id, traits);
2918 visit::walk_pat(self, pattern);
2921 ResolveAttempt(resolution) => resolution,
2923 if let Some(path_res) = resolution {
2924 match path_res.base_def {
2925 // All `<T as Trait>::CONST` should end up here, and
2926 // have the trait already selected.
2927 DefAssociatedConst(..) => {
2928 self.record_def(pattern.id, path_res);
2934 ResolutionError::NotAnAssociatedConst(
2935 &path.segments.last().unwrap().identifier.name.as_str()
2944 ResolutionError::UnresolvedAssociatedConst(
2945 &path.segments.last().unwrap().identifier.name.as_str()
2949 visit::walk_pat(self, pattern);
2952 PatStruct(ref path, _, _) => {
2953 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2954 Some(definition) => {
2955 self.record_def(pattern.id, definition);
2958 debug!("(resolving pattern) didn't find struct \
2959 def: {:?}", result);
2963 ResolutionError::DoesNotNameAStruct(
2964 &*path_names_to_string(path, 0))
2968 visit::walk_path(self, path);
2971 PatLit(_) | PatRange(..) => {
2972 visit::walk_pat(self, pattern);
2983 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2984 -> BareIdentifierPatternResolution {
2985 let module = self.current_module.clone();
2986 match self.resolve_item_in_lexical_scope(module,
2989 Success((target, _)) => {
2990 debug!("(resolve bare identifier pattern) succeeded in \
2991 finding {} at {:?}",
2993 target.bindings.value_def.borrow());
2994 match *target.bindings.value_def.borrow() {
2996 panic!("resolved name in the value namespace to a \
2997 set of name bindings with no def?!");
3000 // For the two success cases, this lookup can be
3001 // considered as not having a private component because
3002 // the lookup happened only within the current module.
3004 def @ DefVariant(..) | def @ DefStruct(..) => {
3005 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3007 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
3008 return FoundConst(def, LastMod(AllPublic));
3013 ResolutionError::StaticVariableReference);
3014 return BareIdentifierPatternUnresolved;
3017 return BareIdentifierPatternUnresolved;
3025 panic!("unexpected indeterminate result");
3029 Some((span, msg)) => {
3030 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3035 debug!("(resolve bare identifier pattern) failed to find {}",
3037 return BareIdentifierPatternUnresolved;
3042 /// Handles paths that may refer to associated items
3043 fn resolve_possibly_assoc_item(&mut self,
3045 maybe_qself: Option<&hir::QSelf>,
3047 namespace: Namespace,
3049 -> AssocItemResolveResult
3051 let max_assoc_types;
3055 if qself.position == 0 {
3056 return TypecheckRequired;
3058 max_assoc_types = path.segments.len() - qself.position;
3059 // Make sure the trait is valid.
3060 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
3063 max_assoc_types = path.segments.len();
3067 let mut resolution = self.with_no_errors(|this| {
3068 this.resolve_path(id, path, 0, namespace, check_ribs)
3070 for depth in 1..max_assoc_types {
3071 if resolution.is_some() {
3074 self.with_no_errors(|this| {
3075 resolution = this.resolve_path(id, path, depth,
3079 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
3080 // A module is not a valid type or value.
3083 ResolveAttempt(resolution)
3086 /// If `check_ribs` is true, checks the local definitions first; i.e.
3087 /// doesn't skip straight to the containing module.
3088 /// Skips `path_depth` trailing segments, which is also reflected in the
3089 /// returned value. See `middle::def::PathResolution` for more info.
3090 pub fn resolve_path(&mut self,
3094 namespace: Namespace,
3095 check_ribs: bool) -> Option<PathResolution> {
3096 let span = path.span;
3097 let segments = &path.segments[..path.segments.len()-path_depth];
3099 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
3102 let def = self.resolve_crate_relative_path(span, segments, namespace);
3103 return def.map(mk_res);
3106 // Try to find a path to an item in a module.
3107 let unqualified_def =
3108 self.resolve_identifier(segments.last().unwrap().identifier,
3113 if segments.len() <= 1 {
3114 return unqualified_def.map(mk_res);
3117 let def = self.resolve_module_relative_path(span, segments, namespace);
3118 match (def, unqualified_def) {
3119 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3121 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3123 "unnecessary qualification".to_string());
3131 // Resolve a single identifier.
3132 fn resolve_identifier(&mut self,
3134 namespace: Namespace,
3137 -> Option<(Def, LastPrivate)> {
3138 // First, check to see whether the name is a primitive type.
3139 if namespace == TypeNS {
3140 if let Some(&prim_ty) = self.primitive_type_table
3142 .get(&identifier.name) {
3143 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
3148 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
3151 return Some((def, LastMod(AllPublic)));
3155 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
3158 // FIXME #4952: Merge me with resolve_name_in_module?
3159 fn resolve_definition_of_name_in_module(&mut self,
3160 containing_module: Rc<Module>,
3162 namespace: Namespace)
3164 // First, search children.
3165 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3167 match containing_module.children.borrow().get(&name) {
3168 Some(child_name_bindings) => {
3169 match child_name_bindings.def_for_namespace(namespace) {
3171 // Found it. Stop the search here.
3172 let p = child_name_bindings.defined_in_public_namespace(namespace);
3173 let lp = if p {LastMod(AllPublic)} else {
3174 LastMod(DependsOn(def.def_id()))
3176 return ChildNameDefinition(def, lp);
3184 // Next, search import resolutions.
3185 match containing_module.import_resolutions.borrow().get(&name) {
3186 Some(import_resolution) if import_resolution.is_public => {
3187 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3188 match target.bindings.def_for_namespace(namespace) {
3191 let id = import_resolution.id(namespace);
3192 // track imports and extern crates as well
3193 self.used_imports.insert((id, namespace));
3194 self.record_import_use(id, name);
3195 match target.target_module.def_id.get() {
3196 Some(DefId{krate: kid, ..}) => {
3197 self.used_crates.insert(kid);
3201 return ImportNameDefinition(def, LastMod(AllPublic));
3204 // This can happen with external impls, due to
3205 // the imperfect way we read the metadata.
3210 Some(..) | None => {} // Continue.
3213 // Finally, search through external children.
3214 if namespace == TypeNS {
3215 if let Some(module) = containing_module.external_module_children.borrow()
3216 .get(&name).cloned() {
3217 if let Some(def_id) = module.def_id.get() {
3218 // track used crates
3219 self.used_crates.insert(def_id.krate);
3220 let lp = if module.is_public {LastMod(AllPublic)} else {
3221 LastMod(DependsOn(def_id))
3223 return ChildNameDefinition(DefMod(def_id), lp);
3228 return NoNameDefinition;
3231 // resolve a "module-relative" path, e.g. a::b::c
3232 fn resolve_module_relative_path(&mut self,
3234 segments: &[hir::PathSegment],
3235 namespace: Namespace)
3236 -> Option<(Def, LastPrivate)> {
3237 let module_path = segments.split_last().unwrap().1.iter()
3238 .map(|ps| ps.identifier.name)
3239 .collect::<Vec<_>>();
3241 let containing_module;
3243 let current_module = self.current_module.clone();
3244 match self.resolve_module_path(current_module,
3250 let (span, msg) = match err {
3251 Some((span, msg)) => (span, msg),
3253 let msg = format!("Use of undeclared type or module `{}`",
3254 names_to_string(&module_path));
3259 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3262 Indeterminate => panic!("indeterminate unexpected"),
3263 Success((resulting_module, resulting_last_private)) => {
3264 containing_module = resulting_module;
3265 last_private = resulting_last_private;
3269 let name = segments.last().unwrap().identifier.name;
3270 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
3273 NoNameDefinition => {
3274 // We failed to resolve the name. Report an error.
3277 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3278 (def, last_private.or(lp))
3281 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
3282 self.used_crates.insert(kid);
3287 /// Invariant: This must be called only during main resolution, not during
3288 /// import resolution.
3289 fn resolve_crate_relative_path(&mut self,
3291 segments: &[hir::PathSegment],
3292 namespace: Namespace)
3293 -> Option<(Def, LastPrivate)> {
3294 let module_path = segments.split_last().unwrap().1.iter()
3295 .map(|ps| ps.identifier.name)
3296 .collect::<Vec<_>>();
3298 let root_module = self.graph_root.get_module();
3300 let containing_module;
3302 match self.resolve_module_path_from_root(root_module,
3307 LastMod(AllPublic)) {
3309 let (span, msg) = match err {
3310 Some((span, msg)) => (span, msg),
3312 let msg = format!("Use of undeclared module `::{}`",
3313 names_to_string(&module_path[..]));
3318 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3323 panic!("indeterminate unexpected");
3326 Success((resulting_module, resulting_last_private)) => {
3327 containing_module = resulting_module;
3328 last_private = resulting_last_private;
3332 let name = segments.last().unwrap().identifier.name;
3333 match self.resolve_definition_of_name_in_module(containing_module,
3336 NoNameDefinition => {
3337 // We failed to resolve the name. Report an error.
3340 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3341 return Some((def, last_private.or(lp)));
3346 fn resolve_identifier_in_local_ribs(&mut self,
3348 namespace: Namespace,
3351 // Check the local set of ribs.
3352 let search_result = match namespace {
3354 let renamed = mtwt::resolve(ident);
3355 self.search_ribs(&self.value_ribs, renamed, span)
3358 let name = ident.name;
3359 self.search_ribs(&self.type_ribs, name, span)
3363 match search_result {
3364 Some(DlDef(def)) => {
3365 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3370 Some(DlField) | Some(DlImpl(_)) | None => {
3376 fn resolve_item_by_name_in_lexical_scope(&mut self,
3378 namespace: Namespace)
3379 -> Option<(Def, LastPrivate)> {
3381 let module = self.current_module.clone();
3382 match self.resolve_item_in_lexical_scope(module,
3385 Success((target, _)) => {
3386 match (*target.bindings).def_for_namespace(namespace) {
3388 // This can happen if we were looking for a type and
3389 // found a module instead. Modules don't have defs.
3390 debug!("(resolving item path by identifier in lexical \
3391 scope) failed to resolve {} after success...",
3396 debug!("(resolving item path in lexical scope) \
3397 resolved `{}` to item",
3399 // This lookup is "all public" because it only searched
3400 // for one identifier in the current module (couldn't
3401 // have passed through reexports or anything like that.
3402 return Some((def, LastMod(AllPublic)));
3407 panic!("unexpected indeterminate result");
3410 debug!("(resolving item path by identifier in lexical scope) \
3411 failed to resolve {}", name);
3413 if let Some((span, msg)) = err {
3414 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3422 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3423 F: FnOnce(&mut Resolver) -> T,
3425 self.emit_errors = false;
3427 self.emit_errors = true;
3431 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3432 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3433 -> Option<(Path, NodeId, FallbackChecks)> {
3435 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3436 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3437 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3438 // This doesn't handle the remaining `Ty` variants as they are not
3439 // that commonly the self_type, it might be interesting to provide
3440 // support for those in future.
3445 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3446 -> Option<Rc<Module>> {
3447 let root = this.current_module.clone();
3448 let last_name = name_path.last().unwrap();
3450 if name_path.len() == 1 {
3451 match this.primitive_type_table.primitive_types.get(last_name) {
3454 match this.current_module.children.borrow().get(last_name) {
3455 Some(child) => child.get_module_if_available(),
3461 match this.resolve_module_path(root,
3466 Success((module, _)) => Some(module),
3472 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3474 let sig = match this.ast_map.get(did.node) {
3475 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3476 hir::MethodTraitItem(ref sig, _) => sig,
3479 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3480 hir::MethodImplItem(ref sig, _) => sig,
3485 sig.explicit_self.node == hir::SelfStatic
3487 csearch::is_static_method(&this.session.cstore, did)
3491 let (path, node_id, allowed) = match self.current_self_type {
3492 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3494 None => return NoSuggestion,
3496 None => return NoSuggestion,
3499 if allowed == Everything {
3500 // Look for a field with the same name in the current self_type.
3501 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3502 Some(DefTy(did, _)) |
3503 Some(DefStruct(did)) |
3504 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3507 if fields.iter().any(|&field_name| name == field_name) {
3512 _ => {} // Self type didn't resolve properly
3516 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3518 // Look for a method in the current self type's impl module.
3519 if let Some(module) = get_module(self, path.span, &name_path) {
3520 if let Some(binding) = module.children.borrow().get(&name) {
3521 if let Some(DefMethod(did)) = binding.def_for_namespace(ValueNS) {
3522 if is_static_method(self, did) {
3523 return StaticMethod(path_names_to_string(&path, 0))
3525 if self.current_trait_ref.is_some() {
3527 } else if allowed == Everything {
3534 // Look for a method in the current trait.
3535 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3536 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3537 if is_static_method(self, did) {
3538 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3548 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3549 let mut maybes: Vec<token::InternedString> = Vec::new();
3550 let mut values: Vec<usize> = Vec::new();
3552 for rib in self.value_ribs.iter().rev() {
3553 for (&k, _) in &rib.bindings {
3554 maybes.push(k.as_str());
3555 values.push(usize::MAX);
3559 let mut smallest = 0;
3560 for (i, other) in maybes.iter().enumerate() {
3561 values[i] = lev_distance(name, &other);
3563 if values[i] <= values[smallest] {
3568 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3569 // maximum edit distance we will accept for a suggestion to one third of
3570 // the typo'd name's length.
3571 let max_distance = std::cmp::max(name.len(), 3) / 3;
3573 if !values.is_empty() &&
3574 values[smallest] <= max_distance &&
3575 name != &maybes[smallest][..] {
3577 Some(maybes[smallest].to_string())
3584 fn resolve_expr(&mut self, expr: &Expr) {
3585 // First, record candidate traits for this expression if it could
3586 // result in the invocation of a method call.
3588 self.record_candidate_traits_for_expr_if_necessary(expr);
3590 // Next, resolve the node.
3592 ExprPath(ref maybe_qself, ref path) => {
3594 match self.resolve_possibly_assoc_item(expr.id,
3595 maybe_qself.as_ref(),
3599 // `<T>::a::b::c` is resolved by typeck alone.
3600 TypecheckRequired => {
3601 let method_name = path.segments.last().unwrap().identifier.name;
3602 let traits = self.get_traits_containing_item(method_name);
3603 self.trait_map.insert(expr.id, traits);
3604 visit::walk_expr(self, expr);
3607 ResolveAttempt(resolution) => resolution,
3610 // This is a local path in the value namespace. Walk through
3611 // scopes looking for it.
3612 if let Some(path_res) = resolution {
3613 // Check if struct variant
3614 if let DefVariant(_, _, true) = path_res.base_def {
3615 let path_name = path_names_to_string(path, 0);
3619 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3621 let msg = format!("did you mean to write: \
3622 `{} {{ /* fields */ }}`?",
3624 if self.emit_errors {
3625 self.session.fileline_help(expr.span, &msg);
3627 self.session.span_help(expr.span, &msg);
3630 // Write the result into the def map.
3631 debug!("(resolving expr) resolved `{}`",
3632 path_names_to_string(path, 0));
3634 // Partial resolutions will need the set of traits in scope,
3635 // so they can be completed during typeck.
3636 if path_res.depth != 0 {
3637 let method_name = path.segments.last().unwrap().identifier.name;
3638 let traits = self.get_traits_containing_item(method_name);
3639 self.trait_map.insert(expr.id, traits);
3642 self.record_def(expr.id, path_res);
3645 // Be helpful if the name refers to a struct
3646 // (The pattern matching def_tys where the id is in self.structs
3647 // matches on regular structs while excluding tuple- and enum-like
3648 // structs, which wouldn't result in this error.)
3649 let path_name = path_names_to_string(path, 0);
3650 let type_res = self.with_no_errors(|this| {
3651 this.resolve_path(expr.id, path, 0, TypeNS, false)
3653 match type_res.map(|r| r.base_def) {
3654 Some(DefTy(struct_id, _))
3655 if self.structs.contains_key(&struct_id) => {
3659 ResolutionError::StructVariantUsedAsFunction(
3663 let msg = format!("did you mean to write: \
3664 `{} {{ /* fields */ }}`?",
3666 if self.emit_errors {
3667 self.session.fileline_help(expr.span, &msg);
3669 self.session.span_help(expr.span, &msg);
3673 // Keep reporting some errors even if they're ignored above.
3674 self.resolve_path(expr.id, path, 0, ValueNS, true);
3676 let mut method_scope = false;
3677 self.value_ribs.iter().rev().all(|rib| {
3678 method_scope = match rib.kind {
3679 MethodRibKind => true,
3680 ItemRibKind | ConstantItemRibKind => false,
3681 _ => return true, // Keep advancing
3683 false // Stop advancing
3686 if method_scope && special_names::self_ == path_name {
3690 ResolutionError::SelfNotAvailableInStaticMethod
3693 let last_name = path.segments.last().unwrap().identifier.name;
3694 let mut msg = match self.find_fallback_in_self_type(last_name) {
3696 // limit search to 5 to reduce the number
3697 // of stupid suggestions
3698 self.find_best_match_for_name(&path_name)
3699 .map_or("".to_string(),
3700 |x| format!("`{}`", x))
3702 Field => format!("`self.{}`", path_name),
3705 format!("to call `self.{}`", path_name),
3706 TraitMethod(path_str) |
3707 StaticMethod(path_str) =>
3708 format!("to call `{}::{}`", path_str, path_name)
3711 if !msg.is_empty() {
3712 msg = format!(". Did you mean {}?", msg)
3717 ResolutionError::UnresolvedName(&*path_name,
3724 visit::walk_expr(self, expr);
3727 ExprStruct(ref path, _, _) => {
3728 // Resolve the path to the structure it goes to. We don't
3729 // check to ensure that the path is actually a structure; that
3730 // is checked later during typeck.
3731 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3732 Some(definition) => self.record_def(expr.id, definition),
3734 debug!("(resolving expression) didn't find struct def",);
3738 ResolutionError::DoesNotNameAStruct(
3739 &*path_names_to_string(path, 0))
3744 visit::walk_expr(self, expr);
3747 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3748 self.with_label_rib(|this| {
3749 let def_like = DlDef(DefLabel(expr.id));
3752 let rib = this.label_ribs.last_mut().unwrap();
3753 let renamed = mtwt::resolve(label);
3754 rib.bindings.insert(renamed, def_like);
3757 visit::walk_expr(this, expr);
3761 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3762 let renamed = mtwt::resolve(label.node);
3763 match self.search_label(renamed) {
3767 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3769 Some(DlDef(def @ DefLabel(_))) => {
3770 // Since this def is a label, it is never read.
3771 self.record_def(expr.id, PathResolution {
3773 last_private: LastMod(AllPublic),
3778 self.session.span_bug(expr.span,
3779 "label wasn't mapped to a \
3786 visit::walk_expr(self, expr);
3791 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3793 ExprField(_, ident) => {
3794 // FIXME(#6890): Even though you can't treat a method like a
3795 // field, we need to add any trait methods we find that match
3796 // the field name so that we can do some nice error reporting
3797 // later on in typeck.
3798 let traits = self.get_traits_containing_item(ident.node.name);
3799 self.trait_map.insert(expr.id, traits);
3801 ExprMethodCall(ident, _, _) => {
3802 debug!("(recording candidate traits for expr) recording \
3805 let traits = self.get_traits_containing_item(ident.node.name);
3806 self.trait_map.insert(expr.id, traits);
3814 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3815 debug!("(getting traits containing item) looking for '{}'",
3818 fn add_trait_info(found_traits: &mut Vec<DefId>,
3819 trait_def_id: DefId,
3821 debug!("(adding trait info) found trait {}:{} for method '{}'",
3825 found_traits.push(trait_def_id);
3828 let mut found_traits = Vec::new();
3829 let mut search_module = self.current_module.clone();
3831 // Look for the current trait.
3832 match self.current_trait_ref {
3833 Some((trait_def_id, _)) => {
3834 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3835 add_trait_info(&mut found_traits, trait_def_id, name);
3838 None => {} // Nothing to do.
3841 // Look for trait children.
3842 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3845 for (_, child_names) in search_module.children.borrow().iter() {
3846 let def = match child_names.def_for_namespace(TypeNS) {
3850 let trait_def_id = match def {
3851 DefTrait(trait_def_id) => trait_def_id,
3854 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3855 add_trait_info(&mut found_traits, trait_def_id, name);
3860 // Look for imports.
3861 for (_, import) in search_module.import_resolutions.borrow().iter() {
3862 let target = match import.target_for_namespace(TypeNS) {
3864 Some(target) => target,
3866 let did = match target.bindings.def_for_namespace(TypeNS) {
3867 Some(DefTrait(trait_def_id)) => trait_def_id,
3868 Some(..) | None => continue,
3870 if self.trait_item_map.contains_key(&(name, did)) {
3871 add_trait_info(&mut found_traits, did, name);
3872 let id = import.type_id;
3873 self.used_imports.insert((id, TypeNS));
3874 let trait_name = self.get_trait_name(did);
3875 self.record_import_use(id, trait_name);
3876 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3877 self.used_crates.insert(kid);
3882 match search_module.parent_link.clone() {
3883 NoParentLink | ModuleParentLink(..) => break,
3884 BlockParentLink(parent_module, _) => {
3885 search_module = parent_module.upgrade().unwrap();
3893 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3894 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3895 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3896 "Import should only be used for `use` directives");
3898 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3899 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3900 self.session.span_bug(span, &format!("path resolved multiple times \
3901 ({:?} before, {:?} now)",
3902 prev_res, resolution));
3906 fn enforce_default_binding_mode(&mut self,
3908 pat_binding_mode: BindingMode,
3910 match pat_binding_mode {
3911 BindByValue(_) => {}
3915 ResolutionError::CannotUseRefBindingModeWith(descr));
3923 // Diagnostics are not particularly efficient, because they're rarely
3927 #[allow(dead_code)] // useful for debugging
3928 fn dump_module(&mut self, module_: Rc<Module>) {
3929 debug!("Dump of module `{}`:", module_to_string(&*module_));
3931 debug!("Children:");
3932 build_reduced_graph::populate_module_if_necessary(self, &module_);
3933 for (&name, _) in module_.children.borrow().iter() {
3934 debug!("* {}", name);
3937 debug!("Import resolutions:");
3938 let import_resolutions = module_.import_resolutions.borrow();
3939 for (&name, import_resolution) in import_resolutions.iter() {
3941 match import_resolution.target_for_namespace(ValueNS) {
3942 None => { value_repr = "".to_string(); }
3944 value_repr = " value:?".to_string();
3950 match import_resolution.target_for_namespace(TypeNS) {
3951 None => { type_repr = "".to_string(); }
3953 type_repr = " type:?".to_string();
3958 debug!("* {}:{}{}", name, value_repr, type_repr);
3964 fn names_to_string(names: &[Name]) -> String {
3965 let mut first = true;
3966 let mut result = String::new();
3971 result.push_str("::")
3973 result.push_str(&name.as_str());
3978 fn path_names_to_string(path: &Path, depth: usize) -> String {
3979 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3981 .map(|seg| seg.identifier.name)
3983 names_to_string(&names[..])
3986 /// A somewhat inefficient routine to obtain the name of a module.
3987 fn module_to_string(module: &Module) -> String {
3988 let mut names = Vec::new();
3990 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3991 match module.parent_link {
3993 ModuleParentLink(ref module, name) => {
3995 collect_mod(names, &*module.upgrade().unwrap());
3997 BlockParentLink(ref module, _) => {
3998 // danger, shouldn't be ident?
3999 names.push(special_idents::opaque.name);
4000 collect_mod(names, &*module.upgrade().unwrap());
4004 collect_mod(&mut names, module);
4006 if names.is_empty() {
4007 return "???".to_string();
4009 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
4013 pub struct CrateMap {
4014 pub def_map: DefMap,
4015 pub freevars: RefCell<FreevarMap>,
4016 pub export_map: ExportMap,
4017 pub trait_map: TraitMap,
4018 pub external_exports: ExternalExports,
4019 pub glob_map: Option<GlobMap>
4022 #[derive(PartialEq,Copy, Clone)]
4023 pub enum MakeGlobMap {
4028 /// Entry point to crate resolution.
4029 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4030 ast_map: &'a hir_map::Map<'tcx>,
4031 make_glob_map: MakeGlobMap)
4033 let krate = ast_map.krate();
4034 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
4036 resolver.resolve_crate(krate);
4037 session.abort_if_errors();
4039 check_unused::check_crate(&mut resolver, krate);
4042 def_map: resolver.def_map,
4043 freevars: resolver.freevars,
4044 export_map: resolver.export_map,
4045 trait_map: resolver.trait_map,
4046 external_exports: resolver.external_exports,
4047 glob_map: if resolver.make_glob_map {
4048 Some(resolver.glob_map)
4055 /// Builds a name resolution walker to be used within this module,
4056 /// or used externally, with an optional callback function.
4058 /// The callback takes a &mut bool which allows callbacks to end a
4059 /// walk when set to true, passing through the rest of the walk, while
4060 /// preserving the ribs + current module. This allows resolve_path
4061 /// calls to be made with the correct scope info. The node in the
4062 /// callback corresponds to the current node in the walk.
4063 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
4064 ast_map: &'a hir_map::Map<'tcx>,
4066 make_glob_map: MakeGlobMap,
4067 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
4068 -> Resolver<'a, 'tcx> {
4069 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4071 resolver.callback = callback;
4073 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4074 session.abort_if_errors();
4076 resolve_imports::resolve_imports(&mut resolver);
4077 session.abort_if_errors();
4079 record_exports::record(&mut resolver);
4080 session.abort_if_errors();
4085 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }