1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
19 #![feature(associated_consts)]
20 #![feature(borrow_state)]
21 #![feature(rustc_diagnostic_macros)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
31 extern crate rustc_bitflags;
32 extern crate rustc_front;
35 use self::PatternBindingMode::*;
36 use self::Namespace::*;
37 use self::NamespaceResult::*;
38 use self::ResolveResult::*;
39 use self::FallbackSuggestion::*;
40 use self::TypeParameters::*;
42 use self::UseLexicalScopeFlag::*;
43 use self::ModulePrefixResult::*;
44 use self::AssocItemResolveResult::*;
45 use self::NameSearchType::*;
46 use self::BareIdentifierPatternResolution::*;
47 use self::ParentLink::*;
48 use self::FallbackChecks::*;
50 use rustc::front::map as hir_map;
51 use rustc::session::Session;
53 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
54 use rustc::middle::def::*;
55 use rustc::middle::def_id::DefId;
56 use rustc::middle::pat_util::pat_bindings;
57 use rustc::middle::privacy::*;
58 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
60 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
63 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
64 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
65 use syntax::attr::AttrMetaMethods;
66 use syntax::codemap::{self, Span, Pos};
67 use syntax::errors::DiagnosticBuilder;
68 use syntax::parse::token::{self, special_names, special_idents};
69 use syntax::util::lev_distance::find_best_match_for_name;
71 use rustc_front::intravisit::{self, FnKind, Visitor};
73 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
74 use rustc_front::hir::Crate;
75 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
76 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
77 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
78 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
79 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
80 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
81 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
82 use rustc_front::hir::Local;
83 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
84 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
85 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
86 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
87 use rustc_front::util::walk_pat;
89 use std::collections::{HashMap, HashSet};
90 use std::cell::{Cell, RefCell};
92 use std::mem::replace;
93 use std::rc::{Rc, Weak};
95 use resolve_imports::{Target, ImportDirective, ImportResolutionPerNamespace};
96 use resolve_imports::Shadowable;
98 // NB: This module needs to be declared first so diagnostics are
99 // registered before they are used.
104 mod build_reduced_graph;
107 // Perform the callback, not walking deeper if the return is true
108 macro_rules! execute_callback {
109 ($node: expr, $walker: expr) => (
110 if let Some(ref callback) = $walker.callback {
111 if callback($node, &mut $walker.resolved) {
118 enum SuggestionType {
120 Function(token::InternedString),
124 pub enum ResolutionError<'a> {
125 /// error E0401: can't use type parameters from outer function
126 TypeParametersFromOuterFunction,
127 /// error E0402: cannot use an outer type parameter in this context
128 OuterTypeParameterContext,
129 /// error E0403: the name is already used for a type parameter in this type parameter list
130 NameAlreadyUsedInTypeParameterList(Name),
131 /// error E0404: is not a trait
132 IsNotATrait(&'a str),
133 /// error E0405: use of undeclared trait name
134 UndeclaredTraitName(&'a str),
135 /// error E0406: undeclared associated type
136 UndeclaredAssociatedType,
137 /// error E0407: method is not a member of trait
138 MethodNotMemberOfTrait(Name, &'a str),
139 /// error E0437: type is not a member of trait
140 TypeNotMemberOfTrait(Name, &'a str),
141 /// error E0438: const is not a member of trait
142 ConstNotMemberOfTrait(Name, &'a str),
143 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
144 VariableNotBoundInPattern(Name, usize),
145 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
146 VariableBoundWithDifferentMode(Name, usize),
147 /// error E0410: variable from pattern is not bound in pattern #1
148 VariableNotBoundInParentPattern(Name, usize),
149 /// error E0411: use of `Self` outside of an impl or trait
150 SelfUsedOutsideImplOrTrait,
151 /// error E0412: use of undeclared
152 UseOfUndeclared(&'a str, &'a str),
153 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
154 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
155 /// error E0414: only irrefutable patterns allowed here
156 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
157 /// error E0415: identifier is bound more than once in this parameter list
158 IdentifierBoundMoreThanOnceInParameterList(&'a str),
159 /// error E0416: identifier is bound more than once in the same pattern
160 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
161 /// error E0417: static variables cannot be referenced in a pattern
162 StaticVariableReference,
163 /// error E0418: is not an enum variant, struct or const
164 NotAnEnumVariantStructOrConst(&'a str),
165 /// error E0419: unresolved enum variant, struct or const
166 UnresolvedEnumVariantStructOrConst(&'a str),
167 /// error E0420: is not an associated const
168 NotAnAssociatedConst(&'a str),
169 /// error E0421: unresolved associated const
170 UnresolvedAssociatedConst(&'a str),
171 /// error E0422: does not name a struct
172 DoesNotNameAStruct(&'a str),
173 /// error E0423: is a struct variant name, but this expression uses it like a function name
174 StructVariantUsedAsFunction(&'a str),
175 /// error E0424: `self` is not available in a static method
176 SelfNotAvailableInStaticMethod,
177 /// error E0425: unresolved name
178 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
179 /// error E0426: use of undeclared label
180 UndeclaredLabel(&'a str),
181 /// error E0427: cannot use `ref` binding mode with ...
182 CannotUseRefBindingModeWith(&'a str),
183 /// error E0428: duplicate definition
184 DuplicateDefinition(&'a str, Name),
185 /// error E0429: `self` imports are only allowed within a { } list
186 SelfImportsOnlyAllowedWithin,
187 /// error E0430: `self` import can only appear once in the list
188 SelfImportCanOnlyAppearOnceInTheList,
189 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
190 SelfImportOnlyInImportListWithNonEmptyPrefix,
191 /// error E0432: unresolved import
192 UnresolvedImport(Option<(&'a str, &'a str)>),
193 /// error E0433: failed to resolve
194 FailedToResolve(&'a str),
195 /// error E0434: can't capture dynamic environment in a fn item
196 CannotCaptureDynamicEnvironmentInFnItem,
197 /// error E0435: attempt to use a non-constant value in a constant
198 AttemptToUseNonConstantValueInConstant,
201 /// Context of where `ResolutionError::UnresolvedName` arose.
202 #[derive(Clone, PartialEq, Eq, Debug)]
203 pub enum UnresolvedNameContext {
204 /// `PathIsMod(id)` indicates that a given path, used in
205 /// expression context, actually resolved to a module rather than
206 /// a value. The `id` attached to the variant is the node id of
207 /// the erroneous path expression.
208 PathIsMod(ast::NodeId),
210 /// `Other` means we have no extra information about the context
211 /// of the unresolved name error. (Maybe we could eliminate all
212 /// such cases; but for now, this is an information-free default.)
216 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
217 span: syntax::codemap::Span,
218 resolution_error: ResolutionError<'b>) {
219 resolve_struct_error(resolver, span, resolution_error).emit();
222 fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
223 span: syntax::codemap::Span,
224 resolution_error: ResolutionError<'b>)
225 -> DiagnosticBuilder<'a> {
226 if !resolver.emit_errors {
227 return resolver.session.diagnostic().struct_dummy();
230 match resolution_error {
231 ResolutionError::TypeParametersFromOuterFunction => {
232 struct_span_err!(resolver.session,
235 "can't use type parameters from outer function; try using a local \
236 type parameter instead")
238 ResolutionError::OuterTypeParameterContext => {
239 struct_span_err!(resolver.session,
242 "cannot use an outer type parameter in this context")
244 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
245 struct_span_err!(resolver.session,
248 "the name `{}` is already used for a type parameter in this type \
252 ResolutionError::IsNotATrait(name) => {
253 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
255 ResolutionError::UndeclaredTraitName(name) => {
256 struct_span_err!(resolver.session,
259 "use of undeclared trait name `{}`",
262 ResolutionError::UndeclaredAssociatedType => {
263 struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
265 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
266 struct_span_err!(resolver.session,
269 "method `{}` is not a member of trait `{}`",
273 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
274 struct_span_err!(resolver.session,
277 "type `{}` is not a member of trait `{}`",
281 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
282 struct_span_err!(resolver.session,
285 "const `{}` is not a member of trait `{}`",
289 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
290 struct_span_err!(resolver.session,
293 "variable `{}` from pattern #1 is not bound in pattern #{}",
297 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
298 struct_span_err!(resolver.session,
301 "variable `{}` is bound with different mode in pattern #{} than in \
306 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
307 struct_span_err!(resolver.session,
310 "variable `{}` from pattern #{} is not bound in pattern #1",
314 ResolutionError::SelfUsedOutsideImplOrTrait => {
315 struct_span_err!(resolver.session,
318 "use of `Self` outside of an impl or trait")
320 ResolutionError::UseOfUndeclared(kind, name) => {
321 struct_span_err!(resolver.session,
324 "use of undeclared {} `{}`",
328 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
329 struct_span_err!(resolver.session,
332 "declaration of `{}` shadows an enum variant \
333 or unit-like struct in scope",
336 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
337 let mut err = struct_span_err!(resolver.session,
340 "only irrefutable patterns allowed here");
342 "there already is a constant in scope sharing the same \
343 name as this pattern");
344 if let Some(sp) = resolver.ast_map.span_if_local(did) {
345 err.span_note(sp, "constant defined here");
347 if let Some(directive) = resolver.current_module
351 let item = resolver.ast_map.expect_item(directive.value_ns.id);
352 err.span_note(item.span, "constant imported here");
356 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
357 struct_span_err!(resolver.session,
360 "identifier `{}` is bound more than once in this parameter list",
363 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
364 struct_span_err!(resolver.session,
367 "identifier `{}` is bound more than once in the same pattern",
370 ResolutionError::StaticVariableReference => {
371 struct_span_err!(resolver.session,
374 "static variables cannot be referenced in a pattern, use a \
377 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
378 struct_span_err!(resolver.session,
381 "`{}` is not an enum variant, struct or const",
384 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
385 struct_span_err!(resolver.session,
388 "unresolved enum variant, struct or const `{}`",
391 ResolutionError::NotAnAssociatedConst(name) => {
392 struct_span_err!(resolver.session,
395 "`{}` is not an associated const",
398 ResolutionError::UnresolvedAssociatedConst(name) => {
399 struct_span_err!(resolver.session,
402 "unresolved associated const `{}`",
405 ResolutionError::DoesNotNameAStruct(name) => {
406 struct_span_err!(resolver.session,
409 "`{}` does not name a structure",
412 ResolutionError::StructVariantUsedAsFunction(path_name) => {
413 struct_span_err!(resolver.session,
416 "`{}` is the name of a struct or struct variant, but this expression \
417 uses it like a function name",
420 ResolutionError::SelfNotAvailableInStaticMethod => {
421 struct_span_err!(resolver.session,
424 "`self` is not available in a static method. Maybe a `self` \
425 argument is missing?")
427 ResolutionError::UnresolvedName(path, msg, context) => {
428 let mut err = struct_span_err!(resolver.session,
431 "unresolved name `{}`{}",
436 UnresolvedNameContext::Other => { } // no help available
437 UnresolvedNameContext::PathIsMod(id) => {
438 let mut help_msg = String::new();
439 let parent_id = resolver.ast_map.get_parent_node(id);
440 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
442 ExprField(_, ident) => {
443 help_msg = format!("To reference an item from the \
444 `{module}` module, use \
445 `{module}::{ident}`",
449 ExprMethodCall(ident, _, _) => {
450 help_msg = format!("To call a function from the \
451 `{module}` module, use \
452 `{module}::{ident}(..)`",
457 help_msg = format!("No function corresponds to `{module}(..)`",
460 _ => { } // no help available
463 help_msg = format!("Module `{module}` cannot be the value of an expression",
467 if !help_msg.is_empty() {
468 err.fileline_help(span, &help_msg);
474 ResolutionError::UndeclaredLabel(name) => {
475 struct_span_err!(resolver.session,
478 "use of undeclared label `{}`",
481 ResolutionError::CannotUseRefBindingModeWith(descr) => {
482 struct_span_err!(resolver.session,
485 "cannot use `ref` binding mode with {}",
488 ResolutionError::DuplicateDefinition(namespace, name) => {
489 struct_span_err!(resolver.session,
492 "duplicate definition of {} `{}`",
496 ResolutionError::SelfImportsOnlyAllowedWithin => {
497 struct_span_err!(resolver.session,
501 "`self` imports are only allowed within a { } list")
503 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
504 struct_span_err!(resolver.session,
507 "`self` import can only appear once in the list")
509 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
510 struct_span_err!(resolver.session,
513 "`self` import can only appear in an import list with a \
516 ResolutionError::UnresolvedImport(name) => {
517 let msg = match name {
518 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
519 None => "unresolved import".to_owned(),
521 struct_span_err!(resolver.session, span, E0432, "{}", msg)
523 ResolutionError::FailedToResolve(msg) => {
524 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
526 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
527 struct_span_err!(resolver.session,
531 "can't capture dynamic environment in a fn item; use the || { ... } \
532 closure form instead")
534 ResolutionError::AttemptToUseNonConstantValueInConstant => {
535 struct_span_err!(resolver.session,
538 "attempt to use a non-constant value in a constant")
543 #[derive(Copy, Clone)]
546 binding_mode: BindingMode,
549 // Map from the name in a pattern to its binding mode.
550 type BindingMap = HashMap<Name, BindingInfo>;
552 #[derive(Copy, Clone, PartialEq)]
553 enum PatternBindingMode {
555 LocalIrrefutableMode,
556 ArgumentIrrefutableMode,
559 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
565 /// A NamespaceResult represents the result of resolving an import in
566 /// a particular namespace. The result is either definitely-resolved,
567 /// definitely- unresolved, or unknown.
569 enum NamespaceResult {
570 /// Means that resolve hasn't gathered enough information yet to determine
571 /// whether the name is bound in this namespace. (That is, it hasn't
572 /// resolved all `use` directives yet.)
574 /// Means that resolve has determined that the name is definitely
575 /// not bound in the namespace.
577 /// Means that resolve has determined that the name is bound in the Module
578 /// argument, and specified by the NameBinding argument.
579 BoundResult(Rc<Module>, NameBinding),
582 impl NamespaceResult {
583 fn is_unknown(&self) -> bool {
585 UnknownResult => true,
589 fn is_unbound(&self) -> bool {
591 UnboundResult => true,
597 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
598 fn visit_nested_item(&mut self, item: hir::ItemId) {
599 self.visit_item(self.ast_map.expect_item(item.id))
601 fn visit_item(&mut self, item: &Item) {
602 execute_callback!(hir_map::Node::NodeItem(item), self);
603 self.resolve_item(item);
605 fn visit_arm(&mut self, arm: &Arm) {
606 self.resolve_arm(arm);
608 fn visit_block(&mut self, block: &Block) {
609 execute_callback!(hir_map::Node::NodeBlock(block), self);
610 self.resolve_block(block);
612 fn visit_expr(&mut self, expr: &Expr) {
613 execute_callback!(hir_map::Node::NodeExpr(expr), self);
614 self.resolve_expr(expr);
616 fn visit_local(&mut self, local: &Local) {
617 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
618 self.resolve_local(local);
620 fn visit_ty(&mut self, ty: &Ty) {
621 self.resolve_type(ty);
623 fn visit_generics(&mut self, generics: &Generics) {
624 self.resolve_generics(generics);
626 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
627 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
628 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
630 // error already reported
631 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
634 intravisit::walk_poly_trait_ref(self, tref, m);
636 fn visit_variant(&mut self,
637 variant: &hir::Variant,
639 item_id: ast::NodeId) {
640 execute_callback!(hir_map::Node::NodeVariant(variant), self);
641 if let Some(ref dis_expr) = variant.node.disr_expr {
642 // resolve the discriminator expr as a constant
643 self.with_constant_rib(|this| {
644 this.visit_expr(dis_expr);
648 // `intravisit::walk_variant` without the discriminant expression.
649 self.visit_variant_data(&variant.node.data,
655 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
656 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
657 let type_parameters = match foreign_item.node {
658 ForeignItemFn(_, ref generics) => {
659 HasTypeParameters(generics, FnSpace, ItemRibKind)
661 ForeignItemStatic(..) => NoTypeParameters,
663 self.with_type_parameter_rib(type_parameters, |this| {
664 intravisit::walk_foreign_item(this, foreign_item);
667 fn visit_fn(&mut self,
668 function_kind: FnKind<'v>,
669 declaration: &'v FnDecl,
673 let rib_kind = match function_kind {
674 FnKind::ItemFn(_, generics, _, _, _, _) => {
675 self.visit_generics(generics);
678 FnKind::Method(_, sig, _) => {
679 self.visit_generics(&sig.generics);
680 self.visit_explicit_self(&sig.explicit_self);
683 FnKind::Closure => ClosureRibKind(node_id),
685 self.resolve_function(rib_kind, declaration, block);
689 type ErrorMessage = Option<(Span, String)>;
691 enum ResolveResult<T> {
692 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
693 Indeterminate, // Couldn't determine due to unresolved globs.
694 Success(T), // Successfully resolved the import.
697 impl<T> ResolveResult<T> {
698 fn success(&self) -> bool {
706 enum FallbackSuggestion {
711 StaticMethod(String),
715 #[derive(Copy, Clone)]
716 enum TypeParameters<'a> {
718 HasTypeParameters(// Type parameters.
721 // Identifies the things that these parameters
722 // were declared on (type, fn, etc)
725 // The kind of the rib used for type parameters.
729 // The rib kind controls the translation of local
730 // definitions (`DefLocal`) to upvars (`DefUpvar`).
731 #[derive(Copy, Clone, Debug)]
733 // No translation needs to be applied.
736 // We passed through a closure scope at the given node ID.
737 // Translate upvars as appropriate.
738 ClosureRibKind(NodeId /* func id */),
740 // We passed through an impl or trait and are now in one of its
741 // methods. Allow references to ty params that impl or trait
742 // binds. Disallow any other upvars (including other ty params that are
746 // We passed through an item scope. Disallow upvars.
749 // We're in a constant item. Can't refer to dynamic stuff.
753 #[derive(Copy, Clone)]
754 enum UseLexicalScopeFlag {
759 enum ModulePrefixResult {
761 PrefixFound(Rc<Module>, usize),
764 #[derive(Copy, Clone)]
765 enum AssocItemResolveResult {
766 /// Syntax such as `<T>::item`, which can't be resolved until type
769 /// We should have been able to resolve the associated item.
770 ResolveAttempt(Option<PathResolution>),
773 #[derive(Copy, Clone, PartialEq)]
774 enum NameSearchType {
775 /// We're doing a name search in order to resolve a `use` directive.
778 /// We're doing a name search in order to resolve a path type, a path
779 /// expression, or a path pattern.
783 #[derive(Copy, Clone)]
784 enum BareIdentifierPatternResolution {
785 FoundStructOrEnumVariant(Def, LastPrivate),
786 FoundConst(Def, LastPrivate, Name),
787 BareIdentifierPatternUnresolved,
793 bindings: HashMap<Name, DefLike>,
798 fn new(kind: RibKind) -> Rib {
800 bindings: HashMap::new(),
806 /// A definition along with the index of the rib it was found on
808 ribs: Option<(Namespace, usize)>,
813 fn from_def(def: Def) -> Self {
821 /// The link from a module up to its nearest parent node.
822 #[derive(Clone,Debug)]
825 ModuleParentLink(Weak<Module>, Name),
826 BlockParentLink(Weak<Module>, NodeId),
829 /// One node in the tree of modules.
831 parent_link: ParentLink,
832 def: Cell<Option<Def>>,
835 children: RefCell<HashMap<Name, NameBindings>>,
836 imports: RefCell<Vec<ImportDirective>>,
838 // The external module children of this node that were declared with
840 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
842 // The anonymous children of this node. Anonymous children are pseudo-
843 // modules that are implicitly created around items contained within
846 // For example, if we have this:
854 // There will be an anonymous module created around `g` with the ID of the
855 // entry block for `f`.
856 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
858 // The status of resolving each import in this module.
859 import_resolutions: RefCell<HashMap<Name, ImportResolutionPerNamespace>>,
861 // The number of unresolved globs that this module exports.
862 glob_count: Cell<usize>,
864 // The number of unresolved pub imports (both regular and globs) in this module
865 pub_count: Cell<usize>,
867 // The number of unresolved pub glob imports in this module
868 pub_glob_count: Cell<usize>,
870 // The index of the import we're resolving.
871 resolved_import_count: Cell<usize>,
873 // Whether this module is populated. If not populated, any attempt to
874 // access the children must be preceded with a
875 // `populate_module_if_necessary` call.
876 populated: Cell<bool>,
880 fn new(parent_link: ParentLink,
886 parent_link: parent_link,
888 is_public: is_public,
889 children: RefCell::new(HashMap::new()),
890 imports: RefCell::new(Vec::new()),
891 external_module_children: RefCell::new(HashMap::new()),
892 anonymous_children: RefCell::new(NodeMap()),
893 import_resolutions: RefCell::new(HashMap::new()),
894 glob_count: Cell::new(0),
895 pub_count: Cell::new(0),
896 pub_glob_count: Cell::new(0),
897 resolved_import_count: Cell::new(0),
898 populated: Cell::new(!external),
902 fn def_id(&self) -> Option<DefId> {
903 self.def.get().as_ref().map(Def::def_id)
906 fn is_normal(&self) -> bool {
907 match self.def.get() {
908 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
913 fn is_trait(&self) -> bool {
914 match self.def.get() {
915 Some(DefTrait(_)) => true,
920 fn all_imports_resolved(&self) -> bool {
921 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
922 // it is currently being resolved ! so nope
925 self.imports.borrow().len() == self.resolved_import_count.get()
931 pub fn inc_glob_count(&self) {
932 self.glob_count.set(self.glob_count.get() + 1);
934 pub fn dec_glob_count(&self) {
935 assert!(self.glob_count.get() > 0);
936 self.glob_count.set(self.glob_count.get() - 1);
938 pub fn inc_pub_count(&self) {
939 self.pub_count.set(self.pub_count.get() + 1);
941 pub fn dec_pub_count(&self) {
942 assert!(self.pub_count.get() > 0);
943 self.pub_count.set(self.pub_count.get() - 1);
945 pub fn inc_pub_glob_count(&self) {
946 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
948 pub fn dec_pub_glob_count(&self) {
949 assert!(self.pub_glob_count.get() > 0);
950 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
954 impl fmt::Debug for Module {
955 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
969 flags DefModifiers: u8 {
970 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
971 // or `use Enum::*` to work on private enums.
972 const PUBLIC = 1 << 0,
973 const IMPORTABLE = 1 << 1,
974 // Variants are considered `PUBLIC`, but some of them live in private enums.
975 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
976 const PRIVATE_VARIANT = 1 << 2,
980 // Records a possibly-private value, type, or module definition.
983 modifiers: DefModifiers, // see note in ImportResolutionPerNamespace about how to use this
984 def_or_module: DefOrModule,
995 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
996 let modifiers = if module.is_public {
999 DefModifiers::empty()
1000 } | DefModifiers::IMPORTABLE;
1002 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
1005 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
1006 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
1009 fn module(&self) -> Option<Rc<Module>> {
1010 match self.def_or_module {
1011 DefOrModule::Module(ref module) => Some(module.clone()),
1012 DefOrModule::Def(_) => None,
1016 fn def(&self) -> Option<Def> {
1017 match self.def_or_module {
1018 DefOrModule::Def(def) => Some(def),
1019 DefOrModule::Module(ref module) => module.def.get(),
1024 // Records at most one definition that a name in a namespace is bound to
1025 #[derive(Clone,Debug)]
1026 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
1030 NameBinding(Rc::new(RefCell::new(None)))
1033 fn create_from_module(module: Rc<Module>) -> Self {
1034 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
1037 fn set(&self, ns_def: NsDef) {
1038 *self.0.borrow_mut() = Some(ns_def);
1041 fn set_modifiers(&self, modifiers: DefModifiers) {
1042 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
1043 ns_def.modifiers = modifiers
1047 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> {
1051 // Lifted versions of the NsDef methods and fields
1052 fn def(&self) -> Option<Def> {
1053 self.borrow().as_ref().and_then(NsDef::def)
1055 fn module(&self) -> Option<Rc<Module>> {
1056 self.borrow().as_ref().and_then(NsDef::module)
1058 fn span(&self) -> Option<Span> {
1059 self.borrow().as_ref().and_then(|def| def.span)
1061 fn modifiers(&self) -> Option<DefModifiers> {
1062 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
1065 fn defined(&self) -> bool {
1066 self.borrow().is_some()
1069 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1070 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1073 fn is_public(&self) -> bool {
1074 self.defined_with(DefModifiers::PUBLIC)
1077 fn def_and_lp(&self) -> (Def, LastPrivate) {
1078 let def = self.def().unwrap();
1079 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1083 // Records the definitions (at most one for each namespace) that a name is
1085 #[derive(Clone,Debug)]
1086 pub struct NameBindings {
1087 type_ns: NameBinding, // < Meaning in type namespace.
1088 value_ns: NameBinding, // < Meaning in value namespace.
1091 impl ::std::ops::Index<Namespace> for NameBindings {
1092 type Output = NameBinding;
1093 fn index(&self, namespace: Namespace) -> &NameBinding {
1094 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1099 fn new() -> NameBindings {
1101 type_ns: NameBinding::new(),
1102 value_ns: NameBinding::new(),
1106 /// Creates a new module in this set of name bindings.
1107 fn define_module(&self, module: Rc<Module>, sp: Span) {
1108 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1111 /// Records a type definition.
1112 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1113 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1114 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1117 /// Records a value definition.
1118 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1119 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1120 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1124 /// Interns the names of the primitive types.
1125 struct PrimitiveTypeTable {
1126 primitive_types: HashMap<Name, PrimTy>,
1129 impl PrimitiveTypeTable {
1130 fn new() -> PrimitiveTypeTable {
1131 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1133 table.intern("bool", TyBool);
1134 table.intern("char", TyChar);
1135 table.intern("f32", TyFloat(TyF32));
1136 table.intern("f64", TyFloat(TyF64));
1137 table.intern("isize", TyInt(TyIs));
1138 table.intern("i8", TyInt(TyI8));
1139 table.intern("i16", TyInt(TyI16));
1140 table.intern("i32", TyInt(TyI32));
1141 table.intern("i64", TyInt(TyI64));
1142 table.intern("str", TyStr);
1143 table.intern("usize", TyUint(TyUs));
1144 table.intern("u8", TyUint(TyU8));
1145 table.intern("u16", TyUint(TyU16));
1146 table.intern("u32", TyUint(TyU32));
1147 table.intern("u64", TyUint(TyU64));
1152 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1153 self.primitive_types.insert(token::intern(string), primitive_type);
1157 /// The main resolver class.
1158 pub struct Resolver<'a, 'tcx: 'a> {
1159 session: &'a Session,
1161 ast_map: &'a hir_map::Map<'tcx>,
1163 graph_root: Rc<Module>,
1165 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1167 structs: FnvHashMap<DefId, Vec<Name>>,
1169 // The number of imports that are currently unresolved.
1170 unresolved_imports: usize,
1172 // The module that represents the current item scope.
1173 current_module: Rc<Module>,
1175 // The current set of local scopes, for values.
1176 // FIXME #4948: Reuse ribs to avoid allocation.
1177 value_ribs: Vec<Rib>,
1179 // The current set of local scopes, for types.
1180 type_ribs: Vec<Rib>,
1182 // The current set of local scopes, for labels.
1183 label_ribs: Vec<Rib>,
1185 // The trait that the current context can refer to.
1186 current_trait_ref: Option<(DefId, TraitRef)>,
1188 // The current self type if inside an impl (used for better errors).
1189 current_self_type: Option<Ty>,
1191 // The idents for the primitive types.
1192 primitive_type_table: PrimitiveTypeTable,
1194 def_map: RefCell<DefMap>,
1195 freevars: FreevarMap,
1196 freevars_seen: NodeMap<NodeMap<usize>>,
1197 export_map: ExportMap,
1198 trait_map: TraitMap,
1199 external_exports: ExternalExports,
1201 // Whether or not to print error messages. Can be set to true
1202 // when getting additional info for error message suggestions,
1203 // so as to avoid printing duplicate errors
1206 make_glob_map: bool,
1207 // Maps imports to the names of items actually imported (this actually maps
1208 // all imports, but only glob imports are actually interesting).
1211 used_imports: HashSet<(NodeId, Namespace)>,
1212 used_crates: HashSet<CrateNum>,
1214 // Callback function for intercepting walks
1215 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1216 // The intention is that the callback modifies this flag.
1217 // Once set, the resolver falls out of the walk, preserving the ribs.
1221 #[derive(PartialEq)]
1222 enum FallbackChecks {
1224 OnlyTraitAndStatics,
1227 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1228 fn new(session: &'a Session,
1229 ast_map: &'a hir_map::Map<'tcx>,
1230 make_glob_map: MakeGlobMap)
1231 -> Resolver<'a, 'tcx> {
1232 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1233 let graph_root = Module::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1240 // The outermost module has def ID 0; this is not reflected in the
1242 graph_root: graph_root.clone(),
1244 trait_item_map: FnvHashMap(),
1245 structs: FnvHashMap(),
1247 unresolved_imports: 0,
1249 current_module: graph_root,
1250 value_ribs: Vec::new(),
1251 type_ribs: Vec::new(),
1252 label_ribs: Vec::new(),
1254 current_trait_ref: None,
1255 current_self_type: None,
1257 primitive_type_table: PrimitiveTypeTable::new(),
1259 def_map: RefCell::new(NodeMap()),
1260 freevars: NodeMap(),
1261 freevars_seen: NodeMap(),
1262 export_map: NodeMap(),
1263 trait_map: NodeMap(),
1264 used_imports: HashSet::new(),
1265 used_crates: HashSet::new(),
1266 external_exports: DefIdSet(),
1269 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1270 glob_map: HashMap::new(),
1278 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1279 if !self.make_glob_map {
1282 if self.glob_map.contains_key(&import_id) {
1283 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1287 let mut new_set = HashSet::new();
1288 new_set.insert(name);
1289 self.glob_map.insert(import_id, new_set);
1292 fn get_trait_name(&self, did: DefId) -> Name {
1293 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1294 self.ast_map.expect_item(node_id).name
1296 self.session.cstore.item_name(did)
1300 /// Checks that the names of external crates don't collide with other
1301 /// external crates.
1302 fn check_for_conflicts_between_external_crates(&self,
1306 if module.external_module_children.borrow().contains_key(&name) {
1307 span_err!(self.session,
1310 "an external crate named `{}` has already been imported into this module",
1315 /// Checks that the names of items don't collide with external crates.
1316 fn check_for_conflicts_between_external_crates_and_items(&self,
1320 if module.external_module_children.borrow().contains_key(&name) {
1321 span_err!(self.session,
1324 "the name `{}` conflicts with an external crate that has been imported \
1330 /// Resolves the given module path from the given root `module_`.
1331 fn resolve_module_path_from_root(&mut self,
1332 module_: Rc<Module>,
1333 module_path: &[Name],
1336 name_search_type: NameSearchType,
1338 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1339 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1340 match module.external_module_children.borrow().get(&needle) {
1341 Some(_) => Some(module.clone()),
1342 None => match module.parent_link {
1343 ModuleParentLink(ref parent, _) => {
1344 search_parent_externals(needle, &parent.upgrade().unwrap())
1351 let mut search_module = module_;
1352 let mut index = index;
1353 let module_path_len = module_path.len();
1354 let mut closest_private = lp;
1356 // Resolve the module part of the path. This does not involve looking
1357 // upward though scope chains; we simply resolve names directly in
1358 // modules as we go.
1359 while index < module_path_len {
1360 let name = module_path[index];
1361 match self.resolve_name_in_module(search_module.clone(),
1367 let segment_name = name.as_str();
1368 let module_name = module_to_string(&*search_module);
1369 let mut span = span;
1370 let msg = if "???" == &module_name[..] {
1371 span.hi = span.lo + Pos::from_usize(segment_name.len());
1373 match search_parent_externals(name, &self.current_module) {
1375 let path_str = names_to_string(module_path);
1376 let target_mod_str = module_to_string(&*module);
1377 let current_mod_str = module_to_string(&*self.current_module);
1379 let prefix = if target_mod_str == current_mod_str {
1380 "self::".to_string()
1382 format!("{}::", target_mod_str)
1385 format!("Did you mean `{}{}`?", prefix, path_str)
1387 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1390 format!("Could not find `{}` in `{}`", segment_name, module_name)
1393 return Failed(Some((span, msg)));
1395 Failed(err) => return Failed(err),
1397 debug!("(resolving module path for import) module resolution is \
1400 return Indeterminate;
1402 Success((target, used_proxy)) => {
1403 // Check to see whether there are type bindings, and, if
1404 // so, whether there is a module within.
1405 if let Some(module_def) = target.binding.module() {
1406 // track extern crates for unused_extern_crate lint
1407 if let Some(did) = module_def.def_id() {
1408 self.used_crates.insert(did.krate);
1411 search_module = module_def;
1413 // Keep track of the closest private module used
1414 // when resolving this import chain.
1415 if !used_proxy && !search_module.is_public {
1416 if let Some(did) = search_module.def_id() {
1417 closest_private = LastMod(DependsOn(did));
1421 let msg = format!("Not a module `{}`", name);
1422 return Failed(Some((span, msg)));
1430 return Success((search_module, closest_private));
1433 /// Attempts to resolve the module part of an import directive or path
1434 /// rooted at the given module.
1436 /// On success, returns the resolved module, and the closest *private*
1437 /// module found to the destination when resolving this path.
1438 fn resolve_module_path(&mut self,
1439 module_: Rc<Module>,
1440 module_path: &[Name],
1441 use_lexical_scope: UseLexicalScopeFlag,
1443 name_search_type: NameSearchType)
1444 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1445 let module_path_len = module_path.len();
1446 assert!(module_path_len > 0);
1448 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1449 names_to_string(module_path),
1450 module_to_string(&*module_));
1452 // Resolve the module prefix, if any.
1453 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1458 match module_prefix_result {
1460 let mpath = names_to_string(module_path);
1461 let mpath = &mpath[..];
1462 match mpath.rfind(':') {
1464 let msg = format!("Could not find `{}` in `{}`",
1465 // idx +- 1 to account for the
1466 // colons on either side
1469 return Failed(Some((span, msg)));
1472 return Failed(None);
1476 Failed(err) => return Failed(err),
1478 debug!("(resolving module path for import) indeterminate; bailing");
1479 return Indeterminate;
1481 Success(NoPrefixFound) => {
1482 // There was no prefix, so we're considering the first element
1483 // of the path. How we handle this depends on whether we were
1484 // instructed to use lexical scope or not.
1485 match use_lexical_scope {
1486 DontUseLexicalScope => {
1487 // This is a crate-relative path. We will start the
1488 // resolution process at index zero.
1489 search_module = self.graph_root.clone();
1491 last_private = LastMod(AllPublic);
1493 UseLexicalScope => {
1494 // This is not a crate-relative path. We resolve the
1495 // first component of the path in the current lexical
1496 // scope and then proceed to resolve below that.
1497 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1498 Failed(err) => return Failed(err),
1500 debug!("(resolving module path for import) indeterminate; bailing");
1501 return Indeterminate;
1503 Success(containing_module) => {
1504 search_module = containing_module;
1506 last_private = LastMod(AllPublic);
1512 Success(PrefixFound(ref containing_module, index)) => {
1513 search_module = containing_module.clone();
1514 start_index = index;
1515 last_private = LastMod(DependsOn(containing_module.def_id()
1520 self.resolve_module_path_from_root(search_module,
1528 /// Invariant: This must only be called during main resolution, not during
1529 /// import resolution.
1530 fn resolve_item_in_lexical_scope(&mut self,
1531 module_: Rc<Module>,
1533 namespace: Namespace,
1535 -> ResolveResult<(Target, bool)> {
1536 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1539 module_to_string(&*module_));
1541 // The current module node is handled specially. First, check for
1542 // its immediate children.
1543 build_reduced_graph::populate_module_if_necessary(self, &module_);
1545 match module_.children.borrow().get(&name) {
1546 Some(name_bindings) if name_bindings[namespace].defined() => {
1547 debug!("top name bindings succeeded");
1548 return Success((Target::new(module_.clone(),
1549 name_bindings[namespace].clone(),
1554 // Not found; continue.
1558 // Now check for its import directives. We don't have to have resolved
1559 // all its imports in the usual way; this is because chains of
1560 // adjacent import statements are processed as though they mutated the
1562 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1563 match import_resolution[namespace].target.clone() {
1565 // Not found; continue.
1566 debug!("(resolving item in lexical scope) found import resolution, but not \
1571 debug!("(resolving item in lexical scope) using import resolution");
1572 // track used imports and extern crates as well
1573 let id = import_resolution[namespace].id;
1575 self.used_imports.insert((id, namespace));
1576 self.record_import_use(id, name);
1577 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1578 self.used_crates.insert(kid);
1581 return Success((target, false));
1586 // Search for external modules.
1587 if namespace == TypeNS {
1588 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1589 let child = module_.external_module_children.borrow().get(&name).cloned();
1590 if let Some(module) = child {
1591 let name_binding = NameBinding::create_from_module(module);
1592 debug!("lower name bindings succeeded");
1593 return Success((Target::new(module_, name_binding, Shadowable::Never),
1598 // Finally, proceed up the scope chain looking for parent modules.
1599 let mut search_module = module_;
1601 // Go to the next parent.
1602 match search_module.parent_link.clone() {
1604 // No more parents. This module was unresolved.
1605 debug!("(resolving item in lexical scope) unresolved module");
1606 return Failed(None);
1608 ModuleParentLink(parent_module_node, _) => {
1609 if search_module.is_normal() {
1610 // We stop the search here.
1611 debug!("(resolving item in lexical scope) unresolved module: not \
1612 searching through module parents");
1613 return Failed(None);
1615 search_module = parent_module_node.upgrade().unwrap();
1618 BlockParentLink(ref parent_module_node, _) => {
1619 search_module = parent_module_node.upgrade().unwrap();
1623 // Resolve the name in the parent module.
1624 match self.resolve_name_in_module(search_module.clone(),
1629 Failed(Some((span, msg))) => {
1630 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1632 Failed(None) => (), // Continue up the search chain.
1634 // We couldn't see through the higher scope because of an
1635 // unresolved import higher up. Bail.
1637 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1638 return Indeterminate;
1640 Success((target, used_reexport)) => {
1641 // We found the module.
1642 debug!("(resolving item in lexical scope) found name in module, done");
1643 return Success((target, used_reexport));
1649 /// Resolves a module name in the current lexical scope.
1650 fn resolve_module_in_lexical_scope(&mut self,
1651 module_: Rc<Module>,
1653 -> ResolveResult<Rc<Module>> {
1654 // If this module is an anonymous module, resolve the item in the
1655 // lexical scope. Otherwise, resolve the item from the crate root.
1656 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS, true);
1657 match resolve_result {
1658 Success((target, _)) => {
1659 if let Some(module_def) = target.binding.module() {
1660 return Success(module_def)
1662 debug!("!!! (resolving module in lexical scope) module \
1663 wasn't actually a module!");
1664 return Failed(None);
1668 debug!("(resolving module in lexical scope) indeterminate; bailing");
1669 return Indeterminate;
1672 debug!("(resolving module in lexical scope) failed to resolve");
1678 /// Returns the nearest normal module parent of the given module.
1679 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1680 let mut module_ = module_;
1682 match module_.parent_link.clone() {
1683 NoParentLink => return None,
1684 ModuleParentLink(new_module, _) |
1685 BlockParentLink(new_module, _) => {
1686 let new_module = new_module.upgrade().unwrap();
1687 if new_module.is_normal() {
1688 return Some(new_module);
1690 module_ = new_module;
1696 /// Returns the nearest normal module parent of the given module, or the
1697 /// module itself if it is a normal module.
1698 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1699 if module_.is_normal() {
1702 match self.get_nearest_normal_module_parent(module_.clone()) {
1704 Some(new_module) => new_module,
1708 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1709 /// (b) some chain of `super::`.
1710 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1711 fn resolve_module_prefix(&mut self,
1712 module_: Rc<Module>,
1713 module_path: &[Name])
1714 -> ResolveResult<ModulePrefixResult> {
1715 // Start at the current module if we see `self` or `super`, or at the
1716 // top of the crate otherwise.
1717 let mut i = match &*module_path[0].as_str() {
1720 _ => return Success(NoPrefixFound),
1722 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1724 // Now loop through all the `super`s we find.
1725 while i < module_path.len() && "super" == module_path[i].as_str() {
1726 debug!("(resolving module prefix) resolving `super` at {}",
1727 module_to_string(&*containing_module));
1728 match self.get_nearest_normal_module_parent(containing_module) {
1729 None => return Failed(None),
1730 Some(new_module) => {
1731 containing_module = new_module;
1737 debug!("(resolving module prefix) finished resolving prefix at {}",
1738 module_to_string(&*containing_module));
1740 return Success(PrefixFound(containing_module, i));
1743 /// Attempts to resolve the supplied name in the given module for the
1744 /// given namespace. If successful, returns the target corresponding to
1747 /// The boolean returned on success is an indicator of whether this lookup
1748 /// passed through a public re-export proxy.
1749 fn resolve_name_in_module(&mut self,
1750 module_: Rc<Module>,
1752 namespace: Namespace,
1753 name_search_type: NameSearchType,
1754 allow_private_imports: bool)
1755 -> ResolveResult<(Target, bool)> {
1756 debug!("(resolving name in module) resolving `{}` in `{}`",
1758 module_to_string(&*module_));
1760 // First, check the direct children of the module.
1761 build_reduced_graph::populate_module_if_necessary(self, &module_);
1763 match module_.children.borrow().get(&name) {
1764 Some(name_bindings) if name_bindings[namespace].defined() => {
1765 debug!("(resolving name in module) found node as child");
1766 return Success((Target::new(module_.clone(),
1767 name_bindings[namespace].clone(),
1776 // Next, check the module's imports if necessary.
1778 // If this is a search of all imports, we should be done with glob
1779 // resolution at this point.
1780 if name_search_type == PathSearch {
1781 assert_eq!(module_.glob_count.get(), 0);
1784 // Check the list of resolved imports.
1785 match module_.import_resolutions.borrow().get(&name) {
1786 Some(import_resolution) if allow_private_imports ||
1787 import_resolution[namespace].is_public => {
1789 if import_resolution[namespace].is_public &&
1790 import_resolution.outstanding_references != 0 {
1791 debug!("(resolving name in module) import unresolved; bailing out");
1792 return Indeterminate;
1794 match import_resolution[namespace].target.clone() {
1796 debug!("(resolving name in module) name found, but not in namespace {:?}",
1800 debug!("(resolving name in module) resolved to import");
1801 // track used imports and extern crates as well
1802 let id = import_resolution[namespace].id;
1803 self.used_imports.insert((id, namespace));
1804 self.record_import_use(id, name);
1805 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1806 self.used_crates.insert(kid);
1808 return Success((target, true));
1812 Some(..) | None => {} // Continue.
1815 // Finally, search through external children.
1816 if namespace == TypeNS {
1817 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1818 let child = module_.external_module_children.borrow().get(&name).cloned();
1819 if let Some(module) = child {
1820 let name_binding = NameBinding::create_from_module(module);
1821 return Success((Target::new(module_, name_binding, Shadowable::Never),
1826 // We're out of luck.
1827 debug!("(resolving name in module) failed to resolve `{}`", name);
1828 return Failed(None);
1831 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1832 let index = module_.resolved_import_count.get();
1833 let imports = module_.imports.borrow();
1834 let import_count = imports.len();
1835 if index != import_count {
1837 (*imports)[index].span,
1838 ResolutionError::UnresolvedImport(None));
1841 // Descend into children and anonymous children.
1842 build_reduced_graph::populate_module_if_necessary(self, &module_);
1844 for (_, child_node) in module_.children.borrow().iter() {
1845 match child_node.type_ns.module() {
1849 Some(child_module) => {
1850 self.report_unresolved_imports(child_module);
1855 for (_, module_) in module_.anonymous_children.borrow().iter() {
1856 self.report_unresolved_imports(module_.clone());
1862 // We maintain a list of value ribs and type ribs.
1864 // Simultaneously, we keep track of the current position in the module
1865 // graph in the `current_module` pointer. When we go to resolve a name in
1866 // the value or type namespaces, we first look through all the ribs and
1867 // then query the module graph. When we resolve a name in the module
1868 // namespace, we can skip all the ribs (since nested modules are not
1869 // allowed within blocks in Rust) and jump straight to the current module
1872 // Named implementations are handled separately. When we find a method
1873 // call, we consult the module node to find all of the implementations in
1874 // scope. This information is lazily cached in the module node. We then
1875 // generate a fake "implementation scope" containing all the
1876 // implementations thus found, for compatibility with old resolve pass.
1878 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1879 where F: FnOnce(&mut Resolver)
1881 let orig_module = self.current_module.clone();
1883 // Move down in the graph.
1889 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1891 match orig_module.children.borrow().get(&name) {
1893 debug!("!!! (with scope) didn't find `{}` in `{}`",
1895 module_to_string(&*orig_module));
1897 Some(name_bindings) => {
1898 match name_bindings.type_ns.module() {
1900 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1902 module_to_string(&*orig_module));
1905 self.current_module = module_;
1915 self.current_module = orig_module;
1918 /// Searches the current set of local scopes for labels.
1919 /// Stops after meeting a closure.
1920 fn search_label(&self, name: Name) -> Option<DefLike> {
1921 for rib in self.label_ribs.iter().rev() {
1927 // Do not resolve labels across function boundary
1931 let result = rib.bindings.get(&name).cloned();
1932 if result.is_some() {
1939 fn resolve_crate(&mut self, krate: &hir::Crate) {
1940 debug!("(resolving crate) starting");
1942 intravisit::walk_crate(self, krate);
1945 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1946 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1947 span_err!(self.session,
1950 "user-defined types or type parameters cannot shadow the primitive types");
1954 fn resolve_item(&mut self, item: &Item) {
1955 let name = item.name;
1957 debug!("(resolving item) resolving {}", name);
1960 ItemEnum(_, ref generics) |
1961 ItemTy(_, ref generics) |
1962 ItemStruct(_, ref generics) => {
1963 self.check_if_primitive_type_name(name, item.span);
1965 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1966 |this| intravisit::walk_item(this, item));
1968 ItemFn(_, _, _, _, ref generics, _) => {
1969 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1970 |this| intravisit::walk_item(this, item));
1973 ItemDefaultImpl(_, ref trait_ref) => {
1974 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1976 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1977 self.resolve_implementation(generics,
1984 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1985 self.check_if_primitive_type_name(name, item.span);
1987 // Create a new rib for the trait-wide type parameters.
1988 self.with_type_parameter_rib(HasTypeParameters(generics,
1992 let local_def_id = this.ast_map.local_def_id(item.id);
1993 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1994 this.visit_generics(generics);
1995 walk_list!(this, visit_ty_param_bound, bounds);
1997 for trait_item in trait_items {
1998 match trait_item.node {
1999 hir::ConstTraitItem(_, ref default) => {
2000 // Only impose the restrictions of
2001 // ConstRibKind if there's an actual constant
2002 // expression in a provided default.
2003 if default.is_some() {
2004 this.with_constant_rib(|this| {
2005 intravisit::walk_trait_item(this, trait_item)
2008 intravisit::walk_trait_item(this, trait_item)
2011 hir::MethodTraitItem(ref sig, _) => {
2012 let type_parameters =
2013 HasTypeParameters(&sig.generics,
2016 this.with_type_parameter_rib(type_parameters, |this| {
2017 intravisit::walk_trait_item(this, trait_item)
2020 hir::TypeTraitItem(..) => {
2021 this.check_if_primitive_type_name(trait_item.name,
2023 this.with_type_parameter_rib(NoTypeParameters, |this| {
2024 intravisit::walk_trait_item(this, trait_item)
2033 ItemMod(_) | ItemForeignMod(_) => {
2034 self.with_scope(Some(name), |this| {
2035 intravisit::walk_item(this, item);
2039 ItemConst(..) | ItemStatic(..) => {
2040 self.with_constant_rib(|this| {
2041 intravisit::walk_item(this, item);
2045 ItemUse(ref view_path) => {
2046 // check for imports shadowing primitive types
2047 let check_rename = |this: &Self, id, name| {
2048 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
2049 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2050 this.check_if_primitive_type_name(name, item.span);
2056 match view_path.node {
2057 hir::ViewPathSimple(name, _) => {
2058 check_rename(self, item.id, name);
2060 hir::ViewPathList(ref prefix, ref items) => {
2062 if let Some(name) = item.node.rename() {
2063 check_rename(self, item.node.id(), name);
2067 // Resolve prefix of an import with empty braces (issue #28388)
2068 if items.is_empty() && !prefix.segments.is_empty() {
2069 match self.resolve_crate_relative_path(prefix.span,
2073 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2077 ResolutionError::FailedToResolve(
2078 &path_names_to_string(prefix, 0)));
2079 self.record_def(item.id, err_path_resolution());
2088 ItemExternCrate(_) => {
2089 // do nothing, these are just around to be encoded
2094 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2095 where F: FnOnce(&mut Resolver)
2097 match type_parameters {
2098 HasTypeParameters(generics, space, rib_kind) => {
2099 let mut function_type_rib = Rib::new(rib_kind);
2100 let mut seen_bindings = HashSet::new();
2101 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2102 let name = type_parameter.name;
2103 debug!("with_type_parameter_rib: {}", type_parameter.id);
2105 if seen_bindings.contains(&name) {
2107 type_parameter.span,
2108 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2110 seen_bindings.insert(name);
2112 // plain insert (no renaming)
2113 function_type_rib.bindings
2115 DlDef(DefTyParam(space,
2118 .local_def_id(type_parameter.id),
2121 self.type_ribs.push(function_type_rib);
2124 NoTypeParameters => {
2131 match type_parameters {
2132 HasTypeParameters(..) => {
2134 self.type_ribs.pop();
2137 NoTypeParameters => {}
2141 fn with_label_rib<F>(&mut self, f: F)
2142 where F: FnOnce(&mut Resolver)
2144 self.label_ribs.push(Rib::new(NormalRibKind));
2147 self.label_ribs.pop();
2151 fn with_constant_rib<F>(&mut self, f: F)
2152 where F: FnOnce(&mut Resolver)
2154 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2155 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2158 self.type_ribs.pop();
2159 self.value_ribs.pop();
2163 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2164 // Create a value rib for the function.
2165 self.value_ribs.push(Rib::new(rib_kind));
2167 // Create a label rib for the function.
2168 self.label_ribs.push(Rib::new(rib_kind));
2170 // Add each argument to the rib.
2171 let mut bindings_list = HashMap::new();
2172 for argument in &declaration.inputs {
2173 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2175 self.visit_ty(&*argument.ty);
2177 debug!("(resolving function) recorded argument");
2179 intravisit::walk_fn_ret_ty(self, &declaration.output);
2181 // Resolve the function body.
2182 self.visit_block(block);
2184 debug!("(resolving function) leaving function");
2187 self.label_ribs.pop();
2188 self.value_ribs.pop();
2192 fn resolve_trait_reference(&mut self,
2196 -> Result<PathResolution, ()> {
2197 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2198 if let DefTrait(_) = path_res.base_def {
2199 debug!("(resolving trait) found trait def: {:?}", path_res);
2203 resolve_struct_error(self,
2205 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2208 // If it's a typedef, give a note
2209 if let DefTy(..) = path_res.base_def {
2210 err.span_note(trait_path.span,
2211 "`type` aliases cannot be used for traits");
2219 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2225 fn resolve_generics(&mut self, generics: &Generics) {
2226 for type_parameter in generics.ty_params.iter() {
2227 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2229 for predicate in &generics.where_clause.predicates {
2231 &hir::WherePredicate::BoundPredicate(_) |
2232 &hir::WherePredicate::RegionPredicate(_) => {}
2233 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2234 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2235 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2236 self.record_def(eq_pred.id, path_res.unwrap());
2240 ResolutionError::UndeclaredAssociatedType);
2241 self.record_def(eq_pred.id, err_path_resolution());
2246 intravisit::walk_generics(self, generics);
2249 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2250 where F: FnOnce(&mut Resolver) -> T
2252 // Handle nested impls (inside fn bodies)
2253 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2254 let result = f(self);
2255 self.current_self_type = previous_value;
2259 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2260 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2262 let mut new_val = None;
2263 let mut new_id = None;
2264 if let Some(trait_ref) = opt_trait_ref {
2265 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2268 assert!(path_res.depth == 0);
2269 self.record_def(trait_ref.ref_id, path_res);
2270 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2271 new_id = Some(path_res.base_def.def_id());
2273 self.record_def(trait_ref.ref_id, err_path_resolution());
2275 intravisit::walk_trait_ref(self, trait_ref);
2277 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2278 let result = f(self, new_id);
2279 self.current_trait_ref = original_trait_ref;
2283 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2284 where F: FnOnce(&mut Resolver)
2286 let mut self_type_rib = Rib::new(NormalRibKind);
2288 // plain insert (no renaming, types are not currently hygienic....)
2289 let name = special_names::type_self;
2290 self_type_rib.bindings.insert(name, DlDef(self_def));
2291 self.type_ribs.push(self_type_rib);
2294 self.type_ribs.pop();
2298 fn resolve_implementation(&mut self,
2299 generics: &Generics,
2300 opt_trait_reference: &Option<TraitRef>,
2303 impl_items: &[ImplItem]) {
2304 // If applicable, create a rib for the type parameters.
2305 self.with_type_parameter_rib(HasTypeParameters(generics,
2309 // Resolve the type parameters.
2310 this.visit_generics(generics);
2312 // Resolve the trait reference, if necessary.
2313 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2314 // Resolve the self type.
2315 this.visit_ty(self_type);
2317 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2318 this.with_current_self_type(self_type, |this| {
2319 for impl_item in impl_items {
2320 match impl_item.node {
2321 hir::ImplItemKind::Const(..) => {
2322 // If this is a trait impl, ensure the const
2324 this.check_trait_item(impl_item.name,
2326 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2327 this.with_constant_rib(|this| {
2328 intravisit::walk_impl_item(this, impl_item);
2331 hir::ImplItemKind::Method(ref sig, _) => {
2332 // If this is a trait impl, ensure the method
2334 this.check_trait_item(impl_item.name,
2336 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2338 // We also need a new scope for the method-
2339 // specific type parameters.
2340 let type_parameters =
2341 HasTypeParameters(&sig.generics,
2344 this.with_type_parameter_rib(type_parameters, |this| {
2345 intravisit::walk_impl_item(this, impl_item);
2348 hir::ImplItemKind::Type(ref ty) => {
2349 // If this is a trait impl, ensure the type
2351 this.check_trait_item(impl_item.name,
2353 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2365 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2366 where F: FnOnce(Name, &str) -> ResolutionError
2368 // If there is a TraitRef in scope for an impl, then the method must be in the
2370 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2371 if !self.trait_item_map.contains_key(&(name, did)) {
2372 let path_str = path_names_to_string(&trait_ref.path, 0);
2373 resolve_error(self, span, err(name, &*path_str));
2378 fn resolve_local(&mut self, local: &Local) {
2379 // Resolve the type.
2380 walk_list!(self, visit_ty, &local.ty);
2382 // Resolve the initializer.
2383 walk_list!(self, visit_expr, &local.init);
2385 // Resolve the pattern.
2386 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2389 // build a map from pattern identifiers to binding-info's.
2390 // this is done hygienically. This could arise for a macro
2391 // that expands into an or-pattern where one 'x' was from the
2392 // user and one 'x' came from the macro.
2393 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2394 let mut result = HashMap::new();
2395 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2396 let name = path1.node;
2400 binding_mode: binding_mode,
2406 // check that all of the arms in an or-pattern have exactly the
2407 // same set of bindings, with the same binding modes for each.
2408 fn check_consistent_bindings(&mut self, arm: &Arm) {
2409 if arm.pats.is_empty() {
2412 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2413 for (i, p) in arm.pats.iter().enumerate() {
2414 let map_i = self.binding_mode_map(&**p);
2416 for (&key, &binding_0) in &map_0 {
2417 match map_i.get(&key) {
2421 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2423 Some(binding_i) => {
2424 if binding_0.binding_mode != binding_i.binding_mode {
2427 ResolutionError::VariableBoundWithDifferentMode(key,
2434 for (&key, &binding) in &map_i {
2435 if !map_0.contains_key(&key) {
2438 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2444 fn resolve_arm(&mut self, arm: &Arm) {
2445 self.value_ribs.push(Rib::new(NormalRibKind));
2447 let mut bindings_list = HashMap::new();
2448 for pattern in &arm.pats {
2449 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2452 // This has to happen *after* we determine which
2453 // pat_idents are variants
2454 self.check_consistent_bindings(arm);
2456 walk_list!(self, visit_expr, &arm.guard);
2457 self.visit_expr(&*arm.body);
2460 self.value_ribs.pop();
2464 fn resolve_block(&mut self, block: &Block) {
2465 debug!("(resolving block) entering block");
2466 self.value_ribs.push(Rib::new(NormalRibKind));
2468 // Move down in the graph, if there's an anonymous module rooted here.
2469 let orig_module = self.current_module.clone();
2470 match orig_module.anonymous_children.borrow().get(&block.id) {
2474 Some(anonymous_module) => {
2475 debug!("(resolving block) found anonymous module, moving down");
2476 self.current_module = anonymous_module.clone();
2480 // Check for imports appearing after non-item statements.
2481 let mut found_non_item = false;
2482 for statement in &block.stmts {
2483 if let hir::StmtDecl(ref declaration, _) = statement.node {
2484 if let hir::DeclItem(i) = declaration.node {
2485 let i = self.ast_map.expect_item(i.id);
2487 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2488 span_err!(self.session,
2491 "imports are not allowed after non-item statements");
2496 found_non_item = true
2499 found_non_item = true;
2503 // Descend into the block.
2504 intravisit::walk_block(self, block);
2508 self.current_module = orig_module;
2509 self.value_ribs.pop();
2511 debug!("(resolving block) leaving block");
2514 fn resolve_type(&mut self, ty: &Ty) {
2516 TyPath(ref maybe_qself, ref path) => {
2517 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2518 maybe_qself.as_ref(),
2522 // `<T>::a::b::c` is resolved by typeck alone.
2523 TypecheckRequired => {
2524 // Resolve embedded types.
2525 intravisit::walk_ty(self, ty);
2528 ResolveAttempt(resolution) => resolution,
2531 // This is a path in the type namespace. Walk through scopes
2535 // Write the result into the def map.
2536 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2537 path_names_to_string(path, 0),
2540 self.record_def(ty.id, def);
2543 self.record_def(ty.id, err_path_resolution());
2545 // Keep reporting some errors even if they're ignored above.
2546 self.resolve_path(ty.id, path, 0, TypeNS, true);
2548 let kind = if maybe_qself.is_some() {
2554 let self_type_name = special_idents::type_self.name;
2555 let is_invalid_self_type_name = path.segments.len() > 0 &&
2556 maybe_qself.is_none() &&
2557 path.segments[0].identifier.name ==
2559 if is_invalid_self_type_name {
2562 ResolutionError::SelfUsedOutsideImplOrTrait);
2566 ResolutionError::UseOfUndeclared(
2568 &*path_names_to_string(path,
2577 // Resolve embedded types.
2578 intravisit::walk_ty(self, ty);
2581 fn resolve_pattern(&mut self,
2583 mode: PatternBindingMode,
2584 // Maps idents to the node ID for the (outermost)
2585 // pattern that binds them
2586 bindings_list: &mut HashMap<Name, NodeId>) {
2587 let pat_id = pattern.id;
2588 walk_pat(pattern, |pattern| {
2589 match pattern.node {
2590 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2591 // The meaning of PatIdent with no type parameters
2592 // depends on whether an enum variant or unit-like struct
2593 // with that name is in scope. The probing lookup has to
2594 // be careful not to emit spurious errors. Only matching
2595 // patterns (match) can match nullary variants or
2596 // unit-like structs. For binding patterns (let
2597 // and the LHS of @-patterns), matching such a value is
2598 // simply disallowed (since it's rarely what you want).
2599 let const_ok = mode == RefutableMode && at_rhs.is_none();
2601 let ident = path1.node;
2602 let renamed = ident.name;
2604 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2606 FoundStructOrEnumVariant(def, lp) if const_ok => {
2607 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2610 self.enforce_default_binding_mode(pattern,
2613 self.record_def(pattern.id,
2620 FoundStructOrEnumVariant(..) => {
2624 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2627 self.record_def(pattern.id, err_path_resolution());
2629 FoundConst(def, lp, _) if const_ok => {
2630 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2632 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2633 self.record_def(pattern.id,
2640 FoundConst(def, _, name) => {
2644 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2647 self.record_def(pattern.id, err_path_resolution());
2649 BareIdentifierPatternUnresolved => {
2650 debug!("(resolving pattern) binding `{}`", renamed);
2652 let def_id = self.ast_map.local_def_id(pattern.id);
2653 let def = DefLocal(def_id, pattern.id);
2655 // Record the definition so that later passes
2656 // will be able to distinguish variants from
2657 // locals in patterns.
2659 self.record_def(pattern.id,
2662 last_private: LastMod(AllPublic),
2666 // Add the binding to the local ribs, if it
2667 // doesn't already exist in the bindings list. (We
2668 // must not add it if it's in the bindings list
2669 // because that breaks the assumptions later
2670 // passes make about or-patterns.)
2671 if !bindings_list.contains_key(&renamed) {
2672 let this = &mut *self;
2673 let last_rib = this.value_ribs.last_mut().unwrap();
2674 last_rib.bindings.insert(renamed, DlDef(def));
2675 bindings_list.insert(renamed, pat_id);
2676 } else if mode == ArgumentIrrefutableMode &&
2677 bindings_list.contains_key(&renamed) {
2678 // Forbid duplicate bindings in the same
2683 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2684 &ident.name.as_str())
2686 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2687 // Then this is a duplicate variable in the
2688 // same disjunction, which is an error.
2692 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2693 &ident.name.as_str())
2696 // Else, not bound in the same pattern: do
2702 PatEnum(ref path, _) => {
2703 // This must be an enum variant, struct or const.
2704 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2709 // The below shouldn't happen because all
2710 // qualified paths should be in PatQPath.
2711 TypecheckRequired =>
2712 self.session.span_bug(path.span,
2713 "resolve_possibly_assoc_item claimed
2715 that a path in PatEnum requires typecheck
2717 to resolve, but qualified paths should be
2720 ResolveAttempt(resolution) => resolution,
2722 if let Some(path_res) = resolution {
2723 match path_res.base_def {
2724 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2725 self.record_def(pattern.id, path_res);
2728 resolve_error(&self,
2730 ResolutionError::StaticVariableReference);
2731 self.record_def(pattern.id, err_path_resolution());
2734 // If anything ends up here entirely resolved,
2735 // it's an error. If anything ends up here
2736 // partially resolved, that's OK, because it may
2737 // be a `T::CONST` that typeck will resolve.
2738 if path_res.depth == 0 {
2742 ResolutionError::NotAnEnumVariantStructOrConst(
2750 self.record_def(pattern.id, err_path_resolution());
2752 let const_name = path.segments
2757 let traits = self.get_traits_containing_item(const_name);
2758 self.trait_map.insert(pattern.id, traits);
2759 self.record_def(pattern.id, path_res);
2767 ResolutionError::UnresolvedEnumVariantStructOrConst(
2768 &path.segments.last().unwrap().identifier.name.as_str())
2770 self.record_def(pattern.id, err_path_resolution());
2772 intravisit::walk_path(self, path);
2775 PatQPath(ref qself, ref path) => {
2776 // Associated constants only.
2777 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2782 TypecheckRequired => {
2783 // All `<T>::CONST` should end up here, and will
2784 // require use of the trait map to resolve
2785 // during typechecking.
2786 let const_name = path.segments
2791 let traits = self.get_traits_containing_item(const_name);
2792 self.trait_map.insert(pattern.id, traits);
2793 intravisit::walk_pat(self, pattern);
2796 ResolveAttempt(resolution) => resolution,
2798 if let Some(path_res) = resolution {
2799 match path_res.base_def {
2800 // All `<T as Trait>::CONST` should end up here, and
2801 // have the trait already selected.
2802 DefAssociatedConst(..) => {
2803 self.record_def(pattern.id, path_res);
2809 ResolutionError::NotAnAssociatedConst(
2810 &path.segments.last().unwrap().identifier.name.as_str()
2813 self.record_def(pattern.id, err_path_resolution());
2819 ResolutionError::UnresolvedAssociatedConst(&path.segments
2825 self.record_def(pattern.id, err_path_resolution());
2827 intravisit::walk_pat(self, pattern);
2830 PatStruct(ref path, _, _) => {
2831 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2832 Some(definition) => {
2833 self.record_def(pattern.id, definition);
2836 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2840 ResolutionError::DoesNotNameAStruct(
2841 &*path_names_to_string(path, 0))
2843 self.record_def(pattern.id, err_path_resolution());
2846 intravisit::walk_path(self, path);
2849 PatLit(_) | PatRange(..) => {
2850 intravisit::walk_pat(self, pattern);
2861 fn resolve_bare_identifier_pattern(&mut self,
2864 -> BareIdentifierPatternResolution {
2865 let module = self.current_module.clone();
2866 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2867 Success((target, _)) => {
2868 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2870 target.binding.borrow());
2871 match target.binding.def() {
2873 panic!("resolved name in the value namespace to a set of name bindings \
2876 // For the two success cases, this lookup can be
2877 // considered as not having a private component because
2878 // the lookup happened only within the current module.
2879 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2880 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2882 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2883 return FoundConst(def, LastMod(AllPublic), name);
2885 Some(DefStatic(..)) => {
2886 resolve_error(self, span, ResolutionError::StaticVariableReference);
2887 return BareIdentifierPatternUnresolved;
2889 _ => return BareIdentifierPatternUnresolved
2894 panic!("unexpected indeterminate result");
2898 Some((span, msg)) => {
2899 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2904 debug!("(resolve bare identifier pattern) failed to find {}", name);
2905 return BareIdentifierPatternUnresolved;
2910 /// Handles paths that may refer to associated items
2911 fn resolve_possibly_assoc_item(&mut self,
2913 maybe_qself: Option<&hir::QSelf>,
2915 namespace: Namespace,
2917 -> AssocItemResolveResult {
2918 let max_assoc_types;
2922 if qself.position == 0 {
2923 return TypecheckRequired;
2925 max_assoc_types = path.segments.len() - qself.position;
2926 // Make sure the trait is valid.
2927 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2930 max_assoc_types = path.segments.len();
2934 let mut resolution = self.with_no_errors(|this| {
2935 this.resolve_path(id, path, 0, namespace, check_ribs)
2937 for depth in 1..max_assoc_types {
2938 if resolution.is_some() {
2941 self.with_no_errors(|this| {
2942 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2945 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2946 // A module is not a valid type or value.
2949 ResolveAttempt(resolution)
2952 /// If `check_ribs` is true, checks the local definitions first; i.e.
2953 /// doesn't skip straight to the containing module.
2954 /// Skips `path_depth` trailing segments, which is also reflected in the
2955 /// returned value. See `middle::def::PathResolution` for more info.
2956 pub fn resolve_path(&mut self,
2960 namespace: Namespace,
2962 -> Option<PathResolution> {
2963 let span = path.span;
2964 let segments = &path.segments[..path.segments.len() - path_depth];
2966 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2969 let def = self.resolve_crate_relative_path(span, segments, namespace);
2970 return def.map(mk_res);
2973 // Try to find a path to an item in a module.
2974 let last_ident = segments.last().unwrap().identifier;
2975 if segments.len() <= 1 {
2976 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2977 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2979 PathResolution::new(def, LastMod(AllPublic), path_depth)
2983 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2984 let def = self.resolve_module_relative_path(span, segments, namespace);
2985 match (def, unqualified_def) {
2986 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2988 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2991 "unnecessary qualification".to_string());
2999 // Resolve a single identifier
3000 fn resolve_identifier(&mut self,
3001 identifier: hir::Ident,
3002 namespace: Namespace,
3005 -> Option<LocalDef> {
3006 // First, check to see whether the name is a primitive type.
3007 if namespace == TypeNS {
3008 if let Some(&prim_ty) = self.primitive_type_table
3010 .get(&identifier.unhygienic_name) {
3011 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
3016 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
3021 let name = identifier.unhygienic_name;
3022 self.resolve_item_by_name_in_lexical_scope(name, namespace, record_used)
3023 .map(LocalDef::from_def)
3026 // Resolve a local definition, potentially adjusting for closures.
3027 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
3028 let ribs = match local_def.ribs {
3029 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
3030 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
3033 let mut def = local_def.def;
3036 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
3038 DefLocal(_, node_id) => {
3042 // Nothing to do. Continue.
3044 ClosureRibKind(function_id) => {
3046 let node_def_id = self.ast_map.local_def_id(node_id);
3048 let seen = self.freevars_seen
3050 .or_insert_with(|| NodeMap());
3051 if let Some(&index) = seen.get(&node_id) {
3052 def = DefUpvar(node_def_id, node_id, index, function_id);
3055 let vec = self.freevars
3057 .or_insert_with(|| vec![]);
3058 let depth = vec.len();
3064 def = DefUpvar(node_def_id, node_id, depth, function_id);
3065 seen.insert(node_id, depth);
3067 ItemRibKind | MethodRibKind => {
3068 // This was an attempt to access an upvar inside a
3069 // named function item. This is not allowed, so we
3073 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3076 ConstantItemRibKind => {
3077 // Still doesn't deal with upvars
3080 ResolutionError::AttemptToUseNonConstantValueInConstant);
3086 DefTyParam(..) | DefSelfTy(..) => {
3089 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3090 // Nothing to do. Continue.
3093 // This was an attempt to use a type parameter outside
3098 ResolutionError::TypeParametersFromOuterFunction);
3101 ConstantItemRibKind => {
3103 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3114 // resolve a "module-relative" path, e.g. a::b::c
3115 fn resolve_module_relative_path(&mut self,
3117 segments: &[hir::PathSegment],
3118 namespace: Namespace)
3119 -> Option<(Def, LastPrivate)> {
3120 let module_path = segments.split_last()
3124 .map(|ps| ps.identifier.name)
3125 .collect::<Vec<_>>();
3127 let containing_module;
3129 let current_module = self.current_module.clone();
3130 match self.resolve_module_path(current_module,
3136 let (span, msg) = match err {
3137 Some((span, msg)) => (span, msg),
3139 let msg = format!("Use of undeclared type or module `{}`",
3140 names_to_string(&module_path));
3145 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3148 Indeterminate => panic!("indeterminate unexpected"),
3149 Success((resulting_module, resulting_last_private)) => {
3150 containing_module = resulting_module;
3151 last_private = resulting_last_private;
3155 let name = segments.last().unwrap().identifier.name;
3156 let def = match self.resolve_name_in_module(containing_module.clone(),
3159 NameSearchType::PathSearch,
3161 Success((Target { binding, .. }, _)) => {
3162 let (def, lp) = binding.def_and_lp();
3163 (def, last_private.or(lp))
3167 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3168 self.used_crates.insert(kid);
3173 /// Invariant: This must be called only during main resolution, not during
3174 /// import resolution.
3175 fn resolve_crate_relative_path(&mut self,
3177 segments: &[hir::PathSegment],
3178 namespace: Namespace)
3179 -> Option<(Def, LastPrivate)> {
3180 let module_path = segments.split_last()
3184 .map(|ps| ps.identifier.name)
3185 .collect::<Vec<_>>();
3187 let root_module = self.graph_root.clone();
3189 let containing_module;
3191 match self.resolve_module_path_from_root(root_module,
3196 LastMod(AllPublic)) {
3198 let (span, msg) = match err {
3199 Some((span, msg)) => (span, msg),
3201 let msg = format!("Use of undeclared module `::{}`",
3202 names_to_string(&module_path[..]));
3207 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3212 panic!("indeterminate unexpected");
3215 Success((resulting_module, resulting_last_private)) => {
3216 containing_module = resulting_module;
3217 last_private = resulting_last_private;
3221 let name = segments.last().unwrap().identifier.name;
3222 match self.resolve_name_in_module(containing_module,
3225 NameSearchType::PathSearch,
3227 Success((Target { binding, .. }, _)) => {
3228 let (def, lp) = binding.def_and_lp();
3229 Some((def, last_private.or(lp)))
3235 fn resolve_identifier_in_local_ribs(&mut self,
3237 namespace: Namespace)
3238 -> Option<LocalDef> {
3239 // Check the local set of ribs.
3240 let (name, ribs) = match namespace {
3241 ValueNS => (ident.name, &self.value_ribs),
3242 TypeNS => (ident.unhygienic_name, &self.type_ribs),
3245 for (i, rib) in ribs.iter().enumerate().rev() {
3246 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3249 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3253 return Some(LocalDef {
3254 ribs: Some((namespace, i)),
3259 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3271 fn resolve_item_by_name_in_lexical_scope(&mut self,
3273 namespace: Namespace,
3277 let module = self.current_module.clone();
3278 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
3279 Success((target, _)) => {
3280 match target.binding.def() {
3282 // This can happen if we were looking for a type and
3283 // found a module instead. Modules don't have defs.
3284 debug!("(resolving item path by identifier in lexical scope) failed to \
3285 resolve {} after success...",
3290 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3292 // This lookup is "all public" because it only searched
3293 // for one identifier in the current module (couldn't
3294 // have passed through reexports or anything like that.
3300 panic!("unexpected indeterminate result");
3303 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3306 if let Some((span, msg)) = err {
3307 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3315 fn with_no_errors<T, F>(&mut self, f: F) -> T
3316 where F: FnOnce(&mut Resolver) -> T
3318 self.emit_errors = false;
3320 self.emit_errors = true;
3324 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3325 fn extract_path_and_node_id(t: &Ty,
3326 allow: FallbackChecks)
3327 -> Option<(Path, NodeId, FallbackChecks)> {
3329 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3330 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3331 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3332 // This doesn't handle the remaining `Ty` variants as they are not
3333 // that commonly the self_type, it might be interesting to provide
3334 // support for those in future.
3339 fn get_module(this: &mut Resolver,
3341 name_path: &[ast::Name])
3342 -> Option<Rc<Module>> {
3343 let root = this.current_module.clone();
3344 let last_name = name_path.last().unwrap();
3346 if name_path.len() == 1 {
3347 match this.primitive_type_table.primitive_types.get(last_name) {
3350 match this.current_module.children.borrow().get(last_name) {
3351 Some(child) => child.type_ns.module(),
3357 match this.resolve_module_path(root,
3362 Success((module, _)) => Some(module),
3368 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3369 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3370 let sig = match this.ast_map.get(node_id) {
3371 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3372 hir::MethodTraitItem(ref sig, _) => sig,
3375 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3376 hir::ImplItemKind::Method(ref sig, _) => sig,
3381 sig.explicit_self.node == hir::SelfStatic
3383 this.session.cstore.is_static_method(did)
3387 let (path, node_id, allowed) = match self.current_self_type {
3388 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3390 None => return NoSuggestion,
3392 None => return NoSuggestion,
3395 if allowed == Everything {
3396 // Look for a field with the same name in the current self_type.
3397 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3398 Some(DefTy(did, _)) |
3399 Some(DefStruct(did)) |
3400 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3403 if fields.iter().any(|&field_name| name == field_name) {
3408 _ => {} // Self type didn't resolve properly
3412 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3414 // Look for a method in the current self type's impl module.
3415 if let Some(module) = get_module(self, path.span, &name_path) {
3416 if let Some(binding) = module.children.borrow().get(&name) {
3417 if let Some(DefMethod(did)) = binding.value_ns.def() {
3418 if is_static_method(self, did) {
3419 return StaticMethod(path_names_to_string(&path, 0));
3421 if self.current_trait_ref.is_some() {
3423 } else if allowed == Everything {
3430 // Look for a method in the current trait.
3431 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3432 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3433 if is_static_method(self, did) {
3434 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3444 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3445 if let Some(macro_name) = self.session.available_macros
3446 .borrow().iter().find(|n| n.as_str() == name) {
3447 return SuggestionType::Macro(format!("{}!", macro_name));
3450 let names = self.value_ribs
3453 .flat_map(|rib| rib.bindings.keys());
3455 if let Some(found) = find_best_match_for_name(names, name, None) {
3456 if name != &*found {
3457 return SuggestionType::Function(found);
3459 } SuggestionType::NotFound
3462 fn resolve_expr(&mut self, expr: &Expr) {
3463 // First, record candidate traits for this expression if it could
3464 // result in the invocation of a method call.
3466 self.record_candidate_traits_for_expr_if_necessary(expr);
3468 // Next, resolve the node.
3470 ExprPath(ref maybe_qself, ref path) => {
3471 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3472 maybe_qself.as_ref(),
3476 // `<T>::a::b::c` is resolved by typeck alone.
3477 TypecheckRequired => {
3478 let method_name = path.segments.last().unwrap().identifier.name;
3479 let traits = self.get_traits_containing_item(method_name);
3480 self.trait_map.insert(expr.id, traits);
3481 intravisit::walk_expr(self, expr);
3484 ResolveAttempt(resolution) => resolution,
3487 // This is a local path in the value namespace. Walk through
3488 // scopes looking for it.
3489 if let Some(path_res) = resolution {
3490 // Check if struct variant
3491 if let DefVariant(_, _, true) = path_res.base_def {
3492 let path_name = path_names_to_string(path, 0);
3494 let mut err = resolve_struct_error(self,
3496 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3498 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3500 if self.emit_errors {
3501 err.fileline_help(expr.span, &msg);
3503 err.span_help(expr.span, &msg);
3506 self.record_def(expr.id, err_path_resolution());
3508 // Write the result into the def map.
3509 debug!("(resolving expr) resolved `{}`",
3510 path_names_to_string(path, 0));
3512 // Partial resolutions will need the set of traits in scope,
3513 // so they can be completed during typeck.
3514 if path_res.depth != 0 {
3515 let method_name = path.segments.last().unwrap().identifier.name;
3516 let traits = self.get_traits_containing_item(method_name);
3517 self.trait_map.insert(expr.id, traits);
3520 self.record_def(expr.id, path_res);
3523 // Be helpful if the name refers to a struct
3524 // (The pattern matching def_tys where the id is in self.structs
3525 // matches on regular structs while excluding tuple- and enum-like
3526 // structs, which wouldn't result in this error.)
3527 let path_name = path_names_to_string(path, 0);
3528 let type_res = self.with_no_errors(|this| {
3529 this.resolve_path(expr.id, path, 0, TypeNS, false)
3532 self.record_def(expr.id, err_path_resolution());
3533 match type_res.map(|r| r.base_def) {
3534 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3535 let mut err = resolve_struct_error(self,
3537 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3539 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3541 if self.emit_errors {
3542 err.fileline_help(expr.span, &msg);
3544 err.span_help(expr.span, &msg);
3549 // Keep reporting some errors even if they're ignored above.
3550 self.resolve_path(expr.id, path, 0, ValueNS, true);
3552 let mut method_scope = false;
3553 self.value_ribs.iter().rev().all(|rib| {
3554 method_scope = match rib.kind {
3555 MethodRibKind => true,
3556 ItemRibKind | ConstantItemRibKind => false,
3557 _ => return true, // Keep advancing
3559 false // Stop advancing
3562 if method_scope && special_names::self_.as_str() == &path_name[..] {
3565 ResolutionError::SelfNotAvailableInStaticMethod);
3567 let last_name = path.segments.last().unwrap().identifier.name;
3568 let mut msg = match self.find_fallback_in_self_type(last_name) {
3570 // limit search to 5 to reduce the number
3571 // of stupid suggestions
3572 match self.find_best_match(&path_name) {
3573 SuggestionType::Macro(s) => {
3574 format!("the macro `{}`", s)
3576 SuggestionType::Function(s) => format!("`{}`", s),
3577 SuggestionType::NotFound => "".to_string(),
3580 Field => format!("`self.{}`", path_name),
3582 TraitItem => format!("to call `self.{}`", path_name),
3583 TraitMethod(path_str) |
3584 StaticMethod(path_str) =>
3585 format!("to call `{}::{}`", path_str, path_name),
3588 let mut context = UnresolvedNameContext::Other;
3589 if !msg.is_empty() {
3590 msg = format!(". Did you mean {}?", msg);
3592 // we check if this a module and if so, we display a help
3594 let name_path = path.segments.iter()
3595 .map(|seg| seg.identifier.name)
3596 .collect::<Vec<_>>();
3597 let current_module = self.current_module.clone();
3599 match self.resolve_module_path(current_module,
3605 context = UnresolvedNameContext::PathIsMod(expr.id);
3613 ResolutionError::UnresolvedName(
3614 &*path_name, &*msg, context));
3620 intravisit::walk_expr(self, expr);
3623 ExprStruct(ref path, _, _) => {
3624 // Resolve the path to the structure it goes to. We don't
3625 // check to ensure that the path is actually a structure; that
3626 // is checked later during typeck.
3627 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3628 Some(definition) => self.record_def(expr.id, definition),
3630 debug!("(resolving expression) didn't find struct def",);
3634 ResolutionError::DoesNotNameAStruct(
3635 &*path_names_to_string(path, 0))
3637 self.record_def(expr.id, err_path_resolution());
3641 intravisit::walk_expr(self, expr);
3644 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3645 self.with_label_rib(|this| {
3646 let def_like = DlDef(DefLabel(expr.id));
3649 let rib = this.label_ribs.last_mut().unwrap();
3650 rib.bindings.insert(label.name, def_like);
3653 intravisit::walk_expr(this, expr);
3657 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3658 match self.search_label(label.node.name) {
3660 self.record_def(expr.id, err_path_resolution());
3663 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3665 Some(DlDef(def @ DefLabel(_))) => {
3666 // Since this def is a label, it is never read.
3667 self.record_def(expr.id,
3670 last_private: LastMod(AllPublic),
3675 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3681 intravisit::walk_expr(self, expr);
3686 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3688 ExprField(_, name) => {
3689 // FIXME(#6890): Even though you can't treat a method like a
3690 // field, we need to add any trait methods we find that match
3691 // the field name so that we can do some nice error reporting
3692 // later on in typeck.
3693 let traits = self.get_traits_containing_item(name.node);
3694 self.trait_map.insert(expr.id, traits);
3696 ExprMethodCall(name, _, _) => {
3697 debug!("(recording candidate traits for expr) recording traits for {}",
3699 let traits = self.get_traits_containing_item(name.node);
3700 self.trait_map.insert(expr.id, traits);
3708 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3709 debug!("(getting traits containing item) looking for '{}'", name);
3711 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3712 debug!("(adding trait info) found trait {:?} for method '{}'",
3715 found_traits.push(trait_def_id);
3718 let mut found_traits = Vec::new();
3719 let mut search_module = self.current_module.clone();
3721 // Look for the current trait.
3722 match self.current_trait_ref {
3723 Some((trait_def_id, _)) => {
3724 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3725 add_trait_info(&mut found_traits, trait_def_id, name);
3728 None => {} // Nothing to do.
3731 // Look for trait children.
3732 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3735 for (_, child_names) in search_module.children.borrow().iter() {
3736 let def = match child_names.type_ns.def() {
3740 let trait_def_id = match def {
3741 DefTrait(trait_def_id) => trait_def_id,
3744 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3745 add_trait_info(&mut found_traits, trait_def_id, name);
3750 // Look for imports.
3751 for (_, import) in search_module.import_resolutions.borrow().iter() {
3752 let target = match import.type_ns.target {
3754 Some(ref target) => target,
3756 let did = match target.binding.def() {
3757 Some(DefTrait(trait_def_id)) => trait_def_id,
3758 Some(..) | None => continue,
3760 if self.trait_item_map.contains_key(&(name, did)) {
3761 add_trait_info(&mut found_traits, did, name);
3762 let id = import.type_ns.id;
3763 self.used_imports.insert((id, TypeNS));
3764 let trait_name = self.get_trait_name(did);
3765 self.record_import_use(id, trait_name);
3766 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3767 self.used_crates.insert(kid);
3772 match search_module.parent_link.clone() {
3773 NoParentLink | ModuleParentLink(..) => break,
3774 BlockParentLink(parent_module, _) => {
3775 search_module = parent_module.upgrade().unwrap();
3783 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3784 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3785 assert!(match resolution.last_private {
3786 LastImport{..} => false,
3789 "Import should only be used for `use` directives");
3791 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3792 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3793 self.session.span_bug(span,
3794 &format!("path resolved multiple times ({:?} before, {:?} now)",
3800 fn enforce_default_binding_mode(&mut self,
3802 pat_binding_mode: BindingMode,
3804 match pat_binding_mode {
3805 BindByValue(_) => {}
3809 ResolutionError::CannotUseRefBindingModeWith(descr));
3817 // Diagnostics are not particularly efficient, because they're rarely
3821 #[allow(dead_code)] // useful for debugging
3822 fn dump_module(&mut self, module_: Rc<Module>) {
3823 debug!("Dump of module `{}`:", module_to_string(&*module_));
3825 debug!("Children:");
3826 build_reduced_graph::populate_module_if_necessary(self, &module_);
3827 for (&name, _) in module_.children.borrow().iter() {
3828 debug!("* {}", name);
3831 debug!("Import resolutions:");
3832 let import_resolutions = module_.import_resolutions.borrow();
3833 for (&name, import_resolution) in import_resolutions.iter() {
3835 match import_resolution.value_ns.target {
3837 value_repr = "".to_string();
3840 value_repr = " value:?".to_string();
3846 match import_resolution.type_ns.target {
3848 type_repr = "".to_string();
3851 type_repr = " type:?".to_string();
3856 debug!("* {}:{}{}", name, value_repr, type_repr);
3862 fn names_to_string(names: &[Name]) -> String {
3863 let mut first = true;
3864 let mut result = String::new();
3869 result.push_str("::")
3871 result.push_str(&name.as_str());
3876 fn path_names_to_string(path: &Path, depth: usize) -> String {
3877 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3879 .map(|seg| seg.identifier.name)
3881 names_to_string(&names[..])
3884 /// A somewhat inefficient routine to obtain the name of a module.
3885 fn module_to_string(module: &Module) -> String {
3886 let mut names = Vec::new();
3888 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3889 match module.parent_link {
3891 ModuleParentLink(ref module, name) => {
3893 collect_mod(names, &*module.upgrade().unwrap());
3895 BlockParentLink(ref module, _) => {
3896 // danger, shouldn't be ident?
3897 names.push(special_idents::opaque.name);
3898 collect_mod(names, &*module.upgrade().unwrap());
3902 collect_mod(&mut names, module);
3904 if names.is_empty() {
3905 return "???".to_string();
3907 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3910 fn err_path_resolution() -> PathResolution {
3913 last_private: LastMod(AllPublic),
3919 pub struct CrateMap {
3920 pub def_map: RefCell<DefMap>,
3921 pub freevars: FreevarMap,
3922 pub export_map: ExportMap,
3923 pub trait_map: TraitMap,
3924 pub external_exports: ExternalExports,
3925 pub glob_map: Option<GlobMap>,
3928 #[derive(PartialEq,Copy, Clone)]
3929 pub enum MakeGlobMap {
3934 /// Entry point to crate resolution.
3935 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3936 ast_map: &'a hir_map::Map<'tcx>,
3937 make_glob_map: MakeGlobMap)
3939 let krate = ast_map.krate();
3940 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3942 resolver.resolve_crate(krate);
3944 check_unused::check_crate(&mut resolver, krate);
3947 def_map: resolver.def_map,
3948 freevars: resolver.freevars,
3949 export_map: resolver.export_map,
3950 trait_map: resolver.trait_map,
3951 external_exports: resolver.external_exports,
3952 glob_map: if resolver.make_glob_map {
3953 Some(resolver.glob_map)
3960 /// Builds a name resolution walker to be used within this module,
3961 /// or used externally, with an optional callback function.
3963 /// The callback takes a &mut bool which allows callbacks to end a
3964 /// walk when set to true, passing through the rest of the walk, while
3965 /// preserving the ribs + current module. This allows resolve_path
3966 /// calls to be made with the correct scope info. The node in the
3967 /// callback corresponds to the current node in the walk.
3968 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3969 ast_map: &'a hir_map::Map<'tcx>,
3971 make_glob_map: MakeGlobMap,
3972 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3973 -> Resolver<'a, 'tcx> {
3974 let mut resolver = Resolver::new(session, ast_map, make_glob_map);
3976 resolver.callback = callback;
3978 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3979 session.abort_if_errors();
3981 resolve_imports::resolve_imports(&mut resolver);
3982 session.abort_if_errors();
3984 record_exports::record(&mut resolver);
3985 session.abort_if_errors();
3990 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }