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/")]
18 #![cfg_attr(not(stage0), deny(warnings))]
20 #![feature(associated_consts)]
21 #![feature(borrow_state)]
22 #![feature(rustc_diagnostic_macros)]
23 #![feature(rustc_private)]
24 #![feature(staged_api)]
33 extern crate rustc_bitflags;
34 extern crate rustc_front;
37 use self::PatternBindingMode::*;
38 use self::Namespace::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::BareIdentifierPatternResolution::*;
47 use self::ParentLink::*;
48 use self::FallbackChecks::*;
50 use rustc::dep_graph::DepNode;
51 use rustc::front::map as hir_map;
52 use rustc::session::Session;
54 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
55 use rustc::middle::def::*;
56 use rustc::middle::def_id::DefId;
57 use rustc::middle::pat_util::pat_bindings;
58 use rustc::middle::privacy::*;
59 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
60 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
61 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
63 use syntax::ast::{self, FloatTy};
64 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
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, PatKind, Path, PrimTy};
84 use rustc_front::hir::{PathSegment, PathParameters};
85 use rustc_front::hir::HirVec;
86 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
87 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
88 use rustc_front::util::walk_pat;
90 use std::collections::{HashMap, HashSet};
91 use std::cell::{Cell, RefCell};
93 use std::mem::replace;
95 use resolve_imports::{ImportDirective, NameResolution};
97 // NB: This module needs to be declared first so diagnostics are
98 // registered before they are used.
102 mod build_reduced_graph;
105 // Perform the callback, not walking deeper if the return is true
106 macro_rules! execute_callback {
107 ($node: expr, $walker: expr) => (
108 if let Some(ref callback) = $walker.callback {
109 if callback($node, &mut $walker.resolved) {
116 enum SuggestionType {
118 Function(token::InternedString),
122 /// Candidates for a name resolution failure
123 pub struct SuggestedCandidates {
125 candidates: Vec<Path>,
128 pub enum ResolutionError<'a> {
129 /// error E0401: can't use type parameters from outer function
130 TypeParametersFromOuterFunction,
131 /// error E0402: cannot use an outer type parameter in this context
132 OuterTypeParameterContext,
133 /// error E0403: the name is already used for a type parameter in this type parameter list
134 NameAlreadyUsedInTypeParameterList(Name),
135 /// error E0404: is not a trait
136 IsNotATrait(&'a str),
137 /// error E0405: use of undeclared trait name
138 UndeclaredTraitName(&'a str, SuggestedCandidates),
139 /// error E0406: undeclared associated type
140 UndeclaredAssociatedType,
141 /// error E0407: method is not a member of trait
142 MethodNotMemberOfTrait(Name, &'a str),
143 /// error E0437: type is not a member of trait
144 TypeNotMemberOfTrait(Name, &'a str),
145 /// error E0438: const is not a member of trait
146 ConstNotMemberOfTrait(Name, &'a str),
147 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
148 VariableNotBoundInPattern(Name, usize),
149 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
150 VariableBoundWithDifferentMode(Name, usize),
151 /// error E0410: variable from pattern is not bound in pattern #1
152 VariableNotBoundInParentPattern(Name, usize),
153 /// error E0411: use of `Self` outside of an impl or trait
154 SelfUsedOutsideImplOrTrait,
155 /// error E0412: use of undeclared
156 UseOfUndeclared(&'a str, &'a str, SuggestedCandidates),
157 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
158 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
159 /// error E0414: only irrefutable patterns allowed here
160 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
161 /// error E0415: identifier is bound more than once in this parameter list
162 IdentifierBoundMoreThanOnceInParameterList(&'a str),
163 /// error E0416: identifier is bound more than once in the same pattern
164 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
165 /// error E0417: static variables cannot be referenced in a pattern
166 StaticVariableReference,
167 /// error E0418: is not an enum variant, struct or const
168 NotAnEnumVariantStructOrConst(&'a str),
169 /// error E0419: unresolved enum variant, struct or const
170 UnresolvedEnumVariantStructOrConst(&'a str),
171 /// error E0420: is not an associated const
172 NotAnAssociatedConst(&'a str),
173 /// error E0421: unresolved associated const
174 UnresolvedAssociatedConst(&'a str),
175 /// error E0422: does not name a struct
176 DoesNotNameAStruct(&'a str),
177 /// error E0423: is a struct variant name, but this expression uses it like a function name
178 StructVariantUsedAsFunction(&'a str),
179 /// error E0424: `self` is not available in a static method
180 SelfNotAvailableInStaticMethod,
181 /// error E0425: unresolved name
182 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
183 /// error E0426: use of undeclared label
184 UndeclaredLabel(&'a str),
185 /// error E0427: cannot use `ref` binding mode with ...
186 CannotUseRefBindingModeWith(&'a str),
187 /// error E0428: duplicate definition
188 DuplicateDefinition(&'a str, Name),
189 /// error E0429: `self` imports are only allowed within a { } list
190 SelfImportsOnlyAllowedWithin,
191 /// error E0430: `self` import can only appear once in the list
192 SelfImportCanOnlyAppearOnceInTheList,
193 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
194 SelfImportOnlyInImportListWithNonEmptyPrefix,
195 /// error E0432: unresolved import
196 UnresolvedImport(Option<(&'a str, &'a str)>),
197 /// error E0433: failed to resolve
198 FailedToResolve(&'a str),
199 /// error E0434: can't capture dynamic environment in a fn item
200 CannotCaptureDynamicEnvironmentInFnItem,
201 /// error E0435: attempt to use a non-constant value in a constant
202 AttemptToUseNonConstantValueInConstant,
205 /// Context of where `ResolutionError::UnresolvedName` arose.
206 #[derive(Clone, PartialEq, Eq, Debug)]
207 pub enum UnresolvedNameContext {
208 /// `PathIsMod(id)` indicates that a given path, used in
209 /// expression context, actually resolved to a module rather than
210 /// a value. The `id` attached to the variant is the node id of
211 /// the erroneous path expression.
212 PathIsMod(ast::NodeId),
214 /// `Other` means we have no extra information about the context
215 /// of the unresolved name error. (Maybe we could eliminate all
216 /// such cases; but for now, this is an information-free default.)
220 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
221 span: syntax::codemap::Span,
222 resolution_error: ResolutionError<'b>) {
223 resolve_struct_error(resolver, span, resolution_error).emit();
226 fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
227 span: syntax::codemap::Span,
228 resolution_error: ResolutionError<'b>)
229 -> DiagnosticBuilder<'a> {
230 if !resolver.emit_errors {
231 return resolver.session.diagnostic().struct_dummy();
234 match resolution_error {
235 ResolutionError::TypeParametersFromOuterFunction => {
236 struct_span_err!(resolver.session,
239 "can't use type parameters from outer function; try using a local \
240 type parameter instead")
242 ResolutionError::OuterTypeParameterContext => {
243 struct_span_err!(resolver.session,
246 "cannot use an outer type parameter in this context")
248 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
249 struct_span_err!(resolver.session,
252 "the name `{}` is already used for a type parameter in this type \
256 ResolutionError::IsNotATrait(name) => {
257 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
259 ResolutionError::UndeclaredTraitName(name, candidates) => {
260 let mut err = struct_span_err!(resolver.session,
263 "trait `{}` is not in scope",
265 show_candidates(&mut err, span, &candidates);
268 ResolutionError::UndeclaredAssociatedType => {
269 struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
271 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
272 struct_span_err!(resolver.session,
275 "method `{}` is not a member of trait `{}`",
279 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
280 struct_span_err!(resolver.session,
283 "type `{}` is not a member of trait `{}`",
287 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
288 struct_span_err!(resolver.session,
291 "const `{}` is not a member of trait `{}`",
295 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
296 struct_span_err!(resolver.session,
299 "variable `{}` from pattern #1 is not bound in pattern #{}",
303 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
304 struct_span_err!(resolver.session,
307 "variable `{}` is bound with different mode in pattern #{} than in \
312 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
313 struct_span_err!(resolver.session,
316 "variable `{}` from pattern #{} is not bound in pattern #1",
320 ResolutionError::SelfUsedOutsideImplOrTrait => {
321 struct_span_err!(resolver.session,
324 "use of `Self` outside of an impl or trait")
326 ResolutionError::UseOfUndeclared(kind, name, candidates) => {
327 let mut err = struct_span_err!(resolver.session,
330 "{} `{}` is undefined or not in scope",
333 show_candidates(&mut err, span, &candidates);
336 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
337 struct_span_err!(resolver.session,
340 "declaration of `{}` shadows an enum variant \
341 or unit-like struct in scope",
344 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
345 let mut err = struct_span_err!(resolver.session,
348 "only irrefutable patterns allowed here");
350 "there already is a constant in scope sharing the same \
351 name as this pattern");
352 if let Some(sp) = resolver.ast_map.span_if_local(did) {
353 err.span_note(sp, "constant defined here");
355 if let Success(binding) = resolver.current_module.resolve_name(name, ValueNS, true) {
356 if binding.is_import() {
357 err.span_note(binding.span.unwrap(), "constant imported here");
362 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
363 struct_span_err!(resolver.session,
366 "identifier `{}` is bound more than once in this parameter list",
369 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
370 struct_span_err!(resolver.session,
373 "identifier `{}` is bound more than once in the same pattern",
376 ResolutionError::StaticVariableReference => {
377 struct_span_err!(resolver.session,
380 "static variables cannot be referenced in a pattern, use a \
383 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
384 struct_span_err!(resolver.session,
387 "`{}` is not an enum variant, struct or const",
390 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
391 struct_span_err!(resolver.session,
394 "unresolved enum variant, struct or const `{}`",
397 ResolutionError::NotAnAssociatedConst(name) => {
398 struct_span_err!(resolver.session,
401 "`{}` is not an associated const",
404 ResolutionError::UnresolvedAssociatedConst(name) => {
405 struct_span_err!(resolver.session,
408 "unresolved associated const `{}`",
411 ResolutionError::DoesNotNameAStruct(name) => {
412 struct_span_err!(resolver.session,
415 "`{}` does not name a structure",
418 ResolutionError::StructVariantUsedAsFunction(path_name) => {
419 struct_span_err!(resolver.session,
422 "`{}` is the name of a struct or struct variant, but this expression \
423 uses it like a function name",
426 ResolutionError::SelfNotAvailableInStaticMethod => {
427 struct_span_err!(resolver.session,
430 "`self` is not available in a static method. Maybe a `self` \
431 argument is missing?")
433 ResolutionError::UnresolvedName(path, msg, context) => {
434 let mut err = struct_span_err!(resolver.session,
437 "unresolved name `{}`{}",
442 UnresolvedNameContext::Other => { } // no help available
443 UnresolvedNameContext::PathIsMod(id) => {
444 let mut help_msg = String::new();
445 let parent_id = resolver.ast_map.get_parent_node(id);
446 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
448 ExprField(_, ident) => {
449 help_msg = format!("To reference an item from the \
450 `{module}` module, use \
451 `{module}::{ident}`",
455 ExprMethodCall(ident, _, _) => {
456 help_msg = format!("To call a function from the \
457 `{module}` module, use \
458 `{module}::{ident}(..)`",
463 help_msg = format!("No function corresponds to `{module}(..)`",
466 _ => { } // no help available
469 help_msg = format!("Module `{module}` cannot be the value of an expression",
473 if !help_msg.is_empty() {
474 err.fileline_help(span, &help_msg);
480 ResolutionError::UndeclaredLabel(name) => {
481 struct_span_err!(resolver.session,
484 "use of undeclared label `{}`",
487 ResolutionError::CannotUseRefBindingModeWith(descr) => {
488 struct_span_err!(resolver.session,
491 "cannot use `ref` binding mode with {}",
494 ResolutionError::DuplicateDefinition(namespace, name) => {
495 struct_span_err!(resolver.session,
498 "duplicate definition of {} `{}`",
502 ResolutionError::SelfImportsOnlyAllowedWithin => {
503 struct_span_err!(resolver.session,
507 "`self` imports are only allowed within a { } list")
509 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
510 struct_span_err!(resolver.session,
513 "`self` import can only appear once in the list")
515 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
516 struct_span_err!(resolver.session,
519 "`self` import can only appear in an import list with a \
522 ResolutionError::UnresolvedImport(name) => {
523 let msg = match name {
524 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
525 None => "unresolved import".to_owned(),
527 struct_span_err!(resolver.session, span, E0432, "{}", msg)
529 ResolutionError::FailedToResolve(msg) => {
530 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
532 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
533 struct_span_err!(resolver.session,
537 "can't capture dynamic environment in a fn item; use the || { ... } \
538 closure form instead")
540 ResolutionError::AttemptToUseNonConstantValueInConstant => {
541 struct_span_err!(resolver.session,
544 "attempt to use a non-constant value in a constant")
549 #[derive(Copy, Clone)]
552 binding_mode: BindingMode,
555 // Map from the name in a pattern to its binding mode.
556 type BindingMap = HashMap<Name, BindingInfo>;
558 #[derive(Copy, Clone, PartialEq)]
559 enum PatternBindingMode {
561 LocalIrrefutableMode,
562 ArgumentIrrefutableMode,
565 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
571 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
572 fn visit_nested_item(&mut self, item: hir::ItemId) {
573 self.visit_item(self.ast_map.expect_item(item.id))
575 fn visit_item(&mut self, item: &Item) {
576 execute_callback!(hir_map::Node::NodeItem(item), self);
577 self.resolve_item(item);
579 fn visit_arm(&mut self, arm: &Arm) {
580 self.resolve_arm(arm);
582 fn visit_block(&mut self, block: &Block) {
583 execute_callback!(hir_map::Node::NodeBlock(block), self);
584 self.resolve_block(block);
586 fn visit_expr(&mut self, expr: &Expr) {
587 execute_callback!(hir_map::Node::NodeExpr(expr), self);
588 self.resolve_expr(expr);
590 fn visit_local(&mut self, local: &Local) {
591 execute_callback!(hir_map::Node::NodeLocal(&local.pat), self);
592 self.resolve_local(local);
594 fn visit_ty(&mut self, ty: &Ty) {
595 self.resolve_type(ty);
597 fn visit_generics(&mut self, generics: &Generics) {
598 self.resolve_generics(generics);
600 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
601 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
602 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
604 // error already reported
605 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
608 intravisit::walk_poly_trait_ref(self, tref, m);
610 fn visit_variant(&mut self,
611 variant: &hir::Variant,
613 item_id: ast::NodeId) {
614 execute_callback!(hir_map::Node::NodeVariant(variant), self);
615 if let Some(ref dis_expr) = variant.node.disr_expr {
616 // resolve the discriminator expr as a constant
617 self.with_constant_rib(|this| {
618 this.visit_expr(dis_expr);
622 // `intravisit::walk_variant` without the discriminant expression.
623 self.visit_variant_data(&variant.node.data,
629 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
630 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
631 let type_parameters = match foreign_item.node {
632 ForeignItemFn(_, ref generics) => {
633 HasTypeParameters(generics, FnSpace, ItemRibKind)
635 ForeignItemStatic(..) => NoTypeParameters,
637 self.with_type_parameter_rib(type_parameters, |this| {
638 intravisit::walk_foreign_item(this, foreign_item);
641 fn visit_fn(&mut self,
642 function_kind: FnKind<'v>,
643 declaration: &'v FnDecl,
647 let rib_kind = match function_kind {
648 FnKind::ItemFn(_, generics, _, _, _, _) => {
649 self.visit_generics(generics);
652 FnKind::Method(_, sig, _) => {
653 self.visit_generics(&sig.generics);
654 self.visit_explicit_self(&sig.explicit_self);
657 FnKind::Closure => ClosureRibKind(node_id),
659 self.resolve_function(rib_kind, declaration, block);
663 pub type ErrorMessage = Option<(Span, String)>;
665 #[derive(Clone, PartialEq, Eq)]
666 pub enum ResolveResult<T> {
667 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
668 Indeterminate, // Couldn't determine due to unresolved globs.
669 Success(T), // Successfully resolved the import.
672 impl<T> ResolveResult<T> {
673 fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
675 Failed(msg) => Failed(msg),
676 Indeterminate => Indeterminate,
681 fn success(self) -> Option<T> {
683 Success(t) => Some(t),
689 enum FallbackSuggestion {
694 StaticMethod(String),
698 #[derive(Copy, Clone)]
699 enum TypeParameters<'tcx, 'a> {
701 HasTypeParameters(// Type parameters.
704 // Identifies the things that these parameters
705 // were declared on (type, fn, etc)
708 // The kind of the rib used for type parameters.
712 // The rib kind controls the translation of local
713 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
714 #[derive(Copy, Clone, Debug)]
716 // No translation needs to be applied.
719 // We passed through a closure scope at the given node ID.
720 // Translate upvars as appropriate.
721 ClosureRibKind(NodeId /* func id */),
723 // We passed through an impl or trait and are now in one of its
724 // methods. Allow references to ty params that impl or trait
725 // binds. Disallow any other upvars (including other ty params that are
729 // We passed through an item scope. Disallow upvars.
732 // We're in a constant item. Can't refer to dynamic stuff.
735 // We passed through an anonymous module.
736 AnonymousModuleRibKind(Module<'a>),
739 #[derive(Copy, Clone)]
740 enum UseLexicalScopeFlag {
745 enum ModulePrefixResult<'a> {
747 PrefixFound(Module<'a>, usize),
750 #[derive(Copy, Clone)]
751 enum AssocItemResolveResult {
752 /// Syntax such as `<T>::item`, which can't be resolved until type
755 /// We should have been able to resolve the associated item.
756 ResolveAttempt(Option<PathResolution>),
759 #[derive(Copy, Clone)]
760 enum BareIdentifierPatternResolution {
761 FoundStructOrEnumVariant(Def, LastPrivate),
762 FoundConst(Def, LastPrivate, Name),
763 BareIdentifierPatternUnresolved,
769 bindings: HashMap<Name, DefLike>,
774 fn new(kind: RibKind<'a>) -> Rib<'a> {
776 bindings: HashMap::new(),
782 /// A definition along with the index of the rib it was found on
784 ribs: Option<(Namespace, usize)>,
789 fn from_def(def: Def) -> Self {
797 /// The link from a module up to its nearest parent node.
798 #[derive(Clone,Debug)]
799 enum ParentLink<'a> {
801 ModuleParentLink(Module<'a>, Name),
802 BlockParentLink(Module<'a>, NodeId),
805 /// One node in the tree of modules.
806 pub struct ModuleS<'a> {
807 parent_link: ParentLink<'a>,
810 is_extern_crate: bool,
812 resolutions: RefCell<HashMap<(Name, Namespace), NameResolution<'a>>>,
813 imports: RefCell<Vec<ImportDirective>>,
815 // The module children of this node, including normal modules and anonymous modules.
816 // Anonymous children are pseudo-modules that are implicitly created around items
817 // contained within blocks.
819 // For example, if we have this:
827 // There will be an anonymous module created around `g` with the ID of the
828 // entry block for `f`.
829 module_children: RefCell<NodeMap<Module<'a>>>,
831 shadowed_traits: RefCell<Vec<&'a NameBinding<'a>>>,
833 // The number of unresolved globs that this module exports.
834 glob_count: Cell<usize>,
836 // The number of unresolved pub imports (both regular and globs) in this module
837 pub_count: Cell<usize>,
839 // The number of unresolved pub glob imports in this module
840 pub_glob_count: Cell<usize>,
842 // The index of the import we're resolving.
843 resolved_import_count: Cell<usize>,
845 // Whether this module is populated. If not populated, any attempt to
846 // access the children must be preceded with a
847 // `populate_module_if_necessary` call.
848 populated: Cell<bool>,
851 pub type Module<'a> = &'a ModuleS<'a>;
853 impl<'a> ModuleS<'a> {
855 fn new(parent_link: ParentLink<'a>, def: Option<Def>, external: bool, is_public: bool) -> Self {
857 parent_link: parent_link,
859 is_public: is_public,
860 is_extern_crate: false,
861 resolutions: RefCell::new(HashMap::new()),
862 imports: RefCell::new(Vec::new()),
863 module_children: RefCell::new(NodeMap()),
864 shadowed_traits: RefCell::new(Vec::new()),
865 glob_count: Cell::new(0),
866 pub_count: Cell::new(0),
867 pub_glob_count: Cell::new(0),
868 resolved_import_count: Cell::new(0),
869 populated: Cell::new(!external),
873 fn resolve_name(&self, name: Name, ns: Namespace, allow_private_imports: bool)
874 -> ResolveResult<&'a NameBinding<'a>> {
876 if allow_private_imports { self.glob_count.get() } else { self.pub_glob_count.get() };
878 self.resolutions.borrow().get(&(name, ns)).cloned().unwrap_or_default().result(glob_count)
879 .and_then(|binding| {
880 let allowed = allow_private_imports || !binding.is_import() || binding.is_public();
881 if allowed { Success(binding) } else { Failed(None) }
885 // Define the name or return the existing binding if there is a collision.
886 fn try_define_child(&self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>)
887 -> Result<(), &'a NameBinding<'a>> {
888 let mut children = self.resolutions.borrow_mut();
889 let resolution = children.entry((name, ns)).or_insert_with(Default::default);
891 // FIXME #31379: We can use methods from imported traits shadowed by non-import items
892 if let Some(old_binding) = resolution.binding {
893 if !old_binding.is_import() && binding.is_import() {
894 if let Some(Def::Trait(_)) = binding.def() {
895 self.shadowed_traits.borrow_mut().push(binding);
900 resolution.try_define(binding)
903 fn increment_outstanding_references_for(&self, name: Name, ns: Namespace) {
904 let mut children = self.resolutions.borrow_mut();
905 children.entry((name, ns)).or_insert_with(Default::default).outstanding_references += 1;
908 fn decrement_outstanding_references_for(&self, name: Name, ns: Namespace) {
909 match self.resolutions.borrow_mut().get_mut(&(name, ns)).unwrap().outstanding_references {
910 0 => panic!("No more outstanding references!"),
911 ref mut outstanding_references => { *outstanding_references -= 1; }
915 fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
916 for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
917 name_resolution.binding.map(|binding| f(name, ns, binding));
921 fn def_id(&self) -> Option<DefId> {
922 self.def.as_ref().map(Def::def_id)
925 fn is_normal(&self) -> bool {
927 Some(Def::Mod(_)) | Some(Def::ForeignMod(_)) => true,
932 fn is_trait(&self) -> bool {
934 Some(Def::Trait(_)) => true,
939 fn all_imports_resolved(&self) -> bool {
940 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
941 // it is currently being resolved ! so nope
944 self.imports.borrow().len() == self.resolved_import_count.get()
948 pub fn inc_glob_count(&self) {
949 self.glob_count.set(self.glob_count.get() + 1);
951 pub fn dec_glob_count(&self) {
952 assert!(self.glob_count.get() > 0);
953 self.glob_count.set(self.glob_count.get() - 1);
955 pub fn inc_pub_count(&self) {
956 self.pub_count.set(self.pub_count.get() + 1);
958 pub fn dec_pub_count(&self) {
959 assert!(self.pub_count.get() > 0);
960 self.pub_count.set(self.pub_count.get() - 1);
962 pub fn inc_pub_glob_count(&self) {
963 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
965 pub fn dec_pub_glob_count(&self) {
966 assert!(self.pub_glob_count.get() > 0);
967 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
971 impl<'a> fmt::Debug for ModuleS<'a> {
972 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
986 flags DefModifiers: u8 {
987 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
988 // or `use Enum::*` to work on private enums.
989 const PUBLIC = 1 << 0,
990 const IMPORTABLE = 1 << 1,
991 // Variants are considered `PUBLIC`, but some of them live in private enums.
992 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
993 const PRIVATE_VARIANT = 1 << 2,
994 const PRELUDE = 1 << 3,
995 const GLOB_IMPORTED = 1 << 4,
999 // Records a possibly-private value, type, or module definition.
1001 pub struct NameBinding<'a> {
1002 modifiers: DefModifiers,
1003 kind: NameBindingKind<'a>,
1008 enum NameBindingKind<'a> {
1012 binding: &'a NameBinding<'a>,
1017 impl<'a> NameBinding<'a> {
1018 fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
1019 let modifiers = if module.is_public {
1020 DefModifiers::PUBLIC
1022 DefModifiers::empty()
1023 } | DefModifiers::IMPORTABLE;
1025 NameBinding { modifiers: modifiers, kind: NameBindingKind::Module(module), span: span }
1028 fn module(&self) -> Option<Module<'a>> {
1030 NameBindingKind::Module(module) => Some(module),
1031 NameBindingKind::Def(_) => None,
1032 NameBindingKind::Import { binding, .. } => binding.module(),
1036 fn def(&self) -> Option<Def> {
1038 NameBindingKind::Def(def) => Some(def),
1039 NameBindingKind::Module(module) => module.def,
1040 NameBindingKind::Import { binding, .. } => binding.def(),
1044 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1045 self.modifiers.contains(modifiers)
1048 fn is_public(&self) -> bool {
1049 self.defined_with(DefModifiers::PUBLIC)
1052 fn def_and_lp(&self) -> (Def, LastPrivate) {
1053 let def = self.def().unwrap();
1054 if let Def::Err = def { return (def, LastMod(AllPublic)) }
1055 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1058 fn is_extern_crate(&self) -> bool {
1059 self.module().map(|module| module.is_extern_crate).unwrap_or(false)
1062 fn is_import(&self) -> bool {
1064 NameBindingKind::Import { .. } => true,
1070 /// Interns the names of the primitive types.
1071 struct PrimitiveTypeTable {
1072 primitive_types: HashMap<Name, PrimTy>,
1075 impl PrimitiveTypeTable {
1076 fn new() -> PrimitiveTypeTable {
1077 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1079 table.intern("bool", TyBool);
1080 table.intern("char", TyChar);
1081 table.intern("f32", TyFloat(FloatTy::F32));
1082 table.intern("f64", TyFloat(FloatTy::F64));
1083 table.intern("isize", TyInt(IntTy::Is));
1084 table.intern("i8", TyInt(IntTy::I8));
1085 table.intern("i16", TyInt(IntTy::I16));
1086 table.intern("i32", TyInt(IntTy::I32));
1087 table.intern("i64", TyInt(IntTy::I64));
1088 table.intern("str", TyStr);
1089 table.intern("usize", TyUint(UintTy::Us));
1090 table.intern("u8", TyUint(UintTy::U8));
1091 table.intern("u16", TyUint(UintTy::U16));
1092 table.intern("u32", TyUint(UintTy::U32));
1093 table.intern("u64", TyUint(UintTy::U64));
1098 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1099 self.primitive_types.insert(token::intern(string), primitive_type);
1103 /// The main resolver class.
1104 pub struct Resolver<'a, 'tcx: 'a> {
1105 session: &'a Session,
1107 ast_map: &'a hir_map::Map<'tcx>,
1109 graph_root: Module<'a>,
1111 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1113 structs: FnvHashMap<DefId, Vec<Name>>,
1115 // The number of imports that are currently unresolved.
1116 unresolved_imports: usize,
1118 // The module that represents the current item scope.
1119 current_module: Module<'a>,
1121 // The current set of local scopes, for values.
1122 // FIXME #4948: Reuse ribs to avoid allocation.
1123 value_ribs: Vec<Rib<'a>>,
1125 // The current set of local scopes, for types.
1126 type_ribs: Vec<Rib<'a>>,
1128 // The current set of local scopes, for labels.
1129 label_ribs: Vec<Rib<'a>>,
1131 // The trait that the current context can refer to.
1132 current_trait_ref: Option<(DefId, TraitRef)>,
1134 // The current self type if inside an impl (used for better errors).
1135 current_self_type: Option<Ty>,
1137 // The idents for the primitive types.
1138 primitive_type_table: PrimitiveTypeTable,
1140 def_map: RefCell<DefMap>,
1141 freevars: FreevarMap,
1142 freevars_seen: NodeMap<NodeMap<usize>>,
1143 export_map: ExportMap,
1144 trait_map: TraitMap,
1145 external_exports: ExternalExports,
1147 // Whether or not to print error messages. Can be set to true
1148 // when getting additional info for error message suggestions,
1149 // so as to avoid printing duplicate errors
1152 make_glob_map: bool,
1153 // Maps imports to the names of items actually imported (this actually maps
1154 // all imports, but only glob imports are actually interesting).
1157 used_imports: HashSet<(NodeId, Namespace)>,
1158 used_crates: HashSet<CrateNum>,
1160 // Callback function for intercepting walks
1161 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1162 // The intention is that the callback modifies this flag.
1163 // Once set, the resolver falls out of the walk, preserving the ribs.
1166 arenas: &'a ResolverArenas<'a>,
1169 pub struct ResolverArenas<'a> {
1170 modules: arena::TypedArena<ModuleS<'a>>,
1171 name_bindings: arena::TypedArena<NameBinding<'a>>,
1174 #[derive(PartialEq)]
1175 enum FallbackChecks {
1177 OnlyTraitAndStatics,
1180 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1181 fn new(session: &'a Session,
1182 ast_map: &'a hir_map::Map<'tcx>,
1183 make_glob_map: MakeGlobMap,
1184 arenas: &'a ResolverArenas<'a>)
1185 -> Resolver<'a, 'tcx> {
1186 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1187 let graph_root = ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, true);
1188 let graph_root = arenas.modules.alloc(graph_root);
1195 // The outermost module has def ID 0; this is not reflected in the
1197 graph_root: graph_root,
1199 trait_item_map: FnvHashMap(),
1200 structs: FnvHashMap(),
1202 unresolved_imports: 0,
1204 current_module: graph_root,
1205 value_ribs: Vec::new(),
1206 type_ribs: Vec::new(),
1207 label_ribs: Vec::new(),
1209 current_trait_ref: None,
1210 current_self_type: None,
1212 primitive_type_table: PrimitiveTypeTable::new(),
1214 def_map: RefCell::new(NodeMap()),
1215 freevars: NodeMap(),
1216 freevars_seen: NodeMap(),
1217 export_map: NodeMap(),
1218 trait_map: NodeMap(),
1219 used_imports: HashSet::new(),
1220 used_crates: HashSet::new(),
1221 external_exports: DefIdSet(),
1224 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1225 glob_map: HashMap::new(),
1234 fn arenas() -> ResolverArenas<'a> {
1236 modules: arena::TypedArena::new(),
1237 name_bindings: arena::TypedArena::new(),
1241 fn new_module(&self,
1242 parent_link: ParentLink<'a>,
1245 is_public: bool) -> Module<'a> {
1246 self.arenas.modules.alloc(ModuleS::new(parent_link, def, external, is_public))
1249 fn new_name_binding(&self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1250 self.arenas.name_bindings.alloc(name_binding)
1253 fn new_extern_crate_module(&self, parent_link: ParentLink<'a>, def: Def) -> Module<'a> {
1254 let mut module = ModuleS::new(parent_link, Some(def), false, true);
1255 module.is_extern_crate = true;
1256 self.arenas.modules.alloc(module)
1259 fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
1260 match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
1264 fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>) {
1265 // track extern crates for unused_extern_crate lint
1266 if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
1267 self.used_crates.insert(krate);
1270 let import_id = match binding.kind {
1271 NameBindingKind::Import { id, .. } => id,
1275 self.used_imports.insert((import_id, ns));
1277 if !self.make_glob_map {
1280 if self.glob_map.contains_key(&import_id) {
1281 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1285 let mut new_set = HashSet::new();
1286 new_set.insert(name);
1287 self.glob_map.insert(import_id, new_set);
1290 fn get_trait_name(&self, did: DefId) -> Name {
1291 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1292 self.ast_map.expect_item(node_id).name
1294 self.session.cstore.item_name(did)
1298 /// Resolves the given module path from the given root `module_`.
1299 fn resolve_module_path_from_root(&mut self,
1300 module_: Module<'a>,
1301 module_path: &[Name],
1305 -> ResolveResult<(Module<'a>, LastPrivate)> {
1306 fn search_parent_externals(needle: Name, module: Module) -> Option<Module> {
1307 match module.resolve_name(needle, TypeNS, false) {
1308 Success(binding) if binding.is_extern_crate() => Some(module),
1309 _ => match module.parent_link {
1310 ModuleParentLink(ref parent, _) => {
1311 search_parent_externals(needle, parent)
1318 let mut search_module = module_;
1319 let mut index = index;
1320 let module_path_len = module_path.len();
1321 let mut closest_private = lp;
1323 // Resolve the module part of the path. This does not involve looking
1324 // upward though scope chains; we simply resolve names directly in
1325 // modules as we go.
1326 while index < module_path_len {
1327 let name = module_path[index];
1328 match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1330 let segment_name = name.as_str();
1331 let module_name = module_to_string(search_module);
1332 let mut span = span;
1333 let msg = if "???" == &module_name {
1334 span.hi = span.lo + Pos::from_usize(segment_name.len());
1336 match search_parent_externals(name, &self.current_module) {
1338 let path_str = names_to_string(module_path);
1339 let target_mod_str = module_to_string(&module);
1340 let current_mod_str = module_to_string(&self.current_module);
1342 let prefix = if target_mod_str == current_mod_str {
1343 "self::".to_string()
1345 format!("{}::", target_mod_str)
1348 format!("Did you mean `{}{}`?", prefix, path_str)
1350 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1353 format!("Could not find `{}` in `{}`", segment_name, module_name)
1356 return Failed(Some((span, msg)));
1358 Failed(err) => return Failed(err),
1360 debug!("(resolving module path for import) module resolution is \
1363 return Indeterminate;
1365 Success(binding) => {
1366 // Check to see whether there are type bindings, and, if
1367 // so, whether there is a module within.
1368 if let Some(module_def) = binding.module() {
1369 search_module = module_def;
1371 // Keep track of the closest private module used
1372 // when resolving this import chain.
1373 if !binding.is_public() {
1374 if let Some(did) = search_module.def_id() {
1375 closest_private = LastMod(DependsOn(did));
1379 let msg = format!("Not a module `{}`", name);
1380 return Failed(Some((span, msg)));
1388 return Success((search_module, closest_private));
1391 /// Attempts to resolve the module part of an import directive or path
1392 /// rooted at the given module.
1394 /// On success, returns the resolved module, and the closest *private*
1395 /// module found to the destination when resolving this path.
1396 fn resolve_module_path(&mut self,
1397 module_: Module<'a>,
1398 module_path: &[Name],
1399 use_lexical_scope: UseLexicalScopeFlag,
1401 -> ResolveResult<(Module<'a>, LastPrivate)> {
1402 if module_path.len() == 0 {
1403 return Success((self.graph_root, LastMod(AllPublic))) // Use the crate root
1406 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1407 names_to_string(module_path),
1408 module_to_string(&module_));
1410 // Resolve the module prefix, if any.
1411 let module_prefix_result = self.resolve_module_prefix(module_, module_path);
1416 match module_prefix_result {
1418 let mpath = names_to_string(module_path);
1419 let mpath = &mpath[..];
1420 match mpath.rfind(':') {
1422 let msg = format!("Could not find `{}` in `{}`",
1423 // idx +- 1 to account for the
1424 // colons on either side
1427 return Failed(Some((span, msg)));
1430 return Failed(None);
1434 Failed(err) => return Failed(err),
1436 debug!("(resolving module path for import) indeterminate; bailing");
1437 return Indeterminate;
1439 Success(NoPrefixFound) => {
1440 // There was no prefix, so we're considering the first element
1441 // of the path. How we handle this depends on whether we were
1442 // instructed to use lexical scope or not.
1443 match use_lexical_scope {
1444 DontUseLexicalScope => {
1445 // This is a crate-relative path. We will start the
1446 // resolution process at index zero.
1447 search_module = self.graph_root;
1449 last_private = LastMod(AllPublic);
1451 UseLexicalScope => {
1452 // This is not a crate-relative path. We resolve the
1453 // first component of the path in the current lexical
1454 // scope and then proceed to resolve below that.
1455 match self.resolve_item_in_lexical_scope(module_,
1459 Failed(err) => return Failed(err),
1461 debug!("(resolving module path for import) indeterminate; bailing");
1462 return Indeterminate;
1464 Success(binding) => match binding.module() {
1465 Some(containing_module) => {
1466 search_module = containing_module;
1468 last_private = LastMod(AllPublic);
1470 None => return Failed(None),
1476 Success(PrefixFound(ref containing_module, index)) => {
1477 search_module = containing_module;
1478 start_index = index;
1479 last_private = LastMod(DependsOn(containing_module.def_id()
1484 self.resolve_module_path_from_root(search_module,
1491 /// Invariant: This must only be called during main resolution, not during
1492 /// import resolution.
1493 fn resolve_item_in_lexical_scope(&mut self,
1494 module_: Module<'a>,
1496 namespace: Namespace,
1498 -> ResolveResult<&'a NameBinding<'a>> {
1499 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1502 module_to_string(&module_));
1504 // Proceed up the scope chain looking for parent modules.
1505 let mut search_module = module_;
1507 // Resolve the name in the parent module.
1508 match self.resolve_name_in_module(search_module, name, namespace, true, record_used) {
1509 Failed(Some((span, msg))) => {
1510 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
1512 Failed(None) => (), // Continue up the search chain.
1514 // We couldn't see through the higher scope because of an
1515 // unresolved import higher up. Bail.
1517 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1518 return Indeterminate;
1520 Success(binding) => {
1521 // We found the module.
1522 debug!("(resolving item in lexical scope) found name in module, done");
1523 return Success(binding);
1527 // Go to the next parent.
1528 match search_module.parent_link {
1530 // No more parents. This module was unresolved.
1531 debug!("(resolving item in lexical scope) unresolved module: no parent module");
1532 return Failed(None);
1534 ModuleParentLink(parent_module_node, _) => {
1535 if search_module.is_normal() {
1536 // We stop the search here.
1537 debug!("(resolving item in lexical scope) unresolved module: not \
1538 searching through module parents");
1539 return Failed(None);
1541 search_module = parent_module_node;
1544 BlockParentLink(parent_module_node, _) => {
1545 search_module = parent_module_node;
1551 /// Returns the nearest normal module parent of the given module.
1552 fn get_nearest_normal_module_parent(&mut self, module_: Module<'a>) -> Option<Module<'a>> {
1553 let mut module_ = module_;
1555 match module_.parent_link {
1556 NoParentLink => return None,
1557 ModuleParentLink(new_module, _) |
1558 BlockParentLink(new_module, _) => {
1559 let new_module = new_module;
1560 if new_module.is_normal() {
1561 return Some(new_module);
1563 module_ = new_module;
1569 /// Returns the nearest normal module parent of the given module, or the
1570 /// module itself if it is a normal module.
1571 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Module<'a>) -> Module<'a> {
1572 if module_.is_normal() {
1575 match self.get_nearest_normal_module_parent(module_) {
1577 Some(new_module) => new_module,
1581 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1582 /// (b) some chain of `super::`.
1583 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1584 fn resolve_module_prefix(&mut self,
1585 module_: Module<'a>,
1586 module_path: &[Name])
1587 -> ResolveResult<ModulePrefixResult<'a>> {
1588 // Start at the current module if we see `self` or `super`, or at the
1589 // top of the crate otherwise.
1590 let mut i = match &*module_path[0].as_str() {
1593 _ => return Success(NoPrefixFound),
1595 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1597 // Now loop through all the `super`s we find.
1598 while i < module_path.len() && "super" == module_path[i].as_str() {
1599 debug!("(resolving module prefix) resolving `super` at {}",
1600 module_to_string(&containing_module));
1601 match self.get_nearest_normal_module_parent(containing_module) {
1602 None => return Failed(None),
1603 Some(new_module) => {
1604 containing_module = new_module;
1610 debug!("(resolving module prefix) finished resolving prefix at {}",
1611 module_to_string(&containing_module));
1613 return Success(PrefixFound(containing_module, i));
1616 /// Attempts to resolve the supplied name in the given module for the
1617 /// given namespace. If successful, returns the binding corresponding to
1619 fn resolve_name_in_module(&mut self,
1622 namespace: Namespace,
1623 allow_private_imports: bool,
1625 -> ResolveResult<&'a NameBinding<'a>> {
1626 debug!("(resolving name in module) resolving `{}` in `{}`", name, module_to_string(module));
1628 build_reduced_graph::populate_module_if_necessary(self, module);
1629 module.resolve_name(name, namespace, allow_private_imports).and_then(|binding| {
1631 self.record_use(name, namespace, binding);
1637 fn report_unresolved_imports(&mut self, module_: Module<'a>) {
1638 let index = module_.resolved_import_count.get();
1639 let imports = module_.imports.borrow();
1640 let import_count = imports.len();
1641 if index != import_count {
1643 (*imports)[index].span,
1644 ResolutionError::UnresolvedImport(None));
1647 // Descend into children and anonymous children.
1648 for (_, module_) in module_.module_children.borrow().iter() {
1649 self.report_unresolved_imports(module_);
1655 // We maintain a list of value ribs and type ribs.
1657 // Simultaneously, we keep track of the current position in the module
1658 // graph in the `current_module` pointer. When we go to resolve a name in
1659 // the value or type namespaces, we first look through all the ribs and
1660 // then query the module graph. When we resolve a name in the module
1661 // namespace, we can skip all the ribs (since nested modules are not
1662 // allowed within blocks in Rust) and jump straight to the current module
1665 // Named implementations are handled separately. When we find a method
1666 // call, we consult the module node to find all of the implementations in
1667 // scope. This information is lazily cached in the module node. We then
1668 // generate a fake "implementation scope" containing all the
1669 // implementations thus found, for compatibility with old resolve pass.
1671 fn with_scope<F>(&mut self, id: NodeId, f: F)
1672 where F: FnOnce(&mut Resolver)
1674 let orig_module = self.current_module;
1676 // Move down in the graph.
1677 if let Some(module) = orig_module.module_children.borrow().get(&id) {
1678 self.current_module = module;
1683 self.current_module = orig_module;
1686 /// Searches the current set of local scopes for labels.
1687 /// Stops after meeting a closure.
1688 fn search_label(&self, name: Name) -> Option<DefLike> {
1689 for rib in self.label_ribs.iter().rev() {
1695 // Do not resolve labels across function boundary
1699 let result = rib.bindings.get(&name).cloned();
1700 if result.is_some() {
1707 fn resolve_crate(&mut self, krate: &hir::Crate) {
1708 debug!("(resolving crate) starting");
1710 intravisit::walk_crate(self, krate);
1713 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1714 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1715 span_err!(self.session,
1718 "user-defined types or type parameters cannot shadow the primitive types");
1722 fn resolve_item(&mut self, item: &Item) {
1723 let name = item.name;
1725 debug!("(resolving item) resolving {}", name);
1728 ItemEnum(_, ref generics) |
1729 ItemTy(_, ref generics) |
1730 ItemStruct(_, ref generics) => {
1731 self.check_if_primitive_type_name(name, item.span);
1733 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1734 |this| intravisit::walk_item(this, item));
1736 ItemFn(_, _, _, _, ref generics, _) => {
1737 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1738 |this| intravisit::walk_item(this, item));
1741 ItemDefaultImpl(_, ref trait_ref) => {
1742 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1744 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1745 self.resolve_implementation(generics,
1752 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1753 self.check_if_primitive_type_name(name, item.span);
1755 // Create a new rib for the trait-wide type parameters.
1756 self.with_type_parameter_rib(HasTypeParameters(generics,
1760 let local_def_id = this.ast_map.local_def_id(item.id);
1761 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1762 this.visit_generics(generics);
1763 walk_list!(this, visit_ty_param_bound, bounds);
1765 for trait_item in trait_items {
1766 match trait_item.node {
1767 hir::ConstTraitItem(_, ref default) => {
1768 // Only impose the restrictions of
1769 // ConstRibKind if there's an actual constant
1770 // expression in a provided default.
1771 if default.is_some() {
1772 this.with_constant_rib(|this| {
1773 intravisit::walk_trait_item(this, trait_item)
1776 intravisit::walk_trait_item(this, trait_item)
1779 hir::MethodTraitItem(ref sig, _) => {
1780 let type_parameters =
1781 HasTypeParameters(&sig.generics,
1784 this.with_type_parameter_rib(type_parameters, |this| {
1785 intravisit::walk_trait_item(this, trait_item)
1788 hir::TypeTraitItem(..) => {
1789 this.check_if_primitive_type_name(trait_item.name,
1791 this.with_type_parameter_rib(NoTypeParameters, |this| {
1792 intravisit::walk_trait_item(this, trait_item)
1801 ItemMod(_) | ItemForeignMod(_) => {
1802 self.with_scope(item.id, |this| {
1803 intravisit::walk_item(this, item);
1807 ItemConst(..) | ItemStatic(..) => {
1808 self.with_constant_rib(|this| {
1809 intravisit::walk_item(this, item);
1813 ItemUse(ref view_path) => {
1814 // check for imports shadowing primitive types
1815 let check_rename = |this: &Self, id, name| {
1816 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
1817 Some(Def::Enum(..)) | Some(Def::TyAlias(..)) | Some(Def::Struct(..)) |
1818 Some(Def::Trait(..)) | None => {
1819 this.check_if_primitive_type_name(name, item.span);
1825 match view_path.node {
1826 hir::ViewPathSimple(name, _) => {
1827 check_rename(self, item.id, name);
1829 hir::ViewPathList(ref prefix, ref items) => {
1831 if let Some(name) = item.node.rename() {
1832 check_rename(self, item.node.id(), name);
1836 // Resolve prefix of an import with empty braces (issue #28388)
1837 if items.is_empty() && !prefix.segments.is_empty() {
1838 match self.resolve_crate_relative_path(prefix.span,
1842 self.record_def(item.id, PathResolution::new(def, lp, 0)),
1846 ResolutionError::FailedToResolve(
1847 &path_names_to_string(prefix, 0)));
1848 self.record_def(item.id, err_path_resolution());
1857 ItemExternCrate(_) => {
1858 // do nothing, these are just around to be encoded
1863 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
1864 where F: FnOnce(&mut Resolver)
1866 match type_parameters {
1867 HasTypeParameters(generics, space, rib_kind) => {
1868 let mut function_type_rib = Rib::new(rib_kind);
1869 let mut seen_bindings = HashSet::new();
1870 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1871 let name = type_parameter.name;
1872 debug!("with_type_parameter_rib: {}", type_parameter.id);
1874 if seen_bindings.contains(&name) {
1876 type_parameter.span,
1877 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1879 seen_bindings.insert(name);
1881 // plain insert (no renaming)
1882 function_type_rib.bindings
1884 DlDef(Def::TyParam(space,
1887 .local_def_id(type_parameter.id),
1890 self.type_ribs.push(function_type_rib);
1893 NoTypeParameters => {
1900 match type_parameters {
1901 HasTypeParameters(..) => {
1903 self.type_ribs.pop();
1906 NoTypeParameters => {}
1910 fn with_label_rib<F>(&mut self, f: F)
1911 where F: FnOnce(&mut Resolver)
1913 self.label_ribs.push(Rib::new(NormalRibKind));
1916 self.label_ribs.pop();
1920 fn with_constant_rib<F>(&mut self, f: F)
1921 where F: FnOnce(&mut Resolver)
1923 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1924 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1927 self.type_ribs.pop();
1928 self.value_ribs.pop();
1932 fn resolve_function(&mut self, rib_kind: RibKind<'a>, declaration: &FnDecl, block: &Block) {
1933 // Create a value rib for the function.
1934 self.value_ribs.push(Rib::new(rib_kind));
1936 // Create a label rib for the function.
1937 self.label_ribs.push(Rib::new(rib_kind));
1939 // Add each argument to the rib.
1940 let mut bindings_list = HashMap::new();
1941 for argument in &declaration.inputs {
1942 self.resolve_pattern(&argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
1944 self.visit_ty(&argument.ty);
1946 debug!("(resolving function) recorded argument");
1948 intravisit::walk_fn_ret_ty(self, &declaration.output);
1950 // Resolve the function body.
1951 self.visit_block(block);
1953 debug!("(resolving function) leaving function");
1956 self.label_ribs.pop();
1957 self.value_ribs.pop();
1961 fn resolve_trait_reference(&mut self,
1965 -> Result<PathResolution, ()> {
1966 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
1967 if let Def::Trait(_) = path_res.base_def {
1968 debug!("(resolving trait) found trait def: {:?}", path_res);
1972 resolve_struct_error(self,
1974 ResolutionError::IsNotATrait(&path_names_to_string(trait_path,
1977 // If it's a typedef, give a note
1978 if let Def::TyAlias(..) = path_res.base_def {
1979 err.span_note(trait_path.span,
1980 "`type` aliases cannot be used for traits");
1987 // find possible candidates
1988 let trait_name = trait_path.segments.last().unwrap().identifier.name;
1990 self.lookup_candidates(
1994 Def::Trait(_) => true,
1999 // create error object
2000 let name = &path_names_to_string(trait_path, path_depth);
2002 ResolutionError::UndeclaredTraitName(
2007 resolve_error(self, trait_path.span, error);
2012 fn resolve_generics(&mut self, generics: &Generics) {
2013 for type_parameter in generics.ty_params.iter() {
2014 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2016 for predicate in &generics.where_clause.predicates {
2018 &hir::WherePredicate::BoundPredicate(_) |
2019 &hir::WherePredicate::RegionPredicate(_) => {}
2020 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2021 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2022 if let Some(PathResolution { base_def: Def::TyParam(..), .. }) = path_res {
2023 self.record_def(eq_pred.id, path_res.unwrap());
2027 ResolutionError::UndeclaredAssociatedType);
2028 self.record_def(eq_pred.id, err_path_resolution());
2033 intravisit::walk_generics(self, generics);
2036 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2037 where F: FnOnce(&mut Resolver) -> T
2039 // Handle nested impls (inside fn bodies)
2040 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2041 let result = f(self);
2042 self.current_self_type = previous_value;
2046 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2047 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2049 let mut new_val = None;
2050 let mut new_id = None;
2051 if let Some(trait_ref) = opt_trait_ref {
2052 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2055 assert!(path_res.depth == 0);
2056 self.record_def(trait_ref.ref_id, path_res);
2057 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2058 new_id = Some(path_res.base_def.def_id());
2060 self.record_def(trait_ref.ref_id, err_path_resolution());
2062 intravisit::walk_trait_ref(self, trait_ref);
2064 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2065 let result = f(self, new_id);
2066 self.current_trait_ref = original_trait_ref;
2070 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2071 where F: FnOnce(&mut Resolver)
2073 let mut self_type_rib = Rib::new(NormalRibKind);
2075 // plain insert (no renaming, types are not currently hygienic....)
2076 let name = special_names::type_self;
2077 self_type_rib.bindings.insert(name, DlDef(self_def));
2078 self.type_ribs.push(self_type_rib);
2081 self.type_ribs.pop();
2085 fn resolve_implementation(&mut self,
2086 generics: &Generics,
2087 opt_trait_reference: &Option<TraitRef>,
2090 impl_items: &[ImplItem]) {
2091 // If applicable, create a rib for the type parameters.
2092 self.with_type_parameter_rib(HasTypeParameters(generics,
2096 // Resolve the type parameters.
2097 this.visit_generics(generics);
2099 // Resolve the trait reference, if necessary.
2100 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2101 // Resolve the self type.
2102 this.visit_ty(self_type);
2104 this.with_self_rib(Def::SelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2105 this.with_current_self_type(self_type, |this| {
2106 for impl_item in impl_items {
2107 match impl_item.node {
2108 hir::ImplItemKind::Const(..) => {
2109 // If this is a trait impl, ensure the const
2111 this.check_trait_item(impl_item.name,
2113 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2114 this.with_constant_rib(|this| {
2115 intravisit::walk_impl_item(this, impl_item);
2118 hir::ImplItemKind::Method(ref sig, _) => {
2119 // If this is a trait impl, ensure the method
2121 this.check_trait_item(impl_item.name,
2123 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2125 // We also need a new scope for the method-
2126 // specific type parameters.
2127 let type_parameters =
2128 HasTypeParameters(&sig.generics,
2131 this.with_type_parameter_rib(type_parameters, |this| {
2132 intravisit::walk_impl_item(this, impl_item);
2135 hir::ImplItemKind::Type(ref ty) => {
2136 // If this is a trait impl, ensure the type
2138 this.check_trait_item(impl_item.name,
2140 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2152 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2153 where F: FnOnce(Name, &str) -> ResolutionError
2155 // If there is a TraitRef in scope for an impl, then the method must be in the
2157 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2158 if !self.trait_item_map.contains_key(&(name, did)) {
2159 let path_str = path_names_to_string(&trait_ref.path, 0);
2160 resolve_error(self, span, err(name, &path_str));
2165 fn resolve_local(&mut self, local: &Local) {
2166 // Resolve the type.
2167 walk_list!(self, visit_ty, &local.ty);
2169 // Resolve the initializer.
2170 walk_list!(self, visit_expr, &local.init);
2172 // Resolve the pattern.
2173 self.resolve_pattern(&local.pat, LocalIrrefutableMode, &mut HashMap::new());
2176 // build a map from pattern identifiers to binding-info's.
2177 // this is done hygienically. This could arise for a macro
2178 // that expands into an or-pattern where one 'x' was from the
2179 // user and one 'x' came from the macro.
2180 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2181 let mut result = HashMap::new();
2182 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2183 let name = path1.node;
2187 binding_mode: binding_mode,
2193 // check that all of the arms in an or-pattern have exactly the
2194 // same set of bindings, with the same binding modes for each.
2195 fn check_consistent_bindings(&mut self, arm: &Arm) {
2196 if arm.pats.is_empty() {
2199 let map_0 = self.binding_mode_map(&arm.pats[0]);
2200 for (i, p) in arm.pats.iter().enumerate() {
2201 let map_i = self.binding_mode_map(&p);
2203 for (&key, &binding_0) in &map_0 {
2204 match map_i.get(&key) {
2208 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2210 Some(binding_i) => {
2211 if binding_0.binding_mode != binding_i.binding_mode {
2214 ResolutionError::VariableBoundWithDifferentMode(key,
2221 for (&key, &binding) in &map_i {
2222 if !map_0.contains_key(&key) {
2225 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2231 fn resolve_arm(&mut self, arm: &Arm) {
2232 self.value_ribs.push(Rib::new(NormalRibKind));
2234 let mut bindings_list = HashMap::new();
2235 for pattern in &arm.pats {
2236 self.resolve_pattern(&pattern, RefutableMode, &mut bindings_list);
2239 // This has to happen *after* we determine which
2240 // pat_idents are variants
2241 self.check_consistent_bindings(arm);
2243 walk_list!(self, visit_expr, &arm.guard);
2244 self.visit_expr(&arm.body);
2247 self.value_ribs.pop();
2251 fn resolve_block(&mut self, block: &Block) {
2252 debug!("(resolving block) entering block");
2253 // Move down in the graph, if there's an anonymous module rooted here.
2254 let orig_module = self.current_module;
2255 let anonymous_module =
2256 orig_module.module_children.borrow().get(&block.id).map(|module| *module);
2258 if let Some(anonymous_module) = anonymous_module {
2259 debug!("(resolving block) found anonymous module, moving down");
2260 self.value_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2261 self.type_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2262 self.current_module = anonymous_module;
2264 self.value_ribs.push(Rib::new(NormalRibKind));
2267 // Descend into the block.
2268 intravisit::walk_block(self, block);
2272 self.current_module = orig_module;
2273 self.value_ribs.pop();
2274 if let Some(_) = anonymous_module {
2275 self.type_ribs.pop();
2278 debug!("(resolving block) leaving block");
2281 fn resolve_type(&mut self, ty: &Ty) {
2283 TyPath(ref maybe_qself, ref path) => {
2284 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2285 maybe_qself.as_ref(),
2289 // `<T>::a::b::c` is resolved by typeck alone.
2290 TypecheckRequired => {
2291 // Resolve embedded types.
2292 intravisit::walk_ty(self, ty);
2295 ResolveAttempt(resolution) => resolution,
2298 // This is a path in the type namespace. Walk through scopes
2302 // Write the result into the def map.
2303 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2304 path_names_to_string(path, 0),
2307 self.record_def(ty.id, def);
2310 self.record_def(ty.id, err_path_resolution());
2312 // Keep reporting some errors even if they're ignored above.
2313 self.resolve_path(ty.id, path, 0, TypeNS, true);
2315 let kind = if maybe_qself.is_some() {
2321 let self_type_name = special_idents::type_self.name;
2322 let is_invalid_self_type_name = path.segments.len() > 0 &&
2323 maybe_qself.is_none() &&
2324 path.segments[0].identifier.name ==
2326 if is_invalid_self_type_name {
2329 ResolutionError::SelfUsedOutsideImplOrTrait);
2331 let segment = path.segments.last();
2332 let segment = segment.expect("missing name in path");
2333 let type_name = segment.identifier.name;
2336 self.lookup_candidates(
2343 Def::TyAlias(_) => true,
2348 // create error object
2349 let name = &path_names_to_string(path, 0);
2351 ResolutionError::UseOfUndeclared(
2357 resolve_error(self, ty.span, error);
2364 // Resolve embedded types.
2365 intravisit::walk_ty(self, ty);
2368 fn resolve_pattern(&mut self,
2370 mode: PatternBindingMode,
2371 // Maps idents to the node ID for the (outermost)
2372 // pattern that binds them
2373 bindings_list: &mut HashMap<Name, NodeId>) {
2374 let pat_id = pattern.id;
2375 walk_pat(pattern, |pattern| {
2376 match pattern.node {
2377 PatKind::Ident(binding_mode, ref path1, ref at_rhs) => {
2378 // The meaning of PatKind::Ident with no type parameters
2379 // depends on whether an enum variant or unit-like struct
2380 // with that name is in scope. The probing lookup has to
2381 // be careful not to emit spurious errors. Only matching
2382 // patterns (match) can match nullary variants or
2383 // unit-like structs. For binding patterns (let
2384 // and the LHS of @-patterns), matching such a value is
2385 // simply disallowed (since it's rarely what you want).
2386 let const_ok = mode == RefutableMode && at_rhs.is_none();
2388 let ident = path1.node;
2389 let renamed = ident.name;
2391 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2393 FoundStructOrEnumVariant(def, lp) if const_ok => {
2394 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2397 self.enforce_default_binding_mode(pattern,
2400 self.record_def(pattern.id,
2407 FoundStructOrEnumVariant(..) => {
2411 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2414 self.record_def(pattern.id, err_path_resolution());
2416 FoundConst(def, lp, _) if const_ok => {
2417 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2419 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2420 self.record_def(pattern.id,
2427 FoundConst(def, _, name) => {
2431 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2434 self.record_def(pattern.id, err_path_resolution());
2436 BareIdentifierPatternUnresolved => {
2437 debug!("(resolving pattern) binding `{}`", renamed);
2439 let def_id = self.ast_map.local_def_id(pattern.id);
2440 let def = Def::Local(def_id, pattern.id);
2442 // Record the definition so that later passes
2443 // will be able to distinguish variants from
2444 // locals in patterns.
2446 self.record_def(pattern.id,
2449 last_private: LastMod(AllPublic),
2453 // Add the binding to the local ribs, if it
2454 // doesn't already exist in the bindings list. (We
2455 // must not add it if it's in the bindings list
2456 // because that breaks the assumptions later
2457 // passes make about or-patterns.)
2458 if !bindings_list.contains_key(&renamed) {
2459 let this = &mut *self;
2460 let last_rib = this.value_ribs.last_mut().unwrap();
2461 last_rib.bindings.insert(renamed, DlDef(def));
2462 bindings_list.insert(renamed, pat_id);
2463 } else if mode == ArgumentIrrefutableMode &&
2464 bindings_list.contains_key(&renamed) {
2465 // Forbid duplicate bindings in the same
2470 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2471 &ident.name.as_str())
2473 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2474 // Then this is a duplicate variable in the
2475 // same disjunction, which is an error.
2479 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2480 &ident.name.as_str())
2483 // Else, not bound in the same pattern: do
2489 PatKind::TupleStruct(ref path, _) | PatKind::Path(ref path) => {
2490 // This must be an enum variant, struct or const.
2491 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2496 // The below shouldn't happen because all
2497 // qualified paths should be in PatKind::QPath.
2498 TypecheckRequired =>
2499 self.session.span_bug(path.span,
2500 "resolve_possibly_assoc_item claimed that a path \
2501 in PatKind::Path or PatKind::TupleStruct \
2502 requires typecheck to resolve, but qualified \
2503 paths should be PatKind::QPath"),
2504 ResolveAttempt(resolution) => resolution,
2506 if let Some(path_res) = resolution {
2507 match path_res.base_def {
2508 Def::Struct(..) if path_res.depth == 0 => {
2509 self.record_def(pattern.id, path_res);
2511 Def::Variant(..) | Def::Const(..) => {
2512 self.record_def(pattern.id, path_res);
2514 Def::Static(..) => {
2515 resolve_error(&self,
2517 ResolutionError::StaticVariableReference);
2518 self.record_def(pattern.id, err_path_resolution());
2521 // If anything ends up here entirely resolved,
2522 // it's an error. If anything ends up here
2523 // partially resolved, that's OK, because it may
2524 // be a `T::CONST` that typeck will resolve.
2525 if path_res.depth == 0 {
2529 ResolutionError::NotAnEnumVariantStructOrConst(
2537 self.record_def(pattern.id, err_path_resolution());
2539 let const_name = path.segments
2544 let traits = self.get_traits_containing_item(const_name);
2545 self.trait_map.insert(pattern.id, traits);
2546 self.record_def(pattern.id, path_res);
2554 ResolutionError::UnresolvedEnumVariantStructOrConst(
2555 &path.segments.last().unwrap().identifier.name.as_str())
2557 self.record_def(pattern.id, err_path_resolution());
2559 intravisit::walk_path(self, path);
2562 PatKind::QPath(ref qself, ref path) => {
2563 // Associated constants only.
2564 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2569 TypecheckRequired => {
2570 // All `<T>::CONST` should end up here, and will
2571 // require use of the trait map to resolve
2572 // during typechecking.
2573 let const_name = path.segments
2578 let traits = self.get_traits_containing_item(const_name);
2579 self.trait_map.insert(pattern.id, traits);
2580 intravisit::walk_pat(self, pattern);
2583 ResolveAttempt(resolution) => resolution,
2585 if let Some(path_res) = resolution {
2586 match path_res.base_def {
2587 // All `<T as Trait>::CONST` should end up here, and
2588 // have the trait already selected.
2589 Def::AssociatedConst(..) => {
2590 self.record_def(pattern.id, path_res);
2596 ResolutionError::NotAnAssociatedConst(
2597 &path.segments.last().unwrap().identifier.name.as_str()
2600 self.record_def(pattern.id, err_path_resolution());
2606 ResolutionError::UnresolvedAssociatedConst(&path.segments
2612 self.record_def(pattern.id, err_path_resolution());
2614 intravisit::walk_pat(self, pattern);
2617 PatKind::Struct(ref path, _, _) => {
2618 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2619 Some(definition) => {
2620 self.record_def(pattern.id, definition);
2623 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2627 ResolutionError::DoesNotNameAStruct(
2628 &path_names_to_string(path, 0))
2630 self.record_def(pattern.id, err_path_resolution());
2633 intravisit::walk_path(self, path);
2636 PatKind::Lit(_) | PatKind::Range(..) => {
2637 intravisit::walk_pat(self, pattern);
2648 fn resolve_bare_identifier_pattern(&mut self,
2651 -> BareIdentifierPatternResolution {
2652 let module = self.current_module;
2653 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2654 Success(binding) => {
2655 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2658 match binding.def() {
2660 panic!("resolved name in the value namespace to a set of name bindings \
2663 // For the two success cases, this lookup can be
2664 // considered as not having a private component because
2665 // the lookup happened only within the current module.
2666 Some(def @ Def::Variant(..)) | Some(def @ Def::Struct(..)) => {
2667 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2669 Some(def @ Def::Const(..)) | Some(def @ Def::AssociatedConst(..)) => {
2670 return FoundConst(def, LastMod(AllPublic), name);
2672 Some(Def::Static(..)) => {
2673 resolve_error(self, span, ResolutionError::StaticVariableReference);
2674 return BareIdentifierPatternUnresolved;
2676 _ => return BareIdentifierPatternUnresolved
2680 Indeterminate => return BareIdentifierPatternUnresolved,
2683 Some((span, msg)) => {
2684 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2689 debug!("(resolve bare identifier pattern) failed to find {}", name);
2690 return BareIdentifierPatternUnresolved;
2695 /// Handles paths that may refer to associated items
2696 fn resolve_possibly_assoc_item(&mut self,
2698 maybe_qself: Option<&hir::QSelf>,
2700 namespace: Namespace,
2702 -> AssocItemResolveResult {
2703 let max_assoc_types;
2707 if qself.position == 0 {
2708 return TypecheckRequired;
2710 max_assoc_types = path.segments.len() - qself.position;
2711 // Make sure the trait is valid.
2712 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2715 max_assoc_types = path.segments.len();
2719 let mut resolution = self.with_no_errors(|this| {
2720 this.resolve_path(id, path, 0, namespace, check_ribs)
2722 for depth in 1..max_assoc_types {
2723 if resolution.is_some() {
2726 self.with_no_errors(|this| {
2727 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2730 if let Some(Def::Mod(_)) = resolution.map(|r| r.base_def) {
2731 // A module is not a valid type or value.
2734 ResolveAttempt(resolution)
2737 /// If `check_ribs` is true, checks the local definitions first; i.e.
2738 /// doesn't skip straight to the containing module.
2739 /// Skips `path_depth` trailing segments, which is also reflected in the
2740 /// returned value. See `middle::def::PathResolution` for more info.
2741 pub fn resolve_path(&mut self,
2745 namespace: Namespace,
2747 -> Option<PathResolution> {
2748 let span = path.span;
2749 let segments = &path.segments[..path.segments.len() - path_depth];
2751 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2754 let def = self.resolve_crate_relative_path(span, segments, namespace);
2755 return def.map(mk_res);
2758 // Try to find a path to an item in a module.
2759 let last_ident = segments.last().unwrap().identifier;
2760 if segments.len() <= 1 {
2761 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2762 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2764 PathResolution::new(def, LastMod(AllPublic), path_depth)
2768 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2769 let def = self.resolve_module_relative_path(span, segments, namespace);
2770 match (def, unqualified_def) {
2771 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2773 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2776 "unnecessary qualification".to_string());
2784 // Resolve a single identifier
2785 fn resolve_identifier(&mut self,
2786 identifier: hir::Ident,
2787 namespace: Namespace,
2790 -> Option<LocalDef> {
2791 if identifier.name == special_idents::invalid.name {
2792 return Some(LocalDef::from_def(Def::Err));
2795 // First, check to see whether the name is a primitive type.
2796 if namespace == TypeNS {
2797 if let Some(&prim_ty) = self.primitive_type_table
2799 .get(&identifier.unhygienic_name) {
2800 return Some(LocalDef::from_def(Def::PrimTy(prim_ty)));
2805 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2811 let module = self.current_module;
2812 let name = identifier.unhygienic_name;
2813 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
2814 Success(binding) => binding.def().map(LocalDef::from_def),
2815 Failed(Some((span, msg))) => {
2816 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2823 // Resolve a local definition, potentially adjusting for closures.
2824 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2825 let ribs = match local_def.ribs {
2826 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2827 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2830 let mut def = local_def.def;
2833 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2835 Def::Local(_, node_id) => {
2838 NormalRibKind | AnonymousModuleRibKind(..) => {
2839 // Nothing to do. Continue.
2841 ClosureRibKind(function_id) => {
2843 let node_def_id = self.ast_map.local_def_id(node_id);
2845 let seen = self.freevars_seen
2847 .or_insert_with(|| NodeMap());
2848 if let Some(&index) = seen.get(&node_id) {
2849 def = Def::Upvar(node_def_id, node_id, index, function_id);
2852 let vec = self.freevars
2854 .or_insert_with(|| vec![]);
2855 let depth = vec.len();
2861 def = Def::Upvar(node_def_id, node_id, depth, function_id);
2862 seen.insert(node_id, depth);
2864 ItemRibKind | MethodRibKind => {
2865 // This was an attempt to access an upvar inside a
2866 // named function item. This is not allowed, so we
2870 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2873 ConstantItemRibKind => {
2874 // Still doesn't deal with upvars
2877 ResolutionError::AttemptToUseNonConstantValueInConstant);
2883 Def::TyParam(..) | Def::SelfTy(..) => {
2886 NormalRibKind | MethodRibKind | ClosureRibKind(..) |
2887 AnonymousModuleRibKind(..) => {
2888 // Nothing to do. Continue.
2891 // This was an attempt to use a type parameter outside
2896 ResolutionError::TypeParametersFromOuterFunction);
2899 ConstantItemRibKind => {
2901 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2912 // resolve a "module-relative" path, e.g. a::b::c
2913 fn resolve_module_relative_path(&mut self,
2915 segments: &[hir::PathSegment],
2916 namespace: Namespace)
2917 -> Option<(Def, LastPrivate)> {
2918 let module_path = segments.split_last()
2922 .map(|ps| ps.identifier.name)
2923 .collect::<Vec<_>>();
2925 let containing_module;
2927 let current_module = self.current_module;
2928 match self.resolve_module_path(current_module, &module_path, UseLexicalScope, span) {
2930 let (span, msg) = match err {
2931 Some((span, msg)) => (span, msg),
2933 let msg = format!("Use of undeclared type or module `{}`",
2934 names_to_string(&module_path));
2939 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2942 Indeterminate => return None,
2943 Success((resulting_module, resulting_last_private)) => {
2944 containing_module = resulting_module;
2945 last_private = resulting_last_private;
2949 let name = segments.last().unwrap().identifier.name;
2950 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2951 let def = match result {
2952 Success(binding) => {
2953 let (def, lp) = binding.def_and_lp();
2954 (def, last_private.or(lp))
2961 /// Invariant: This must be called only during main resolution, not during
2962 /// import resolution.
2963 fn resolve_crate_relative_path(&mut self,
2965 segments: &[hir::PathSegment],
2966 namespace: Namespace)
2967 -> Option<(Def, LastPrivate)> {
2968 let module_path = segments.split_last()
2972 .map(|ps| ps.identifier.name)
2973 .collect::<Vec<_>>();
2975 let root_module = self.graph_root;
2977 let containing_module;
2979 match self.resolve_module_path_from_root(root_module,
2983 LastMod(AllPublic)) {
2985 let (span, msg) = match err {
2986 Some((span, msg)) => (span, msg),
2988 let msg = format!("Use of undeclared module `::{}`",
2989 names_to_string(&module_path));
2994 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2998 Indeterminate => return None,
3000 Success((resulting_module, resulting_last_private)) => {
3001 containing_module = resulting_module;
3002 last_private = resulting_last_private;
3006 let name = segments.last().unwrap().identifier.name;
3007 match self.resolve_name_in_module(containing_module, name, namespace, false, true) {
3008 Success(binding) => {
3009 let (def, lp) = binding.def_and_lp();
3010 Some((def, last_private.or(lp)))
3016 fn resolve_identifier_in_local_ribs(&mut self,
3018 namespace: Namespace)
3019 -> Option<LocalDef> {
3020 // Check the local set of ribs.
3021 let name = match namespace { ValueNS => ident.name, TypeNS => ident.unhygienic_name };
3023 for i in (0 .. self.get_ribs(namespace).len()).rev() {
3024 if let Some(def_like) = self.get_ribs(namespace)[i].bindings.get(&name).cloned() {
3027 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3031 return Some(LocalDef {
3032 ribs: Some((namespace, i)),
3037 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3045 if let AnonymousModuleRibKind(module) = self.get_ribs(namespace)[i].kind {
3046 if let Success(binding) = self.resolve_name_in_module(module,
3047 ident.unhygienic_name,
3051 if let Some(def) = binding.def() {
3052 return Some(LocalDef::from_def(def));
3061 fn with_no_errors<T, F>(&mut self, f: F) -> T
3062 where F: FnOnce(&mut Resolver) -> T
3064 self.emit_errors = false;
3066 self.emit_errors = true;
3070 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3071 fn extract_path_and_node_id(t: &Ty,
3072 allow: FallbackChecks)
3073 -> Option<(Path, NodeId, FallbackChecks)> {
3075 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3076 TyPtr(ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, OnlyTraitAndStatics),
3077 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, allow),
3078 // This doesn't handle the remaining `Ty` variants as they are not
3079 // that commonly the self_type, it might be interesting to provide
3080 // support for those in future.
3085 fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
3087 name_path: &[ast::Name])
3088 -> Option<Module<'a>> {
3089 let root = this.current_module;
3090 let last_name = name_path.last().unwrap();
3092 if name_path.len() == 1 {
3093 match this.primitive_type_table.primitive_types.get(last_name) {
3095 None => this.current_module.resolve_name(*last_name, TypeNS, true).success()
3096 .and_then(NameBinding::module)
3099 match this.resolve_module_path(root, &name_path, UseLexicalScope, span) {
3100 Success((module, _)) => Some(module),
3106 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3107 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3108 let sig = match this.ast_map.get(node_id) {
3109 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3110 hir::MethodTraitItem(ref sig, _) => sig,
3113 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3114 hir::ImplItemKind::Method(ref sig, _) => sig,
3119 sig.explicit_self.node == hir::SelfStatic
3121 this.session.cstore.is_static_method(did)
3125 let (path, node_id, allowed) = match self.current_self_type {
3126 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3128 None => return NoSuggestion,
3130 None => return NoSuggestion,
3133 if allowed == Everything {
3134 // Look for a field with the same name in the current self_type.
3135 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3136 Some(Def::Enum(did)) |
3137 Some(Def::TyAlias(did)) |
3138 Some(Def::Struct(did)) |
3139 Some(Def::Variant(_, did)) => match self.structs.get(&did) {
3142 if fields.iter().any(|&field_name| name == field_name) {
3147 _ => {} // Self type didn't resolve properly
3151 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3153 // Look for a method in the current self type's impl module.
3154 if let Some(module) = get_module(self, path.span, &name_path) {
3155 if let Success(binding) = module.resolve_name(name, ValueNS, true) {
3156 if let Some(Def::Method(did)) = binding.def() {
3157 if is_static_method(self, did) {
3158 return StaticMethod(path_names_to_string(&path, 0));
3160 if self.current_trait_ref.is_some() {
3162 } else if allowed == Everything {
3169 // Look for a method in the current trait.
3170 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3171 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3172 if is_static_method(self, did) {
3173 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3183 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3184 if let Some(macro_name) = self.session.available_macros
3185 .borrow().iter().find(|n| n.as_str() == name) {
3186 return SuggestionType::Macro(format!("{}!", macro_name));
3189 let names = self.value_ribs
3192 .flat_map(|rib| rib.bindings.keys());
3194 if let Some(found) = find_best_match_for_name(names, name, None) {
3196 return SuggestionType::Function(found);
3198 } SuggestionType::NotFound
3201 fn resolve_expr(&mut self, expr: &Expr) {
3202 // First, record candidate traits for this expression if it could
3203 // result in the invocation of a method call.
3205 self.record_candidate_traits_for_expr_if_necessary(expr);
3207 // Next, resolve the node.
3209 ExprPath(ref maybe_qself, ref path) => {
3210 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3211 maybe_qself.as_ref(),
3215 // `<T>::a::b::c` is resolved by typeck alone.
3216 TypecheckRequired => {
3217 let method_name = path.segments.last().unwrap().identifier.name;
3218 let traits = self.get_traits_containing_item(method_name);
3219 self.trait_map.insert(expr.id, traits);
3220 intravisit::walk_expr(self, expr);
3223 ResolveAttempt(resolution) => resolution,
3226 // This is a local path in the value namespace. Walk through
3227 // scopes looking for it.
3228 if let Some(path_res) = resolution {
3229 // Check if struct variant
3230 let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
3231 self.structs.contains_key(&variant_id)
3235 if is_struct_variant {
3236 let _ = self.structs.contains_key(&path_res.base_def.def_id());
3237 let path_name = path_names_to_string(path, 0);
3239 let mut err = resolve_struct_error(self,
3241 ResolutionError::StructVariantUsedAsFunction(&path_name));
3243 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3245 if self.emit_errors {
3246 err.fileline_help(expr.span, &msg);
3248 err.span_help(expr.span, &msg);
3251 self.record_def(expr.id, err_path_resolution());
3253 // Write the result into the def map.
3254 debug!("(resolving expr) resolved `{}`",
3255 path_names_to_string(path, 0));
3257 // Partial resolutions will need the set of traits in scope,
3258 // so they can be completed during typeck.
3259 if path_res.depth != 0 {
3260 let method_name = path.segments.last().unwrap().identifier.name;
3261 let traits = self.get_traits_containing_item(method_name);
3262 self.trait_map.insert(expr.id, traits);
3265 self.record_def(expr.id, path_res);
3268 // Be helpful if the name refers to a struct
3269 // (The pattern matching def_tys where the id is in self.structs
3270 // matches on regular structs while excluding tuple- and enum-like
3271 // structs, which wouldn't result in this error.)
3272 let path_name = path_names_to_string(path, 0);
3273 let type_res = self.with_no_errors(|this| {
3274 this.resolve_path(expr.id, path, 0, TypeNS, false)
3277 self.record_def(expr.id, err_path_resolution());
3278 match type_res.map(|r| r.base_def) {
3279 Some(Def::Struct(..)) => {
3280 let mut err = resolve_struct_error(self,
3282 ResolutionError::StructVariantUsedAsFunction(&path_name));
3284 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3286 if self.emit_errors {
3287 err.fileline_help(expr.span, &msg);
3289 err.span_help(expr.span, &msg);
3294 // Keep reporting some errors even if they're ignored above.
3295 self.resolve_path(expr.id, path, 0, ValueNS, true);
3297 let mut method_scope = false;
3298 self.value_ribs.iter().rev().all(|rib| {
3299 method_scope = match rib.kind {
3300 MethodRibKind => true,
3301 ItemRibKind | ConstantItemRibKind => false,
3302 _ => return true, // Keep advancing
3304 false // Stop advancing
3307 if method_scope && special_names::self_.as_str() == &path_name[..] {
3310 ResolutionError::SelfNotAvailableInStaticMethod);
3312 let last_name = path.segments.last().unwrap().identifier.name;
3313 let mut msg = match self.find_fallback_in_self_type(last_name) {
3315 // limit search to 5 to reduce the number
3316 // of stupid suggestions
3317 match self.find_best_match(&path_name) {
3318 SuggestionType::Macro(s) => {
3319 format!("the macro `{}`", s)
3321 SuggestionType::Function(s) => format!("`{}`", s),
3322 SuggestionType::NotFound => "".to_string(),
3325 Field => format!("`self.{}`", path_name),
3327 TraitItem => format!("to call `self.{}`", path_name),
3328 TraitMethod(path_str) |
3329 StaticMethod(path_str) =>
3330 format!("to call `{}::{}`", path_str, path_name),
3333 let mut context = UnresolvedNameContext::Other;
3334 if !msg.is_empty() {
3335 msg = format!(". Did you mean {}?", msg);
3337 // we check if this a module and if so, we display a help
3339 let name_path = path.segments.iter()
3340 .map(|seg| seg.identifier.name)
3341 .collect::<Vec<_>>();
3342 let current_module = self.current_module;
3344 match self.resolve_module_path(current_module,
3349 context = UnresolvedNameContext::PathIsMod(expr.id);
3357 ResolutionError::UnresolvedName(
3358 &path_name, &msg, context));
3364 intravisit::walk_expr(self, expr);
3367 ExprStruct(ref path, _, _) => {
3368 // Resolve the path to the structure it goes to. We don't
3369 // check to ensure that the path is actually a structure; that
3370 // is checked later during typeck.
3371 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3372 Some(definition) => self.record_def(expr.id, definition),
3374 debug!("(resolving expression) didn't find struct def",);
3378 ResolutionError::DoesNotNameAStruct(
3379 &path_names_to_string(path, 0))
3381 self.record_def(expr.id, err_path_resolution());
3385 intravisit::walk_expr(self, expr);
3388 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3389 self.with_label_rib(|this| {
3390 let def_like = DlDef(Def::Label(expr.id));
3393 let rib = this.label_ribs.last_mut().unwrap();
3394 rib.bindings.insert(label.name, def_like);
3397 intravisit::walk_expr(this, expr);
3401 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3402 match self.search_label(label.node.name) {
3404 self.record_def(expr.id, err_path_resolution());
3407 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3409 Some(DlDef(def @ Def::Label(_))) => {
3410 // Since this def is a label, it is never read.
3411 self.record_def(expr.id,
3414 last_private: LastMod(AllPublic),
3419 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3425 intravisit::walk_expr(self, expr);
3430 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3432 ExprField(_, name) => {
3433 // FIXME(#6890): Even though you can't treat a method like a
3434 // field, we need to add any trait methods we find that match
3435 // the field name so that we can do some nice error reporting
3436 // later on in typeck.
3437 let traits = self.get_traits_containing_item(name.node);
3438 self.trait_map.insert(expr.id, traits);
3440 ExprMethodCall(name, _, _) => {
3441 debug!("(recording candidate traits for expr) recording traits for {}",
3443 let traits = self.get_traits_containing_item(name.node);
3444 self.trait_map.insert(expr.id, traits);
3452 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3453 debug!("(getting traits containing item) looking for '{}'", name);
3455 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3456 debug!("(adding trait info) found trait {:?} for method '{}'",
3459 found_traits.push(trait_def_id);
3462 let mut found_traits = Vec::new();
3463 let mut search_module = self.current_module;
3465 // Look for the current trait.
3466 match self.current_trait_ref {
3467 Some((trait_def_id, _)) => {
3468 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3469 add_trait_info(&mut found_traits, trait_def_id, name);
3472 None => {} // Nothing to do.
3475 // Look for trait children.
3476 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3478 search_module.for_each_child(|_, ns, name_binding| {
3479 if ns != TypeNS { return }
3480 let trait_def_id = match name_binding.def() {
3481 Some(Def::Trait(trait_def_id)) => trait_def_id,
3482 Some(..) | None => return,
3484 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3485 add_trait_info(&mut found_traits, trait_def_id, name);
3486 let trait_name = self.get_trait_name(trait_def_id);
3487 self.record_use(trait_name, TypeNS, name_binding);
3491 // Look for shadowed traits.
3492 for binding in search_module.shadowed_traits.borrow().iter() {
3493 let did = binding.def().unwrap().def_id();
3494 if self.trait_item_map.contains_key(&(name, did)) {
3495 add_trait_info(&mut found_traits, did, name);
3496 let trait_name = self.get_trait_name(did);
3497 self.record_use(trait_name, TypeNS, binding);
3501 match search_module.parent_link {
3502 NoParentLink | ModuleParentLink(..) => break,
3503 BlockParentLink(parent_module, _) => {
3504 search_module = parent_module;
3512 /// When name resolution fails, this method can be used to look up candidate
3513 /// entities with the expected name. It allows filtering them using the
3514 /// supplied predicate (which should be used to only accept the types of
3515 /// definitions expected e.g. traits). The lookup spans across all crates.
3517 /// NOTE: The method does not look into imports, but this is not a problem,
3518 /// since we report the definitions (thus, the de-aliased imports).
3519 fn lookup_candidates<FilterFn>(&mut self,
3521 namespace: Namespace,
3522 filter_fn: FilterFn) -> SuggestedCandidates
3523 where FilterFn: Fn(Def) -> bool {
3525 let mut lookup_results = Vec::new();
3526 let mut worklist = Vec::new();
3527 worklist.push((self.graph_root, Vec::new(), false));
3529 while let Some((in_module,
3531 in_module_is_extern)) = worklist.pop() {
3532 build_reduced_graph::populate_module_if_necessary(self, &in_module);
3534 in_module.for_each_child(|name, ns, name_binding| {
3536 // avoid imports entirely
3537 if name_binding.is_import() { return; }
3539 // collect results based on the filter function
3540 if let Some(def) = name_binding.def() {
3541 if name == lookup_name && ns == namespace && filter_fn(def) {
3543 let ident = hir::Ident::from_name(name);
3544 let params = PathParameters::none();
3545 let segment = PathSegment {
3549 let span = name_binding.span.unwrap_or(syntax::codemap::DUMMY_SP);
3550 let mut segms = path_segments.clone();
3551 segms.push(segment);
3552 let segms = HirVec::from_vec(segms);
3558 // the entity is accessible in the following cases:
3559 // 1. if it's defined in the same crate, it's always
3560 // accessible (since private entities can be made public)
3561 // 2. if it's defined in another crate, it's accessible
3562 // only if both the module is public and the entity is
3563 // declared as public (due to pruning, we don't explore
3564 // outside crate private modules => no need to check this)
3565 if !in_module_is_extern || name_binding.is_public() {
3566 lookup_results.push(path);
3571 // collect submodules to explore
3572 if let Some(module) = name_binding.module() {
3574 let path_segments = match module.parent_link {
3575 NoParentLink => path_segments.clone(),
3576 ModuleParentLink(_, name) => {
3577 let mut paths = path_segments.clone();
3578 let ident = hir::Ident::from_name(name);
3579 let params = PathParameters::none();
3580 let segm = PathSegment {
3587 _ => unreachable!(),
3590 if !in_module_is_extern || name_binding.is_public() {
3591 // add the module to the lookup
3592 let is_extern = in_module_is_extern || module.is_extern_crate;
3593 worklist.push((module, path_segments, is_extern));
3599 SuggestedCandidates {
3600 name: lookup_name.as_str().to_string(),
3601 candidates: lookup_results,
3605 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3606 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3607 assert!(match resolution.last_private {
3608 LastImport{..} => false,
3611 "Import should only be used for `use` directives");
3613 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3614 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3615 self.session.span_bug(span,
3616 &format!("path resolved multiple times ({:?} before, {:?} now)",
3622 fn enforce_default_binding_mode(&mut self,
3624 pat_binding_mode: BindingMode,
3626 match pat_binding_mode {
3627 BindByValue(_) => {}
3631 ResolutionError::CannotUseRefBindingModeWith(descr));
3638 fn names_to_string(names: &[Name]) -> String {
3639 let mut first = true;
3640 let mut result = String::new();
3645 result.push_str("::")
3647 result.push_str(&name.as_str());
3652 fn path_names_to_string(path: &Path, depth: usize) -> String {
3653 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3655 .map(|seg| seg.identifier.name)
3657 names_to_string(&names[..])
3660 /// When an entity with a given name is not available in scope, we search for
3661 /// entities with that name in all crates. This method allows outputting the
3662 /// results of this search in a programmer-friendly way
3663 fn show_candidates(session: &mut DiagnosticBuilder,
3664 span: syntax::codemap::Span,
3665 candidates: &SuggestedCandidates) {
3667 let paths = &candidates.candidates;
3669 if paths.len() > 0 {
3670 // don't show more than MAX_CANDIDATES results, so
3671 // we're consistent with the trait suggestions
3672 const MAX_CANDIDATES: usize = 5;
3674 // we want consistent results across executions, but candidates are produced
3675 // by iterating through a hash map, so make sure they are ordered:
3676 let mut path_strings: Vec<_> = paths.into_iter()
3677 .map(|p| path_names_to_string(&p, 0))
3679 path_strings.sort();
3681 // behave differently based on how many candidates we have:
3682 if !paths.is_empty() {
3683 if paths.len() == 1 {
3684 session.fileline_help(
3686 &format!("you can to import it into scope: `use {};`.",
3690 session.fileline_help(span, "you can import several candidates \
3691 into scope (`use ...;`):");
3692 let count = path_strings.len() as isize - MAX_CANDIDATES as isize + 1;
3694 for (idx, path_string) in path_strings.iter().enumerate() {
3695 if idx == MAX_CANDIDATES - 1 && count > 1 {
3696 session.fileline_help(
3698 &format!(" and {} other candidates", count).to_string(),
3702 session.fileline_help(
3704 &format!(" `{}`", path_string).to_string(),
3712 session.fileline_help(
3714 &format!("no candidates by the name of `{}` found in your \
3715 project; maybe you misspelled the name or forgot to import \
3716 an external crate?", candidates.name.to_string()),
3721 /// A somewhat inefficient routine to obtain the name of a module.
3722 fn module_to_string(module: Module) -> String {
3723 let mut names = Vec::new();
3725 fn collect_mod(names: &mut Vec<ast::Name>, module: Module) {
3726 match module.parent_link {
3728 ModuleParentLink(ref module, name) => {
3730 collect_mod(names, module);
3732 BlockParentLink(ref module, _) => {
3733 // danger, shouldn't be ident?
3734 names.push(special_idents::opaque.name);
3735 collect_mod(names, module);
3739 collect_mod(&mut names, module);
3741 if names.is_empty() {
3742 return "???".to_string();
3744 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3747 fn err_path_resolution() -> PathResolution {
3750 last_private: LastMod(AllPublic),
3756 pub struct CrateMap {
3757 pub def_map: RefCell<DefMap>,
3758 pub freevars: FreevarMap,
3759 pub export_map: ExportMap,
3760 pub trait_map: TraitMap,
3761 pub external_exports: ExternalExports,
3762 pub glob_map: Option<GlobMap>,
3765 #[derive(PartialEq,Copy, Clone)]
3766 pub enum MakeGlobMap {
3771 /// Entry point to crate resolution.
3772 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3773 ast_map: &'a hir_map::Map<'tcx>,
3774 make_glob_map: MakeGlobMap)
3776 // Currently, we ignore the name resolution data structures for
3777 // the purposes of dependency tracking. Instead we will run name
3778 // resolution and include its output in the hash of each item,
3779 // much like we do for macro expansion. In other words, the hash
3780 // reflects not just its contents but the results of name
3781 // resolution on those contents. Hopefully we'll push this back at
3783 let _task = ast_map.dep_graph.in_task(DepNode::Resolve);
3785 let krate = ast_map.krate();
3786 let arenas = Resolver::arenas();
3787 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3789 resolver.resolve_crate(krate);
3791 check_unused::check_crate(&mut resolver, krate);
3794 def_map: resolver.def_map,
3795 freevars: resolver.freevars,
3796 export_map: resolver.export_map,
3797 trait_map: resolver.trait_map,
3798 external_exports: resolver.external_exports,
3799 glob_map: if resolver.make_glob_map {
3800 Some(resolver.glob_map)
3807 /// Builds a name resolution walker to be used within this module,
3808 /// or used externally, with an optional callback function.
3810 /// The callback takes a &mut bool which allows callbacks to end a
3811 /// walk when set to true, passing through the rest of the walk, while
3812 /// preserving the ribs + current module. This allows resolve_path
3813 /// calls to be made with the correct scope info. The node in the
3814 /// callback corresponds to the current node in the walk.
3815 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3816 ast_map: &'a hir_map::Map<'tcx>,
3818 make_glob_map: MakeGlobMap,
3819 arenas: &'a ResolverArenas<'a>,
3820 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3821 -> Resolver<'a, 'tcx> {
3822 let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
3824 resolver.callback = callback;
3826 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3828 resolve_imports::resolve_imports(&mut resolver);
3833 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }