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)]
30 extern crate syntax_pos;
31 extern crate rustc_errors as errors;
36 use self::Namespace::*;
37 use self::ResolveResult::*;
38 use self::FallbackSuggestion::*;
39 use self::TypeParameters::*;
41 use self::UseLexicalScopeFlag::*;
42 use self::ModulePrefixResult::*;
43 use self::ParentLink::*;
45 use rustc::hir::map::Definitions;
46 use rustc::hir::{self, PrimTy, TyBool, TyChar, TyFloat, TyInt, TyUint, TyStr};
47 use rustc::session::Session;
49 use rustc::hir::def::*;
50 use rustc::hir::def_id::DefId;
52 use rustc::ty::subst::{ParamSpace, FnSpace, TypeSpace};
53 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
54 use rustc::util::nodemap::{NodeMap, NodeSet, FnvHashMap, FnvHashSet};
56 use syntax::ext::mtwt;
57 use syntax::ast::{self, FloatTy};
58 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
59 use syntax::parse::token::{self, keywords};
60 use syntax::util::lev_distance::find_best_match_for_name;
62 use syntax::visit::{self, FnKind, Visitor};
63 use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind};
64 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, Generics};
65 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
66 use syntax::ast::{Local, Mutability, Pat, PatKind, Path};
67 use syntax::ast::{PathSegment, PathParameters, QSelf, TraitItemKind, TraitRef, Ty, TyKind};
70 use errors::DiagnosticBuilder;
72 use std::collections::{HashMap, HashSet};
73 use std::cell::{Cell, RefCell};
75 use std::mem::replace;
77 use resolve_imports::{ImportDirective, NameResolution};
79 // NB: This module needs to be declared first so diagnostics are
80 // registered before they are used.
84 mod build_reduced_graph;
89 Function(token::InternedString),
93 /// Candidates for a name resolution failure
94 struct SuggestedCandidates {
96 candidates: Vec<Path>,
99 enum ResolutionError<'a> {
100 /// error E0401: can't use type parameters from outer function
101 TypeParametersFromOuterFunction,
102 /// error E0402: cannot use an outer type parameter in this context
103 OuterTypeParameterContext,
104 /// error E0403: the name is already used for a type parameter in this type parameter list
105 NameAlreadyUsedInTypeParameterList(Name),
106 /// error E0404: is not a trait
107 IsNotATrait(&'a str),
108 /// error E0405: use of undeclared trait name
109 UndeclaredTraitName(&'a str, SuggestedCandidates),
110 /// error E0407: method is not a member of trait
111 MethodNotMemberOfTrait(Name, &'a str),
112 /// error E0437: type is not a member of trait
113 TypeNotMemberOfTrait(Name, &'a str),
114 /// error E0438: const is not a member of trait
115 ConstNotMemberOfTrait(Name, &'a str),
116 /// error E0408: variable `{}` from pattern #{} is not bound in pattern #{}
117 VariableNotBoundInPattern(Name, usize, usize),
118 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
119 VariableBoundWithDifferentMode(Name, usize),
120 /// error E0411: use of `Self` outside of an impl or trait
121 SelfUsedOutsideImplOrTrait,
122 /// error E0412: use of undeclared
123 UseOfUndeclared(&'a str, &'a str, SuggestedCandidates),
124 /// error E0415: identifier is bound more than once in this parameter list
125 IdentifierBoundMoreThanOnceInParameterList(&'a str),
126 /// error E0416: identifier is bound more than once in the same pattern
127 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
128 /// error E0422: does not name a struct
129 DoesNotNameAStruct(&'a str),
130 /// error E0423: is a struct variant name, but this expression uses it like a function name
131 StructVariantUsedAsFunction(&'a str),
132 /// error E0424: `self` is not available in a static method
133 SelfNotAvailableInStaticMethod,
134 /// error E0425: unresolved name
138 context: UnresolvedNameContext<'a>,
139 is_static_method: bool,
143 /// error E0426: use of undeclared label
144 UndeclaredLabel(&'a str),
145 /// error E0429: `self` imports are only allowed within a { } list
146 SelfImportsOnlyAllowedWithin,
147 /// error E0430: `self` import can only appear once in the list
148 SelfImportCanOnlyAppearOnceInTheList,
149 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
150 SelfImportOnlyInImportListWithNonEmptyPrefix,
151 /// error E0432: unresolved import
152 UnresolvedImport(Option<(&'a str, &'a str)>),
153 /// error E0433: failed to resolve
154 FailedToResolve(&'a str),
155 /// error E0434: can't capture dynamic environment in a fn item
156 CannotCaptureDynamicEnvironmentInFnItem,
157 /// error E0435: attempt to use a non-constant value in a constant
158 AttemptToUseNonConstantValueInConstant,
159 /// error E0530: X bindings cannot shadow Ys
160 BindingShadowsSomethingUnacceptable(&'a str, &'a str, Name),
161 /// error E0531: unresolved pattern path kind `name`
162 PatPathUnresolved(&'a str, &'a Path),
163 /// error E0532: expected pattern path kind, found another pattern path kind
164 PatPathUnexpected(&'a str, &'a str, &'a Path),
167 /// Context of where `ResolutionError::UnresolvedName` arose.
168 #[derive(Clone, PartialEq, Eq, Debug)]
169 enum UnresolvedNameContext<'a> {
170 /// `PathIsMod(parent)` indicates that a given path, used in
171 /// expression context, actually resolved to a module rather than
172 /// a value. The optional expression attached to the variant is the
173 /// the parent of the erroneous path expression.
174 PathIsMod(Option<&'a Expr>),
176 /// `Other` means we have no extra information about the context
177 /// of the unresolved name error. (Maybe we could eliminate all
178 /// such cases; but for now, this is an information-free default.)
182 fn resolve_error<'b, 'a: 'b, 'c>(resolver: &'b Resolver<'a>,
183 span: syntax_pos::Span,
184 resolution_error: ResolutionError<'c>) {
185 resolve_struct_error(resolver, span, resolution_error).emit();
188 fn resolve_struct_error<'b, 'a: 'b, 'c>(resolver: &'b Resolver<'a>,
189 span: syntax_pos::Span,
190 resolution_error: ResolutionError<'c>)
191 -> DiagnosticBuilder<'a> {
192 if !resolver.emit_errors {
193 return resolver.session.diagnostic().struct_dummy();
196 match resolution_error {
197 ResolutionError::TypeParametersFromOuterFunction => {
198 let mut err = struct_span_err!(resolver.session,
201 "can't use type parameters from outer function; \
202 try using a local type parameter instead");
203 err.span_label(span, &format!("use of type variable from outer function"));
206 ResolutionError::OuterTypeParameterContext => {
207 struct_span_err!(resolver.session,
210 "cannot use an outer type parameter in this context")
212 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
213 struct_span_err!(resolver.session,
216 "the name `{}` is already used for a type parameter in this type \
220 ResolutionError::IsNotATrait(name) => {
221 struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
223 ResolutionError::UndeclaredTraitName(name, candidates) => {
224 let mut err = struct_span_err!(resolver.session,
227 "trait `{}` is not in scope",
229 show_candidates(&mut err, &candidates);
230 err.span_label(span, &format!("`{}` is not in scope", name));
233 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
234 struct_span_err!(resolver.session,
237 "method `{}` is not a member of trait `{}`",
241 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
242 struct_span_err!(resolver.session,
245 "type `{}` is not a member of trait `{}`",
249 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
250 struct_span_err!(resolver.session,
253 "const `{}` is not a member of trait `{}`",
257 ResolutionError::VariableNotBoundInPattern(variable_name, from, to) => {
258 struct_span_err!(resolver.session,
261 "variable `{}` from pattern #{} is not bound in pattern #{}",
266 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
267 struct_span_err!(resolver.session,
270 "variable `{}` is bound with different mode in pattern #{} than in \
275 ResolutionError::SelfUsedOutsideImplOrTrait => {
276 let mut err = struct_span_err!(resolver.session,
279 "use of `Self` outside of an impl or trait");
280 err.span_label(span, &format!("used outside of impl or trait"));
283 ResolutionError::UseOfUndeclared(kind, name, candidates) => {
284 let mut err = struct_span_err!(resolver.session,
287 "{} `{}` is undefined or not in scope",
290 show_candidates(&mut err, &candidates);
291 err.span_label(span, &format!("undefined or not in scope"));
294 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
295 let mut err = struct_span_err!(resolver.session,
298 "identifier `{}` is bound more than once in this parameter list",
300 err.span_label(span, &format!("used as parameter more than once"));
303 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
304 let mut err = struct_span_err!(resolver.session,
307 "identifier `{}` is bound more than once in the same pattern",
309 err.span_label(span, &format!("used in a pattern more than once"));
312 ResolutionError::DoesNotNameAStruct(name) => {
313 struct_span_err!(resolver.session,
316 "`{}` does not name a structure",
319 ResolutionError::StructVariantUsedAsFunction(path_name) => {
320 struct_span_err!(resolver.session,
323 "`{}` is the name of a struct or struct variant, but this expression \
324 uses it like a function name",
327 ResolutionError::SelfNotAvailableInStaticMethod => {
328 struct_span_err!(resolver.session,
331 "`self` is not available in a static method. Maybe a `self` \
332 argument is missing?")
334 ResolutionError::UnresolvedName { path, message: msg, context, is_static_method,
336 let mut err = struct_span_err!(resolver.session,
339 "unresolved name `{}`{}",
343 UnresolvedNameContext::Other => {
344 if msg.is_empty() && is_static_method && is_field {
345 err.help("this is an associated function, you don't have access to \
346 this type's fields or methods");
349 UnresolvedNameContext::PathIsMod(parent) => {
350 err.help(&match parent.map(|parent| &parent.node) {
351 Some(&ExprKind::Field(_, ident)) => {
352 format!("to reference an item from the `{module}` module, \
353 use `{module}::{ident}`",
357 Some(&ExprKind::MethodCall(ident, _, _)) => {
358 format!("to call a function from the `{module}` module, \
359 use `{module}::{ident}(..)`",
364 format!("{def} `{module}` cannot be used as an expression",
365 def = def.kind_name(),
373 ResolutionError::UndeclaredLabel(name) => {
374 struct_span_err!(resolver.session,
377 "use of undeclared label `{}`",
380 ResolutionError::SelfImportsOnlyAllowedWithin => {
381 struct_span_err!(resolver.session,
385 "`self` imports are only allowed within a { } list")
387 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
388 struct_span_err!(resolver.session,
391 "`self` import can only appear once in the list")
393 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
394 struct_span_err!(resolver.session,
397 "`self` import can only appear in an import list with a \
400 ResolutionError::UnresolvedImport(name) => {
401 let msg = match name {
402 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
403 None => "unresolved import".to_owned(),
405 struct_span_err!(resolver.session, span, E0432, "{}", msg)
407 ResolutionError::FailedToResolve(msg) => {
408 struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
410 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
411 struct_span_err!(resolver.session,
415 "can't capture dynamic environment in a fn item; use the || { ... } \
416 closure form instead")
418 ResolutionError::AttemptToUseNonConstantValueInConstant => {
419 struct_span_err!(resolver.session,
422 "attempt to use a non-constant value in a constant")
424 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, shadows_what, name) => {
425 let mut err = struct_span_err!(resolver.session,
428 "{}s cannot shadow {}s", what_binding, shadows_what);
429 err.span_label(span, &format!("cannot be named the same as a {}", shadows_what));
430 if let Success(binding) = resolver.current_module.resolve_name(name, ValueNS, true) {
431 let participle = if binding.is_import() { "imported" } else { "defined" };
432 err.span_label(binding.span, &format!("a {} `{}` is {} here",
433 shadows_what, name, participle));
437 ResolutionError::PatPathUnresolved(expected_what, path) => {
438 struct_span_err!(resolver.session,
441 "unresolved {} `{}`",
443 path.segments.last().unwrap().identifier)
445 ResolutionError::PatPathUnexpected(expected_what, found_what, path) => {
446 struct_span_err!(resolver.session,
449 "expected {}, found {} `{}`",
452 path.segments.last().unwrap().identifier)
457 #[derive(Copy, Clone)]
460 binding_mode: BindingMode,
463 // Map from the name in a pattern to its binding mode.
464 type BindingMap = HashMap<Name, BindingInfo>;
466 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
477 fn is_refutable(self) -> bool {
479 PatternSource::Match | PatternSource::IfLet | PatternSource::WhileLet => true,
480 PatternSource::Let | PatternSource::For | PatternSource::FnParam => false,
483 fn descr(self) -> &'static str {
485 PatternSource::Match => "match binding",
486 PatternSource::IfLet => "if let binding",
487 PatternSource::WhileLet => "while let binding",
488 PatternSource::Let => "let binding",
489 PatternSource::For => "for binding",
490 PatternSource::FnParam => "function parameter",
495 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
501 impl<'a> Visitor for Resolver<'a> {
502 fn visit_item(&mut self, item: &Item) {
503 self.resolve_item(item);
505 fn visit_arm(&mut self, arm: &Arm) {
506 self.resolve_arm(arm);
508 fn visit_block(&mut self, block: &Block) {
509 self.resolve_block(block);
511 fn visit_expr(&mut self, expr: &Expr) {
512 self.resolve_expr(expr, None);
514 fn visit_local(&mut self, local: &Local) {
515 self.resolve_local(local);
517 fn visit_ty(&mut self, ty: &Ty) {
518 self.resolve_type(ty);
520 fn visit_poly_trait_ref(&mut self, tref: &ast::PolyTraitRef, m: &ast::TraitBoundModifier) {
521 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
522 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
524 // error already reported
525 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
528 visit::walk_poly_trait_ref(self, tref, m);
530 fn visit_variant(&mut self,
531 variant: &ast::Variant,
533 item_id: ast::NodeId) {
534 if let Some(ref dis_expr) = variant.node.disr_expr {
535 // resolve the discriminator expr as a constant
536 self.with_constant_rib(|this| {
537 this.visit_expr(dis_expr);
541 // `visit::walk_variant` without the discriminant expression.
542 self.visit_variant_data(&variant.node.data,
548 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
549 let type_parameters = match foreign_item.node {
550 ForeignItemKind::Fn(_, ref generics) => {
551 HasTypeParameters(generics, FnSpace, ItemRibKind)
553 ForeignItemKind::Static(..) => NoTypeParameters,
555 self.with_type_parameter_rib(type_parameters, |this| {
556 visit::walk_foreign_item(this, foreign_item);
559 fn visit_fn(&mut self,
560 function_kind: FnKind,
561 declaration: &FnDecl,
565 let rib_kind = match function_kind {
566 FnKind::ItemFn(_, generics, _, _, _, _) => {
567 self.visit_generics(generics);
570 FnKind::Method(_, sig, _) => {
571 self.visit_generics(&sig.generics);
572 MethodRibKind(!sig.decl.has_self())
574 FnKind::Closure => ClosureRibKind(node_id),
576 self.resolve_function(rib_kind, declaration, block);
580 pub type ErrorMessage = Option<(Span, String)>;
582 #[derive(Clone, PartialEq, Eq)]
583 pub enum ResolveResult<T> {
584 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
585 Indeterminate, // Couldn't determine due to unresolved globs.
586 Success(T), // Successfully resolved the import.
589 impl<T> ResolveResult<T> {
590 fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
592 Failed(msg) => Failed(msg),
593 Indeterminate => Indeterminate,
598 fn success(self) -> Option<T> {
600 Success(t) => Some(t),
606 enum FallbackSuggestion {
613 #[derive(Copy, Clone)]
614 enum TypeParameters<'a, 'b> {
616 HasTypeParameters(// Type parameters.
619 // Identifies the things that these parameters
620 // were declared on (type, fn, etc)
623 // The kind of the rib used for type parameters.
627 // The rib kind controls the translation of local
628 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
629 #[derive(Copy, Clone, Debug)]
631 // No translation needs to be applied.
634 // We passed through a closure scope at the given node ID.
635 // Translate upvars as appropriate.
636 ClosureRibKind(NodeId /* func id */),
638 // We passed through an impl or trait and are now in one of its
639 // methods. Allow references to ty params that impl or trait
640 // binds. Disallow any other upvars (including other ty params that are
643 // The boolean value represents the fact that this method is static or not.
646 // We passed through an item scope. Disallow upvars.
649 // We're in a constant item. Can't refer to dynamic stuff.
652 // We passed through a module.
653 ModuleRibKind(Module<'a>),
656 #[derive(Copy, Clone)]
657 enum UseLexicalScopeFlag {
662 enum ModulePrefixResult<'a> {
664 PrefixFound(Module<'a>, usize),
670 bindings: HashMap<Name, Def>,
675 fn new(kind: RibKind<'a>) -> Rib<'a> {
677 bindings: HashMap::new(),
683 /// A definition along with the index of the rib it was found on
685 ribs: Option<(Namespace, usize)>,
690 fn from_def(def: Def) -> Self {
698 enum LexicalScopeBinding<'a> {
699 Item(&'a NameBinding<'a>),
703 impl<'a> LexicalScopeBinding<'a> {
704 fn local_def(self) -> LocalDef {
706 LexicalScopeBinding::LocalDef(local_def) => local_def,
707 LexicalScopeBinding::Item(binding) => LocalDef::from_def(binding.def().unwrap()),
711 fn module(self) -> Option<Module<'a>> {
713 LexicalScopeBinding::Item(binding) => binding.module(),
719 /// The link from a module up to its nearest parent node.
720 #[derive(Clone,Debug)]
721 enum ParentLink<'a> {
723 ModuleParentLink(Module<'a>, Name),
724 BlockParentLink(Module<'a>, NodeId),
727 /// One node in the tree of modules.
728 pub struct ModuleS<'a> {
729 parent_link: ParentLink<'a>,
732 // If the module is an extern crate, `def` is root of the external crate and `extern_crate_id`
733 // is the NodeId of the local `extern crate` item (otherwise, `extern_crate_id` is None).
734 extern_crate_id: Option<NodeId>,
736 resolutions: RefCell<HashMap<(Name, Namespace), &'a RefCell<NameResolution<'a>>>>,
737 unresolved_imports: RefCell<Vec<&'a ImportDirective<'a>>>,
739 no_implicit_prelude: Cell<bool>,
741 glob_importers: RefCell<Vec<(Module<'a>, &'a ImportDirective<'a>)>>,
742 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
744 // Used to memoize the traits in this module for faster searches through all traits in scope.
745 traits: RefCell<Option<Box<[(Name, &'a NameBinding<'a>)]>>>,
747 // Whether this module is populated. If not populated, any attempt to
748 // access the children must be preceded with a
749 // `populate_module_if_necessary` call.
750 populated: Cell<bool>,
752 arenas: &'a ResolverArenas<'a>,
755 pub type Module<'a> = &'a ModuleS<'a>;
757 impl<'a> ModuleS<'a> {
758 fn new(parent_link: ParentLink<'a>,
761 arenas: &'a ResolverArenas<'a>) -> Self {
763 parent_link: parent_link,
765 extern_crate_id: None,
766 resolutions: RefCell::new(HashMap::new()),
767 unresolved_imports: RefCell::new(Vec::new()),
768 no_implicit_prelude: Cell::new(false),
769 glob_importers: RefCell::new(Vec::new()),
770 globs: RefCell::new((Vec::new())),
771 traits: RefCell::new(None),
772 populated: Cell::new(!external),
777 fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
778 for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
779 name_resolution.borrow().binding.map(|binding| f(name, ns, binding));
783 fn def_id(&self) -> Option<DefId> {
784 self.def.as_ref().map(Def::def_id)
787 // `self` resolves to the first module ancestor that `is_normal`.
788 fn is_normal(&self) -> bool {
790 Some(Def::Mod(_)) => true,
795 fn is_trait(&self) -> bool {
797 Some(Def::Trait(_)) => true,
803 impl<'a> fmt::Debug for ModuleS<'a> {
804 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
805 write!(f, "{:?}", self.def)
809 // Records a possibly-private value, type, or module definition.
810 #[derive(Clone, Debug)]
811 pub struct NameBinding<'a> {
812 kind: NameBindingKind<'a>,
817 #[derive(Clone, Debug)]
818 enum NameBindingKind<'a> {
822 binding: &'a NameBinding<'a>,
823 directive: &'a ImportDirective<'a>,
824 // Some(error) if using this imported name causes the import to be a privacy error
825 privacy_error: Option<Box<PrivacyError<'a>>>,
829 #[derive(Clone, Debug)]
830 struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);
832 impl<'a> NameBinding<'a> {
833 fn module(&self) -> Option<Module<'a>> {
835 NameBindingKind::Module(module) => Some(module),
836 NameBindingKind::Def(_) => None,
837 NameBindingKind::Import { binding, .. } => binding.module(),
841 fn def(&self) -> Option<Def> {
843 NameBindingKind::Def(def) => Some(def),
844 NameBindingKind::Module(module) => module.def,
845 NameBindingKind::Import { binding, .. } => binding.def(),
849 fn is_pseudo_public(&self) -> bool {
850 self.pseudo_vis() == ty::Visibility::Public
853 // We sometimes need to treat variants as `pub` for backwards compatibility
854 fn pseudo_vis(&self) -> ty::Visibility {
855 if self.is_variant() { ty::Visibility::Public } else { self.vis }
858 fn is_variant(&self) -> bool {
860 NameBindingKind::Def(Def::Variant(..)) => true,
865 fn is_extern_crate(&self) -> bool {
866 self.module().and_then(|module| module.extern_crate_id).is_some()
869 fn is_import(&self) -> bool {
871 NameBindingKind::Import { .. } => true,
876 fn is_glob_import(&self) -> bool {
878 NameBindingKind::Import { directive, .. } => directive.is_glob(),
883 fn is_importable(&self) -> bool {
884 match self.def().unwrap() {
885 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
891 /// Interns the names of the primitive types.
892 struct PrimitiveTypeTable {
893 primitive_types: HashMap<Name, PrimTy>,
896 impl PrimitiveTypeTable {
897 fn new() -> PrimitiveTypeTable {
898 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
900 table.intern("bool", TyBool);
901 table.intern("char", TyChar);
902 table.intern("f32", TyFloat(FloatTy::F32));
903 table.intern("f64", TyFloat(FloatTy::F64));
904 table.intern("isize", TyInt(IntTy::Is));
905 table.intern("i8", TyInt(IntTy::I8));
906 table.intern("i16", TyInt(IntTy::I16));
907 table.intern("i32", TyInt(IntTy::I32));
908 table.intern("i64", TyInt(IntTy::I64));
909 table.intern("str", TyStr);
910 table.intern("usize", TyUint(UintTy::Us));
911 table.intern("u8", TyUint(UintTy::U8));
912 table.intern("u16", TyUint(UintTy::U16));
913 table.intern("u32", TyUint(UintTy::U32));
914 table.intern("u64", TyUint(UintTy::U64));
919 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
920 self.primitive_types.insert(token::intern(string), primitive_type);
924 /// The main resolver class.
925 pub struct Resolver<'a> {
926 session: &'a Session,
928 definitions: &'a mut Definitions,
930 graph_root: Module<'a>,
932 prelude: Option<Module<'a>>,
934 trait_item_map: FnvHashMap<(Name, DefId), bool /* is static method? */>,
936 structs: FnvHashMap<DefId, Vec<Name>>,
938 // The number of imports that are currently unresolved.
939 unresolved_imports: usize,
941 // The module that represents the current item scope.
942 current_module: Module<'a>,
944 // The current set of local scopes, for values.
945 // FIXME #4948: Reuse ribs to avoid allocation.
946 value_ribs: Vec<Rib<'a>>,
948 // The current set of local scopes, for types.
949 type_ribs: Vec<Rib<'a>>,
951 // The current set of local scopes, for labels.
952 label_ribs: Vec<Rib<'a>>,
954 // The trait that the current context can refer to.
955 current_trait_ref: Option<(DefId, TraitRef)>,
957 // The current self type if inside an impl (used for better errors).
958 current_self_type: Option<Ty>,
960 // The idents for the primitive types.
961 primitive_type_table: PrimitiveTypeTable,
964 pub freevars: FreevarMap,
965 freevars_seen: NodeMap<NodeMap<usize>>,
966 pub export_map: ExportMap,
967 pub trait_map: TraitMap,
969 // A map from nodes to modules, both normal (`mod`) modules and anonymous modules.
970 // Anonymous modules are pseudo-modules that are implicitly created around items
971 // contained within blocks.
973 // For example, if we have this:
981 // There will be an anonymous module created around `g` with the ID of the
982 // entry block for `f`.
983 module_map: NodeMap<Module<'a>>,
985 // Whether or not to print error messages. Can be set to true
986 // when getting additional info for error message suggestions,
987 // so as to avoid printing duplicate errors
990 pub make_glob_map: bool,
991 // Maps imports to the names of items actually imported (this actually maps
992 // all imports, but only glob imports are actually interesting).
993 pub glob_map: GlobMap,
995 used_imports: HashSet<(NodeId, Namespace)>,
996 used_crates: HashSet<CrateNum>,
997 pub maybe_unused_trait_imports: NodeSet,
999 privacy_errors: Vec<PrivacyError<'a>>,
1001 arenas: &'a ResolverArenas<'a>,
1004 struct ResolverArenas<'a> {
1005 modules: arena::TypedArena<ModuleS<'a>>,
1006 local_modules: RefCell<Vec<Module<'a>>>,
1007 name_bindings: arena::TypedArena<NameBinding<'a>>,
1008 import_directives: arena::TypedArena<ImportDirective<'a>>,
1009 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1012 impl<'a> ResolverArenas<'a> {
1013 fn alloc_module(&'a self, module: ModuleS<'a>) -> Module<'a> {
1014 let module = self.modules.alloc(module);
1015 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1016 self.local_modules.borrow_mut().push(module);
1020 fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1021 self.local_modules.borrow()
1023 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1024 self.name_bindings.alloc(name_binding)
1026 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1027 -> &'a ImportDirective {
1028 self.import_directives.alloc(import_directive)
1030 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1031 self.name_resolutions.alloc(Default::default())
1035 impl<'a> ty::NodeIdTree for Resolver<'a> {
1036 fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool {
1037 let ancestor = self.definitions.local_def_id(ancestor);
1038 let mut module = *self.module_map.get(&node).unwrap();
1039 while module.def_id() != Some(ancestor) {
1040 let module_parent = match self.get_nearest_normal_module_parent(module) {
1041 Some(parent) => parent,
1042 None => return false,
1044 module = module_parent;
1050 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1051 fn resolve_generated_global_path(&mut self, path: &hir::Path, is_value: bool) -> Def {
1052 let namespace = if is_value { ValueNS } else { TypeNS };
1053 match self.resolve_crate_relative_path(path.span, &path.segments, namespace) {
1054 Ok(binding) => binding.def().unwrap(),
1055 Err(true) => Def::Err,
1057 let path_name = &format!("{}", path);
1059 ResolutionError::UnresolvedName {
1062 context: UnresolvedNameContext::Other,
1063 is_static_method: false,
1067 resolve_error(self, path.span, error);
1073 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1074 self.def_map.get(&id).cloned()
1077 fn record_resolution(&mut self, id: NodeId, def: Def) {
1078 self.def_map.insert(id, PathResolution::new(def));
1081 fn definitions(&mut self) -> Option<&mut Definitions> {
1082 Some(self.definitions)
1087 fn name(&self) -> Name;
1090 impl Named for ast::PathSegment {
1091 fn name(&self) -> Name {
1092 self.identifier.name
1096 impl Named for hir::PathSegment {
1097 fn name(&self) -> Name {
1102 impl<'a> Resolver<'a> {
1103 fn new(session: &'a Session,
1104 definitions: &'a mut Definitions,
1105 make_glob_map: MakeGlobMap,
1106 arenas: &'a ResolverArenas<'a>)
1108 let root_def_id = definitions.local_def_id(CRATE_NODE_ID);
1110 ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, arenas);
1111 let graph_root = arenas.alloc_module(graph_root);
1112 let mut module_map = NodeMap();
1113 module_map.insert(CRATE_NODE_ID, graph_root);
1118 definitions: definitions,
1120 // The outermost module has def ID 0; this is not reflected in the
1122 graph_root: graph_root,
1125 trait_item_map: FnvHashMap(),
1126 structs: FnvHashMap(),
1128 unresolved_imports: 0,
1130 current_module: graph_root,
1131 value_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
1132 type_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
1133 label_ribs: Vec::new(),
1135 current_trait_ref: None,
1136 current_self_type: None,
1138 primitive_type_table: PrimitiveTypeTable::new(),
1141 freevars: NodeMap(),
1142 freevars_seen: NodeMap(),
1143 export_map: NodeMap(),
1144 trait_map: NodeMap(),
1145 module_map: module_map,
1148 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1149 glob_map: NodeMap(),
1151 used_imports: HashSet::new(),
1152 used_crates: HashSet::new(),
1153 maybe_unused_trait_imports: NodeSet(),
1155 privacy_errors: Vec::new(),
1161 fn arenas() -> ResolverArenas<'a> {
1163 modules: arena::TypedArena::new(),
1164 local_modules: RefCell::new(Vec::new()),
1165 name_bindings: arena::TypedArena::new(),
1166 import_directives: arena::TypedArena::new(),
1167 name_resolutions: arena::TypedArena::new(),
1171 fn new_module(&self, parent_link: ParentLink<'a>, def: Option<Def>, external: bool)
1173 self.arenas.alloc_module(ModuleS::new(parent_link, def, external, self.arenas))
1176 fn new_extern_crate_module(&self, parent_link: ParentLink<'a>, def: Def, local_node_id: NodeId)
1178 let mut module = ModuleS::new(parent_link, Some(def), false, self.arenas);
1179 module.extern_crate_id = Some(local_node_id);
1180 self.arenas.modules.alloc(module)
1183 fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
1184 match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
1188 fn record_use(&mut self, name: Name, binding: &'a NameBinding<'a>) {
1189 // track extern crates for unused_extern_crate lint
1190 if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
1191 self.used_crates.insert(krate);
1194 let (directive, privacy_error) = match binding.kind {
1195 NameBindingKind::Import { directive, ref privacy_error, .. } =>
1196 (directive, privacy_error),
1200 if let Some(error) = privacy_error.as_ref() {
1201 self.privacy_errors.push((**error).clone());
1204 if !self.make_glob_map {
1207 if self.glob_map.contains_key(&directive.id) {
1208 self.glob_map.get_mut(&directive.id).unwrap().insert(name);
1212 let mut new_set = FnvHashSet();
1213 new_set.insert(name);
1214 self.glob_map.insert(directive.id, new_set);
1217 /// Resolves the given module path from the given root `module_`.
1218 fn resolve_module_path_from_root(&mut self,
1219 module_: Module<'a>,
1220 module_path: &[Name],
1223 -> ResolveResult<Module<'a>> {
1224 fn search_parent_externals(needle: Name, module: Module) -> Option<Module> {
1225 match module.resolve_name(needle, TypeNS, false) {
1226 Success(binding) if binding.is_extern_crate() => Some(module),
1227 _ => match module.parent_link {
1228 ModuleParentLink(ref parent, _) => {
1229 search_parent_externals(needle, parent)
1236 let mut search_module = module_;
1237 let mut index = index;
1238 let module_path_len = module_path.len();
1240 // Resolve the module part of the path. This does not involve looking
1241 // upward though scope chains; we simply resolve names directly in
1242 // modules as we go.
1243 while index < module_path_len {
1244 let name = module_path[index];
1245 match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1247 let segment_name = name.as_str();
1248 let module_name = module_to_string(search_module);
1249 let msg = if "???" == &module_name {
1250 match search_parent_externals(name, &self.current_module) {
1252 let path_str = names_to_string(module_path);
1253 let target_mod_str = module_to_string(&module);
1254 let current_mod_str = module_to_string(&self.current_module);
1256 let prefix = if target_mod_str == current_mod_str {
1257 "self::".to_string()
1259 format!("{}::", target_mod_str)
1262 format!("Did you mean `{}{}`?", prefix, path_str)
1264 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1267 format!("Could not find `{}` in `{}`", segment_name, module_name)
1270 return Failed(Some((span, msg)));
1272 Failed(err) => return Failed(err),
1274 debug!("(resolving module path for import) module resolution is \
1277 return Indeterminate;
1279 Success(binding) => {
1280 // Check to see whether there are type bindings, and, if
1281 // so, whether there is a module within.
1282 if let Some(module_def) = binding.module() {
1283 self.check_privacy(name, binding, span);
1284 search_module = module_def;
1286 let msg = format!("Not a module `{}`", name);
1287 return Failed(Some((span, msg)));
1295 return Success(search_module);
1298 /// Attempts to resolve the module part of an import directive or path
1299 /// rooted at the given module.
1300 fn resolve_module_path(&mut self,
1301 module_path: &[Name],
1302 use_lexical_scope: UseLexicalScopeFlag,
1304 -> ResolveResult<Module<'a>> {
1305 if module_path.len() == 0 {
1306 return Success(self.graph_root) // Use the crate root
1309 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1310 names_to_string(module_path),
1311 module_to_string(self.current_module));
1313 // Resolve the module prefix, if any.
1314 let module_prefix_result = self.resolve_module_prefix(module_path, span);
1318 match module_prefix_result {
1319 Failed(err) => return Failed(err),
1321 debug!("(resolving module path for import) indeterminate; bailing");
1322 return Indeterminate;
1324 Success(NoPrefixFound) => {
1325 // There was no prefix, so we're considering the first element
1326 // of the path. How we handle this depends on whether we were
1327 // instructed to use lexical scope or not.
1328 match use_lexical_scope {
1329 DontUseLexicalScope => {
1330 // This is a crate-relative path. We will start the
1331 // resolution process at index zero.
1332 search_module = self.graph_root;
1335 UseLexicalScope => {
1336 // This is not a crate-relative path. We resolve the
1337 // first component of the path in the current lexical
1338 // scope and then proceed to resolve below that.
1339 let ident = ast::Ident::with_empty_ctxt(module_path[0]);
1340 match self.resolve_ident_in_lexical_scope(ident, TypeNS, true)
1341 .and_then(LexicalScopeBinding::module) {
1342 None => return Failed(None),
1343 Some(containing_module) => {
1344 search_module = containing_module;
1351 Success(PrefixFound(ref containing_module, index)) => {
1352 search_module = containing_module;
1353 start_index = index;
1357 self.resolve_module_path_from_root(search_module,
1363 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
1364 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
1365 /// `ident` in the first scope that defines it (or None if no scopes define it).
1367 /// A block's items are above its local variables in the scope hierarchy, regardless of where
1368 /// the items are defined in the block. For example,
1371 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
1374 /// g(); // This resolves to the local variable `g` since it shadows the item.
1378 /// Invariant: This must only be called during main resolution, not during
1379 /// import resolution.
1380 fn resolve_ident_in_lexical_scope(&mut self,
1384 -> Option<LexicalScopeBinding<'a>> {
1385 let name = match ns { ValueNS => mtwt::resolve(ident), TypeNS => ident.name };
1387 // Walk backwards up the ribs in scope.
1388 for i in (0 .. self.get_ribs(ns).len()).rev() {
1389 if let Some(def) = self.get_ribs(ns)[i].bindings.get(&name).cloned() {
1390 // The ident resolves to a type parameter or local variable.
1391 return Some(LexicalScopeBinding::LocalDef(LocalDef {
1392 ribs: Some((ns, i)),
1397 if let ModuleRibKind(module) = self.get_ribs(ns)[i].kind {
1398 let name = ident.name;
1399 let item = self.resolve_name_in_module(module, name, ns, true, record_used);
1400 if let Success(binding) = item {
1401 // The ident resolves to an item.
1402 return Some(LexicalScopeBinding::Item(binding));
1405 // We can only see through anonymous modules
1406 if module.def.is_some() {
1407 return match self.prelude {
1408 Some(prelude) if !module.no_implicit_prelude.get() => {
1409 prelude.resolve_name(name, ns, false).success()
1410 .map(LexicalScopeBinding::Item)
1421 /// Returns the nearest normal module parent of the given module.
1422 fn get_nearest_normal_module_parent(&self, module_: Module<'a>) -> Option<Module<'a>> {
1423 let mut module_ = module_;
1425 match module_.parent_link {
1426 NoParentLink => return None,
1427 ModuleParentLink(new_module, _) |
1428 BlockParentLink(new_module, _) => {
1429 let new_module = new_module;
1430 if new_module.is_normal() {
1431 return Some(new_module);
1433 module_ = new_module;
1439 /// Returns the nearest normal module parent of the given module, or the
1440 /// module itself if it is a normal module.
1441 fn get_nearest_normal_module_parent_or_self(&self, module_: Module<'a>) -> Module<'a> {
1442 if module_.is_normal() {
1445 match self.get_nearest_normal_module_parent(module_) {
1447 Some(new_module) => new_module,
1451 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1452 /// (b) some chain of `super::`.
1453 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1454 fn resolve_module_prefix(&mut self, module_path: &[Name], span: Span)
1455 -> ResolveResult<ModulePrefixResult<'a>> {
1456 // Start at the current module if we see `self` or `super`, or at the
1457 // top of the crate otherwise.
1458 let mut i = match &*module_path[0].as_str() {
1461 _ => return Success(NoPrefixFound),
1463 let module_ = self.current_module;
1464 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1466 // Now loop through all the `super`s we find.
1467 while i < module_path.len() && "super" == module_path[i].as_str() {
1468 debug!("(resolving module prefix) resolving `super` at {}",
1469 module_to_string(&containing_module));
1470 match self.get_nearest_normal_module_parent(containing_module) {
1472 let msg = "There are too many initial `super`s.".into();
1473 return Failed(Some((span, msg)));
1475 Some(new_module) => {
1476 containing_module = new_module;
1482 debug!("(resolving module prefix) finished resolving prefix at {}",
1483 module_to_string(&containing_module));
1485 return Success(PrefixFound(containing_module, i));
1488 /// Attempts to resolve the supplied name in the given module for the
1489 /// given namespace. If successful, returns the binding corresponding to
1491 fn resolve_name_in_module(&mut self,
1494 namespace: Namespace,
1495 use_lexical_scope: bool,
1497 -> ResolveResult<&'a NameBinding<'a>> {
1498 debug!("(resolving name in module) resolving `{}` in `{}`", name, module_to_string(module));
1500 self.populate_module_if_necessary(module);
1501 module.resolve_name(name, namespace, use_lexical_scope).and_then(|binding| {
1503 if let NameBindingKind::Import { directive, .. } = binding.kind {
1504 self.used_imports.insert((directive.id, namespace));
1506 self.record_use(name, binding);
1514 // We maintain a list of value ribs and type ribs.
1516 // Simultaneously, we keep track of the current position in the module
1517 // graph in the `current_module` pointer. When we go to resolve a name in
1518 // the value or type namespaces, we first look through all the ribs and
1519 // then query the module graph. When we resolve a name in the module
1520 // namespace, we can skip all the ribs (since nested modules are not
1521 // allowed within blocks in Rust) and jump straight to the current module
1524 // Named implementations are handled separately. When we find a method
1525 // call, we consult the module node to find all of the implementations in
1526 // scope. This information is lazily cached in the module node. We then
1527 // generate a fake "implementation scope" containing all the
1528 // implementations thus found, for compatibility with old resolve pass.
1530 fn with_scope<F>(&mut self, id: NodeId, f: F)
1531 where F: FnOnce(&mut Resolver)
1533 let module = self.module_map.get(&id).cloned(); // clones a reference
1534 if let Some(module) = module {
1535 // Move down in the graph.
1536 let orig_module = ::std::mem::replace(&mut self.current_module, module);
1537 self.value_ribs.push(Rib::new(ModuleRibKind(module)));
1538 self.type_ribs.push(Rib::new(ModuleRibKind(module)));
1542 self.current_module = orig_module;
1543 self.value_ribs.pop();
1544 self.type_ribs.pop();
1550 /// Searches the current set of local scopes for labels.
1551 /// Stops after meeting a closure.
1552 fn search_label(&self, name: Name) -> Option<Def> {
1553 for rib in self.label_ribs.iter().rev() {
1559 // Do not resolve labels across function boundary
1563 let result = rib.bindings.get(&name).cloned();
1564 if result.is_some() {
1571 fn resolve_crate(&mut self, krate: &Crate) {
1572 debug!("(resolving crate) starting");
1573 self.current_module = self.graph_root;
1574 visit::walk_crate(self, krate);
1577 fn resolve_item(&mut self, item: &Item) {
1578 let name = item.ident.name;
1580 debug!("(resolving item) resolving {}", name);
1583 ItemKind::Enum(_, ref generics) |
1584 ItemKind::Ty(_, ref generics) |
1585 ItemKind::Struct(_, ref generics) => {
1586 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1587 |this| visit::walk_item(this, item));
1589 ItemKind::Fn(_, _, _, _, ref generics, _) => {
1590 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1591 |this| visit::walk_item(this, item));
1594 ItemKind::DefaultImpl(_, ref trait_ref) => {
1595 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1597 ItemKind::Impl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
1598 self.resolve_implementation(generics,
1604 ItemKind::Trait(_, ref generics, ref bounds, ref trait_items) => {
1605 // Create a new rib for the trait-wide type parameters.
1606 self.with_type_parameter_rib(HasTypeParameters(generics,
1610 let local_def_id = this.definitions.local_def_id(item.id);
1611 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1612 this.visit_generics(generics);
1613 walk_list!(this, visit_ty_param_bound, bounds);
1615 for trait_item in trait_items {
1616 match trait_item.node {
1617 TraitItemKind::Const(_, ref default) => {
1618 // Only impose the restrictions of
1619 // ConstRibKind if there's an actual constant
1620 // expression in a provided default.
1621 if default.is_some() {
1622 this.with_constant_rib(|this| {
1623 visit::walk_trait_item(this, trait_item)
1626 visit::walk_trait_item(this, trait_item)
1629 TraitItemKind::Method(ref sig, _) => {
1630 let type_parameters =
1631 HasTypeParameters(&sig.generics,
1633 MethodRibKind(!sig.decl.has_self()));
1634 this.with_type_parameter_rib(type_parameters, |this| {
1635 visit::walk_trait_item(this, trait_item)
1638 TraitItemKind::Type(..) => {
1639 this.with_type_parameter_rib(NoTypeParameters, |this| {
1640 visit::walk_trait_item(this, trait_item)
1643 TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1650 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1651 self.with_scope(item.id, |this| {
1652 visit::walk_item(this, item);
1656 ItemKind::Const(..) | ItemKind::Static(..) => {
1657 self.with_constant_rib(|this| {
1658 visit::walk_item(this, item);
1662 ItemKind::Use(ref view_path) => {
1663 match view_path.node {
1664 ast::ViewPathList(ref prefix, ref items) => {
1665 // Resolve prefix of an import with empty braces (issue #28388)
1666 if items.is_empty() && !prefix.segments.is_empty() {
1667 match self.resolve_crate_relative_path(prefix.span,
1671 let def = binding.def().unwrap();
1672 self.record_def(item.id, PathResolution::new(def));
1674 Err(true) => self.record_def(item.id, err_path_resolution()),
1678 ResolutionError::FailedToResolve(
1679 &path_names_to_string(prefix, 0)));
1680 self.record_def(item.id, err_path_resolution());
1689 ItemKind::ExternCrate(_) => {
1690 // do nothing, these are just around to be encoded
1693 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
1697 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
1698 where F: FnOnce(&mut Resolver)
1700 match type_parameters {
1701 HasTypeParameters(generics, space, rib_kind) => {
1702 let mut function_type_rib = Rib::new(rib_kind);
1703 let mut seen_bindings = HashSet::new();
1704 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1705 let name = type_parameter.ident.name;
1706 debug!("with_type_parameter_rib: {}", type_parameter.id);
1708 if seen_bindings.contains(&name) {
1710 type_parameter.span,
1711 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1713 seen_bindings.insert(name);
1715 // plain insert (no renaming)
1716 let def_id = self.definitions.local_def_id(type_parameter.id);
1717 let def = Def::TyParam(space, index as u32, def_id, name);
1718 function_type_rib.bindings.insert(name, def);
1720 self.type_ribs.push(function_type_rib);
1723 NoTypeParameters => {
1730 if let HasTypeParameters(..) = type_parameters {
1731 self.type_ribs.pop();
1735 fn with_label_rib<F>(&mut self, f: F)
1736 where F: FnOnce(&mut Resolver)
1738 self.label_ribs.push(Rib::new(NormalRibKind));
1740 self.label_ribs.pop();
1743 fn with_constant_rib<F>(&mut self, f: F)
1744 where F: FnOnce(&mut Resolver)
1746 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1747 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1749 self.type_ribs.pop();
1750 self.value_ribs.pop();
1753 fn resolve_function(&mut self,
1754 rib_kind: RibKind<'a>,
1755 declaration: &FnDecl,
1757 // Create a value rib for the function.
1758 self.value_ribs.push(Rib::new(rib_kind));
1760 // Create a label rib for the function.
1761 self.label_ribs.push(Rib::new(rib_kind));
1763 // Add each argument to the rib.
1764 let mut bindings_list = HashMap::new();
1765 for argument in &declaration.inputs {
1766 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
1768 self.visit_ty(&argument.ty);
1770 debug!("(resolving function) recorded argument");
1772 visit::walk_fn_ret_ty(self, &declaration.output);
1774 // Resolve the function body.
1775 self.visit_block(block);
1777 debug!("(resolving function) leaving function");
1779 self.label_ribs.pop();
1780 self.value_ribs.pop();
1783 fn resolve_trait_reference(&mut self,
1787 -> Result<PathResolution, ()> {
1788 self.resolve_path(id, trait_path, path_depth, TypeNS).and_then(|path_res| {
1789 if let Def::Trait(_) = path_res.base_def {
1790 debug!("(resolving trait) found trait def: {:?}", path_res);
1794 resolve_struct_error(self,
1796 ResolutionError::IsNotATrait(&path_names_to_string(trait_path,
1799 // If it's a typedef, give a note
1800 if let Def::TyAlias(..) = path_res.base_def {
1801 let trait_name = trait_path.segments.last().unwrap().identifier.name;
1802 err.span_label(trait_path.span,
1803 &format!("`{}` is not a trait", trait_name));
1805 let definition_site = {
1806 let segments = &trait_path.segments;
1807 if trait_path.global {
1808 self.resolve_crate_relative_path(trait_path.span, segments, TypeNS)
1810 self.resolve_module_relative_path(trait_path.span, segments, TypeNS)
1811 }.map(|binding| binding.span).unwrap_or(syntax_pos::DUMMY_SP)
1814 if definition_site != syntax_pos::DUMMY_SP {
1815 err.span_label(definition_site,
1816 &format!("type aliases cannot be used for traits"));
1822 }).map_err(|error_reported| {
1823 if error_reported { return }
1825 // find possible candidates
1826 let trait_name = trait_path.segments.last().unwrap().identifier.name;
1828 self.lookup_candidates(
1832 Def::Trait(_) => true,
1837 // create error object
1838 let name = &path_names_to_string(trait_path, path_depth);
1840 ResolutionError::UndeclaredTraitName(
1845 resolve_error(self, trait_path.span, error);
1849 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
1850 where F: FnOnce(&mut Resolver) -> T
1852 // Handle nested impls (inside fn bodies)
1853 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
1854 let result = f(self);
1855 self.current_self_type = previous_value;
1859 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
1860 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
1862 let mut new_val = None;
1863 let mut new_id = None;
1864 if let Some(trait_ref) = opt_trait_ref {
1865 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
1868 assert!(path_res.depth == 0);
1869 self.record_def(trait_ref.ref_id, path_res);
1870 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
1871 new_id = Some(path_res.base_def.def_id());
1873 self.record_def(trait_ref.ref_id, err_path_resolution());
1875 visit::walk_trait_ref(self, trait_ref);
1877 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1878 let result = f(self, new_id);
1879 self.current_trait_ref = original_trait_ref;
1883 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
1884 where F: FnOnce(&mut Resolver)
1886 let mut self_type_rib = Rib::new(NormalRibKind);
1888 // plain insert (no renaming, types are not currently hygienic....)
1889 self_type_rib.bindings.insert(keywords::SelfType.name(), self_def);
1890 self.type_ribs.push(self_type_rib);
1892 self.type_ribs.pop();
1895 fn resolve_implementation(&mut self,
1896 generics: &Generics,
1897 opt_trait_reference: &Option<TraitRef>,
1900 impl_items: &[ImplItem]) {
1901 // If applicable, create a rib for the type parameters.
1902 self.with_type_parameter_rib(HasTypeParameters(generics,
1906 // Resolve the type parameters.
1907 this.visit_generics(generics);
1909 // Resolve the trait reference, if necessary.
1910 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1911 // Resolve the self type.
1912 this.visit_ty(self_type);
1914 this.with_self_rib(Def::SelfTy(trait_id, Some(item_id)), |this| {
1915 this.with_current_self_type(self_type, |this| {
1916 for impl_item in impl_items {
1917 this.resolve_visibility(&impl_item.vis);
1918 match impl_item.node {
1919 ImplItemKind::Const(..) => {
1920 // If this is a trait impl, ensure the const
1922 this.check_trait_item(impl_item.ident.name,
1924 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
1925 visit::walk_impl_item(this, impl_item);
1927 ImplItemKind::Method(ref sig, _) => {
1928 // If this is a trait impl, ensure the method
1930 this.check_trait_item(impl_item.ident.name,
1932 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
1934 // We also need a new scope for the method-
1935 // specific type parameters.
1936 let type_parameters =
1937 HasTypeParameters(&sig.generics,
1939 MethodRibKind(!sig.decl.has_self()));
1940 this.with_type_parameter_rib(type_parameters, |this| {
1941 visit::walk_impl_item(this, impl_item);
1944 ImplItemKind::Type(ref ty) => {
1945 // If this is a trait impl, ensure the type
1947 this.check_trait_item(impl_item.ident.name,
1949 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
1953 ImplItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1962 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
1963 where F: FnOnce(Name, &str) -> ResolutionError
1965 // If there is a TraitRef in scope for an impl, then the method must be in the
1967 if let Some((did, ref trait_ref)) = self.current_trait_ref {
1968 if !self.trait_item_map.contains_key(&(name, did)) {
1969 let path_str = path_names_to_string(&trait_ref.path, 0);
1970 resolve_error(self, span, err(name, &path_str));
1975 fn resolve_local(&mut self, local: &Local) {
1976 // Resolve the type.
1977 walk_list!(self, visit_ty, &local.ty);
1979 // Resolve the initializer.
1980 walk_list!(self, visit_expr, &local.init);
1982 // Resolve the pattern.
1983 self.resolve_pattern(&local.pat, PatternSource::Let, &mut HashMap::new());
1986 // build a map from pattern identifiers to binding-info's.
1987 // this is done hygienically. This could arise for a macro
1988 // that expands into an or-pattern where one 'x' was from the
1989 // user and one 'x' came from the macro.
1990 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1991 let mut binding_map = HashMap::new();
1993 pat.walk(&mut |pat| {
1994 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
1995 if sub_pat.is_some() || match self.def_map.get(&pat.id) {
1996 Some(&PathResolution { base_def: Def::Local(..), .. }) => true,
1999 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2000 binding_map.insert(mtwt::resolve(ident.node), binding_info);
2009 // check that all of the arms in an or-pattern have exactly the
2010 // same set of bindings, with the same binding modes for each.
2011 fn check_consistent_bindings(&mut self, arm: &Arm) {
2012 if arm.pats.is_empty() {
2015 let map_0 = self.binding_mode_map(&arm.pats[0]);
2016 for (i, p) in arm.pats.iter().enumerate() {
2017 let map_i = self.binding_mode_map(&p);
2019 for (&key, &binding_0) in &map_0 {
2020 match map_i.get(&key) {
2024 ResolutionError::VariableNotBoundInPattern(key, 1, i + 1));
2026 Some(binding_i) => {
2027 if binding_0.binding_mode != binding_i.binding_mode {
2030 ResolutionError::VariableBoundWithDifferentMode(key,
2037 for (&key, &binding) in &map_i {
2038 if !map_0.contains_key(&key) {
2041 ResolutionError::VariableNotBoundInPattern(key, i + 1, 1));
2047 fn resolve_arm(&mut self, arm: &Arm) {
2048 self.value_ribs.push(Rib::new(NormalRibKind));
2050 let mut bindings_list = HashMap::new();
2051 for pattern in &arm.pats {
2052 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2055 // This has to happen *after* we determine which
2056 // pat_idents are variants
2057 self.check_consistent_bindings(arm);
2059 walk_list!(self, visit_expr, &arm.guard);
2060 self.visit_expr(&arm.body);
2062 self.value_ribs.pop();
2065 fn resolve_block(&mut self, block: &Block) {
2066 debug!("(resolving block) entering block");
2067 // Move down in the graph, if there's an anonymous module rooted here.
2068 let orig_module = self.current_module;
2069 let anonymous_module = self.module_map.get(&block.id).cloned(); // clones a reference
2071 if let Some(anonymous_module) = anonymous_module {
2072 debug!("(resolving block) found anonymous module, moving down");
2073 self.value_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
2074 self.type_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
2075 self.current_module = anonymous_module;
2077 self.value_ribs.push(Rib::new(NormalRibKind));
2080 // Descend into the block.
2081 visit::walk_block(self, block);
2084 self.current_module = orig_module;
2085 self.value_ribs.pop();
2086 if let Some(_) = anonymous_module {
2087 self.type_ribs.pop();
2089 debug!("(resolving block) leaving block");
2092 fn resolve_type(&mut self, ty: &Ty) {
2094 TyKind::Path(ref maybe_qself, ref path) => {
2095 // This is a path in the type namespace. Walk through scopes
2097 if let Some(def) = self.resolve_possibly_assoc_item(ty.id, maybe_qself.as_ref(),
2099 match def.base_def {
2100 Def::Mod(..) if def.depth == 0 => {
2101 self.session.span_err(path.span, "expected type, found module");
2102 self.record_def(ty.id, err_path_resolution());
2105 // Write the result into the def map.
2106 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2107 path_names_to_string(path, 0), ty.id, def);
2108 self.record_def(ty.id, def);
2112 self.record_def(ty.id, err_path_resolution());
2114 // Keep reporting some errors even if they're ignored above.
2115 if let Err(true) = self.resolve_path(ty.id, path, 0, TypeNS) {
2116 // `resolve_path` already reported the error
2118 let kind = if maybe_qself.is_some() {
2124 let is_invalid_self_type_name = path.segments.len() > 0 &&
2125 maybe_qself.is_none() &&
2126 path.segments[0].identifier.name ==
2127 keywords::SelfType.name();
2128 if is_invalid_self_type_name {
2131 ResolutionError::SelfUsedOutsideImplOrTrait);
2133 let segment = path.segments.last();
2134 let segment = segment.expect("missing name in path");
2135 let type_name = segment.identifier.name;
2138 self.lookup_candidates(
2145 Def::TyAlias(_) => true,
2150 // create error object
2151 let name = &path_names_to_string(path, 0);
2153 ResolutionError::UseOfUndeclared(
2159 resolve_error(self, ty.span, error);
2166 // Resolve embedded types.
2167 visit::walk_ty(self, ty);
2170 fn fresh_binding(&mut self,
2171 ident: &ast::SpannedIdent,
2173 outer_pat_id: NodeId,
2174 pat_src: PatternSource,
2175 bindings: &mut HashMap<Name, NodeId>)
2177 // Add the binding to the local ribs, if it
2178 // doesn't already exist in the bindings map. (We
2179 // must not add it if it's in the bindings map
2180 // because that breaks the assumptions later
2181 // passes make about or-patterns.)
2182 let renamed = mtwt::resolve(ident.node);
2183 let def = match bindings.get(&renamed).cloned() {
2184 Some(id) if id == outer_pat_id => {
2185 // `Variant(a, a)`, error
2189 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2190 &ident.node.name.as_str())
2194 Some(..) if pat_src == PatternSource::FnParam => {
2195 // `fn f(a: u8, a: u8)`, error
2199 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2200 &ident.node.name.as_str())
2204 Some(..) if pat_src == PatternSource::Match => {
2205 // `Variant1(a) | Variant2(a)`, ok
2206 // Reuse definition from the first `a`.
2207 self.value_ribs.last_mut().unwrap().bindings[&renamed]
2210 span_bug!(ident.span, "two bindings with the same name from \
2211 unexpected pattern source {:?}", pat_src);
2214 // A completely fresh binding, add to the lists.
2215 // FIXME: Later stages are not ready to deal with `Def::Err` here yet, so
2216 // define `Invalid` bindings as `Def::Local`, just don't add them to the lists.
2217 let def = Def::Local(self.definitions.local_def_id(pat_id), pat_id);
2218 if ident.node.name != keywords::Invalid.name() {
2219 bindings.insert(renamed, outer_pat_id);
2220 self.value_ribs.last_mut().unwrap().bindings.insert(renamed, def);
2226 PathResolution::new(def)
2229 fn resolve_pattern_path<ExpectedFn>(&mut self,
2231 qself: Option<&QSelf>,
2233 namespace: Namespace,
2234 expected_fn: ExpectedFn,
2235 expected_what: &str)
2236 where ExpectedFn: FnOnce(Def) -> bool
2238 let resolution = if let Some(resolution) = self.resolve_possibly_assoc_item(pat_id,
2239 qself, path, namespace) {
2240 if resolution.depth == 0 {
2241 if expected_fn(resolution.base_def) {
2247 ResolutionError::PatPathUnexpected(expected_what,
2248 resolution.kind_name(), path)
2250 err_path_resolution()
2253 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
2254 // or `<T>::A::B`. If `B` should be resolved in value namespace then
2255 // it needs to be added to the trait map.
2256 if namespace == ValueNS {
2257 let item_name = path.segments.last().unwrap().identifier.name;
2258 let traits = self.get_traits_containing_item(item_name);
2259 self.trait_map.insert(pat_id, traits);
2264 if let Err(false) = self.resolve_path(pat_id, path, 0, namespace) {
2268 ResolutionError::PatPathUnresolved(expected_what, path)
2271 err_path_resolution()
2274 self.record_def(pat_id, resolution);
2277 fn resolve_pattern(&mut self,
2279 pat_src: PatternSource,
2280 // Maps idents to the node ID for the
2281 // outermost pattern that binds them.
2282 bindings: &mut HashMap<Name, NodeId>) {
2283 // Visit all direct subpatterns of this pattern.
2284 let outer_pat_id = pat.id;
2285 pat.walk(&mut |pat| {
2287 PatKind::Ident(bmode, ref ident, ref opt_pat) => {
2288 // First try to resolve the identifier as some existing
2289 // entity, then fall back to a fresh binding.
2290 let resolution = if let Ok(resolution) = self.resolve_path(pat.id,
2291 &Path::from_ident(ident.span, ident.node), 0, ValueNS) {
2292 let always_binding = !pat_src.is_refutable() || opt_pat.is_some() ||
2293 bmode != BindingMode::ByValue(Mutability::Immutable);
2294 match resolution.base_def {
2295 Def::Struct(..) | Def::Variant(..) |
2296 Def::Const(..) | Def::AssociatedConst(..) if !always_binding => {
2297 // A constant, unit variant, etc pattern.
2300 Def::Struct(..) | Def::Variant(..) |
2301 Def::Const(..) | Def::AssociatedConst(..) | Def::Static(..) => {
2302 // A fresh binding that shadows something unacceptable.
2306 ResolutionError::BindingShadowsSomethingUnacceptable(
2307 pat_src.descr(), resolution.kind_name(), ident.node.name)
2309 err_path_resolution()
2311 Def::Local(..) | Def::Upvar(..) | Def::Fn(..) | Def::Err => {
2312 // These entities are explicitly allowed
2313 // to be shadowed by fresh bindings.
2314 self.fresh_binding(ident, pat.id, outer_pat_id,
2318 span_bug!(ident.span, "unexpected definition for an \
2319 identifier in pattern {:?}", def);
2323 // Fall back to a fresh binding.
2324 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2327 self.record_def(pat.id, resolution);
2330 PatKind::TupleStruct(ref path, _, _) => {
2331 self.resolve_pattern_path(pat.id, None, path, ValueNS, |def| {
2333 Def::Struct(..) | Def::Variant(..) | Def::Err => true,
2336 }, "variant or struct");
2339 PatKind::Path(ref qself, ref path) => {
2340 self.resolve_pattern_path(pat.id, qself.as_ref(), path, ValueNS, |def| {
2342 Def::Struct(..) | Def::Variant(..) |
2343 Def::Const(..) | Def::AssociatedConst(..) | Def::Err => true,
2346 }, "variant, struct or constant");
2349 PatKind::Struct(ref path, _, _) => {
2350 self.resolve_pattern_path(pat.id, None, path, TypeNS, |def| {
2352 Def::Struct(..) | Def::Variant(..) |
2353 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::Err => true,
2356 }, "variant, struct or type alias");
2364 visit::walk_pat(self, pat);
2367 /// Handles paths that may refer to associated items
2368 fn resolve_possibly_assoc_item(&mut self,
2370 maybe_qself: Option<&QSelf>,
2372 namespace: Namespace)
2373 -> Option<PathResolution> {
2374 let max_assoc_types;
2378 if qself.position == 0 {
2379 // FIXME: Create some fake resolution that can't possibly be a type.
2380 return Some(PathResolution {
2381 base_def: Def::Mod(self.definitions.local_def_id(ast::CRATE_NODE_ID)),
2382 depth: path.segments.len(),
2385 max_assoc_types = path.segments.len() - qself.position;
2386 // Make sure the trait is valid.
2387 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2390 max_assoc_types = path.segments.len();
2394 let mut resolution = self.with_no_errors(|this| {
2395 this.resolve_path(id, path, 0, namespace).ok()
2397 for depth in 1..max_assoc_types {
2398 if resolution.is_some() {
2401 self.with_no_errors(|this| {
2402 let partial_resolution = this.resolve_path(id, path, depth, TypeNS).ok();
2403 if let Some(Def::Mod(..)) = partial_resolution.map(|r| r.base_def) {
2404 // Modules cannot have associated items
2406 resolution = partial_resolution;
2413 /// Skips `path_depth` trailing segments, which is also reflected in the
2414 /// returned value. See `hir::def::PathResolution` for more info.
2415 fn resolve_path(&mut self, id: NodeId, path: &Path, path_depth: usize, namespace: Namespace)
2416 -> Result<PathResolution, bool /* true if an error was reported */ > {
2417 debug!("resolve_path(id={:?} path={:?}, path_depth={:?})", id, path, path_depth);
2419 let span = path.span;
2420 let segments = &path.segments[..path.segments.len() - path_depth];
2422 let mk_res = |def| PathResolution { base_def: def, depth: path_depth };
2425 let binding = self.resolve_crate_relative_path(span, segments, namespace);
2426 return binding.map(|binding| mk_res(binding.def().unwrap()));
2429 // Try to find a path to an item in a module.
2430 let last_ident = segments.last().unwrap().identifier;
2431 // Resolve a single identifier with fallback to primitive types
2432 let resolve_identifier_with_fallback = |this: &mut Self, record_used| {
2433 let def = this.resolve_identifier(last_ident, namespace, record_used);
2435 None | Some(LocalDef{def: Def::Mod(..), ..}) if namespace == TypeNS =>
2436 this.primitive_type_table
2438 .get(&last_ident.name)
2439 .map_or(def, |prim_ty| Some(LocalDef::from_def(Def::PrimTy(*prim_ty)))),
2444 if segments.len() == 1 {
2445 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
2446 // don't report an error right away, but try to fallback to a primitive type.
2447 // So, we are still able to successfully resolve something like
2449 // use std::u8; // bring module u8 in scope
2450 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
2451 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
2452 // // not to non-existent std::u8::max_value
2455 // Such behavior is required for backward compatibility.
2456 // The same fallback is used when `a` resolves to nothing.
2457 let def = resolve_identifier_with_fallback(self, true).ok_or(false);
2458 return def.and_then(|def| self.adjust_local_def(def, span).ok_or(true)).map(mk_res);
2461 let unqualified_def = resolve_identifier_with_fallback(self, false);
2462 let qualified_binding = self.resolve_module_relative_path(span, segments, namespace);
2463 match (qualified_binding, unqualified_def) {
2464 (Ok(binding), Some(ref ud)) if binding.def().unwrap() == ud.def => {
2466 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2469 "unnecessary qualification".to_string());
2474 qualified_binding.map(|binding| mk_res(binding.def().unwrap()))
2477 // Resolve a single identifier
2478 fn resolve_identifier(&mut self,
2479 identifier: ast::Ident,
2480 namespace: Namespace,
2482 -> Option<LocalDef> {
2483 if identifier.name == keywords::Invalid.name() {
2484 return Some(LocalDef::from_def(Def::Err));
2487 self.resolve_ident_in_lexical_scope(identifier, namespace, record_used)
2488 .map(LexicalScopeBinding::local_def)
2491 // Resolve a local definition, potentially adjusting for closures.
2492 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2493 let ribs = match local_def.ribs {
2494 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2495 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2498 let mut def = local_def.def;
2501 span_bug!(span, "unexpected {:?} in bindings", def)
2503 Def::Local(_, node_id) => {
2506 NormalRibKind | ModuleRibKind(..) => {
2507 // Nothing to do. Continue.
2509 ClosureRibKind(function_id) => {
2511 let node_def_id = self.definitions.local_def_id(node_id);
2513 let seen = self.freevars_seen
2515 .or_insert_with(|| NodeMap());
2516 if let Some(&index) = seen.get(&node_id) {
2517 def = Def::Upvar(node_def_id, node_id, index, function_id);
2520 let vec = self.freevars
2522 .or_insert_with(|| vec![]);
2523 let depth = vec.len();
2529 def = Def::Upvar(node_def_id, node_id, depth, function_id);
2530 seen.insert(node_id, depth);
2532 ItemRibKind | MethodRibKind(_) => {
2533 // This was an attempt to access an upvar inside a
2534 // named function item. This is not allowed, so we
2538 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2541 ConstantItemRibKind => {
2542 // Still doesn't deal with upvars
2545 ResolutionError::AttemptToUseNonConstantValueInConstant);
2551 Def::TyParam(..) | Def::SelfTy(..) => {
2554 NormalRibKind | MethodRibKind(_) | ClosureRibKind(..) |
2555 ModuleRibKind(..) => {
2556 // Nothing to do. Continue.
2559 // This was an attempt to use a type parameter outside
2564 ResolutionError::TypeParametersFromOuterFunction);
2567 ConstantItemRibKind => {
2569 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2580 // resolve a "module-relative" path, e.g. a::b::c
2581 fn resolve_module_relative_path(&mut self,
2583 segments: &[ast::PathSegment],
2584 namespace: Namespace)
2585 -> Result<&'a NameBinding<'a>,
2586 bool /* true if an error was reported */> {
2587 let module_path = segments.split_last()
2591 .map(|ps| ps.identifier.name)
2592 .collect::<Vec<_>>();
2594 let containing_module;
2595 match self.resolve_module_path(&module_path, UseLexicalScope, span) {
2597 let (span, msg) = match err {
2598 Some((span, msg)) => (span, msg),
2600 let msg = format!("Use of undeclared type or module `{}`",
2601 names_to_string(&module_path));
2606 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2609 Indeterminate => return Err(false),
2610 Success(resulting_module) => {
2611 containing_module = resulting_module;
2615 let name = segments.last().unwrap().identifier.name;
2616 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2617 result.success().map(|binding| {
2618 self.check_privacy(name, binding, span);
2623 /// Invariant: This must be called only during main resolution, not during
2624 /// import resolution.
2625 fn resolve_crate_relative_path<T>(&mut self, span: Span, segments: &[T], namespace: Namespace)
2626 -> Result<&'a NameBinding<'a>,
2627 bool /* true if an error was reported */>
2630 let module_path = segments.split_last().unwrap().1.iter().map(T::name).collect::<Vec<_>>();
2631 let root_module = self.graph_root;
2633 let containing_module;
2634 match self.resolve_module_path_from_root(root_module,
2639 let (span, msg) = match err {
2640 Some((span, msg)) => (span, msg),
2642 let msg = format!("Use of undeclared module `::{}`",
2643 names_to_string(&module_path));
2648 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2652 Indeterminate => return Err(false),
2654 Success(resulting_module) => {
2655 containing_module = resulting_module;
2659 let name = segments.last().unwrap().name();
2660 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2661 result.success().map(|binding| {
2662 self.check_privacy(name, binding, span);
2667 fn with_no_errors<T, F>(&mut self, f: F) -> T
2668 where F: FnOnce(&mut Resolver) -> T
2670 self.emit_errors = false;
2672 self.emit_errors = true;
2676 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
2677 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2679 TyKind::Path(None, _) => Some(t.id),
2680 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2681 // This doesn't handle the remaining `Ty` variants as they are not
2682 // that commonly the self_type, it might be interesting to provide
2683 // support for those in future.
2688 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
2689 // Look for a field with the same name in the current self_type.
2690 if let Some(resolution) = self.def_map.get(&node_id) {
2691 match resolution.base_def {
2692 Def::Enum(did) | Def::TyAlias(did) |
2693 Def::Struct(did) | Def::Variant(_, did) if resolution.depth == 0 => {
2694 if let Some(fields) = self.structs.get(&did) {
2695 if fields.iter().any(|&field_name| name == field_name) {
2705 // Look for a method in the current trait.
2706 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
2707 if let Some(&is_static_method) = self.trait_item_map.get(&(name, trait_did)) {
2708 if is_static_method {
2709 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2719 fn find_best_match(&mut self, name: &str) -> SuggestionType {
2720 if let Some(macro_name) = self.session.available_macros
2721 .borrow().iter().find(|n| n.as_str() == name) {
2722 return SuggestionType::Macro(format!("{}!", macro_name));
2725 let names = self.value_ribs
2728 .flat_map(|rib| rib.bindings.keys());
2730 if let Some(found) = find_best_match_for_name(names, name, None) {
2732 return SuggestionType::Function(found);
2734 } SuggestionType::NotFound
2737 fn resolve_labeled_block(&mut self, label: Option<ast::Ident>, id: NodeId, block: &Block) {
2738 if let Some(label) = label {
2739 let (label, def) = (mtwt::resolve(label), Def::Label(id));
2740 self.with_label_rib(|this| {
2741 this.label_ribs.last_mut().unwrap().bindings.insert(label, def);
2742 this.visit_block(block);
2745 self.visit_block(block);
2749 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
2750 // First, record candidate traits for this expression if it could
2751 // result in the invocation of a method call.
2753 self.record_candidate_traits_for_expr_if_necessary(expr);
2755 // Next, resolve the node.
2757 ExprKind::Path(ref maybe_qself, ref path) => {
2758 // This is a local path in the value namespace. Walk through
2759 // scopes looking for it.
2760 if let Some(path_res) = self.resolve_possibly_assoc_item(expr.id,
2761 maybe_qself.as_ref(), path, ValueNS) {
2762 // Check if struct variant
2763 let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
2764 self.structs.contains_key(&variant_id)
2768 if is_struct_variant {
2769 let _ = self.structs.contains_key(&path_res.base_def.def_id());
2770 let path_name = path_names_to_string(path, 0);
2772 let mut err = resolve_struct_error(self,
2774 ResolutionError::StructVariantUsedAsFunction(&path_name));
2776 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2778 if self.emit_errors {
2781 err.span_help(expr.span, &msg);
2784 self.record_def(expr.id, err_path_resolution());
2786 // Write the result into the def map.
2787 debug!("(resolving expr) resolved `{}`",
2788 path_names_to_string(path, 0));
2790 // Partial resolutions will need the set of traits in scope,
2791 // so they can be completed during typeck.
2792 if path_res.depth != 0 {
2793 let method_name = path.segments.last().unwrap().identifier.name;
2794 let traits = self.get_traits_containing_item(method_name);
2795 self.trait_map.insert(expr.id, traits);
2798 self.record_def(expr.id, path_res);
2801 // Be helpful if the name refers to a struct
2802 // (The pattern matching def_tys where the id is in self.structs
2803 // matches on regular structs while excluding tuple- and enum-like
2804 // structs, which wouldn't result in this error.)
2805 let path_name = path_names_to_string(path, 0);
2806 let type_res = self.with_no_errors(|this| {
2807 this.resolve_path(expr.id, path, 0, TypeNS)
2810 self.record_def(expr.id, err_path_resolution());
2812 if let Ok(Def::Struct(..)) = type_res.map(|r| r.base_def) {
2814 ResolutionError::StructVariantUsedAsFunction(&path_name);
2815 let mut err = resolve_struct_error(self, expr.span, error_variant);
2817 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2820 if self.emit_errors {
2823 err.span_help(expr.span, &msg);
2827 // Keep reporting some errors even if they're ignored above.
2828 if let Err(true) = self.resolve_path(expr.id, path, 0, ValueNS) {
2829 // `resolve_path` already reported the error
2831 let mut method_scope = false;
2832 let mut is_static = false;
2833 self.value_ribs.iter().rev().all(|rib| {
2834 method_scope = match rib.kind {
2835 MethodRibKind(is_static_) => {
2836 is_static = is_static_;
2839 ItemRibKind | ConstantItemRibKind => false,
2840 _ => return true, // Keep advancing
2842 false // Stop advancing
2846 &path_name[..] == keywords::SelfValue.name().as_str() {
2849 ResolutionError::SelfNotAvailableInStaticMethod);
2851 let last_name = path.segments.last().unwrap().identifier.name;
2852 let (mut msg, is_field) =
2853 match self.find_fallback_in_self_type(last_name) {
2855 // limit search to 5 to reduce the number
2856 // of stupid suggestions
2857 (match self.find_best_match(&path_name) {
2858 SuggestionType::Macro(s) => {
2859 format!("the macro `{}`", s)
2861 SuggestionType::Function(s) => format!("`{}`", s),
2862 SuggestionType::NotFound => "".to_string(),
2866 (if is_static && method_scope {
2869 format!("`self.{}`", path_name)
2872 TraitItem => (format!("to call `self.{}`", path_name), false),
2873 TraitMethod(path_str) =>
2874 (format!("to call `{}::{}`", path_str, path_name), false),
2877 let mut context = UnresolvedNameContext::Other;
2878 let mut def = Def::Err;
2879 if !msg.is_empty() {
2880 msg = format!(". Did you mean {}?", msg);
2882 // we check if this a module and if so, we display a help
2884 let name_path = path.segments.iter()
2885 .map(|seg| seg.identifier.name)
2886 .collect::<Vec<_>>();
2888 match self.resolve_module_path(&name_path[..],
2892 if let Some(def_type) = e.def {
2895 context = UnresolvedNameContext::PathIsMod(parent);
2903 ResolutionError::UnresolvedName {
2907 is_static_method: method_scope && is_static,
2916 visit::walk_expr(self, expr);
2919 ExprKind::Struct(ref path, _, _) => {
2920 // Resolve the path to the structure it goes to. We don't
2921 // check to ensure that the path is actually a structure; that
2922 // is checked later during typeck.
2923 match self.resolve_path(expr.id, path, 0, TypeNS) {
2924 Ok(definition) => self.record_def(expr.id, definition),
2925 Err(true) => self.record_def(expr.id, err_path_resolution()),
2927 debug!("(resolving expression) didn't find struct def",);
2931 ResolutionError::DoesNotNameAStruct(
2932 &path_names_to_string(path, 0))
2934 self.record_def(expr.id, err_path_resolution());
2938 visit::walk_expr(self, expr);
2941 ExprKind::Loop(_, Some(label)) | ExprKind::While(_, _, Some(label)) => {
2942 self.with_label_rib(|this| {
2943 let def = Def::Label(expr.id);
2946 let rib = this.label_ribs.last_mut().unwrap();
2947 rib.bindings.insert(mtwt::resolve(label.node), def);
2950 visit::walk_expr(this, expr);
2954 ExprKind::Break(Some(label)) | ExprKind::Continue(Some(label)) => {
2955 match self.search_label(mtwt::resolve(label.node)) {
2957 self.record_def(expr.id, err_path_resolution());
2960 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
2962 Some(def @ Def::Label(_)) => {
2963 // Since this def is a label, it is never read.
2964 self.record_def(expr.id, PathResolution::new(def))
2967 span_bug!(expr.span, "label wasn't mapped to a label def!")
2972 ExprKind::IfLet(ref pattern, ref subexpression, ref if_block, ref optional_else) => {
2973 self.visit_expr(subexpression);
2975 self.value_ribs.push(Rib::new(NormalRibKind));
2976 self.resolve_pattern(pattern, PatternSource::IfLet, &mut HashMap::new());
2977 self.visit_block(if_block);
2978 self.value_ribs.pop();
2980 optional_else.as_ref().map(|expr| self.visit_expr(expr));
2983 ExprKind::WhileLet(ref pattern, ref subexpression, ref block, label) => {
2984 self.visit_expr(subexpression);
2985 self.value_ribs.push(Rib::new(NormalRibKind));
2986 self.resolve_pattern(pattern, PatternSource::WhileLet, &mut HashMap::new());
2988 self.resolve_labeled_block(label.map(|l| l.node), expr.id, block);
2990 self.value_ribs.pop();
2993 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
2994 self.visit_expr(subexpression);
2995 self.value_ribs.push(Rib::new(NormalRibKind));
2996 self.resolve_pattern(pattern, PatternSource::For, &mut HashMap::new());
2998 self.resolve_labeled_block(label.map(|l| l.node), expr.id, block);
3000 self.value_ribs.pop();
3003 ExprKind::Field(ref subexpression, _) => {
3004 self.resolve_expr(subexpression, Some(expr));
3006 ExprKind::MethodCall(_, ref types, ref arguments) => {
3007 let mut arguments = arguments.iter();
3008 self.resolve_expr(arguments.next().unwrap(), Some(expr));
3009 for argument in arguments {
3010 self.resolve_expr(argument, None);
3012 for ty in types.iter() {
3018 visit::walk_expr(self, expr);
3023 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3025 ExprKind::Field(_, name) => {
3026 // FIXME(#6890): Even though you can't treat a method like a
3027 // field, we need to add any trait methods we find that match
3028 // the field name so that we can do some nice error reporting
3029 // later on in typeck.
3030 let traits = self.get_traits_containing_item(name.node.name);
3031 self.trait_map.insert(expr.id, traits);
3033 ExprKind::MethodCall(name, _, _) => {
3034 debug!("(recording candidate traits for expr) recording traits for {}",
3036 let traits = self.get_traits_containing_item(name.node.name);
3037 self.trait_map.insert(expr.id, traits);
3045 fn get_traits_containing_item(&mut self, name: Name) -> Vec<TraitCandidate> {
3046 debug!("(getting traits containing item) looking for '{}'", name);
3048 fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
3049 trait_def_id: DefId,
3050 import_id: Option<NodeId>,
3052 debug!("(adding trait info) found trait {:?} for method '{}'",
3055 found_traits.push(TraitCandidate {
3056 def_id: trait_def_id,
3057 import_id: import_id,
3061 let mut found_traits = Vec::new();
3062 // Look for the current trait.
3063 if let Some((trait_def_id, _)) = self.current_trait_ref {
3064 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3065 add_trait_info(&mut found_traits, trait_def_id, None, name);
3069 let mut search_module = self.current_module;
3071 // Look for trait children.
3072 let mut search_in_module = |this: &mut Self, module: Module<'a>| {
3073 let mut traits = module.traits.borrow_mut();
3074 if traits.is_none() {
3075 let mut collected_traits = Vec::new();
3076 module.for_each_child(|name, ns, binding| {
3077 if ns != TypeNS { return }
3078 if let Some(Def::Trait(_)) = binding.def() {
3079 collected_traits.push((name, binding));
3082 *traits = Some(collected_traits.into_boxed_slice());
3085 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
3086 let trait_def_id = binding.def().unwrap().def_id();
3087 if this.trait_item_map.contains_key(&(name, trait_def_id)) {
3088 let mut import_id = None;
3089 if let NameBindingKind::Import { directive, .. } = binding.kind {
3090 let id = directive.id;
3091 this.maybe_unused_trait_imports.insert(id);
3092 import_id = Some(id);
3094 add_trait_info(&mut found_traits, trait_def_id, import_id, name);
3095 this.record_use(trait_name, binding);
3099 search_in_module(self, search_module);
3101 match search_module.parent_link {
3102 NoParentLink | ModuleParentLink(..) => {
3103 if !search_module.no_implicit_prelude.get() {
3104 self.prelude.map(|prelude| search_in_module(self, prelude));
3108 BlockParentLink(parent_module, _) => {
3109 search_module = parent_module;
3117 /// When name resolution fails, this method can be used to look up candidate
3118 /// entities with the expected name. It allows filtering them using the
3119 /// supplied predicate (which should be used to only accept the types of
3120 /// definitions expected e.g. traits). The lookup spans across all crates.
3122 /// NOTE: The method does not look into imports, but this is not a problem,
3123 /// since we report the definitions (thus, the de-aliased imports).
3124 fn lookup_candidates<FilterFn>(&mut self,
3126 namespace: Namespace,
3127 filter_fn: FilterFn) -> SuggestedCandidates
3128 where FilterFn: Fn(Def) -> bool {
3130 let mut lookup_results = Vec::new();
3131 let mut worklist = Vec::new();
3132 worklist.push((self.graph_root, Vec::new(), false));
3134 while let Some((in_module,
3136 in_module_is_extern)) = worklist.pop() {
3137 self.populate_module_if_necessary(in_module);
3139 in_module.for_each_child(|name, ns, name_binding| {
3141 // avoid imports entirely
3142 if name_binding.is_import() { return; }
3144 // collect results based on the filter function
3145 if let Some(def) = name_binding.def() {
3146 if name == lookup_name && ns == namespace && filter_fn(def) {
3148 let ident = ast::Ident::with_empty_ctxt(name);
3149 let params = PathParameters::none();
3150 let segment = PathSegment {
3154 let span = name_binding.span;
3155 let mut segms = path_segments.clone();
3156 segms.push(segment);
3162 // the entity is accessible in the following cases:
3163 // 1. if it's defined in the same crate, it's always
3164 // accessible (since private entities can be made public)
3165 // 2. if it's defined in another crate, it's accessible
3166 // only if both the module is public and the entity is
3167 // declared as public (due to pruning, we don't explore
3168 // outside crate private modules => no need to check this)
3169 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3170 lookup_results.push(path);
3175 // collect submodules to explore
3176 if let Some(module) = name_binding.module() {
3178 let path_segments = match module.parent_link {
3179 NoParentLink => path_segments.clone(),
3180 ModuleParentLink(_, name) => {
3181 let mut paths = path_segments.clone();
3182 let ident = ast::Ident::with_empty_ctxt(name);
3183 let params = PathParameters::none();
3184 let segm = PathSegment {
3194 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3195 // add the module to the lookup
3196 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3197 worklist.push((module, path_segments, is_extern));
3203 SuggestedCandidates {
3204 name: lookup_name.as_str().to_string(),
3205 candidates: lookup_results,
3209 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3210 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3211 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3212 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3216 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
3217 let (path, id) = match *vis {
3218 ast::Visibility::Public => return ty::Visibility::Public,
3219 ast::Visibility::Crate(_) => return ty::Visibility::Restricted(ast::CRATE_NODE_ID),
3220 ast::Visibility::Restricted { ref path, id } => (path, id),
3221 ast::Visibility::Inherited => {
3222 let current_module =
3223 self.get_nearest_normal_module_parent_or_self(self.current_module);
3225 self.definitions.as_local_node_id(current_module.def_id().unwrap()).unwrap();
3226 return ty::Visibility::Restricted(id);
3230 let segments: Vec<_> = path.segments.iter().map(|seg| seg.identifier.name).collect();
3231 let mut path_resolution = err_path_resolution();
3232 let vis = match self.resolve_module_path(&segments, DontUseLexicalScope, path.span) {
3233 Success(module) => {
3234 let def = module.def.unwrap();
3235 path_resolution = PathResolution::new(def);
3236 ty::Visibility::Restricted(self.definitions.as_local_node_id(def.def_id()).unwrap())
3238 Failed(Some((span, msg))) => {
3239 self.session.span_err(span, &format!("failed to resolve module path. {}", msg));
3240 ty::Visibility::Public
3243 self.session.span_err(path.span, "unresolved module path");
3244 ty::Visibility::Public
3247 self.def_map.insert(id, path_resolution);
3248 if !self.is_accessible(vis) {
3249 let msg = format!("visibilities can only be restricted to ancestor modules");
3250 self.session.span_err(path.span, &msg);
3255 fn is_accessible(&self, vis: ty::Visibility) -> bool {
3256 let current_module = self.get_nearest_normal_module_parent_or_self(self.current_module);
3257 let node_id = self.definitions.as_local_node_id(current_module.def_id().unwrap()).unwrap();
3258 vis.is_accessible_from(node_id, self)
3261 fn check_privacy(&mut self, name: Name, binding: &'a NameBinding<'a>, span: Span) {
3262 if !self.is_accessible(binding.vis) {
3263 self.privacy_errors.push(PrivacyError(span, name, binding));
3267 fn report_privacy_errors(&self) {
3268 if self.privacy_errors.len() == 0 { return }
3269 let mut reported_spans = HashSet::new();
3270 for &PrivacyError(span, name, binding) in &self.privacy_errors {
3271 if !reported_spans.insert(span) { continue }
3272 if binding.is_extern_crate() {
3273 // Warn when using an inaccessible extern crate.
3274 let node_id = binding.module().unwrap().extern_crate_id.unwrap();
3275 let msg = format!("extern crate `{}` is private", name);
3276 self.session.add_lint(lint::builtin::INACCESSIBLE_EXTERN_CRATE, node_id, span, msg);
3278 let def = binding.def().unwrap();
3279 self.session.span_err(span, &format!("{} `{}` is private", def.kind_name(), name));
3284 fn report_conflict(&self,
3288 binding: &NameBinding,
3289 old_binding: &NameBinding) {
3290 // Error on the second of two conflicting names
3291 if old_binding.span.lo > binding.span.lo {
3292 return self.report_conflict(parent, name, ns, old_binding, binding);
3295 let container = match parent.def {
3296 Some(Def::Mod(_)) => "module",
3297 Some(Def::Trait(_)) => "trait",
3302 let (participle, noun) = match old_binding.is_import() || old_binding.is_extern_crate() {
3303 true => ("imported", "import"),
3304 false => ("defined", "definition"),
3307 let span = binding.span;
3309 let kind = match (ns, old_binding.module()) {
3310 (ValueNS, _) => "a value",
3311 (TypeNS, Some(module)) if module.extern_crate_id.is_some() => "an extern crate",
3312 (TypeNS, Some(module)) if module.is_normal() => "a module",
3313 (TypeNS, Some(module)) if module.is_trait() => "a trait",
3314 (TypeNS, _) => "a type",
3316 format!("{} named `{}` has already been {} in this {}",
3317 kind, name, participle, container)
3320 let mut err = match (old_binding.is_extern_crate(), binding.is_extern_crate()) {
3321 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
3322 (true, _) | (_, true) if binding.is_import() || old_binding.is_import() =>
3323 struct_span_err!(self.session, span, E0254, "{}", msg),
3324 (true, _) | (_, true) => struct_span_err!(self.session, span, E0260, "{}", msg),
3325 _ => match (old_binding.is_import(), binding.is_import()) {
3326 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
3327 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
3329 let mut e = struct_span_err!(self.session, span, E0255, "{}", msg);
3330 e.span_label(span, &format!("`{}` was already imported", name));
3336 if old_binding.span != syntax_pos::DUMMY_SP {
3337 err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
3343 fn names_to_string(names: &[Name]) -> String {
3344 let mut first = true;
3345 let mut result = String::new();
3350 result.push_str("::")
3352 result.push_str(&name.as_str());
3357 fn path_names_to_string(path: &Path, depth: usize) -> String {
3358 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3360 .map(|seg| seg.identifier.name)
3362 names_to_string(&names[..])
3365 /// When an entity with a given name is not available in scope, we search for
3366 /// entities with that name in all crates. This method allows outputting the
3367 /// results of this search in a programmer-friendly way
3368 fn show_candidates(session: &mut DiagnosticBuilder,
3369 candidates: &SuggestedCandidates) {
3371 let paths = &candidates.candidates;
3373 if paths.len() > 0 {
3374 // don't show more than MAX_CANDIDATES results, so
3375 // we're consistent with the trait suggestions
3376 const MAX_CANDIDATES: usize = 5;
3378 // we want consistent results across executions, but candidates are produced
3379 // by iterating through a hash map, so make sure they are ordered:
3380 let mut path_strings: Vec<_> = paths.into_iter()
3381 .map(|p| path_names_to_string(&p, 0))
3383 path_strings.sort();
3385 // behave differently based on how many candidates we have:
3386 if !paths.is_empty() {
3387 if paths.len() == 1 {
3389 &format!("you can import it into scope: `use {};`.",
3393 session.help("you can import several candidates \
3394 into scope (`use ...;`):");
3395 let count = path_strings.len() as isize - MAX_CANDIDATES as isize + 1;
3397 for (idx, path_string) in path_strings.iter().enumerate() {
3398 if idx == MAX_CANDIDATES - 1 && count > 1 {
3400 &format!(" and {} other candidates", count).to_string(),
3405 &format!(" `{}`", path_string).to_string(),
3414 &format!("no candidates by the name of `{}` found in your \
3415 project; maybe you misspelled the name or forgot to import \
3416 an external crate?", candidates.name.to_string()),
3421 /// A somewhat inefficient routine to obtain the name of a module.
3422 fn module_to_string(module: Module) -> String {
3423 let mut names = Vec::new();
3425 fn collect_mod(names: &mut Vec<ast::Name>, module: Module) {
3426 match module.parent_link {
3428 ModuleParentLink(ref module, name) => {
3430 collect_mod(names, module);
3432 BlockParentLink(ref module, _) => {
3433 // danger, shouldn't be ident?
3434 names.push(token::intern("<opaque>"));
3435 collect_mod(names, module);
3439 collect_mod(&mut names, module);
3441 if names.is_empty() {
3442 return "???".to_string();
3444 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3447 fn err_path_resolution() -> PathResolution {
3448 PathResolution::new(Def::Err)
3451 #[derive(PartialEq,Copy, Clone)]
3452 pub enum MakeGlobMap {
3457 /// Entry point to crate resolution.
3458 pub fn resolve_crate<'a, 'b>(resolver: &'b mut Resolver<'a>, krate: &'b Crate) {
3459 // Currently, we ignore the name resolution data structures for
3460 // the purposes of dependency tracking. Instead we will run name
3461 // resolution and include its output in the hash of each item,
3462 // much like we do for macro expansion. In other words, the hash
3463 // reflects not just its contents but the results of name
3464 // resolution on those contents. Hopefully we'll push this back at
3466 let _ignore = resolver.session.dep_graph.in_ignore();
3468 resolver.build_reduced_graph(krate);
3469 resolve_imports::resolve_imports(resolver);
3470 resolver.resolve_crate(krate);
3472 check_unused::check_crate(resolver, krate);
3473 resolver.report_privacy_errors();
3476 pub fn with_resolver<'a, T, F>(session: &'a Session,
3477 definitions: &'a mut Definitions,
3478 make_glob_map: MakeGlobMap,
3480 where F: for<'b> FnOnce(Resolver<'b>) -> T,
3482 let arenas = Resolver::arenas();
3483 let resolver = Resolver::new(session, definitions, make_glob_map, &arenas);
3487 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }