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(rustc_diagnostic_macros)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
32 extern crate rustc_bitflags;
33 extern crate rustc_front;
36 use self::PatternBindingMode::*;
37 use self::Namespace::*;
38 use self::ResolveResult::*;
39 use self::FallbackSuggestion::*;
40 use self::TypeParameters::*;
42 use self::UseLexicalScopeFlag::*;
43 use self::ModulePrefixResult::*;
44 use self::AssocItemResolveResult::*;
45 use self::BareIdentifierPatternResolution::*;
46 use self::ParentLink::*;
47 use self::FallbackChecks::*;
49 use rustc::dep_graph::DepNode;
50 use rustc::front::map as hir_map;
51 use rustc::session::Session;
53 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
54 use rustc::middle::def::*;
55 use rustc::middle::def_id::DefId;
56 use rustc::middle::pat_util::pat_bindings;
57 use rustc::middle::privacy::*;
58 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
60 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
62 use syntax::ast::{self, FloatTy};
63 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
64 use syntax::attr::AttrMetaMethods;
65 use syntax::codemap::{self, Span, Pos};
66 use syntax::errors::DiagnosticBuilder;
67 use syntax::parse::token::{self, special_names, special_idents};
68 use syntax::util::lev_distance::find_best_match_for_name;
70 use rustc_front::intravisit::{self, FnKind, Visitor};
72 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
73 use rustc_front::hir::Crate;
74 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
75 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
76 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
77 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
78 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
79 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
80 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
81 use rustc_front::hir::Local;
82 use rustc_front::hir::{Pat, PatKind, Path, PrimTy};
83 use rustc_front::hir::{PathSegment, PathParameters};
84 use rustc_front::hir::HirVec;
85 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
86 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
87 use rustc_front::util::walk_pat;
89 use std::collections::{HashMap, HashSet};
90 use std::cell::{Cell, RefCell};
92 use std::mem::replace;
94 use resolve_imports::{ImportDirective, NameResolution};
96 // NB: This module needs to be declared first so diagnostics are
97 // registered before they are used.
101 mod build_reduced_graph;
104 // Perform the callback, not walking deeper if the return is true
105 macro_rules! execute_callback {
106 ($node: expr, $walker: expr) => (
107 if let Some(ref callback) = $walker.callback {
108 if callback($node, &mut $walker.resolved) {
115 enum SuggestionType {
117 Function(token::InternedString),
121 /// Candidates for a name resolution failure
122 pub struct SuggestedCandidates {
124 candidates: Vec<Path>,
127 pub enum ResolutionError<'a> {
128 /// error E0401: can't use type parameters from outer function
129 TypeParametersFromOuterFunction,
130 /// error E0402: cannot use an outer type parameter in this context
131 OuterTypeParameterContext,
132 /// error E0403: the name is already used for a type parameter in this type parameter list
133 NameAlreadyUsedInTypeParameterList(Name),
134 /// error E0404: is not a trait
135 IsNotATrait(&'a str),
136 /// error E0405: use of undeclared trait name
137 UndeclaredTraitName(&'a str, SuggestedCandidates),
138 /// error E0406: undeclared associated type
139 UndeclaredAssociatedType,
140 /// error E0407: method is not a member of trait
141 MethodNotMemberOfTrait(Name, &'a str),
142 /// error E0437: type is not a member of trait
143 TypeNotMemberOfTrait(Name, &'a str),
144 /// error E0438: const is not a member of trait
145 ConstNotMemberOfTrait(Name, &'a str),
146 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
147 VariableNotBoundInPattern(Name, usize),
148 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
149 VariableBoundWithDifferentMode(Name, usize),
150 /// error E0410: variable from pattern is not bound in pattern #1
151 VariableNotBoundInParentPattern(Name, usize),
152 /// error E0411: use of `Self` outside of an impl or trait
153 SelfUsedOutsideImplOrTrait,
154 /// error E0412: use of undeclared
155 UseOfUndeclared(&'a str, &'a str, SuggestedCandidates),
156 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
157 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
158 /// error E0414: only irrefutable patterns allowed here
159 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
160 /// error E0415: identifier is bound more than once in this parameter list
161 IdentifierBoundMoreThanOnceInParameterList(&'a str),
162 /// error E0416: identifier is bound more than once in the same pattern
163 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
164 /// error E0417: static variables cannot be referenced in a pattern
165 StaticVariableReference,
166 /// error E0418: is not an enum variant, struct or const
167 NotAnEnumVariantStructOrConst(&'a str),
168 /// error E0419: unresolved enum variant, struct or const
169 UnresolvedEnumVariantStructOrConst(&'a str),
170 /// error E0420: is not an associated const
171 NotAnAssociatedConst(&'a str),
172 /// error E0421: unresolved associated const
173 UnresolvedAssociatedConst(&'a str),
174 /// error E0422: does not name a struct
175 DoesNotNameAStruct(&'a str),
176 /// error E0423: is a struct variant name, but this expression uses it like a function name
177 StructVariantUsedAsFunction(&'a str),
178 /// error E0424: `self` is not available in a static method
179 SelfNotAvailableInStaticMethod,
180 /// error E0425: unresolved name
181 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
182 /// error E0426: use of undeclared label
183 UndeclaredLabel(&'a str),
184 /// error E0427: cannot use `ref` binding mode with ...
185 CannotUseRefBindingModeWith(&'a str),
186 /// error E0428: duplicate definition
187 DuplicateDefinition(&'a str, Name),
188 /// error E0429: `self` imports are only allowed within a { } list
189 SelfImportsOnlyAllowedWithin,
190 /// error E0430: `self` import can only appear once in the list
191 SelfImportCanOnlyAppearOnceInTheList,
192 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
193 SelfImportOnlyInImportListWithNonEmptyPrefix,
194 /// error E0432: unresolved import
195 UnresolvedImport(Option<(&'a str, &'a str)>),
196 /// error E0433: failed to resolve
197 FailedToResolve(&'a str),
198 /// error E0434: can't capture dynamic environment in a fn item
199 CannotCaptureDynamicEnvironmentInFnItem,
200 /// error E0435: attempt to use a non-constant value in a constant
201 AttemptToUseNonConstantValueInConstant,
204 /// Context of where `ResolutionError::UnresolvedName` arose.
205 #[derive(Clone, PartialEq, Eq, Debug)]
206 pub enum UnresolvedNameContext {
207 /// `PathIsMod(id)` indicates that a given path, used in
208 /// expression context, actually resolved to a module rather than
209 /// a value. The `id` attached to the variant is the node id of
210 /// the erroneous path expression.
211 PathIsMod(ast::NodeId),
213 /// `Other` means we have no extra information about the context
214 /// of the unresolved name error. (Maybe we could eliminate all
215 /// such cases; but for now, this is an information-free default.)
219 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
220 span: syntax::codemap::Span,
221 resolution_error: ResolutionError<'b>) {
222 resolve_struct_error(resolver, span, resolution_error).emit();
225 fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
226 span: syntax::codemap::Span,
227 resolution_error: ResolutionError<'b>)
228 -> DiagnosticBuilder<'a> {
229 if !resolver.emit_errors {
230 return resolver.session.diagnostic().struct_dummy();
233 match resolution_error {
234 ResolutionError::TypeParametersFromOuterFunction => {
235 struct_span_err!(resolver.session,
238 "can't use type parameters from outer function; try using a local \
239 type parameter instead")
241 ResolutionError::OuterTypeParameterContext => {
242 struct_span_err!(resolver.session,
245 "cannot use an outer type parameter in this context")
247 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
248 struct_span_err!(resolver.session,
251 "the name `{}` is already used for a type parameter in this type \
255 ResolutionError::IsNotATrait(name) => {
256 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
258 ResolutionError::UndeclaredTraitName(name, candidates) => {
259 let mut err = struct_span_err!(resolver.session,
262 "trait `{}` is not in scope",
264 show_candidates(&mut err, span, &candidates);
267 ResolutionError::UndeclaredAssociatedType => {
268 struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
270 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
271 struct_span_err!(resolver.session,
274 "method `{}` is not a member of trait `{}`",
278 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
279 struct_span_err!(resolver.session,
282 "type `{}` is not a member of trait `{}`",
286 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
287 struct_span_err!(resolver.session,
290 "const `{}` is not a member of trait `{}`",
294 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
295 struct_span_err!(resolver.session,
298 "variable `{}` from pattern #1 is not bound in pattern #{}",
302 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
303 struct_span_err!(resolver.session,
306 "variable `{}` is bound with different mode in pattern #{} than in \
311 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
312 struct_span_err!(resolver.session,
315 "variable `{}` from pattern #{} is not bound in pattern #1",
319 ResolutionError::SelfUsedOutsideImplOrTrait => {
320 struct_span_err!(resolver.session,
323 "use of `Self` outside of an impl or trait")
325 ResolutionError::UseOfUndeclared(kind, name, candidates) => {
326 let mut err = struct_span_err!(resolver.session,
329 "{} `{}` is undefined or not in scope",
332 show_candidates(&mut err, span, &candidates);
335 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
336 struct_span_err!(resolver.session,
339 "declaration of `{}` shadows an enum variant \
340 or unit-like struct in scope",
343 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
344 let mut err = struct_span_err!(resolver.session,
347 "only irrefutable patterns allowed here");
349 "there already is a constant in scope sharing the same \
350 name as this pattern");
351 if let Some(sp) = resolver.ast_map.span_if_local(did) {
352 err.span_note(sp, "constant defined here");
354 if let Success(binding) = resolver.current_module.resolve_name(name, ValueNS, true) {
355 if binding.is_import() {
356 err.span_note(binding.span.unwrap(), "constant imported here");
361 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
362 struct_span_err!(resolver.session,
365 "identifier `{}` is bound more than once in this parameter list",
368 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
369 struct_span_err!(resolver.session,
372 "identifier `{}` is bound more than once in the same pattern",
375 ResolutionError::StaticVariableReference => {
376 struct_span_err!(resolver.session,
379 "static variables cannot be referenced in a pattern, use a \
382 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
383 struct_span_err!(resolver.session,
386 "`{}` is not an enum variant, struct or const",
389 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
390 struct_span_err!(resolver.session,
393 "unresolved enum variant, struct or const `{}`",
396 ResolutionError::NotAnAssociatedConst(name) => {
397 struct_span_err!(resolver.session,
400 "`{}` is not an associated const",
403 ResolutionError::UnresolvedAssociatedConst(name) => {
404 struct_span_err!(resolver.session,
407 "unresolved associated const `{}`",
410 ResolutionError::DoesNotNameAStruct(name) => {
411 struct_span_err!(resolver.session,
414 "`{}` does not name a structure",
417 ResolutionError::StructVariantUsedAsFunction(path_name) => {
418 struct_span_err!(resolver.session,
421 "`{}` is the name of a struct or struct variant, but this expression \
422 uses it like a function name",
425 ResolutionError::SelfNotAvailableInStaticMethod => {
426 struct_span_err!(resolver.session,
429 "`self` is not available in a static method. Maybe a `self` \
430 argument is missing?")
432 ResolutionError::UnresolvedName(path, msg, context) => {
433 let mut err = struct_span_err!(resolver.session,
436 "unresolved name `{}`{}",
441 UnresolvedNameContext::Other => { } // no help available
442 UnresolvedNameContext::PathIsMod(id) => {
443 let mut help_msg = String::new();
444 let parent_id = resolver.ast_map.get_parent_node(id);
445 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
447 ExprField(_, ident) => {
448 help_msg = format!("To reference an item from the \
449 `{module}` module, use \
450 `{module}::{ident}`",
454 ExprMethodCall(ident, _, _) => {
455 help_msg = format!("To call a function from the \
456 `{module}` module, use \
457 `{module}::{ident}(..)`",
462 help_msg = format!("No function corresponds to `{module}(..)`",
465 _ => { } // no help available
468 help_msg = format!("Module `{module}` cannot be the value of an expression",
472 if !help_msg.is_empty() {
473 err.fileline_help(span, &help_msg);
479 ResolutionError::UndeclaredLabel(name) => {
480 struct_span_err!(resolver.session,
483 "use of undeclared label `{}`",
486 ResolutionError::CannotUseRefBindingModeWith(descr) => {
487 struct_span_err!(resolver.session,
490 "cannot use `ref` binding mode with {}",
493 ResolutionError::DuplicateDefinition(namespace, name) => {
494 struct_span_err!(resolver.session,
497 "duplicate definition of {} `{}`",
501 ResolutionError::SelfImportsOnlyAllowedWithin => {
502 struct_span_err!(resolver.session,
506 "`self` imports are only allowed within a { } list")
508 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
509 struct_span_err!(resolver.session,
512 "`self` import can only appear once in the list")
514 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
515 struct_span_err!(resolver.session,
518 "`self` import can only appear in an import list with a \
521 ResolutionError::UnresolvedImport(name) => {
522 let msg = match name {
523 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
524 None => "unresolved import".to_owned(),
526 struct_span_err!(resolver.session, span, E0432, "{}", msg)
528 ResolutionError::FailedToResolve(msg) => {
529 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
531 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
532 struct_span_err!(resolver.session,
536 "can't capture dynamic environment in a fn item; use the || { ... } \
537 closure form instead")
539 ResolutionError::AttemptToUseNonConstantValueInConstant => {
540 struct_span_err!(resolver.session,
543 "attempt to use a non-constant value in a constant")
548 #[derive(Copy, Clone)]
551 binding_mode: BindingMode,
554 // Map from the name in a pattern to its binding mode.
555 type BindingMap = HashMap<Name, BindingInfo>;
557 #[derive(Copy, Clone, PartialEq)]
558 enum PatternBindingMode {
560 LocalIrrefutableMode,
561 ArgumentIrrefutableMode,
564 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
570 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
571 fn visit_nested_item(&mut self, item: hir::ItemId) {
572 self.visit_item(self.ast_map.expect_item(item.id))
574 fn visit_item(&mut self, item: &Item) {
575 execute_callback!(hir_map::Node::NodeItem(item), self);
576 self.resolve_item(item);
578 fn visit_arm(&mut self, arm: &Arm) {
579 self.resolve_arm(arm);
581 fn visit_block(&mut self, block: &Block) {
582 execute_callback!(hir_map::Node::NodeBlock(block), self);
583 self.resolve_block(block);
585 fn visit_expr(&mut self, expr: &Expr) {
586 execute_callback!(hir_map::Node::NodeExpr(expr), self);
587 self.resolve_expr(expr);
589 fn visit_local(&mut self, local: &Local) {
590 execute_callback!(hir_map::Node::NodeLocal(&local.pat), self);
591 self.resolve_local(local);
593 fn visit_ty(&mut self, ty: &Ty) {
594 self.resolve_type(ty);
596 fn visit_generics(&mut self, generics: &Generics) {
597 self.resolve_generics(generics);
599 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
600 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
601 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
603 // error already reported
604 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
607 intravisit::walk_poly_trait_ref(self, tref, m);
609 fn visit_variant(&mut self,
610 variant: &hir::Variant,
612 item_id: ast::NodeId) {
613 execute_callback!(hir_map::Node::NodeVariant(variant), self);
614 if let Some(ref dis_expr) = variant.node.disr_expr {
615 // resolve the discriminator expr as a constant
616 self.with_constant_rib(|this| {
617 this.visit_expr(dis_expr);
621 // `intravisit::walk_variant` without the discriminant expression.
622 self.visit_variant_data(&variant.node.data,
628 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
629 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
630 let type_parameters = match foreign_item.node {
631 ForeignItemFn(_, ref generics) => {
632 HasTypeParameters(generics, FnSpace, ItemRibKind)
634 ForeignItemStatic(..) => NoTypeParameters,
636 self.with_type_parameter_rib(type_parameters, |this| {
637 intravisit::walk_foreign_item(this, foreign_item);
640 fn visit_fn(&mut self,
641 function_kind: FnKind<'v>,
642 declaration: &'v FnDecl,
646 let rib_kind = match function_kind {
647 FnKind::ItemFn(_, generics, _, _, _, _) => {
648 self.visit_generics(generics);
651 FnKind::Method(_, sig, _) => {
652 self.visit_generics(&sig.generics);
653 self.visit_explicit_self(&sig.explicit_self);
656 FnKind::Closure => ClosureRibKind(node_id),
658 self.resolve_function(rib_kind, declaration, block);
662 pub type ErrorMessage = Option<(Span, String)>;
664 #[derive(Clone, PartialEq, Eq)]
665 pub enum ResolveResult<T> {
666 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
667 Indeterminate, // Couldn't determine due to unresolved globs.
668 Success(T), // Successfully resolved the import.
671 impl<T> ResolveResult<T> {
672 fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
674 Failed(msg) => Failed(msg),
675 Indeterminate => Indeterminate,
680 fn success(self) -> Option<T> {
682 Success(t) => Some(t),
688 enum FallbackSuggestion {
693 StaticMethod(String),
697 #[derive(Copy, Clone)]
698 enum TypeParameters<'tcx, 'a> {
700 HasTypeParameters(// Type parameters.
703 // Identifies the things that these parameters
704 // were declared on (type, fn, etc)
707 // The kind of the rib used for type parameters.
711 // The rib kind controls the translation of local
712 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
713 #[derive(Copy, Clone, Debug)]
715 // No translation needs to be applied.
718 // We passed through a closure scope at the given node ID.
719 // Translate upvars as appropriate.
720 ClosureRibKind(NodeId /* func id */),
722 // We passed through an impl or trait and are now in one of its
723 // methods. Allow references to ty params that impl or trait
724 // binds. Disallow any other upvars (including other ty params that are
728 // We passed through an item scope. Disallow upvars.
731 // We're in a constant item. Can't refer to dynamic stuff.
734 // We passed through an anonymous module.
735 AnonymousModuleRibKind(Module<'a>),
738 #[derive(Copy, Clone)]
739 enum UseLexicalScopeFlag {
744 enum ModulePrefixResult<'a> {
746 PrefixFound(Module<'a>, usize),
749 #[derive(Copy, Clone)]
750 enum AssocItemResolveResult {
751 /// Syntax such as `<T>::item`, which can't be resolved until type
754 /// We should have been able to resolve the associated item.
755 ResolveAttempt(Option<PathResolution>),
758 #[derive(Copy, Clone)]
759 enum BareIdentifierPatternResolution {
760 FoundStructOrEnumVariant(Def, LastPrivate),
761 FoundConst(Def, LastPrivate, Name),
762 BareIdentifierPatternUnresolved,
768 bindings: HashMap<Name, DefLike>,
773 fn new(kind: RibKind<'a>) -> Rib<'a> {
775 bindings: HashMap::new(),
781 /// A definition along with the index of the rib it was found on
783 ribs: Option<(Namespace, usize)>,
788 fn from_def(def: Def) -> Self {
796 /// The link from a module up to its nearest parent node.
797 #[derive(Clone,Debug)]
798 enum ParentLink<'a> {
800 ModuleParentLink(Module<'a>, Name),
801 BlockParentLink(Module<'a>, NodeId),
804 /// One node in the tree of modules.
805 pub struct ModuleS<'a> {
806 parent_link: ParentLink<'a>,
809 is_extern_crate: bool,
811 resolutions: RefCell<HashMap<(Name, Namespace), NameResolution<'a>>>,
812 unresolved_imports: RefCell<Vec<ImportDirective>>,
814 // The module children of this node, including normal modules and anonymous modules.
815 // Anonymous children are pseudo-modules that are implicitly created around items
816 // contained within blocks.
818 // For example, if we have this:
826 // There will be an anonymous module created around `g` with the ID of the
827 // entry block for `f`.
828 module_children: RefCell<NodeMap<Module<'a>>>,
830 shadowed_traits: RefCell<Vec<&'a NameBinding<'a>>>,
832 // The number of unresolved globs that this module exports.
833 glob_count: Cell<usize>,
835 // The number of unresolved pub imports (both regular and globs) in this module
836 pub_count: Cell<usize>,
838 // The number of unresolved pub glob imports in this module
839 pub_glob_count: Cell<usize>,
841 // Whether this module is populated. If not populated, any attempt to
842 // access the children must be preceded with a
843 // `populate_module_if_necessary` call.
844 populated: Cell<bool>,
847 pub type Module<'a> = &'a ModuleS<'a>;
849 impl<'a> ModuleS<'a> {
851 fn new(parent_link: ParentLink<'a>, def: Option<Def>, external: bool, is_public: bool) -> Self {
853 parent_link: parent_link,
855 is_public: is_public,
856 is_extern_crate: false,
857 resolutions: RefCell::new(HashMap::new()),
858 unresolved_imports: RefCell::new(Vec::new()),
859 module_children: RefCell::new(NodeMap()),
860 shadowed_traits: RefCell::new(Vec::new()),
861 glob_count: Cell::new(0),
862 pub_count: Cell::new(0),
863 pub_glob_count: Cell::new(0),
864 populated: Cell::new(!external),
868 fn resolve_name(&self, name: Name, ns: Namespace, allow_private_imports: bool)
869 -> ResolveResult<&'a NameBinding<'a>> {
871 if allow_private_imports { self.glob_count.get() } else { self.pub_glob_count.get() };
873 self.resolutions.borrow().get(&(name, ns)).cloned().unwrap_or_default().result(glob_count)
874 .and_then(|binding| {
875 let allowed = allow_private_imports || !binding.is_import() || binding.is_public();
876 if allowed { Success(binding) } else { Failed(None) }
880 // Define the name or return the existing binding if there is a collision.
881 fn try_define_child(&self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>)
882 -> Result<(), &'a NameBinding<'a>> {
883 let mut children = self.resolutions.borrow_mut();
884 let resolution = children.entry((name, ns)).or_insert_with(Default::default);
886 // FIXME #31379: We can use methods from imported traits shadowed by non-import items
887 if let Some(old_binding) = resolution.binding {
888 if !old_binding.is_import() && binding.is_import() {
889 if let Some(Def::Trait(_)) = binding.def() {
890 self.shadowed_traits.borrow_mut().push(binding);
895 resolution.try_define(binding)
898 fn increment_outstanding_references_for(&self, name: Name, ns: Namespace) {
899 let mut children = self.resolutions.borrow_mut();
900 children.entry((name, ns)).or_insert_with(Default::default).outstanding_references += 1;
903 fn decrement_outstanding_references_for(&self, name: Name, ns: Namespace) {
904 match self.resolutions.borrow_mut().get_mut(&(name, ns)).unwrap().outstanding_references {
905 0 => panic!("No more outstanding references!"),
906 ref mut outstanding_references => { *outstanding_references -= 1; }
910 fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
911 for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
912 name_resolution.binding.map(|binding| f(name, ns, binding));
916 fn def_id(&self) -> Option<DefId> {
917 self.def.as_ref().map(Def::def_id)
920 fn is_normal(&self) -> bool {
922 Some(Def::Mod(_)) | Some(Def::ForeignMod(_)) => true,
927 fn is_trait(&self) -> bool {
929 Some(Def::Trait(_)) => true,
934 pub fn inc_glob_count(&self) {
935 self.glob_count.set(self.glob_count.get() + 1);
937 pub fn dec_glob_count(&self) {
938 assert!(self.glob_count.get() > 0);
939 self.glob_count.set(self.glob_count.get() - 1);
941 pub fn inc_pub_count(&self) {
942 self.pub_count.set(self.pub_count.get() + 1);
944 pub fn dec_pub_count(&self) {
945 assert!(self.pub_count.get() > 0);
946 self.pub_count.set(self.pub_count.get() - 1);
948 pub fn inc_pub_glob_count(&self) {
949 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
951 pub fn dec_pub_glob_count(&self) {
952 assert!(self.pub_glob_count.get() > 0);
953 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
957 impl<'a> fmt::Debug for ModuleS<'a> {
958 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
972 flags DefModifiers: u8 {
973 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
974 // or `use Enum::*` to work on private enums.
975 const PUBLIC = 1 << 0,
976 const IMPORTABLE = 1 << 1,
977 // Variants are considered `PUBLIC`, but some of them live in private enums.
978 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
979 const PRIVATE_VARIANT = 1 << 2,
980 const PRELUDE = 1 << 3,
981 const GLOB_IMPORTED = 1 << 4,
985 // Records a possibly-private value, type, or module definition.
987 pub struct NameBinding<'a> {
988 modifiers: DefModifiers,
989 kind: NameBindingKind<'a>,
994 enum NameBindingKind<'a> {
998 binding: &'a NameBinding<'a>,
1003 impl<'a> NameBinding<'a> {
1004 fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
1005 let modifiers = if module.is_public {
1006 DefModifiers::PUBLIC
1008 DefModifiers::empty()
1009 } | DefModifiers::IMPORTABLE;
1011 NameBinding { modifiers: modifiers, kind: NameBindingKind::Module(module), span: span }
1014 fn module(&self) -> Option<Module<'a>> {
1016 NameBindingKind::Module(module) => Some(module),
1017 NameBindingKind::Def(_) => None,
1018 NameBindingKind::Import { binding, .. } => binding.module(),
1022 fn def(&self) -> Option<Def> {
1024 NameBindingKind::Def(def) => Some(def),
1025 NameBindingKind::Module(module) => module.def,
1026 NameBindingKind::Import { binding, .. } => binding.def(),
1030 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1031 self.modifiers.contains(modifiers)
1034 fn is_public(&self) -> bool {
1035 self.defined_with(DefModifiers::PUBLIC)
1038 fn def_and_lp(&self) -> (Def, LastPrivate) {
1039 let def = self.def().unwrap();
1040 if let Def::Err = def { return (def, LastMod(AllPublic)) }
1041 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1044 fn is_extern_crate(&self) -> bool {
1045 self.module().map(|module| module.is_extern_crate).unwrap_or(false)
1048 fn is_import(&self) -> bool {
1050 NameBindingKind::Import { .. } => true,
1056 /// Interns the names of the primitive types.
1057 struct PrimitiveTypeTable {
1058 primitive_types: HashMap<Name, PrimTy>,
1061 impl PrimitiveTypeTable {
1062 fn new() -> PrimitiveTypeTable {
1063 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1065 table.intern("bool", TyBool);
1066 table.intern("char", TyChar);
1067 table.intern("f32", TyFloat(FloatTy::F32));
1068 table.intern("f64", TyFloat(FloatTy::F64));
1069 table.intern("isize", TyInt(IntTy::Is));
1070 table.intern("i8", TyInt(IntTy::I8));
1071 table.intern("i16", TyInt(IntTy::I16));
1072 table.intern("i32", TyInt(IntTy::I32));
1073 table.intern("i64", TyInt(IntTy::I64));
1074 table.intern("str", TyStr);
1075 table.intern("usize", TyUint(UintTy::Us));
1076 table.intern("u8", TyUint(UintTy::U8));
1077 table.intern("u16", TyUint(UintTy::U16));
1078 table.intern("u32", TyUint(UintTy::U32));
1079 table.intern("u64", TyUint(UintTy::U64));
1084 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1085 self.primitive_types.insert(token::intern(string), primitive_type);
1089 /// The main resolver class.
1090 pub struct Resolver<'a, 'tcx: 'a> {
1091 session: &'a Session,
1093 ast_map: &'a hir_map::Map<'tcx>,
1095 graph_root: Module<'a>,
1097 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1099 structs: FnvHashMap<DefId, Vec<Name>>,
1101 // The number of imports that are currently unresolved.
1102 unresolved_imports: usize,
1104 // The module that represents the current item scope.
1105 current_module: Module<'a>,
1107 // The current set of local scopes, for values.
1108 // FIXME #4948: Reuse ribs to avoid allocation.
1109 value_ribs: Vec<Rib<'a>>,
1111 // The current set of local scopes, for types.
1112 type_ribs: Vec<Rib<'a>>,
1114 // The current set of local scopes, for labels.
1115 label_ribs: Vec<Rib<'a>>,
1117 // The trait that the current context can refer to.
1118 current_trait_ref: Option<(DefId, TraitRef)>,
1120 // The current self type if inside an impl (used for better errors).
1121 current_self_type: Option<Ty>,
1123 // The idents for the primitive types.
1124 primitive_type_table: PrimitiveTypeTable,
1126 def_map: RefCell<DefMap>,
1127 freevars: FreevarMap,
1128 freevars_seen: NodeMap<NodeMap<usize>>,
1129 export_map: ExportMap,
1130 trait_map: TraitMap,
1131 external_exports: ExternalExports,
1133 // Whether or not to print error messages. Can be set to true
1134 // when getting additional info for error message suggestions,
1135 // so as to avoid printing duplicate errors
1138 make_glob_map: bool,
1139 // Maps imports to the names of items actually imported (this actually maps
1140 // all imports, but only glob imports are actually interesting).
1143 used_imports: HashSet<(NodeId, Namespace)>,
1144 used_crates: HashSet<CrateNum>,
1146 // Callback function for intercepting walks
1147 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1148 // The intention is that the callback modifies this flag.
1149 // Once set, the resolver falls out of the walk, preserving the ribs.
1152 arenas: &'a ResolverArenas<'a>,
1155 pub struct ResolverArenas<'a> {
1156 modules: arena::TypedArena<ModuleS<'a>>,
1157 name_bindings: arena::TypedArena<NameBinding<'a>>,
1160 #[derive(PartialEq)]
1161 enum FallbackChecks {
1163 OnlyTraitAndStatics,
1166 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1167 fn new(session: &'a Session,
1168 ast_map: &'a hir_map::Map<'tcx>,
1169 make_glob_map: MakeGlobMap,
1170 arenas: &'a ResolverArenas<'a>)
1171 -> Resolver<'a, 'tcx> {
1172 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1173 let graph_root = ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, true);
1174 let graph_root = arenas.modules.alloc(graph_root);
1181 // The outermost module has def ID 0; this is not reflected in the
1183 graph_root: graph_root,
1185 trait_item_map: FnvHashMap(),
1186 structs: FnvHashMap(),
1188 unresolved_imports: 0,
1190 current_module: graph_root,
1191 value_ribs: Vec::new(),
1192 type_ribs: Vec::new(),
1193 label_ribs: Vec::new(),
1195 current_trait_ref: None,
1196 current_self_type: None,
1198 primitive_type_table: PrimitiveTypeTable::new(),
1200 def_map: RefCell::new(NodeMap()),
1201 freevars: NodeMap(),
1202 freevars_seen: NodeMap(),
1203 export_map: NodeMap(),
1204 trait_map: NodeMap(),
1205 used_imports: HashSet::new(),
1206 used_crates: HashSet::new(),
1207 external_exports: DefIdSet(),
1210 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1211 glob_map: HashMap::new(),
1220 fn arenas() -> ResolverArenas<'a> {
1222 modules: arena::TypedArena::new(),
1223 name_bindings: arena::TypedArena::new(),
1227 fn new_module(&self,
1228 parent_link: ParentLink<'a>,
1231 is_public: bool) -> Module<'a> {
1232 self.arenas.modules.alloc(ModuleS::new(parent_link, def, external, is_public))
1235 fn new_name_binding(&self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1236 self.arenas.name_bindings.alloc(name_binding)
1239 fn new_extern_crate_module(&self, parent_link: ParentLink<'a>, def: Def) -> Module<'a> {
1240 let mut module = ModuleS::new(parent_link, Some(def), false, true);
1241 module.is_extern_crate = true;
1242 self.arenas.modules.alloc(module)
1245 fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
1246 match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
1250 fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>) {
1251 // track extern crates for unused_extern_crate lint
1252 if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
1253 self.used_crates.insert(krate);
1256 let import_id = match binding.kind {
1257 NameBindingKind::Import { id, .. } => id,
1261 self.used_imports.insert((import_id, ns));
1263 if !self.make_glob_map {
1266 if self.glob_map.contains_key(&import_id) {
1267 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1271 let mut new_set = HashSet::new();
1272 new_set.insert(name);
1273 self.glob_map.insert(import_id, new_set);
1276 fn get_trait_name(&self, did: DefId) -> Name {
1277 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1278 self.ast_map.expect_item(node_id).name
1280 self.session.cstore.item_name(did)
1284 /// Resolves the given module path from the given root `module_`.
1285 fn resolve_module_path_from_root(&mut self,
1286 module_: Module<'a>,
1287 module_path: &[Name],
1291 -> ResolveResult<(Module<'a>, LastPrivate)> {
1292 fn search_parent_externals(needle: Name, module: Module) -> Option<Module> {
1293 match module.resolve_name(needle, TypeNS, false) {
1294 Success(binding) if binding.is_extern_crate() => Some(module),
1295 _ => match module.parent_link {
1296 ModuleParentLink(ref parent, _) => {
1297 search_parent_externals(needle, parent)
1304 let mut search_module = module_;
1305 let mut index = index;
1306 let module_path_len = module_path.len();
1307 let mut closest_private = lp;
1309 // Resolve the module part of the path. This does not involve looking
1310 // upward though scope chains; we simply resolve names directly in
1311 // modules as we go.
1312 while index < module_path_len {
1313 let name = module_path[index];
1314 match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1316 let segment_name = name.as_str();
1317 let module_name = module_to_string(search_module);
1318 let mut span = span;
1319 let msg = if "???" == &module_name {
1320 span.hi = span.lo + Pos::from_usize(segment_name.len());
1322 match search_parent_externals(name, &self.current_module) {
1324 let path_str = names_to_string(module_path);
1325 let target_mod_str = module_to_string(&module);
1326 let current_mod_str = module_to_string(&self.current_module);
1328 let prefix = if target_mod_str == current_mod_str {
1329 "self::".to_string()
1331 format!("{}::", target_mod_str)
1334 format!("Did you mean `{}{}`?", prefix, path_str)
1336 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1339 format!("Could not find `{}` in `{}`", segment_name, module_name)
1342 return Failed(Some((span, msg)));
1344 Failed(err) => return Failed(err),
1346 debug!("(resolving module path for import) module resolution is \
1349 return Indeterminate;
1351 Success(binding) => {
1352 // Check to see whether there are type bindings, and, if
1353 // so, whether there is a module within.
1354 if let Some(module_def) = binding.module() {
1355 search_module = module_def;
1357 // Keep track of the closest private module used
1358 // when resolving this import chain.
1359 if !binding.is_public() {
1360 if let Some(did) = search_module.def_id() {
1361 closest_private = LastMod(DependsOn(did));
1365 let msg = format!("Not a module `{}`", name);
1366 return Failed(Some((span, msg)));
1374 return Success((search_module, closest_private));
1377 /// Attempts to resolve the module part of an import directive or path
1378 /// rooted at the given module.
1380 /// On success, returns the resolved module, and the closest *private*
1381 /// module found to the destination when resolving this path.
1382 fn resolve_module_path(&mut self,
1383 module_: Module<'a>,
1384 module_path: &[Name],
1385 use_lexical_scope: UseLexicalScopeFlag,
1387 -> ResolveResult<(Module<'a>, LastPrivate)> {
1388 if module_path.len() == 0 {
1389 return Success((self.graph_root, LastMod(AllPublic))) // Use the crate root
1392 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1393 names_to_string(module_path),
1394 module_to_string(&module_));
1396 // Resolve the module prefix, if any.
1397 let module_prefix_result = self.resolve_module_prefix(module_, module_path);
1402 match module_prefix_result {
1404 let mpath = names_to_string(module_path);
1405 let mpath = &mpath[..];
1406 match mpath.rfind(':') {
1408 let msg = format!("Could not find `{}` in `{}`",
1409 // idx +- 1 to account for the
1410 // colons on either side
1413 return Failed(Some((span, msg)));
1416 return Failed(None);
1420 Failed(err) => return Failed(err),
1422 debug!("(resolving module path for import) indeterminate; bailing");
1423 return Indeterminate;
1425 Success(NoPrefixFound) => {
1426 // There was no prefix, so we're considering the first element
1427 // of the path. How we handle this depends on whether we were
1428 // instructed to use lexical scope or not.
1429 match use_lexical_scope {
1430 DontUseLexicalScope => {
1431 // This is a crate-relative path. We will start the
1432 // resolution process at index zero.
1433 search_module = self.graph_root;
1435 last_private = LastMod(AllPublic);
1437 UseLexicalScope => {
1438 // This is not a crate-relative path. We resolve the
1439 // first component of the path in the current lexical
1440 // scope and then proceed to resolve below that.
1441 match self.resolve_item_in_lexical_scope(module_,
1445 Failed(err) => return Failed(err),
1447 debug!("(resolving module path for import) indeterminate; bailing");
1448 return Indeterminate;
1450 Success(binding) => match binding.module() {
1451 Some(containing_module) => {
1452 search_module = containing_module;
1454 last_private = LastMod(AllPublic);
1456 None => return Failed(None),
1462 Success(PrefixFound(ref containing_module, index)) => {
1463 search_module = containing_module;
1464 start_index = index;
1465 last_private = LastMod(DependsOn(containing_module.def_id()
1470 self.resolve_module_path_from_root(search_module,
1477 /// Invariant: This must only be called during main resolution, not during
1478 /// import resolution.
1479 fn resolve_item_in_lexical_scope(&mut self,
1480 module_: Module<'a>,
1482 namespace: Namespace,
1484 -> ResolveResult<&'a NameBinding<'a>> {
1485 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1488 module_to_string(&module_));
1490 // Proceed up the scope chain looking for parent modules.
1491 let mut search_module = module_;
1493 // Resolve the name in the parent module.
1494 match self.resolve_name_in_module(search_module, name, namespace, true, record_used) {
1495 Failed(Some((span, msg))) => {
1496 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
1498 Failed(None) => (), // Continue up the search chain.
1500 // We couldn't see through the higher scope because of an
1501 // unresolved import higher up. Bail.
1503 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1504 return Indeterminate;
1506 Success(binding) => {
1507 // We found the module.
1508 debug!("(resolving item in lexical scope) found name in module, done");
1509 return Success(binding);
1513 // Go to the next parent.
1514 match search_module.parent_link {
1516 // No more parents. This module was unresolved.
1517 debug!("(resolving item in lexical scope) unresolved module: no parent module");
1518 return Failed(None);
1520 ModuleParentLink(parent_module_node, _) => {
1521 if search_module.is_normal() {
1522 // We stop the search here.
1523 debug!("(resolving item in lexical scope) unresolved module: not \
1524 searching through module parents");
1525 return Failed(None);
1527 search_module = parent_module_node;
1530 BlockParentLink(parent_module_node, _) => {
1531 search_module = parent_module_node;
1537 /// Returns the nearest normal module parent of the given module.
1538 fn get_nearest_normal_module_parent(&mut self, module_: Module<'a>) -> Option<Module<'a>> {
1539 let mut module_ = module_;
1541 match module_.parent_link {
1542 NoParentLink => return None,
1543 ModuleParentLink(new_module, _) |
1544 BlockParentLink(new_module, _) => {
1545 let new_module = new_module;
1546 if new_module.is_normal() {
1547 return Some(new_module);
1549 module_ = new_module;
1555 /// Returns the nearest normal module parent of the given module, or the
1556 /// module itself if it is a normal module.
1557 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Module<'a>) -> Module<'a> {
1558 if module_.is_normal() {
1561 match self.get_nearest_normal_module_parent(module_) {
1563 Some(new_module) => new_module,
1567 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1568 /// (b) some chain of `super::`.
1569 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1570 fn resolve_module_prefix(&mut self,
1571 module_: Module<'a>,
1572 module_path: &[Name])
1573 -> ResolveResult<ModulePrefixResult<'a>> {
1574 // Start at the current module if we see `self` or `super`, or at the
1575 // top of the crate otherwise.
1576 let mut i = match &*module_path[0].as_str() {
1579 _ => return Success(NoPrefixFound),
1581 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1583 // Now loop through all the `super`s we find.
1584 while i < module_path.len() && "super" == module_path[i].as_str() {
1585 debug!("(resolving module prefix) resolving `super` at {}",
1586 module_to_string(&containing_module));
1587 match self.get_nearest_normal_module_parent(containing_module) {
1588 None => return Failed(None),
1589 Some(new_module) => {
1590 containing_module = new_module;
1596 debug!("(resolving module prefix) finished resolving prefix at {}",
1597 module_to_string(&containing_module));
1599 return Success(PrefixFound(containing_module, i));
1602 /// Attempts to resolve the supplied name in the given module for the
1603 /// given namespace. If successful, returns the binding corresponding to
1605 fn resolve_name_in_module(&mut self,
1608 namespace: Namespace,
1609 allow_private_imports: bool,
1611 -> ResolveResult<&'a NameBinding<'a>> {
1612 debug!("(resolving name in module) resolving `{}` in `{}`", name, module_to_string(module));
1614 build_reduced_graph::populate_module_if_necessary(self, module);
1615 module.resolve_name(name, namespace, allow_private_imports).and_then(|binding| {
1617 self.record_use(name, namespace, binding);
1623 fn report_unresolved_imports(&mut self, module_: Module<'a>) {
1624 for import in module_.unresolved_imports.borrow().iter() {
1625 resolve_error(self, import.span, ResolutionError::UnresolvedImport(None));
1629 // Descend into children and anonymous children.
1630 for (_, module_) in module_.module_children.borrow().iter() {
1631 self.report_unresolved_imports(module_);
1637 // We maintain a list of value ribs and type ribs.
1639 // Simultaneously, we keep track of the current position in the module
1640 // graph in the `current_module` pointer. When we go to resolve a name in
1641 // the value or type namespaces, we first look through all the ribs and
1642 // then query the module graph. When we resolve a name in the module
1643 // namespace, we can skip all the ribs (since nested modules are not
1644 // allowed within blocks in Rust) and jump straight to the current module
1647 // Named implementations are handled separately. When we find a method
1648 // call, we consult the module node to find all of the implementations in
1649 // scope. This information is lazily cached in the module node. We then
1650 // generate a fake "implementation scope" containing all the
1651 // implementations thus found, for compatibility with old resolve pass.
1653 fn with_scope<F>(&mut self, id: NodeId, f: F)
1654 where F: FnOnce(&mut Resolver)
1656 let orig_module = self.current_module;
1658 // Move down in the graph.
1659 if let Some(module) = orig_module.module_children.borrow().get(&id) {
1660 self.current_module = module;
1665 self.current_module = orig_module;
1668 /// Searches the current set of local scopes for labels.
1669 /// Stops after meeting a closure.
1670 fn search_label(&self, name: Name) -> Option<DefLike> {
1671 for rib in self.label_ribs.iter().rev() {
1677 // Do not resolve labels across function boundary
1681 let result = rib.bindings.get(&name).cloned();
1682 if result.is_some() {
1689 fn resolve_crate(&mut self, krate: &hir::Crate) {
1690 debug!("(resolving crate) starting");
1692 intravisit::walk_crate(self, krate);
1695 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1696 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1697 span_err!(self.session,
1700 "user-defined types or type parameters cannot shadow the primitive types");
1704 fn resolve_item(&mut self, item: &Item) {
1705 let name = item.name;
1707 debug!("(resolving item) resolving {}", name);
1710 ItemEnum(_, ref generics) |
1711 ItemTy(_, ref generics) |
1712 ItemStruct(_, ref generics) => {
1713 self.check_if_primitive_type_name(name, item.span);
1715 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1716 |this| intravisit::walk_item(this, item));
1718 ItemFn(_, _, _, _, ref generics, _) => {
1719 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1720 |this| intravisit::walk_item(this, item));
1723 ItemDefaultImpl(_, ref trait_ref) => {
1724 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1726 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1727 self.resolve_implementation(generics,
1734 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1735 self.check_if_primitive_type_name(name, item.span);
1737 // Create a new rib for the trait-wide type parameters.
1738 self.with_type_parameter_rib(HasTypeParameters(generics,
1742 let local_def_id = this.ast_map.local_def_id(item.id);
1743 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1744 this.visit_generics(generics);
1745 walk_list!(this, visit_ty_param_bound, bounds);
1747 for trait_item in trait_items {
1748 match trait_item.node {
1749 hir::ConstTraitItem(_, ref default) => {
1750 // Only impose the restrictions of
1751 // ConstRibKind if there's an actual constant
1752 // expression in a provided default.
1753 if default.is_some() {
1754 this.with_constant_rib(|this| {
1755 intravisit::walk_trait_item(this, trait_item)
1758 intravisit::walk_trait_item(this, trait_item)
1761 hir::MethodTraitItem(ref sig, _) => {
1762 let type_parameters =
1763 HasTypeParameters(&sig.generics,
1766 this.with_type_parameter_rib(type_parameters, |this| {
1767 intravisit::walk_trait_item(this, trait_item)
1770 hir::TypeTraitItem(..) => {
1771 this.check_if_primitive_type_name(trait_item.name,
1773 this.with_type_parameter_rib(NoTypeParameters, |this| {
1774 intravisit::walk_trait_item(this, trait_item)
1783 ItemMod(_) | ItemForeignMod(_) => {
1784 self.with_scope(item.id, |this| {
1785 intravisit::walk_item(this, item);
1789 ItemConst(..) | ItemStatic(..) => {
1790 self.with_constant_rib(|this| {
1791 intravisit::walk_item(this, item);
1795 ItemUse(ref view_path) => {
1796 // check for imports shadowing primitive types
1797 let check_rename = |this: &Self, id, name| {
1798 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
1799 Some(Def::Enum(..)) | Some(Def::TyAlias(..)) | Some(Def::Struct(..)) |
1800 Some(Def::Trait(..)) | None => {
1801 this.check_if_primitive_type_name(name, item.span);
1807 match view_path.node {
1808 hir::ViewPathSimple(name, _) => {
1809 check_rename(self, item.id, name);
1811 hir::ViewPathList(ref prefix, ref items) => {
1813 if let Some(name) = item.node.rename() {
1814 check_rename(self, item.node.id(), name);
1818 // Resolve prefix of an import with empty braces (issue #28388)
1819 if items.is_empty() && !prefix.segments.is_empty() {
1820 match self.resolve_crate_relative_path(prefix.span,
1824 self.record_def(item.id, PathResolution::new(def, lp, 0)),
1828 ResolutionError::FailedToResolve(
1829 &path_names_to_string(prefix, 0)));
1830 self.record_def(item.id, err_path_resolution());
1839 ItemExternCrate(_) => {
1840 // do nothing, these are just around to be encoded
1845 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
1846 where F: FnOnce(&mut Resolver)
1848 match type_parameters {
1849 HasTypeParameters(generics, space, rib_kind) => {
1850 let mut function_type_rib = Rib::new(rib_kind);
1851 let mut seen_bindings = HashSet::new();
1852 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1853 let name = type_parameter.name;
1854 debug!("with_type_parameter_rib: {}", type_parameter.id);
1856 if seen_bindings.contains(&name) {
1858 type_parameter.span,
1859 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1861 seen_bindings.insert(name);
1863 // plain insert (no renaming)
1864 function_type_rib.bindings
1866 DlDef(Def::TyParam(space,
1869 .local_def_id(type_parameter.id),
1872 self.type_ribs.push(function_type_rib);
1875 NoTypeParameters => {
1882 match type_parameters {
1883 HasTypeParameters(..) => {
1885 self.type_ribs.pop();
1888 NoTypeParameters => {}
1892 fn with_label_rib<F>(&mut self, f: F)
1893 where F: FnOnce(&mut Resolver)
1895 self.label_ribs.push(Rib::new(NormalRibKind));
1898 self.label_ribs.pop();
1902 fn with_constant_rib<F>(&mut self, f: F)
1903 where F: FnOnce(&mut Resolver)
1905 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1906 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1909 self.type_ribs.pop();
1910 self.value_ribs.pop();
1914 fn resolve_function(&mut self, rib_kind: RibKind<'a>, declaration: &FnDecl, block: &Block) {
1915 // Create a value rib for the function.
1916 self.value_ribs.push(Rib::new(rib_kind));
1918 // Create a label rib for the function.
1919 self.label_ribs.push(Rib::new(rib_kind));
1921 // Add each argument to the rib.
1922 let mut bindings_list = HashMap::new();
1923 for argument in &declaration.inputs {
1924 self.resolve_pattern(&argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
1926 self.visit_ty(&argument.ty);
1928 debug!("(resolving function) recorded argument");
1930 intravisit::walk_fn_ret_ty(self, &declaration.output);
1932 // Resolve the function body.
1933 self.visit_block(block);
1935 debug!("(resolving function) leaving function");
1938 self.label_ribs.pop();
1939 self.value_ribs.pop();
1943 fn resolve_trait_reference(&mut self,
1947 -> Result<PathResolution, ()> {
1948 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
1949 if let Def::Trait(_) = path_res.base_def {
1950 debug!("(resolving trait) found trait def: {:?}", path_res);
1954 resolve_struct_error(self,
1956 ResolutionError::IsNotATrait(&path_names_to_string(trait_path,
1959 // If it's a typedef, give a note
1960 if let Def::TyAlias(..) = path_res.base_def {
1961 err.span_note(trait_path.span,
1962 "`type` aliases cannot be used for traits");
1969 // find possible candidates
1970 let trait_name = trait_path.segments.last().unwrap().identifier.name;
1972 self.lookup_candidates(
1976 Def::Trait(_) => true,
1981 // create error object
1982 let name = &path_names_to_string(trait_path, path_depth);
1984 ResolutionError::UndeclaredTraitName(
1989 resolve_error(self, trait_path.span, error);
1994 fn resolve_generics(&mut self, generics: &Generics) {
1995 for type_parameter in generics.ty_params.iter() {
1996 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
1998 for predicate in &generics.where_clause.predicates {
2000 &hir::WherePredicate::BoundPredicate(_) |
2001 &hir::WherePredicate::RegionPredicate(_) => {}
2002 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2003 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2004 if let Some(PathResolution { base_def: Def::TyParam(..), .. }) = path_res {
2005 self.record_def(eq_pred.id, path_res.unwrap());
2009 ResolutionError::UndeclaredAssociatedType);
2010 self.record_def(eq_pred.id, err_path_resolution());
2015 intravisit::walk_generics(self, generics);
2018 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2019 where F: FnOnce(&mut Resolver) -> T
2021 // Handle nested impls (inside fn bodies)
2022 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2023 let result = f(self);
2024 self.current_self_type = previous_value;
2028 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2029 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2031 let mut new_val = None;
2032 let mut new_id = None;
2033 if let Some(trait_ref) = opt_trait_ref {
2034 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2037 assert!(path_res.depth == 0);
2038 self.record_def(trait_ref.ref_id, path_res);
2039 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2040 new_id = Some(path_res.base_def.def_id());
2042 self.record_def(trait_ref.ref_id, err_path_resolution());
2044 intravisit::walk_trait_ref(self, trait_ref);
2046 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2047 let result = f(self, new_id);
2048 self.current_trait_ref = original_trait_ref;
2052 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2053 where F: FnOnce(&mut Resolver)
2055 let mut self_type_rib = Rib::new(NormalRibKind);
2057 // plain insert (no renaming, types are not currently hygienic....)
2058 let name = special_names::type_self;
2059 self_type_rib.bindings.insert(name, DlDef(self_def));
2060 self.type_ribs.push(self_type_rib);
2063 self.type_ribs.pop();
2067 fn resolve_implementation(&mut self,
2068 generics: &Generics,
2069 opt_trait_reference: &Option<TraitRef>,
2072 impl_items: &[ImplItem]) {
2073 // If applicable, create a rib for the type parameters.
2074 self.with_type_parameter_rib(HasTypeParameters(generics,
2078 // Resolve the type parameters.
2079 this.visit_generics(generics);
2081 // Resolve the trait reference, if necessary.
2082 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2083 // Resolve the self type.
2084 this.visit_ty(self_type);
2086 this.with_self_rib(Def::SelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2087 this.with_current_self_type(self_type, |this| {
2088 for impl_item in impl_items {
2089 match impl_item.node {
2090 hir::ImplItemKind::Const(..) => {
2091 // If this is a trait impl, ensure the const
2093 this.check_trait_item(impl_item.name,
2095 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2096 this.with_constant_rib(|this| {
2097 intravisit::walk_impl_item(this, impl_item);
2100 hir::ImplItemKind::Method(ref sig, _) => {
2101 // If this is a trait impl, ensure the method
2103 this.check_trait_item(impl_item.name,
2105 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2107 // We also need a new scope for the method-
2108 // specific type parameters.
2109 let type_parameters =
2110 HasTypeParameters(&sig.generics,
2113 this.with_type_parameter_rib(type_parameters, |this| {
2114 intravisit::walk_impl_item(this, impl_item);
2117 hir::ImplItemKind::Type(ref ty) => {
2118 // If this is a trait impl, ensure the type
2120 this.check_trait_item(impl_item.name,
2122 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2134 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2135 where F: FnOnce(Name, &str) -> ResolutionError
2137 // If there is a TraitRef in scope for an impl, then the method must be in the
2139 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2140 if !self.trait_item_map.contains_key(&(name, did)) {
2141 let path_str = path_names_to_string(&trait_ref.path, 0);
2142 resolve_error(self, span, err(name, &path_str));
2147 fn resolve_local(&mut self, local: &Local) {
2148 // Resolve the type.
2149 walk_list!(self, visit_ty, &local.ty);
2151 // Resolve the initializer.
2152 walk_list!(self, visit_expr, &local.init);
2154 // Resolve the pattern.
2155 self.resolve_pattern(&local.pat, LocalIrrefutableMode, &mut HashMap::new());
2158 // build a map from pattern identifiers to binding-info's.
2159 // this is done hygienically. This could arise for a macro
2160 // that expands into an or-pattern where one 'x' was from the
2161 // user and one 'x' came from the macro.
2162 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2163 let mut result = HashMap::new();
2164 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2165 let name = path1.node;
2169 binding_mode: binding_mode,
2175 // check that all of the arms in an or-pattern have exactly the
2176 // same set of bindings, with the same binding modes for each.
2177 fn check_consistent_bindings(&mut self, arm: &Arm) {
2178 if arm.pats.is_empty() {
2181 let map_0 = self.binding_mode_map(&arm.pats[0]);
2182 for (i, p) in arm.pats.iter().enumerate() {
2183 let map_i = self.binding_mode_map(&p);
2185 for (&key, &binding_0) in &map_0 {
2186 match map_i.get(&key) {
2190 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2192 Some(binding_i) => {
2193 if binding_0.binding_mode != binding_i.binding_mode {
2196 ResolutionError::VariableBoundWithDifferentMode(key,
2203 for (&key, &binding) in &map_i {
2204 if !map_0.contains_key(&key) {
2207 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2213 fn resolve_arm(&mut self, arm: &Arm) {
2214 self.value_ribs.push(Rib::new(NormalRibKind));
2216 let mut bindings_list = HashMap::new();
2217 for pattern in &arm.pats {
2218 self.resolve_pattern(&pattern, RefutableMode, &mut bindings_list);
2221 // This has to happen *after* we determine which
2222 // pat_idents are variants
2223 self.check_consistent_bindings(arm);
2225 walk_list!(self, visit_expr, &arm.guard);
2226 self.visit_expr(&arm.body);
2229 self.value_ribs.pop();
2233 fn resolve_block(&mut self, block: &Block) {
2234 debug!("(resolving block) entering block");
2235 // Move down in the graph, if there's an anonymous module rooted here.
2236 let orig_module = self.current_module;
2237 let anonymous_module =
2238 orig_module.module_children.borrow().get(&block.id).map(|module| *module);
2240 if let Some(anonymous_module) = anonymous_module {
2241 debug!("(resolving block) found anonymous module, moving down");
2242 self.value_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2243 self.type_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2244 self.current_module = anonymous_module;
2246 self.value_ribs.push(Rib::new(NormalRibKind));
2249 // Descend into the block.
2250 intravisit::walk_block(self, block);
2254 self.current_module = orig_module;
2255 self.value_ribs.pop();
2256 if let Some(_) = anonymous_module {
2257 self.type_ribs.pop();
2260 debug!("(resolving block) leaving block");
2263 fn resolve_type(&mut self, ty: &Ty) {
2265 TyPath(ref maybe_qself, ref path) => {
2266 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2267 maybe_qself.as_ref(),
2271 // `<T>::a::b::c` is resolved by typeck alone.
2272 TypecheckRequired => {
2273 // Resolve embedded types.
2274 intravisit::walk_ty(self, ty);
2277 ResolveAttempt(resolution) => resolution,
2280 // This is a path in the type namespace. Walk through scopes
2284 // Write the result into the def map.
2285 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2286 path_names_to_string(path, 0),
2289 self.record_def(ty.id, def);
2292 self.record_def(ty.id, err_path_resolution());
2294 // Keep reporting some errors even if they're ignored above.
2295 self.resolve_path(ty.id, path, 0, TypeNS, true);
2297 let kind = if maybe_qself.is_some() {
2303 let self_type_name = special_idents::type_self.name;
2304 let is_invalid_self_type_name = path.segments.len() > 0 &&
2305 maybe_qself.is_none() &&
2306 path.segments[0].identifier.name ==
2308 if is_invalid_self_type_name {
2311 ResolutionError::SelfUsedOutsideImplOrTrait);
2313 let segment = path.segments.last();
2314 let segment = segment.expect("missing name in path");
2315 let type_name = segment.identifier.name;
2318 self.lookup_candidates(
2325 Def::TyAlias(_) => true,
2330 // create error object
2331 let name = &path_names_to_string(path, 0);
2333 ResolutionError::UseOfUndeclared(
2339 resolve_error(self, ty.span, error);
2346 // Resolve embedded types.
2347 intravisit::walk_ty(self, ty);
2350 fn resolve_pattern(&mut self,
2352 mode: PatternBindingMode,
2353 // Maps idents to the node ID for the (outermost)
2354 // pattern that binds them
2355 bindings_list: &mut HashMap<Name, NodeId>) {
2356 let pat_id = pattern.id;
2357 walk_pat(pattern, |pattern| {
2358 match pattern.node {
2359 PatKind::Ident(binding_mode, ref path1, ref at_rhs) => {
2360 // The meaning of PatKind::Ident with no type parameters
2361 // depends on whether an enum variant or unit-like struct
2362 // with that name is in scope. The probing lookup has to
2363 // be careful not to emit spurious errors. Only matching
2364 // patterns (match) can match nullary variants or
2365 // unit-like structs. For binding patterns (let
2366 // and the LHS of @-patterns), matching such a value is
2367 // simply disallowed (since it's rarely what you want).
2368 let const_ok = mode == RefutableMode && at_rhs.is_none();
2370 let ident = path1.node;
2371 let renamed = ident.name;
2373 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2375 FoundStructOrEnumVariant(def, lp) if const_ok => {
2376 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2379 self.enforce_default_binding_mode(pattern,
2382 self.record_def(pattern.id,
2389 FoundStructOrEnumVariant(..) => {
2393 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2396 self.record_def(pattern.id, err_path_resolution());
2398 FoundConst(def, lp, _) if const_ok => {
2399 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2401 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2402 self.record_def(pattern.id,
2409 FoundConst(def, _, name) => {
2413 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2416 self.record_def(pattern.id, err_path_resolution());
2418 BareIdentifierPatternUnresolved => {
2419 debug!("(resolving pattern) binding `{}`", renamed);
2421 let def_id = self.ast_map.local_def_id(pattern.id);
2422 let def = Def::Local(def_id, pattern.id);
2424 // Record the definition so that later passes
2425 // will be able to distinguish variants from
2426 // locals in patterns.
2428 self.record_def(pattern.id,
2431 last_private: LastMod(AllPublic),
2435 // Add the binding to the local ribs, if it
2436 // doesn't already exist in the bindings list. (We
2437 // must not add it if it's in the bindings list
2438 // because that breaks the assumptions later
2439 // passes make about or-patterns.)
2440 if !bindings_list.contains_key(&renamed) {
2441 let this = &mut *self;
2442 let last_rib = this.value_ribs.last_mut().unwrap();
2443 last_rib.bindings.insert(renamed, DlDef(def));
2444 bindings_list.insert(renamed, pat_id);
2445 } else if mode == ArgumentIrrefutableMode &&
2446 bindings_list.contains_key(&renamed) {
2447 // Forbid duplicate bindings in the same
2452 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2453 &ident.name.as_str())
2455 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2456 // Then this is a duplicate variable in the
2457 // same disjunction, which is an error.
2461 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2462 &ident.name.as_str())
2465 // Else, not bound in the same pattern: do
2471 PatKind::TupleStruct(ref path, _) | PatKind::Path(ref path) => {
2472 // This must be an enum variant, struct or const.
2473 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2478 // The below shouldn't happen because all
2479 // qualified paths should be in PatKind::QPath.
2480 TypecheckRequired =>
2481 self.session.span_bug(path.span,
2482 "resolve_possibly_assoc_item claimed that a path \
2483 in PatKind::Path or PatKind::TupleStruct \
2484 requires typecheck to resolve, but qualified \
2485 paths should be PatKind::QPath"),
2486 ResolveAttempt(resolution) => resolution,
2488 if let Some(path_res) = resolution {
2489 match path_res.base_def {
2490 Def::Struct(..) if path_res.depth == 0 => {
2491 self.record_def(pattern.id, path_res);
2493 Def::Variant(..) | Def::Const(..) => {
2494 self.record_def(pattern.id, path_res);
2496 Def::Static(..) => {
2497 resolve_error(&self,
2499 ResolutionError::StaticVariableReference);
2500 self.record_def(pattern.id, err_path_resolution());
2503 // If anything ends up here entirely resolved,
2504 // it's an error. If anything ends up here
2505 // partially resolved, that's OK, because it may
2506 // be a `T::CONST` that typeck will resolve.
2507 if path_res.depth == 0 {
2511 ResolutionError::NotAnEnumVariantStructOrConst(
2519 self.record_def(pattern.id, err_path_resolution());
2521 let const_name = path.segments
2526 let traits = self.get_traits_containing_item(const_name);
2527 self.trait_map.insert(pattern.id, traits);
2528 self.record_def(pattern.id, path_res);
2536 ResolutionError::UnresolvedEnumVariantStructOrConst(
2537 &path.segments.last().unwrap().identifier.name.as_str())
2539 self.record_def(pattern.id, err_path_resolution());
2541 intravisit::walk_path(self, path);
2544 PatKind::QPath(ref qself, ref path) => {
2545 // Associated constants only.
2546 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2551 TypecheckRequired => {
2552 // All `<T>::CONST` should end up here, and will
2553 // require use of the trait map to resolve
2554 // during typechecking.
2555 let const_name = path.segments
2560 let traits = self.get_traits_containing_item(const_name);
2561 self.trait_map.insert(pattern.id, traits);
2562 intravisit::walk_pat(self, pattern);
2565 ResolveAttempt(resolution) => resolution,
2567 if let Some(path_res) = resolution {
2568 match path_res.base_def {
2569 // All `<T as Trait>::CONST` should end up here, and
2570 // have the trait already selected.
2571 Def::AssociatedConst(..) => {
2572 self.record_def(pattern.id, path_res);
2578 ResolutionError::NotAnAssociatedConst(
2579 &path.segments.last().unwrap().identifier.name.as_str()
2582 self.record_def(pattern.id, err_path_resolution());
2588 ResolutionError::UnresolvedAssociatedConst(&path.segments
2594 self.record_def(pattern.id, err_path_resolution());
2596 intravisit::walk_pat(self, pattern);
2599 PatKind::Struct(ref path, _, _) => {
2600 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2601 Some(definition) => {
2602 self.record_def(pattern.id, definition);
2605 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2609 ResolutionError::DoesNotNameAStruct(
2610 &path_names_to_string(path, 0))
2612 self.record_def(pattern.id, err_path_resolution());
2615 intravisit::walk_path(self, path);
2618 PatKind::Lit(_) | PatKind::Range(..) => {
2619 intravisit::walk_pat(self, pattern);
2630 fn resolve_bare_identifier_pattern(&mut self,
2633 -> BareIdentifierPatternResolution {
2634 let module = self.current_module;
2635 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2636 Success(binding) => {
2637 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2640 match binding.def() {
2642 panic!("resolved name in the value namespace to a set of name bindings \
2645 // For the two success cases, this lookup can be
2646 // considered as not having a private component because
2647 // the lookup happened only within the current module.
2648 Some(def @ Def::Variant(..)) | Some(def @ Def::Struct(..)) => {
2649 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2651 Some(def @ Def::Const(..)) | Some(def @ Def::AssociatedConst(..)) => {
2652 return FoundConst(def, LastMod(AllPublic), name);
2654 Some(Def::Static(..)) => {
2655 resolve_error(self, span, ResolutionError::StaticVariableReference);
2656 return BareIdentifierPatternUnresolved;
2658 _ => return BareIdentifierPatternUnresolved
2662 Indeterminate => return BareIdentifierPatternUnresolved,
2665 Some((span, msg)) => {
2666 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2671 debug!("(resolve bare identifier pattern) failed to find {}", name);
2672 return BareIdentifierPatternUnresolved;
2677 /// Handles paths that may refer to associated items
2678 fn resolve_possibly_assoc_item(&mut self,
2680 maybe_qself: Option<&hir::QSelf>,
2682 namespace: Namespace,
2684 -> AssocItemResolveResult {
2685 let max_assoc_types;
2689 if qself.position == 0 {
2690 return TypecheckRequired;
2692 max_assoc_types = path.segments.len() - qself.position;
2693 // Make sure the trait is valid.
2694 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2697 max_assoc_types = path.segments.len();
2701 let mut resolution = self.with_no_errors(|this| {
2702 this.resolve_path(id, path, 0, namespace, check_ribs)
2704 for depth in 1..max_assoc_types {
2705 if resolution.is_some() {
2708 self.with_no_errors(|this| {
2709 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2712 if let Some(Def::Mod(_)) = resolution.map(|r| r.base_def) {
2713 // A module is not a valid type or value.
2716 ResolveAttempt(resolution)
2719 /// If `check_ribs` is true, checks the local definitions first; i.e.
2720 /// doesn't skip straight to the containing module.
2721 /// Skips `path_depth` trailing segments, which is also reflected in the
2722 /// returned value. See `middle::def::PathResolution` for more info.
2723 pub fn resolve_path(&mut self,
2727 namespace: Namespace,
2729 -> Option<PathResolution> {
2730 let span = path.span;
2731 let segments = &path.segments[..path.segments.len() - path_depth];
2733 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2736 let def = self.resolve_crate_relative_path(span, segments, namespace);
2737 return def.map(mk_res);
2740 // Try to find a path to an item in a module.
2741 let last_ident = segments.last().unwrap().identifier;
2742 if segments.len() <= 1 {
2743 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2744 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2746 PathResolution::new(def, LastMod(AllPublic), path_depth)
2750 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2751 let def = self.resolve_module_relative_path(span, segments, namespace);
2752 match (def, unqualified_def) {
2753 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2755 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2758 "unnecessary qualification".to_string());
2766 // Resolve a single identifier
2767 fn resolve_identifier(&mut self,
2768 identifier: hir::Ident,
2769 namespace: Namespace,
2772 -> Option<LocalDef> {
2773 if identifier.name == special_idents::invalid.name {
2774 return Some(LocalDef::from_def(Def::Err));
2777 // First, check to see whether the name is a primitive type.
2778 if namespace == TypeNS {
2779 if let Some(&prim_ty) = self.primitive_type_table
2781 .get(&identifier.unhygienic_name) {
2782 return Some(LocalDef::from_def(Def::PrimTy(prim_ty)));
2787 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2793 let module = self.current_module;
2794 let name = identifier.unhygienic_name;
2795 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
2796 Success(binding) => binding.def().map(LocalDef::from_def),
2797 Failed(Some((span, msg))) => {
2798 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2805 // Resolve a local definition, potentially adjusting for closures.
2806 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2807 let ribs = match local_def.ribs {
2808 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2809 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2812 let mut def = local_def.def;
2815 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2817 Def::Local(_, node_id) => {
2820 NormalRibKind | AnonymousModuleRibKind(..) => {
2821 // Nothing to do. Continue.
2823 ClosureRibKind(function_id) => {
2825 let node_def_id = self.ast_map.local_def_id(node_id);
2827 let seen = self.freevars_seen
2829 .or_insert_with(|| NodeMap());
2830 if let Some(&index) = seen.get(&node_id) {
2831 def = Def::Upvar(node_def_id, node_id, index, function_id);
2834 let vec = self.freevars
2836 .or_insert_with(|| vec![]);
2837 let depth = vec.len();
2843 def = Def::Upvar(node_def_id, node_id, depth, function_id);
2844 seen.insert(node_id, depth);
2846 ItemRibKind | MethodRibKind => {
2847 // This was an attempt to access an upvar inside a
2848 // named function item. This is not allowed, so we
2852 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2855 ConstantItemRibKind => {
2856 // Still doesn't deal with upvars
2859 ResolutionError::AttemptToUseNonConstantValueInConstant);
2865 Def::TyParam(..) | Def::SelfTy(..) => {
2868 NormalRibKind | MethodRibKind | ClosureRibKind(..) |
2869 AnonymousModuleRibKind(..) => {
2870 // Nothing to do. Continue.
2873 // This was an attempt to use a type parameter outside
2878 ResolutionError::TypeParametersFromOuterFunction);
2881 ConstantItemRibKind => {
2883 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2894 // resolve a "module-relative" path, e.g. a::b::c
2895 fn resolve_module_relative_path(&mut self,
2897 segments: &[hir::PathSegment],
2898 namespace: Namespace)
2899 -> Option<(Def, LastPrivate)> {
2900 let module_path = segments.split_last()
2904 .map(|ps| ps.identifier.name)
2905 .collect::<Vec<_>>();
2907 let containing_module;
2909 let current_module = self.current_module;
2910 match self.resolve_module_path(current_module, &module_path, UseLexicalScope, span) {
2912 let (span, msg) = match err {
2913 Some((span, msg)) => (span, msg),
2915 let msg = format!("Use of undeclared type or module `{}`",
2916 names_to_string(&module_path));
2921 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2924 Indeterminate => return None,
2925 Success((resulting_module, resulting_last_private)) => {
2926 containing_module = resulting_module;
2927 last_private = resulting_last_private;
2931 let name = segments.last().unwrap().identifier.name;
2932 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2933 let def = match result {
2934 Success(binding) => {
2935 let (def, lp) = binding.def_and_lp();
2936 (def, last_private.or(lp))
2943 /// Invariant: This must be called only during main resolution, not during
2944 /// import resolution.
2945 fn resolve_crate_relative_path(&mut self,
2947 segments: &[hir::PathSegment],
2948 namespace: Namespace)
2949 -> Option<(Def, LastPrivate)> {
2950 let module_path = segments.split_last()
2954 .map(|ps| ps.identifier.name)
2955 .collect::<Vec<_>>();
2957 let root_module = self.graph_root;
2959 let containing_module;
2961 match self.resolve_module_path_from_root(root_module,
2965 LastMod(AllPublic)) {
2967 let (span, msg) = match err {
2968 Some((span, msg)) => (span, msg),
2970 let msg = format!("Use of undeclared module `::{}`",
2971 names_to_string(&module_path));
2976 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2980 Indeterminate => return None,
2982 Success((resulting_module, resulting_last_private)) => {
2983 containing_module = resulting_module;
2984 last_private = resulting_last_private;
2988 let name = segments.last().unwrap().identifier.name;
2989 match self.resolve_name_in_module(containing_module, name, namespace, false, true) {
2990 Success(binding) => {
2991 let (def, lp) = binding.def_and_lp();
2992 Some((def, last_private.or(lp)))
2998 fn resolve_identifier_in_local_ribs(&mut self,
3000 namespace: Namespace)
3001 -> Option<LocalDef> {
3002 // Check the local set of ribs.
3003 let name = match namespace { ValueNS => ident.name, TypeNS => ident.unhygienic_name };
3005 for i in (0 .. self.get_ribs(namespace).len()).rev() {
3006 if let Some(def_like) = self.get_ribs(namespace)[i].bindings.get(&name).cloned() {
3009 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3013 return Some(LocalDef {
3014 ribs: Some((namespace, i)),
3019 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3027 if let AnonymousModuleRibKind(module) = self.get_ribs(namespace)[i].kind {
3028 if let Success(binding) = self.resolve_name_in_module(module,
3029 ident.unhygienic_name,
3033 if let Some(def) = binding.def() {
3034 return Some(LocalDef::from_def(def));
3043 fn with_no_errors<T, F>(&mut self, f: F) -> T
3044 where F: FnOnce(&mut Resolver) -> T
3046 self.emit_errors = false;
3048 self.emit_errors = true;
3052 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3053 fn extract_path_and_node_id(t: &Ty,
3054 allow: FallbackChecks)
3055 -> Option<(Path, NodeId, FallbackChecks)> {
3057 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3058 TyPtr(ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, OnlyTraitAndStatics),
3059 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, allow),
3060 // This doesn't handle the remaining `Ty` variants as they are not
3061 // that commonly the self_type, it might be interesting to provide
3062 // support for those in future.
3067 fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
3069 name_path: &[ast::Name])
3070 -> Option<Module<'a>> {
3071 let root = this.current_module;
3072 let last_name = name_path.last().unwrap();
3074 if name_path.len() == 1 {
3075 match this.primitive_type_table.primitive_types.get(last_name) {
3077 None => this.current_module.resolve_name(*last_name, TypeNS, true).success()
3078 .and_then(NameBinding::module)
3081 match this.resolve_module_path(root, &name_path, UseLexicalScope, span) {
3082 Success((module, _)) => Some(module),
3088 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3089 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3090 let sig = match this.ast_map.get(node_id) {
3091 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3092 hir::MethodTraitItem(ref sig, _) => sig,
3095 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3096 hir::ImplItemKind::Method(ref sig, _) => sig,
3101 sig.explicit_self.node == hir::SelfStatic
3103 this.session.cstore.is_static_method(did)
3107 let (path, node_id, allowed) = match self.current_self_type {
3108 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3110 None => return NoSuggestion,
3112 None => return NoSuggestion,
3115 if allowed == Everything {
3116 // Look for a field with the same name in the current self_type.
3117 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3118 Some(Def::Enum(did)) |
3119 Some(Def::TyAlias(did)) |
3120 Some(Def::Struct(did)) |
3121 Some(Def::Variant(_, did)) => match self.structs.get(&did) {
3124 if fields.iter().any(|&field_name| name == field_name) {
3129 _ => {} // Self type didn't resolve properly
3133 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3135 // Look for a method in the current self type's impl module.
3136 if let Some(module) = get_module(self, path.span, &name_path) {
3137 if let Success(binding) = module.resolve_name(name, ValueNS, true) {
3138 if let Some(Def::Method(did)) = binding.def() {
3139 if is_static_method(self, did) {
3140 return StaticMethod(path_names_to_string(&path, 0));
3142 if self.current_trait_ref.is_some() {
3144 } else if allowed == Everything {
3151 // Look for a method in the current trait.
3152 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3153 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3154 if is_static_method(self, did) {
3155 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3165 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3166 if let Some(macro_name) = self.session.available_macros
3167 .borrow().iter().find(|n| n.as_str() == name) {
3168 return SuggestionType::Macro(format!("{}!", macro_name));
3171 let names = self.value_ribs
3174 .flat_map(|rib| rib.bindings.keys());
3176 if let Some(found) = find_best_match_for_name(names, name, None) {
3178 return SuggestionType::Function(found);
3180 } SuggestionType::NotFound
3183 fn resolve_expr(&mut self, expr: &Expr) {
3184 // First, record candidate traits for this expression if it could
3185 // result in the invocation of a method call.
3187 self.record_candidate_traits_for_expr_if_necessary(expr);
3189 // Next, resolve the node.
3191 ExprPath(ref maybe_qself, ref path) => {
3192 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3193 maybe_qself.as_ref(),
3197 // `<T>::a::b::c` is resolved by typeck alone.
3198 TypecheckRequired => {
3199 let method_name = path.segments.last().unwrap().identifier.name;
3200 let traits = self.get_traits_containing_item(method_name);
3201 self.trait_map.insert(expr.id, traits);
3202 intravisit::walk_expr(self, expr);
3205 ResolveAttempt(resolution) => resolution,
3208 // This is a local path in the value namespace. Walk through
3209 // scopes looking for it.
3210 if let Some(path_res) = resolution {
3211 // Check if struct variant
3212 let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
3213 self.structs.contains_key(&variant_id)
3217 if is_struct_variant {
3218 let _ = self.structs.contains_key(&path_res.base_def.def_id());
3219 let path_name = path_names_to_string(path, 0);
3221 let mut err = resolve_struct_error(self,
3223 ResolutionError::StructVariantUsedAsFunction(&path_name));
3225 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3227 if self.emit_errors {
3228 err.fileline_help(expr.span, &msg);
3230 err.span_help(expr.span, &msg);
3233 self.record_def(expr.id, err_path_resolution());
3235 // Write the result into the def map.
3236 debug!("(resolving expr) resolved `{}`",
3237 path_names_to_string(path, 0));
3239 // Partial resolutions will need the set of traits in scope,
3240 // so they can be completed during typeck.
3241 if path_res.depth != 0 {
3242 let method_name = path.segments.last().unwrap().identifier.name;
3243 let traits = self.get_traits_containing_item(method_name);
3244 self.trait_map.insert(expr.id, traits);
3247 self.record_def(expr.id, path_res);
3250 // Be helpful if the name refers to a struct
3251 // (The pattern matching def_tys where the id is in self.structs
3252 // matches on regular structs while excluding tuple- and enum-like
3253 // structs, which wouldn't result in this error.)
3254 let path_name = path_names_to_string(path, 0);
3255 let type_res = self.with_no_errors(|this| {
3256 this.resolve_path(expr.id, path, 0, TypeNS, false)
3259 self.record_def(expr.id, err_path_resolution());
3260 match type_res.map(|r| r.base_def) {
3261 Some(Def::Struct(..)) => {
3262 let mut err = resolve_struct_error(self,
3264 ResolutionError::StructVariantUsedAsFunction(&path_name));
3266 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3268 if self.emit_errors {
3269 err.fileline_help(expr.span, &msg);
3271 err.span_help(expr.span, &msg);
3276 // Keep reporting some errors even if they're ignored above.
3277 self.resolve_path(expr.id, path, 0, ValueNS, true);
3279 let mut method_scope = false;
3280 self.value_ribs.iter().rev().all(|rib| {
3281 method_scope = match rib.kind {
3282 MethodRibKind => true,
3283 ItemRibKind | ConstantItemRibKind => false,
3284 _ => return true, // Keep advancing
3286 false // Stop advancing
3289 if method_scope && special_names::self_.as_str() == &path_name[..] {
3292 ResolutionError::SelfNotAvailableInStaticMethod);
3294 let last_name = path.segments.last().unwrap().identifier.name;
3295 let mut msg = match self.find_fallback_in_self_type(last_name) {
3297 // limit search to 5 to reduce the number
3298 // of stupid suggestions
3299 match self.find_best_match(&path_name) {
3300 SuggestionType::Macro(s) => {
3301 format!("the macro `{}`", s)
3303 SuggestionType::Function(s) => format!("`{}`", s),
3304 SuggestionType::NotFound => "".to_string(),
3307 Field => format!("`self.{}`", path_name),
3309 TraitItem => format!("to call `self.{}`", path_name),
3310 TraitMethod(path_str) |
3311 StaticMethod(path_str) =>
3312 format!("to call `{}::{}`", path_str, path_name),
3315 let mut context = UnresolvedNameContext::Other;
3316 if !msg.is_empty() {
3317 msg = format!(". Did you mean {}?", msg);
3319 // we check if this a module and if so, we display a help
3321 let name_path = path.segments.iter()
3322 .map(|seg| seg.identifier.name)
3323 .collect::<Vec<_>>();
3324 let current_module = self.current_module;
3326 match self.resolve_module_path(current_module,
3331 context = UnresolvedNameContext::PathIsMod(expr.id);
3339 ResolutionError::UnresolvedName(
3340 &path_name, &msg, context));
3346 intravisit::walk_expr(self, expr);
3349 ExprStruct(ref path, _, _) => {
3350 // Resolve the path to the structure it goes to. We don't
3351 // check to ensure that the path is actually a structure; that
3352 // is checked later during typeck.
3353 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3354 Some(definition) => self.record_def(expr.id, definition),
3356 debug!("(resolving expression) didn't find struct def",);
3360 ResolutionError::DoesNotNameAStruct(
3361 &path_names_to_string(path, 0))
3363 self.record_def(expr.id, err_path_resolution());
3367 intravisit::walk_expr(self, expr);
3370 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3371 self.with_label_rib(|this| {
3372 let def_like = DlDef(Def::Label(expr.id));
3375 let rib = this.label_ribs.last_mut().unwrap();
3376 rib.bindings.insert(label.name, def_like);
3379 intravisit::walk_expr(this, expr);
3383 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3384 match self.search_label(label.node.name) {
3386 self.record_def(expr.id, err_path_resolution());
3389 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3391 Some(DlDef(def @ Def::Label(_))) => {
3392 // Since this def is a label, it is never read.
3393 self.record_def(expr.id,
3396 last_private: LastMod(AllPublic),
3401 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3407 intravisit::walk_expr(self, expr);
3412 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3414 ExprField(_, name) => {
3415 // FIXME(#6890): Even though you can't treat a method like a
3416 // field, we need to add any trait methods we find that match
3417 // the field name so that we can do some nice error reporting
3418 // later on in typeck.
3419 let traits = self.get_traits_containing_item(name.node);
3420 self.trait_map.insert(expr.id, traits);
3422 ExprMethodCall(name, _, _) => {
3423 debug!("(recording candidate traits for expr) recording traits for {}",
3425 let traits = self.get_traits_containing_item(name.node);
3426 self.trait_map.insert(expr.id, traits);
3434 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3435 debug!("(getting traits containing item) looking for '{}'", name);
3437 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3438 debug!("(adding trait info) found trait {:?} for method '{}'",
3441 found_traits.push(trait_def_id);
3444 let mut found_traits = Vec::new();
3445 let mut search_module = self.current_module;
3447 // Look for the current trait.
3448 match self.current_trait_ref {
3449 Some((trait_def_id, _)) => {
3450 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3451 add_trait_info(&mut found_traits, trait_def_id, name);
3454 None => {} // Nothing to do.
3457 // Look for trait children.
3458 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3460 search_module.for_each_child(|_, ns, name_binding| {
3461 if ns != TypeNS { return }
3462 let trait_def_id = match name_binding.def() {
3463 Some(Def::Trait(trait_def_id)) => trait_def_id,
3464 Some(..) | None => return,
3466 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3467 add_trait_info(&mut found_traits, trait_def_id, name);
3468 let trait_name = self.get_trait_name(trait_def_id);
3469 self.record_use(trait_name, TypeNS, name_binding);
3473 // Look for shadowed traits.
3474 for binding in search_module.shadowed_traits.borrow().iter() {
3475 let did = binding.def().unwrap().def_id();
3476 if self.trait_item_map.contains_key(&(name, did)) {
3477 add_trait_info(&mut found_traits, did, name);
3478 let trait_name = self.get_trait_name(did);
3479 self.record_use(trait_name, TypeNS, binding);
3483 match search_module.parent_link {
3484 NoParentLink | ModuleParentLink(..) => break,
3485 BlockParentLink(parent_module, _) => {
3486 search_module = parent_module;
3494 /// When name resolution fails, this method can be used to look up candidate
3495 /// entities with the expected name. It allows filtering them using the
3496 /// supplied predicate (which should be used to only accept the types of
3497 /// definitions expected e.g. traits). The lookup spans across all crates.
3499 /// NOTE: The method does not look into imports, but this is not a problem,
3500 /// since we report the definitions (thus, the de-aliased imports).
3501 fn lookup_candidates<FilterFn>(&mut self,
3503 namespace: Namespace,
3504 filter_fn: FilterFn) -> SuggestedCandidates
3505 where FilterFn: Fn(Def) -> bool {
3507 let mut lookup_results = Vec::new();
3508 let mut worklist = Vec::new();
3509 worklist.push((self.graph_root, Vec::new(), false));
3511 while let Some((in_module,
3513 in_module_is_extern)) = worklist.pop() {
3514 build_reduced_graph::populate_module_if_necessary(self, &in_module);
3516 in_module.for_each_child(|name, ns, name_binding| {
3518 // avoid imports entirely
3519 if name_binding.is_import() { return; }
3521 // collect results based on the filter function
3522 if let Some(def) = name_binding.def() {
3523 if name == lookup_name && ns == namespace && filter_fn(def) {
3525 let ident = hir::Ident::from_name(name);
3526 let params = PathParameters::none();
3527 let segment = PathSegment {
3531 let span = name_binding.span.unwrap_or(syntax::codemap::DUMMY_SP);
3532 let mut segms = path_segments.clone();
3533 segms.push(segment);
3534 let segms = HirVec::from_vec(segms);
3540 // the entity is accessible in the following cases:
3541 // 1. if it's defined in the same crate, it's always
3542 // accessible (since private entities can be made public)
3543 // 2. if it's defined in another crate, it's accessible
3544 // only if both the module is public and the entity is
3545 // declared as public (due to pruning, we don't explore
3546 // outside crate private modules => no need to check this)
3547 if !in_module_is_extern || name_binding.is_public() {
3548 lookup_results.push(path);
3553 // collect submodules to explore
3554 if let Some(module) = name_binding.module() {
3556 let path_segments = match module.parent_link {
3557 NoParentLink => path_segments.clone(),
3558 ModuleParentLink(_, name) => {
3559 let mut paths = path_segments.clone();
3560 let ident = hir::Ident::from_name(name);
3561 let params = PathParameters::none();
3562 let segm = PathSegment {
3569 _ => unreachable!(),
3572 if !in_module_is_extern || name_binding.is_public() {
3573 // add the module to the lookup
3574 let is_extern = in_module_is_extern || module.is_extern_crate;
3575 worklist.push((module, path_segments, is_extern));
3581 SuggestedCandidates {
3582 name: lookup_name.as_str().to_string(),
3583 candidates: lookup_results,
3587 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3588 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3589 assert!(match resolution.last_private {
3590 LastImport{..} => false,
3593 "Import should only be used for `use` directives");
3595 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3596 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3597 self.session.span_bug(span,
3598 &format!("path resolved multiple times ({:?} before, {:?} now)",
3604 fn enforce_default_binding_mode(&mut self,
3606 pat_binding_mode: BindingMode,
3608 match pat_binding_mode {
3609 BindByValue(_) => {}
3613 ResolutionError::CannotUseRefBindingModeWith(descr));
3620 fn names_to_string(names: &[Name]) -> String {
3621 let mut first = true;
3622 let mut result = String::new();
3627 result.push_str("::")
3629 result.push_str(&name.as_str());
3634 fn path_names_to_string(path: &Path, depth: usize) -> String {
3635 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3637 .map(|seg| seg.identifier.name)
3639 names_to_string(&names[..])
3642 /// When an entity with a given name is not available in scope, we search for
3643 /// entities with that name in all crates. This method allows outputting the
3644 /// results of this search in a programmer-friendly way
3645 fn show_candidates(session: &mut DiagnosticBuilder,
3646 span: syntax::codemap::Span,
3647 candidates: &SuggestedCandidates) {
3649 let paths = &candidates.candidates;
3651 if paths.len() > 0 {
3652 // don't show more than MAX_CANDIDATES results, so
3653 // we're consistent with the trait suggestions
3654 const MAX_CANDIDATES: usize = 5;
3656 // we want consistent results across executions, but candidates are produced
3657 // by iterating through a hash map, so make sure they are ordered:
3658 let mut path_strings: Vec<_> = paths.into_iter()
3659 .map(|p| path_names_to_string(&p, 0))
3661 path_strings.sort();
3663 // behave differently based on how many candidates we have:
3664 if !paths.is_empty() {
3665 if paths.len() == 1 {
3666 session.fileline_help(
3668 &format!("you can to import it into scope: `use {};`.",
3672 session.fileline_help(span, "you can import several candidates \
3673 into scope (`use ...;`):");
3674 let count = path_strings.len() as isize - MAX_CANDIDATES as isize + 1;
3676 for (idx, path_string) in path_strings.iter().enumerate() {
3677 if idx == MAX_CANDIDATES - 1 && count > 1 {
3678 session.fileline_help(
3680 &format!(" and {} other candidates", count).to_string(),
3684 session.fileline_help(
3686 &format!(" `{}`", path_string).to_string(),
3694 session.fileline_help(
3696 &format!("no candidates by the name of `{}` found in your \
3697 project; maybe you misspelled the name or forgot to import \
3698 an external crate?", candidates.name.to_string()),
3703 /// A somewhat inefficient routine to obtain the name of a module.
3704 fn module_to_string(module: Module) -> String {
3705 let mut names = Vec::new();
3707 fn collect_mod(names: &mut Vec<ast::Name>, module: Module) {
3708 match module.parent_link {
3710 ModuleParentLink(ref module, name) => {
3712 collect_mod(names, module);
3714 BlockParentLink(ref module, _) => {
3715 // danger, shouldn't be ident?
3716 names.push(special_idents::opaque.name);
3717 collect_mod(names, module);
3721 collect_mod(&mut names, module);
3723 if names.is_empty() {
3724 return "???".to_string();
3726 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3729 fn err_path_resolution() -> PathResolution {
3732 last_private: LastMod(AllPublic),
3738 pub struct CrateMap {
3739 pub def_map: RefCell<DefMap>,
3740 pub freevars: FreevarMap,
3741 pub export_map: ExportMap,
3742 pub trait_map: TraitMap,
3743 pub external_exports: ExternalExports,
3744 pub glob_map: Option<GlobMap>,
3747 #[derive(PartialEq,Copy, Clone)]
3748 pub enum MakeGlobMap {
3753 /// Entry point to crate resolution.
3754 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3755 ast_map: &'a hir_map::Map<'tcx>,
3756 make_glob_map: MakeGlobMap)
3758 // Currently, we ignore the name resolution data structures for
3759 // the purposes of dependency tracking. Instead we will run name
3760 // resolution and include its output in the hash of each item,
3761 // much like we do for macro expansion. In other words, the hash
3762 // reflects not just its contents but the results of name
3763 // resolution on those contents. Hopefully we'll push this back at
3765 let _task = ast_map.dep_graph.in_task(DepNode::Resolve);
3767 let krate = ast_map.krate();
3768 let arenas = Resolver::arenas();
3769 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3771 resolver.resolve_crate(krate);
3773 check_unused::check_crate(&mut resolver, krate);
3776 def_map: resolver.def_map,
3777 freevars: resolver.freevars,
3778 export_map: resolver.export_map,
3779 trait_map: resolver.trait_map,
3780 external_exports: resolver.external_exports,
3781 glob_map: if resolver.make_glob_map {
3782 Some(resolver.glob_map)
3789 /// Builds a name resolution walker to be used within this module,
3790 /// or used externally, with an optional callback function.
3792 /// The callback takes a &mut bool which allows callbacks to end a
3793 /// walk when set to true, passing through the rest of the walk, while
3794 /// preserving the ribs + current module. This allows resolve_path
3795 /// calls to be made with the correct scope info. The node in the
3796 /// callback corresponds to the current node in the walk.
3797 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3798 ast_map: &'a hir_map::Map<'tcx>,
3800 make_glob_map: MakeGlobMap,
3801 arenas: &'a ResolverArenas<'a>,
3802 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3803 -> Resolver<'a, 'tcx> {
3804 let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
3806 resolver.callback = callback;
3808 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3810 resolve_imports::resolve_imports(&mut resolver);
3815 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }