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 #![crate_name = "rustc_resolve"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
19 #![feature(associated_consts)]
20 #![feature(borrow_state)]
21 #![feature(rustc_diagnostic_macros)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
31 extern crate rustc_bitflags;
32 extern crate rustc_front;
35 use self::PatternBindingMode::*;
36 use self::Namespace::*;
37 use self::NamespaceResult::*;
38 use self::ResolveResult::*;
39 use self::FallbackSuggestion::*;
40 use self::TypeParameters::*;
42 use self::UseLexicalScopeFlag::*;
43 use self::ModulePrefixResult::*;
44 use self::AssocItemResolveResult::*;
45 use self::NameSearchType::*;
46 use self::BareIdentifierPatternResolution::*;
47 use self::ParentLink::*;
48 use self::FallbackChecks::*;
50 use rustc::front::map as hir_map;
51 use rustc::session::Session;
53 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
54 use rustc::middle::def::*;
55 use rustc::middle::def_id::DefId;
56 use rustc::middle::pat_util::pat_bindings;
57 use rustc::middle::privacy::*;
58 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
60 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
63 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
64 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
65 use syntax::attr::AttrMetaMethods;
66 use syntax::codemap::{self, Span, Pos};
67 use syntax::errors::DiagnosticBuilder;
68 use syntax::parse::token::{self, special_names, special_idents};
69 use syntax::util::lev_distance::find_best_match_for_name;
71 use rustc_front::intravisit::{self, FnKind, Visitor};
73 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
74 use rustc_front::hir::Crate;
75 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprField};
76 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
77 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
78 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
79 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
80 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
81 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
82 use rustc_front::hir::Local;
83 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
84 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
85 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
86 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
87 use rustc_front::util::walk_pat;
89 use std::collections::{HashMap, HashSet};
90 use std::cell::{Cell, RefCell};
92 use std::mem::replace;
93 use std::rc::{Rc, Weak};
95 use resolve_imports::{Target, ImportDirective, ImportResolutionPerNamespace};
96 use resolve_imports::Shadowable;
98 // NB: This module needs to be declared first so diagnostics are
99 // registered before they are used.
104 mod build_reduced_graph;
107 // Perform the callback, not walking deeper if the return is true
108 macro_rules! execute_callback {
109 ($node: expr, $walker: expr) => (
110 if let Some(ref callback) = $walker.callback {
111 if callback($node, &mut $walker.resolved) {
118 enum SuggestionType {
120 Function(token::InternedString),
124 pub enum ResolutionError<'a> {
125 /// error E0260: name conflicts with an extern crate
126 NameConflictsWithExternCrate(Name),
127 /// error E0401: can't use type parameters from outer function
128 TypeParametersFromOuterFunction,
129 /// error E0402: cannot use an outer type parameter in this context
130 OuterTypeParameterContext,
131 /// error E0403: the name is already used for a type parameter in this type parameter list
132 NameAlreadyUsedInTypeParameterList(Name),
133 /// error E0404: is not a trait
134 IsNotATrait(&'a str),
135 /// error E0405: use of undeclared trait name
136 UndeclaredTraitName(&'a str),
137 /// error E0406: undeclared associated type
138 UndeclaredAssociatedType,
139 /// error E0407: method is not a member of trait
140 MethodNotMemberOfTrait(Name, &'a str),
141 /// error E0437: type is not a member of trait
142 TypeNotMemberOfTrait(Name, &'a str),
143 /// error E0438: const is not a member of trait
144 ConstNotMemberOfTrait(Name, &'a str),
145 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
146 VariableNotBoundInPattern(Name, usize),
147 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
148 VariableBoundWithDifferentMode(Name, usize),
149 /// error E0410: variable from pattern is not bound in pattern #1
150 VariableNotBoundInParentPattern(Name, usize),
151 /// error E0411: use of `Self` outside of an impl or trait
152 SelfUsedOutsideImplOrTrait,
153 /// error E0412: use of undeclared
154 UseOfUndeclared(&'a str, &'a str),
155 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
156 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
157 /// error E0414: only irrefutable patterns allowed here
158 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
159 /// error E0415: identifier is bound more than once in this parameter list
160 IdentifierBoundMoreThanOnceInParameterList(&'a str),
161 /// error E0416: identifier is bound more than once in the same pattern
162 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
163 /// error E0417: static variables cannot be referenced in a pattern
164 StaticVariableReference,
165 /// error E0418: is not an enum variant, struct or const
166 NotAnEnumVariantStructOrConst(&'a str),
167 /// error E0419: unresolved enum variant, struct or const
168 UnresolvedEnumVariantStructOrConst(&'a str),
169 /// error E0420: is not an associated const
170 NotAnAssociatedConst(&'a str),
171 /// error E0421: unresolved associated const
172 UnresolvedAssociatedConst(&'a str),
173 /// error E0422: does not name a struct
174 DoesNotNameAStruct(&'a str),
175 /// error E0423: is a struct variant name, but this expression uses it like a function name
176 StructVariantUsedAsFunction(&'a str),
177 /// error E0424: `self` is not available in a static method
178 SelfNotAvailableInStaticMethod,
179 /// error E0425: unresolved name
180 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
181 /// error E0426: use of undeclared label
182 UndeclaredLabel(&'a str),
183 /// error E0427: cannot use `ref` binding mode with ...
184 CannotUseRefBindingModeWith(&'a str),
185 /// error E0428: duplicate definition
186 DuplicateDefinition(&'a str, Name),
187 /// error E0429: `self` imports are only allowed within a { } list
188 SelfImportsOnlyAllowedWithin,
189 /// error E0430: `self` import can only appear once in the list
190 SelfImportCanOnlyAppearOnceInTheList,
191 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
192 SelfImportOnlyInImportListWithNonEmptyPrefix,
193 /// error E0432: unresolved import
194 UnresolvedImport(Option<(&'a str, &'a str)>),
195 /// error E0433: failed to resolve
196 FailedToResolve(&'a str),
197 /// error E0434: can't capture dynamic environment in a fn item
198 CannotCaptureDynamicEnvironmentInFnItem,
199 /// error E0435: attempt to use a non-constant value in a constant
200 AttemptToUseNonConstantValueInConstant,
203 /// Context of where `ResolutionError::UnresolvedName` arose.
204 #[derive(Clone, PartialEq, Eq, Debug)]
205 pub enum UnresolvedNameContext {
206 /// `PathIsMod(id)` indicates that a given path, used in
207 /// expression context, actually resolved to a module rather than
208 /// a value. The `id` attached to the variant is the node id of
209 /// the erroneous path expression.
210 PathIsMod(ast::NodeId),
212 /// `Other` means we have no extra information about the context
213 /// of the unresolved name error. (Maybe we could eliminate all
214 /// such cases; but for now, this is an information-free default.)
218 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
219 span: syntax::codemap::Span,
220 resolution_error: ResolutionError<'b>) {
221 resolve_struct_error(resolver, span, resolution_error).emit();
224 fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
225 span: syntax::codemap::Span,
226 resolution_error: ResolutionError<'b>)
227 -> DiagnosticBuilder<'a> {
228 if !resolver.emit_errors {
229 return resolver.session.diagnostic().struct_dummy();
232 match resolution_error {
233 ResolutionError::NameConflictsWithExternCrate(name) => {
234 struct_span_err!(resolver.session,
237 "the name `{}` conflicts with an external crate \
238 that has been imported into this module",
241 ResolutionError::TypeParametersFromOuterFunction => {
242 struct_span_err!(resolver.session,
245 "can't use type parameters from outer function; try using a local \
246 type parameter instead")
248 ResolutionError::OuterTypeParameterContext => {
249 struct_span_err!(resolver.session,
252 "cannot use an outer type parameter in this context")
254 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
255 struct_span_err!(resolver.session,
258 "the name `{}` is already used for a type parameter in this type \
262 ResolutionError::IsNotATrait(name) => {
263 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
265 ResolutionError::UndeclaredTraitName(name) => {
266 struct_span_err!(resolver.session,
269 "use of undeclared trait name `{}`",
272 ResolutionError::UndeclaredAssociatedType => {
273 struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
275 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
276 struct_span_err!(resolver.session,
279 "method `{}` is not a member of trait `{}`",
283 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
284 struct_span_err!(resolver.session,
287 "type `{}` is not a member of trait `{}`",
291 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
292 struct_span_err!(resolver.session,
295 "const `{}` is not a member of trait `{}`",
299 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
300 struct_span_err!(resolver.session,
303 "variable `{}` from pattern #1 is not bound in pattern #{}",
307 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
308 struct_span_err!(resolver.session,
311 "variable `{}` is bound with different mode in pattern #{} than in \
316 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
317 struct_span_err!(resolver.session,
320 "variable `{}` from pattern #{} is not bound in pattern #1",
324 ResolutionError::SelfUsedOutsideImplOrTrait => {
325 struct_span_err!(resolver.session,
328 "use of `Self` outside of an impl or trait")
330 ResolutionError::UseOfUndeclared(kind, name) => {
331 struct_span_err!(resolver.session,
334 "use of undeclared {} `{}`",
338 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
339 struct_span_err!(resolver.session,
342 "declaration of `{}` shadows an enum variant \
343 or unit-like struct in scope",
346 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
347 let mut err = struct_span_err!(resolver.session,
350 "only irrefutable patterns allowed here");
352 "there already is a constant in scope sharing the same \
353 name as this pattern");
354 if let Some(sp) = resolver.ast_map.span_if_local(did) {
355 err.span_note(sp, "constant defined here");
357 if let Some(directive) = resolver.current_module
361 let item = resolver.ast_map.expect_item(directive.value_ns.id);
362 err.span_note(item.span, "constant imported here");
366 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
367 struct_span_err!(resolver.session,
370 "identifier `{}` is bound more than once in this parameter list",
373 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
374 struct_span_err!(resolver.session,
377 "identifier `{}` is bound more than once in the same pattern",
380 ResolutionError::StaticVariableReference => {
381 struct_span_err!(resolver.session,
384 "static variables cannot be referenced in a pattern, use a \
387 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
388 struct_span_err!(resolver.session,
391 "`{}` is not an enum variant, struct or const",
394 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
395 struct_span_err!(resolver.session,
398 "unresolved enum variant, struct or const `{}`",
401 ResolutionError::NotAnAssociatedConst(name) => {
402 struct_span_err!(resolver.session,
405 "`{}` is not an associated const",
408 ResolutionError::UnresolvedAssociatedConst(name) => {
409 struct_span_err!(resolver.session,
412 "unresolved associated const `{}`",
415 ResolutionError::DoesNotNameAStruct(name) => {
416 struct_span_err!(resolver.session,
419 "`{}` does not name a structure",
422 ResolutionError::StructVariantUsedAsFunction(path_name) => {
423 struct_span_err!(resolver.session,
426 "`{}` is the name of a struct or struct variant, but this expression \
427 uses it like a function name",
430 ResolutionError::SelfNotAvailableInStaticMethod => {
431 struct_span_err!(resolver.session,
434 "`self` is not available in a static method. Maybe a `self` \
435 argument is missing?")
437 ResolutionError::UnresolvedName(path, msg, context) => {
438 let mut err = struct_span_err!(resolver.session,
441 "unresolved name `{}`{}",
446 UnresolvedNameContext::Other => {} // no help available
447 UnresolvedNameContext::PathIsMod(id) => {
448 let mut help_msg = String::new();
449 let parent_id = resolver.ast_map.get_parent_node(id);
450 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
452 ExprField(_, ident) => {
453 help_msg = format!("To reference an item from the \
454 `{module}` module, use \
455 `{module}::{ident}`",
460 ExprMethodCall(ident, _, _) => {
461 help_msg = format!("To call a function from the \
462 `{module}` module, use \
463 `{module}::{ident}(..)`",
468 _ => {} // no help available
472 if !help_msg.is_empty() {
473 err.fileline_help(span, &help_msg);
479 ResolutionError::UndeclaredLabel(name) => {
480 struct_span_err!(resolver.session,
483 "use of undeclared label `{}`",
486 ResolutionError::CannotUseRefBindingModeWith(descr) => {
487 struct_span_err!(resolver.session,
490 "cannot use `ref` binding mode with {}",
493 ResolutionError::DuplicateDefinition(namespace, name) => {
494 struct_span_err!(resolver.session,
497 "duplicate definition of {} `{}`",
501 ResolutionError::SelfImportsOnlyAllowedWithin => {
502 struct_span_err!(resolver.session,
506 "`self` imports are only allowed within a { } list")
508 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
509 struct_span_err!(resolver.session,
512 "`self` import can only appear once in the list")
514 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
515 struct_span_err!(resolver.session,
518 "`self` import can only appear in an import list with a \
521 ResolutionError::UnresolvedImport(name) => {
522 let msg = match name {
523 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
524 None => "unresolved import".to_owned(),
526 struct_span_err!(resolver.session, span, E0432, "{}", msg)
528 ResolutionError::FailedToResolve(msg) => {
529 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
531 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
532 struct_span_err!(resolver.session,
536 "can't capture dynamic environment in a fn item; use the || { ... } \
537 closure form instead")
539 ResolutionError::AttemptToUseNonConstantValueInConstant => {
540 struct_span_err!(resolver.session,
543 "attempt to use a non-constant value in a constant")
548 #[derive(Copy, Clone)]
551 binding_mode: BindingMode,
554 // Map from the name in a pattern to its binding mode.
555 type BindingMap = HashMap<Name, BindingInfo>;
557 #[derive(Copy, Clone, PartialEq)]
558 enum PatternBindingMode {
560 LocalIrrefutableMode,
561 ArgumentIrrefutableMode,
564 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
570 /// A NamespaceResult represents the result of resolving an import in
571 /// a particular namespace. The result is either definitely-resolved,
572 /// definitely- unresolved, or unknown.
574 enum NamespaceResult {
575 /// Means that resolve hasn't gathered enough information yet to determine
576 /// whether the name is bound in this namespace. (That is, it hasn't
577 /// resolved all `use` directives yet.)
579 /// Means that resolve has determined that the name is definitely
580 /// not bound in the namespace.
582 /// Means that resolve has determined that the name is bound in the Module
583 /// argument, and specified by the NameBinding argument.
584 BoundResult(Rc<Module>, NameBinding),
587 impl NamespaceResult {
588 fn is_unknown(&self) -> bool {
590 UnknownResult => true,
594 fn is_unbound(&self) -> bool {
596 UnboundResult => true,
602 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
603 fn visit_nested_item(&mut self, item: hir::ItemId) {
604 self.visit_item(self.ast_map.expect_item(item.id))
606 fn visit_item(&mut self, item: &Item) {
607 execute_callback!(hir_map::Node::NodeItem(item), self);
608 self.resolve_item(item);
610 fn visit_arm(&mut self, arm: &Arm) {
611 self.resolve_arm(arm);
613 fn visit_block(&mut self, block: &Block) {
614 execute_callback!(hir_map::Node::NodeBlock(block), self);
615 self.resolve_block(block);
617 fn visit_expr(&mut self, expr: &Expr) {
618 execute_callback!(hir_map::Node::NodeExpr(expr), self);
619 self.resolve_expr(expr);
621 fn visit_local(&mut self, local: &Local) {
622 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
623 self.resolve_local(local);
625 fn visit_ty(&mut self, ty: &Ty) {
626 self.resolve_type(ty);
628 fn visit_generics(&mut self, generics: &Generics) {
629 self.resolve_generics(generics);
631 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
632 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
633 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
635 // error already reported
636 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
639 intravisit::walk_poly_trait_ref(self, tref, m);
641 fn visit_variant(&mut self,
642 variant: &hir::Variant,
644 item_id: ast::NodeId) {
645 execute_callback!(hir_map::Node::NodeVariant(variant), self);
646 if let Some(ref dis_expr) = variant.node.disr_expr {
647 // resolve the discriminator expr as a constant
648 self.with_constant_rib(|this| {
649 this.visit_expr(dis_expr);
653 // `intravisit::walk_variant` without the discriminant expression.
654 self.visit_variant_data(&variant.node.data,
660 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
661 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
662 let type_parameters = match foreign_item.node {
663 ForeignItemFn(_, ref generics) => {
664 HasTypeParameters(generics, FnSpace, ItemRibKind)
666 ForeignItemStatic(..) => NoTypeParameters,
668 self.with_type_parameter_rib(type_parameters, |this| {
669 intravisit::walk_foreign_item(this, foreign_item);
672 fn visit_fn(&mut self,
673 function_kind: FnKind<'v>,
674 declaration: &'v FnDecl,
678 let rib_kind = match function_kind {
679 FnKind::ItemFn(_, generics, _, _, _, _) => {
680 self.visit_generics(generics);
683 FnKind::Method(_, sig, _) => {
684 self.visit_generics(&sig.generics);
685 self.visit_explicit_self(&sig.explicit_self);
688 FnKind::Closure => ClosureRibKind(node_id),
690 self.resolve_function(rib_kind, declaration, block);
694 type ErrorMessage = Option<(Span, String)>;
696 enum ResolveResult<T> {
697 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
698 Indeterminate, // Couldn't determine due to unresolved globs.
699 Success(T), // Successfully resolved the import.
702 impl<T> ResolveResult<T> {
703 fn success(&self) -> bool {
711 enum FallbackSuggestion {
716 StaticMethod(String),
720 #[derive(Copy, Clone)]
721 enum TypeParameters<'a> {
723 HasTypeParameters(// Type parameters.
726 // Identifies the things that these parameters
727 // were declared on (type, fn, etc)
730 // The kind of the rib used for type parameters.
734 // The rib kind controls the translation of local
735 // definitions (`DefLocal`) to upvars (`DefUpvar`).
736 #[derive(Copy, Clone, Debug)]
738 // No translation needs to be applied.
741 // We passed through a closure scope at the given node ID.
742 // Translate upvars as appropriate.
743 ClosureRibKind(NodeId /* func id */),
745 // We passed through an impl or trait and are now in one of its
746 // methods. Allow references to ty params that impl or trait
747 // binds. Disallow any other upvars (including other ty params that are
751 // We passed through an item scope. Disallow upvars.
754 // We're in a constant item. Can't refer to dynamic stuff.
758 #[derive(Copy, Clone)]
759 enum UseLexicalScopeFlag {
764 enum ModulePrefixResult {
766 PrefixFound(Rc<Module>, usize),
769 #[derive(Copy, Clone)]
770 enum AssocItemResolveResult {
771 /// Syntax such as `<T>::item`, which can't be resolved until type
774 /// We should have been able to resolve the associated item.
775 ResolveAttempt(Option<PathResolution>),
778 #[derive(Copy, Clone, PartialEq)]
779 enum NameSearchType {
780 /// We're doing a name search in order to resolve a `use` directive.
783 /// We're doing a name search in order to resolve a path type, a path
784 /// expression, or a path pattern.
788 #[derive(Copy, Clone)]
789 enum BareIdentifierPatternResolution {
790 FoundStructOrEnumVariant(Def, LastPrivate),
791 FoundConst(Def, LastPrivate, Name),
792 BareIdentifierPatternUnresolved,
798 bindings: HashMap<Name, DefLike>,
803 fn new(kind: RibKind) -> Rib {
805 bindings: HashMap::new(),
811 /// A definition along with the index of the rib it was found on
813 ribs: Option<(Namespace, usize)>,
818 fn from_def(def: Def) -> Self {
826 /// The link from a module up to its nearest parent node.
827 #[derive(Clone,Debug)]
830 ModuleParentLink(Weak<Module>, Name),
831 BlockParentLink(Weak<Module>, NodeId),
834 /// One node in the tree of modules.
836 parent_link: ParentLink,
837 def: Cell<Option<Def>>,
840 children: RefCell<HashMap<Name, NameBindings>>,
841 imports: RefCell<Vec<ImportDirective>>,
843 // The external module children of this node that were declared with
845 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
847 // The anonymous children of this node. Anonymous children are pseudo-
848 // modules that are implicitly created around items contained within
851 // For example, if we have this:
859 // There will be an anonymous module created around `g` with the ID of the
860 // entry block for `f`.
861 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
863 // The status of resolving each import in this module.
864 import_resolutions: RefCell<HashMap<Name, ImportResolutionPerNamespace>>,
866 // The number of unresolved globs that this module exports.
867 glob_count: Cell<usize>,
869 // The number of unresolved pub imports (both regular and globs) in this module
870 pub_count: Cell<usize>,
872 // The number of unresolved pub glob imports in this module
873 pub_glob_count: Cell<usize>,
875 // The index of the import we're resolving.
876 resolved_import_count: Cell<usize>,
878 // Whether this module is populated. If not populated, any attempt to
879 // access the children must be preceded with a
880 // `populate_module_if_necessary` call.
881 populated: Cell<bool>,
885 fn new(parent_link: ParentLink,
891 parent_link: parent_link,
893 is_public: is_public,
894 children: RefCell::new(HashMap::new()),
895 imports: RefCell::new(Vec::new()),
896 external_module_children: RefCell::new(HashMap::new()),
897 anonymous_children: RefCell::new(NodeMap()),
898 import_resolutions: RefCell::new(HashMap::new()),
899 glob_count: Cell::new(0),
900 pub_count: Cell::new(0),
901 pub_glob_count: Cell::new(0),
902 resolved_import_count: Cell::new(0),
903 populated: Cell::new(!external),
907 fn def_id(&self) -> Option<DefId> {
908 self.def.get().as_ref().map(Def::def_id)
911 fn is_normal(&self) -> bool {
912 match self.def.get() {
913 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
918 fn is_trait(&self) -> bool {
919 match self.def.get() {
920 Some(DefTrait(_)) => true,
925 fn all_imports_resolved(&self) -> bool {
926 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
927 // it is currently being resolved ! so nope
930 self.imports.borrow().len() == self.resolved_import_count.get()
936 pub fn inc_glob_count(&self) {
937 self.glob_count.set(self.glob_count.get() + 1);
939 pub fn dec_glob_count(&self) {
940 assert!(self.glob_count.get() > 0);
941 self.glob_count.set(self.glob_count.get() - 1);
943 pub fn inc_pub_count(&self) {
944 self.pub_count.set(self.pub_count.get() + 1);
946 pub fn dec_pub_count(&self) {
947 assert!(self.pub_count.get() > 0);
948 self.pub_count.set(self.pub_count.get() - 1);
950 pub fn inc_pub_glob_count(&self) {
951 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
953 pub fn dec_pub_glob_count(&self) {
954 assert!(self.pub_glob_count.get() > 0);
955 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
959 impl fmt::Debug for Module {
960 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
974 flags DefModifiers: u8 {
975 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
976 // or `use Enum::*` to work on private enums.
977 const PUBLIC = 1 << 0,
978 const IMPORTABLE = 1 << 1,
979 // Variants are considered `PUBLIC`, but some of them live in private enums.
980 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
981 const PRIVATE_VARIANT = 1 << 2,
985 // Records a possibly-private value, type, or module definition.
988 modifiers: DefModifiers, // see note in ImportResolutionPerNamespace about how to use this
989 def_or_module: DefOrModule,
1000 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
1001 let modifiers = if module.is_public {
1002 DefModifiers::PUBLIC
1004 DefModifiers::empty()
1005 } | DefModifiers::IMPORTABLE;
1007 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
1010 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
1011 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
1014 fn module(&self) -> Option<Rc<Module>> {
1015 match self.def_or_module {
1016 DefOrModule::Module(ref module) => Some(module.clone()),
1017 DefOrModule::Def(_) => None,
1021 fn def(&self) -> Option<Def> {
1022 match self.def_or_module {
1023 DefOrModule::Def(def) => Some(def),
1024 DefOrModule::Module(ref module) => module.def.get(),
1029 // Records at most one definition that a name in a namespace is bound to
1030 #[derive(Clone,Debug)]
1031 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
1035 NameBinding(Rc::new(RefCell::new(None)))
1038 fn create_from_module(module: Rc<Module>) -> Self {
1039 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
1042 fn set(&self, ns_def: NsDef) {
1043 *self.0.borrow_mut() = Some(ns_def);
1046 fn set_modifiers(&self, modifiers: DefModifiers) {
1047 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
1048 ns_def.modifiers = modifiers
1052 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> {
1056 // Lifted versions of the NsDef methods and fields
1057 fn def(&self) -> Option<Def> {
1058 self.borrow().as_ref().and_then(NsDef::def)
1060 fn module(&self) -> Option<Rc<Module>> {
1061 self.borrow().as_ref().and_then(NsDef::module)
1063 fn span(&self) -> Option<Span> {
1064 self.borrow().as_ref().and_then(|def| def.span)
1066 fn modifiers(&self) -> Option<DefModifiers> {
1067 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
1070 fn defined(&self) -> bool {
1071 self.borrow().is_some()
1074 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1075 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1078 fn is_public(&self) -> bool {
1079 self.defined_with(DefModifiers::PUBLIC)
1082 fn def_and_lp(&self) -> (Def, LastPrivate) {
1083 let def = self.def().unwrap();
1084 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1088 // Records the definitions (at most one for each namespace) that a name is
1090 #[derive(Clone,Debug)]
1091 pub struct NameBindings {
1092 type_ns: NameBinding, // < Meaning in type namespace.
1093 value_ns: NameBinding, // < Meaning in value namespace.
1096 impl ::std::ops::Index<Namespace> for NameBindings {
1097 type Output = NameBinding;
1098 fn index(&self, namespace: Namespace) -> &NameBinding {
1099 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1104 fn new() -> NameBindings {
1106 type_ns: NameBinding::new(),
1107 value_ns: NameBinding::new(),
1111 /// Creates a new module in this set of name bindings.
1112 fn define_module(&self, module: Rc<Module>, sp: Span) {
1113 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1116 /// Records a type definition.
1117 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1118 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1119 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1122 /// Records a value definition.
1123 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1124 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1125 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1129 /// Interns the names of the primitive types.
1130 struct PrimitiveTypeTable {
1131 primitive_types: HashMap<Name, PrimTy>,
1134 impl PrimitiveTypeTable {
1135 fn new() -> PrimitiveTypeTable {
1136 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1138 table.intern("bool", TyBool);
1139 table.intern("char", TyChar);
1140 table.intern("f32", TyFloat(TyF32));
1141 table.intern("f64", TyFloat(TyF64));
1142 table.intern("isize", TyInt(TyIs));
1143 table.intern("i8", TyInt(TyI8));
1144 table.intern("i16", TyInt(TyI16));
1145 table.intern("i32", TyInt(TyI32));
1146 table.intern("i64", TyInt(TyI64));
1147 table.intern("str", TyStr);
1148 table.intern("usize", TyUint(TyUs));
1149 table.intern("u8", TyUint(TyU8));
1150 table.intern("u16", TyUint(TyU16));
1151 table.intern("u32", TyUint(TyU32));
1152 table.intern("u64", TyUint(TyU64));
1157 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1158 self.primitive_types.insert(token::intern(string), primitive_type);
1162 /// The main resolver class.
1163 pub struct Resolver<'a, 'tcx: 'a> {
1164 session: &'a Session,
1166 ast_map: &'a hir_map::Map<'tcx>,
1168 graph_root: Rc<Module>,
1170 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1172 structs: FnvHashMap<DefId, Vec<Name>>,
1174 // The number of imports that are currently unresolved.
1175 unresolved_imports: usize,
1177 // The module that represents the current item scope.
1178 current_module: Rc<Module>,
1180 // The current set of local scopes, for values.
1181 // FIXME #4948: Reuse ribs to avoid allocation.
1182 value_ribs: Vec<Rib>,
1184 // The current set of local scopes, for types.
1185 type_ribs: Vec<Rib>,
1187 // The current set of local scopes, for labels.
1188 label_ribs: Vec<Rib>,
1190 // The trait that the current context can refer to.
1191 current_trait_ref: Option<(DefId, TraitRef)>,
1193 // The current self type if inside an impl (used for better errors).
1194 current_self_type: Option<Ty>,
1196 // The idents for the primitive types.
1197 primitive_type_table: PrimitiveTypeTable,
1199 def_map: RefCell<DefMap>,
1200 freevars: FreevarMap,
1201 freevars_seen: NodeMap<NodeMap<usize>>,
1202 export_map: ExportMap,
1203 trait_map: TraitMap,
1204 external_exports: ExternalExports,
1206 // Whether or not to print error messages. Can be set to true
1207 // when getting additional info for error message suggestions,
1208 // so as to avoid printing duplicate errors
1211 make_glob_map: bool,
1212 // Maps imports to the names of items actually imported (this actually maps
1213 // all imports, but only glob imports are actually interesting).
1216 used_imports: HashSet<(NodeId, Namespace)>,
1217 used_crates: HashSet<CrateNum>,
1219 // Callback function for intercepting walks
1220 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1221 // The intention is that the callback modifies this flag.
1222 // Once set, the resolver falls out of the walk, preserving the ribs.
1226 #[derive(PartialEq)]
1227 enum FallbackChecks {
1229 OnlyTraitAndStatics,
1232 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1233 fn new(session: &'a Session,
1234 ast_map: &'a hir_map::Map<'tcx>,
1235 make_glob_map: MakeGlobMap)
1236 -> Resolver<'a, 'tcx> {
1237 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1238 let graph_root = Module::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1245 // The outermost module has def ID 0; this is not reflected in the
1247 graph_root: graph_root.clone(),
1249 trait_item_map: FnvHashMap(),
1250 structs: FnvHashMap(),
1252 unresolved_imports: 0,
1254 current_module: graph_root,
1255 value_ribs: Vec::new(),
1256 type_ribs: Vec::new(),
1257 label_ribs: Vec::new(),
1259 current_trait_ref: None,
1260 current_self_type: None,
1262 primitive_type_table: PrimitiveTypeTable::new(),
1264 def_map: RefCell::new(NodeMap()),
1265 freevars: NodeMap(),
1266 freevars_seen: NodeMap(),
1267 export_map: NodeMap(),
1268 trait_map: NodeMap(),
1269 used_imports: HashSet::new(),
1270 used_crates: HashSet::new(),
1271 external_exports: DefIdSet(),
1274 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1275 glob_map: HashMap::new(),
1283 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1284 if !self.make_glob_map {
1287 if self.glob_map.contains_key(&import_id) {
1288 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1292 let mut new_set = HashSet::new();
1293 new_set.insert(name);
1294 self.glob_map.insert(import_id, new_set);
1297 fn get_trait_name(&self, did: DefId) -> Name {
1298 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1299 self.ast_map.expect_item(node_id).name
1301 self.session.cstore.item_name(did)
1305 /// Check that an external crate doesn't collide with items or other external crates.
1306 fn check_for_conflicts_for_external_crate(&self, module: &Module, name: Name, span: Span) {
1307 if module.external_module_children.borrow().contains_key(&name) {
1308 span_err!(self.session,
1311 "an external crate named `{}` has already been imported into this module",
1314 match module.children.borrow().get(&name) {
1315 Some(name_bindings) if name_bindings.type_ns.defined() => {
1317 name_bindings.type_ns.span().unwrap_or(codemap::DUMMY_SP),
1318 ResolutionError::NameConflictsWithExternCrate(name));
1324 /// Checks that the names of items don't collide with external crates.
1325 fn check_for_conflicts_between_external_crates_and_items(&self,
1329 if module.external_module_children.borrow().contains_key(&name) {
1330 resolve_error(self, span, ResolutionError::NameConflictsWithExternCrate(name));
1334 /// Resolves the given module path from the given root `module_`.
1335 fn resolve_module_path_from_root(&mut self,
1336 module_: Rc<Module>,
1337 module_path: &[Name],
1340 name_search_type: NameSearchType,
1342 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1343 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1344 match module.external_module_children.borrow().get(&needle) {
1345 Some(_) => Some(module.clone()),
1346 None => match module.parent_link {
1347 ModuleParentLink(ref parent, _) => {
1348 search_parent_externals(needle, &parent.upgrade().unwrap())
1355 let mut search_module = module_;
1356 let mut index = index;
1357 let module_path_len = module_path.len();
1358 let mut closest_private = lp;
1360 // Resolve the module part of the path. This does not involve looking
1361 // upward though scope chains; we simply resolve names directly in
1362 // modules as we go.
1363 while index < module_path_len {
1364 let name = module_path[index];
1365 match self.resolve_name_in_module(search_module.clone(),
1371 let segment_name = name.as_str();
1372 let module_name = module_to_string(&*search_module);
1373 let mut span = span;
1374 let msg = if "???" == &module_name[..] {
1375 span.hi = span.lo + Pos::from_usize(segment_name.len());
1377 match search_parent_externals(name, &self.current_module) {
1379 let path_str = names_to_string(module_path);
1380 let target_mod_str = module_to_string(&*module);
1381 let current_mod_str = module_to_string(&*self.current_module);
1383 let prefix = if target_mod_str == current_mod_str {
1384 "self::".to_string()
1386 format!("{}::", target_mod_str)
1389 format!("Did you mean `{}{}`?", prefix, path_str)
1391 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1394 format!("Could not find `{}` in `{}`", segment_name, module_name)
1397 return Failed(Some((span, msg)));
1399 Failed(err) => return Failed(err),
1401 debug!("(resolving module path for import) module resolution is \
1404 return Indeterminate;
1406 Success((target, used_proxy)) => {
1407 // Check to see whether there are type bindings, and, if
1408 // so, whether there is a module within.
1409 if let Some(module_def) = target.binding.module() {
1410 // track extern crates for unused_extern_crate lint
1411 if let Some(did) = module_def.def_id() {
1412 self.used_crates.insert(did.krate);
1415 search_module = module_def;
1417 // Keep track of the closest private module used
1418 // when resolving this import chain.
1419 if !used_proxy && !search_module.is_public {
1420 if let Some(did) = search_module.def_id() {
1421 closest_private = LastMod(DependsOn(did));
1425 let msg = format!("Not a module `{}`", name);
1426 return Failed(Some((span, msg)));
1434 return Success((search_module, closest_private));
1437 /// Attempts to resolve the module part of an import directive or path
1438 /// rooted at the given module.
1440 /// On success, returns the resolved module, and the closest *private*
1441 /// module found to the destination when resolving this path.
1442 fn resolve_module_path(&mut self,
1443 module_: Rc<Module>,
1444 module_path: &[Name],
1445 use_lexical_scope: UseLexicalScopeFlag,
1447 name_search_type: NameSearchType)
1448 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1449 let module_path_len = module_path.len();
1450 assert!(module_path_len > 0);
1452 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1453 names_to_string(module_path),
1454 module_to_string(&*module_));
1456 // Resolve the module prefix, if any.
1457 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1462 match module_prefix_result {
1464 let mpath = names_to_string(module_path);
1465 let mpath = &mpath[..];
1466 match mpath.rfind(':') {
1468 let msg = format!("Could not find `{}` in `{}`",
1469 // idx +- 1 to account for the
1470 // colons on either side
1473 return Failed(Some((span, msg)));
1476 return Failed(None);
1480 Failed(err) => return Failed(err),
1482 debug!("(resolving module path for import) indeterminate; bailing");
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.clone();
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_, module_path[0]) {
1502 Failed(err) => return Failed(err),
1504 debug!("(resolving module path for import) indeterminate; bailing");
1505 return Indeterminate;
1507 Success(containing_module) => {
1508 search_module = containing_module;
1510 last_private = LastMod(AllPublic);
1516 Success(PrefixFound(ref containing_module, index)) => {
1517 search_module = containing_module.clone();
1518 start_index = index;
1519 last_private = LastMod(DependsOn(containing_module.def_id()
1524 self.resolve_module_path_from_root(search_module,
1532 /// Invariant: This must only be called during main resolution, not during
1533 /// import resolution.
1534 fn resolve_item_in_lexical_scope(&mut self,
1535 module_: Rc<Module>,
1537 namespace: Namespace,
1539 -> ResolveResult<(Target, bool)> {
1540 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1543 module_to_string(&*module_));
1545 // The current module node is handled specially. First, check for
1546 // its immediate children.
1547 build_reduced_graph::populate_module_if_necessary(self, &module_);
1549 match module_.children.borrow().get(&name) {
1550 Some(name_bindings) if name_bindings[namespace].defined() => {
1551 debug!("top name bindings succeeded");
1552 return Success((Target::new(module_.clone(),
1553 name_bindings[namespace].clone(),
1558 // Not found; continue.
1562 // Now check for its import directives. We don't have to have resolved
1563 // all its imports in the usual way; this is because chains of
1564 // adjacent import statements are processed as though they mutated the
1566 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1567 match import_resolution[namespace].target.clone() {
1569 // Not found; continue.
1570 debug!("(resolving item in lexical scope) found import resolution, but not \
1575 debug!("(resolving item in lexical scope) using import resolution");
1576 // track used imports and extern crates as well
1577 let id = import_resolution[namespace].id;
1579 self.used_imports.insert((id, namespace));
1580 self.record_import_use(id, name);
1581 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1582 self.used_crates.insert(kid);
1585 return Success((target, false));
1590 // Search for external modules.
1591 if namespace == TypeNS {
1592 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1593 let child = module_.external_module_children.borrow().get(&name).cloned();
1594 if let Some(module) = child {
1595 let name_binding = NameBinding::create_from_module(module);
1596 debug!("lower name bindings succeeded");
1597 return Success((Target::new(module_, name_binding, Shadowable::Never),
1602 // Finally, proceed up the scope chain looking for parent modules.
1603 let mut search_module = module_;
1605 // Go to the next parent.
1606 match search_module.parent_link.clone() {
1608 // No more parents. This module was unresolved.
1609 debug!("(resolving item in lexical scope) unresolved module");
1610 return Failed(None);
1612 ModuleParentLink(parent_module_node, _) => {
1613 if search_module.is_normal() {
1614 // We stop the search here.
1615 debug!("(resolving item in lexical scope) unresolved module: not \
1616 searching through module parents");
1617 return Failed(None);
1619 search_module = parent_module_node.upgrade().unwrap();
1622 BlockParentLink(ref parent_module_node, _) => {
1623 search_module = parent_module_node.upgrade().unwrap();
1627 // Resolve the name in the parent module.
1628 match self.resolve_name_in_module(search_module.clone(),
1633 Failed(Some((span, msg))) => {
1634 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1636 Failed(None) => (), // Continue up the search chain.
1638 // We couldn't see through the higher scope because of an
1639 // unresolved import higher up. Bail.
1641 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1642 return Indeterminate;
1644 Success((target, used_reexport)) => {
1645 // We found the module.
1646 debug!("(resolving item in lexical scope) found name in module, done");
1647 return Success((target, used_reexport));
1653 /// Resolves a module name in the current lexical scope.
1654 fn resolve_module_in_lexical_scope(&mut self,
1655 module_: Rc<Module>,
1657 -> ResolveResult<Rc<Module>> {
1658 // If this module is an anonymous module, resolve the item in the
1659 // lexical scope. Otherwise, resolve the item from the crate root.
1660 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS, true);
1661 match resolve_result {
1662 Success((target, _)) => {
1663 if let Some(module_def) = target.binding.module() {
1664 return Success(module_def)
1666 debug!("!!! (resolving module in lexical scope) module \
1667 wasn't actually a module!");
1668 return Failed(None);
1672 debug!("(resolving module in lexical scope) indeterminate; bailing");
1673 return Indeterminate;
1676 debug!("(resolving module in lexical scope) failed to resolve");
1682 /// Returns the nearest normal module parent of the given module.
1683 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1684 let mut module_ = module_;
1686 match module_.parent_link.clone() {
1687 NoParentLink => return None,
1688 ModuleParentLink(new_module, _) |
1689 BlockParentLink(new_module, _) => {
1690 let new_module = new_module.upgrade().unwrap();
1691 if new_module.is_normal() {
1692 return Some(new_module);
1694 module_ = new_module;
1700 /// Returns the nearest normal module parent of the given module, or the
1701 /// module itself if it is a normal module.
1702 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1703 if module_.is_normal() {
1706 match self.get_nearest_normal_module_parent(module_.clone()) {
1708 Some(new_module) => new_module,
1712 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1713 /// (b) some chain of `super::`.
1714 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1715 fn resolve_module_prefix(&mut self,
1716 module_: Rc<Module>,
1717 module_path: &[Name])
1718 -> ResolveResult<ModulePrefixResult> {
1719 // Start at the current module if we see `self` or `super`, or at the
1720 // top of the crate otherwise.
1721 let mut i = match &*module_path[0].as_str() {
1724 _ => return Success(NoPrefixFound),
1726 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1728 // Now loop through all the `super`s we find.
1729 while i < module_path.len() && "super" == module_path[i].as_str() {
1730 debug!("(resolving module prefix) resolving `super` at {}",
1731 module_to_string(&*containing_module));
1732 match self.get_nearest_normal_module_parent(containing_module) {
1733 None => return Failed(None),
1734 Some(new_module) => {
1735 containing_module = new_module;
1741 debug!("(resolving module prefix) finished resolving prefix at {}",
1742 module_to_string(&*containing_module));
1744 return Success(PrefixFound(containing_module, i));
1747 /// Attempts to resolve the supplied name in the given module for the
1748 /// given namespace. If successful, returns the target corresponding to
1751 /// The boolean returned on success is an indicator of whether this lookup
1752 /// passed through a public re-export proxy.
1753 fn resolve_name_in_module(&mut self,
1754 module_: Rc<Module>,
1756 namespace: Namespace,
1757 name_search_type: NameSearchType,
1758 allow_private_imports: bool)
1759 -> ResolveResult<(Target, bool)> {
1760 debug!("(resolving name in module) resolving `{}` in `{}`",
1762 module_to_string(&*module_));
1764 // First, check the direct children of the module.
1765 build_reduced_graph::populate_module_if_necessary(self, &module_);
1767 match module_.children.borrow().get(&name) {
1768 Some(name_bindings) if name_bindings[namespace].defined() => {
1769 debug!("(resolving name in module) found node as child");
1770 return Success((Target::new(module_.clone(),
1771 name_bindings[namespace].clone(),
1780 // Next, check the module's imports if necessary.
1782 // If this is a search of all imports, we should be done with glob
1783 // resolution at this point.
1784 if name_search_type == PathSearch {
1785 assert_eq!(module_.glob_count.get(), 0);
1788 // Check the list of resolved imports.
1789 match module_.import_resolutions.borrow().get(&name) {
1790 Some(import_resolution) if allow_private_imports ||
1791 import_resolution[namespace].is_public => {
1793 if import_resolution[namespace].is_public &&
1794 import_resolution.outstanding_references != 0 {
1795 debug!("(resolving name in module) import unresolved; bailing out");
1796 return Indeterminate;
1798 match import_resolution[namespace].target.clone() {
1800 debug!("(resolving name in module) name found, but not in namespace {:?}",
1804 debug!("(resolving name in module) resolved to import");
1805 // track used imports and extern crates as well
1806 let id = import_resolution[namespace].id;
1807 self.used_imports.insert((id, namespace));
1808 self.record_import_use(id, name);
1809 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1810 self.used_crates.insert(kid);
1812 return Success((target, true));
1816 Some(..) | None => {} // Continue.
1819 // Finally, search through external children.
1820 if namespace == TypeNS {
1821 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1822 let child = module_.external_module_children.borrow().get(&name).cloned();
1823 if let Some(module) = child {
1824 let name_binding = NameBinding::create_from_module(module);
1825 return Success((Target::new(module_, name_binding, Shadowable::Never),
1830 // We're out of luck.
1831 debug!("(resolving name in module) failed to resolve `{}`", name);
1832 return Failed(None);
1835 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1836 let index = module_.resolved_import_count.get();
1837 let imports = module_.imports.borrow();
1838 let import_count = imports.len();
1839 if index != import_count {
1841 (*imports)[index].span,
1842 ResolutionError::UnresolvedImport(None));
1845 // Descend into children and anonymous children.
1846 build_reduced_graph::populate_module_if_necessary(self, &module_);
1848 for (_, child_node) in module_.children.borrow().iter() {
1849 match child_node.type_ns.module() {
1853 Some(child_module) => {
1854 self.report_unresolved_imports(child_module);
1859 for (_, module_) in module_.anonymous_children.borrow().iter() {
1860 self.report_unresolved_imports(module_.clone());
1866 // We maintain a list of value ribs and type ribs.
1868 // Simultaneously, we keep track of the current position in the module
1869 // graph in the `current_module` pointer. When we go to resolve a name in
1870 // the value or type namespaces, we first look through all the ribs and
1871 // then query the module graph. When we resolve a name in the module
1872 // namespace, we can skip all the ribs (since nested modules are not
1873 // allowed within blocks in Rust) and jump straight to the current module
1876 // Named implementations are handled separately. When we find a method
1877 // call, we consult the module node to find all of the implementations in
1878 // scope. This information is lazily cached in the module node. We then
1879 // generate a fake "implementation scope" containing all the
1880 // implementations thus found, for compatibility with old resolve pass.
1882 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1883 where F: FnOnce(&mut Resolver)
1885 let orig_module = self.current_module.clone();
1887 // Move down in the graph.
1893 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1895 match orig_module.children.borrow().get(&name) {
1897 debug!("!!! (with scope) didn't find `{}` in `{}`",
1899 module_to_string(&*orig_module));
1901 Some(name_bindings) => {
1902 match name_bindings.type_ns.module() {
1904 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1906 module_to_string(&*orig_module));
1909 self.current_module = module_;
1919 self.current_module = orig_module;
1922 /// Searches the current set of local scopes for labels.
1923 /// Stops after meeting a closure.
1924 fn search_label(&self, name: Name) -> Option<DefLike> {
1925 for rib in self.label_ribs.iter().rev() {
1931 // Do not resolve labels across function boundary
1935 let result = rib.bindings.get(&name).cloned();
1936 if result.is_some() {
1943 fn resolve_crate(&mut self, krate: &hir::Crate) {
1944 debug!("(resolving crate) starting");
1946 intravisit::walk_crate(self, krate);
1949 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1950 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1951 span_err!(self.session,
1954 "user-defined types or type parameters cannot shadow the primitive types");
1958 fn resolve_item(&mut self, item: &Item) {
1959 let name = item.name;
1961 debug!("(resolving item) resolving {}", name);
1964 ItemEnum(_, ref generics) |
1965 ItemTy(_, ref generics) |
1966 ItemStruct(_, ref generics) => {
1967 self.check_if_primitive_type_name(name, item.span);
1969 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1970 |this| intravisit::walk_item(this, item));
1972 ItemFn(_, _, _, _, ref generics, _) => {
1973 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1974 |this| intravisit::walk_item(this, item));
1977 ItemDefaultImpl(_, ref trait_ref) => {
1978 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1980 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1981 self.resolve_implementation(generics,
1988 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1989 self.check_if_primitive_type_name(name, item.span);
1991 // Create a new rib for the trait-wide type parameters.
1992 self.with_type_parameter_rib(HasTypeParameters(generics,
1996 let local_def_id = this.ast_map.local_def_id(item.id);
1997 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1998 this.visit_generics(generics);
1999 walk_list!(this, visit_ty_param_bound, bounds);
2001 for trait_item in trait_items {
2002 match trait_item.node {
2003 hir::ConstTraitItem(_, ref default) => {
2004 // Only impose the restrictions of
2005 // ConstRibKind if there's an actual constant
2006 // expression in a provided default.
2007 if default.is_some() {
2008 this.with_constant_rib(|this| {
2009 intravisit::walk_trait_item(this, trait_item)
2012 intravisit::walk_trait_item(this, trait_item)
2015 hir::MethodTraitItem(ref sig, _) => {
2016 let type_parameters =
2017 HasTypeParameters(&sig.generics,
2020 this.with_type_parameter_rib(type_parameters, |this| {
2021 intravisit::walk_trait_item(this, trait_item)
2024 hir::TypeTraitItem(..) => {
2025 this.check_if_primitive_type_name(trait_item.name,
2027 this.with_type_parameter_rib(NoTypeParameters, |this| {
2028 intravisit::walk_trait_item(this, trait_item)
2037 ItemMod(_) | ItemForeignMod(_) => {
2038 self.with_scope(Some(name), |this| {
2039 intravisit::walk_item(this, item);
2043 ItemConst(..) | ItemStatic(..) => {
2044 self.with_constant_rib(|this| {
2045 intravisit::walk_item(this, item);
2049 ItemUse(ref view_path) => {
2050 // check for imports shadowing primitive types
2051 let check_rename = |this: &Self, id, name| {
2052 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
2053 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2054 this.check_if_primitive_type_name(name, item.span);
2060 match view_path.node {
2061 hir::ViewPathSimple(name, _) => {
2062 check_rename(self, item.id, name);
2064 hir::ViewPathList(ref prefix, ref items) => {
2066 if let Some(name) = item.node.rename() {
2067 check_rename(self, item.node.id(), name);
2071 // Resolve prefix of an import with empty braces (issue #28388)
2072 if items.is_empty() && !prefix.segments.is_empty() {
2073 match self.resolve_crate_relative_path(prefix.span,
2077 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2081 ResolutionError::FailedToResolve(
2082 &path_names_to_string(prefix, 0)));
2083 self.record_def(item.id, err_path_resolution());
2092 ItemExternCrate(_) => {
2093 // do nothing, these are just around to be encoded
2098 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2099 where F: FnOnce(&mut Resolver)
2101 match type_parameters {
2102 HasTypeParameters(generics, space, rib_kind) => {
2103 let mut function_type_rib = Rib::new(rib_kind);
2104 let mut seen_bindings = HashSet::new();
2105 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2106 let name = type_parameter.name;
2107 debug!("with_type_parameter_rib: {}", type_parameter.id);
2109 if seen_bindings.contains(&name) {
2111 type_parameter.span,
2112 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2114 seen_bindings.insert(name);
2116 // plain insert (no renaming)
2117 function_type_rib.bindings
2119 DlDef(DefTyParam(space,
2122 .local_def_id(type_parameter.id),
2125 self.type_ribs.push(function_type_rib);
2128 NoTypeParameters => {
2135 match type_parameters {
2136 HasTypeParameters(..) => {
2138 self.type_ribs.pop();
2141 NoTypeParameters => {}
2145 fn with_label_rib<F>(&mut self, f: F)
2146 where F: FnOnce(&mut Resolver)
2148 self.label_ribs.push(Rib::new(NormalRibKind));
2151 self.label_ribs.pop();
2155 fn with_constant_rib<F>(&mut self, f: F)
2156 where F: FnOnce(&mut Resolver)
2158 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2159 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2162 self.type_ribs.pop();
2163 self.value_ribs.pop();
2167 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2168 // Create a value rib for the function.
2169 self.value_ribs.push(Rib::new(rib_kind));
2171 // Create a label rib for the function.
2172 self.label_ribs.push(Rib::new(rib_kind));
2174 // Add each argument to the rib.
2175 let mut bindings_list = HashMap::new();
2176 for argument in &declaration.inputs {
2177 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2179 self.visit_ty(&*argument.ty);
2181 debug!("(resolving function) recorded argument");
2183 intravisit::walk_fn_ret_ty(self, &declaration.output);
2185 // Resolve the function body.
2186 self.visit_block(block);
2188 debug!("(resolving function) leaving function");
2191 self.label_ribs.pop();
2192 self.value_ribs.pop();
2196 fn resolve_trait_reference(&mut self,
2200 -> Result<PathResolution, ()> {
2201 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2202 if let DefTrait(_) = path_res.base_def {
2203 debug!("(resolving trait) found trait def: {:?}", path_res);
2207 resolve_struct_error(self,
2209 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2212 // If it's a typedef, give a note
2213 if let DefTy(..) = path_res.base_def {
2214 err.span_note(trait_path.span,
2215 "`type` aliases cannot be used for traits");
2223 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2229 fn resolve_generics(&mut self, generics: &Generics) {
2230 for type_parameter in generics.ty_params.iter() {
2231 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2233 for predicate in &generics.where_clause.predicates {
2235 &hir::WherePredicate::BoundPredicate(_) |
2236 &hir::WherePredicate::RegionPredicate(_) => {}
2237 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2238 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2239 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2240 self.record_def(eq_pred.id, path_res.unwrap());
2244 ResolutionError::UndeclaredAssociatedType);
2245 self.record_def(eq_pred.id, err_path_resolution());
2250 intravisit::walk_generics(self, generics);
2253 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2254 where F: FnOnce(&mut Resolver) -> T
2256 // Handle nested impls (inside fn bodies)
2257 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2258 let result = f(self);
2259 self.current_self_type = previous_value;
2263 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2264 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2266 let mut new_val = None;
2267 let mut new_id = None;
2268 if let Some(trait_ref) = opt_trait_ref {
2269 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2272 assert!(path_res.depth == 0);
2273 self.record_def(trait_ref.ref_id, path_res);
2274 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2275 new_id = Some(path_res.base_def.def_id());
2277 self.record_def(trait_ref.ref_id, err_path_resolution());
2279 intravisit::walk_trait_ref(self, trait_ref);
2281 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2282 let result = f(self, new_id);
2283 self.current_trait_ref = original_trait_ref;
2287 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2288 where F: FnOnce(&mut Resolver)
2290 let mut self_type_rib = Rib::new(NormalRibKind);
2292 // plain insert (no renaming, types are not currently hygienic....)
2293 let name = special_names::type_self;
2294 self_type_rib.bindings.insert(name, DlDef(self_def));
2295 self.type_ribs.push(self_type_rib);
2298 self.type_ribs.pop();
2302 fn resolve_implementation(&mut self,
2303 generics: &Generics,
2304 opt_trait_reference: &Option<TraitRef>,
2307 impl_items: &[ImplItem]) {
2308 // If applicable, create a rib for the type parameters.
2309 self.with_type_parameter_rib(HasTypeParameters(generics,
2313 // Resolve the type parameters.
2314 this.visit_generics(generics);
2316 // Resolve the trait reference, if necessary.
2317 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2318 // Resolve the self type.
2319 this.visit_ty(self_type);
2321 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2322 this.with_current_self_type(self_type, |this| {
2323 for impl_item in impl_items {
2324 match impl_item.node {
2325 hir::ImplItemKind::Const(..) => {
2326 // If this is a trait impl, ensure the const
2328 this.check_trait_item(impl_item.name,
2330 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2331 this.with_constant_rib(|this| {
2332 intravisit::walk_impl_item(this, impl_item);
2335 hir::ImplItemKind::Method(ref sig, _) => {
2336 // If this is a trait impl, ensure the method
2338 this.check_trait_item(impl_item.name,
2340 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2342 // We also need a new scope for the method-
2343 // specific type parameters.
2344 let type_parameters =
2345 HasTypeParameters(&sig.generics,
2348 this.with_type_parameter_rib(type_parameters, |this| {
2349 intravisit::walk_impl_item(this, impl_item);
2352 hir::ImplItemKind::Type(ref ty) => {
2353 // If this is a trait impl, ensure the type
2355 this.check_trait_item(impl_item.name,
2357 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2369 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2370 where F: FnOnce(Name, &str) -> ResolutionError
2372 // If there is a TraitRef in scope for an impl, then the method must be in the
2374 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2375 if !self.trait_item_map.contains_key(&(name, did)) {
2376 let path_str = path_names_to_string(&trait_ref.path, 0);
2377 resolve_error(self, span, err(name, &*path_str));
2382 fn resolve_local(&mut self, local: &Local) {
2383 // Resolve the type.
2384 walk_list!(self, visit_ty, &local.ty);
2386 // Resolve the initializer.
2387 walk_list!(self, visit_expr, &local.init);
2389 // Resolve the pattern.
2390 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2393 // build a map from pattern identifiers to binding-info's.
2394 // this is done hygienically. This could arise for a macro
2395 // that expands into an or-pattern where one 'x' was from the
2396 // user and one 'x' came from the macro.
2397 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2398 let mut result = HashMap::new();
2399 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2400 let name = path1.node;
2404 binding_mode: binding_mode,
2410 // check that all of the arms in an or-pattern have exactly the
2411 // same set of bindings, with the same binding modes for each.
2412 fn check_consistent_bindings(&mut self, arm: &Arm) {
2413 if arm.pats.is_empty() {
2416 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2417 for (i, p) in arm.pats.iter().enumerate() {
2418 let map_i = self.binding_mode_map(&**p);
2420 for (&key, &binding_0) in &map_0 {
2421 match map_i.get(&key) {
2425 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2427 Some(binding_i) => {
2428 if binding_0.binding_mode != binding_i.binding_mode {
2431 ResolutionError::VariableBoundWithDifferentMode(key,
2438 for (&key, &binding) in &map_i {
2439 if !map_0.contains_key(&key) {
2442 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2448 fn resolve_arm(&mut self, arm: &Arm) {
2449 self.value_ribs.push(Rib::new(NormalRibKind));
2451 let mut bindings_list = HashMap::new();
2452 for pattern in &arm.pats {
2453 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2456 // This has to happen *after* we determine which
2457 // pat_idents are variants
2458 self.check_consistent_bindings(arm);
2460 walk_list!(self, visit_expr, &arm.guard);
2461 self.visit_expr(&*arm.body);
2464 self.value_ribs.pop();
2468 fn resolve_block(&mut self, block: &Block) {
2469 debug!("(resolving block) entering block");
2470 self.value_ribs.push(Rib::new(NormalRibKind));
2472 // Move down in the graph, if there's an anonymous module rooted here.
2473 let orig_module = self.current_module.clone();
2474 match orig_module.anonymous_children.borrow().get(&block.id) {
2478 Some(anonymous_module) => {
2479 debug!("(resolving block) found anonymous module, moving down");
2480 self.current_module = anonymous_module.clone();
2484 // Check for imports appearing after non-item statements.
2485 let mut found_non_item = false;
2486 for statement in &block.stmts {
2487 if let hir::StmtDecl(ref declaration, _) = statement.node {
2488 if let hir::DeclItem(i) = declaration.node {
2489 let i = self.ast_map.expect_item(i.id);
2491 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2492 span_err!(self.session,
2495 "imports are not allowed after non-item statements");
2500 found_non_item = true
2503 found_non_item = true;
2507 // Descend into the block.
2508 intravisit::walk_block(self, block);
2512 self.current_module = orig_module;
2513 self.value_ribs.pop();
2515 debug!("(resolving block) leaving block");
2518 fn resolve_type(&mut self, ty: &Ty) {
2520 TyPath(ref maybe_qself, ref path) => {
2521 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2522 maybe_qself.as_ref(),
2526 // `<T>::a::b::c` is resolved by typeck alone.
2527 TypecheckRequired => {
2528 // Resolve embedded types.
2529 intravisit::walk_ty(self, ty);
2532 ResolveAttempt(resolution) => resolution,
2535 // This is a path in the type namespace. Walk through scopes
2539 // Write the result into the def map.
2540 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2541 path_names_to_string(path, 0),
2544 self.record_def(ty.id, def);
2547 self.record_def(ty.id, err_path_resolution());
2549 // Keep reporting some errors even if they're ignored above.
2550 self.resolve_path(ty.id, path, 0, TypeNS, true);
2552 let kind = if maybe_qself.is_some() {
2558 let self_type_name = special_idents::type_self.name;
2559 let is_invalid_self_type_name = path.segments.len() > 0 &&
2560 maybe_qself.is_none() &&
2561 path.segments[0].identifier.name ==
2563 if is_invalid_self_type_name {
2566 ResolutionError::SelfUsedOutsideImplOrTrait);
2570 ResolutionError::UseOfUndeclared(
2572 &*path_names_to_string(path,
2581 // Resolve embedded types.
2582 intravisit::walk_ty(self, ty);
2585 fn resolve_pattern(&mut self,
2587 mode: PatternBindingMode,
2588 // Maps idents to the node ID for the (outermost)
2589 // pattern that binds them
2590 bindings_list: &mut HashMap<Name, NodeId>) {
2591 let pat_id = pattern.id;
2592 walk_pat(pattern, |pattern| {
2593 match pattern.node {
2594 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2595 // The meaning of PatIdent with no type parameters
2596 // depends on whether an enum variant or unit-like struct
2597 // with that name is in scope. The probing lookup has to
2598 // be careful not to emit spurious errors. Only matching
2599 // patterns (match) can match nullary variants or
2600 // unit-like structs. For binding patterns (let
2601 // and the LHS of @-patterns), matching such a value is
2602 // simply disallowed (since it's rarely what you want).
2603 let const_ok = mode == RefutableMode && at_rhs.is_none();
2605 let ident = path1.node;
2606 let renamed = ident.name;
2608 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2610 FoundStructOrEnumVariant(def, lp) if const_ok => {
2611 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2614 self.enforce_default_binding_mode(pattern,
2617 self.record_def(pattern.id,
2624 FoundStructOrEnumVariant(..) => {
2628 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2631 self.record_def(pattern.id, err_path_resolution());
2633 FoundConst(def, lp, _) if const_ok => {
2634 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2636 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2637 self.record_def(pattern.id,
2644 FoundConst(def, _, name) => {
2648 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2651 self.record_def(pattern.id, err_path_resolution());
2653 BareIdentifierPatternUnresolved => {
2654 debug!("(resolving pattern) binding `{}`", renamed);
2656 let def_id = self.ast_map.local_def_id(pattern.id);
2657 let def = DefLocal(def_id, pattern.id);
2659 // Record the definition so that later passes
2660 // will be able to distinguish variants from
2661 // locals in patterns.
2663 self.record_def(pattern.id,
2666 last_private: LastMod(AllPublic),
2670 // Add the binding to the local ribs, if it
2671 // doesn't already exist in the bindings list. (We
2672 // must not add it if it's in the bindings list
2673 // because that breaks the assumptions later
2674 // passes make about or-patterns.)
2675 if !bindings_list.contains_key(&renamed) {
2676 let this = &mut *self;
2677 let last_rib = this.value_ribs.last_mut().unwrap();
2678 last_rib.bindings.insert(renamed, DlDef(def));
2679 bindings_list.insert(renamed, pat_id);
2680 } else if mode == ArgumentIrrefutableMode &&
2681 bindings_list.contains_key(&renamed) {
2682 // Forbid duplicate bindings in the same
2687 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2688 &ident.name.as_str())
2690 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2691 // Then this is a duplicate variable in the
2692 // same disjunction, which is an error.
2696 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2697 &ident.name.as_str())
2700 // Else, not bound in the same pattern: do
2706 PatEnum(ref path, _) => {
2707 // This must be an enum variant, struct or const.
2708 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2713 // The below shouldn't happen because all
2714 // qualified paths should be in PatQPath.
2715 TypecheckRequired =>
2716 self.session.span_bug(path.span,
2717 "resolve_possibly_assoc_item claimed
2719 that a path in PatEnum requires typecheck
2721 to resolve, but qualified paths should be
2724 ResolveAttempt(resolution) => resolution,
2726 if let Some(path_res) = resolution {
2727 match path_res.base_def {
2728 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2729 self.record_def(pattern.id, path_res);
2732 resolve_error(&self,
2734 ResolutionError::StaticVariableReference);
2735 self.record_def(pattern.id, err_path_resolution());
2738 // If anything ends up here entirely resolved,
2739 // it's an error. If anything ends up here
2740 // partially resolved, that's OK, because it may
2741 // be a `T::CONST` that typeck will resolve.
2742 if path_res.depth == 0 {
2746 ResolutionError::NotAnEnumVariantStructOrConst(
2754 self.record_def(pattern.id, err_path_resolution());
2756 let const_name = path.segments
2761 let traits = self.get_traits_containing_item(const_name);
2762 self.trait_map.insert(pattern.id, traits);
2763 self.record_def(pattern.id, path_res);
2771 ResolutionError::UnresolvedEnumVariantStructOrConst(
2772 &path.segments.last().unwrap().identifier.name.as_str())
2774 self.record_def(pattern.id, err_path_resolution());
2776 intravisit::walk_path(self, path);
2779 PatQPath(ref qself, ref path) => {
2780 // Associated constants only.
2781 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2786 TypecheckRequired => {
2787 // All `<T>::CONST` should end up here, and will
2788 // require use of the trait map to resolve
2789 // during typechecking.
2790 let const_name = path.segments
2795 let traits = self.get_traits_containing_item(const_name);
2796 self.trait_map.insert(pattern.id, traits);
2797 intravisit::walk_pat(self, pattern);
2800 ResolveAttempt(resolution) => resolution,
2802 if let Some(path_res) = resolution {
2803 match path_res.base_def {
2804 // All `<T as Trait>::CONST` should end up here, and
2805 // have the trait already selected.
2806 DefAssociatedConst(..) => {
2807 self.record_def(pattern.id, path_res);
2813 ResolutionError::NotAnAssociatedConst(
2814 &path.segments.last().unwrap().identifier.name.as_str()
2817 self.record_def(pattern.id, err_path_resolution());
2823 ResolutionError::UnresolvedAssociatedConst(&path.segments
2829 self.record_def(pattern.id, err_path_resolution());
2831 intravisit::walk_pat(self, pattern);
2834 PatStruct(ref path, _, _) => {
2835 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2836 Some(definition) => {
2837 self.record_def(pattern.id, definition);
2840 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2844 ResolutionError::DoesNotNameAStruct(
2845 &*path_names_to_string(path, 0))
2847 self.record_def(pattern.id, err_path_resolution());
2850 intravisit::walk_path(self, path);
2853 PatLit(_) | PatRange(..) => {
2854 intravisit::walk_pat(self, pattern);
2865 fn resolve_bare_identifier_pattern(&mut self,
2868 -> BareIdentifierPatternResolution {
2869 let module = self.current_module.clone();
2870 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2871 Success((target, _)) => {
2872 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2874 target.binding.borrow());
2875 match target.binding.def() {
2877 panic!("resolved name in the value namespace to a set of name bindings \
2880 // For the two success cases, this lookup can be
2881 // considered as not having a private component because
2882 // the lookup happened only within the current module.
2883 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2884 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2886 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2887 return FoundConst(def, LastMod(AllPublic), name);
2889 Some(DefStatic(..)) => {
2890 resolve_error(self, span, ResolutionError::StaticVariableReference);
2891 return BareIdentifierPatternUnresolved;
2893 _ => return BareIdentifierPatternUnresolved
2898 panic!("unexpected indeterminate result");
2902 Some((span, msg)) => {
2903 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2908 debug!("(resolve bare identifier pattern) failed to find {}", name);
2909 return BareIdentifierPatternUnresolved;
2914 /// Handles paths that may refer to associated items
2915 fn resolve_possibly_assoc_item(&mut self,
2917 maybe_qself: Option<&hir::QSelf>,
2919 namespace: Namespace,
2921 -> AssocItemResolveResult {
2922 let max_assoc_types;
2926 if qself.position == 0 {
2927 return TypecheckRequired;
2929 max_assoc_types = path.segments.len() - qself.position;
2930 // Make sure the trait is valid.
2931 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2934 max_assoc_types = path.segments.len();
2938 let mut resolution = self.with_no_errors(|this| {
2939 this.resolve_path(id, path, 0, namespace, check_ribs)
2941 for depth in 1..max_assoc_types {
2942 if resolution.is_some() {
2945 self.with_no_errors(|this| {
2946 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2949 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2950 // A module is not a valid type or value.
2953 ResolveAttempt(resolution)
2956 /// If `check_ribs` is true, checks the local definitions first; i.e.
2957 /// doesn't skip straight to the containing module.
2958 /// Skips `path_depth` trailing segments, which is also reflected in the
2959 /// returned value. See `middle::def::PathResolution` for more info.
2960 pub fn resolve_path(&mut self,
2964 namespace: Namespace,
2966 -> Option<PathResolution> {
2967 let span = path.span;
2968 let segments = &path.segments[..path.segments.len() - path_depth];
2970 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2973 let def = self.resolve_crate_relative_path(span, segments, namespace);
2974 return def.map(mk_res);
2977 // Try to find a path to an item in a module.
2978 let last_ident = segments.last().unwrap().identifier;
2979 if segments.len() <= 1 {
2980 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2981 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2983 PathResolution::new(def, LastMod(AllPublic), path_depth)
2987 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2988 let def = self.resolve_module_relative_path(span, segments, namespace);
2989 match (def, unqualified_def) {
2990 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2992 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2995 "unnecessary qualification".to_string());
3003 // Resolve a single identifier
3004 fn resolve_identifier(&mut self,
3005 identifier: hir::Ident,
3006 namespace: Namespace,
3009 -> Option<LocalDef> {
3010 // First, check to see whether the name is a primitive type.
3011 if namespace == TypeNS {
3012 if let Some(&prim_ty) = self.primitive_type_table
3014 .get(&identifier.unhygienic_name) {
3015 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
3020 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
3025 let name = identifier.unhygienic_name;
3026 self.resolve_item_by_name_in_lexical_scope(name, namespace, record_used)
3027 .map(LocalDef::from_def)
3030 // Resolve a local definition, potentially adjusting for closures.
3031 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
3032 let ribs = match local_def.ribs {
3033 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
3034 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
3037 let mut def = local_def.def;
3040 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
3042 DefLocal(_, node_id) => {
3046 // Nothing to do. Continue.
3048 ClosureRibKind(function_id) => {
3050 let node_def_id = self.ast_map.local_def_id(node_id);
3052 let seen = self.freevars_seen
3054 .or_insert_with(|| NodeMap());
3055 if let Some(&index) = seen.get(&node_id) {
3056 def = DefUpvar(node_def_id, node_id, index, function_id);
3059 let vec = self.freevars
3061 .or_insert_with(|| vec![]);
3062 let depth = vec.len();
3068 def = DefUpvar(node_def_id, node_id, depth, function_id);
3069 seen.insert(node_id, depth);
3071 ItemRibKind | MethodRibKind => {
3072 // This was an attempt to access an upvar inside a
3073 // named function item. This is not allowed, so we
3077 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3080 ConstantItemRibKind => {
3081 // Still doesn't deal with upvars
3084 ResolutionError::AttemptToUseNonConstantValueInConstant);
3090 DefTyParam(..) | DefSelfTy(..) => {
3093 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3094 // Nothing to do. Continue.
3097 // This was an attempt to use a type parameter outside
3102 ResolutionError::TypeParametersFromOuterFunction);
3105 ConstantItemRibKind => {
3107 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3118 // resolve a "module-relative" path, e.g. a::b::c
3119 fn resolve_module_relative_path(&mut self,
3121 segments: &[hir::PathSegment],
3122 namespace: Namespace)
3123 -> Option<(Def, LastPrivate)> {
3124 let module_path = segments.split_last()
3128 .map(|ps| ps.identifier.name)
3129 .collect::<Vec<_>>();
3131 let containing_module;
3133 let current_module = self.current_module.clone();
3134 match self.resolve_module_path(current_module,
3140 let (span, msg) = match err {
3141 Some((span, msg)) => (span, msg),
3143 let msg = format!("Use of undeclared type or module `{}`",
3144 names_to_string(&module_path));
3149 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3152 Indeterminate => panic!("indeterminate unexpected"),
3153 Success((resulting_module, resulting_last_private)) => {
3154 containing_module = resulting_module;
3155 last_private = resulting_last_private;
3159 let name = segments.last().unwrap().identifier.name;
3160 let def = match self.resolve_name_in_module(containing_module.clone(),
3163 NameSearchType::PathSearch,
3165 Success((Target { binding, .. }, _)) => {
3166 let (def, lp) = binding.def_and_lp();
3167 (def, last_private.or(lp))
3171 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3172 self.used_crates.insert(kid);
3177 /// Invariant: This must be called only during main resolution, not during
3178 /// import resolution.
3179 fn resolve_crate_relative_path(&mut self,
3181 segments: &[hir::PathSegment],
3182 namespace: Namespace)
3183 -> Option<(Def, LastPrivate)> {
3184 let module_path = segments.split_last()
3188 .map(|ps| ps.identifier.name)
3189 .collect::<Vec<_>>();
3191 let root_module = self.graph_root.clone();
3193 let containing_module;
3195 match self.resolve_module_path_from_root(root_module,
3200 LastMod(AllPublic)) {
3202 let (span, msg) = match err {
3203 Some((span, msg)) => (span, msg),
3205 let msg = format!("Use of undeclared module `::{}`",
3206 names_to_string(&module_path[..]));
3211 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3216 panic!("indeterminate unexpected");
3219 Success((resulting_module, resulting_last_private)) => {
3220 containing_module = resulting_module;
3221 last_private = resulting_last_private;
3225 let name = segments.last().unwrap().identifier.name;
3226 match self.resolve_name_in_module(containing_module,
3229 NameSearchType::PathSearch,
3231 Success((Target { binding, .. }, _)) => {
3232 let (def, lp) = binding.def_and_lp();
3233 Some((def, last_private.or(lp)))
3239 fn resolve_identifier_in_local_ribs(&mut self,
3241 namespace: Namespace)
3242 -> Option<LocalDef> {
3243 // Check the local set of ribs.
3244 let (name, ribs) = match namespace {
3245 ValueNS => (ident.name, &self.value_ribs),
3246 TypeNS => (ident.unhygienic_name, &self.type_ribs),
3249 for (i, rib) in ribs.iter().enumerate().rev() {
3250 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3253 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3257 return Some(LocalDef {
3258 ribs: Some((namespace, i)),
3263 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3275 fn resolve_item_by_name_in_lexical_scope(&mut self,
3277 namespace: Namespace,
3281 let module = self.current_module.clone();
3282 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
3283 Success((target, _)) => {
3284 match target.binding.def() {
3286 // This can happen if we were looking for a type and
3287 // found a module instead. Modules don't have defs.
3288 debug!("(resolving item path by identifier in lexical scope) failed to \
3289 resolve {} after success...",
3294 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3296 // This lookup is "all public" because it only searched
3297 // for one identifier in the current module (couldn't
3298 // have passed through reexports or anything like that.
3304 panic!("unexpected indeterminate result");
3307 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3310 if let Some((span, msg)) = err {
3311 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3319 fn with_no_errors<T, F>(&mut self, f: F) -> T
3320 where F: FnOnce(&mut Resolver) -> T
3322 self.emit_errors = false;
3324 self.emit_errors = true;
3328 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3329 fn extract_path_and_node_id(t: &Ty,
3330 allow: FallbackChecks)
3331 -> Option<(Path, NodeId, FallbackChecks)> {
3333 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3334 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3335 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3336 // This doesn't handle the remaining `Ty` variants as they are not
3337 // that commonly the self_type, it might be interesting to provide
3338 // support for those in future.
3343 fn get_module(this: &mut Resolver,
3345 name_path: &[ast::Name])
3346 -> Option<Rc<Module>> {
3347 let root = this.current_module.clone();
3348 let last_name = name_path.last().unwrap();
3350 if name_path.len() == 1 {
3351 match this.primitive_type_table.primitive_types.get(last_name) {
3354 match this.current_module.children.borrow().get(last_name) {
3355 Some(child) => child.type_ns.module(),
3361 match this.resolve_module_path(root,
3366 Success((module, _)) => Some(module),
3372 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3373 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3374 let sig = match this.ast_map.get(node_id) {
3375 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3376 hir::MethodTraitItem(ref sig, _) => sig,
3379 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3380 hir::ImplItemKind::Method(ref sig, _) => sig,
3385 sig.explicit_self.node == hir::SelfStatic
3387 this.session.cstore.is_static_method(did)
3391 let (path, node_id, allowed) = match self.current_self_type {
3392 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3394 None => return NoSuggestion,
3396 None => return NoSuggestion,
3399 if allowed == Everything {
3400 // Look for a field with the same name in the current self_type.
3401 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3402 Some(DefTy(did, _)) |
3403 Some(DefStruct(did)) |
3404 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3407 if fields.iter().any(|&field_name| name == field_name) {
3412 _ => {} // Self type didn't resolve properly
3416 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3418 // Look for a method in the current self type's impl module.
3419 if let Some(module) = get_module(self, path.span, &name_path) {
3420 if let Some(binding) = module.children.borrow().get(&name) {
3421 if let Some(DefMethod(did)) = binding.value_ns.def() {
3422 if is_static_method(self, did) {
3423 return StaticMethod(path_names_to_string(&path, 0));
3425 if self.current_trait_ref.is_some() {
3427 } else if allowed == Everything {
3434 // Look for a method in the current trait.
3435 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3436 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3437 if is_static_method(self, did) {
3438 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3448 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3449 if let Some(macro_name) = self.session.available_macros
3450 .borrow().iter().find(|n| n.as_str() == name) {
3451 return SuggestionType::Macro(format!("{}!", macro_name));
3454 let names = self.value_ribs
3457 .flat_map(|rib| rib.bindings.keys());
3459 if let Some(found) = find_best_match_for_name(names, name, None) {
3460 if name != &*found {
3461 return SuggestionType::Function(found);
3463 } SuggestionType::NotFound
3466 fn resolve_expr(&mut self, expr: &Expr) {
3467 // First, record candidate traits for this expression if it could
3468 // result in the invocation of a method call.
3470 self.record_candidate_traits_for_expr_if_necessary(expr);
3472 // Next, resolve the node.
3474 ExprPath(ref maybe_qself, ref path) => {
3475 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3476 maybe_qself.as_ref(),
3480 // `<T>::a::b::c` is resolved by typeck alone.
3481 TypecheckRequired => {
3482 let method_name = path.segments.last().unwrap().identifier.name;
3483 let traits = self.get_traits_containing_item(method_name);
3484 self.trait_map.insert(expr.id, traits);
3485 intravisit::walk_expr(self, expr);
3488 ResolveAttempt(resolution) => resolution,
3491 // This is a local path in the value namespace. Walk through
3492 // scopes looking for it.
3493 if let Some(path_res) = resolution {
3494 // Check if struct variant
3495 if let DefVariant(_, _, true) = path_res.base_def {
3496 let path_name = path_names_to_string(path, 0);
3498 let mut err = resolve_struct_error(self,
3500 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3502 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3504 if self.emit_errors {
3505 err.fileline_help(expr.span, &msg);
3507 err.span_help(expr.span, &msg);
3510 self.record_def(expr.id, err_path_resolution());
3512 // Write the result into the def map.
3513 debug!("(resolving expr) resolved `{}`",
3514 path_names_to_string(path, 0));
3516 // Partial resolutions will need the set of traits in scope,
3517 // so they can be completed during typeck.
3518 if path_res.depth != 0 {
3519 let method_name = path.segments.last().unwrap().identifier.name;
3520 let traits = self.get_traits_containing_item(method_name);
3521 self.trait_map.insert(expr.id, traits);
3524 self.record_def(expr.id, path_res);
3527 // Be helpful if the name refers to a struct
3528 // (The pattern matching def_tys where the id is in self.structs
3529 // matches on regular structs while excluding tuple- and enum-like
3530 // structs, which wouldn't result in this error.)
3531 let path_name = path_names_to_string(path, 0);
3532 let type_res = self.with_no_errors(|this| {
3533 this.resolve_path(expr.id, path, 0, TypeNS, false)
3536 self.record_def(expr.id, err_path_resolution());
3537 match type_res.map(|r| r.base_def) {
3538 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3539 let mut err = resolve_struct_error(self,
3541 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3543 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3545 if self.emit_errors {
3546 err.fileline_help(expr.span, &msg);
3548 err.span_help(expr.span, &msg);
3553 // Keep reporting some errors even if they're ignored above.
3554 self.resolve_path(expr.id, path, 0, ValueNS, true);
3556 let mut method_scope = false;
3557 self.value_ribs.iter().rev().all(|rib| {
3558 method_scope = match rib.kind {
3559 MethodRibKind => true,
3560 ItemRibKind | ConstantItemRibKind => false,
3561 _ => return true, // Keep advancing
3563 false // Stop advancing
3566 if method_scope && special_names::self_.as_str() == &path_name[..] {
3569 ResolutionError::SelfNotAvailableInStaticMethod);
3571 let last_name = path.segments.last().unwrap().identifier.name;
3572 let mut msg = match self.find_fallback_in_self_type(last_name) {
3574 // limit search to 5 to reduce the number
3575 // of stupid suggestions
3576 match self.find_best_match(&path_name) {
3577 SuggestionType::Macro(s) => {
3578 format!("the macro `{}`", s)
3580 SuggestionType::Function(s) => format!("`{}`", s),
3581 SuggestionType::NotFound => "".to_string(),
3584 Field => format!("`self.{}`", path_name),
3586 TraitItem => format!("to call `self.{}`", path_name),
3587 TraitMethod(path_str) |
3588 StaticMethod(path_str) =>
3589 format!("to call `{}::{}`", path_str, path_name),
3592 let mut context = UnresolvedNameContext::Other;
3593 if !msg.is_empty() {
3594 msg = format!(". Did you mean {}?", msg);
3596 // we check if this a module and if so, we display a help
3598 let name_path = path.segments.iter()
3599 .map(|seg| seg.identifier.name)
3600 .collect::<Vec<_>>();
3601 let current_module = self.current_module.clone();
3603 match self.resolve_module_path(current_module,
3609 context = UnresolvedNameContext::PathIsMod(expr.id);
3617 ResolutionError::UnresolvedName(
3618 &*path_name, &*msg, context));
3624 intravisit::walk_expr(self, expr);
3627 ExprStruct(ref path, _, _) => {
3628 // Resolve the path to the structure it goes to. We don't
3629 // check to ensure that the path is actually a structure; that
3630 // is checked later during typeck.
3631 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3632 Some(definition) => self.record_def(expr.id, definition),
3634 debug!("(resolving expression) didn't find struct def",);
3638 ResolutionError::DoesNotNameAStruct(
3639 &*path_names_to_string(path, 0))
3641 self.record_def(expr.id, err_path_resolution());
3645 intravisit::walk_expr(self, expr);
3648 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3649 self.with_label_rib(|this| {
3650 let def_like = DlDef(DefLabel(expr.id));
3653 let rib = this.label_ribs.last_mut().unwrap();
3654 rib.bindings.insert(label.name, def_like);
3657 intravisit::walk_expr(this, expr);
3661 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3662 match self.search_label(label.node.name) {
3664 self.record_def(expr.id, err_path_resolution());
3667 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3669 Some(DlDef(def @ DefLabel(_))) => {
3670 // Since this def is a label, it is never read.
3671 self.record_def(expr.id,
3674 last_private: LastMod(AllPublic),
3679 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3685 intravisit::walk_expr(self, expr);
3690 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3692 ExprField(_, name) => {
3693 // FIXME(#6890): Even though you can't treat a method like a
3694 // field, we need to add any trait methods we find that match
3695 // the field name so that we can do some nice error reporting
3696 // later on in typeck.
3697 let traits = self.get_traits_containing_item(name.node);
3698 self.trait_map.insert(expr.id, traits);
3700 ExprMethodCall(name, _, _) => {
3701 debug!("(recording candidate traits for expr) recording traits for {}",
3703 let traits = self.get_traits_containing_item(name.node);
3704 self.trait_map.insert(expr.id, traits);
3712 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3713 debug!("(getting traits containing item) looking for '{}'", name);
3715 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3716 debug!("(adding trait info) found trait {:?} for method '{}'",
3719 found_traits.push(trait_def_id);
3722 let mut found_traits = Vec::new();
3723 let mut search_module = self.current_module.clone();
3725 // Look for the current trait.
3726 match self.current_trait_ref {
3727 Some((trait_def_id, _)) => {
3728 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3729 add_trait_info(&mut found_traits, trait_def_id, name);
3732 None => {} // Nothing to do.
3735 // Look for trait children.
3736 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3739 for (_, child_names) in search_module.children.borrow().iter() {
3740 let def = match child_names.type_ns.def() {
3744 let trait_def_id = match def {
3745 DefTrait(trait_def_id) => trait_def_id,
3748 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3749 add_trait_info(&mut found_traits, trait_def_id, name);
3754 // Look for imports.
3755 for (_, import) in search_module.import_resolutions.borrow().iter() {
3756 let target = match import.type_ns.target {
3758 Some(ref target) => target,
3760 let did = match target.binding.def() {
3761 Some(DefTrait(trait_def_id)) => trait_def_id,
3762 Some(..) | None => continue,
3764 if self.trait_item_map.contains_key(&(name, did)) {
3765 add_trait_info(&mut found_traits, did, name);
3766 let id = import.type_ns.id;
3767 self.used_imports.insert((id, TypeNS));
3768 let trait_name = self.get_trait_name(did);
3769 self.record_import_use(id, trait_name);
3770 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3771 self.used_crates.insert(kid);
3776 match search_module.parent_link.clone() {
3777 NoParentLink | ModuleParentLink(..) => break,
3778 BlockParentLink(parent_module, _) => {
3779 search_module = parent_module.upgrade().unwrap();
3787 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3788 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3789 assert!(match resolution.last_private {
3790 LastImport{..} => false,
3793 "Import should only be used for `use` directives");
3795 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3796 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3797 self.session.span_bug(span,
3798 &format!("path resolved multiple times ({:?} before, {:?} now)",
3804 fn enforce_default_binding_mode(&mut self,
3806 pat_binding_mode: BindingMode,
3808 match pat_binding_mode {
3809 BindByValue(_) => {}
3813 ResolutionError::CannotUseRefBindingModeWith(descr));
3821 // Diagnostics are not particularly efficient, because they're rarely
3825 #[allow(dead_code)] // useful for debugging
3826 fn dump_module(&mut self, module_: Rc<Module>) {
3827 debug!("Dump of module `{}`:", module_to_string(&*module_));
3829 debug!("Children:");
3830 build_reduced_graph::populate_module_if_necessary(self, &module_);
3831 for (&name, _) in module_.children.borrow().iter() {
3832 debug!("* {}", name);
3835 debug!("Import resolutions:");
3836 let import_resolutions = module_.import_resolutions.borrow();
3837 for (&name, import_resolution) in import_resolutions.iter() {
3839 match import_resolution.value_ns.target {
3841 value_repr = "".to_string();
3844 value_repr = " value:?".to_string();
3850 match import_resolution.type_ns.target {
3852 type_repr = "".to_string();
3855 type_repr = " type:?".to_string();
3860 debug!("* {}:{}{}", name, value_repr, type_repr);
3866 fn names_to_string(names: &[Name]) -> String {
3867 let mut first = true;
3868 let mut result = String::new();
3873 result.push_str("::")
3875 result.push_str(&name.as_str());
3880 fn path_names_to_string(path: &Path, depth: usize) -> String {
3881 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3883 .map(|seg| seg.identifier.name)
3885 names_to_string(&names[..])
3888 /// A somewhat inefficient routine to obtain the name of a module.
3889 fn module_to_string(module: &Module) -> String {
3890 let mut names = Vec::new();
3892 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3893 match module.parent_link {
3895 ModuleParentLink(ref module, name) => {
3897 collect_mod(names, &*module.upgrade().unwrap());
3899 BlockParentLink(ref module, _) => {
3900 // danger, shouldn't be ident?
3901 names.push(special_idents::opaque.name);
3902 collect_mod(names, &*module.upgrade().unwrap());
3906 collect_mod(&mut names, module);
3908 if names.is_empty() {
3909 return "???".to_string();
3911 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3914 fn err_path_resolution() -> PathResolution {
3917 last_private: LastMod(AllPublic),
3923 pub struct CrateMap {
3924 pub def_map: RefCell<DefMap>,
3925 pub freevars: FreevarMap,
3926 pub export_map: ExportMap,
3927 pub trait_map: TraitMap,
3928 pub external_exports: ExternalExports,
3929 pub glob_map: Option<GlobMap>,
3932 #[derive(PartialEq,Copy, Clone)]
3933 pub enum MakeGlobMap {
3938 /// Entry point to crate resolution.
3939 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3940 ast_map: &'a hir_map::Map<'tcx>,
3941 make_glob_map: MakeGlobMap)
3943 let krate = ast_map.krate();
3944 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3946 resolver.resolve_crate(krate);
3948 check_unused::check_crate(&mut resolver, krate);
3951 def_map: resolver.def_map,
3952 freevars: resolver.freevars,
3953 export_map: resolver.export_map,
3954 trait_map: resolver.trait_map,
3955 external_exports: resolver.external_exports,
3956 glob_map: if resolver.make_glob_map {
3957 Some(resolver.glob_map)
3964 /// Builds a name resolution walker to be used within this module,
3965 /// or used externally, with an optional callback function.
3967 /// The callback takes a &mut bool which allows callbacks to end a
3968 /// walk when set to true, passing through the rest of the walk, while
3969 /// preserving the ribs + current module. This allows resolve_path
3970 /// calls to be made with the correct scope info. The node in the
3971 /// callback corresponds to the current node in the walk.
3972 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3973 ast_map: &'a hir_map::Map<'tcx>,
3975 make_glob_map: MakeGlobMap,
3976 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3977 -> Resolver<'a, 'tcx> {
3978 let mut resolver = Resolver::new(session, ast_map, make_glob_map);
3980 resolver.callback = callback;
3982 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3983 session.abort_if_errors();
3985 resolve_imports::resolve_imports(&mut resolver);
3986 session.abort_if_errors();
3988 record_exports::record(&mut resolver);
3989 session.abort_if_errors();
3994 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }