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.
105 mod build_reduced_graph;
108 // Perform the callback, not walking deeper if the return is true
109 macro_rules! execute_callback {
110 ($node: expr, $walker: expr) => (
111 if let Some(ref callback) = $walker.callback {
112 if callback($node, &mut $walker.resolved) {
119 enum SuggestionType {
121 Function(token::InternedString),
125 pub enum ResolutionError<'a> {
126 /// error E0260: name conflicts with an extern crate
127 NameConflictsWithExternCrate(Name),
128 /// error E0401: can't use type parameters from outer function
129 TypeParametersFromOuterFunction,
130 /// error E0402: cannot use an outer type parameter in this context
131 OuterTypeParameterContext,
132 /// error E0403: the name is already used for a type parameter in this type parameter list
133 NameAlreadyUsedInTypeParameterList(Name),
134 /// error E0404: is not a trait
135 IsNotATrait(&'a str),
136 /// error E0405: use of undeclared trait name
137 UndeclaredTraitName(&'a str),
138 /// error E0406: undeclared associated type
139 UndeclaredAssociatedType,
140 /// error E0407: method is not a member of trait
141 MethodNotMemberOfTrait(Name, &'a str),
142 /// error E0437: type is not a member of trait
143 TypeNotMemberOfTrait(Name, &'a str),
144 /// error E0438: const is not a member of trait
145 ConstNotMemberOfTrait(Name, &'a str),
146 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
147 VariableNotBoundInPattern(Name, usize),
148 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
149 VariableBoundWithDifferentMode(Name, usize),
150 /// error E0410: variable from pattern is not bound in pattern #1
151 VariableNotBoundInParentPattern(Name, usize),
152 /// error E0411: use of `Self` outside of an impl or trait
153 SelfUsedOutsideImplOrTrait,
154 /// error E0412: use of undeclared
155 UseOfUndeclared(&'a str, &'a str),
156 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
157 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
158 /// error E0414: only irrefutable patterns allowed here
159 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
160 /// error E0415: identifier is bound more than once in this parameter list
161 IdentifierBoundMoreThanOnceInParameterList(&'a str),
162 /// error E0416: identifier is bound more than once in the same pattern
163 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
164 /// error E0417: static variables cannot be referenced in a pattern
165 StaticVariableReference,
166 /// error E0418: is not an enum variant, struct or const
167 NotAnEnumVariantStructOrConst(&'a str),
168 /// error E0419: unresolved enum variant, struct or const
169 UnresolvedEnumVariantStructOrConst(&'a str),
170 /// error E0420: is not an associated const
171 NotAnAssociatedConst(&'a str),
172 /// error E0421: unresolved associated const
173 UnresolvedAssociatedConst(&'a str),
174 /// error E0422: does not name a struct
175 DoesNotNameAStruct(&'a str),
176 /// error E0423: is a struct variant name, but this expression uses it like a function name
177 StructVariantUsedAsFunction(&'a str),
178 /// error E0424: `self` is not available in a static method
179 SelfNotAvailableInStaticMethod,
180 /// error E0425: unresolved name
181 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
182 /// error E0426: use of undeclared label
183 UndeclaredLabel(&'a str),
184 /// error E0427: cannot use `ref` binding mode with ...
185 CannotUseRefBindingModeWith(&'a str),
186 /// error E0428: duplicate definition
187 DuplicateDefinition(&'a str, Name),
188 /// error E0429: `self` imports are only allowed within a { } list
189 SelfImportsOnlyAllowedWithin,
190 /// error E0430: `self` import can only appear once in the list
191 SelfImportCanOnlyAppearOnceInTheList,
192 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
193 SelfImportOnlyInImportListWithNonEmptyPrefix,
194 /// error E0432: unresolved import
195 UnresolvedImport(Option<(&'a str, &'a str)>),
196 /// error E0433: failed to resolve
197 FailedToResolve(&'a str),
198 /// error E0434: can't capture dynamic environment in a fn item
199 CannotCaptureDynamicEnvironmentInFnItem,
200 /// error E0435: attempt to use a non-constant value in a constant
201 AttemptToUseNonConstantValueInConstant,
204 /// Context of where `ResolutionError::UnresolvedName` arose.
205 #[derive(Clone, PartialEq, Eq, Debug)]
206 pub enum UnresolvedNameContext {
207 /// `PathIsMod(id)` indicates that a given path, used in
208 /// expression context, actually resolved to a module rather than
209 /// a value. The `id` attached to the variant is the node id of
210 /// the erroneous path expression.
211 PathIsMod(ast::NodeId),
213 /// `Other` means we have no extra information about the context
214 /// of the unresolved name error. (Maybe we could eliminate all
215 /// such cases; but for now, this is an information-free default.)
219 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
220 span: syntax::codemap::Span,
221 resolution_error: ResolutionError<'b>) {
222 resolve_struct_error(resolver, span, resolution_error).emit();
225 fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
226 span: syntax::codemap::Span,
227 resolution_error: ResolutionError<'b>)
228 -> DiagnosticBuilder<'a> {
229 if !resolver.emit_errors {
230 return resolver.session.diagnostic().struct_dummy();
233 match resolution_error {
234 ResolutionError::NameConflictsWithExternCrate(name) => {
235 struct_span_err!(resolver.session,
238 "the name `{}` conflicts with an external crate \
239 that has been imported into this module",
242 ResolutionError::TypeParametersFromOuterFunction => {
243 struct_span_err!(resolver.session,
246 "can't use type parameters from outer function; try using a local \
247 type parameter instead")
249 ResolutionError::OuterTypeParameterContext => {
250 struct_span_err!(resolver.session,
253 "cannot use an outer type parameter in this context")
255 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
256 struct_span_err!(resolver.session,
259 "the name `{}` is already used for a type parameter in this type \
263 ResolutionError::IsNotATrait(name) => {
264 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
266 ResolutionError::UndeclaredTraitName(name) => {
267 struct_span_err!(resolver.session,
270 "use of undeclared trait name `{}`",
273 ResolutionError::UndeclaredAssociatedType => {
274 struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
276 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
277 struct_span_err!(resolver.session,
280 "method `{}` is not a member of trait `{}`",
284 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
285 struct_span_err!(resolver.session,
288 "type `{}` is not a member of trait `{}`",
292 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
293 struct_span_err!(resolver.session,
296 "const `{}` is not a member of trait `{}`",
300 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
301 struct_span_err!(resolver.session,
304 "variable `{}` from pattern #1 is not bound in pattern #{}",
308 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
309 struct_span_err!(resolver.session,
312 "variable `{}` is bound with different mode in pattern #{} than in \
317 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
318 struct_span_err!(resolver.session,
321 "variable `{}` from pattern #{} is not bound in pattern #1",
325 ResolutionError::SelfUsedOutsideImplOrTrait => {
326 struct_span_err!(resolver.session,
329 "use of `Self` outside of an impl or trait")
331 ResolutionError::UseOfUndeclared(kind, name) => {
332 struct_span_err!(resolver.session,
335 "use of undeclared {} `{}`",
339 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
340 struct_span_err!(resolver.session,
343 "declaration of `{}` shadows an enum variant \
344 or unit-like struct in scope",
347 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
348 let mut err = struct_span_err!(resolver.session,
351 "only irrefutable patterns allowed here");
353 "there already is a constant in scope sharing the same \
354 name as this pattern");
355 if let Some(sp) = resolver.ast_map.span_if_local(did) {
356 err.span_note(sp, "constant defined here");
358 if let Some(directive) = resolver.current_module
362 let item = resolver.ast_map.expect_item(directive.value_ns.id);
363 err.span_note(item.span, "constant imported here");
367 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
368 struct_span_err!(resolver.session,
371 "identifier `{}` is bound more than once in this parameter list",
374 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
375 struct_span_err!(resolver.session,
378 "identifier `{}` is bound more than once in the same pattern",
381 ResolutionError::StaticVariableReference => {
382 struct_span_err!(resolver.session,
385 "static variables cannot be referenced in a pattern, use a \
388 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
389 struct_span_err!(resolver.session,
392 "`{}` is not an enum variant, struct or const",
395 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
396 struct_span_err!(resolver.session,
399 "unresolved enum variant, struct or const `{}`",
402 ResolutionError::NotAnAssociatedConst(name) => {
403 struct_span_err!(resolver.session,
406 "`{}` is not an associated const",
409 ResolutionError::UnresolvedAssociatedConst(name) => {
410 struct_span_err!(resolver.session,
413 "unresolved associated const `{}`",
416 ResolutionError::DoesNotNameAStruct(name) => {
417 struct_span_err!(resolver.session,
420 "`{}` does not name a structure",
423 ResolutionError::StructVariantUsedAsFunction(path_name) => {
424 struct_span_err!(resolver.session,
427 "`{}` is the name of a struct or struct variant, but this expression \
428 uses it like a function name",
431 ResolutionError::SelfNotAvailableInStaticMethod => {
432 struct_span_err!(resolver.session,
435 "`self` is not available in a static method. Maybe a `self` \
436 argument is missing?")
438 ResolutionError::UnresolvedName(path, msg, context) => {
439 let mut err = struct_span_err!(resolver.session,
442 "unresolved name `{}`{}",
447 UnresolvedNameContext::Other => { } // no help available
448 UnresolvedNameContext::PathIsMod(id) => {
449 let mut help_msg = String::new();
450 let parent_id = resolver.ast_map.get_parent_node(id);
451 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
453 ExprField(_, ident) => {
454 help_msg = format!("To reference an item from the \
455 `{module}` module, use \
456 `{module}::{ident}`",
460 ExprMethodCall(ident, _, _) => {
461 help_msg = format!("To call a function from the \
462 `{module}` module, use \
463 `{module}::{ident}(..)`",
468 help_msg = format!("No function corresponds to `{module}(..)`",
471 _ => { } // no help available
474 help_msg = format!("Module `{module}` cannot be the value of an expression",
478 if !help_msg.is_empty() {
479 err.fileline_help(span, &help_msg);
485 ResolutionError::UndeclaredLabel(name) => {
486 struct_span_err!(resolver.session,
489 "use of undeclared label `{}`",
492 ResolutionError::CannotUseRefBindingModeWith(descr) => {
493 struct_span_err!(resolver.session,
496 "cannot use `ref` binding mode with {}",
499 ResolutionError::DuplicateDefinition(namespace, name) => {
500 struct_span_err!(resolver.session,
503 "duplicate definition of {} `{}`",
507 ResolutionError::SelfImportsOnlyAllowedWithin => {
508 struct_span_err!(resolver.session,
512 "`self` imports are only allowed within a { } list")
514 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
515 struct_span_err!(resolver.session,
518 "`self` import can only appear once in the list")
520 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
521 struct_span_err!(resolver.session,
524 "`self` import can only appear in an import list with a \
527 ResolutionError::UnresolvedImport(name) => {
528 let msg = match name {
529 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
530 None => "unresolved import".to_owned(),
532 struct_span_err!(resolver.session, span, E0432, "{}", msg)
534 ResolutionError::FailedToResolve(msg) => {
535 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
537 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
538 struct_span_err!(resolver.session,
542 "can't capture dynamic environment in a fn item; use the || { ... } \
543 closure form instead")
545 ResolutionError::AttemptToUseNonConstantValueInConstant => {
546 struct_span_err!(resolver.session,
549 "attempt to use a non-constant value in a constant")
554 #[derive(Copy, Clone)]
557 binding_mode: BindingMode,
560 // Map from the name in a pattern to its binding mode.
561 type BindingMap = HashMap<Name, BindingInfo>;
563 #[derive(Copy, Clone, PartialEq)]
564 enum PatternBindingMode {
566 LocalIrrefutableMode,
567 ArgumentIrrefutableMode,
570 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
576 /// A NamespaceResult represents the result of resolving an import in
577 /// a particular namespace. The result is either definitely-resolved,
578 /// definitely- unresolved, or unknown.
580 enum NamespaceResult<'a> {
581 /// Means that resolve hasn't gathered enough information yet to determine
582 /// whether the name is bound in this namespace. (That is, it hasn't
583 /// resolved all `use` directives yet.)
585 /// Means that resolve has determined that the name is definitely
586 /// not bound in the namespace.
588 /// Means that resolve has determined that the name is bound in the Module
589 /// argument, and specified by the NameBinding argument.
590 BoundResult(Module<'a>, NameBinding<'a>),
593 impl<'a> NamespaceResult<'a> {
594 fn is_unknown(&self) -> bool {
596 UnknownResult => true,
600 fn is_unbound(&self) -> bool {
602 UnboundResult => true,
608 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
609 fn visit_nested_item(&mut self, item: hir::ItemId) {
610 self.visit_item(self.ast_map.expect_item(item.id))
612 fn visit_item(&mut self, item: &Item) {
613 execute_callback!(hir_map::Node::NodeItem(item), self);
614 self.resolve_item(item);
616 fn visit_arm(&mut self, arm: &Arm) {
617 self.resolve_arm(arm);
619 fn visit_block(&mut self, block: &Block) {
620 execute_callback!(hir_map::Node::NodeBlock(block), self);
621 self.resolve_block(block);
623 fn visit_expr(&mut self, expr: &Expr) {
624 execute_callback!(hir_map::Node::NodeExpr(expr), self);
625 self.resolve_expr(expr);
627 fn visit_local(&mut self, local: &Local) {
628 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
629 self.resolve_local(local);
631 fn visit_ty(&mut self, ty: &Ty) {
632 self.resolve_type(ty);
634 fn visit_generics(&mut self, generics: &Generics) {
635 self.resolve_generics(generics);
637 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
638 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
639 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
641 // error already reported
642 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
645 intravisit::walk_poly_trait_ref(self, tref, m);
647 fn visit_variant(&mut self,
648 variant: &hir::Variant,
650 item_id: ast::NodeId) {
651 execute_callback!(hir_map::Node::NodeVariant(variant), self);
652 if let Some(ref dis_expr) = variant.node.disr_expr {
653 // resolve the discriminator expr as a constant
654 self.with_constant_rib(|this| {
655 this.visit_expr(dis_expr);
659 // `intravisit::walk_variant` without the discriminant expression.
660 self.visit_variant_data(&variant.node.data,
666 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
667 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
668 let type_parameters = match foreign_item.node {
669 ForeignItemFn(_, ref generics) => {
670 HasTypeParameters(generics, FnSpace, ItemRibKind)
672 ForeignItemStatic(..) => NoTypeParameters,
674 self.with_type_parameter_rib(type_parameters, |this| {
675 intravisit::walk_foreign_item(this, foreign_item);
678 fn visit_fn(&mut self,
679 function_kind: FnKind<'v>,
680 declaration: &'v FnDecl,
684 let rib_kind = match function_kind {
685 FnKind::ItemFn(_, generics, _, _, _, _) => {
686 self.visit_generics(generics);
689 FnKind::Method(_, sig, _) => {
690 self.visit_generics(&sig.generics);
691 self.visit_explicit_self(&sig.explicit_self);
694 FnKind::Closure => ClosureRibKind(node_id),
696 self.resolve_function(rib_kind, declaration, block);
700 type ErrorMessage = Option<(Span, String)>;
702 enum ResolveResult<T> {
703 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
704 Indeterminate, // Couldn't determine due to unresolved globs.
705 Success(T), // Successfully resolved the import.
708 impl<T> ResolveResult<T> {
709 fn success(&self) -> bool {
717 enum FallbackSuggestion {
722 StaticMethod(String),
726 #[derive(Copy, Clone)]
727 enum TypeParameters<'a> {
729 HasTypeParameters(// Type parameters.
732 // Identifies the things that these parameters
733 // were declared on (type, fn, etc)
736 // The kind of the rib used for type parameters.
740 // The rib kind controls the translation of local
741 // definitions (`DefLocal`) to upvars (`DefUpvar`).
742 #[derive(Copy, Clone, Debug)]
744 // No translation needs to be applied.
747 // We passed through a closure scope at the given node ID.
748 // Translate upvars as appropriate.
749 ClosureRibKind(NodeId /* func id */),
751 // We passed through an impl or trait and are now in one of its
752 // methods. Allow references to ty params that impl or trait
753 // binds. Disallow any other upvars (including other ty params that are
757 // We passed through an item scope. Disallow upvars.
760 // We're in a constant item. Can't refer to dynamic stuff.
764 #[derive(Copy, Clone)]
765 enum UseLexicalScopeFlag {
770 enum ModulePrefixResult<'a> {
772 PrefixFound(Module<'a>, usize),
775 #[derive(Copy, Clone)]
776 enum AssocItemResolveResult {
777 /// Syntax such as `<T>::item`, which can't be resolved until type
780 /// We should have been able to resolve the associated item.
781 ResolveAttempt(Option<PathResolution>),
784 #[derive(Copy, Clone, PartialEq)]
785 enum NameSearchType {
786 /// We're doing a name search in order to resolve a `use` directive.
789 /// We're doing a name search in order to resolve a path type, a path
790 /// expression, or a path pattern.
794 #[derive(Copy, Clone)]
795 enum BareIdentifierPatternResolution {
796 FoundStructOrEnumVariant(Def, LastPrivate),
797 FoundConst(Def, LastPrivate, Name),
798 BareIdentifierPatternUnresolved,
804 bindings: HashMap<Name, DefLike>,
809 fn new(kind: RibKind) -> Rib {
811 bindings: HashMap::new(),
817 /// A definition along with the index of the rib it was found on
819 ribs: Option<(Namespace, usize)>,
824 fn from_def(def: Def) -> Self {
832 /// The link from a module up to its nearest parent node.
833 #[derive(Clone,Debug)]
834 enum ParentLink<'a> {
836 ModuleParentLink(Module<'a>, Name),
837 BlockParentLink(Module<'a>, NodeId),
840 /// One node in the tree of modules.
841 pub struct ModuleS<'a> {
842 parent_link: ParentLink<'a>,
843 def: Cell<Option<Def>>,
846 children: RefCell<HashMap<Name, NameBindings<'a>>>,
847 imports: RefCell<Vec<ImportDirective>>,
849 // The external module children of this node that were declared with
851 external_module_children: RefCell<HashMap<Name, Module<'a>>>,
853 // The anonymous children of this node. Anonymous children are pseudo-
854 // modules that are implicitly created around items contained within
857 // For example, if we have this:
865 // There will be an anonymous module created around `g` with the ID of the
866 // entry block for `f`.
867 anonymous_children: RefCell<NodeMap<Module<'a>>>,
869 // The status of resolving each import in this module.
870 import_resolutions: RefCell<HashMap<Name, ImportResolutionPerNamespace<'a>>>,
872 // The number of unresolved globs that this module exports.
873 glob_count: Cell<usize>,
875 // The number of unresolved pub imports (both regular and globs) in this module
876 pub_count: Cell<usize>,
878 // The number of unresolved pub glob imports in this module
879 pub_glob_count: Cell<usize>,
881 // The index of the import we're resolving.
882 resolved_import_count: Cell<usize>,
884 // Whether this module is populated. If not populated, any attempt to
885 // access the children must be preceded with a
886 // `populate_module_if_necessary` call.
887 populated: Cell<bool>,
890 pub type Module<'a> = &'a ModuleS<'a>;
892 impl<'a> ModuleS<'a> {
893 fn new(parent_link: ParentLink<'a>, def: Option<Def>, external: bool, is_public: bool) -> Self {
895 parent_link: parent_link,
897 is_public: is_public,
898 children: RefCell::new(HashMap::new()),
899 imports: RefCell::new(Vec::new()),
900 external_module_children: RefCell::new(HashMap::new()),
901 anonymous_children: RefCell::new(NodeMap()),
902 import_resolutions: RefCell::new(HashMap::new()),
903 glob_count: Cell::new(0),
904 pub_count: Cell::new(0),
905 pub_glob_count: Cell::new(0),
906 resolved_import_count: Cell::new(0),
907 populated: Cell::new(!external),
911 fn def_id(&self) -> Option<DefId> {
912 self.def.get().as_ref().map(Def::def_id)
915 fn is_normal(&self) -> bool {
916 match self.def.get() {
917 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
922 fn is_trait(&self) -> bool {
923 match self.def.get() {
924 Some(DefTrait(_)) => true,
929 fn all_imports_resolved(&self) -> bool {
930 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
931 // it is currently being resolved ! so nope
934 self.imports.borrow().len() == self.resolved_import_count.get()
938 pub fn inc_glob_count(&self) {
939 self.glob_count.set(self.glob_count.get() + 1);
941 pub fn dec_glob_count(&self) {
942 assert!(self.glob_count.get() > 0);
943 self.glob_count.set(self.glob_count.get() - 1);
945 pub fn inc_pub_count(&self) {
946 self.pub_count.set(self.pub_count.get() + 1);
948 pub fn dec_pub_count(&self) {
949 assert!(self.pub_count.get() > 0);
950 self.pub_count.set(self.pub_count.get() - 1);
952 pub fn inc_pub_glob_count(&self) {
953 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
955 pub fn dec_pub_glob_count(&self) {
956 assert!(self.pub_glob_count.get() > 0);
957 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
961 impl<'a> fmt::Debug for ModuleS<'a> {
962 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
976 flags DefModifiers: u8 {
977 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
978 // or `use Enum::*` to work on private enums.
979 const PUBLIC = 1 << 0,
980 const IMPORTABLE = 1 << 1,
981 // Variants are considered `PUBLIC`, but some of them live in private enums.
982 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
983 const PRIVATE_VARIANT = 1 << 2,
987 // Records a possibly-private value, type, or module definition.
990 modifiers: DefModifiers, // see note in ImportResolutionPerNamespace about how to use this
991 def_or_module: DefOrModule<'a>,
996 enum DefOrModule<'a> {
1001 impl<'a> NsDef<'a> {
1002 fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
1003 let modifiers = if module.is_public {
1004 DefModifiers::PUBLIC
1006 DefModifiers::empty()
1007 } | DefModifiers::IMPORTABLE;
1009 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
1012 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
1013 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
1016 fn module(&self) -> Option<Module<'a>> {
1017 match self.def_or_module {
1018 DefOrModule::Module(ref module) => Some(module),
1019 DefOrModule::Def(_) => None,
1023 fn def(&self) -> Option<Def> {
1024 match self.def_or_module {
1025 DefOrModule::Def(def) => Some(def),
1026 DefOrModule::Module(ref module) => module.def.get(),
1031 // Records at most one definition that a name in a namespace is bound to
1032 #[derive(Clone,Debug)]
1033 pub struct NameBinding<'a>(Rc<RefCell<Option<NsDef<'a>>>>);
1035 impl<'a> NameBinding<'a> {
1037 NameBinding(Rc::new(RefCell::new(None)))
1040 fn create_from_module(module: Module<'a>) -> Self {
1041 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
1044 fn set(&self, ns_def: NsDef<'a>) {
1045 *self.0.borrow_mut() = Some(ns_def);
1048 fn set_modifiers(&self, modifiers: DefModifiers) {
1049 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
1050 ns_def.modifiers = modifiers
1054 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef<'a>>> {
1058 // Lifted versions of the NsDef methods and fields
1059 fn def(&self) -> Option<Def> {
1060 self.borrow().as_ref().and_then(NsDef::def)
1062 fn module(&self) -> Option<Module<'a>> {
1063 self.borrow().as_ref().and_then(NsDef::module)
1065 fn span(&self) -> Option<Span> {
1066 self.borrow().as_ref().and_then(|def| def.span)
1068 fn modifiers(&self) -> Option<DefModifiers> {
1069 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
1072 fn defined(&self) -> bool {
1073 self.borrow().is_some()
1076 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1077 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1080 fn is_public(&self) -> bool {
1081 self.defined_with(DefModifiers::PUBLIC)
1084 fn def_and_lp(&self) -> (Def, LastPrivate) {
1085 let def = self.def().unwrap();
1086 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1090 // Records the definitions (at most one for each namespace) that a name is
1092 #[derive(Clone,Debug)]
1093 pub struct NameBindings<'a> {
1094 type_ns: NameBinding<'a>, // < Meaning in type namespace.
1095 value_ns: NameBinding<'a>, // < Meaning in value namespace.
1098 impl<'a> ::std::ops::Index<Namespace> for NameBindings<'a> {
1099 type Output = NameBinding<'a>;
1100 fn index(&self, namespace: Namespace) -> &NameBinding<'a> {
1101 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1105 impl<'a> NameBindings<'a> {
1108 type_ns: NameBinding::new(),
1109 value_ns: NameBinding::new(),
1113 /// Creates a new module in this set of name bindings.
1114 fn define_module(&self, module: Module<'a>, sp: Span) {
1115 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1118 /// Records a type definition.
1119 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1120 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1121 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1124 /// Records a value definition.
1125 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1126 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1127 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1131 /// Interns the names of the primitive types.
1132 struct PrimitiveTypeTable {
1133 primitive_types: HashMap<Name, PrimTy>,
1136 impl PrimitiveTypeTable {
1137 fn new() -> PrimitiveTypeTable {
1138 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1140 table.intern("bool", TyBool);
1141 table.intern("char", TyChar);
1142 table.intern("f32", TyFloat(TyF32));
1143 table.intern("f64", TyFloat(TyF64));
1144 table.intern("isize", TyInt(TyIs));
1145 table.intern("i8", TyInt(TyI8));
1146 table.intern("i16", TyInt(TyI16));
1147 table.intern("i32", TyInt(TyI32));
1148 table.intern("i64", TyInt(TyI64));
1149 table.intern("str", TyStr);
1150 table.intern("usize", TyUint(TyUs));
1151 table.intern("u8", TyUint(TyU8));
1152 table.intern("u16", TyUint(TyU16));
1153 table.intern("u32", TyUint(TyU32));
1154 table.intern("u64", TyUint(TyU64));
1159 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1160 self.primitive_types.insert(token::intern(string), primitive_type);
1164 /// The main resolver class.
1165 pub struct Resolver<'a, 'tcx: 'a> {
1166 session: &'a Session,
1168 ast_map: &'a hir_map::Map<'tcx>,
1170 graph_root: Module<'a>,
1172 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1174 structs: FnvHashMap<DefId, Vec<Name>>,
1176 // The number of imports that are currently unresolved.
1177 unresolved_imports: usize,
1179 // The module that represents the current item scope.
1180 current_module: Module<'a>,
1182 // The current set of local scopes, for values.
1183 // FIXME #4948: Reuse ribs to avoid allocation.
1184 value_ribs: Vec<Rib>,
1186 // The current set of local scopes, for types.
1187 type_ribs: Vec<Rib>,
1189 // The current set of local scopes, for labels.
1190 label_ribs: Vec<Rib>,
1192 // The trait that the current context can refer to.
1193 current_trait_ref: Option<(DefId, TraitRef)>,
1195 // The current self type if inside an impl (used for better errors).
1196 current_self_type: Option<Ty>,
1198 // The idents for the primitive types.
1199 primitive_type_table: PrimitiveTypeTable,
1201 def_map: RefCell<DefMap>,
1202 freevars: FreevarMap,
1203 freevars_seen: NodeMap<NodeMap<usize>>,
1204 export_map: ExportMap,
1205 trait_map: TraitMap,
1206 external_exports: ExternalExports,
1208 // Whether or not to print error messages. Can be set to true
1209 // when getting additional info for error message suggestions,
1210 // so as to avoid printing duplicate errors
1213 make_glob_map: bool,
1214 // Maps imports to the names of items actually imported (this actually maps
1215 // all imports, but only glob imports are actually interesting).
1218 used_imports: HashSet<(NodeId, Namespace)>,
1219 used_crates: HashSet<CrateNum>,
1221 // Callback function for intercepting walks
1222 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1223 // The intention is that the callback modifies this flag.
1224 // Once set, the resolver falls out of the walk, preserving the ribs.
1227 arenas: &'a ResolverArenas<'a>,
1230 pub struct ResolverArenas<'a> {
1231 modules: arena::TypedArena<ModuleS<'a>>,
1234 #[derive(PartialEq)]
1235 enum FallbackChecks {
1237 OnlyTraitAndStatics,
1240 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1241 fn new(session: &'a Session,
1242 ast_map: &'a hir_map::Map<'tcx>,
1243 make_glob_map: MakeGlobMap,
1244 arenas: &'a ResolverArenas<'a>)
1245 -> Resolver<'a, 'tcx> {
1246 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1247 let graph_root = ModuleS::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1248 let graph_root = arenas.modules.alloc(graph_root);
1255 // The outermost module has def ID 0; this is not reflected in the
1257 graph_root: graph_root,
1259 trait_item_map: FnvHashMap(),
1260 structs: FnvHashMap(),
1262 unresolved_imports: 0,
1264 current_module: graph_root,
1265 value_ribs: Vec::new(),
1266 type_ribs: Vec::new(),
1267 label_ribs: Vec::new(),
1269 current_trait_ref: None,
1270 current_self_type: None,
1272 primitive_type_table: PrimitiveTypeTable::new(),
1274 def_map: RefCell::new(NodeMap()),
1275 freevars: NodeMap(),
1276 freevars_seen: NodeMap(),
1277 export_map: NodeMap(),
1278 trait_map: NodeMap(),
1279 used_imports: HashSet::new(),
1280 used_crates: HashSet::new(),
1281 external_exports: DefIdSet(),
1284 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1285 glob_map: HashMap::new(),
1294 fn arenas() -> ResolverArenas<'a> {
1296 modules: arena::TypedArena::new(),
1300 fn new_module(&self,
1301 parent_link: ParentLink<'a>,
1304 is_public: bool) -> Module<'a> {
1305 self.arenas.modules.alloc(ModuleS::new(parent_link, def, external, is_public))
1309 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1310 if !self.make_glob_map {
1313 if self.glob_map.contains_key(&import_id) {
1314 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1318 let mut new_set = HashSet::new();
1319 new_set.insert(name);
1320 self.glob_map.insert(import_id, new_set);
1323 fn get_trait_name(&self, did: DefId) -> Name {
1324 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1325 self.ast_map.expect_item(node_id).name
1327 self.session.cstore.item_name(did)
1331 /// Check that an external crate doesn't collide with items or other external crates.
1332 fn check_for_conflicts_for_external_crate(&self, module: Module<'a>, name: Name, span: Span) {
1333 if module.external_module_children.borrow().contains_key(&name) {
1334 span_err!(self.session,
1337 "an external crate named `{}` has already been imported into this module",
1340 match module.children.borrow().get(&name) {
1341 Some(name_bindings) if name_bindings.type_ns.defined() => {
1343 name_bindings.type_ns.span().unwrap_or(codemap::DUMMY_SP),
1344 ResolutionError::NameConflictsWithExternCrate(name));
1350 /// Checks that the names of items don't collide with external crates.
1351 fn check_for_conflicts_between_external_crates_and_items(&self,
1355 if module.external_module_children.borrow().contains_key(&name) {
1356 resolve_error(self, span, ResolutionError::NameConflictsWithExternCrate(name));
1360 /// Resolves the given module path from the given root `module_`.
1361 fn resolve_module_path_from_root(&mut self,
1362 module_: Module<'a>,
1363 module_path: &[Name],
1366 name_search_type: NameSearchType,
1368 -> ResolveResult<(Module<'a>, LastPrivate)> {
1369 fn search_parent_externals<'a>(needle: Name, module: Module<'a>)
1370 -> Option<Module<'a>> {
1371 match module.external_module_children.borrow().get(&needle) {
1372 Some(_) => Some(module),
1373 None => match module.parent_link {
1374 ModuleParentLink(ref parent, _) => {
1375 search_parent_externals(needle, parent)
1382 let mut search_module = module_;
1383 let mut index = index;
1384 let module_path_len = module_path.len();
1385 let mut closest_private = lp;
1387 // Resolve the module part of the path. This does not involve looking
1388 // upward though scope chains; we simply resolve names directly in
1389 // modules as we go.
1390 while index < module_path_len {
1391 let name = module_path[index];
1392 match self.resolve_name_in_module(search_module,
1398 let segment_name = name.as_str();
1399 let module_name = module_to_string(search_module);
1400 let mut span = span;
1401 let msg = if "???" == &module_name[..] {
1402 span.hi = span.lo + Pos::from_usize(segment_name.len());
1404 match search_parent_externals(name, &self.current_module) {
1406 let path_str = names_to_string(module_path);
1407 let target_mod_str = module_to_string(&*module);
1408 let current_mod_str = module_to_string(&*self.current_module);
1410 let prefix = if target_mod_str == current_mod_str {
1411 "self::".to_string()
1413 format!("{}::", target_mod_str)
1416 format!("Did you mean `{}{}`?", prefix, path_str)
1418 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1421 format!("Could not find `{}` in `{}`", segment_name, module_name)
1424 return Failed(Some((span, msg)));
1426 Failed(err) => return Failed(err),
1428 debug!("(resolving module path for import) module resolution is \
1431 return Indeterminate;
1433 Success((target, used_proxy)) => {
1434 // Check to see whether there are type bindings, and, if
1435 // so, whether there is a module within.
1436 if let Some(module_def) = target.binding.module() {
1437 // track extern crates for unused_extern_crate lint
1438 if let Some(did) = module_def.def_id() {
1439 self.used_crates.insert(did.krate);
1442 search_module = module_def;
1444 // Keep track of the closest private module used
1445 // when resolving this import chain.
1446 if !used_proxy && !search_module.is_public {
1447 if let Some(did) = search_module.def_id() {
1448 closest_private = LastMod(DependsOn(did));
1452 let msg = format!("Not a module `{}`", name);
1453 return Failed(Some((span, msg)));
1461 return Success((search_module, closest_private));
1464 /// Attempts to resolve the module part of an import directive or path
1465 /// rooted at the given module.
1467 /// On success, returns the resolved module, and the closest *private*
1468 /// module found to the destination when resolving this path.
1469 fn resolve_module_path(&mut self,
1470 module_: Module<'a>,
1471 module_path: &[Name],
1472 use_lexical_scope: UseLexicalScopeFlag,
1474 name_search_type: NameSearchType)
1475 -> ResolveResult<(Module<'a>, LastPrivate)> {
1476 let module_path_len = module_path.len();
1477 assert!(module_path_len > 0);
1479 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1480 names_to_string(module_path),
1481 module_to_string(&*module_));
1483 // Resolve the module prefix, if any.
1484 let module_prefix_result = self.resolve_module_prefix(module_, module_path);
1489 match module_prefix_result {
1491 let mpath = names_to_string(module_path);
1492 let mpath = &mpath[..];
1493 match mpath.rfind(':') {
1495 let msg = format!("Could not find `{}` in `{}`",
1496 // idx +- 1 to account for the
1497 // colons on either side
1500 return Failed(Some((span, msg)));
1503 return Failed(None);
1507 Failed(err) => return Failed(err),
1509 debug!("(resolving module path for import) indeterminate; bailing");
1510 return Indeterminate;
1512 Success(NoPrefixFound) => {
1513 // There was no prefix, so we're considering the first element
1514 // of the path. How we handle this depends on whether we were
1515 // instructed to use lexical scope or not.
1516 match use_lexical_scope {
1517 DontUseLexicalScope => {
1518 // This is a crate-relative path. We will start the
1519 // resolution process at index zero.
1520 search_module = self.graph_root;
1522 last_private = LastMod(AllPublic);
1524 UseLexicalScope => {
1525 // This is not a crate-relative path. We resolve the
1526 // first component of the path in the current lexical
1527 // scope and then proceed to resolve below that.
1528 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1529 Failed(err) => return Failed(err),
1531 debug!("(resolving module path for import) indeterminate; bailing");
1532 return Indeterminate;
1534 Success(containing_module) => {
1535 search_module = containing_module;
1537 last_private = LastMod(AllPublic);
1543 Success(PrefixFound(ref containing_module, index)) => {
1544 search_module = containing_module;
1545 start_index = index;
1546 last_private = LastMod(DependsOn(containing_module.def_id()
1551 self.resolve_module_path_from_root(search_module,
1559 /// Invariant: This must only be called during main resolution, not during
1560 /// import resolution.
1561 fn resolve_item_in_lexical_scope(&mut self,
1562 module_: Module<'a>,
1564 namespace: Namespace,
1566 -> ResolveResult<(Target<'a>, bool)> {
1567 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1570 module_to_string(&*module_));
1572 // The current module node is handled specially. First, check for
1573 // its immediate children.
1574 build_reduced_graph::populate_module_if_necessary(self, &module_);
1576 match module_.children.borrow().get(&name) {
1577 Some(name_bindings) if name_bindings[namespace].defined() => {
1578 debug!("top name bindings succeeded");
1579 return Success((Target::new(module_,
1580 name_bindings[namespace].clone(),
1585 // Not found; continue.
1589 // Now check for its import directives. We don't have to have resolved
1590 // all its imports in the usual way; this is because chains of
1591 // adjacent import statements are processed as though they mutated the
1593 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1594 match import_resolution[namespace].target.clone() {
1596 // Not found; continue.
1597 debug!("(resolving item in lexical scope) found import resolution, but not \
1602 debug!("(resolving item in lexical scope) using import resolution");
1603 // track used imports and extern crates as well
1604 let id = import_resolution[namespace].id;
1606 self.used_imports.insert((id, namespace));
1607 self.record_import_use(id, name);
1608 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1609 self.used_crates.insert(kid);
1612 return Success((target, false));
1617 // Search for external modules.
1618 if namespace == TypeNS {
1619 let children = module_.external_module_children.borrow();
1620 if let Some(module) = children.get(&name) {
1621 let name_binding = NameBinding::create_from_module(module);
1622 debug!("lower name bindings succeeded");
1623 return Success((Target::new(module_, name_binding, Shadowable::Never),
1628 // Finally, proceed up the scope chain looking for parent modules.
1629 let mut search_module = module_;
1631 // Go to the next parent.
1632 match search_module.parent_link {
1634 // No more parents. This module was unresolved.
1635 debug!("(resolving item in lexical scope) unresolved module");
1636 return Failed(None);
1638 ModuleParentLink(parent_module_node, _) => {
1639 if search_module.is_normal() {
1640 // We stop the search here.
1641 debug!("(resolving item in lexical scope) unresolved module: not \
1642 searching through module parents");
1643 return Failed(None);
1645 search_module = parent_module_node;
1648 BlockParentLink(parent_module_node, _) => {
1649 search_module = parent_module_node;
1653 // Resolve the name in the parent module.
1654 match self.resolve_name_in_module(search_module,
1659 Failed(Some((span, msg))) => {
1660 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1662 Failed(None) => (), // Continue up the search chain.
1664 // We couldn't see through the higher scope because of an
1665 // unresolved import higher up. Bail.
1667 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1668 return Indeterminate;
1670 Success((target, used_reexport)) => {
1671 // We found the module.
1672 debug!("(resolving item in lexical scope) found name in module, done");
1673 return Success((target, used_reexport));
1679 /// Resolves a module name in the current lexical scope.
1680 fn resolve_module_in_lexical_scope(&mut self,
1681 module_: Module<'a>,
1683 -> ResolveResult<Module<'a>> {
1684 // If this module is an anonymous module, resolve the item in the
1685 // lexical scope. Otherwise, resolve the item from the crate root.
1686 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS, true);
1687 match resolve_result {
1688 Success((target, _)) => {
1689 if let Some(module_def) = target.binding.module() {
1690 return Success(module_def)
1692 debug!("!!! (resolving module in lexical scope) module \
1693 wasn't actually a module!");
1694 return Failed(None);
1698 debug!("(resolving module in lexical scope) indeterminate; bailing");
1699 return Indeterminate;
1702 debug!("(resolving module in lexical scope) failed to resolve");
1708 /// Returns the nearest normal module parent of the given module.
1709 fn get_nearest_normal_module_parent(&mut self, module_: Module<'a>) -> Option<Module<'a>> {
1710 let mut module_ = module_;
1712 match module_.parent_link {
1713 NoParentLink => return None,
1714 ModuleParentLink(new_module, _) |
1715 BlockParentLink(new_module, _) => {
1716 let new_module = new_module;
1717 if new_module.is_normal() {
1718 return Some(new_module);
1720 module_ = new_module;
1726 /// Returns the nearest normal module parent of the given module, or the
1727 /// module itself if it is a normal module.
1728 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Module<'a>) -> Module<'a> {
1729 if module_.is_normal() {
1732 match self.get_nearest_normal_module_parent(module_) {
1734 Some(new_module) => new_module,
1738 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1739 /// (b) some chain of `super::`.
1740 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1741 fn resolve_module_prefix(&mut self,
1742 module_: Module<'a>,
1743 module_path: &[Name])
1744 -> ResolveResult<ModulePrefixResult<'a>> {
1745 // Start at the current module if we see `self` or `super`, or at the
1746 // top of the crate otherwise.
1747 let mut i = match &*module_path[0].as_str() {
1750 _ => return Success(NoPrefixFound),
1752 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1754 // Now loop through all the `super`s we find.
1755 while i < module_path.len() && "super" == module_path[i].as_str() {
1756 debug!("(resolving module prefix) resolving `super` at {}",
1757 module_to_string(&*containing_module));
1758 match self.get_nearest_normal_module_parent(containing_module) {
1759 None => return Failed(None),
1760 Some(new_module) => {
1761 containing_module = new_module;
1767 debug!("(resolving module prefix) finished resolving prefix at {}",
1768 module_to_string(&*containing_module));
1770 return Success(PrefixFound(containing_module, i));
1773 /// Attempts to resolve the supplied name in the given module for the
1774 /// given namespace. If successful, returns the target corresponding to
1777 /// The boolean returned on success is an indicator of whether this lookup
1778 /// passed through a public re-export proxy.
1779 fn resolve_name_in_module(&mut self,
1780 module_: Module<'a>,
1782 namespace: Namespace,
1783 name_search_type: NameSearchType,
1784 allow_private_imports: bool)
1785 -> ResolveResult<(Target<'a>, bool)> {
1786 debug!("(resolving name in module) resolving `{}` in `{}`",
1788 module_to_string(&*module_));
1790 // First, check the direct children of the module.
1791 build_reduced_graph::populate_module_if_necessary(self, &module_);
1793 let children = module_.children.borrow();
1794 match children.get(&name) {
1795 Some(name_bindings) if name_bindings[namespace].defined() => {
1796 debug!("(resolving name in module) found node as child");
1797 return Success((Target::new(module_,
1798 name_bindings[namespace].clone(),
1807 // Next, check the module's imports if necessary.
1809 // If this is a search of all imports, we should be done with glob
1810 // resolution at this point.
1811 if name_search_type == PathSearch {
1812 assert_eq!(module_.glob_count.get(), 0);
1815 // Check the list of resolved imports.
1816 let children = module_.import_resolutions.borrow();
1817 match children.get(&name) {
1818 Some(import_resolution) if allow_private_imports ||
1819 import_resolution[namespace].is_public => {
1821 if import_resolution[namespace].is_public &&
1822 import_resolution.outstanding_references != 0 {
1823 debug!("(resolving name in module) import unresolved; bailing out");
1824 return Indeterminate;
1826 match import_resolution[namespace].target.clone() {
1828 debug!("(resolving name in module) name found, but not in namespace {:?}",
1832 debug!("(resolving name in module) resolved to import");
1833 // track used imports and extern crates as well
1834 let id = import_resolution[namespace].id;
1835 self.used_imports.insert((id, namespace));
1836 self.record_import_use(id, name);
1837 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1838 self.used_crates.insert(kid);
1840 return Success((target, true));
1844 Some(..) | None => {} // Continue.
1847 // Finally, search through external children.
1848 if namespace == TypeNS {
1849 let children = module_.external_module_children.borrow();
1850 if let Some(module) = children.get(&name) {
1851 let name_binding = NameBinding::create_from_module(module);
1852 return Success((Target::new(module_, name_binding, Shadowable::Never),
1857 // We're out of luck.
1858 debug!("(resolving name in module) failed to resolve `{}`", name);
1859 return Failed(None);
1862 fn report_unresolved_imports(&mut self, module_: Module<'a>) {
1863 let index = module_.resolved_import_count.get();
1864 let imports = module_.imports.borrow();
1865 let import_count = imports.len();
1866 if index != import_count {
1868 (*imports)[index].span,
1869 ResolutionError::UnresolvedImport(None));
1872 // Descend into children and anonymous children.
1873 build_reduced_graph::populate_module_if_necessary(self, &module_);
1875 for (_, child_node) in module_.children.borrow().iter() {
1876 match child_node.type_ns.module() {
1880 Some(child_module) => {
1881 self.report_unresolved_imports(child_module);
1886 for (_, module_) in module_.anonymous_children.borrow().iter() {
1887 self.report_unresolved_imports(module_);
1893 // We maintain a list of value ribs and type ribs.
1895 // Simultaneously, we keep track of the current position in the module
1896 // graph in the `current_module` pointer. When we go to resolve a name in
1897 // the value or type namespaces, we first look through all the ribs and
1898 // then query the module graph. When we resolve a name in the module
1899 // namespace, we can skip all the ribs (since nested modules are not
1900 // allowed within blocks in Rust) and jump straight to the current module
1903 // Named implementations are handled separately. When we find a method
1904 // call, we consult the module node to find all of the implementations in
1905 // scope. This information is lazily cached in the module node. We then
1906 // generate a fake "implementation scope" containing all the
1907 // implementations thus found, for compatibility with old resolve pass.
1909 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1910 where F: FnOnce(&mut Resolver)
1912 let orig_module = self.current_module;
1914 // Move down in the graph.
1920 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1922 match orig_module.children.borrow().get(&name) {
1924 debug!("!!! (with scope) didn't find `{}` in `{}`",
1926 module_to_string(&*orig_module));
1928 Some(name_bindings) => {
1929 match name_bindings.type_ns.module() {
1931 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1933 module_to_string(&*orig_module));
1936 self.current_module = module_;
1946 self.current_module = orig_module;
1949 /// Searches the current set of local scopes for labels.
1950 /// Stops after meeting a closure.
1951 fn search_label(&self, name: Name) -> Option<DefLike> {
1952 for rib in self.label_ribs.iter().rev() {
1958 // Do not resolve labels across function boundary
1962 let result = rib.bindings.get(&name).cloned();
1963 if result.is_some() {
1970 fn resolve_crate(&mut self, krate: &hir::Crate) {
1971 debug!("(resolving crate) starting");
1973 intravisit::walk_crate(self, krate);
1976 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1977 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1978 span_err!(self.session,
1981 "user-defined types or type parameters cannot shadow the primitive types");
1985 fn resolve_item(&mut self, item: &Item) {
1986 let name = item.name;
1988 debug!("(resolving item) resolving {}", name);
1991 ItemEnum(_, ref generics) |
1992 ItemTy(_, ref generics) |
1993 ItemStruct(_, ref generics) => {
1994 self.check_if_primitive_type_name(name, item.span);
1996 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1997 |this| intravisit::walk_item(this, item));
1999 ItemFn(_, _, _, _, ref generics, _) => {
2000 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
2001 |this| intravisit::walk_item(this, item));
2004 ItemDefaultImpl(_, ref trait_ref) => {
2005 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
2007 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
2008 self.resolve_implementation(generics,
2015 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2016 self.check_if_primitive_type_name(name, item.span);
2018 // Create a new rib for the trait-wide type parameters.
2019 self.with_type_parameter_rib(HasTypeParameters(generics,
2023 let local_def_id = this.ast_map.local_def_id(item.id);
2024 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
2025 this.visit_generics(generics);
2026 walk_list!(this, visit_ty_param_bound, bounds);
2028 for trait_item in trait_items {
2029 match trait_item.node {
2030 hir::ConstTraitItem(_, ref default) => {
2031 // Only impose the restrictions of
2032 // ConstRibKind if there's an actual constant
2033 // expression in a provided default.
2034 if default.is_some() {
2035 this.with_constant_rib(|this| {
2036 intravisit::walk_trait_item(this, trait_item)
2039 intravisit::walk_trait_item(this, trait_item)
2042 hir::MethodTraitItem(ref sig, _) => {
2043 let type_parameters =
2044 HasTypeParameters(&sig.generics,
2047 this.with_type_parameter_rib(type_parameters, |this| {
2048 intravisit::walk_trait_item(this, trait_item)
2051 hir::TypeTraitItem(..) => {
2052 this.check_if_primitive_type_name(trait_item.name,
2054 this.with_type_parameter_rib(NoTypeParameters, |this| {
2055 intravisit::walk_trait_item(this, trait_item)
2064 ItemMod(_) | ItemForeignMod(_) => {
2065 self.with_scope(Some(name), |this| {
2066 intravisit::walk_item(this, item);
2070 ItemConst(..) | ItemStatic(..) => {
2071 self.with_constant_rib(|this| {
2072 intravisit::walk_item(this, item);
2076 ItemUse(ref view_path) => {
2077 // check for imports shadowing primitive types
2078 let check_rename = |this: &Self, id, name| {
2079 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
2080 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2081 this.check_if_primitive_type_name(name, item.span);
2087 match view_path.node {
2088 hir::ViewPathSimple(name, _) => {
2089 check_rename(self, item.id, name);
2091 hir::ViewPathList(ref prefix, ref items) => {
2093 if let Some(name) = item.node.rename() {
2094 check_rename(self, item.node.id(), name);
2098 // Resolve prefix of an import with empty braces (issue #28388)
2099 if items.is_empty() && !prefix.segments.is_empty() {
2100 match self.resolve_crate_relative_path(prefix.span,
2104 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2108 ResolutionError::FailedToResolve(
2109 &path_names_to_string(prefix, 0)));
2110 self.record_def(item.id, err_path_resolution());
2119 ItemExternCrate(_) => {
2120 // do nothing, these are just around to be encoded
2125 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2126 where F: FnOnce(&mut Resolver)
2128 match type_parameters {
2129 HasTypeParameters(generics, space, rib_kind) => {
2130 let mut function_type_rib = Rib::new(rib_kind);
2131 let mut seen_bindings = HashSet::new();
2132 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2133 let name = type_parameter.name;
2134 debug!("with_type_parameter_rib: {}", type_parameter.id);
2136 if seen_bindings.contains(&name) {
2138 type_parameter.span,
2139 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2141 seen_bindings.insert(name);
2143 // plain insert (no renaming)
2144 function_type_rib.bindings
2146 DlDef(DefTyParam(space,
2149 .local_def_id(type_parameter.id),
2152 self.type_ribs.push(function_type_rib);
2155 NoTypeParameters => {
2162 match type_parameters {
2163 HasTypeParameters(..) => {
2165 self.type_ribs.pop();
2168 NoTypeParameters => {}
2172 fn with_label_rib<F>(&mut self, f: F)
2173 where F: FnOnce(&mut Resolver)
2175 self.label_ribs.push(Rib::new(NormalRibKind));
2178 self.label_ribs.pop();
2182 fn with_constant_rib<F>(&mut self, f: F)
2183 where F: FnOnce(&mut Resolver)
2185 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2186 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2189 self.type_ribs.pop();
2190 self.value_ribs.pop();
2194 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2195 // Create a value rib for the function.
2196 self.value_ribs.push(Rib::new(rib_kind));
2198 // Create a label rib for the function.
2199 self.label_ribs.push(Rib::new(rib_kind));
2201 // Add each argument to the rib.
2202 let mut bindings_list = HashMap::new();
2203 for argument in &declaration.inputs {
2204 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2206 self.visit_ty(&*argument.ty);
2208 debug!("(resolving function) recorded argument");
2210 intravisit::walk_fn_ret_ty(self, &declaration.output);
2212 // Resolve the function body.
2213 self.visit_block(block);
2215 debug!("(resolving function) leaving function");
2218 self.label_ribs.pop();
2219 self.value_ribs.pop();
2223 fn resolve_trait_reference(&mut self,
2227 -> Result<PathResolution, ()> {
2228 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2229 if let DefTrait(_) = path_res.base_def {
2230 debug!("(resolving trait) found trait def: {:?}", path_res);
2234 resolve_struct_error(self,
2236 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2239 // If it's a typedef, give a note
2240 if let DefTy(..) = path_res.base_def {
2241 err.span_note(trait_path.span,
2242 "`type` aliases cannot be used for traits");
2250 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2256 fn resolve_generics(&mut self, generics: &Generics) {
2257 for type_parameter in generics.ty_params.iter() {
2258 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2260 for predicate in &generics.where_clause.predicates {
2262 &hir::WherePredicate::BoundPredicate(_) |
2263 &hir::WherePredicate::RegionPredicate(_) => {}
2264 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2265 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2266 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2267 self.record_def(eq_pred.id, path_res.unwrap());
2271 ResolutionError::UndeclaredAssociatedType);
2272 self.record_def(eq_pred.id, err_path_resolution());
2277 intravisit::walk_generics(self, generics);
2280 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2281 where F: FnOnce(&mut Resolver) -> T
2283 // Handle nested impls (inside fn bodies)
2284 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2285 let result = f(self);
2286 self.current_self_type = previous_value;
2290 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2291 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2293 let mut new_val = None;
2294 let mut new_id = None;
2295 if let Some(trait_ref) = opt_trait_ref {
2296 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2299 assert!(path_res.depth == 0);
2300 self.record_def(trait_ref.ref_id, path_res);
2301 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2302 new_id = Some(path_res.base_def.def_id());
2304 self.record_def(trait_ref.ref_id, err_path_resolution());
2306 intravisit::walk_trait_ref(self, trait_ref);
2308 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2309 let result = f(self, new_id);
2310 self.current_trait_ref = original_trait_ref;
2314 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2315 where F: FnOnce(&mut Resolver)
2317 let mut self_type_rib = Rib::new(NormalRibKind);
2319 // plain insert (no renaming, types are not currently hygienic....)
2320 let name = special_names::type_self;
2321 self_type_rib.bindings.insert(name, DlDef(self_def));
2322 self.type_ribs.push(self_type_rib);
2325 self.type_ribs.pop();
2329 fn resolve_implementation(&mut self,
2330 generics: &Generics,
2331 opt_trait_reference: &Option<TraitRef>,
2334 impl_items: &[ImplItem]) {
2335 // If applicable, create a rib for the type parameters.
2336 self.with_type_parameter_rib(HasTypeParameters(generics,
2340 // Resolve the type parameters.
2341 this.visit_generics(generics);
2343 // Resolve the trait reference, if necessary.
2344 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2345 // Resolve the self type.
2346 this.visit_ty(self_type);
2348 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2349 this.with_current_self_type(self_type, |this| {
2350 for impl_item in impl_items {
2351 match impl_item.node {
2352 hir::ImplItemKind::Const(..) => {
2353 // If this is a trait impl, ensure the const
2355 this.check_trait_item(impl_item.name,
2357 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2358 this.with_constant_rib(|this| {
2359 intravisit::walk_impl_item(this, impl_item);
2362 hir::ImplItemKind::Method(ref sig, _) => {
2363 // If this is a trait impl, ensure the method
2365 this.check_trait_item(impl_item.name,
2367 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2369 // We also need a new scope for the method-
2370 // specific type parameters.
2371 let type_parameters =
2372 HasTypeParameters(&sig.generics,
2375 this.with_type_parameter_rib(type_parameters, |this| {
2376 intravisit::walk_impl_item(this, impl_item);
2379 hir::ImplItemKind::Type(ref ty) => {
2380 // If this is a trait impl, ensure the type
2382 this.check_trait_item(impl_item.name,
2384 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2396 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2397 where F: FnOnce(Name, &str) -> ResolutionError
2399 // If there is a TraitRef in scope for an impl, then the method must be in the
2401 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2402 if !self.trait_item_map.contains_key(&(name, did)) {
2403 let path_str = path_names_to_string(&trait_ref.path, 0);
2404 resolve_error(self, span, err(name, &*path_str));
2409 fn resolve_local(&mut self, local: &Local) {
2410 // Resolve the type.
2411 walk_list!(self, visit_ty, &local.ty);
2413 // Resolve the initializer.
2414 walk_list!(self, visit_expr, &local.init);
2416 // Resolve the pattern.
2417 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2420 // build a map from pattern identifiers to binding-info's.
2421 // this is done hygienically. This could arise for a macro
2422 // that expands into an or-pattern where one 'x' was from the
2423 // user and one 'x' came from the macro.
2424 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2425 let mut result = HashMap::new();
2426 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2427 let name = path1.node;
2431 binding_mode: binding_mode,
2437 // check that all of the arms in an or-pattern have exactly the
2438 // same set of bindings, with the same binding modes for each.
2439 fn check_consistent_bindings(&mut self, arm: &Arm) {
2440 if arm.pats.is_empty() {
2443 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2444 for (i, p) in arm.pats.iter().enumerate() {
2445 let map_i = self.binding_mode_map(&**p);
2447 for (&key, &binding_0) in &map_0 {
2448 match map_i.get(&key) {
2452 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2454 Some(binding_i) => {
2455 if binding_0.binding_mode != binding_i.binding_mode {
2458 ResolutionError::VariableBoundWithDifferentMode(key,
2465 for (&key, &binding) in &map_i {
2466 if !map_0.contains_key(&key) {
2469 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2475 fn resolve_arm(&mut self, arm: &Arm) {
2476 self.value_ribs.push(Rib::new(NormalRibKind));
2478 let mut bindings_list = HashMap::new();
2479 for pattern in &arm.pats {
2480 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2483 // This has to happen *after* we determine which
2484 // pat_idents are variants
2485 self.check_consistent_bindings(arm);
2487 walk_list!(self, visit_expr, &arm.guard);
2488 self.visit_expr(&*arm.body);
2491 self.value_ribs.pop();
2495 fn resolve_block(&mut self, block: &Block) {
2496 debug!("(resolving block) entering block");
2497 self.value_ribs.push(Rib::new(NormalRibKind));
2499 // Move down in the graph, if there's an anonymous module rooted here.
2500 let orig_module = self.current_module;
2501 match orig_module.anonymous_children.borrow().get(&block.id) {
2505 Some(anonymous_module) => {
2506 debug!("(resolving block) found anonymous module, moving down");
2507 self.current_module = anonymous_module;
2511 // Check for imports appearing after non-item statements.
2512 let mut found_non_item = false;
2513 for statement in &block.stmts {
2514 if let hir::StmtDecl(ref declaration, _) = statement.node {
2515 if let hir::DeclItem(i) = declaration.node {
2516 let i = self.ast_map.expect_item(i.id);
2518 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2519 span_err!(self.session,
2522 "imports are not allowed after non-item statements");
2527 found_non_item = true
2530 found_non_item = true;
2534 // Descend into the block.
2535 intravisit::walk_block(self, block);
2539 self.current_module = orig_module;
2540 self.value_ribs.pop();
2542 debug!("(resolving block) leaving block");
2545 fn resolve_type(&mut self, ty: &Ty) {
2547 TyPath(ref maybe_qself, ref path) => {
2548 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2549 maybe_qself.as_ref(),
2553 // `<T>::a::b::c` is resolved by typeck alone.
2554 TypecheckRequired => {
2555 // Resolve embedded types.
2556 intravisit::walk_ty(self, ty);
2559 ResolveAttempt(resolution) => resolution,
2562 // This is a path in the type namespace. Walk through scopes
2566 // Write the result into the def map.
2567 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2568 path_names_to_string(path, 0),
2571 self.record_def(ty.id, def);
2574 self.record_def(ty.id, err_path_resolution());
2576 // Keep reporting some errors even if they're ignored above.
2577 self.resolve_path(ty.id, path, 0, TypeNS, true);
2579 let kind = if maybe_qself.is_some() {
2585 let self_type_name = special_idents::type_self.name;
2586 let is_invalid_self_type_name = path.segments.len() > 0 &&
2587 maybe_qself.is_none() &&
2588 path.segments[0].identifier.name ==
2590 if is_invalid_self_type_name {
2593 ResolutionError::SelfUsedOutsideImplOrTrait);
2597 ResolutionError::UseOfUndeclared(
2599 &*path_names_to_string(path,
2608 // Resolve embedded types.
2609 intravisit::walk_ty(self, ty);
2612 fn resolve_pattern(&mut self,
2614 mode: PatternBindingMode,
2615 // Maps idents to the node ID for the (outermost)
2616 // pattern that binds them
2617 bindings_list: &mut HashMap<Name, NodeId>) {
2618 let pat_id = pattern.id;
2619 walk_pat(pattern, |pattern| {
2620 match pattern.node {
2621 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2622 // The meaning of PatIdent with no type parameters
2623 // depends on whether an enum variant or unit-like struct
2624 // with that name is in scope. The probing lookup has to
2625 // be careful not to emit spurious errors. Only matching
2626 // patterns (match) can match nullary variants or
2627 // unit-like structs. For binding patterns (let
2628 // and the LHS of @-patterns), matching such a value is
2629 // simply disallowed (since it's rarely what you want).
2630 let const_ok = mode == RefutableMode && at_rhs.is_none();
2632 let ident = path1.node;
2633 let renamed = ident.name;
2635 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2637 FoundStructOrEnumVariant(def, lp) if const_ok => {
2638 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2641 self.enforce_default_binding_mode(pattern,
2644 self.record_def(pattern.id,
2651 FoundStructOrEnumVariant(..) => {
2655 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2658 self.record_def(pattern.id, err_path_resolution());
2660 FoundConst(def, lp, _) if const_ok => {
2661 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2663 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2664 self.record_def(pattern.id,
2671 FoundConst(def, _, name) => {
2675 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2678 self.record_def(pattern.id, err_path_resolution());
2680 BareIdentifierPatternUnresolved => {
2681 debug!("(resolving pattern) binding `{}`", renamed);
2683 let def_id = self.ast_map.local_def_id(pattern.id);
2684 let def = DefLocal(def_id, pattern.id);
2686 // Record the definition so that later passes
2687 // will be able to distinguish variants from
2688 // locals in patterns.
2690 self.record_def(pattern.id,
2693 last_private: LastMod(AllPublic),
2697 // Add the binding to the local ribs, if it
2698 // doesn't already exist in the bindings list. (We
2699 // must not add it if it's in the bindings list
2700 // because that breaks the assumptions later
2701 // passes make about or-patterns.)
2702 if !bindings_list.contains_key(&renamed) {
2703 let this = &mut *self;
2704 let last_rib = this.value_ribs.last_mut().unwrap();
2705 last_rib.bindings.insert(renamed, DlDef(def));
2706 bindings_list.insert(renamed, pat_id);
2707 } else if mode == ArgumentIrrefutableMode &&
2708 bindings_list.contains_key(&renamed) {
2709 // Forbid duplicate bindings in the same
2714 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2715 &ident.name.as_str())
2717 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2718 // Then this is a duplicate variable in the
2719 // same disjunction, which is an error.
2723 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2724 &ident.name.as_str())
2727 // Else, not bound in the same pattern: do
2733 PatEnum(ref path, _) => {
2734 // This must be an enum variant, struct or const.
2735 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2740 // The below shouldn't happen because all
2741 // qualified paths should be in PatQPath.
2742 TypecheckRequired =>
2743 self.session.span_bug(path.span,
2744 "resolve_possibly_assoc_item claimed
2746 that a path in PatEnum requires typecheck
2748 to resolve, but qualified paths should be
2751 ResolveAttempt(resolution) => resolution,
2753 if let Some(path_res) = resolution {
2754 match path_res.base_def {
2755 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2756 self.record_def(pattern.id, path_res);
2759 resolve_error(&self,
2761 ResolutionError::StaticVariableReference);
2762 self.record_def(pattern.id, err_path_resolution());
2765 // If anything ends up here entirely resolved,
2766 // it's an error. If anything ends up here
2767 // partially resolved, that's OK, because it may
2768 // be a `T::CONST` that typeck will resolve.
2769 if path_res.depth == 0 {
2773 ResolutionError::NotAnEnumVariantStructOrConst(
2781 self.record_def(pattern.id, err_path_resolution());
2783 let const_name = path.segments
2788 let traits = self.get_traits_containing_item(const_name);
2789 self.trait_map.insert(pattern.id, traits);
2790 self.record_def(pattern.id, path_res);
2798 ResolutionError::UnresolvedEnumVariantStructOrConst(
2799 &path.segments.last().unwrap().identifier.name.as_str())
2801 self.record_def(pattern.id, err_path_resolution());
2803 intravisit::walk_path(self, path);
2806 PatQPath(ref qself, ref path) => {
2807 // Associated constants only.
2808 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2813 TypecheckRequired => {
2814 // All `<T>::CONST` should end up here, and will
2815 // require use of the trait map to resolve
2816 // during typechecking.
2817 let const_name = path.segments
2822 let traits = self.get_traits_containing_item(const_name);
2823 self.trait_map.insert(pattern.id, traits);
2824 intravisit::walk_pat(self, pattern);
2827 ResolveAttempt(resolution) => resolution,
2829 if let Some(path_res) = resolution {
2830 match path_res.base_def {
2831 // All `<T as Trait>::CONST` should end up here, and
2832 // have the trait already selected.
2833 DefAssociatedConst(..) => {
2834 self.record_def(pattern.id, path_res);
2840 ResolutionError::NotAnAssociatedConst(
2841 &path.segments.last().unwrap().identifier.name.as_str()
2844 self.record_def(pattern.id, err_path_resolution());
2850 ResolutionError::UnresolvedAssociatedConst(&path.segments
2856 self.record_def(pattern.id, err_path_resolution());
2858 intravisit::walk_pat(self, pattern);
2861 PatStruct(ref path, _, _) => {
2862 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2863 Some(definition) => {
2864 self.record_def(pattern.id, definition);
2867 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2871 ResolutionError::DoesNotNameAStruct(
2872 &*path_names_to_string(path, 0))
2874 self.record_def(pattern.id, err_path_resolution());
2877 intravisit::walk_path(self, path);
2880 PatLit(_) | PatRange(..) => {
2881 intravisit::walk_pat(self, pattern);
2892 fn resolve_bare_identifier_pattern(&mut self,
2895 -> BareIdentifierPatternResolution {
2896 let module = self.current_module;
2897 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2898 Success((target, _)) => {
2899 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2901 target.binding.borrow());
2902 match target.binding.def() {
2904 panic!("resolved name in the value namespace to a set of name bindings \
2907 // For the two success cases, this lookup can be
2908 // considered as not having a private component because
2909 // the lookup happened only within the current module.
2910 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2911 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2913 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2914 return FoundConst(def, LastMod(AllPublic), name);
2916 Some(DefStatic(..)) => {
2917 resolve_error(self, span, ResolutionError::StaticVariableReference);
2918 return BareIdentifierPatternUnresolved;
2920 _ => return BareIdentifierPatternUnresolved
2925 panic!("unexpected indeterminate result");
2929 Some((span, msg)) => {
2930 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2935 debug!("(resolve bare identifier pattern) failed to find {}", name);
2936 return BareIdentifierPatternUnresolved;
2941 /// Handles paths that may refer to associated items
2942 fn resolve_possibly_assoc_item(&mut self,
2944 maybe_qself: Option<&hir::QSelf>,
2946 namespace: Namespace,
2948 -> AssocItemResolveResult {
2949 let max_assoc_types;
2953 if qself.position == 0 {
2954 return TypecheckRequired;
2956 max_assoc_types = path.segments.len() - qself.position;
2957 // Make sure the trait is valid.
2958 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2961 max_assoc_types = path.segments.len();
2965 let mut resolution = self.with_no_errors(|this| {
2966 this.resolve_path(id, path, 0, namespace, check_ribs)
2968 for depth in 1..max_assoc_types {
2969 if resolution.is_some() {
2972 self.with_no_errors(|this| {
2973 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2976 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2977 // A module is not a valid type or value.
2980 ResolveAttempt(resolution)
2983 /// If `check_ribs` is true, checks the local definitions first; i.e.
2984 /// doesn't skip straight to the containing module.
2985 /// Skips `path_depth` trailing segments, which is also reflected in the
2986 /// returned value. See `middle::def::PathResolution` for more info.
2987 pub fn resolve_path(&mut self,
2991 namespace: Namespace,
2993 -> Option<PathResolution> {
2994 let span = path.span;
2995 let segments = &path.segments[..path.segments.len() - path_depth];
2997 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
3000 let def = self.resolve_crate_relative_path(span, segments, namespace);
3001 return def.map(mk_res);
3004 // Try to find a path to an item in a module.
3005 let last_ident = segments.last().unwrap().identifier;
3006 if segments.len() <= 1 {
3007 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
3008 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
3010 PathResolution::new(def, LastMod(AllPublic), path_depth)
3014 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
3015 let def = self.resolve_module_relative_path(span, segments, namespace);
3016 match (def, unqualified_def) {
3017 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
3019 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3022 "unnecessary qualification".to_string());
3030 // Resolve a single identifier
3031 fn resolve_identifier(&mut self,
3032 identifier: hir::Ident,
3033 namespace: Namespace,
3036 -> Option<LocalDef> {
3037 // First, check to see whether the name is a primitive type.
3038 if namespace == TypeNS {
3039 if let Some(&prim_ty) = self.primitive_type_table
3041 .get(&identifier.unhygienic_name) {
3042 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
3047 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
3052 let name = identifier.unhygienic_name;
3053 self.resolve_item_by_name_in_lexical_scope(name, namespace, record_used)
3054 .map(LocalDef::from_def)
3057 // Resolve a local definition, potentially adjusting for closures.
3058 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
3059 let ribs = match local_def.ribs {
3060 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
3061 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
3064 let mut def = local_def.def;
3067 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
3069 DefLocal(_, node_id) => {
3073 // Nothing to do. Continue.
3075 ClosureRibKind(function_id) => {
3077 let node_def_id = self.ast_map.local_def_id(node_id);
3079 let seen = self.freevars_seen
3081 .or_insert_with(|| NodeMap());
3082 if let Some(&index) = seen.get(&node_id) {
3083 def = DefUpvar(node_def_id, node_id, index, function_id);
3086 let vec = self.freevars
3088 .or_insert_with(|| vec![]);
3089 let depth = vec.len();
3095 def = DefUpvar(node_def_id, node_id, depth, function_id);
3096 seen.insert(node_id, depth);
3098 ItemRibKind | MethodRibKind => {
3099 // This was an attempt to access an upvar inside a
3100 // named function item. This is not allowed, so we
3104 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3107 ConstantItemRibKind => {
3108 // Still doesn't deal with upvars
3111 ResolutionError::AttemptToUseNonConstantValueInConstant);
3117 DefTyParam(..) | DefSelfTy(..) => {
3120 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3121 // Nothing to do. Continue.
3124 // This was an attempt to use a type parameter outside
3129 ResolutionError::TypeParametersFromOuterFunction);
3132 ConstantItemRibKind => {
3134 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3145 // resolve a "module-relative" path, e.g. a::b::c
3146 fn resolve_module_relative_path(&mut self,
3148 segments: &[hir::PathSegment],
3149 namespace: Namespace)
3150 -> Option<(Def, LastPrivate)> {
3151 let module_path = segments.split_last()
3155 .map(|ps| ps.identifier.name)
3156 .collect::<Vec<_>>();
3158 let containing_module;
3160 let current_module = self.current_module;
3161 match self.resolve_module_path(current_module,
3167 let (span, msg) = match err {
3168 Some((span, msg)) => (span, msg),
3170 let msg = format!("Use of undeclared type or module `{}`",
3171 names_to_string(&module_path));
3176 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3179 Indeterminate => panic!("indeterminate unexpected"),
3180 Success((resulting_module, resulting_last_private)) => {
3181 containing_module = resulting_module;
3182 last_private = resulting_last_private;
3186 let name = segments.last().unwrap().identifier.name;
3187 let def = match self.resolve_name_in_module(containing_module,
3190 NameSearchType::PathSearch,
3192 Success((Target { binding, .. }, _)) => {
3193 let (def, lp) = binding.def_and_lp();
3194 (def, last_private.or(lp))
3198 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3199 self.used_crates.insert(kid);
3204 /// Invariant: This must be called only during main resolution, not during
3205 /// import resolution.
3206 fn resolve_crate_relative_path(&mut self,
3208 segments: &[hir::PathSegment],
3209 namespace: Namespace)
3210 -> Option<(Def, LastPrivate)> {
3211 let module_path = segments.split_last()
3215 .map(|ps| ps.identifier.name)
3216 .collect::<Vec<_>>();
3218 let root_module = self.graph_root;
3220 let containing_module;
3222 match self.resolve_module_path_from_root(root_module,
3227 LastMod(AllPublic)) {
3229 let (span, msg) = match err {
3230 Some((span, msg)) => (span, msg),
3232 let msg = format!("Use of undeclared module `::{}`",
3233 names_to_string(&module_path[..]));
3238 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3243 panic!("indeterminate unexpected");
3246 Success((resulting_module, resulting_last_private)) => {
3247 containing_module = resulting_module;
3248 last_private = resulting_last_private;
3252 let name = segments.last().unwrap().identifier.name;
3253 match self.resolve_name_in_module(containing_module,
3256 NameSearchType::PathSearch,
3258 Success((Target { binding, .. }, _)) => {
3259 let (def, lp) = binding.def_and_lp();
3260 Some((def, last_private.or(lp)))
3266 fn resolve_identifier_in_local_ribs(&mut self,
3268 namespace: Namespace)
3269 -> Option<LocalDef> {
3270 // Check the local set of ribs.
3271 let (name, ribs) = match namespace {
3272 ValueNS => (ident.name, &self.value_ribs),
3273 TypeNS => (ident.unhygienic_name, &self.type_ribs),
3276 for (i, rib) in ribs.iter().enumerate().rev() {
3277 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3280 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3284 return Some(LocalDef {
3285 ribs: Some((namespace, i)),
3290 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3302 fn resolve_item_by_name_in_lexical_scope(&mut self,
3304 namespace: Namespace,
3308 let module = self.current_module;
3309 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
3310 Success((target, _)) => {
3311 match target.binding.def() {
3313 // This can happen if we were looking for a type and
3314 // found a module instead. Modules don't have defs.
3315 debug!("(resolving item path by identifier in lexical scope) failed to \
3316 resolve {} after success...",
3321 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3323 // This lookup is "all public" because it only searched
3324 // for one identifier in the current module (couldn't
3325 // have passed through reexports or anything like that.
3331 panic!("unexpected indeterminate result");
3334 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3337 if let Some((span, msg)) = err {
3338 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3346 fn with_no_errors<T, F>(&mut self, f: F) -> T
3347 where F: FnOnce(&mut Resolver) -> T
3349 self.emit_errors = false;
3351 self.emit_errors = true;
3355 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3356 fn extract_path_and_node_id(t: &Ty,
3357 allow: FallbackChecks)
3358 -> Option<(Path, NodeId, FallbackChecks)> {
3360 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3361 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3362 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3363 // This doesn't handle the remaining `Ty` variants as they are not
3364 // that commonly the self_type, it might be interesting to provide
3365 // support for those in future.
3370 fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
3372 name_path: &[ast::Name])
3373 -> Option<Module<'a>> {
3374 let root = this.current_module;
3375 let last_name = name_path.last().unwrap();
3377 if name_path.len() == 1 {
3378 match this.primitive_type_table.primitive_types.get(last_name) {
3381 match this.current_module.children.borrow().get(last_name) {
3382 Some(child) => child.type_ns.module(),
3388 match this.resolve_module_path(root,
3393 Success((module, _)) => Some(module),
3399 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3400 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3401 let sig = match this.ast_map.get(node_id) {
3402 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3403 hir::MethodTraitItem(ref sig, _) => sig,
3406 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3407 hir::ImplItemKind::Method(ref sig, _) => sig,
3412 sig.explicit_self.node == hir::SelfStatic
3414 this.session.cstore.is_static_method(did)
3418 let (path, node_id, allowed) = match self.current_self_type {
3419 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3421 None => return NoSuggestion,
3423 None => return NoSuggestion,
3426 if allowed == Everything {
3427 // Look for a field with the same name in the current self_type.
3428 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3429 Some(DefTy(did, _)) |
3430 Some(DefStruct(did)) |
3431 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3434 if fields.iter().any(|&field_name| name == field_name) {
3439 _ => {} // Self type didn't resolve properly
3443 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3445 // Look for a method in the current self type's impl module.
3446 if let Some(module) = get_module(self, path.span, &name_path) {
3447 if let Some(binding) = module.children.borrow().get(&name) {
3448 if let Some(DefMethod(did)) = binding.value_ns.def() {
3449 if is_static_method(self, did) {
3450 return StaticMethod(path_names_to_string(&path, 0));
3452 if self.current_trait_ref.is_some() {
3454 } else if allowed == Everything {
3461 // Look for a method in the current trait.
3462 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3463 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3464 if is_static_method(self, did) {
3465 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3475 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3476 if let Some(macro_name) = self.session.available_macros
3477 .borrow().iter().find(|n| n.as_str() == name) {
3478 return SuggestionType::Macro(format!("{}!", macro_name));
3481 let names = self.value_ribs
3484 .flat_map(|rib| rib.bindings.keys());
3486 if let Some(found) = find_best_match_for_name(names, name, None) {
3487 if name != &*found {
3488 return SuggestionType::Function(found);
3490 } SuggestionType::NotFound
3493 fn resolve_expr(&mut self, expr: &Expr) {
3494 // First, record candidate traits for this expression if it could
3495 // result in the invocation of a method call.
3497 self.record_candidate_traits_for_expr_if_necessary(expr);
3499 // Next, resolve the node.
3501 ExprPath(ref maybe_qself, ref path) => {
3502 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3503 maybe_qself.as_ref(),
3507 // `<T>::a::b::c` is resolved by typeck alone.
3508 TypecheckRequired => {
3509 let method_name = path.segments.last().unwrap().identifier.name;
3510 let traits = self.get_traits_containing_item(method_name);
3511 self.trait_map.insert(expr.id, traits);
3512 intravisit::walk_expr(self, expr);
3515 ResolveAttempt(resolution) => resolution,
3518 // This is a local path in the value namespace. Walk through
3519 // scopes looking for it.
3520 if let Some(path_res) = resolution {
3521 // Check if struct variant
3522 if let DefVariant(_, _, true) = path_res.base_def {
3523 let path_name = path_names_to_string(path, 0);
3525 let mut err = resolve_struct_error(self,
3527 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3529 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3531 if self.emit_errors {
3532 err.fileline_help(expr.span, &msg);
3534 err.span_help(expr.span, &msg);
3537 self.record_def(expr.id, err_path_resolution());
3539 // Write the result into the def map.
3540 debug!("(resolving expr) resolved `{}`",
3541 path_names_to_string(path, 0));
3543 // Partial resolutions will need the set of traits in scope,
3544 // so they can be completed during typeck.
3545 if path_res.depth != 0 {
3546 let method_name = path.segments.last().unwrap().identifier.name;
3547 let traits = self.get_traits_containing_item(method_name);
3548 self.trait_map.insert(expr.id, traits);
3551 self.record_def(expr.id, path_res);
3554 // Be helpful if the name refers to a struct
3555 // (The pattern matching def_tys where the id is in self.structs
3556 // matches on regular structs while excluding tuple- and enum-like
3557 // structs, which wouldn't result in this error.)
3558 let path_name = path_names_to_string(path, 0);
3559 let type_res = self.with_no_errors(|this| {
3560 this.resolve_path(expr.id, path, 0, TypeNS, false)
3563 self.record_def(expr.id, err_path_resolution());
3564 match type_res.map(|r| r.base_def) {
3565 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3566 let mut err = resolve_struct_error(self,
3568 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3570 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3572 if self.emit_errors {
3573 err.fileline_help(expr.span, &msg);
3575 err.span_help(expr.span, &msg);
3580 // Keep reporting some errors even if they're ignored above.
3581 self.resolve_path(expr.id, path, 0, ValueNS, true);
3583 let mut method_scope = false;
3584 self.value_ribs.iter().rev().all(|rib| {
3585 method_scope = match rib.kind {
3586 MethodRibKind => true,
3587 ItemRibKind | ConstantItemRibKind => false,
3588 _ => return true, // Keep advancing
3590 false // Stop advancing
3593 if method_scope && special_names::self_.as_str() == &path_name[..] {
3596 ResolutionError::SelfNotAvailableInStaticMethod);
3598 let last_name = path.segments.last().unwrap().identifier.name;
3599 let mut msg = match self.find_fallback_in_self_type(last_name) {
3601 // limit search to 5 to reduce the number
3602 // of stupid suggestions
3603 match self.find_best_match(&path_name) {
3604 SuggestionType::Macro(s) => {
3605 format!("the macro `{}`", s)
3607 SuggestionType::Function(s) => format!("`{}`", s),
3608 SuggestionType::NotFound => "".to_string(),
3611 Field => format!("`self.{}`", path_name),
3613 TraitItem => format!("to call `self.{}`", path_name),
3614 TraitMethod(path_str) |
3615 StaticMethod(path_str) =>
3616 format!("to call `{}::{}`", path_str, path_name),
3619 let mut context = UnresolvedNameContext::Other;
3620 if !msg.is_empty() {
3621 msg = format!(". Did you mean {}?", msg);
3623 // we check if this a module and if so, we display a help
3625 let name_path = path.segments.iter()
3626 .map(|seg| seg.identifier.name)
3627 .collect::<Vec<_>>();
3628 let current_module = self.current_module;
3630 match self.resolve_module_path(current_module,
3636 context = UnresolvedNameContext::PathIsMod(expr.id);
3644 ResolutionError::UnresolvedName(
3645 &*path_name, &*msg, context));
3651 intravisit::walk_expr(self, expr);
3654 ExprStruct(ref path, _, _) => {
3655 // Resolve the path to the structure it goes to. We don't
3656 // check to ensure that the path is actually a structure; that
3657 // is checked later during typeck.
3658 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3659 Some(definition) => self.record_def(expr.id, definition),
3661 debug!("(resolving expression) didn't find struct def",);
3665 ResolutionError::DoesNotNameAStruct(
3666 &*path_names_to_string(path, 0))
3668 self.record_def(expr.id, err_path_resolution());
3672 intravisit::walk_expr(self, expr);
3675 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3676 self.with_label_rib(|this| {
3677 let def_like = DlDef(DefLabel(expr.id));
3680 let rib = this.label_ribs.last_mut().unwrap();
3681 rib.bindings.insert(label.name, def_like);
3684 intravisit::walk_expr(this, expr);
3688 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3689 match self.search_label(label.node.name) {
3691 self.record_def(expr.id, err_path_resolution());
3694 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3696 Some(DlDef(def @ DefLabel(_))) => {
3697 // Since this def is a label, it is never read.
3698 self.record_def(expr.id,
3701 last_private: LastMod(AllPublic),
3706 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3712 intravisit::walk_expr(self, expr);
3717 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3719 ExprField(_, name) => {
3720 // FIXME(#6890): Even though you can't treat a method like a
3721 // field, we need to add any trait methods we find that match
3722 // the field name so that we can do some nice error reporting
3723 // later on in typeck.
3724 let traits = self.get_traits_containing_item(name.node);
3725 self.trait_map.insert(expr.id, traits);
3727 ExprMethodCall(name, _, _) => {
3728 debug!("(recording candidate traits for expr) recording traits for {}",
3730 let traits = self.get_traits_containing_item(name.node);
3731 self.trait_map.insert(expr.id, traits);
3739 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3740 debug!("(getting traits containing item) looking for '{}'", name);
3742 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3743 debug!("(adding trait info) found trait {:?} for method '{}'",
3746 found_traits.push(trait_def_id);
3749 let mut found_traits = Vec::new();
3750 let mut search_module = self.current_module;
3752 // Look for the current trait.
3753 match self.current_trait_ref {
3754 Some((trait_def_id, _)) => {
3755 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3756 add_trait_info(&mut found_traits, trait_def_id, name);
3759 None => {} // Nothing to do.
3762 // Look for trait children.
3763 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3766 for (_, child_names) in search_module.children.borrow().iter() {
3767 let def = match child_names.type_ns.def() {
3771 let trait_def_id = match def {
3772 DefTrait(trait_def_id) => trait_def_id,
3775 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3776 add_trait_info(&mut found_traits, trait_def_id, name);
3781 // Look for imports.
3782 for (_, import) in search_module.import_resolutions.borrow().iter() {
3783 let target = match import.type_ns.target {
3785 Some(ref target) => target,
3787 let did = match target.binding.def() {
3788 Some(DefTrait(trait_def_id)) => trait_def_id,
3789 Some(..) | None => continue,
3791 if self.trait_item_map.contains_key(&(name, did)) {
3792 add_trait_info(&mut found_traits, did, name);
3793 let id = import.type_ns.id;
3794 self.used_imports.insert((id, TypeNS));
3795 let trait_name = self.get_trait_name(did);
3796 self.record_import_use(id, trait_name);
3797 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3798 self.used_crates.insert(kid);
3803 match search_module.parent_link {
3804 NoParentLink | ModuleParentLink(..) => break,
3805 BlockParentLink(parent_module, _) => {
3806 search_module = parent_module;
3814 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3815 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3816 assert!(match resolution.last_private {
3817 LastImport{..} => false,
3820 "Import should only be used for `use` directives");
3822 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3823 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3824 self.session.span_bug(span,
3825 &format!("path resolved multiple times ({:?} before, {:?} now)",
3831 fn enforce_default_binding_mode(&mut self,
3833 pat_binding_mode: BindingMode,
3835 match pat_binding_mode {
3836 BindByValue(_) => {}
3840 ResolutionError::CannotUseRefBindingModeWith(descr));
3848 // Diagnostics are not particularly efficient, because they're rarely
3852 #[allow(dead_code)] // useful for debugging
3853 fn dump_module(&mut self, module_: Module<'a>) {
3854 debug!("Dump of module `{}`:", module_to_string(&*module_));
3856 debug!("Children:");
3857 build_reduced_graph::populate_module_if_necessary(self, &module_);
3858 for (&name, _) in module_.children.borrow().iter() {
3859 debug!("* {}", name);
3862 debug!("Import resolutions:");
3863 let import_resolutions = module_.import_resolutions.borrow();
3864 for (&name, import_resolution) in import_resolutions.iter() {
3866 match import_resolution.value_ns.target {
3868 value_repr = "".to_string();
3871 value_repr = " value:?".to_string();
3877 match import_resolution.type_ns.target {
3879 type_repr = "".to_string();
3882 type_repr = " type:?".to_string();
3887 debug!("* {}:{}{}", name, value_repr, type_repr);
3893 fn names_to_string(names: &[Name]) -> String {
3894 let mut first = true;
3895 let mut result = String::new();
3900 result.push_str("::")
3902 result.push_str(&name.as_str());
3907 fn path_names_to_string(path: &Path, depth: usize) -> String {
3908 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3910 .map(|seg| seg.identifier.name)
3912 names_to_string(&names[..])
3915 /// A somewhat inefficient routine to obtain the name of a module.
3916 fn module_to_string<'a>(module: Module<'a>) -> String {
3917 let mut names = Vec::new();
3919 fn collect_mod<'a>(names: &mut Vec<ast::Name>, module: Module<'a>) {
3920 match module.parent_link {
3922 ModuleParentLink(ref module, name) => {
3924 collect_mod(names, module);
3926 BlockParentLink(ref module, _) => {
3927 // danger, shouldn't be ident?
3928 names.push(special_idents::opaque.name);
3929 collect_mod(names, module);
3933 collect_mod(&mut names, module);
3935 if names.is_empty() {
3936 return "???".to_string();
3938 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3941 fn err_path_resolution() -> PathResolution {
3944 last_private: LastMod(AllPublic),
3950 pub struct CrateMap {
3951 pub def_map: RefCell<DefMap>,
3952 pub freevars: FreevarMap,
3953 pub export_map: ExportMap,
3954 pub trait_map: TraitMap,
3955 pub external_exports: ExternalExports,
3956 pub glob_map: Option<GlobMap>,
3959 #[derive(PartialEq,Copy, Clone)]
3960 pub enum MakeGlobMap {
3965 /// Entry point to crate resolution.
3966 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3967 ast_map: &'a hir_map::Map<'tcx>,
3968 make_glob_map: MakeGlobMap)
3970 let krate = ast_map.krate();
3971 let arenas = Resolver::arenas();
3972 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3974 resolver.resolve_crate(krate);
3976 check_unused::check_crate(&mut resolver, krate);
3979 def_map: resolver.def_map,
3980 freevars: resolver.freevars,
3981 export_map: resolver.export_map,
3982 trait_map: resolver.trait_map,
3983 external_exports: resolver.external_exports,
3984 glob_map: if resolver.make_glob_map {
3985 Some(resolver.glob_map)
3992 /// Builds a name resolution walker to be used within this module,
3993 /// or used externally, with an optional callback function.
3995 /// The callback takes a &mut bool which allows callbacks to end a
3996 /// walk when set to true, passing through the rest of the walk, while
3997 /// preserving the ribs + current module. This allows resolve_path
3998 /// calls to be made with the correct scope info. The node in the
3999 /// callback corresponds to the current node in the walk.
4000 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
4001 ast_map: &'a hir_map::Map<'tcx>,
4003 make_glob_map: MakeGlobMap,
4004 arenas: &'a ResolverArenas<'a>,
4005 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
4006 -> Resolver<'a, 'tcx> {
4007 let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
4009 resolver.callback = callback;
4011 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4012 session.abort_if_errors();
4014 resolve_imports::resolve_imports(&mut resolver);
4015 session.abort_if_errors();
4017 record_exports::record(&mut resolver);
4018 session.abort_if_errors();
4023 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }