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)]
32 extern crate rustc_bitflags;
33 extern crate rustc_front;
36 use self::PatternBindingMode::*;
37 use self::Namespace::*;
38 use self::NamespaceResult::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::NameSearchType::*;
47 use self::BareIdentifierPatternResolution::*;
48 use self::ParentLink::*;
49 use self::FallbackChecks::*;
51 use rustc::front::map as hir_map;
52 use rustc::session::Session;
54 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
55 use rustc::middle::def::*;
56 use rustc::middle::def_id::DefId;
57 use rustc::middle::pat_util::pat_bindings;
58 use rustc::middle::privacy::*;
59 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
60 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
61 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
64 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
65 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
66 use syntax::attr::AttrMetaMethods;
67 use syntax::codemap::{self, Span, Pos};
68 use syntax::errors::DiagnosticBuilder;
69 use syntax::parse::token::{self, special_names, special_idents};
70 use syntax::util::lev_distance::find_best_match_for_name;
72 use rustc_front::intravisit::{self, FnKind, Visitor};
74 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
75 use rustc_front::hir::Crate;
76 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
77 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
78 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
79 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
80 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
81 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
82 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
83 use rustc_front::hir::Local;
84 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
85 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
86 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
87 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
88 use rustc_front::util::walk_pat;
90 use std::collections::{HashMap, HashSet};
91 use std::cell::{Cell, RefCell};
93 use std::mem::replace;
96 use resolve_imports::{Target, ImportDirective, ImportResolutionPerNamespace};
97 use resolve_imports::Shadowable;
99 // NB: This module needs to be declared first so diagnostics are
100 // 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}`",
459 ExprMethodCall(ident, _, _) => {
460 help_msg = format!("To call a function from the \
461 `{module}` module, use \
462 `{module}::{ident}(..)`",
467 help_msg = format!("No function corresponds to `{module}(..)`",
470 _ => { } // no help available
473 help_msg = format!("Module `{module}` cannot be the value of an expression",
477 if !help_msg.is_empty() {
478 err.fileline_help(span, &help_msg);
484 ResolutionError::UndeclaredLabel(name) => {
485 struct_span_err!(resolver.session,
488 "use of undeclared label `{}`",
491 ResolutionError::CannotUseRefBindingModeWith(descr) => {
492 struct_span_err!(resolver.session,
495 "cannot use `ref` binding mode with {}",
498 ResolutionError::DuplicateDefinition(namespace, name) => {
499 struct_span_err!(resolver.session,
502 "duplicate definition of {} `{}`",
506 ResolutionError::SelfImportsOnlyAllowedWithin => {
507 struct_span_err!(resolver.session,
511 "`self` imports are only allowed within a { } list")
513 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
514 struct_span_err!(resolver.session,
517 "`self` import can only appear once in the list")
519 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
520 struct_span_err!(resolver.session,
523 "`self` import can only appear in an import list with a \
526 ResolutionError::UnresolvedImport(name) => {
527 let msg = match name {
528 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
529 None => "unresolved import".to_owned(),
531 struct_span_err!(resolver.session, span, E0432, "{}", msg)
533 ResolutionError::FailedToResolve(msg) => {
534 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
536 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
537 struct_span_err!(resolver.session,
541 "can't capture dynamic environment in a fn item; use the || { ... } \
542 closure form instead")
544 ResolutionError::AttemptToUseNonConstantValueInConstant => {
545 struct_span_err!(resolver.session,
548 "attempt to use a non-constant value in a constant")
553 #[derive(Copy, Clone)]
556 binding_mode: BindingMode,
559 // Map from the name in a pattern to its binding mode.
560 type BindingMap = HashMap<Name, BindingInfo>;
562 #[derive(Copy, Clone, PartialEq)]
563 enum PatternBindingMode {
565 LocalIrrefutableMode,
566 ArgumentIrrefutableMode,
569 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
575 /// A NamespaceResult represents the result of resolving an import in
576 /// a particular namespace. The result is either definitely-resolved,
577 /// definitely- unresolved, or unknown.
579 enum NamespaceResult<'a> {
580 /// Means that resolve hasn't gathered enough information yet to determine
581 /// whether the name is bound in this namespace. (That is, it hasn't
582 /// resolved all `use` directives yet.)
584 /// Means that resolve has determined that the name is definitely
585 /// not bound in the namespace.
587 /// Means that resolve has determined that the name is bound in the Module
588 /// argument, and specified by the NameBinding argument.
589 BoundResult(Module<'a>, NameBinding<'a>),
592 impl<'a> NamespaceResult<'a> {
593 fn is_unknown(&self) -> bool {
595 UnknownResult => true,
599 fn is_unbound(&self) -> bool {
601 UnboundResult => true,
607 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
608 fn visit_nested_item(&mut self, item: hir::ItemId) {
609 self.visit_item(self.ast_map.expect_item(item.id))
611 fn visit_item(&mut self, item: &Item) {
612 execute_callback!(hir_map::Node::NodeItem(item), self);
613 self.resolve_item(item);
615 fn visit_arm(&mut self, arm: &Arm) {
616 self.resolve_arm(arm);
618 fn visit_block(&mut self, block: &Block) {
619 execute_callback!(hir_map::Node::NodeBlock(block), self);
620 self.resolve_block(block);
622 fn visit_expr(&mut self, expr: &Expr) {
623 execute_callback!(hir_map::Node::NodeExpr(expr), self);
624 self.resolve_expr(expr);
626 fn visit_local(&mut self, local: &Local) {
627 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
628 self.resolve_local(local);
630 fn visit_ty(&mut self, ty: &Ty) {
631 self.resolve_type(ty);
633 fn visit_generics(&mut self, generics: &Generics) {
634 self.resolve_generics(generics);
636 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
637 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
638 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
640 // error already reported
641 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
644 intravisit::walk_poly_trait_ref(self, tref, m);
646 fn visit_variant(&mut self,
647 variant: &hir::Variant,
649 item_id: ast::NodeId) {
650 execute_callback!(hir_map::Node::NodeVariant(variant), self);
651 if let Some(ref dis_expr) = variant.node.disr_expr {
652 // resolve the discriminator expr as a constant
653 self.with_constant_rib(|this| {
654 this.visit_expr(dis_expr);
658 // `intravisit::walk_variant` without the discriminant expression.
659 self.visit_variant_data(&variant.node.data,
665 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
666 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
667 let type_parameters = match foreign_item.node {
668 ForeignItemFn(_, ref generics) => {
669 HasTypeParameters(generics, FnSpace, ItemRibKind)
671 ForeignItemStatic(..) => NoTypeParameters,
673 self.with_type_parameter_rib(type_parameters, |this| {
674 intravisit::walk_foreign_item(this, foreign_item);
677 fn visit_fn(&mut self,
678 function_kind: FnKind<'v>,
679 declaration: &'v FnDecl,
683 let rib_kind = match function_kind {
684 FnKind::ItemFn(_, generics, _, _, _, _) => {
685 self.visit_generics(generics);
688 FnKind::Method(_, sig, _) => {
689 self.visit_generics(&sig.generics);
690 self.visit_explicit_self(&sig.explicit_self);
693 FnKind::Closure => ClosureRibKind(node_id),
695 self.resolve_function(rib_kind, declaration, block);
699 type ErrorMessage = Option<(Span, String)>;
701 enum ResolveResult<T> {
702 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
703 Indeterminate, // Couldn't determine due to unresolved globs.
704 Success(T), // Successfully resolved the import.
707 impl<T> ResolveResult<T> {
708 fn success(&self) -> bool {
716 enum FallbackSuggestion {
721 StaticMethod(String),
725 #[derive(Copy, Clone)]
726 enum TypeParameters<'a> {
728 HasTypeParameters(// Type parameters.
731 // Identifies the things that these parameters
732 // were declared on (type, fn, etc)
735 // The kind of the rib used for type parameters.
739 // The rib kind controls the translation of local
740 // definitions (`DefLocal`) to upvars (`DefUpvar`).
741 #[derive(Copy, Clone, Debug)]
743 // No translation needs to be applied.
746 // We passed through a closure scope at the given node ID.
747 // Translate upvars as appropriate.
748 ClosureRibKind(NodeId /* func id */),
750 // We passed through an impl or trait and are now in one of its
751 // methods. Allow references to ty params that impl or trait
752 // binds. Disallow any other upvars (including other ty params that are
756 // We passed through an item scope. Disallow upvars.
759 // We're in a constant item. Can't refer to dynamic stuff.
763 #[derive(Copy, Clone)]
764 enum UseLexicalScopeFlag {
769 enum ModulePrefixResult<'a> {
771 PrefixFound(Module<'a>, usize),
774 #[derive(Copy, Clone)]
775 enum AssocItemResolveResult {
776 /// Syntax such as `<T>::item`, which can't be resolved until type
779 /// We should have been able to resolve the associated item.
780 ResolveAttempt(Option<PathResolution>),
783 #[derive(Copy, Clone, PartialEq)]
784 enum NameSearchType {
785 /// We're doing a name search in order to resolve a `use` directive.
788 /// We're doing a name search in order to resolve a path type, a path
789 /// expression, or a path pattern.
793 #[derive(Copy, Clone)]
794 enum BareIdentifierPatternResolution {
795 FoundStructOrEnumVariant(Def, LastPrivate),
796 FoundConst(Def, LastPrivate, Name),
797 BareIdentifierPatternUnresolved,
803 bindings: HashMap<Name, DefLike>,
808 fn new(kind: RibKind) -> Rib {
810 bindings: HashMap::new(),
816 /// A definition along with the index of the rib it was found on
818 ribs: Option<(Namespace, usize)>,
823 fn from_def(def: Def) -> Self {
831 /// The link from a module up to its nearest parent node.
832 #[derive(Clone,Debug)]
833 enum ParentLink<'a> {
835 ModuleParentLink(Module<'a>, Name),
836 BlockParentLink(Module<'a>, NodeId),
839 /// One node in the tree of modules.
840 pub struct ModuleS<'a> {
841 parent_link: ParentLink<'a>,
842 def: Cell<Option<Def>>,
845 children: RefCell<HashMap<Name, NameBindings<'a>>>,
846 imports: RefCell<Vec<ImportDirective>>,
848 // The external module children of this node that were declared with
850 external_module_children: RefCell<HashMap<Name, Module<'a>>>,
852 // The anonymous children of this node. Anonymous children are pseudo-
853 // modules that are implicitly created around items contained within
856 // For example, if we have this:
864 // There will be an anonymous module created around `g` with the ID of the
865 // entry block for `f`.
866 anonymous_children: RefCell<NodeMap<Module<'a>>>,
868 // The status of resolving each import in this module.
869 import_resolutions: RefCell<HashMap<Name, ImportResolutionPerNamespace<'a>>>,
871 // The number of unresolved globs that this module exports.
872 glob_count: Cell<usize>,
874 // The number of unresolved pub imports (both regular and globs) in this module
875 pub_count: Cell<usize>,
877 // The number of unresolved pub glob imports in this module
878 pub_glob_count: Cell<usize>,
880 // The index of the import we're resolving.
881 resolved_import_count: Cell<usize>,
883 // Whether this module is populated. If not populated, any attempt to
884 // access the children must be preceded with a
885 // `populate_module_if_necessary` call.
886 populated: Cell<bool>,
889 pub type Module<'a> = &'a ModuleS<'a>;
891 impl<'a> ModuleS<'a> {
892 fn new(parent_link: ParentLink<'a>, def: Option<Def>, external: bool, is_public: bool) -> Self {
894 parent_link: parent_link,
896 is_public: is_public,
897 children: RefCell::new(HashMap::new()),
898 imports: RefCell::new(Vec::new()),
899 external_module_children: RefCell::new(HashMap::new()),
900 anonymous_children: RefCell::new(NodeMap()),
901 import_resolutions: RefCell::new(HashMap::new()),
902 glob_count: Cell::new(0),
903 pub_count: Cell::new(0),
904 pub_glob_count: Cell::new(0),
905 resolved_import_count: Cell::new(0),
906 populated: Cell::new(!external),
910 fn def_id(&self) -> Option<DefId> {
911 self.def.get().as_ref().map(Def::def_id)
914 fn is_normal(&self) -> bool {
915 match self.def.get() {
916 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
921 fn is_trait(&self) -> bool {
922 match self.def.get() {
923 Some(DefTrait(_)) => true,
928 fn all_imports_resolved(&self) -> bool {
929 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
930 // it is currently being resolved ! so nope
933 self.imports.borrow().len() == self.resolved_import_count.get()
937 pub fn inc_glob_count(&self) {
938 self.glob_count.set(self.glob_count.get() + 1);
940 pub fn dec_glob_count(&self) {
941 assert!(self.glob_count.get() > 0);
942 self.glob_count.set(self.glob_count.get() - 1);
944 pub fn inc_pub_count(&self) {
945 self.pub_count.set(self.pub_count.get() + 1);
947 pub fn dec_pub_count(&self) {
948 assert!(self.pub_count.get() > 0);
949 self.pub_count.set(self.pub_count.get() - 1);
951 pub fn inc_pub_glob_count(&self) {
952 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
954 pub fn dec_pub_glob_count(&self) {
955 assert!(self.pub_glob_count.get() > 0);
956 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
960 impl<'a> fmt::Debug for ModuleS<'a> {
961 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
975 flags DefModifiers: u8 {
976 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
977 // or `use Enum::*` to work on private enums.
978 const PUBLIC = 1 << 0,
979 const IMPORTABLE = 1 << 1,
980 // Variants are considered `PUBLIC`, but some of them live in private enums.
981 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
982 const PRIVATE_VARIANT = 1 << 2,
986 // Records a possibly-private value, type, or module definition.
989 modifiers: DefModifiers, // see note in ImportResolutionPerNamespace about how to use this
990 def_or_module: DefOrModule<'a>,
995 enum DefOrModule<'a> {
1000 impl<'a> NsDef<'a> {
1001 fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
1002 let modifiers = if module.is_public {
1003 DefModifiers::PUBLIC
1005 DefModifiers::empty()
1006 } | DefModifiers::IMPORTABLE;
1008 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
1011 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
1012 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
1015 fn module(&self) -> Option<Module<'a>> {
1016 match self.def_or_module {
1017 DefOrModule::Module(ref module) => Some(module),
1018 DefOrModule::Def(_) => None,
1022 fn def(&self) -> Option<Def> {
1023 match self.def_or_module {
1024 DefOrModule::Def(def) => Some(def),
1025 DefOrModule::Module(ref module) => module.def.get(),
1030 // Records at most one definition that a name in a namespace is bound to
1031 #[derive(Clone,Debug)]
1032 pub struct NameBinding<'a>(Rc<RefCell<Option<NsDef<'a>>>>);
1034 impl<'a> NameBinding<'a> {
1036 NameBinding(Rc::new(RefCell::new(None)))
1039 fn create_from_module(module: Module<'a>) -> Self {
1040 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
1043 fn set(&self, ns_def: NsDef<'a>) {
1044 *self.0.borrow_mut() = Some(ns_def);
1047 fn set_modifiers(&self, modifiers: DefModifiers) {
1048 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
1049 ns_def.modifiers = modifiers
1053 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef<'a>>> {
1057 // Lifted versions of the NsDef methods and fields
1058 fn def(&self) -> Option<Def> {
1059 self.borrow().as_ref().and_then(NsDef::def)
1061 fn module(&self) -> Option<Module<'a>> {
1062 self.borrow().as_ref().and_then(NsDef::module)
1064 fn span(&self) -> Option<Span> {
1065 self.borrow().as_ref().and_then(|def| def.span)
1067 fn modifiers(&self) -> Option<DefModifiers> {
1068 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
1071 fn defined(&self) -> bool {
1072 self.borrow().is_some()
1075 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1076 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1079 fn is_public(&self) -> bool {
1080 self.defined_with(DefModifiers::PUBLIC)
1083 fn def_and_lp(&self) -> (Def, LastPrivate) {
1084 let def = self.def().unwrap();
1085 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1089 // Records the definitions (at most one for each namespace) that a name is
1091 #[derive(Clone,Debug)]
1092 pub struct NameBindings<'a> {
1093 type_ns: NameBinding<'a>, // < Meaning in type namespace.
1094 value_ns: NameBinding<'a>, // < Meaning in value namespace.
1097 impl<'a> ::std::ops::Index<Namespace> for NameBindings<'a> {
1098 type Output = NameBinding<'a>;
1099 fn index(&self, namespace: Namespace) -> &NameBinding<'a> {
1100 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1104 impl<'a> NameBindings<'a> {
1107 type_ns: NameBinding::new(),
1108 value_ns: NameBinding::new(),
1112 /// Creates a new module in this set of name bindings.
1113 fn define_module(&self, module: Module<'a>, sp: Span) {
1114 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1117 /// Records a type definition.
1118 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1119 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1120 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1123 /// Records a value definition.
1124 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1125 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1126 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1130 /// Interns the names of the primitive types.
1131 struct PrimitiveTypeTable {
1132 primitive_types: HashMap<Name, PrimTy>,
1135 impl PrimitiveTypeTable {
1136 fn new() -> PrimitiveTypeTable {
1137 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1139 table.intern("bool", TyBool);
1140 table.intern("char", TyChar);
1141 table.intern("f32", TyFloat(TyF32));
1142 table.intern("f64", TyFloat(TyF64));
1143 table.intern("isize", TyInt(TyIs));
1144 table.intern("i8", TyInt(TyI8));
1145 table.intern("i16", TyInt(TyI16));
1146 table.intern("i32", TyInt(TyI32));
1147 table.intern("i64", TyInt(TyI64));
1148 table.intern("str", TyStr);
1149 table.intern("usize", TyUint(TyUs));
1150 table.intern("u8", TyUint(TyU8));
1151 table.intern("u16", TyUint(TyU16));
1152 table.intern("u32", TyUint(TyU32));
1153 table.intern("u64", TyUint(TyU64));
1158 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1159 self.primitive_types.insert(token::intern(string), primitive_type);
1163 /// The main resolver class.
1164 pub struct Resolver<'a, 'tcx: 'a> {
1165 session: &'a Session,
1167 ast_map: &'a hir_map::Map<'tcx>,
1169 graph_root: Module<'a>,
1171 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1173 structs: FnvHashMap<DefId, Vec<Name>>,
1175 // The number of imports that are currently unresolved.
1176 unresolved_imports: usize,
1178 // The module that represents the current item scope.
1179 current_module: Module<'a>,
1181 // The current set of local scopes, for values.
1182 // FIXME #4948: Reuse ribs to avoid allocation.
1183 value_ribs: Vec<Rib>,
1185 // The current set of local scopes, for types.
1186 type_ribs: Vec<Rib>,
1188 // The current set of local scopes, for labels.
1189 label_ribs: Vec<Rib>,
1191 // The trait that the current context can refer to.
1192 current_trait_ref: Option<(DefId, TraitRef)>,
1194 // The current self type if inside an impl (used for better errors).
1195 current_self_type: Option<Ty>,
1197 // The idents for the primitive types.
1198 primitive_type_table: PrimitiveTypeTable,
1200 def_map: RefCell<DefMap>,
1201 freevars: FreevarMap,
1202 freevars_seen: NodeMap<NodeMap<usize>>,
1203 export_map: ExportMap,
1204 trait_map: TraitMap,
1205 external_exports: ExternalExports,
1207 // Whether or not to print error messages. Can be set to true
1208 // when getting additional info for error message suggestions,
1209 // so as to avoid printing duplicate errors
1212 make_glob_map: bool,
1213 // Maps imports to the names of items actually imported (this actually maps
1214 // all imports, but only glob imports are actually interesting).
1217 used_imports: HashSet<(NodeId, Namespace)>,
1218 used_crates: HashSet<CrateNum>,
1220 // Callback function for intercepting walks
1221 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1222 // The intention is that the callback modifies this flag.
1223 // Once set, the resolver falls out of the walk, preserving the ribs.
1226 arenas: &'a ResolverArenas<'a>,
1229 pub struct ResolverArenas<'a> {
1230 modules: arena::TypedArena<ModuleS<'a>>,
1233 #[derive(PartialEq)]
1234 enum FallbackChecks {
1236 OnlyTraitAndStatics,
1239 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1240 fn new(session: &'a Session,
1241 ast_map: &'a hir_map::Map<'tcx>,
1242 make_glob_map: MakeGlobMap,
1243 arenas: &'a ResolverArenas<'a>)
1244 -> Resolver<'a, 'tcx> {
1245 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1246 let graph_root = ModuleS::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1247 let graph_root = arenas.modules.alloc(graph_root);
1254 // The outermost module has def ID 0; this is not reflected in the
1256 graph_root: graph_root,
1258 trait_item_map: FnvHashMap(),
1259 structs: FnvHashMap(),
1261 unresolved_imports: 0,
1263 current_module: graph_root,
1264 value_ribs: Vec::new(),
1265 type_ribs: Vec::new(),
1266 label_ribs: Vec::new(),
1268 current_trait_ref: None,
1269 current_self_type: None,
1271 primitive_type_table: PrimitiveTypeTable::new(),
1273 def_map: RefCell::new(NodeMap()),
1274 freevars: NodeMap(),
1275 freevars_seen: NodeMap(),
1276 export_map: NodeMap(),
1277 trait_map: NodeMap(),
1278 used_imports: HashSet::new(),
1279 used_crates: HashSet::new(),
1280 external_exports: DefIdSet(),
1283 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1284 glob_map: HashMap::new(),
1293 fn arenas() -> ResolverArenas<'a> {
1295 modules: arena::TypedArena::new(),
1299 fn new_module(&self,
1300 parent_link: ParentLink<'a>,
1303 is_public: bool) -> Module<'a> {
1304 self.arenas.modules.alloc(ModuleS::new(parent_link, def, external, is_public))
1308 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1309 if !self.make_glob_map {
1312 if self.glob_map.contains_key(&import_id) {
1313 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1317 let mut new_set = HashSet::new();
1318 new_set.insert(name);
1319 self.glob_map.insert(import_id, new_set);
1322 fn get_trait_name(&self, did: DefId) -> Name {
1323 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1324 self.ast_map.expect_item(node_id).name
1326 self.session.cstore.item_name(did)
1330 /// Check that an external crate doesn't collide with items or other external crates.
1331 fn check_for_conflicts_for_external_crate(&self, module: Module<'a>, name: Name, span: Span) {
1332 if module.external_module_children.borrow().contains_key(&name) {
1333 span_err!(self.session,
1336 "an external crate named `{}` has already been imported into this module",
1339 match module.children.borrow().get(&name) {
1340 Some(name_bindings) if name_bindings.type_ns.defined() => {
1342 name_bindings.type_ns.span().unwrap_or(codemap::DUMMY_SP),
1343 ResolutionError::NameConflictsWithExternCrate(name));
1349 /// Checks that the names of items don't collide with external crates.
1350 fn check_for_conflicts_between_external_crates_and_items(&self,
1354 if module.external_module_children.borrow().contains_key(&name) {
1355 resolve_error(self, span, ResolutionError::NameConflictsWithExternCrate(name));
1359 /// Resolves the given module path from the given root `module_`.
1360 fn resolve_module_path_from_root(&mut self,
1361 module_: Module<'a>,
1362 module_path: &[Name],
1365 name_search_type: NameSearchType,
1367 -> ResolveResult<(Module<'a>, LastPrivate)> {
1368 fn search_parent_externals<'a>(needle: Name, module: Module<'a>)
1369 -> Option<Module<'a>> {
1370 match module.external_module_children.borrow().get(&needle) {
1371 Some(_) => Some(module),
1372 None => match module.parent_link {
1373 ModuleParentLink(ref parent, _) => {
1374 search_parent_externals(needle, parent)
1381 let mut search_module = module_;
1382 let mut index = index;
1383 let module_path_len = module_path.len();
1384 let mut closest_private = lp;
1386 // Resolve the module part of the path. This does not involve looking
1387 // upward though scope chains; we simply resolve names directly in
1388 // modules as we go.
1389 while index < module_path_len {
1390 let name = module_path[index];
1391 match self.resolve_name_in_module(search_module,
1397 let segment_name = name.as_str();
1398 let module_name = module_to_string(search_module);
1399 let mut span = span;
1400 let msg = if "???" == &module_name[..] {
1401 span.hi = span.lo + Pos::from_usize(segment_name.len());
1403 match search_parent_externals(name, &self.current_module) {
1405 let path_str = names_to_string(module_path);
1406 let target_mod_str = module_to_string(&*module);
1407 let current_mod_str = module_to_string(&*self.current_module);
1409 let prefix = if target_mod_str == current_mod_str {
1410 "self::".to_string()
1412 format!("{}::", target_mod_str)
1415 format!("Did you mean `{}{}`?", prefix, path_str)
1417 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1420 format!("Could not find `{}` in `{}`", segment_name, module_name)
1423 return Failed(Some((span, msg)));
1425 Failed(err) => return Failed(err),
1427 debug!("(resolving module path for import) module resolution is \
1430 return Indeterminate;
1432 Success((target, used_proxy)) => {
1433 // Check to see whether there are type bindings, and, if
1434 // so, whether there is a module within.
1435 if let Some(module_def) = target.binding.module() {
1436 // track extern crates for unused_extern_crate lint
1437 if let Some(did) = module_def.def_id() {
1438 self.used_crates.insert(did.krate);
1441 search_module = module_def;
1443 // Keep track of the closest private module used
1444 // when resolving this import chain.
1445 if !used_proxy && !search_module.is_public {
1446 if let Some(did) = search_module.def_id() {
1447 closest_private = LastMod(DependsOn(did));
1451 let msg = format!("Not a module `{}`", name);
1452 return Failed(Some((span, msg)));
1460 return Success((search_module, closest_private));
1463 /// Attempts to resolve the module part of an import directive or path
1464 /// rooted at the given module.
1466 /// On success, returns the resolved module, and the closest *private*
1467 /// module found to the destination when resolving this path.
1468 fn resolve_module_path(&mut self,
1469 module_: Module<'a>,
1470 module_path: &[Name],
1471 use_lexical_scope: UseLexicalScopeFlag,
1473 name_search_type: NameSearchType)
1474 -> ResolveResult<(Module<'a>, LastPrivate)> {
1475 let module_path_len = module_path.len();
1476 assert!(module_path_len > 0);
1478 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1479 names_to_string(module_path),
1480 module_to_string(&*module_));
1482 // Resolve the module prefix, if any.
1483 let module_prefix_result = self.resolve_module_prefix(module_, module_path);
1488 match module_prefix_result {
1490 let mpath = names_to_string(module_path);
1491 let mpath = &mpath[..];
1492 match mpath.rfind(':') {
1494 let msg = format!("Could not find `{}` in `{}`",
1495 // idx +- 1 to account for the
1496 // colons on either side
1499 return Failed(Some((span, msg)));
1502 return Failed(None);
1506 Failed(err) => return Failed(err),
1508 debug!("(resolving module path for import) indeterminate; bailing");
1509 return Indeterminate;
1511 Success(NoPrefixFound) => {
1512 // There was no prefix, so we're considering the first element
1513 // of the path. How we handle this depends on whether we were
1514 // instructed to use lexical scope or not.
1515 match use_lexical_scope {
1516 DontUseLexicalScope => {
1517 // This is a crate-relative path. We will start the
1518 // resolution process at index zero.
1519 search_module = self.graph_root;
1521 last_private = LastMod(AllPublic);
1523 UseLexicalScope => {
1524 // This is not a crate-relative path. We resolve the
1525 // first component of the path in the current lexical
1526 // scope and then proceed to resolve below that.
1527 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1528 Failed(err) => return Failed(err),
1530 debug!("(resolving module path for import) indeterminate; bailing");
1531 return Indeterminate;
1533 Success(containing_module) => {
1534 search_module = containing_module;
1536 last_private = LastMod(AllPublic);
1542 Success(PrefixFound(ref containing_module, index)) => {
1543 search_module = containing_module;
1544 start_index = index;
1545 last_private = LastMod(DependsOn(containing_module.def_id()
1550 self.resolve_module_path_from_root(search_module,
1558 /// Invariant: This must only be called during main resolution, not during
1559 /// import resolution.
1560 fn resolve_item_in_lexical_scope(&mut self,
1561 module_: Module<'a>,
1563 namespace: Namespace,
1565 -> ResolveResult<(Target<'a>, bool)> {
1566 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1569 module_to_string(&*module_));
1571 // The current module node is handled specially. First, check for
1572 // its immediate children.
1573 build_reduced_graph::populate_module_if_necessary(self, &module_);
1575 match module_.children.borrow().get(&name) {
1576 Some(name_bindings) if name_bindings[namespace].defined() => {
1577 debug!("top name bindings succeeded");
1578 return Success((Target::new(module_,
1579 name_bindings[namespace].clone(),
1584 // Not found; continue.
1588 // Now check for its import directives. We don't have to have resolved
1589 // all its imports in the usual way; this is because chains of
1590 // adjacent import statements are processed as though they mutated the
1592 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1593 match import_resolution[namespace].target.clone() {
1595 // Not found; continue.
1596 debug!("(resolving item in lexical scope) found import resolution, but not \
1601 debug!("(resolving item in lexical scope) using import resolution");
1602 // track used imports and extern crates as well
1603 let id = import_resolution[namespace].id;
1605 self.used_imports.insert((id, namespace));
1606 self.record_import_use(id, name);
1607 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1608 self.used_crates.insert(kid);
1611 return Success((target, false));
1616 // Search for external modules.
1617 if namespace == TypeNS {
1618 let children = module_.external_module_children.borrow();
1619 if let Some(module) = children.get(&name) {
1620 let name_binding = NameBinding::create_from_module(module);
1621 debug!("lower name bindings succeeded");
1622 return Success((Target::new(module_, name_binding, Shadowable::Never),
1627 // Finally, proceed up the scope chain looking for parent modules.
1628 let mut search_module = module_;
1630 // Go to the next parent.
1631 match search_module.parent_link {
1633 // No more parents. This module was unresolved.
1634 debug!("(resolving item in lexical scope) unresolved module");
1635 return Failed(None);
1637 ModuleParentLink(parent_module_node, _) => {
1638 if search_module.is_normal() {
1639 // We stop the search here.
1640 debug!("(resolving item in lexical scope) unresolved module: not \
1641 searching through module parents");
1642 return Failed(None);
1644 search_module = parent_module_node;
1647 BlockParentLink(parent_module_node, _) => {
1648 search_module = parent_module_node;
1652 // Resolve the name in the parent module.
1653 match self.resolve_name_in_module(search_module,
1658 Failed(Some((span, msg))) => {
1659 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1661 Failed(None) => (), // Continue up the search chain.
1663 // We couldn't see through the higher scope because of an
1664 // unresolved import higher up. Bail.
1666 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1667 return Indeterminate;
1669 Success((target, used_reexport)) => {
1670 // We found the module.
1671 debug!("(resolving item in lexical scope) found name in module, done");
1672 return Success((target, used_reexport));
1678 /// Resolves a module name in the current lexical scope.
1679 fn resolve_module_in_lexical_scope(&mut self,
1680 module_: Module<'a>,
1682 -> ResolveResult<Module<'a>> {
1683 // If this module is an anonymous module, resolve the item in the
1684 // lexical scope. Otherwise, resolve the item from the crate root.
1685 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS, true);
1686 match resolve_result {
1687 Success((target, _)) => {
1688 if let Some(module_def) = target.binding.module() {
1689 return Success(module_def)
1691 debug!("!!! (resolving module in lexical scope) module \
1692 wasn't actually a module!");
1693 return Failed(None);
1697 debug!("(resolving module in lexical scope) indeterminate; bailing");
1698 return Indeterminate;
1701 debug!("(resolving module in lexical scope) failed to resolve");
1707 /// Returns the nearest normal module parent of the given module.
1708 fn get_nearest_normal_module_parent(&mut self, module_: Module<'a>) -> Option<Module<'a>> {
1709 let mut module_ = module_;
1711 match module_.parent_link {
1712 NoParentLink => return None,
1713 ModuleParentLink(new_module, _) |
1714 BlockParentLink(new_module, _) => {
1715 let new_module = new_module;
1716 if new_module.is_normal() {
1717 return Some(new_module);
1719 module_ = new_module;
1725 /// Returns the nearest normal module parent of the given module, or the
1726 /// module itself if it is a normal module.
1727 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Module<'a>) -> Module<'a> {
1728 if module_.is_normal() {
1731 match self.get_nearest_normal_module_parent(module_) {
1733 Some(new_module) => new_module,
1737 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1738 /// (b) some chain of `super::`.
1739 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1740 fn resolve_module_prefix(&mut self,
1741 module_: Module<'a>,
1742 module_path: &[Name])
1743 -> ResolveResult<ModulePrefixResult<'a>> {
1744 // Start at the current module if we see `self` or `super`, or at the
1745 // top of the crate otherwise.
1746 let mut i = match &*module_path[0].as_str() {
1749 _ => return Success(NoPrefixFound),
1751 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1753 // Now loop through all the `super`s we find.
1754 while i < module_path.len() && "super" == module_path[i].as_str() {
1755 debug!("(resolving module prefix) resolving `super` at {}",
1756 module_to_string(&*containing_module));
1757 match self.get_nearest_normal_module_parent(containing_module) {
1758 None => return Failed(None),
1759 Some(new_module) => {
1760 containing_module = new_module;
1766 debug!("(resolving module prefix) finished resolving prefix at {}",
1767 module_to_string(&*containing_module));
1769 return Success(PrefixFound(containing_module, i));
1772 /// Attempts to resolve the supplied name in the given module for the
1773 /// given namespace. If successful, returns the target corresponding to
1776 /// The boolean returned on success is an indicator of whether this lookup
1777 /// passed through a public re-export proxy.
1778 fn resolve_name_in_module(&mut self,
1779 module_: Module<'a>,
1781 namespace: Namespace,
1782 name_search_type: NameSearchType,
1783 allow_private_imports: bool)
1784 -> ResolveResult<(Target<'a>, bool)> {
1785 debug!("(resolving name in module) resolving `{}` in `{}`",
1787 module_to_string(&*module_));
1789 // First, check the direct children of the module.
1790 build_reduced_graph::populate_module_if_necessary(self, &module_);
1792 let children = module_.children.borrow();
1793 match children.get(&name) {
1794 Some(name_bindings) if name_bindings[namespace].defined() => {
1795 debug!("(resolving name in module) found node as child");
1796 return Success((Target::new(module_,
1797 name_bindings[namespace].clone(),
1806 // Next, check the module's imports if necessary.
1808 // If this is a search of all imports, we should be done with glob
1809 // resolution at this point.
1810 if name_search_type == PathSearch {
1811 assert_eq!(module_.glob_count.get(), 0);
1814 // Check the list of resolved imports.
1815 let children = module_.import_resolutions.borrow();
1816 match children.get(&name) {
1817 Some(import_resolution) if allow_private_imports ||
1818 import_resolution[namespace].is_public => {
1820 if import_resolution[namespace].is_public &&
1821 import_resolution.outstanding_references != 0 {
1822 debug!("(resolving name in module) import unresolved; bailing out");
1823 return Indeterminate;
1825 match import_resolution[namespace].target.clone() {
1827 debug!("(resolving name in module) name found, but not in namespace {:?}",
1831 debug!("(resolving name in module) resolved to import");
1832 // track used imports and extern crates as well
1833 let id = import_resolution[namespace].id;
1834 self.used_imports.insert((id, namespace));
1835 self.record_import_use(id, name);
1836 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1837 self.used_crates.insert(kid);
1839 return Success((target, true));
1843 Some(..) | None => {} // Continue.
1846 // Finally, search through external children.
1847 if namespace == TypeNS {
1848 let children = module_.external_module_children.borrow();
1849 if let Some(module) = children.get(&name) {
1850 let name_binding = NameBinding::create_from_module(module);
1851 return Success((Target::new(module_, name_binding, Shadowable::Never),
1856 // We're out of luck.
1857 debug!("(resolving name in module) failed to resolve `{}`", name);
1858 return Failed(None);
1861 fn report_unresolved_imports(&mut self, module_: Module<'a>) {
1862 let index = module_.resolved_import_count.get();
1863 let imports = module_.imports.borrow();
1864 let import_count = imports.len();
1865 if index != import_count {
1867 (*imports)[index].span,
1868 ResolutionError::UnresolvedImport(None));
1871 // Descend into children and anonymous children.
1872 build_reduced_graph::populate_module_if_necessary(self, &module_);
1874 for (_, child_node) in module_.children.borrow().iter() {
1875 match child_node.type_ns.module() {
1879 Some(child_module) => {
1880 self.report_unresolved_imports(child_module);
1885 for (_, module_) in module_.anonymous_children.borrow().iter() {
1886 self.report_unresolved_imports(module_);
1892 // We maintain a list of value ribs and type ribs.
1894 // Simultaneously, we keep track of the current position in the module
1895 // graph in the `current_module` pointer. When we go to resolve a name in
1896 // the value or type namespaces, we first look through all the ribs and
1897 // then query the module graph. When we resolve a name in the module
1898 // namespace, we can skip all the ribs (since nested modules are not
1899 // allowed within blocks in Rust) and jump straight to the current module
1902 // Named implementations are handled separately. When we find a method
1903 // call, we consult the module node to find all of the implementations in
1904 // scope. This information is lazily cached in the module node. We then
1905 // generate a fake "implementation scope" containing all the
1906 // implementations thus found, for compatibility with old resolve pass.
1908 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1909 where F: FnOnce(&mut Resolver)
1911 let orig_module = self.current_module;
1913 // Move down in the graph.
1919 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1921 match orig_module.children.borrow().get(&name) {
1923 debug!("!!! (with scope) didn't find `{}` in `{}`",
1925 module_to_string(&*orig_module));
1927 Some(name_bindings) => {
1928 match name_bindings.type_ns.module() {
1930 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1932 module_to_string(&*orig_module));
1935 self.current_module = module_;
1945 self.current_module = orig_module;
1948 /// Searches the current set of local scopes for labels.
1949 /// Stops after meeting a closure.
1950 fn search_label(&self, name: Name) -> Option<DefLike> {
1951 for rib in self.label_ribs.iter().rev() {
1957 // Do not resolve labels across function boundary
1961 let result = rib.bindings.get(&name).cloned();
1962 if result.is_some() {
1969 fn resolve_crate(&mut self, krate: &hir::Crate) {
1970 debug!("(resolving crate) starting");
1972 intravisit::walk_crate(self, krate);
1975 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1976 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1977 span_err!(self.session,
1980 "user-defined types or type parameters cannot shadow the primitive types");
1984 fn resolve_item(&mut self, item: &Item) {
1985 let name = item.name;
1987 debug!("(resolving item) resolving {}", name);
1990 ItemEnum(_, ref generics) |
1991 ItemTy(_, ref generics) |
1992 ItemStruct(_, ref generics) => {
1993 self.check_if_primitive_type_name(name, item.span);
1995 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1996 |this| intravisit::walk_item(this, item));
1998 ItemFn(_, _, _, _, ref generics, _) => {
1999 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
2000 |this| intravisit::walk_item(this, item));
2003 ItemDefaultImpl(_, ref trait_ref) => {
2004 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
2006 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
2007 self.resolve_implementation(generics,
2014 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2015 self.check_if_primitive_type_name(name, item.span);
2017 // Create a new rib for the trait-wide type parameters.
2018 self.with_type_parameter_rib(HasTypeParameters(generics,
2022 let local_def_id = this.ast_map.local_def_id(item.id);
2023 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
2024 this.visit_generics(generics);
2025 walk_list!(this, visit_ty_param_bound, bounds);
2027 for trait_item in trait_items {
2028 match trait_item.node {
2029 hir::ConstTraitItem(_, ref default) => {
2030 // Only impose the restrictions of
2031 // ConstRibKind if there's an actual constant
2032 // expression in a provided default.
2033 if default.is_some() {
2034 this.with_constant_rib(|this| {
2035 intravisit::walk_trait_item(this, trait_item)
2038 intravisit::walk_trait_item(this, trait_item)
2041 hir::MethodTraitItem(ref sig, _) => {
2042 let type_parameters =
2043 HasTypeParameters(&sig.generics,
2046 this.with_type_parameter_rib(type_parameters, |this| {
2047 intravisit::walk_trait_item(this, trait_item)
2050 hir::TypeTraitItem(..) => {
2051 this.check_if_primitive_type_name(trait_item.name,
2053 this.with_type_parameter_rib(NoTypeParameters, |this| {
2054 intravisit::walk_trait_item(this, trait_item)
2063 ItemMod(_) | ItemForeignMod(_) => {
2064 self.with_scope(Some(name), |this| {
2065 intravisit::walk_item(this, item);
2069 ItemConst(..) | ItemStatic(..) => {
2070 self.with_constant_rib(|this| {
2071 intravisit::walk_item(this, item);
2075 ItemUse(ref view_path) => {
2076 // check for imports shadowing primitive types
2077 let check_rename = |this: &Self, id, name| {
2078 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
2079 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2080 this.check_if_primitive_type_name(name, item.span);
2086 match view_path.node {
2087 hir::ViewPathSimple(name, _) => {
2088 check_rename(self, item.id, name);
2090 hir::ViewPathList(ref prefix, ref items) => {
2092 if let Some(name) = item.node.rename() {
2093 check_rename(self, item.node.id(), name);
2097 // Resolve prefix of an import with empty braces (issue #28388)
2098 if items.is_empty() && !prefix.segments.is_empty() {
2099 match self.resolve_crate_relative_path(prefix.span,
2103 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2107 ResolutionError::FailedToResolve(
2108 &path_names_to_string(prefix, 0)));
2109 self.record_def(item.id, err_path_resolution());
2118 ItemExternCrate(_) => {
2119 // do nothing, these are just around to be encoded
2124 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2125 where F: FnOnce(&mut Resolver)
2127 match type_parameters {
2128 HasTypeParameters(generics, space, rib_kind) => {
2129 let mut function_type_rib = Rib::new(rib_kind);
2130 let mut seen_bindings = HashSet::new();
2131 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2132 let name = type_parameter.name;
2133 debug!("with_type_parameter_rib: {}", type_parameter.id);
2135 if seen_bindings.contains(&name) {
2137 type_parameter.span,
2138 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2140 seen_bindings.insert(name);
2142 // plain insert (no renaming)
2143 function_type_rib.bindings
2145 DlDef(DefTyParam(space,
2148 .local_def_id(type_parameter.id),
2151 self.type_ribs.push(function_type_rib);
2154 NoTypeParameters => {
2161 match type_parameters {
2162 HasTypeParameters(..) => {
2164 self.type_ribs.pop();
2167 NoTypeParameters => {}
2171 fn with_label_rib<F>(&mut self, f: F)
2172 where F: FnOnce(&mut Resolver)
2174 self.label_ribs.push(Rib::new(NormalRibKind));
2177 self.label_ribs.pop();
2181 fn with_constant_rib<F>(&mut self, f: F)
2182 where F: FnOnce(&mut Resolver)
2184 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2185 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2188 self.type_ribs.pop();
2189 self.value_ribs.pop();
2193 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2194 // Create a value rib for the function.
2195 self.value_ribs.push(Rib::new(rib_kind));
2197 // Create a label rib for the function.
2198 self.label_ribs.push(Rib::new(rib_kind));
2200 // Add each argument to the rib.
2201 let mut bindings_list = HashMap::new();
2202 for argument in &declaration.inputs {
2203 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2205 self.visit_ty(&*argument.ty);
2207 debug!("(resolving function) recorded argument");
2209 intravisit::walk_fn_ret_ty(self, &declaration.output);
2211 // Resolve the function body.
2212 self.visit_block(block);
2214 debug!("(resolving function) leaving function");
2217 self.label_ribs.pop();
2218 self.value_ribs.pop();
2222 fn resolve_trait_reference(&mut self,
2226 -> Result<PathResolution, ()> {
2227 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2228 if let DefTrait(_) = path_res.base_def {
2229 debug!("(resolving trait) found trait def: {:?}", path_res);
2233 resolve_struct_error(self,
2235 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2238 // If it's a typedef, give a note
2239 if let DefTy(..) = path_res.base_def {
2240 err.span_note(trait_path.span,
2241 "`type` aliases cannot be used for traits");
2249 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2255 fn resolve_generics(&mut self, generics: &Generics) {
2256 for type_parameter in generics.ty_params.iter() {
2257 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2259 for predicate in &generics.where_clause.predicates {
2261 &hir::WherePredicate::BoundPredicate(_) |
2262 &hir::WherePredicate::RegionPredicate(_) => {}
2263 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2264 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2265 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2266 self.record_def(eq_pred.id, path_res.unwrap());
2270 ResolutionError::UndeclaredAssociatedType);
2271 self.record_def(eq_pred.id, err_path_resolution());
2276 intravisit::walk_generics(self, generics);
2279 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2280 where F: FnOnce(&mut Resolver) -> T
2282 // Handle nested impls (inside fn bodies)
2283 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2284 let result = f(self);
2285 self.current_self_type = previous_value;
2289 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2290 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2292 let mut new_val = None;
2293 let mut new_id = None;
2294 if let Some(trait_ref) = opt_trait_ref {
2295 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2298 assert!(path_res.depth == 0);
2299 self.record_def(trait_ref.ref_id, path_res);
2300 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2301 new_id = Some(path_res.base_def.def_id());
2303 self.record_def(trait_ref.ref_id, err_path_resolution());
2305 intravisit::walk_trait_ref(self, trait_ref);
2307 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2308 let result = f(self, new_id);
2309 self.current_trait_ref = original_trait_ref;
2313 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2314 where F: FnOnce(&mut Resolver)
2316 let mut self_type_rib = Rib::new(NormalRibKind);
2318 // plain insert (no renaming, types are not currently hygienic....)
2319 let name = special_names::type_self;
2320 self_type_rib.bindings.insert(name, DlDef(self_def));
2321 self.type_ribs.push(self_type_rib);
2324 self.type_ribs.pop();
2328 fn resolve_implementation(&mut self,
2329 generics: &Generics,
2330 opt_trait_reference: &Option<TraitRef>,
2333 impl_items: &[ImplItem]) {
2334 // If applicable, create a rib for the type parameters.
2335 self.with_type_parameter_rib(HasTypeParameters(generics,
2339 // Resolve the type parameters.
2340 this.visit_generics(generics);
2342 // Resolve the trait reference, if necessary.
2343 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2344 // Resolve the self type.
2345 this.visit_ty(self_type);
2347 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2348 this.with_current_self_type(self_type, |this| {
2349 for impl_item in impl_items {
2350 match impl_item.node {
2351 hir::ImplItemKind::Const(..) => {
2352 // If this is a trait impl, ensure the const
2354 this.check_trait_item(impl_item.name,
2356 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2357 this.with_constant_rib(|this| {
2358 intravisit::walk_impl_item(this, impl_item);
2361 hir::ImplItemKind::Method(ref sig, _) => {
2362 // If this is a trait impl, ensure the method
2364 this.check_trait_item(impl_item.name,
2366 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2368 // We also need a new scope for the method-
2369 // specific type parameters.
2370 let type_parameters =
2371 HasTypeParameters(&sig.generics,
2374 this.with_type_parameter_rib(type_parameters, |this| {
2375 intravisit::walk_impl_item(this, impl_item);
2378 hir::ImplItemKind::Type(ref ty) => {
2379 // If this is a trait impl, ensure the type
2381 this.check_trait_item(impl_item.name,
2383 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2395 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2396 where F: FnOnce(Name, &str) -> ResolutionError
2398 // If there is a TraitRef in scope for an impl, then the method must be in the
2400 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2401 if !self.trait_item_map.contains_key(&(name, did)) {
2402 let path_str = path_names_to_string(&trait_ref.path, 0);
2403 resolve_error(self, span, err(name, &*path_str));
2408 fn resolve_local(&mut self, local: &Local) {
2409 // Resolve the type.
2410 walk_list!(self, visit_ty, &local.ty);
2412 // Resolve the initializer.
2413 walk_list!(self, visit_expr, &local.init);
2415 // Resolve the pattern.
2416 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2419 // build a map from pattern identifiers to binding-info's.
2420 // this is done hygienically. This could arise for a macro
2421 // that expands into an or-pattern where one 'x' was from the
2422 // user and one 'x' came from the macro.
2423 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2424 let mut result = HashMap::new();
2425 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2426 let name = path1.node;
2430 binding_mode: binding_mode,
2436 // check that all of the arms in an or-pattern have exactly the
2437 // same set of bindings, with the same binding modes for each.
2438 fn check_consistent_bindings(&mut self, arm: &Arm) {
2439 if arm.pats.is_empty() {
2442 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2443 for (i, p) in arm.pats.iter().enumerate() {
2444 let map_i = self.binding_mode_map(&**p);
2446 for (&key, &binding_0) in &map_0 {
2447 match map_i.get(&key) {
2451 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2453 Some(binding_i) => {
2454 if binding_0.binding_mode != binding_i.binding_mode {
2457 ResolutionError::VariableBoundWithDifferentMode(key,
2464 for (&key, &binding) in &map_i {
2465 if !map_0.contains_key(&key) {
2468 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2474 fn resolve_arm(&mut self, arm: &Arm) {
2475 self.value_ribs.push(Rib::new(NormalRibKind));
2477 let mut bindings_list = HashMap::new();
2478 for pattern in &arm.pats {
2479 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2482 // This has to happen *after* we determine which
2483 // pat_idents are variants
2484 self.check_consistent_bindings(arm);
2486 walk_list!(self, visit_expr, &arm.guard);
2487 self.visit_expr(&*arm.body);
2490 self.value_ribs.pop();
2494 fn resolve_block(&mut self, block: &Block) {
2495 debug!("(resolving block) entering block");
2496 self.value_ribs.push(Rib::new(NormalRibKind));
2498 // Move down in the graph, if there's an anonymous module rooted here.
2499 let orig_module = self.current_module;
2500 match orig_module.anonymous_children.borrow().get(&block.id) {
2504 Some(anonymous_module) => {
2505 debug!("(resolving block) found anonymous module, moving down");
2506 self.current_module = anonymous_module;
2510 // Check for imports appearing after non-item statements.
2511 let mut found_non_item = false;
2512 for statement in &block.stmts {
2513 if let hir::StmtDecl(ref declaration, _) = statement.node {
2514 if let hir::DeclItem(i) = declaration.node {
2515 let i = self.ast_map.expect_item(i.id);
2517 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2518 span_err!(self.session,
2521 "imports are not allowed after non-item statements");
2526 found_non_item = true
2529 found_non_item = true;
2533 // Descend into the block.
2534 intravisit::walk_block(self, block);
2538 self.current_module = orig_module;
2539 self.value_ribs.pop();
2541 debug!("(resolving block) leaving block");
2544 fn resolve_type(&mut self, ty: &Ty) {
2546 TyPath(ref maybe_qself, ref path) => {
2547 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2548 maybe_qself.as_ref(),
2552 // `<T>::a::b::c` is resolved by typeck alone.
2553 TypecheckRequired => {
2554 // Resolve embedded types.
2555 intravisit::walk_ty(self, ty);
2558 ResolveAttempt(resolution) => resolution,
2561 // This is a path in the type namespace. Walk through scopes
2565 // Write the result into the def map.
2566 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2567 path_names_to_string(path, 0),
2570 self.record_def(ty.id, def);
2573 self.record_def(ty.id, err_path_resolution());
2575 // Keep reporting some errors even if they're ignored above.
2576 self.resolve_path(ty.id, path, 0, TypeNS, true);
2578 let kind = if maybe_qself.is_some() {
2584 let self_type_name = special_idents::type_self.name;
2585 let is_invalid_self_type_name = path.segments.len() > 0 &&
2586 maybe_qself.is_none() &&
2587 path.segments[0].identifier.name ==
2589 if is_invalid_self_type_name {
2592 ResolutionError::SelfUsedOutsideImplOrTrait);
2596 ResolutionError::UseOfUndeclared(
2598 &*path_names_to_string(path,
2607 // Resolve embedded types.
2608 intravisit::walk_ty(self, ty);
2611 fn resolve_pattern(&mut self,
2613 mode: PatternBindingMode,
2614 // Maps idents to the node ID for the (outermost)
2615 // pattern that binds them
2616 bindings_list: &mut HashMap<Name, NodeId>) {
2617 let pat_id = pattern.id;
2618 walk_pat(pattern, |pattern| {
2619 match pattern.node {
2620 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2621 // The meaning of PatIdent with no type parameters
2622 // depends on whether an enum variant or unit-like struct
2623 // with that name is in scope. The probing lookup has to
2624 // be careful not to emit spurious errors. Only matching
2625 // patterns (match) can match nullary variants or
2626 // unit-like structs. For binding patterns (let
2627 // and the LHS of @-patterns), matching such a value is
2628 // simply disallowed (since it's rarely what you want).
2629 let const_ok = mode == RefutableMode && at_rhs.is_none();
2631 let ident = path1.node;
2632 let renamed = ident.name;
2634 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2636 FoundStructOrEnumVariant(def, lp) if const_ok => {
2637 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2640 self.enforce_default_binding_mode(pattern,
2643 self.record_def(pattern.id,
2650 FoundStructOrEnumVariant(..) => {
2654 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2657 self.record_def(pattern.id, err_path_resolution());
2659 FoundConst(def, lp, _) if const_ok => {
2660 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2662 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2663 self.record_def(pattern.id,
2670 FoundConst(def, _, name) => {
2674 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2677 self.record_def(pattern.id, err_path_resolution());
2679 BareIdentifierPatternUnresolved => {
2680 debug!("(resolving pattern) binding `{}`", renamed);
2682 let def_id = self.ast_map.local_def_id(pattern.id);
2683 let def = DefLocal(def_id, pattern.id);
2685 // Record the definition so that later passes
2686 // will be able to distinguish variants from
2687 // locals in patterns.
2689 self.record_def(pattern.id,
2692 last_private: LastMod(AllPublic),
2696 // Add the binding to the local ribs, if it
2697 // doesn't already exist in the bindings list. (We
2698 // must not add it if it's in the bindings list
2699 // because that breaks the assumptions later
2700 // passes make about or-patterns.)
2701 if !bindings_list.contains_key(&renamed) {
2702 let this = &mut *self;
2703 let last_rib = this.value_ribs.last_mut().unwrap();
2704 last_rib.bindings.insert(renamed, DlDef(def));
2705 bindings_list.insert(renamed, pat_id);
2706 } else if mode == ArgumentIrrefutableMode &&
2707 bindings_list.contains_key(&renamed) {
2708 // Forbid duplicate bindings in the same
2713 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2714 &ident.name.as_str())
2716 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2717 // Then this is a duplicate variable in the
2718 // same disjunction, which is an error.
2722 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2723 &ident.name.as_str())
2726 // Else, not bound in the same pattern: do
2732 PatEnum(ref path, _) => {
2733 // This must be an enum variant, struct or const.
2734 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2739 // The below shouldn't happen because all
2740 // qualified paths should be in PatQPath.
2741 TypecheckRequired =>
2742 self.session.span_bug(path.span,
2743 "resolve_possibly_assoc_item claimed
2745 that a path in PatEnum requires typecheck
2747 to resolve, but qualified paths should be
2750 ResolveAttempt(resolution) => resolution,
2752 if let Some(path_res) = resolution {
2753 match path_res.base_def {
2754 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2755 self.record_def(pattern.id, path_res);
2758 resolve_error(&self,
2760 ResolutionError::StaticVariableReference);
2761 self.record_def(pattern.id, err_path_resolution());
2764 // If anything ends up here entirely resolved,
2765 // it's an error. If anything ends up here
2766 // partially resolved, that's OK, because it may
2767 // be a `T::CONST` that typeck will resolve.
2768 if path_res.depth == 0 {
2772 ResolutionError::NotAnEnumVariantStructOrConst(
2780 self.record_def(pattern.id, err_path_resolution());
2782 let const_name = path.segments
2787 let traits = self.get_traits_containing_item(const_name);
2788 self.trait_map.insert(pattern.id, traits);
2789 self.record_def(pattern.id, path_res);
2797 ResolutionError::UnresolvedEnumVariantStructOrConst(
2798 &path.segments.last().unwrap().identifier.name.as_str())
2800 self.record_def(pattern.id, err_path_resolution());
2802 intravisit::walk_path(self, path);
2805 PatQPath(ref qself, ref path) => {
2806 // Associated constants only.
2807 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2812 TypecheckRequired => {
2813 // All `<T>::CONST` should end up here, and will
2814 // require use of the trait map to resolve
2815 // during typechecking.
2816 let const_name = path.segments
2821 let traits = self.get_traits_containing_item(const_name);
2822 self.trait_map.insert(pattern.id, traits);
2823 intravisit::walk_pat(self, pattern);
2826 ResolveAttempt(resolution) => resolution,
2828 if let Some(path_res) = resolution {
2829 match path_res.base_def {
2830 // All `<T as Trait>::CONST` should end up here, and
2831 // have the trait already selected.
2832 DefAssociatedConst(..) => {
2833 self.record_def(pattern.id, path_res);
2839 ResolutionError::NotAnAssociatedConst(
2840 &path.segments.last().unwrap().identifier.name.as_str()
2843 self.record_def(pattern.id, err_path_resolution());
2849 ResolutionError::UnresolvedAssociatedConst(&path.segments
2855 self.record_def(pattern.id, err_path_resolution());
2857 intravisit::walk_pat(self, pattern);
2860 PatStruct(ref path, _, _) => {
2861 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2862 Some(definition) => {
2863 self.record_def(pattern.id, definition);
2866 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2870 ResolutionError::DoesNotNameAStruct(
2871 &*path_names_to_string(path, 0))
2873 self.record_def(pattern.id, err_path_resolution());
2876 intravisit::walk_path(self, path);
2879 PatLit(_) | PatRange(..) => {
2880 intravisit::walk_pat(self, pattern);
2891 fn resolve_bare_identifier_pattern(&mut self,
2894 -> BareIdentifierPatternResolution {
2895 let module = self.current_module;
2896 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2897 Success((target, _)) => {
2898 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2900 target.binding.borrow());
2901 match target.binding.def() {
2903 panic!("resolved name in the value namespace to a set of name bindings \
2906 // For the two success cases, this lookup can be
2907 // considered as not having a private component because
2908 // the lookup happened only within the current module.
2909 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2910 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2912 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2913 return FoundConst(def, LastMod(AllPublic), name);
2915 Some(DefStatic(..)) => {
2916 resolve_error(self, span, ResolutionError::StaticVariableReference);
2917 return BareIdentifierPatternUnresolved;
2919 _ => return BareIdentifierPatternUnresolved
2924 panic!("unexpected indeterminate result");
2928 Some((span, msg)) => {
2929 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2934 debug!("(resolve bare identifier pattern) failed to find {}", name);
2935 return BareIdentifierPatternUnresolved;
2940 /// Handles paths that may refer to associated items
2941 fn resolve_possibly_assoc_item(&mut self,
2943 maybe_qself: Option<&hir::QSelf>,
2945 namespace: Namespace,
2947 -> AssocItemResolveResult {
2948 let max_assoc_types;
2952 if qself.position == 0 {
2953 return TypecheckRequired;
2955 max_assoc_types = path.segments.len() - qself.position;
2956 // Make sure the trait is valid.
2957 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2960 max_assoc_types = path.segments.len();
2964 let mut resolution = self.with_no_errors(|this| {
2965 this.resolve_path(id, path, 0, namespace, check_ribs)
2967 for depth in 1..max_assoc_types {
2968 if resolution.is_some() {
2971 self.with_no_errors(|this| {
2972 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2975 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2976 // A module is not a valid type or value.
2979 ResolveAttempt(resolution)
2982 /// If `check_ribs` is true, checks the local definitions first; i.e.
2983 /// doesn't skip straight to the containing module.
2984 /// Skips `path_depth` trailing segments, which is also reflected in the
2985 /// returned value. See `middle::def::PathResolution` for more info.
2986 pub fn resolve_path(&mut self,
2990 namespace: Namespace,
2992 -> Option<PathResolution> {
2993 let span = path.span;
2994 let segments = &path.segments[..path.segments.len() - path_depth];
2996 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2999 let def = self.resolve_crate_relative_path(span, segments, namespace);
3000 return def.map(mk_res);
3003 // Try to find a path to an item in a module.
3004 let last_ident = segments.last().unwrap().identifier;
3005 if segments.len() <= 1 {
3006 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
3007 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
3009 PathResolution::new(def, LastMod(AllPublic), path_depth)
3013 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
3014 let def = self.resolve_module_relative_path(span, segments, namespace);
3015 match (def, unqualified_def) {
3016 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
3018 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3021 "unnecessary qualification".to_string());
3029 // Resolve a single identifier
3030 fn resolve_identifier(&mut self,
3031 identifier: hir::Ident,
3032 namespace: Namespace,
3035 -> Option<LocalDef> {
3036 // First, check to see whether the name is a primitive type.
3037 if namespace == TypeNS {
3038 if let Some(&prim_ty) = self.primitive_type_table
3040 .get(&identifier.unhygienic_name) {
3041 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
3046 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
3051 let name = identifier.unhygienic_name;
3052 self.resolve_item_by_name_in_lexical_scope(name, namespace, record_used)
3053 .map(LocalDef::from_def)
3056 // Resolve a local definition, potentially adjusting for closures.
3057 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
3058 let ribs = match local_def.ribs {
3059 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
3060 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
3063 let mut def = local_def.def;
3066 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
3068 DefLocal(_, node_id) => {
3072 // Nothing to do. Continue.
3074 ClosureRibKind(function_id) => {
3076 let node_def_id = self.ast_map.local_def_id(node_id);
3078 let seen = self.freevars_seen
3080 .or_insert_with(|| NodeMap());
3081 if let Some(&index) = seen.get(&node_id) {
3082 def = DefUpvar(node_def_id, node_id, index, function_id);
3085 let vec = self.freevars
3087 .or_insert_with(|| vec![]);
3088 let depth = vec.len();
3094 def = DefUpvar(node_def_id, node_id, depth, function_id);
3095 seen.insert(node_id, depth);
3097 ItemRibKind | MethodRibKind => {
3098 // This was an attempt to access an upvar inside a
3099 // named function item. This is not allowed, so we
3103 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3106 ConstantItemRibKind => {
3107 // Still doesn't deal with upvars
3110 ResolutionError::AttemptToUseNonConstantValueInConstant);
3116 DefTyParam(..) | DefSelfTy(..) => {
3119 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3120 // Nothing to do. Continue.
3123 // This was an attempt to use a type parameter outside
3128 ResolutionError::TypeParametersFromOuterFunction);
3131 ConstantItemRibKind => {
3133 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3144 // resolve a "module-relative" path, e.g. a::b::c
3145 fn resolve_module_relative_path(&mut self,
3147 segments: &[hir::PathSegment],
3148 namespace: Namespace)
3149 -> Option<(Def, LastPrivate)> {
3150 let module_path = segments.split_last()
3154 .map(|ps| ps.identifier.name)
3155 .collect::<Vec<_>>();
3157 let containing_module;
3159 let current_module = self.current_module;
3160 match self.resolve_module_path(current_module,
3166 let (span, msg) = match err {
3167 Some((span, msg)) => (span, msg),
3169 let msg = format!("Use of undeclared type or module `{}`",
3170 names_to_string(&module_path));
3175 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3178 Indeterminate => panic!("indeterminate unexpected"),
3179 Success((resulting_module, resulting_last_private)) => {
3180 containing_module = resulting_module;
3181 last_private = resulting_last_private;
3185 let name = segments.last().unwrap().identifier.name;
3186 let def = match self.resolve_name_in_module(containing_module,
3189 NameSearchType::PathSearch,
3191 Success((Target { binding, .. }, _)) => {
3192 let (def, lp) = binding.def_and_lp();
3193 (def, last_private.or(lp))
3197 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3198 self.used_crates.insert(kid);
3203 /// Invariant: This must be called only during main resolution, not during
3204 /// import resolution.
3205 fn resolve_crate_relative_path(&mut self,
3207 segments: &[hir::PathSegment],
3208 namespace: Namespace)
3209 -> Option<(Def, LastPrivate)> {
3210 let module_path = segments.split_last()
3214 .map(|ps| ps.identifier.name)
3215 .collect::<Vec<_>>();
3217 let root_module = self.graph_root;
3219 let containing_module;
3221 match self.resolve_module_path_from_root(root_module,
3226 LastMod(AllPublic)) {
3228 let (span, msg) = match err {
3229 Some((span, msg)) => (span, msg),
3231 let msg = format!("Use of undeclared module `::{}`",
3232 names_to_string(&module_path[..]));
3237 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3242 panic!("indeterminate unexpected");
3245 Success((resulting_module, resulting_last_private)) => {
3246 containing_module = resulting_module;
3247 last_private = resulting_last_private;
3251 let name = segments.last().unwrap().identifier.name;
3252 match self.resolve_name_in_module(containing_module,
3255 NameSearchType::PathSearch,
3257 Success((Target { binding, .. }, _)) => {
3258 let (def, lp) = binding.def_and_lp();
3259 Some((def, last_private.or(lp)))
3265 fn resolve_identifier_in_local_ribs(&mut self,
3267 namespace: Namespace)
3268 -> Option<LocalDef> {
3269 // Check the local set of ribs.
3270 let (name, ribs) = match namespace {
3271 ValueNS => (ident.name, &self.value_ribs),
3272 TypeNS => (ident.unhygienic_name, &self.type_ribs),
3275 for (i, rib) in ribs.iter().enumerate().rev() {
3276 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3279 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3283 return Some(LocalDef {
3284 ribs: Some((namespace, i)),
3289 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3301 fn resolve_item_by_name_in_lexical_scope(&mut self,
3303 namespace: Namespace,
3307 let module = self.current_module;
3308 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
3309 Success((target, _)) => {
3310 match target.binding.def() {
3312 // This can happen if we were looking for a type and
3313 // found a module instead. Modules don't have defs.
3314 debug!("(resolving item path by identifier in lexical scope) failed to \
3315 resolve {} after success...",
3320 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3322 // This lookup is "all public" because it only searched
3323 // for one identifier in the current module (couldn't
3324 // have passed through reexports or anything like that.
3330 panic!("unexpected indeterminate result");
3333 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3336 if let Some((span, msg)) = err {
3337 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3345 fn with_no_errors<T, F>(&mut self, f: F) -> T
3346 where F: FnOnce(&mut Resolver) -> T
3348 self.emit_errors = false;
3350 self.emit_errors = true;
3354 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3355 fn extract_path_and_node_id(t: &Ty,
3356 allow: FallbackChecks)
3357 -> Option<(Path, NodeId, FallbackChecks)> {
3359 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3360 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3361 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3362 // This doesn't handle the remaining `Ty` variants as they are not
3363 // that commonly the self_type, it might be interesting to provide
3364 // support for those in future.
3369 fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
3371 name_path: &[ast::Name])
3372 -> Option<Module<'a>> {
3373 let root = this.current_module;
3374 let last_name = name_path.last().unwrap();
3376 if name_path.len() == 1 {
3377 match this.primitive_type_table.primitive_types.get(last_name) {
3380 match this.current_module.children.borrow().get(last_name) {
3381 Some(child) => child.type_ns.module(),
3387 match this.resolve_module_path(root,
3392 Success((module, _)) => Some(module),
3398 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3399 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3400 let sig = match this.ast_map.get(node_id) {
3401 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3402 hir::MethodTraitItem(ref sig, _) => sig,
3405 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3406 hir::ImplItemKind::Method(ref sig, _) => sig,
3411 sig.explicit_self.node == hir::SelfStatic
3413 this.session.cstore.is_static_method(did)
3417 let (path, node_id, allowed) = match self.current_self_type {
3418 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3420 None => return NoSuggestion,
3422 None => return NoSuggestion,
3425 if allowed == Everything {
3426 // Look for a field with the same name in the current self_type.
3427 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3428 Some(DefTy(did, _)) |
3429 Some(DefStruct(did)) |
3430 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3433 if fields.iter().any(|&field_name| name == field_name) {
3438 _ => {} // Self type didn't resolve properly
3442 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3444 // Look for a method in the current self type's impl module.
3445 if let Some(module) = get_module(self, path.span, &name_path) {
3446 if let Some(binding) = module.children.borrow().get(&name) {
3447 if let Some(DefMethod(did)) = binding.value_ns.def() {
3448 if is_static_method(self, did) {
3449 return StaticMethod(path_names_to_string(&path, 0));
3451 if self.current_trait_ref.is_some() {
3453 } else if allowed == Everything {
3460 // Look for a method in the current trait.
3461 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3462 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3463 if is_static_method(self, did) {
3464 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3474 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3475 if let Some(macro_name) = self.session.available_macros
3476 .borrow().iter().find(|n| n.as_str() == name) {
3477 return SuggestionType::Macro(format!("{}!", macro_name));
3480 let names = self.value_ribs
3483 .flat_map(|rib| rib.bindings.keys());
3485 if let Some(found) = find_best_match_for_name(names, name, None) {
3486 if name != &*found {
3487 return SuggestionType::Function(found);
3489 } SuggestionType::NotFound
3492 fn resolve_expr(&mut self, expr: &Expr) {
3493 // First, record candidate traits for this expression if it could
3494 // result in the invocation of a method call.
3496 self.record_candidate_traits_for_expr_if_necessary(expr);
3498 // Next, resolve the node.
3500 ExprPath(ref maybe_qself, ref path) => {
3501 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3502 maybe_qself.as_ref(),
3506 // `<T>::a::b::c` is resolved by typeck alone.
3507 TypecheckRequired => {
3508 let method_name = path.segments.last().unwrap().identifier.name;
3509 let traits = self.get_traits_containing_item(method_name);
3510 self.trait_map.insert(expr.id, traits);
3511 intravisit::walk_expr(self, expr);
3514 ResolveAttempt(resolution) => resolution,
3517 // This is a local path in the value namespace. Walk through
3518 // scopes looking for it.
3519 if let Some(path_res) = resolution {
3520 // Check if struct variant
3521 if let DefVariant(_, _, true) = path_res.base_def {
3522 let path_name = path_names_to_string(path, 0);
3524 let mut err = resolve_struct_error(self,
3526 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3528 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3530 if self.emit_errors {
3531 err.fileline_help(expr.span, &msg);
3533 err.span_help(expr.span, &msg);
3536 self.record_def(expr.id, err_path_resolution());
3538 // Write the result into the def map.
3539 debug!("(resolving expr) resolved `{}`",
3540 path_names_to_string(path, 0));
3542 // Partial resolutions will need the set of traits in scope,
3543 // so they can be completed during typeck.
3544 if path_res.depth != 0 {
3545 let method_name = path.segments.last().unwrap().identifier.name;
3546 let traits = self.get_traits_containing_item(method_name);
3547 self.trait_map.insert(expr.id, traits);
3550 self.record_def(expr.id, path_res);
3553 // Be helpful if the name refers to a struct
3554 // (The pattern matching def_tys where the id is in self.structs
3555 // matches on regular structs while excluding tuple- and enum-like
3556 // structs, which wouldn't result in this error.)
3557 let path_name = path_names_to_string(path, 0);
3558 let type_res = self.with_no_errors(|this| {
3559 this.resolve_path(expr.id, path, 0, TypeNS, false)
3562 self.record_def(expr.id, err_path_resolution());
3563 match type_res.map(|r| r.base_def) {
3564 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3565 let mut err = resolve_struct_error(self,
3567 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3569 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3571 if self.emit_errors {
3572 err.fileline_help(expr.span, &msg);
3574 err.span_help(expr.span, &msg);
3579 // Keep reporting some errors even if they're ignored above.
3580 self.resolve_path(expr.id, path, 0, ValueNS, true);
3582 let mut method_scope = false;
3583 self.value_ribs.iter().rev().all(|rib| {
3584 method_scope = match rib.kind {
3585 MethodRibKind => true,
3586 ItemRibKind | ConstantItemRibKind => false,
3587 _ => return true, // Keep advancing
3589 false // Stop advancing
3592 if method_scope && special_names::self_.as_str() == &path_name[..] {
3595 ResolutionError::SelfNotAvailableInStaticMethod);
3597 let last_name = path.segments.last().unwrap().identifier.name;
3598 let mut msg = match self.find_fallback_in_self_type(last_name) {
3600 // limit search to 5 to reduce the number
3601 // of stupid suggestions
3602 match self.find_best_match(&path_name) {
3603 SuggestionType::Macro(s) => {
3604 format!("the macro `{}`", s)
3606 SuggestionType::Function(s) => format!("`{}`", s),
3607 SuggestionType::NotFound => "".to_string(),
3610 Field => format!("`self.{}`", path_name),
3612 TraitItem => format!("to call `self.{}`", path_name),
3613 TraitMethod(path_str) |
3614 StaticMethod(path_str) =>
3615 format!("to call `{}::{}`", path_str, path_name),
3618 let mut context = UnresolvedNameContext::Other;
3619 if !msg.is_empty() {
3620 msg = format!(". Did you mean {}?", msg);
3622 // we check if this a module and if so, we display a help
3624 let name_path = path.segments.iter()
3625 .map(|seg| seg.identifier.name)
3626 .collect::<Vec<_>>();
3627 let current_module = self.current_module;
3629 match self.resolve_module_path(current_module,
3635 context = UnresolvedNameContext::PathIsMod(expr.id);
3643 ResolutionError::UnresolvedName(
3644 &*path_name, &*msg, context));
3650 intravisit::walk_expr(self, expr);
3653 ExprStruct(ref path, _, _) => {
3654 // Resolve the path to the structure it goes to. We don't
3655 // check to ensure that the path is actually a structure; that
3656 // is checked later during typeck.
3657 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3658 Some(definition) => self.record_def(expr.id, definition),
3660 debug!("(resolving expression) didn't find struct def",);
3664 ResolutionError::DoesNotNameAStruct(
3665 &*path_names_to_string(path, 0))
3667 self.record_def(expr.id, err_path_resolution());
3671 intravisit::walk_expr(self, expr);
3674 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3675 self.with_label_rib(|this| {
3676 let def_like = DlDef(DefLabel(expr.id));
3679 let rib = this.label_ribs.last_mut().unwrap();
3680 rib.bindings.insert(label.name, def_like);
3683 intravisit::walk_expr(this, expr);
3687 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3688 match self.search_label(label.node.name) {
3690 self.record_def(expr.id, err_path_resolution());
3693 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3695 Some(DlDef(def @ DefLabel(_))) => {
3696 // Since this def is a label, it is never read.
3697 self.record_def(expr.id,
3700 last_private: LastMod(AllPublic),
3705 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3711 intravisit::walk_expr(self, expr);
3716 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3718 ExprField(_, name) => {
3719 // FIXME(#6890): Even though you can't treat a method like a
3720 // field, we need to add any trait methods we find that match
3721 // the field name so that we can do some nice error reporting
3722 // later on in typeck.
3723 let traits = self.get_traits_containing_item(name.node);
3724 self.trait_map.insert(expr.id, traits);
3726 ExprMethodCall(name, _, _) => {
3727 debug!("(recording candidate traits for expr) recording traits for {}",
3729 let traits = self.get_traits_containing_item(name.node);
3730 self.trait_map.insert(expr.id, traits);
3738 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3739 debug!("(getting traits containing item) looking for '{}'", name);
3741 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3742 debug!("(adding trait info) found trait {:?} for method '{}'",
3745 found_traits.push(trait_def_id);
3748 let mut found_traits = Vec::new();
3749 let mut search_module = self.current_module;
3751 // Look for the current trait.
3752 match self.current_trait_ref {
3753 Some((trait_def_id, _)) => {
3754 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3755 add_trait_info(&mut found_traits, trait_def_id, name);
3758 None => {} // Nothing to do.
3761 // Look for trait children.
3762 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3765 for (_, child_names) in search_module.children.borrow().iter() {
3766 let def = match child_names.type_ns.def() {
3770 let trait_def_id = match def {
3771 DefTrait(trait_def_id) => trait_def_id,
3774 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3775 add_trait_info(&mut found_traits, trait_def_id, name);
3780 // Look for imports.
3781 for (_, import) in search_module.import_resolutions.borrow().iter() {
3782 let target = match import.type_ns.target {
3784 Some(ref target) => target,
3786 let did = match target.binding.def() {
3787 Some(DefTrait(trait_def_id)) => trait_def_id,
3788 Some(..) | None => continue,
3790 if self.trait_item_map.contains_key(&(name, did)) {
3791 add_trait_info(&mut found_traits, did, name);
3792 let id = import.type_ns.id;
3793 self.used_imports.insert((id, TypeNS));
3794 let trait_name = self.get_trait_name(did);
3795 self.record_import_use(id, trait_name);
3796 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3797 self.used_crates.insert(kid);
3802 match search_module.parent_link {
3803 NoParentLink | ModuleParentLink(..) => break,
3804 BlockParentLink(parent_module, _) => {
3805 search_module = parent_module;
3813 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3814 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3815 assert!(match resolution.last_private {
3816 LastImport{..} => false,
3819 "Import should only be used for `use` directives");
3821 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3822 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3823 self.session.span_bug(span,
3824 &format!("path resolved multiple times ({:?} before, {:?} now)",
3830 fn enforce_default_binding_mode(&mut self,
3832 pat_binding_mode: BindingMode,
3834 match pat_binding_mode {
3835 BindByValue(_) => {}
3839 ResolutionError::CannotUseRefBindingModeWith(descr));
3847 // Diagnostics are not particularly efficient, because they're rarely
3851 #[allow(dead_code)] // useful for debugging
3852 fn dump_module(&mut self, module_: Module<'a>) {
3853 debug!("Dump of module `{}`:", module_to_string(&*module_));
3855 debug!("Children:");
3856 build_reduced_graph::populate_module_if_necessary(self, &module_);
3857 for (&name, _) in module_.children.borrow().iter() {
3858 debug!("* {}", name);
3861 debug!("Import resolutions:");
3862 let import_resolutions = module_.import_resolutions.borrow();
3863 for (&name, import_resolution) in import_resolutions.iter() {
3865 match import_resolution.value_ns.target {
3867 value_repr = "".to_string();
3870 value_repr = " value:?".to_string();
3876 match import_resolution.type_ns.target {
3878 type_repr = "".to_string();
3881 type_repr = " type:?".to_string();
3886 debug!("* {}:{}{}", name, value_repr, type_repr);
3892 fn names_to_string(names: &[Name]) -> String {
3893 let mut first = true;
3894 let mut result = String::new();
3899 result.push_str("::")
3901 result.push_str(&name.as_str());
3906 fn path_names_to_string(path: &Path, depth: usize) -> String {
3907 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3909 .map(|seg| seg.identifier.name)
3911 names_to_string(&names[..])
3914 /// A somewhat inefficient routine to obtain the name of a module.
3915 fn module_to_string<'a>(module: Module<'a>) -> String {
3916 let mut names = Vec::new();
3918 fn collect_mod<'a>(names: &mut Vec<ast::Name>, module: Module<'a>) {
3919 match module.parent_link {
3921 ModuleParentLink(ref module, name) => {
3923 collect_mod(names, module);
3925 BlockParentLink(ref module, _) => {
3926 // danger, shouldn't be ident?
3927 names.push(special_idents::opaque.name);
3928 collect_mod(names, module);
3932 collect_mod(&mut names, module);
3934 if names.is_empty() {
3935 return "???".to_string();
3937 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3940 fn err_path_resolution() -> PathResolution {
3943 last_private: LastMod(AllPublic),
3949 pub struct CrateMap {
3950 pub def_map: RefCell<DefMap>,
3951 pub freevars: FreevarMap,
3952 pub export_map: ExportMap,
3953 pub trait_map: TraitMap,
3954 pub external_exports: ExternalExports,
3955 pub glob_map: Option<GlobMap>,
3958 #[derive(PartialEq,Copy, Clone)]
3959 pub enum MakeGlobMap {
3964 /// Entry point to crate resolution.
3965 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3966 ast_map: &'a hir_map::Map<'tcx>,
3967 make_glob_map: MakeGlobMap)
3969 let krate = ast_map.krate();
3970 let arenas = Resolver::arenas();
3971 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3973 resolver.resolve_crate(krate);
3975 check_unused::check_crate(&mut resolver, krate);
3978 def_map: resolver.def_map,
3979 freevars: resolver.freevars,
3980 export_map: resolver.export_map,
3981 trait_map: resolver.trait_map,
3982 external_exports: resolver.external_exports,
3983 glob_map: if resolver.make_glob_map {
3984 Some(resolver.glob_map)
3991 /// Builds a name resolution walker to be used within this module,
3992 /// or used externally, with an optional callback function.
3994 /// The callback takes a &mut bool which allows callbacks to end a
3995 /// walk when set to true, passing through the rest of the walk, while
3996 /// preserving the ribs + current module. This allows resolve_path
3997 /// calls to be made with the correct scope info. The node in the
3998 /// callback corresponds to the current node in the walk.
3999 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
4000 ast_map: &'a hir_map::Map<'tcx>,
4002 make_glob_map: MakeGlobMap,
4003 arenas: &'a ResolverArenas<'a>,
4004 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
4005 -> Resolver<'a, 'tcx> {
4006 let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
4008 resolver.callback = callback;
4010 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4011 session.abort_if_errors();
4013 resolve_imports::resolve_imports(&mut resolver);
4014 session.abort_if_errors();
4019 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }