1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
18 #![cfg_attr(not(stage0), deny(warnings))]
20 #![feature(associated_consts)]
21 #![feature(borrow_state)]
22 #![feature(rustc_diagnostic_macros)]
23 #![feature(rustc_private)]
24 #![feature(staged_api)]
33 extern crate rustc_bitflags;
34 extern crate rustc_front;
37 use self::PatternBindingMode::*;
38 use self::Namespace::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::BareIdentifierPatternResolution::*;
47 use self::ParentLink::*;
48 use self::FallbackChecks::*;
50 use rustc::dep_graph::DepNode;
51 use rustc::front::map as hir_map;
52 use rustc::session::Session;
54 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
55 use rustc::middle::def::*;
56 use rustc::middle::def_id::DefId;
57 use rustc::middle::pat_util::pat_bindings;
58 use rustc::middle::privacy::*;
59 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
60 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
61 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
63 use syntax::ast::{self, FloatTy};
64 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
65 use syntax::attr::AttrMetaMethods;
66 use syntax::codemap::{self, Span, Pos};
67 use syntax::errors::DiagnosticBuilder;
68 use syntax::parse::token::{self, special_names, special_idents};
69 use syntax::util::lev_distance::find_best_match_for_name;
71 use rustc_front::intravisit::{self, FnKind, Visitor};
73 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
74 use rustc_front::hir::Crate;
75 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
76 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
77 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
78 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
79 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
80 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
81 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
82 use rustc_front::hir::Local;
83 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
84 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
85 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
86 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
87 use rustc_front::util::walk_pat;
89 use std::collections::{HashMap, HashSet};
90 use std::cell::{Cell, RefCell};
92 use std::mem::replace;
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 pub enum ResolutionError<'a> {
122 /// error E0401: can't use type parameters from outer function
123 TypeParametersFromOuterFunction,
124 /// error E0402: cannot use an outer type parameter in this context
125 OuterTypeParameterContext,
126 /// error E0403: the name is already used for a type parameter in this type parameter list
127 NameAlreadyUsedInTypeParameterList(Name),
128 /// error E0404: is not a trait
129 IsNotATrait(&'a str),
130 /// error E0405: use of undeclared trait name
131 UndeclaredTraitName(&'a str),
132 /// error E0406: undeclared associated type
133 UndeclaredAssociatedType,
134 /// error E0407: method is not a member of trait
135 MethodNotMemberOfTrait(Name, &'a str),
136 /// error E0437: type is not a member of trait
137 TypeNotMemberOfTrait(Name, &'a str),
138 /// error E0438: const is not a member of trait
139 ConstNotMemberOfTrait(Name, &'a str),
140 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
141 VariableNotBoundInPattern(Name, usize),
142 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
143 VariableBoundWithDifferentMode(Name, usize),
144 /// error E0410: variable from pattern is not bound in pattern #1
145 VariableNotBoundInParentPattern(Name, usize),
146 /// error E0411: use of `Self` outside of an impl or trait
147 SelfUsedOutsideImplOrTrait,
148 /// error E0412: use of undeclared
149 UseOfUndeclared(&'a str, &'a str),
150 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
151 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
152 /// error E0414: only irrefutable patterns allowed here
153 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
154 /// error E0415: identifier is bound more than once in this parameter list
155 IdentifierBoundMoreThanOnceInParameterList(&'a str),
156 /// error E0416: identifier is bound more than once in the same pattern
157 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
158 /// error E0417: static variables cannot be referenced in a pattern
159 StaticVariableReference,
160 /// error E0418: is not an enum variant, struct or const
161 NotAnEnumVariantStructOrConst(&'a str),
162 /// error E0419: unresolved enum variant, struct or const
163 UnresolvedEnumVariantStructOrConst(&'a str),
164 /// error E0420: is not an associated const
165 NotAnAssociatedConst(&'a str),
166 /// error E0421: unresolved associated const
167 UnresolvedAssociatedConst(&'a str),
168 /// error E0422: does not name a struct
169 DoesNotNameAStruct(&'a str),
170 /// error E0423: is a struct variant name, but this expression uses it like a function name
171 StructVariantUsedAsFunction(&'a str),
172 /// error E0424: `self` is not available in a static method
173 SelfNotAvailableInStaticMethod,
174 /// error E0425: unresolved name
175 UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
176 /// error E0426: use of undeclared label
177 UndeclaredLabel(&'a str),
178 /// error E0427: cannot use `ref` binding mode with ...
179 CannotUseRefBindingModeWith(&'a str),
180 /// error E0428: duplicate definition
181 DuplicateDefinition(&'a str, Name),
182 /// error E0429: `self` imports are only allowed within a { } list
183 SelfImportsOnlyAllowedWithin,
184 /// error E0430: `self` import can only appear once in the list
185 SelfImportCanOnlyAppearOnceInTheList,
186 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
187 SelfImportOnlyInImportListWithNonEmptyPrefix,
188 /// error E0432: unresolved import
189 UnresolvedImport(Option<(&'a str, &'a str)>),
190 /// error E0433: failed to resolve
191 FailedToResolve(&'a str),
192 /// error E0434: can't capture dynamic environment in a fn item
193 CannotCaptureDynamicEnvironmentInFnItem,
194 /// error E0435: attempt to use a non-constant value in a constant
195 AttemptToUseNonConstantValueInConstant,
198 /// Context of where `ResolutionError::UnresolvedName` arose.
199 #[derive(Clone, PartialEq, Eq, Debug)]
200 pub enum UnresolvedNameContext {
201 /// `PathIsMod(id)` indicates that a given path, used in
202 /// expression context, actually resolved to a module rather than
203 /// a value. The `id` attached to the variant is the node id of
204 /// the erroneous path expression.
205 PathIsMod(ast::NodeId),
207 /// `Other` means we have no extra information about the context
208 /// of the unresolved name error. (Maybe we could eliminate all
209 /// such cases; but for now, this is an information-free default.)
213 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
214 span: syntax::codemap::Span,
215 resolution_error: ResolutionError<'b>) {
216 resolve_struct_error(resolver, span, resolution_error).emit();
219 fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
220 span: syntax::codemap::Span,
221 resolution_error: ResolutionError<'b>)
222 -> DiagnosticBuilder<'a> {
223 if !resolver.emit_errors {
224 return resolver.session.diagnostic().struct_dummy();
227 match resolution_error {
228 ResolutionError::TypeParametersFromOuterFunction => {
229 struct_span_err!(resolver.session,
232 "can't use type parameters from outer function; try using a local \
233 type parameter instead")
235 ResolutionError::OuterTypeParameterContext => {
236 struct_span_err!(resolver.session,
239 "cannot use an outer type parameter in this context")
241 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
242 struct_span_err!(resolver.session,
245 "the name `{}` is already used for a type parameter in this type \
249 ResolutionError::IsNotATrait(name) => {
250 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
252 ResolutionError::UndeclaredTraitName(name) => {
253 struct_span_err!(resolver.session,
256 "use of undeclared trait name `{}`",
259 ResolutionError::UndeclaredAssociatedType => {
260 struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
262 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
263 struct_span_err!(resolver.session,
266 "method `{}` is not a member of trait `{}`",
270 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
271 struct_span_err!(resolver.session,
274 "type `{}` is not a member of trait `{}`",
278 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
279 struct_span_err!(resolver.session,
282 "const `{}` is not a member of trait `{}`",
286 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
287 struct_span_err!(resolver.session,
290 "variable `{}` from pattern #1 is not bound in pattern #{}",
294 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
295 struct_span_err!(resolver.session,
298 "variable `{}` is bound with different mode in pattern #{} than in \
303 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
304 struct_span_err!(resolver.session,
307 "variable `{}` from pattern #{} is not bound in pattern #1",
311 ResolutionError::SelfUsedOutsideImplOrTrait => {
312 struct_span_err!(resolver.session,
315 "use of `Self` outside of an impl or trait")
317 ResolutionError::UseOfUndeclared(kind, name) => {
318 struct_span_err!(resolver.session,
321 "use of undeclared {} `{}`",
325 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
326 struct_span_err!(resolver.session,
329 "declaration of `{}` shadows an enum variant \
330 or unit-like struct in scope",
333 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
334 let mut err = struct_span_err!(resolver.session,
337 "only irrefutable patterns allowed here");
339 "there already is a constant in scope sharing the same \
340 name as this pattern");
341 if let Some(sp) = resolver.ast_map.span_if_local(did) {
342 err.span_note(sp, "constant defined here");
344 if let Success(binding) = resolver.current_module.resolve_name(name, ValueNS, true) {
345 if binding.is_import() {
346 err.span_note(binding.span.unwrap(), "constant imported here");
351 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
352 struct_span_err!(resolver.session,
355 "identifier `{}` is bound more than once in this parameter list",
358 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
359 struct_span_err!(resolver.session,
362 "identifier `{}` is bound more than once in the same pattern",
365 ResolutionError::StaticVariableReference => {
366 struct_span_err!(resolver.session,
369 "static variables cannot be referenced in a pattern, use a \
372 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
373 struct_span_err!(resolver.session,
376 "`{}` is not an enum variant, struct or const",
379 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
380 struct_span_err!(resolver.session,
383 "unresolved enum variant, struct or const `{}`",
386 ResolutionError::NotAnAssociatedConst(name) => {
387 struct_span_err!(resolver.session,
390 "`{}` is not an associated const",
393 ResolutionError::UnresolvedAssociatedConst(name) => {
394 struct_span_err!(resolver.session,
397 "unresolved associated const `{}`",
400 ResolutionError::DoesNotNameAStruct(name) => {
401 struct_span_err!(resolver.session,
404 "`{}` does not name a structure",
407 ResolutionError::StructVariantUsedAsFunction(path_name) => {
408 struct_span_err!(resolver.session,
411 "`{}` is the name of a struct or struct variant, but this expression \
412 uses it like a function name",
415 ResolutionError::SelfNotAvailableInStaticMethod => {
416 struct_span_err!(resolver.session,
419 "`self` is not available in a static method. Maybe a `self` \
420 argument is missing?")
422 ResolutionError::UnresolvedName(path, msg, context) => {
423 let mut err = struct_span_err!(resolver.session,
426 "unresolved name `{}`{}",
431 UnresolvedNameContext::Other => { } // no help available
432 UnresolvedNameContext::PathIsMod(id) => {
433 let mut help_msg = String::new();
434 let parent_id = resolver.ast_map.get_parent_node(id);
435 if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
437 ExprField(_, ident) => {
438 help_msg = format!("To reference an item from the \
439 `{module}` module, use \
440 `{module}::{ident}`",
444 ExprMethodCall(ident, _, _) => {
445 help_msg = format!("To call a function from the \
446 `{module}` module, use \
447 `{module}::{ident}(..)`",
452 help_msg = format!("No function corresponds to `{module}(..)`",
455 _ => { } // no help available
458 help_msg = format!("Module `{module}` cannot be the value of an expression",
462 if !help_msg.is_empty() {
463 err.fileline_help(span, &help_msg);
469 ResolutionError::UndeclaredLabel(name) => {
470 struct_span_err!(resolver.session,
473 "use of undeclared label `{}`",
476 ResolutionError::CannotUseRefBindingModeWith(descr) => {
477 struct_span_err!(resolver.session,
480 "cannot use `ref` binding mode with {}",
483 ResolutionError::DuplicateDefinition(namespace, name) => {
484 struct_span_err!(resolver.session,
487 "duplicate definition of {} `{}`",
491 ResolutionError::SelfImportsOnlyAllowedWithin => {
492 struct_span_err!(resolver.session,
496 "`self` imports are only allowed within a { } list")
498 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
499 struct_span_err!(resolver.session,
502 "`self` import can only appear once in the list")
504 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
505 struct_span_err!(resolver.session,
508 "`self` import can only appear in an import list with a \
511 ResolutionError::UnresolvedImport(name) => {
512 let msg = match name {
513 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
514 None => "unresolved import".to_owned(),
516 struct_span_err!(resolver.session, span, E0432, "{}", msg)
518 ResolutionError::FailedToResolve(msg) => {
519 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
521 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
522 struct_span_err!(resolver.session,
526 "can't capture dynamic environment in a fn item; use the || { ... } \
527 closure form instead")
529 ResolutionError::AttemptToUseNonConstantValueInConstant => {
530 struct_span_err!(resolver.session,
533 "attempt to use a non-constant value in a constant")
538 #[derive(Copy, Clone)]
541 binding_mode: BindingMode,
544 // Map from the name in a pattern to its binding mode.
545 type BindingMap = HashMap<Name, BindingInfo>;
547 #[derive(Copy, Clone, PartialEq)]
548 enum PatternBindingMode {
550 LocalIrrefutableMode,
551 ArgumentIrrefutableMode,
554 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
560 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
561 fn visit_nested_item(&mut self, item: hir::ItemId) {
562 self.visit_item(self.ast_map.expect_item(item.id))
564 fn visit_item(&mut self, item: &Item) {
565 execute_callback!(hir_map::Node::NodeItem(item), self);
566 self.resolve_item(item);
568 fn visit_arm(&mut self, arm: &Arm) {
569 self.resolve_arm(arm);
571 fn visit_block(&mut self, block: &Block) {
572 execute_callback!(hir_map::Node::NodeBlock(block), self);
573 self.resolve_block(block);
575 fn visit_expr(&mut self, expr: &Expr) {
576 execute_callback!(hir_map::Node::NodeExpr(expr), self);
577 self.resolve_expr(expr);
579 fn visit_local(&mut self, local: &Local) {
580 execute_callback!(hir_map::Node::NodeLocal(&local.pat), self);
581 self.resolve_local(local);
583 fn visit_ty(&mut self, ty: &Ty) {
584 self.resolve_type(ty);
586 fn visit_generics(&mut self, generics: &Generics) {
587 self.resolve_generics(generics);
589 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
590 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
591 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
593 // error already reported
594 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
597 intravisit::walk_poly_trait_ref(self, tref, m);
599 fn visit_variant(&mut self,
600 variant: &hir::Variant,
602 item_id: ast::NodeId) {
603 execute_callback!(hir_map::Node::NodeVariant(variant), self);
604 if let Some(ref dis_expr) = variant.node.disr_expr {
605 // resolve the discriminator expr as a constant
606 self.with_constant_rib(|this| {
607 this.visit_expr(dis_expr);
611 // `intravisit::walk_variant` without the discriminant expression.
612 self.visit_variant_data(&variant.node.data,
618 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
619 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
620 let type_parameters = match foreign_item.node {
621 ForeignItemFn(_, ref generics) => {
622 HasTypeParameters(generics, FnSpace, ItemRibKind)
624 ForeignItemStatic(..) => NoTypeParameters,
626 self.with_type_parameter_rib(type_parameters, |this| {
627 intravisit::walk_foreign_item(this, foreign_item);
630 fn visit_fn(&mut self,
631 function_kind: FnKind<'v>,
632 declaration: &'v FnDecl,
636 let rib_kind = match function_kind {
637 FnKind::ItemFn(_, generics, _, _, _, _) => {
638 self.visit_generics(generics);
641 FnKind::Method(_, sig, _) => {
642 self.visit_generics(&sig.generics);
643 self.visit_explicit_self(&sig.explicit_self);
646 FnKind::Closure => ClosureRibKind(node_id),
648 self.resolve_function(rib_kind, declaration, block);
652 pub type ErrorMessage = Option<(Span, String)>;
654 #[derive(Clone, PartialEq, Eq)]
655 pub enum ResolveResult<T> {
656 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
657 Indeterminate, // Couldn't determine due to unresolved globs.
658 Success(T), // Successfully resolved the import.
661 impl<T> ResolveResult<T> {
662 fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
664 Failed(msg) => Failed(msg),
665 Indeterminate => Indeterminate,
670 fn success(self) -> Option<T> {
672 Success(t) => Some(t),
678 enum FallbackSuggestion {
683 StaticMethod(String),
687 #[derive(Copy, Clone)]
688 enum TypeParameters<'tcx, 'a> {
690 HasTypeParameters(// Type parameters.
693 // Identifies the things that these parameters
694 // were declared on (type, fn, etc)
697 // The kind of the rib used for type parameters.
701 // The rib kind controls the translation of local
702 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
703 #[derive(Copy, Clone, Debug)]
705 // No translation needs to be applied.
708 // We passed through a closure scope at the given node ID.
709 // Translate upvars as appropriate.
710 ClosureRibKind(NodeId /* func id */),
712 // We passed through an impl or trait and are now in one of its
713 // methods. Allow references to ty params that impl or trait
714 // binds. Disallow any other upvars (including other ty params that are
718 // We passed through an item scope. Disallow upvars.
721 // We're in a constant item. Can't refer to dynamic stuff.
724 // We passed through an anonymous module.
725 AnonymousModuleRibKind(Module<'a>),
728 #[derive(Copy, Clone)]
729 enum UseLexicalScopeFlag {
734 enum ModulePrefixResult<'a> {
736 PrefixFound(Module<'a>, usize),
739 #[derive(Copy, Clone)]
740 enum AssocItemResolveResult {
741 /// Syntax such as `<T>::item`, which can't be resolved until type
744 /// We should have been able to resolve the associated item.
745 ResolveAttempt(Option<PathResolution>),
748 #[derive(Copy, Clone)]
749 enum BareIdentifierPatternResolution {
750 FoundStructOrEnumVariant(Def, LastPrivate),
751 FoundConst(Def, LastPrivate, Name),
752 BareIdentifierPatternUnresolved,
758 bindings: HashMap<Name, DefLike>,
763 fn new(kind: RibKind<'a>) -> Rib<'a> {
765 bindings: HashMap::new(),
771 /// A definition along with the index of the rib it was found on
773 ribs: Option<(Namespace, usize)>,
778 fn from_def(def: Def) -> Self {
786 /// The link from a module up to its nearest parent node.
787 #[derive(Clone,Debug)]
788 enum ParentLink<'a> {
790 ModuleParentLink(Module<'a>, Name),
791 BlockParentLink(Module<'a>, NodeId),
794 /// One node in the tree of modules.
795 pub struct ModuleS<'a> {
796 parent_link: ParentLink<'a>,
799 is_extern_crate: bool,
801 resolutions: RefCell<HashMap<(Name, Namespace), NameResolution<'a>>>,
802 imports: RefCell<Vec<ImportDirective>>,
804 // The module children of this node, including normal modules and anonymous modules.
805 // Anonymous children are pseudo-modules that are implicitly created around items
806 // contained within blocks.
808 // For example, if we have this:
816 // There will be an anonymous module created around `g` with the ID of the
817 // entry block for `f`.
818 module_children: RefCell<NodeMap<Module<'a>>>,
820 shadowed_traits: RefCell<Vec<&'a NameBinding<'a>>>,
822 // The number of unresolved globs that this module exports.
823 glob_count: Cell<usize>,
825 // The number of unresolved pub imports (both regular and globs) in this module
826 pub_count: Cell<usize>,
828 // The number of unresolved pub glob imports in this module
829 pub_glob_count: Cell<usize>,
831 // The index of the import we're resolving.
832 resolved_import_count: Cell<usize>,
834 // Whether this module is populated. If not populated, any attempt to
835 // access the children must be preceded with a
836 // `populate_module_if_necessary` call.
837 populated: Cell<bool>,
840 pub type Module<'a> = &'a ModuleS<'a>;
842 impl<'a> ModuleS<'a> {
843 fn new(parent_link: ParentLink<'a>, def: Option<Def>, external: bool, is_public: bool) -> Self {
845 parent_link: parent_link,
847 is_public: is_public,
848 is_extern_crate: false,
849 resolutions: RefCell::new(HashMap::new()),
850 imports: RefCell::new(Vec::new()),
851 module_children: RefCell::new(NodeMap()),
852 shadowed_traits: RefCell::new(Vec::new()),
853 glob_count: Cell::new(0),
854 pub_count: Cell::new(0),
855 pub_glob_count: Cell::new(0),
856 resolved_import_count: Cell::new(0),
857 populated: Cell::new(!external),
861 fn resolve_name(&self, name: Name, ns: Namespace, allow_private_imports: bool)
862 -> ResolveResult<&'a NameBinding<'a>> {
864 if allow_private_imports { self.glob_count.get() } else { self.pub_glob_count.get() };
866 self.resolutions.borrow().get(&(name, ns)).cloned().unwrap_or_default().result(glob_count)
867 .and_then(|binding| {
868 let allowed = allow_private_imports || !binding.is_import() || binding.is_public();
869 if allowed { Success(binding) } else { Failed(None) }
873 // Define the name or return the existing binding if there is a collision.
874 fn try_define_child(&self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>)
875 -> Result<(), &'a NameBinding<'a>> {
876 let mut children = self.resolutions.borrow_mut();
877 let resolution = children.entry((name, ns)).or_insert_with(Default::default);
879 // FIXME #31379: We can use methods from imported traits shadowed by non-import items
880 if let Some(old_binding) = resolution.binding {
881 if !old_binding.is_import() && binding.is_import() {
882 if let Some(Def::Trait(_)) = binding.def() {
883 self.shadowed_traits.borrow_mut().push(binding);
888 resolution.try_define(binding)
891 fn increment_outstanding_references_for(&self, name: Name, ns: Namespace) {
892 let mut children = self.resolutions.borrow_mut();
893 children.entry((name, ns)).or_insert_with(Default::default).outstanding_references += 1;
896 fn decrement_outstanding_references_for(&self, name: Name, ns: Namespace) {
897 match self.resolutions.borrow_mut().get_mut(&(name, ns)).unwrap().outstanding_references {
898 0 => panic!("No more outstanding references!"),
899 ref mut outstanding_references => { *outstanding_references -= 1; }
903 fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
904 for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
905 name_resolution.binding.map(|binding| f(name, ns, binding));
909 fn def_id(&self) -> Option<DefId> {
910 self.def.as_ref().map(Def::def_id)
913 fn is_normal(&self) -> bool {
915 Some(Def::Mod(_)) | Some(Def::ForeignMod(_)) => true,
920 fn is_trait(&self) -> bool {
922 Some(Def::Trait(_)) => true,
927 fn all_imports_resolved(&self) -> bool {
928 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
929 // it is currently being resolved ! so nope
932 self.imports.borrow().len() == self.resolved_import_count.get()
936 pub fn inc_glob_count(&self) {
937 self.glob_count.set(self.glob_count.get() + 1);
939 pub fn dec_glob_count(&self) {
940 assert!(self.glob_count.get() > 0);
941 self.glob_count.set(self.glob_count.get() - 1);
943 pub fn inc_pub_count(&self) {
944 self.pub_count.set(self.pub_count.get() + 1);
946 pub fn dec_pub_count(&self) {
947 assert!(self.pub_count.get() > 0);
948 self.pub_count.set(self.pub_count.get() - 1);
950 pub fn inc_pub_glob_count(&self) {
951 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
953 pub fn dec_pub_glob_count(&self) {
954 assert!(self.pub_glob_count.get() > 0);
955 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
959 impl<'a> fmt::Debug for ModuleS<'a> {
960 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
974 flags DefModifiers: u8 {
975 // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
976 // or `use Enum::*` to work on private enums.
977 const PUBLIC = 1 << 0,
978 const IMPORTABLE = 1 << 1,
979 // Variants are considered `PUBLIC`, but some of them live in private enums.
980 // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
981 const PRIVATE_VARIANT = 1 << 2,
982 const PRELUDE = 1 << 3,
983 const GLOB_IMPORTED = 1 << 4,
987 // Records a possibly-private value, type, or module definition.
989 pub struct NameBinding<'a> {
990 modifiers: DefModifiers,
991 kind: NameBindingKind<'a>,
996 enum NameBindingKind<'a> {
1000 binding: &'a NameBinding<'a>,
1005 impl<'a> NameBinding<'a> {
1006 fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
1007 let modifiers = if module.is_public {
1008 DefModifiers::PUBLIC
1010 DefModifiers::empty()
1011 } | DefModifiers::IMPORTABLE;
1013 NameBinding { modifiers: modifiers, kind: NameBindingKind::Module(module), span: span }
1016 fn module(&self) -> Option<Module<'a>> {
1018 NameBindingKind::Module(module) => Some(module),
1019 NameBindingKind::Def(_) => None,
1020 NameBindingKind::Import { binding, .. } => binding.module(),
1024 fn def(&self) -> Option<Def> {
1026 NameBindingKind::Def(def) => Some(def),
1027 NameBindingKind::Module(module) => module.def,
1028 NameBindingKind::Import { binding, .. } => binding.def(),
1032 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1033 self.modifiers.contains(modifiers)
1036 fn is_public(&self) -> bool {
1037 self.defined_with(DefModifiers::PUBLIC)
1040 fn def_and_lp(&self) -> (Def, LastPrivate) {
1041 let def = self.def().unwrap();
1042 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1045 fn is_extern_crate(&self) -> bool {
1046 self.module().map(|module| module.is_extern_crate).unwrap_or(false)
1049 fn is_import(&self) -> bool {
1051 NameBindingKind::Import { .. } => true,
1057 /// Interns the names of the primitive types.
1058 struct PrimitiveTypeTable {
1059 primitive_types: HashMap<Name, PrimTy>,
1062 impl PrimitiveTypeTable {
1063 fn new() -> PrimitiveTypeTable {
1064 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1066 table.intern("bool", TyBool);
1067 table.intern("char", TyChar);
1068 table.intern("f32", TyFloat(FloatTy::F32));
1069 table.intern("f64", TyFloat(FloatTy::F64));
1070 table.intern("isize", TyInt(IntTy::Is));
1071 table.intern("i8", TyInt(IntTy::I8));
1072 table.intern("i16", TyInt(IntTy::I16));
1073 table.intern("i32", TyInt(IntTy::I32));
1074 table.intern("i64", TyInt(IntTy::I64));
1075 table.intern("str", TyStr);
1076 table.intern("usize", TyUint(UintTy::Us));
1077 table.intern("u8", TyUint(UintTy::U8));
1078 table.intern("u16", TyUint(UintTy::U16));
1079 table.intern("u32", TyUint(UintTy::U32));
1080 table.intern("u64", TyUint(UintTy::U64));
1085 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1086 self.primitive_types.insert(token::intern(string), primitive_type);
1090 /// The main resolver class.
1091 pub struct Resolver<'a, 'tcx: 'a> {
1092 session: &'a Session,
1094 ast_map: &'a hir_map::Map<'tcx>,
1096 graph_root: Module<'a>,
1098 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1100 structs: FnvHashMap<DefId, Vec<Name>>,
1102 // The number of imports that are currently unresolved.
1103 unresolved_imports: usize,
1105 // The module that represents the current item scope.
1106 current_module: Module<'a>,
1108 // The current set of local scopes, for values.
1109 // FIXME #4948: Reuse ribs to avoid allocation.
1110 value_ribs: Vec<Rib<'a>>,
1112 // The current set of local scopes, for types.
1113 type_ribs: Vec<Rib<'a>>,
1115 // The current set of local scopes, for labels.
1116 label_ribs: Vec<Rib<'a>>,
1118 // The trait that the current context can refer to.
1119 current_trait_ref: Option<(DefId, TraitRef)>,
1121 // The current self type if inside an impl (used for better errors).
1122 current_self_type: Option<Ty>,
1124 // The idents for the primitive types.
1125 primitive_type_table: PrimitiveTypeTable,
1127 def_map: RefCell<DefMap>,
1128 freevars: FreevarMap,
1129 freevars_seen: NodeMap<NodeMap<usize>>,
1130 export_map: ExportMap,
1131 trait_map: TraitMap,
1132 external_exports: ExternalExports,
1134 // Whether or not to print error messages. Can be set to true
1135 // when getting additional info for error message suggestions,
1136 // so as to avoid printing duplicate errors
1139 make_glob_map: bool,
1140 // Maps imports to the names of items actually imported (this actually maps
1141 // all imports, but only glob imports are actually interesting).
1144 used_imports: HashSet<(NodeId, Namespace)>,
1145 used_crates: HashSet<CrateNum>,
1147 // Callback function for intercepting walks
1148 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1149 // The intention is that the callback modifies this flag.
1150 // Once set, the resolver falls out of the walk, preserving the ribs.
1153 arenas: &'a ResolverArenas<'a>,
1156 pub struct ResolverArenas<'a> {
1157 modules: arena::TypedArena<ModuleS<'a>>,
1158 name_bindings: arena::TypedArena<NameBinding<'a>>,
1161 #[derive(PartialEq)]
1162 enum FallbackChecks {
1164 OnlyTraitAndStatics,
1167 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1168 fn new(session: &'a Session,
1169 ast_map: &'a hir_map::Map<'tcx>,
1170 make_glob_map: MakeGlobMap,
1171 arenas: &'a ResolverArenas<'a>)
1172 -> Resolver<'a, 'tcx> {
1173 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1174 let graph_root = ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, true);
1175 let graph_root = arenas.modules.alloc(graph_root);
1182 // The outermost module has def ID 0; this is not reflected in the
1184 graph_root: graph_root,
1186 trait_item_map: FnvHashMap(),
1187 structs: FnvHashMap(),
1189 unresolved_imports: 0,
1191 current_module: graph_root,
1192 value_ribs: Vec::new(),
1193 type_ribs: Vec::new(),
1194 label_ribs: Vec::new(),
1196 current_trait_ref: None,
1197 current_self_type: None,
1199 primitive_type_table: PrimitiveTypeTable::new(),
1201 def_map: RefCell::new(NodeMap()),
1202 freevars: NodeMap(),
1203 freevars_seen: NodeMap(),
1204 export_map: NodeMap(),
1205 trait_map: NodeMap(),
1206 used_imports: HashSet::new(),
1207 used_crates: HashSet::new(),
1208 external_exports: DefIdSet(),
1211 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1212 glob_map: HashMap::new(),
1221 fn arenas() -> ResolverArenas<'a> {
1223 modules: arena::TypedArena::new(),
1224 name_bindings: arena::TypedArena::new(),
1228 fn new_module(&self,
1229 parent_link: ParentLink<'a>,
1232 is_public: bool) -> Module<'a> {
1233 self.arenas.modules.alloc(ModuleS::new(parent_link, def, external, is_public))
1236 fn new_name_binding(&self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1237 self.arenas.name_bindings.alloc(name_binding)
1240 fn new_extern_crate_module(&self, parent_link: ParentLink<'a>, def: Def) -> Module<'a> {
1241 let mut module = ModuleS::new(parent_link, Some(def), false, true);
1242 module.is_extern_crate = true;
1243 self.arenas.modules.alloc(module)
1246 fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
1247 match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
1251 fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>) {
1252 // track extern crates for unused_extern_crate lint
1253 if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
1254 self.used_crates.insert(krate);
1257 let import_id = match binding.kind {
1258 NameBindingKind::Import { id, .. } => id,
1262 self.used_imports.insert((import_id, ns));
1264 if !self.make_glob_map {
1267 if self.glob_map.contains_key(&import_id) {
1268 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1272 let mut new_set = HashSet::new();
1273 new_set.insert(name);
1274 self.glob_map.insert(import_id, new_set);
1277 fn get_trait_name(&self, did: DefId) -> Name {
1278 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1279 self.ast_map.expect_item(node_id).name
1281 self.session.cstore.item_name(did)
1285 /// Resolves the given module path from the given root `module_`.
1286 fn resolve_module_path_from_root(&mut self,
1287 module_: Module<'a>,
1288 module_path: &[Name],
1292 -> ResolveResult<(Module<'a>, LastPrivate)> {
1293 fn search_parent_externals<'a>(needle: Name, module: Module<'a>) -> Option<Module<'a>> {
1294 match module.resolve_name(needle, TypeNS, false) {
1295 Success(binding) if binding.is_extern_crate() => Some(module),
1296 _ => match module.parent_link {
1297 ModuleParentLink(ref parent, _) => {
1298 search_parent_externals(needle, parent)
1305 let mut search_module = module_;
1306 let mut index = index;
1307 let module_path_len = module_path.len();
1308 let mut closest_private = lp;
1310 // Resolve the module part of the path. This does not involve looking
1311 // upward though scope chains; we simply resolve names directly in
1312 // modules as we go.
1313 while index < module_path_len {
1314 let name = module_path[index];
1315 match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1317 let segment_name = name.as_str();
1318 let module_name = module_to_string(search_module);
1319 let mut span = span;
1320 let msg = if "???" == &module_name {
1321 span.hi = span.lo + Pos::from_usize(segment_name.len());
1323 match search_parent_externals(name, &self.current_module) {
1325 let path_str = names_to_string(module_path);
1326 let target_mod_str = module_to_string(&module);
1327 let current_mod_str = module_to_string(&self.current_module);
1329 let prefix = if target_mod_str == current_mod_str {
1330 "self::".to_string()
1332 format!("{}::", target_mod_str)
1335 format!("Did you mean `{}{}`?", prefix, path_str)
1337 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1340 format!("Could not find `{}` in `{}`", segment_name, module_name)
1343 return Failed(Some((span, msg)));
1345 Failed(err) => return Failed(err),
1347 debug!("(resolving module path for import) module resolution is \
1350 return Indeterminate;
1352 Success(binding) => {
1353 // Check to see whether there are type bindings, and, if
1354 // so, whether there is a module within.
1355 if let Some(module_def) = binding.module() {
1356 search_module = module_def;
1358 // Keep track of the closest private module used
1359 // when resolving this import chain.
1360 if !binding.is_public() {
1361 if let Some(did) = search_module.def_id() {
1362 closest_private = LastMod(DependsOn(did));
1366 let msg = format!("Not a module `{}`", name);
1367 return Failed(Some((span, msg)));
1375 return Success((search_module, closest_private));
1378 /// Attempts to resolve the module part of an import directive or path
1379 /// rooted at the given module.
1381 /// On success, returns the resolved module, and the closest *private*
1382 /// module found to the destination when resolving this path.
1383 fn resolve_module_path(&mut self,
1384 module_: Module<'a>,
1385 module_path: &[Name],
1386 use_lexical_scope: UseLexicalScopeFlag,
1388 -> ResolveResult<(Module<'a>, LastPrivate)> {
1389 if module_path.len() == 0 {
1390 return Success((self.graph_root, LastMod(AllPublic))) // Use the crate root
1393 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1394 names_to_string(module_path),
1395 module_to_string(&module_));
1397 // Resolve the module prefix, if any.
1398 let module_prefix_result = self.resolve_module_prefix(module_, module_path);
1403 match module_prefix_result {
1405 let mpath = names_to_string(module_path);
1406 let mpath = &mpath[..];
1407 match mpath.rfind(':') {
1409 let msg = format!("Could not find `{}` in `{}`",
1410 // idx +- 1 to account for the
1411 // colons on either side
1414 return Failed(Some((span, msg)));
1417 return Failed(None);
1421 Failed(err) => return Failed(err),
1423 debug!("(resolving module path for import) indeterminate; bailing");
1424 return Indeterminate;
1426 Success(NoPrefixFound) => {
1427 // There was no prefix, so we're considering the first element
1428 // of the path. How we handle this depends on whether we were
1429 // instructed to use lexical scope or not.
1430 match use_lexical_scope {
1431 DontUseLexicalScope => {
1432 // This is a crate-relative path. We will start the
1433 // resolution process at index zero.
1434 search_module = self.graph_root;
1436 last_private = LastMod(AllPublic);
1438 UseLexicalScope => {
1439 // This is not a crate-relative path. We resolve the
1440 // first component of the path in the current lexical
1441 // scope and then proceed to resolve below that.
1442 match self.resolve_item_in_lexical_scope(module_,
1446 Failed(err) => return Failed(err),
1448 debug!("(resolving module path for import) indeterminate; bailing");
1449 return Indeterminate;
1451 Success(binding) => match binding.module() {
1452 Some(containing_module) => {
1453 search_module = containing_module;
1455 last_private = LastMod(AllPublic);
1457 None => return Failed(None),
1463 Success(PrefixFound(ref containing_module, index)) => {
1464 search_module = containing_module;
1465 start_index = index;
1466 last_private = LastMod(DependsOn(containing_module.def_id()
1471 self.resolve_module_path_from_root(search_module,
1478 /// Invariant: This must only be called during main resolution, not during
1479 /// import resolution.
1480 fn resolve_item_in_lexical_scope(&mut self,
1481 module_: Module<'a>,
1483 namespace: Namespace,
1485 -> ResolveResult<&'a NameBinding<'a>> {
1486 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1489 module_to_string(&module_));
1491 // Proceed up the scope chain looking for parent modules.
1492 let mut search_module = module_;
1494 // Resolve the name in the parent module.
1495 match self.resolve_name_in_module(search_module, name, namespace, true, record_used) {
1496 Failed(Some((span, msg))) => {
1497 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
1499 Failed(None) => (), // Continue up the search chain.
1501 // We couldn't see through the higher scope because of an
1502 // unresolved import higher up. Bail.
1504 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1505 return Indeterminate;
1507 Success(binding) => {
1508 // We found the module.
1509 debug!("(resolving item in lexical scope) found name in module, done");
1510 return Success(binding);
1514 // Go to the next parent.
1515 match search_module.parent_link {
1517 // No more parents. This module was unresolved.
1518 debug!("(resolving item in lexical scope) unresolved module: no parent module");
1519 return Failed(None);
1521 ModuleParentLink(parent_module_node, _) => {
1522 if search_module.is_normal() {
1523 // We stop the search here.
1524 debug!("(resolving item in lexical scope) unresolved module: not \
1525 searching through module parents");
1526 return Failed(None);
1528 search_module = parent_module_node;
1531 BlockParentLink(parent_module_node, _) => {
1532 search_module = parent_module_node;
1538 /// Returns the nearest normal module parent of the given module.
1539 fn get_nearest_normal_module_parent(&mut self, module_: Module<'a>) -> Option<Module<'a>> {
1540 let mut module_ = module_;
1542 match module_.parent_link {
1543 NoParentLink => return None,
1544 ModuleParentLink(new_module, _) |
1545 BlockParentLink(new_module, _) => {
1546 let new_module = new_module;
1547 if new_module.is_normal() {
1548 return Some(new_module);
1550 module_ = new_module;
1556 /// Returns the nearest normal module parent of the given module, or the
1557 /// module itself if it is a normal module.
1558 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Module<'a>) -> Module<'a> {
1559 if module_.is_normal() {
1562 match self.get_nearest_normal_module_parent(module_) {
1564 Some(new_module) => new_module,
1568 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1569 /// (b) some chain of `super::`.
1570 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1571 fn resolve_module_prefix(&mut self,
1572 module_: Module<'a>,
1573 module_path: &[Name])
1574 -> ResolveResult<ModulePrefixResult<'a>> {
1575 // Start at the current module if we see `self` or `super`, or at the
1576 // top of the crate otherwise.
1577 let mut i = match &*module_path[0].as_str() {
1580 _ => return Success(NoPrefixFound),
1582 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1584 // Now loop through all the `super`s we find.
1585 while i < module_path.len() && "super" == module_path[i].as_str() {
1586 debug!("(resolving module prefix) resolving `super` at {}",
1587 module_to_string(&containing_module));
1588 match self.get_nearest_normal_module_parent(containing_module) {
1589 None => return Failed(None),
1590 Some(new_module) => {
1591 containing_module = new_module;
1597 debug!("(resolving module prefix) finished resolving prefix at {}",
1598 module_to_string(&containing_module));
1600 return Success(PrefixFound(containing_module, i));
1603 /// Attempts to resolve the supplied name in the given module for the
1604 /// given namespace. If successful, returns the binding corresponding to
1606 fn resolve_name_in_module(&mut self,
1609 namespace: Namespace,
1610 allow_private_imports: bool,
1612 -> ResolveResult<&'a NameBinding<'a>> {
1613 debug!("(resolving name in module) resolving `{}` in `{}`", name, module_to_string(module));
1615 build_reduced_graph::populate_module_if_necessary(self, module);
1616 module.resolve_name(name, namespace, allow_private_imports).and_then(|binding| {
1618 self.record_use(name, namespace, binding);
1624 fn report_unresolved_imports(&mut self, module_: Module<'a>) {
1625 let index = module_.resolved_import_count.get();
1626 let imports = module_.imports.borrow();
1627 let import_count = imports.len();
1628 if index != import_count {
1630 (*imports)[index].span,
1631 ResolutionError::UnresolvedImport(None));
1634 // Descend into children and anonymous children.
1635 for (_, module_) in module_.module_children.borrow().iter() {
1636 self.report_unresolved_imports(module_);
1642 // We maintain a list of value ribs and type ribs.
1644 // Simultaneously, we keep track of the current position in the module
1645 // graph in the `current_module` pointer. When we go to resolve a name in
1646 // the value or type namespaces, we first look through all the ribs and
1647 // then query the module graph. When we resolve a name in the module
1648 // namespace, we can skip all the ribs (since nested modules are not
1649 // allowed within blocks in Rust) and jump straight to the current module
1652 // Named implementations are handled separately. When we find a method
1653 // call, we consult the module node to find all of the implementations in
1654 // scope. This information is lazily cached in the module node. We then
1655 // generate a fake "implementation scope" containing all the
1656 // implementations thus found, for compatibility with old resolve pass.
1658 fn with_scope<F>(&mut self, id: NodeId, f: F)
1659 where F: FnOnce(&mut Resolver)
1661 let orig_module = self.current_module;
1663 // Move down in the graph.
1664 if let Some(module) = orig_module.module_children.borrow().get(&id) {
1665 self.current_module = module;
1670 self.current_module = orig_module;
1673 /// Searches the current set of local scopes for labels.
1674 /// Stops after meeting a closure.
1675 fn search_label(&self, name: Name) -> Option<DefLike> {
1676 for rib in self.label_ribs.iter().rev() {
1682 // Do not resolve labels across function boundary
1686 let result = rib.bindings.get(&name).cloned();
1687 if result.is_some() {
1694 fn resolve_crate(&mut self, krate: &hir::Crate) {
1695 debug!("(resolving crate) starting");
1697 intravisit::walk_crate(self, krate);
1700 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1701 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1702 span_err!(self.session,
1705 "user-defined types or type parameters cannot shadow the primitive types");
1709 fn resolve_item(&mut self, item: &Item) {
1710 let name = item.name;
1712 debug!("(resolving item) resolving {}", name);
1715 ItemEnum(_, ref generics) |
1716 ItemTy(_, ref generics) |
1717 ItemStruct(_, ref generics) => {
1718 self.check_if_primitive_type_name(name, item.span);
1720 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1721 |this| intravisit::walk_item(this, item));
1723 ItemFn(_, _, _, _, ref generics, _) => {
1724 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1725 |this| intravisit::walk_item(this, item));
1728 ItemDefaultImpl(_, ref trait_ref) => {
1729 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1731 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1732 self.resolve_implementation(generics,
1739 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1740 self.check_if_primitive_type_name(name, item.span);
1742 // Create a new rib for the trait-wide type parameters.
1743 self.with_type_parameter_rib(HasTypeParameters(generics,
1747 let local_def_id = this.ast_map.local_def_id(item.id);
1748 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1749 this.visit_generics(generics);
1750 walk_list!(this, visit_ty_param_bound, bounds);
1752 for trait_item in trait_items {
1753 match trait_item.node {
1754 hir::ConstTraitItem(_, ref default) => {
1755 // Only impose the restrictions of
1756 // ConstRibKind if there's an actual constant
1757 // expression in a provided default.
1758 if default.is_some() {
1759 this.with_constant_rib(|this| {
1760 intravisit::walk_trait_item(this, trait_item)
1763 intravisit::walk_trait_item(this, trait_item)
1766 hir::MethodTraitItem(ref sig, _) => {
1767 let type_parameters =
1768 HasTypeParameters(&sig.generics,
1771 this.with_type_parameter_rib(type_parameters, |this| {
1772 intravisit::walk_trait_item(this, trait_item)
1775 hir::TypeTraitItem(..) => {
1776 this.check_if_primitive_type_name(trait_item.name,
1778 this.with_type_parameter_rib(NoTypeParameters, |this| {
1779 intravisit::walk_trait_item(this, trait_item)
1788 ItemMod(_) | ItemForeignMod(_) => {
1789 self.with_scope(item.id, |this| {
1790 intravisit::walk_item(this, item);
1794 ItemConst(..) | ItemStatic(..) => {
1795 self.with_constant_rib(|this| {
1796 intravisit::walk_item(this, item);
1800 ItemUse(ref view_path) => {
1801 // check for imports shadowing primitive types
1802 let check_rename = |this: &Self, id, name| {
1803 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
1804 Some(Def::Enum(..)) | Some(Def::TyAlias(..)) | Some(Def::Struct(..)) |
1805 Some(Def::Trait(..)) | None => {
1806 this.check_if_primitive_type_name(name, item.span);
1812 match view_path.node {
1813 hir::ViewPathSimple(name, _) => {
1814 check_rename(self, item.id, name);
1816 hir::ViewPathList(ref prefix, ref items) => {
1818 if let Some(name) = item.node.rename() {
1819 check_rename(self, item.node.id(), name);
1823 // Resolve prefix of an import with empty braces (issue #28388)
1824 if items.is_empty() && !prefix.segments.is_empty() {
1825 match self.resolve_crate_relative_path(prefix.span,
1829 self.record_def(item.id, PathResolution::new(def, lp, 0)),
1833 ResolutionError::FailedToResolve(
1834 &path_names_to_string(prefix, 0)));
1835 self.record_def(item.id, err_path_resolution());
1844 ItemExternCrate(_) => {
1845 // do nothing, these are just around to be encoded
1850 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
1851 where F: FnOnce(&mut Resolver)
1853 match type_parameters {
1854 HasTypeParameters(generics, space, rib_kind) => {
1855 let mut function_type_rib = Rib::new(rib_kind);
1856 let mut seen_bindings = HashSet::new();
1857 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1858 let name = type_parameter.name;
1859 debug!("with_type_parameter_rib: {}", type_parameter.id);
1861 if seen_bindings.contains(&name) {
1863 type_parameter.span,
1864 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1866 seen_bindings.insert(name);
1868 // plain insert (no renaming)
1869 function_type_rib.bindings
1871 DlDef(Def::TyParam(space,
1874 .local_def_id(type_parameter.id),
1877 self.type_ribs.push(function_type_rib);
1880 NoTypeParameters => {
1887 match type_parameters {
1888 HasTypeParameters(..) => {
1890 self.type_ribs.pop();
1893 NoTypeParameters => {}
1897 fn with_label_rib<F>(&mut self, f: F)
1898 where F: FnOnce(&mut Resolver)
1900 self.label_ribs.push(Rib::new(NormalRibKind));
1903 self.label_ribs.pop();
1907 fn with_constant_rib<F>(&mut self, f: F)
1908 where F: FnOnce(&mut Resolver)
1910 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1911 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1914 self.type_ribs.pop();
1915 self.value_ribs.pop();
1919 fn resolve_function(&mut self, rib_kind: RibKind<'a>, declaration: &FnDecl, block: &Block) {
1920 // Create a value rib for the function.
1921 self.value_ribs.push(Rib::new(rib_kind));
1923 // Create a label rib for the function.
1924 self.label_ribs.push(Rib::new(rib_kind));
1926 // Add each argument to the rib.
1927 let mut bindings_list = HashMap::new();
1928 for argument in &declaration.inputs {
1929 self.resolve_pattern(&argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
1931 self.visit_ty(&argument.ty);
1933 debug!("(resolving function) recorded argument");
1935 intravisit::walk_fn_ret_ty(self, &declaration.output);
1937 // Resolve the function body.
1938 self.visit_block(block);
1940 debug!("(resolving function) leaving function");
1943 self.label_ribs.pop();
1944 self.value_ribs.pop();
1948 fn resolve_trait_reference(&mut self,
1952 -> Result<PathResolution, ()> {
1953 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
1954 if let Def::Trait(_) = path_res.base_def {
1955 debug!("(resolving trait) found trait def: {:?}", path_res);
1959 resolve_struct_error(self,
1961 ResolutionError::IsNotATrait(&path_names_to_string(trait_path,
1964 // If it's a typedef, give a note
1965 if let Def::TyAlias(..) = path_res.base_def {
1966 err.span_note(trait_path.span,
1967 "`type` aliases cannot be used for traits");
1975 ResolutionError::UndeclaredTraitName(&path_names_to_string(trait_path,
1981 fn resolve_generics(&mut self, generics: &Generics) {
1982 for type_parameter in generics.ty_params.iter() {
1983 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
1985 for predicate in &generics.where_clause.predicates {
1987 &hir::WherePredicate::BoundPredicate(_) |
1988 &hir::WherePredicate::RegionPredicate(_) => {}
1989 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1990 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
1991 if let Some(PathResolution { base_def: Def::TyParam(..), .. }) = path_res {
1992 self.record_def(eq_pred.id, path_res.unwrap());
1996 ResolutionError::UndeclaredAssociatedType);
1997 self.record_def(eq_pred.id, err_path_resolution());
2002 intravisit::walk_generics(self, generics);
2005 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2006 where F: FnOnce(&mut Resolver) -> T
2008 // Handle nested impls (inside fn bodies)
2009 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2010 let result = f(self);
2011 self.current_self_type = previous_value;
2015 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2016 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2018 let mut new_val = None;
2019 let mut new_id = None;
2020 if let Some(trait_ref) = opt_trait_ref {
2021 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2024 assert!(path_res.depth == 0);
2025 self.record_def(trait_ref.ref_id, path_res);
2026 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2027 new_id = Some(path_res.base_def.def_id());
2029 self.record_def(trait_ref.ref_id, err_path_resolution());
2031 intravisit::walk_trait_ref(self, trait_ref);
2033 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2034 let result = f(self, new_id);
2035 self.current_trait_ref = original_trait_ref;
2039 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2040 where F: FnOnce(&mut Resolver)
2042 let mut self_type_rib = Rib::new(NormalRibKind);
2044 // plain insert (no renaming, types are not currently hygienic....)
2045 let name = special_names::type_self;
2046 self_type_rib.bindings.insert(name, DlDef(self_def));
2047 self.type_ribs.push(self_type_rib);
2050 self.type_ribs.pop();
2054 fn resolve_implementation(&mut self,
2055 generics: &Generics,
2056 opt_trait_reference: &Option<TraitRef>,
2059 impl_items: &[ImplItem]) {
2060 // If applicable, create a rib for the type parameters.
2061 self.with_type_parameter_rib(HasTypeParameters(generics,
2065 // Resolve the type parameters.
2066 this.visit_generics(generics);
2068 // Resolve the trait reference, if necessary.
2069 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2070 // Resolve the self type.
2071 this.visit_ty(self_type);
2073 this.with_self_rib(Def::SelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2074 this.with_current_self_type(self_type, |this| {
2075 for impl_item in impl_items {
2076 match impl_item.node {
2077 hir::ImplItemKind::Const(..) => {
2078 // If this is a trait impl, ensure the const
2080 this.check_trait_item(impl_item.name,
2082 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2083 this.with_constant_rib(|this| {
2084 intravisit::walk_impl_item(this, impl_item);
2087 hir::ImplItemKind::Method(ref sig, _) => {
2088 // If this is a trait impl, ensure the method
2090 this.check_trait_item(impl_item.name,
2092 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2094 // We also need a new scope for the method-
2095 // specific type parameters.
2096 let type_parameters =
2097 HasTypeParameters(&sig.generics,
2100 this.with_type_parameter_rib(type_parameters, |this| {
2101 intravisit::walk_impl_item(this, impl_item);
2104 hir::ImplItemKind::Type(ref ty) => {
2105 // If this is a trait impl, ensure the type
2107 this.check_trait_item(impl_item.name,
2109 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2121 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2122 where F: FnOnce(Name, &str) -> ResolutionError
2124 // If there is a TraitRef in scope for an impl, then the method must be in the
2126 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2127 if !self.trait_item_map.contains_key(&(name, did)) {
2128 let path_str = path_names_to_string(&trait_ref.path, 0);
2129 resolve_error(self, span, err(name, &path_str));
2134 fn resolve_local(&mut self, local: &Local) {
2135 // Resolve the type.
2136 walk_list!(self, visit_ty, &local.ty);
2138 // Resolve the initializer.
2139 walk_list!(self, visit_expr, &local.init);
2141 // Resolve the pattern.
2142 self.resolve_pattern(&local.pat, LocalIrrefutableMode, &mut HashMap::new());
2145 // build a map from pattern identifiers to binding-info's.
2146 // this is done hygienically. This could arise for a macro
2147 // that expands into an or-pattern where one 'x' was from the
2148 // user and one 'x' came from the macro.
2149 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2150 let mut result = HashMap::new();
2151 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2152 let name = path1.node;
2156 binding_mode: binding_mode,
2162 // check that all of the arms in an or-pattern have exactly the
2163 // same set of bindings, with the same binding modes for each.
2164 fn check_consistent_bindings(&mut self, arm: &Arm) {
2165 if arm.pats.is_empty() {
2168 let map_0 = self.binding_mode_map(&arm.pats[0]);
2169 for (i, p) in arm.pats.iter().enumerate() {
2170 let map_i = self.binding_mode_map(&p);
2172 for (&key, &binding_0) in &map_0 {
2173 match map_i.get(&key) {
2177 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2179 Some(binding_i) => {
2180 if binding_0.binding_mode != binding_i.binding_mode {
2183 ResolutionError::VariableBoundWithDifferentMode(key,
2190 for (&key, &binding) in &map_i {
2191 if !map_0.contains_key(&key) {
2194 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2200 fn resolve_arm(&mut self, arm: &Arm) {
2201 self.value_ribs.push(Rib::new(NormalRibKind));
2203 let mut bindings_list = HashMap::new();
2204 for pattern in &arm.pats {
2205 self.resolve_pattern(&pattern, RefutableMode, &mut bindings_list);
2208 // This has to happen *after* we determine which
2209 // pat_idents are variants
2210 self.check_consistent_bindings(arm);
2212 walk_list!(self, visit_expr, &arm.guard);
2213 self.visit_expr(&arm.body);
2216 self.value_ribs.pop();
2220 fn resolve_block(&mut self, block: &Block) {
2221 debug!("(resolving block) entering block");
2222 // Move down in the graph, if there's an anonymous module rooted here.
2223 let orig_module = self.current_module;
2224 let anonymous_module =
2225 orig_module.module_children.borrow().get(&block.id).map(|module| *module);
2227 if let Some(anonymous_module) = anonymous_module {
2228 debug!("(resolving block) found anonymous module, moving down");
2229 self.value_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2230 self.type_ribs.push(Rib::new(AnonymousModuleRibKind(anonymous_module)));
2231 self.current_module = anonymous_module;
2233 self.value_ribs.push(Rib::new(NormalRibKind));
2236 // Descend into the block.
2237 intravisit::walk_block(self, block);
2241 self.current_module = orig_module;
2242 self.value_ribs.pop();
2243 if let Some(_) = anonymous_module {
2244 self.type_ribs.pop();
2247 debug!("(resolving block) leaving block");
2250 fn resolve_type(&mut self, ty: &Ty) {
2252 TyPath(ref maybe_qself, ref path) => {
2253 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2254 maybe_qself.as_ref(),
2258 // `<T>::a::b::c` is resolved by typeck alone.
2259 TypecheckRequired => {
2260 // Resolve embedded types.
2261 intravisit::walk_ty(self, ty);
2264 ResolveAttempt(resolution) => resolution,
2267 // This is a path in the type namespace. Walk through scopes
2271 // Write the result into the def map.
2272 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2273 path_names_to_string(path, 0),
2276 self.record_def(ty.id, def);
2279 self.record_def(ty.id, err_path_resolution());
2281 // Keep reporting some errors even if they're ignored above.
2282 self.resolve_path(ty.id, path, 0, TypeNS, true);
2284 let kind = if maybe_qself.is_some() {
2290 let self_type_name = special_idents::type_self.name;
2291 let is_invalid_self_type_name = path.segments.len() > 0 &&
2292 maybe_qself.is_none() &&
2293 path.segments[0].identifier.name ==
2295 if is_invalid_self_type_name {
2298 ResolutionError::SelfUsedOutsideImplOrTrait);
2302 ResolutionError::UseOfUndeclared(
2304 &path_names_to_string(path,
2313 // Resolve embedded types.
2314 intravisit::walk_ty(self, ty);
2317 fn resolve_pattern(&mut self,
2319 mode: PatternBindingMode,
2320 // Maps idents to the node ID for the (outermost)
2321 // pattern that binds them
2322 bindings_list: &mut HashMap<Name, NodeId>) {
2323 let pat_id = pattern.id;
2324 walk_pat(pattern, |pattern| {
2325 match pattern.node {
2326 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2327 // The meaning of PatIdent with no type parameters
2328 // depends on whether an enum variant or unit-like struct
2329 // with that name is in scope. The probing lookup has to
2330 // be careful not to emit spurious errors. Only matching
2331 // patterns (match) can match nullary variants or
2332 // unit-like structs. For binding patterns (let
2333 // and the LHS of @-patterns), matching such a value is
2334 // simply disallowed (since it's rarely what you want).
2335 let const_ok = mode == RefutableMode && at_rhs.is_none();
2337 let ident = path1.node;
2338 let renamed = ident.name;
2340 match self.resolve_bare_identifier_pattern(ident.unhygienic_name,
2342 FoundStructOrEnumVariant(def, lp) if const_ok => {
2343 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2346 self.enforce_default_binding_mode(pattern,
2349 self.record_def(pattern.id,
2356 FoundStructOrEnumVariant(..) => {
2360 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2363 self.record_def(pattern.id, err_path_resolution());
2365 FoundConst(def, lp, _) if const_ok => {
2366 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2368 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2369 self.record_def(pattern.id,
2376 FoundConst(def, _, name) => {
2380 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2383 self.record_def(pattern.id, err_path_resolution());
2385 BareIdentifierPatternUnresolved => {
2386 debug!("(resolving pattern) binding `{}`", renamed);
2388 let def_id = self.ast_map.local_def_id(pattern.id);
2389 let def = Def::Local(def_id, pattern.id);
2391 // Record the definition so that later passes
2392 // will be able to distinguish variants from
2393 // locals in patterns.
2395 self.record_def(pattern.id,
2398 last_private: LastMod(AllPublic),
2402 // Add the binding to the local ribs, if it
2403 // doesn't already exist in the bindings list. (We
2404 // must not add it if it's in the bindings list
2405 // because that breaks the assumptions later
2406 // passes make about or-patterns.)
2407 if !bindings_list.contains_key(&renamed) {
2408 let this = &mut *self;
2409 let last_rib = this.value_ribs.last_mut().unwrap();
2410 last_rib.bindings.insert(renamed, DlDef(def));
2411 bindings_list.insert(renamed, pat_id);
2412 } else if mode == ArgumentIrrefutableMode &&
2413 bindings_list.contains_key(&renamed) {
2414 // Forbid duplicate bindings in the same
2419 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2420 &ident.name.as_str())
2422 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2423 // Then this is a duplicate variable in the
2424 // same disjunction, which is an error.
2428 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2429 &ident.name.as_str())
2432 // Else, not bound in the same pattern: do
2438 PatEnum(ref path, _) => {
2439 // This must be an enum variant, struct or const.
2440 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2445 // The below shouldn't happen because all
2446 // qualified paths should be in PatQPath.
2447 TypecheckRequired =>
2448 self.session.span_bug(path.span,
2449 "resolve_possibly_assoc_item claimed
2451 that a path in PatEnum requires typecheck
2453 to resolve, but qualified paths should be
2456 ResolveAttempt(resolution) => resolution,
2458 if let Some(path_res) = resolution {
2459 match path_res.base_def {
2460 Def::Struct(..) if path_res.depth == 0 => {
2461 self.record_def(pattern.id, path_res);
2463 Def::Variant(..) | Def::Const(..) => {
2464 self.record_def(pattern.id, path_res);
2466 Def::Static(..) => {
2467 resolve_error(&self,
2469 ResolutionError::StaticVariableReference);
2470 self.record_def(pattern.id, err_path_resolution());
2473 // If anything ends up here entirely resolved,
2474 // it's an error. If anything ends up here
2475 // partially resolved, that's OK, because it may
2476 // be a `T::CONST` that typeck will resolve.
2477 if path_res.depth == 0 {
2481 ResolutionError::NotAnEnumVariantStructOrConst(
2489 self.record_def(pattern.id, err_path_resolution());
2491 let const_name = path.segments
2496 let traits = self.get_traits_containing_item(const_name);
2497 self.trait_map.insert(pattern.id, traits);
2498 self.record_def(pattern.id, path_res);
2506 ResolutionError::UnresolvedEnumVariantStructOrConst(
2507 &path.segments.last().unwrap().identifier.name.as_str())
2509 self.record_def(pattern.id, err_path_resolution());
2511 intravisit::walk_path(self, path);
2514 PatQPath(ref qself, ref path) => {
2515 // Associated constants only.
2516 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2521 TypecheckRequired => {
2522 // All `<T>::CONST` should end up here, and will
2523 // require use of the trait map to resolve
2524 // during typechecking.
2525 let const_name = path.segments
2530 let traits = self.get_traits_containing_item(const_name);
2531 self.trait_map.insert(pattern.id, traits);
2532 intravisit::walk_pat(self, pattern);
2535 ResolveAttempt(resolution) => resolution,
2537 if let Some(path_res) = resolution {
2538 match path_res.base_def {
2539 // All `<T as Trait>::CONST` should end up here, and
2540 // have the trait already selected.
2541 Def::AssociatedConst(..) => {
2542 self.record_def(pattern.id, path_res);
2548 ResolutionError::NotAnAssociatedConst(
2549 &path.segments.last().unwrap().identifier.name.as_str()
2552 self.record_def(pattern.id, err_path_resolution());
2558 ResolutionError::UnresolvedAssociatedConst(&path.segments
2564 self.record_def(pattern.id, err_path_resolution());
2566 intravisit::walk_pat(self, pattern);
2569 PatStruct(ref path, _, _) => {
2570 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2571 Some(definition) => {
2572 self.record_def(pattern.id, definition);
2575 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2579 ResolutionError::DoesNotNameAStruct(
2580 &path_names_to_string(path, 0))
2582 self.record_def(pattern.id, err_path_resolution());
2585 intravisit::walk_path(self, path);
2588 PatLit(_) | PatRange(..) => {
2589 intravisit::walk_pat(self, pattern);
2600 fn resolve_bare_identifier_pattern(&mut self,
2603 -> BareIdentifierPatternResolution {
2604 let module = self.current_module;
2605 match self.resolve_item_in_lexical_scope(module, name, ValueNS, true) {
2606 Success(binding) => {
2607 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2610 match binding.def() {
2612 panic!("resolved name in the value namespace to a set of name bindings \
2615 // For the two success cases, this lookup can be
2616 // considered as not having a private component because
2617 // the lookup happened only within the current module.
2618 Some(def @ Def::Variant(..)) | Some(def @ Def::Struct(..)) => {
2619 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2621 Some(def @ Def::Const(..)) | Some(def @ Def::AssociatedConst(..)) => {
2622 return FoundConst(def, LastMod(AllPublic), name);
2624 Some(Def::Static(..)) => {
2625 resolve_error(self, span, ResolutionError::StaticVariableReference);
2626 return BareIdentifierPatternUnresolved;
2628 _ => return BareIdentifierPatternUnresolved
2632 Indeterminate => return BareIdentifierPatternUnresolved,
2635 Some((span, msg)) => {
2636 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2641 debug!("(resolve bare identifier pattern) failed to find {}", name);
2642 return BareIdentifierPatternUnresolved;
2647 /// Handles paths that may refer to associated items
2648 fn resolve_possibly_assoc_item(&mut self,
2650 maybe_qself: Option<&hir::QSelf>,
2652 namespace: Namespace,
2654 -> AssocItemResolveResult {
2655 let max_assoc_types;
2659 if qself.position == 0 {
2660 return TypecheckRequired;
2662 max_assoc_types = path.segments.len() - qself.position;
2663 // Make sure the trait is valid.
2664 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2667 max_assoc_types = path.segments.len();
2671 let mut resolution = self.with_no_errors(|this| {
2672 this.resolve_path(id, path, 0, namespace, check_ribs)
2674 for depth in 1..max_assoc_types {
2675 if resolution.is_some() {
2678 self.with_no_errors(|this| {
2679 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2682 if let Some(Def::Mod(_)) = resolution.map(|r| r.base_def) {
2683 // A module is not a valid type or value.
2686 ResolveAttempt(resolution)
2689 /// If `check_ribs` is true, checks the local definitions first; i.e.
2690 /// doesn't skip straight to the containing module.
2691 /// Skips `path_depth` trailing segments, which is also reflected in the
2692 /// returned value. See `middle::def::PathResolution` for more info.
2693 pub fn resolve_path(&mut self,
2697 namespace: Namespace,
2699 -> Option<PathResolution> {
2700 let span = path.span;
2701 let segments = &path.segments[..path.segments.len() - path_depth];
2703 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2706 let def = self.resolve_crate_relative_path(span, segments, namespace);
2707 return def.map(mk_res);
2710 // Try to find a path to an item in a module.
2711 let last_ident = segments.last().unwrap().identifier;
2712 if segments.len() <= 1 {
2713 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, true);
2714 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2716 PathResolution::new(def, LastMod(AllPublic), path_depth)
2720 let unqualified_def = self.resolve_identifier(last_ident, namespace, check_ribs, false);
2721 let def = self.resolve_module_relative_path(span, segments, namespace);
2722 match (def, unqualified_def) {
2723 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2725 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2728 "unnecessary qualification".to_string());
2736 // Resolve a single identifier
2737 fn resolve_identifier(&mut self,
2738 identifier: hir::Ident,
2739 namespace: Namespace,
2742 -> Option<LocalDef> {
2743 if identifier.name == special_idents::invalid.name {
2744 return Some(LocalDef::from_def(Def::Err));
2747 // First, check to see whether the name is a primitive type.
2748 if namespace == TypeNS {
2749 if let Some(&prim_ty) = self.primitive_type_table
2751 .get(&identifier.unhygienic_name) {
2752 return Some(LocalDef::from_def(Def::PrimTy(prim_ty)));
2757 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2763 let module = self.current_module;
2764 let name = identifier.unhygienic_name;
2765 match self.resolve_item_in_lexical_scope(module, name, namespace, record_used) {
2766 Success(binding) => binding.def().map(LocalDef::from_def),
2767 Failed(Some((span, msg))) => {
2768 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2775 // Resolve a local definition, potentially adjusting for closures.
2776 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2777 let ribs = match local_def.ribs {
2778 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2779 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2782 let mut def = local_def.def;
2785 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2787 Def::Local(_, node_id) => {
2790 NormalRibKind | AnonymousModuleRibKind(..) => {
2791 // Nothing to do. Continue.
2793 ClosureRibKind(function_id) => {
2795 let node_def_id = self.ast_map.local_def_id(node_id);
2797 let seen = self.freevars_seen
2799 .or_insert_with(|| NodeMap());
2800 if let Some(&index) = seen.get(&node_id) {
2801 def = Def::Upvar(node_def_id, node_id, index, function_id);
2804 let vec = self.freevars
2806 .or_insert_with(|| vec![]);
2807 let depth = vec.len();
2813 def = Def::Upvar(node_def_id, node_id, depth, function_id);
2814 seen.insert(node_id, depth);
2816 ItemRibKind | MethodRibKind => {
2817 // This was an attempt to access an upvar inside a
2818 // named function item. This is not allowed, so we
2822 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2825 ConstantItemRibKind => {
2826 // Still doesn't deal with upvars
2829 ResolutionError::AttemptToUseNonConstantValueInConstant);
2835 Def::TyParam(..) | Def::SelfTy(..) => {
2838 NormalRibKind | MethodRibKind | ClosureRibKind(..) |
2839 AnonymousModuleRibKind(..) => {
2840 // Nothing to do. Continue.
2843 // This was an attempt to use a type parameter outside
2848 ResolutionError::TypeParametersFromOuterFunction);
2851 ConstantItemRibKind => {
2853 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2864 // resolve a "module-relative" path, e.g. a::b::c
2865 fn resolve_module_relative_path(&mut self,
2867 segments: &[hir::PathSegment],
2868 namespace: Namespace)
2869 -> Option<(Def, LastPrivate)> {
2870 let module_path = segments.split_last()
2874 .map(|ps| ps.identifier.name)
2875 .collect::<Vec<_>>();
2877 let containing_module;
2879 let current_module = self.current_module;
2880 match self.resolve_module_path(current_module, &module_path, UseLexicalScope, span) {
2882 let (span, msg) = match err {
2883 Some((span, msg)) => (span, msg),
2885 let msg = format!("Use of undeclared type or module `{}`",
2886 names_to_string(&module_path));
2891 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2894 Indeterminate => return None,
2895 Success((resulting_module, resulting_last_private)) => {
2896 containing_module = resulting_module;
2897 last_private = resulting_last_private;
2901 let name = segments.last().unwrap().identifier.name;
2902 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2903 let def = match result {
2904 Success(binding) => {
2905 let (def, lp) = binding.def_and_lp();
2906 (def, last_private.or(lp))
2913 /// Invariant: This must be called only during main resolution, not during
2914 /// import resolution.
2915 fn resolve_crate_relative_path(&mut self,
2917 segments: &[hir::PathSegment],
2918 namespace: Namespace)
2919 -> Option<(Def, LastPrivate)> {
2920 let module_path = segments.split_last()
2924 .map(|ps| ps.identifier.name)
2925 .collect::<Vec<_>>();
2927 let root_module = self.graph_root;
2929 let containing_module;
2931 match self.resolve_module_path_from_root(root_module,
2935 LastMod(AllPublic)) {
2937 let (span, msg) = match err {
2938 Some((span, msg)) => (span, msg),
2940 let msg = format!("Use of undeclared module `::{}`",
2941 names_to_string(&module_path));
2946 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2950 Indeterminate => return None,
2952 Success((resulting_module, resulting_last_private)) => {
2953 containing_module = resulting_module;
2954 last_private = resulting_last_private;
2958 let name = segments.last().unwrap().identifier.name;
2959 match self.resolve_name_in_module(containing_module, name, namespace, false, true) {
2960 Success(binding) => {
2961 let (def, lp) = binding.def_and_lp();
2962 Some((def, last_private.or(lp)))
2968 fn resolve_identifier_in_local_ribs(&mut self,
2970 namespace: Namespace)
2971 -> Option<LocalDef> {
2972 // Check the local set of ribs.
2973 let name = match namespace { ValueNS => ident.name, TypeNS => ident.unhygienic_name };
2975 for i in (0 .. self.get_ribs(namespace).len()).rev() {
2976 if let Some(def_like) = self.get_ribs(namespace)[i].bindings.get(&name).cloned() {
2979 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
2983 return Some(LocalDef {
2984 ribs: Some((namespace, i)),
2989 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
2997 if let AnonymousModuleRibKind(module) = self.get_ribs(namespace)[i].kind {
2998 if let Success(binding) = self.resolve_name_in_module(module,
2999 ident.unhygienic_name,
3003 if let Some(def) = binding.def() {
3004 return Some(LocalDef::from_def(def));
3013 fn with_no_errors<T, F>(&mut self, f: F) -> T
3014 where F: FnOnce(&mut Resolver) -> T
3016 self.emit_errors = false;
3018 self.emit_errors = true;
3022 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3023 fn extract_path_and_node_id(t: &Ty,
3024 allow: FallbackChecks)
3025 -> Option<(Path, NodeId, FallbackChecks)> {
3027 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3028 TyPtr(ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, OnlyTraitAndStatics),
3029 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, allow),
3030 // This doesn't handle the remaining `Ty` variants as they are not
3031 // that commonly the self_type, it might be interesting to provide
3032 // support for those in future.
3037 fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
3039 name_path: &[ast::Name])
3040 -> Option<Module<'a>> {
3041 let root = this.current_module;
3042 let last_name = name_path.last().unwrap();
3044 if name_path.len() == 1 {
3045 match this.primitive_type_table.primitive_types.get(last_name) {
3047 None => this.current_module.resolve_name(*last_name, TypeNS, true).success()
3048 .and_then(NameBinding::module)
3051 match this.resolve_module_path(root, &name_path, UseLexicalScope, span) {
3052 Success((module, _)) => Some(module),
3058 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3059 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3060 let sig = match this.ast_map.get(node_id) {
3061 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3062 hir::MethodTraitItem(ref sig, _) => sig,
3065 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3066 hir::ImplItemKind::Method(ref sig, _) => sig,
3071 sig.explicit_self.node == hir::SelfStatic
3073 this.session.cstore.is_static_method(did)
3077 let (path, node_id, allowed) = match self.current_self_type {
3078 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3080 None => return NoSuggestion,
3082 None => return NoSuggestion,
3085 if allowed == Everything {
3086 // Look for a field with the same name in the current self_type.
3087 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3088 Some(Def::Enum(did)) |
3089 Some(Def::TyAlias(did)) |
3090 Some(Def::Struct(did)) |
3091 Some(Def::Variant(_, did)) => match self.structs.get(&did) {
3094 if fields.iter().any(|&field_name| name == field_name) {
3099 _ => {} // Self type didn't resolve properly
3103 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3105 // Look for a method in the current self type's impl module.
3106 if let Some(module) = get_module(self, path.span, &name_path) {
3107 if let Success(binding) = module.resolve_name(name, ValueNS, true) {
3108 if let Some(Def::Method(did)) = binding.def() {
3109 if is_static_method(self, did) {
3110 return StaticMethod(path_names_to_string(&path, 0));
3112 if self.current_trait_ref.is_some() {
3114 } else if allowed == Everything {
3121 // Look for a method in the current trait.
3122 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3123 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3124 if is_static_method(self, did) {
3125 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3135 fn find_best_match(&mut self, name: &str) -> SuggestionType {
3136 if let Some(macro_name) = self.session.available_macros
3137 .borrow().iter().find(|n| n.as_str() == name) {
3138 return SuggestionType::Macro(format!("{}!", macro_name));
3141 let names = self.value_ribs
3144 .flat_map(|rib| rib.bindings.keys());
3146 if let Some(found) = find_best_match_for_name(names, name, None) {
3148 return SuggestionType::Function(found);
3150 } SuggestionType::NotFound
3153 fn resolve_expr(&mut self, expr: &Expr) {
3154 // First, record candidate traits for this expression if it could
3155 // result in the invocation of a method call.
3157 self.record_candidate_traits_for_expr_if_necessary(expr);
3159 // Next, resolve the node.
3161 ExprPath(ref maybe_qself, ref path) => {
3162 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3163 maybe_qself.as_ref(),
3167 // `<T>::a::b::c` is resolved by typeck alone.
3168 TypecheckRequired => {
3169 let method_name = path.segments.last().unwrap().identifier.name;
3170 let traits = self.get_traits_containing_item(method_name);
3171 self.trait_map.insert(expr.id, traits);
3172 intravisit::walk_expr(self, expr);
3175 ResolveAttempt(resolution) => resolution,
3178 // This is a local path in the value namespace. Walk through
3179 // scopes looking for it.
3180 if let Some(path_res) = resolution {
3181 // Check if struct variant
3182 let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
3183 self.structs.contains_key(&variant_id)
3187 if is_struct_variant {
3188 let _ = self.structs.contains_key(&path_res.base_def.def_id());
3189 let path_name = path_names_to_string(path, 0);
3191 let mut err = resolve_struct_error(self,
3193 ResolutionError::StructVariantUsedAsFunction(&path_name));
3195 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3197 if self.emit_errors {
3198 err.fileline_help(expr.span, &msg);
3200 err.span_help(expr.span, &msg);
3203 self.record_def(expr.id, err_path_resolution());
3205 // Write the result into the def map.
3206 debug!("(resolving expr) resolved `{}`",
3207 path_names_to_string(path, 0));
3209 // Partial resolutions will need the set of traits in scope,
3210 // so they can be completed during typeck.
3211 if path_res.depth != 0 {
3212 let method_name = path.segments.last().unwrap().identifier.name;
3213 let traits = self.get_traits_containing_item(method_name);
3214 self.trait_map.insert(expr.id, traits);
3217 self.record_def(expr.id, path_res);
3220 // Be helpful if the name refers to a struct
3221 // (The pattern matching def_tys where the id is in self.structs
3222 // matches on regular structs while excluding tuple- and enum-like
3223 // structs, which wouldn't result in this error.)
3224 let path_name = path_names_to_string(path, 0);
3225 let type_res = self.with_no_errors(|this| {
3226 this.resolve_path(expr.id, path, 0, TypeNS, false)
3229 self.record_def(expr.id, err_path_resolution());
3230 match type_res.map(|r| r.base_def) {
3231 Some(Def::Struct(..)) => {
3232 let mut err = resolve_struct_error(self,
3234 ResolutionError::StructVariantUsedAsFunction(&path_name));
3236 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3238 if self.emit_errors {
3239 err.fileline_help(expr.span, &msg);
3241 err.span_help(expr.span, &msg);
3246 // Keep reporting some errors even if they're ignored above.
3247 self.resolve_path(expr.id, path, 0, ValueNS, true);
3249 let mut method_scope = false;
3250 self.value_ribs.iter().rev().all(|rib| {
3251 method_scope = match rib.kind {
3252 MethodRibKind => true,
3253 ItemRibKind | ConstantItemRibKind => false,
3254 _ => return true, // Keep advancing
3256 false // Stop advancing
3259 if method_scope && special_names::self_.as_str() == &path_name[..] {
3262 ResolutionError::SelfNotAvailableInStaticMethod);
3264 let last_name = path.segments.last().unwrap().identifier.name;
3265 let mut msg = match self.find_fallback_in_self_type(last_name) {
3267 // limit search to 5 to reduce the number
3268 // of stupid suggestions
3269 match self.find_best_match(&path_name) {
3270 SuggestionType::Macro(s) => {
3271 format!("the macro `{}`", s)
3273 SuggestionType::Function(s) => format!("`{}`", s),
3274 SuggestionType::NotFound => "".to_string(),
3277 Field => format!("`self.{}`", path_name),
3279 TraitItem => format!("to call `self.{}`", path_name),
3280 TraitMethod(path_str) |
3281 StaticMethod(path_str) =>
3282 format!("to call `{}::{}`", path_str, path_name),
3285 let mut context = UnresolvedNameContext::Other;
3286 if !msg.is_empty() {
3287 msg = format!(". Did you mean {}?", msg);
3289 // we check if this a module and if so, we display a help
3291 let name_path = path.segments.iter()
3292 .map(|seg| seg.identifier.name)
3293 .collect::<Vec<_>>();
3294 let current_module = self.current_module;
3296 match self.resolve_module_path(current_module,
3301 context = UnresolvedNameContext::PathIsMod(expr.id);
3309 ResolutionError::UnresolvedName(
3310 &path_name, &msg, context));
3316 intravisit::walk_expr(self, expr);
3319 ExprStruct(ref path, _, _) => {
3320 // Resolve the path to the structure it goes to. We don't
3321 // check to ensure that the path is actually a structure; that
3322 // is checked later during typeck.
3323 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3324 Some(definition) => self.record_def(expr.id, definition),
3326 debug!("(resolving expression) didn't find struct def",);
3330 ResolutionError::DoesNotNameAStruct(
3331 &path_names_to_string(path, 0))
3333 self.record_def(expr.id, err_path_resolution());
3337 intravisit::walk_expr(self, expr);
3340 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3341 self.with_label_rib(|this| {
3342 let def_like = DlDef(Def::Label(expr.id));
3345 let rib = this.label_ribs.last_mut().unwrap();
3346 rib.bindings.insert(label.name, def_like);
3349 intravisit::walk_expr(this, expr);
3353 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3354 match self.search_label(label.node.name) {
3356 self.record_def(expr.id, err_path_resolution());
3359 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3361 Some(DlDef(def @ Def::Label(_))) => {
3362 // Since this def is a label, it is never read.
3363 self.record_def(expr.id,
3366 last_private: LastMod(AllPublic),
3371 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3377 intravisit::walk_expr(self, expr);
3382 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3384 ExprField(_, name) => {
3385 // FIXME(#6890): Even though you can't treat a method like a
3386 // field, we need to add any trait methods we find that match
3387 // the field name so that we can do some nice error reporting
3388 // later on in typeck.
3389 let traits = self.get_traits_containing_item(name.node);
3390 self.trait_map.insert(expr.id, traits);
3392 ExprMethodCall(name, _, _) => {
3393 debug!("(recording candidate traits for expr) recording traits for {}",
3395 let traits = self.get_traits_containing_item(name.node);
3396 self.trait_map.insert(expr.id, traits);
3404 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3405 debug!("(getting traits containing item) looking for '{}'", name);
3407 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3408 debug!("(adding trait info) found trait {:?} for method '{}'",
3411 found_traits.push(trait_def_id);
3414 let mut found_traits = Vec::new();
3415 let mut search_module = self.current_module;
3417 // Look for the current trait.
3418 match self.current_trait_ref {
3419 Some((trait_def_id, _)) => {
3420 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3421 add_trait_info(&mut found_traits, trait_def_id, name);
3424 None => {} // Nothing to do.
3427 // Look for trait children.
3428 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3430 search_module.for_each_child(|_, ns, name_binding| {
3431 if ns != TypeNS { return }
3432 let trait_def_id = match name_binding.def() {
3433 Some(Def::Trait(trait_def_id)) => trait_def_id,
3434 Some(..) | None => return,
3436 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3437 add_trait_info(&mut found_traits, trait_def_id, name);
3438 let trait_name = self.get_trait_name(trait_def_id);
3439 self.record_use(trait_name, TypeNS, name_binding);
3443 // Look for shadowed traits.
3444 for binding in search_module.shadowed_traits.borrow().iter() {
3445 let did = binding.def().unwrap().def_id();
3446 if self.trait_item_map.contains_key(&(name, did)) {
3447 add_trait_info(&mut found_traits, did, name);
3448 let trait_name = self.get_trait_name(did);
3449 self.record_use(trait_name, TypeNS, binding);
3453 match search_module.parent_link {
3454 NoParentLink | ModuleParentLink(..) => break,
3455 BlockParentLink(parent_module, _) => {
3456 search_module = parent_module;
3464 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3465 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3466 assert!(match resolution.last_private {
3467 LastImport{..} => false,
3470 "Import should only be used for `use` directives");
3472 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3473 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3474 self.session.span_bug(span,
3475 &format!("path resolved multiple times ({:?} before, {:?} now)",
3481 fn enforce_default_binding_mode(&mut self,
3483 pat_binding_mode: BindingMode,
3485 match pat_binding_mode {
3486 BindByValue(_) => {}
3490 ResolutionError::CannotUseRefBindingModeWith(descr));
3497 fn names_to_string(names: &[Name]) -> String {
3498 let mut first = true;
3499 let mut result = String::new();
3504 result.push_str("::")
3506 result.push_str(&name.as_str());
3511 fn path_names_to_string(path: &Path, depth: usize) -> String {
3512 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3514 .map(|seg| seg.identifier.name)
3516 names_to_string(&names[..])
3519 /// A somewhat inefficient routine to obtain the name of a module.
3520 fn module_to_string<'a>(module: Module<'a>) -> String {
3521 let mut names = Vec::new();
3523 fn collect_mod<'a>(names: &mut Vec<ast::Name>, module: Module<'a>) {
3524 match module.parent_link {
3526 ModuleParentLink(ref module, name) => {
3528 collect_mod(names, module);
3530 BlockParentLink(ref module, _) => {
3531 // danger, shouldn't be ident?
3532 names.push(special_idents::opaque.name);
3533 collect_mod(names, module);
3537 collect_mod(&mut names, module);
3539 if names.is_empty() {
3540 return "???".to_string();
3542 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3545 fn err_path_resolution() -> PathResolution {
3548 last_private: LastMod(AllPublic),
3554 pub struct CrateMap {
3555 pub def_map: RefCell<DefMap>,
3556 pub freevars: FreevarMap,
3557 pub export_map: ExportMap,
3558 pub trait_map: TraitMap,
3559 pub external_exports: ExternalExports,
3560 pub glob_map: Option<GlobMap>,
3563 #[derive(PartialEq,Copy, Clone)]
3564 pub enum MakeGlobMap {
3569 /// Entry point to crate resolution.
3570 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3571 ast_map: &'a hir_map::Map<'tcx>,
3572 make_glob_map: MakeGlobMap)
3574 // Currently, we ignore the name resolution data structures for
3575 // the purposes of dependency tracking. Instead we will run name
3576 // resolution and include its output in the hash of each item,
3577 // much like we do for macro expansion. In other words, the hash
3578 // reflects not just its contents but the results of name
3579 // resolution on those contents. Hopefully we'll push this back at
3581 let _task = ast_map.dep_graph.in_task(DepNode::Resolve);
3583 let krate = ast_map.krate();
3584 let arenas = Resolver::arenas();
3585 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3587 resolver.resolve_crate(krate);
3589 check_unused::check_crate(&mut resolver, krate);
3592 def_map: resolver.def_map,
3593 freevars: resolver.freevars,
3594 export_map: resolver.export_map,
3595 trait_map: resolver.trait_map,
3596 external_exports: resolver.external_exports,
3597 glob_map: if resolver.make_glob_map {
3598 Some(resolver.glob_map)
3605 /// Builds a name resolution walker to be used within this module,
3606 /// or used externally, with an optional callback function.
3608 /// The callback takes a &mut bool which allows callbacks to end a
3609 /// walk when set to true, passing through the rest of the walk, while
3610 /// preserving the ribs + current module. This allows resolve_path
3611 /// calls to be made with the correct scope info. The node in the
3612 /// callback corresponds to the current node in the walk.
3613 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3614 ast_map: &'a hir_map::Map<'tcx>,
3616 make_glob_map: MakeGlobMap,
3617 arenas: &'a ResolverArenas<'a>,
3618 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3619 -> Resolver<'a, 'tcx> {
3620 let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
3622 resolver.callback = callback;
3624 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3626 resolve_imports::resolve_imports(&mut resolver);
3631 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }