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::{CRATE_DEF_INDEX, DefId};
52 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
53 use rustc::util::nodemap::{NodeMap, NodeSet, FnvHashMap, FnvHashSet};
55 use syntax::ext::hygiene::Mark;
56 use syntax::ast::{self, FloatTy};
57 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
58 use syntax::parse::token::{self, keywords};
59 use syntax::util::lev_distance::find_best_match_for_name;
61 use syntax::visit::{self, FnKind, Visitor};
62 use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind};
63 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, Generics};
64 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
65 use syntax::ast::{Local, Mutability, Pat, PatKind, Path};
66 use syntax::ast::{PathSegment, PathParameters, QSelf, TraitItemKind, TraitRef, Ty, TyKind};
69 use errors::DiagnosticBuilder;
71 use std::collections::{HashMap, HashSet};
72 use std::cell::{Cell, RefCell};
74 use std::mem::replace;
76 use resolve_imports::{ImportDirective, NameResolution};
78 // NB: This module needs to be declared first so diagnostics are
79 // registered before they are used.
83 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, Name, &'a NameBinding<'a>),
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 let mut err = struct_span_err!(resolver.session,
224 "`{}` is not a trait",
226 err.span_label(span, &format!("not a trait"));
229 ResolutionError::UndeclaredTraitName(name, candidates) => {
230 let mut err = struct_span_err!(resolver.session,
233 "trait `{}` is not in scope",
235 show_candidates(&mut err, &candidates);
236 err.span_label(span, &format!("`{}` is not in scope", name));
239 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
240 struct_span_err!(resolver.session,
243 "method `{}` is not a member of trait `{}`",
247 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
248 struct_span_err!(resolver.session,
251 "type `{}` is not a member of trait `{}`",
255 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
256 struct_span_err!(resolver.session,
259 "const `{}` is not a member of trait `{}`",
263 ResolutionError::VariableNotBoundInPattern(variable_name, from, to) => {
264 struct_span_err!(resolver.session,
267 "variable `{}` from pattern #{} is not bound in pattern #{}",
272 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
273 struct_span_err!(resolver.session,
276 "variable `{}` is bound with different mode in pattern #{} than in \
281 ResolutionError::SelfUsedOutsideImplOrTrait => {
282 let mut err = struct_span_err!(resolver.session,
285 "use of `Self` outside of an impl or trait");
286 err.span_label(span, &format!("used outside of impl or trait"));
289 ResolutionError::UseOfUndeclared(kind, name, candidates) => {
290 let mut err = struct_span_err!(resolver.session,
293 "{} `{}` is undefined or not in scope",
296 show_candidates(&mut err, &candidates);
297 err.span_label(span, &format!("undefined or not in scope"));
300 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
301 let mut err = struct_span_err!(resolver.session,
304 "identifier `{}` is bound more than once in this parameter list",
306 err.span_label(span, &format!("used as parameter more than once"));
309 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
310 let mut err = struct_span_err!(resolver.session,
313 "identifier `{}` is bound more than once in the same pattern",
315 err.span_label(span, &format!("used in a pattern more than once"));
318 ResolutionError::DoesNotNameAStruct(name) => {
319 let mut err = struct_span_err!(resolver.session,
322 "`{}` does not name a structure",
324 err.span_label(span, &format!("not a structure"));
327 ResolutionError::StructVariantUsedAsFunction(path_name) => {
328 struct_span_err!(resolver.session,
331 "`{}` is the name of a struct or struct variant, but this expression \
332 uses it like a function name",
335 ResolutionError::SelfNotAvailableInStaticMethod => {
336 struct_span_err!(resolver.session,
339 "`self` is not available in a static method. Maybe a `self` \
340 argument is missing?")
342 ResolutionError::UnresolvedName { path, message: msg, context, is_static_method,
344 let mut err = struct_span_err!(resolver.session,
347 "unresolved name `{}`{}",
351 UnresolvedNameContext::Other => {
352 if msg.is_empty() && is_static_method && is_field {
353 err.help("this is an associated function, you don't have access to \
354 this type's fields or methods");
357 UnresolvedNameContext::PathIsMod(parent) => {
358 err.help(&match parent.map(|parent| &parent.node) {
359 Some(&ExprKind::Field(_, ident)) => {
360 format!("to reference an item from the `{module}` module, \
361 use `{module}::{ident}`",
365 Some(&ExprKind::MethodCall(ident, _, _)) => {
366 format!("to call a function from the `{module}` module, \
367 use `{module}::{ident}(..)`",
372 format!("{def} `{module}` cannot be used as an expression",
373 def = def.kind_name(),
381 ResolutionError::UndeclaredLabel(name) => {
382 struct_span_err!(resolver.session,
385 "use of undeclared label `{}`",
388 ResolutionError::SelfImportsOnlyAllowedWithin => {
389 struct_span_err!(resolver.session,
393 "`self` imports are only allowed within a { } list")
395 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
396 struct_span_err!(resolver.session,
399 "`self` import can only appear once in the list")
401 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
402 struct_span_err!(resolver.session,
405 "`self` import can only appear in an import list with a \
408 ResolutionError::UnresolvedImport(name) => {
409 let msg = match name {
410 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
411 None => "unresolved import".to_owned(),
413 struct_span_err!(resolver.session, span, E0432, "{}", msg)
415 ResolutionError::FailedToResolve(msg) => {
416 let mut err = struct_span_err!(resolver.session, span, E0433,
417 "failed to resolve. {}", msg);
418 err.span_label(span, &msg);
421 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
422 struct_span_err!(resolver.session,
426 "can't capture dynamic environment in a fn item; use the || { ... } \
427 closure form instead")
429 ResolutionError::AttemptToUseNonConstantValueInConstant => {
430 struct_span_err!(resolver.session,
433 "attempt to use a non-constant value in a constant")
435 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
436 let shadows_what = PathResolution::new(binding.def().unwrap()).kind_name();
437 let mut err = struct_span_err!(resolver.session,
440 "{}s cannot shadow {}s", what_binding, shadows_what);
441 err.span_label(span, &format!("cannot be named the same as a {}", shadows_what));
442 let participle = if binding.is_import() { "imported" } else { "defined" };
443 let msg = &format!("a {} `{}` is {} here", shadows_what, name, participle);
444 err.span_label(binding.span, msg);
447 ResolutionError::PatPathUnresolved(expected_what, path) => {
448 struct_span_err!(resolver.session,
451 "unresolved {} `{}`",
453 path.segments.last().unwrap().identifier)
455 ResolutionError::PatPathUnexpected(expected_what, found_what, path) => {
456 struct_span_err!(resolver.session,
459 "expected {}, found {} `{}`",
462 path.segments.last().unwrap().identifier)
467 #[derive(Copy, Clone)]
470 binding_mode: BindingMode,
473 // Map from the name in a pattern to its binding mode.
474 type BindingMap = HashMap<ast::Ident, BindingInfo>;
476 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
487 fn is_refutable(self) -> bool {
489 PatternSource::Match | PatternSource::IfLet | PatternSource::WhileLet => true,
490 PatternSource::Let | PatternSource::For | PatternSource::FnParam => false,
493 fn descr(self) -> &'static str {
495 PatternSource::Match => "match binding",
496 PatternSource::IfLet => "if let binding",
497 PatternSource::WhileLet => "while let binding",
498 PatternSource::Let => "let binding",
499 PatternSource::For => "for binding",
500 PatternSource::FnParam => "function parameter",
505 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
511 impl<'a> Visitor for Resolver<'a> {
512 fn visit_item(&mut self, item: &Item) {
513 self.resolve_item(item);
515 fn visit_arm(&mut self, arm: &Arm) {
516 self.resolve_arm(arm);
518 fn visit_block(&mut self, block: &Block) {
519 self.resolve_block(block);
521 fn visit_expr(&mut self, expr: &Expr) {
522 self.resolve_expr(expr, None);
524 fn visit_local(&mut self, local: &Local) {
525 self.resolve_local(local);
527 fn visit_ty(&mut self, ty: &Ty) {
528 self.resolve_type(ty);
530 fn visit_poly_trait_ref(&mut self, tref: &ast::PolyTraitRef, m: &ast::TraitBoundModifier) {
531 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
532 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
534 // error already reported
535 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
538 visit::walk_poly_trait_ref(self, tref, m);
540 fn visit_variant(&mut self,
541 variant: &ast::Variant,
543 item_id: ast::NodeId) {
544 if let Some(ref dis_expr) = variant.node.disr_expr {
545 // resolve the discriminator expr as a constant
546 self.with_constant_rib(|this| {
547 this.visit_expr(dis_expr);
551 // `visit::walk_variant` without the discriminant expression.
552 self.visit_variant_data(&variant.node.data,
558 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
559 let type_parameters = match foreign_item.node {
560 ForeignItemKind::Fn(_, ref generics) => {
561 HasTypeParameters(generics, ItemRibKind)
563 ForeignItemKind::Static(..) => NoTypeParameters,
565 self.with_type_parameter_rib(type_parameters, |this| {
566 visit::walk_foreign_item(this, foreign_item);
569 fn visit_fn(&mut self,
570 function_kind: FnKind,
571 declaration: &FnDecl,
575 let rib_kind = match function_kind {
576 FnKind::ItemFn(_, generics, _, _, _, _) => {
577 self.visit_generics(generics);
580 FnKind::Method(_, sig, _) => {
581 self.visit_generics(&sig.generics);
582 MethodRibKind(!sig.decl.has_self())
584 FnKind::Closure => ClosureRibKind(node_id),
586 self.resolve_function(rib_kind, declaration, block);
590 pub type ErrorMessage = Option<(Span, String)>;
592 #[derive(Clone, PartialEq, Eq)]
593 pub enum ResolveResult<T> {
594 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
595 Indeterminate, // Couldn't determine due to unresolved globs.
596 Success(T), // Successfully resolved the import.
599 impl<T> ResolveResult<T> {
600 fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
602 Failed(msg) => Failed(msg),
603 Indeterminate => Indeterminate,
608 fn success(self) -> Option<T> {
610 Success(t) => Some(t),
616 enum FallbackSuggestion {
623 #[derive(Copy, Clone)]
624 enum TypeParameters<'a, 'b> {
626 HasTypeParameters(// Type parameters.
629 // The kind of the rib used for type parameters.
633 // The rib kind controls the translation of local
634 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
635 #[derive(Copy, Clone, Debug)]
637 // No translation needs to be applied.
640 // We passed through a closure scope at the given node ID.
641 // Translate upvars as appropriate.
642 ClosureRibKind(NodeId /* func id */),
644 // We passed through an impl or trait and are now in one of its
645 // methods. Allow references to ty params that impl or trait
646 // binds. Disallow any other upvars (including other ty params that are
649 // The boolean value represents the fact that this method is static or not.
652 // We passed through an item scope. Disallow upvars.
655 // We're in a constant item. Can't refer to dynamic stuff.
658 // We passed through a module.
659 ModuleRibKind(Module<'a>),
661 // We passed through a `macro_rules!` statement with the given expansion
662 MacroDefinition(Mark),
665 #[derive(Copy, Clone)]
666 enum UseLexicalScopeFlag {
671 enum ModulePrefixResult<'a> {
673 PrefixFound(Module<'a>, usize),
679 bindings: HashMap<ast::Ident, Def>,
684 fn new(kind: RibKind<'a>) -> Rib<'a> {
686 bindings: HashMap::new(),
692 /// A definition along with the index of the rib it was found on
694 ribs: Option<(Namespace, usize)>,
699 fn from_def(def: Def) -> Self {
707 enum LexicalScopeBinding<'a> {
708 Item(&'a NameBinding<'a>),
712 impl<'a> LexicalScopeBinding<'a> {
713 fn local_def(self) -> LocalDef {
715 LexicalScopeBinding::LocalDef(local_def) => local_def,
716 LexicalScopeBinding::Item(binding) => LocalDef::from_def(binding.def().unwrap()),
720 fn item(self) -> Option<&'a NameBinding<'a>> {
722 LexicalScopeBinding::Item(binding) => Some(binding),
727 fn module(self) -> Option<Module<'a>> {
728 self.item().and_then(NameBinding::module)
732 /// The link from a module up to its nearest parent node.
733 #[derive(Clone,Debug)]
734 enum ParentLink<'a> {
736 ModuleParentLink(Module<'a>, Name),
737 BlockParentLink(Module<'a>, NodeId),
740 /// One node in the tree of modules.
741 pub struct ModuleS<'a> {
742 parent_link: ParentLink<'a>,
745 // If the module is an extern crate, `def` is root of the external crate and `extern_crate_id`
746 // is the NodeId of the local `extern crate` item (otherwise, `extern_crate_id` is None).
747 extern_crate_id: Option<NodeId>,
749 resolutions: RefCell<HashMap<(Name, Namespace), &'a RefCell<NameResolution<'a>>>>,
750 unresolved_imports: RefCell<Vec<&'a ImportDirective<'a>>>,
752 no_implicit_prelude: Cell<bool>,
754 glob_importers: RefCell<Vec<(Module<'a>, &'a ImportDirective<'a>)>>,
755 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
757 // Used to memoize the traits in this module for faster searches through all traits in scope.
758 traits: RefCell<Option<Box<[(Name, &'a NameBinding<'a>)]>>>,
760 // Whether this module is populated. If not populated, any attempt to
761 // access the children must be preceded with a
762 // `populate_module_if_necessary` call.
763 populated: Cell<bool>,
765 arenas: &'a ResolverArenas<'a>,
768 pub type Module<'a> = &'a ModuleS<'a>;
770 impl<'a> ModuleS<'a> {
771 fn new(parent_link: ParentLink<'a>,
774 arenas: &'a ResolverArenas<'a>) -> Self {
776 parent_link: parent_link,
778 extern_crate_id: None,
779 resolutions: RefCell::new(HashMap::new()),
780 unresolved_imports: RefCell::new(Vec::new()),
781 no_implicit_prelude: Cell::new(false),
782 glob_importers: RefCell::new(Vec::new()),
783 globs: RefCell::new((Vec::new())),
784 traits: RefCell::new(None),
785 populated: Cell::new(!external),
790 fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
791 for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
792 name_resolution.borrow().binding.map(|binding| f(name, ns, binding));
796 fn def_id(&self) -> Option<DefId> {
797 self.def.as_ref().map(Def::def_id)
800 // `self` resolves to the first module ancestor that `is_normal`.
801 fn is_normal(&self) -> bool {
803 Some(Def::Mod(_)) => true,
808 fn is_trait(&self) -> bool {
810 Some(Def::Trait(_)) => true,
816 impl<'a> fmt::Debug for ModuleS<'a> {
817 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
818 write!(f, "{:?}", self.def)
822 // Records a possibly-private value, type, or module definition.
823 #[derive(Clone, Debug)]
824 pub struct NameBinding<'a> {
825 kind: NameBindingKind<'a>,
830 pub trait ToNameBinding<'a> {
831 fn to_name_binding(self) -> NameBinding<'a>;
834 impl<'a> ToNameBinding<'a> for NameBinding<'a> {
835 fn to_name_binding(self) -> NameBinding<'a> {
840 #[derive(Clone, Debug)]
841 enum NameBindingKind<'a> {
845 binding: &'a NameBinding<'a>,
846 directive: &'a ImportDirective<'a>,
850 #[derive(Clone, Debug)]
851 struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);
853 impl<'a> NameBinding<'a> {
854 fn module(&self) -> Option<Module<'a>> {
856 NameBindingKind::Module(module) => Some(module),
857 NameBindingKind::Def(_) => None,
858 NameBindingKind::Import { binding, .. } => binding.module(),
862 fn def(&self) -> Option<Def> {
864 NameBindingKind::Def(def) => Some(def),
865 NameBindingKind::Module(module) => module.def,
866 NameBindingKind::Import { binding, .. } => binding.def(),
870 fn is_pseudo_public(&self) -> bool {
871 self.pseudo_vis() == ty::Visibility::Public
874 // We sometimes need to treat variants as `pub` for backwards compatibility
875 fn pseudo_vis(&self) -> ty::Visibility {
876 if self.is_variant() { ty::Visibility::Public } else { self.vis }
879 fn is_variant(&self) -> bool {
881 NameBindingKind::Def(Def::Variant(..)) => true,
886 fn is_extern_crate(&self) -> bool {
887 self.module().and_then(|module| module.extern_crate_id).is_some()
890 fn is_import(&self) -> bool {
892 NameBindingKind::Import { .. } => true,
897 fn is_glob_import(&self) -> bool {
899 NameBindingKind::Import { directive, .. } => directive.is_glob(),
904 fn is_importable(&self) -> bool {
905 match self.def().unwrap() {
906 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
912 /// Interns the names of the primitive types.
913 struct PrimitiveTypeTable {
914 primitive_types: HashMap<Name, PrimTy>,
917 impl PrimitiveTypeTable {
918 fn new() -> PrimitiveTypeTable {
919 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
921 table.intern("bool", TyBool);
922 table.intern("char", TyChar);
923 table.intern("f32", TyFloat(FloatTy::F32));
924 table.intern("f64", TyFloat(FloatTy::F64));
925 table.intern("isize", TyInt(IntTy::Is));
926 table.intern("i8", TyInt(IntTy::I8));
927 table.intern("i16", TyInt(IntTy::I16));
928 table.intern("i32", TyInt(IntTy::I32));
929 table.intern("i64", TyInt(IntTy::I64));
930 table.intern("str", TyStr);
931 table.intern("usize", TyUint(UintTy::Us));
932 table.intern("u8", TyUint(UintTy::U8));
933 table.intern("u16", TyUint(UintTy::U16));
934 table.intern("u32", TyUint(UintTy::U32));
935 table.intern("u64", TyUint(UintTy::U64));
940 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
941 self.primitive_types.insert(token::intern(string), primitive_type);
945 /// The main resolver class.
946 pub struct Resolver<'a> {
947 session: &'a Session,
949 pub definitions: Definitions,
951 // Maps the node id of a statement to the expansions of the `macro_rules!`s
952 // immediately above the statement (if appropriate).
953 macros_at_scope: HashMap<NodeId, Vec<Mark>>,
955 graph_root: Module<'a>,
957 prelude: Option<Module<'a>>,
959 trait_item_map: FnvHashMap<(Name, DefId), bool /* is static method? */>,
961 structs: FnvHashMap<DefId, Vec<Name>>,
963 // The number of imports that are currently unresolved.
964 unresolved_imports: usize,
966 // The module that represents the current item scope.
967 current_module: Module<'a>,
969 // The current set of local scopes, for values.
970 // FIXME #4948: Reuse ribs to avoid allocation.
971 value_ribs: Vec<Rib<'a>>,
973 // The current set of local scopes, for types.
974 type_ribs: Vec<Rib<'a>>,
976 // The current set of local scopes, for labels.
977 label_ribs: Vec<Rib<'a>>,
979 // The trait that the current context can refer to.
980 current_trait_ref: Option<(DefId, TraitRef)>,
982 // The current self type if inside an impl (used for better errors).
983 current_self_type: Option<Ty>,
985 // The idents for the primitive types.
986 primitive_type_table: PrimitiveTypeTable,
989 pub freevars: FreevarMap,
990 freevars_seen: NodeMap<NodeMap<usize>>,
991 pub export_map: ExportMap,
992 pub trait_map: TraitMap,
994 // A map from nodes to modules, both normal (`mod`) modules and anonymous modules.
995 // Anonymous modules are pseudo-modules that are implicitly created around items
996 // contained within blocks.
998 // For example, if we have this:
1006 // There will be an anonymous module created around `g` with the ID of the
1007 // entry block for `f`.
1008 module_map: NodeMap<Module<'a>>,
1010 // Whether or not to print error messages. Can be set to true
1011 // when getting additional info for error message suggestions,
1012 // so as to avoid printing duplicate errors
1015 pub make_glob_map: bool,
1016 // Maps imports to the names of items actually imported (this actually maps
1017 // all imports, but only glob imports are actually interesting).
1018 pub glob_map: GlobMap,
1020 used_imports: HashSet<(NodeId, Namespace)>,
1021 used_crates: HashSet<CrateNum>,
1022 pub maybe_unused_trait_imports: NodeSet,
1024 privacy_errors: Vec<PrivacyError<'a>>,
1026 arenas: &'a ResolverArenas<'a>,
1029 pub struct ResolverArenas<'a> {
1030 modules: arena::TypedArena<ModuleS<'a>>,
1031 local_modules: RefCell<Vec<Module<'a>>>,
1032 name_bindings: arena::TypedArena<NameBinding<'a>>,
1033 import_directives: arena::TypedArena<ImportDirective<'a>>,
1034 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1037 impl<'a> ResolverArenas<'a> {
1038 fn alloc_module(&'a self, module: ModuleS<'a>) -> Module<'a> {
1039 let module = self.modules.alloc(module);
1040 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1041 self.local_modules.borrow_mut().push(module);
1045 fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1046 self.local_modules.borrow()
1048 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1049 self.name_bindings.alloc(name_binding)
1051 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1052 -> &'a ImportDirective {
1053 self.import_directives.alloc(import_directive)
1055 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1056 self.name_resolutions.alloc(Default::default())
1060 impl<'a> ty::NodeIdTree for Resolver<'a> {
1061 fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool {
1062 let ancestor = self.definitions.local_def_id(ancestor);
1063 let mut module = *self.module_map.get(&node).unwrap();
1064 while module.def_id() != Some(ancestor) {
1065 let module_parent = match self.get_nearest_normal_module_parent(module) {
1066 Some(parent) => parent,
1067 None => return false,
1069 module = module_parent;
1075 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1076 fn resolve_generated_global_path(&mut self, path: &hir::Path, is_value: bool) -> Def {
1077 let namespace = if is_value { ValueNS } else { TypeNS };
1078 match self.resolve_crate_relative_path(path.span, &path.segments, namespace) {
1079 Ok(binding) => binding.def().unwrap(),
1080 Err(true) => Def::Err,
1082 let path_name = &format!("{}", path);
1084 ResolutionError::UnresolvedName {
1087 context: UnresolvedNameContext::Other,
1088 is_static_method: false,
1092 resolve_error(self, path.span, error);
1098 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1099 self.def_map.get(&id).cloned()
1102 fn record_resolution(&mut self, id: NodeId, def: Def) {
1103 self.def_map.insert(id, PathResolution::new(def));
1106 fn definitions(&mut self) -> Option<&mut Definitions> {
1107 Some(&mut self.definitions)
1112 fn name(&self) -> Name;
1115 impl Named for ast::PathSegment {
1116 fn name(&self) -> Name {
1117 self.identifier.name
1121 impl Named for hir::PathSegment {
1122 fn name(&self) -> Name {
1127 impl<'a> Resolver<'a> {
1128 pub fn new(session: &'a Session, make_glob_map: MakeGlobMap, arenas: &'a ResolverArenas<'a>)
1130 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1132 ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, arenas);
1133 let graph_root = arenas.alloc_module(graph_root);
1134 let mut module_map = NodeMap();
1135 module_map.insert(CRATE_NODE_ID, graph_root);
1140 definitions: Definitions::new(),
1141 macros_at_scope: HashMap::new(),
1143 // The outermost module has def ID 0; this is not reflected in the
1145 graph_root: graph_root,
1148 trait_item_map: FnvHashMap(),
1149 structs: FnvHashMap(),
1151 unresolved_imports: 0,
1153 current_module: graph_root,
1154 value_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
1155 type_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
1156 label_ribs: Vec::new(),
1158 current_trait_ref: None,
1159 current_self_type: None,
1161 primitive_type_table: PrimitiveTypeTable::new(),
1164 freevars: NodeMap(),
1165 freevars_seen: NodeMap(),
1166 export_map: NodeMap(),
1167 trait_map: NodeMap(),
1168 module_map: module_map,
1171 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1172 glob_map: NodeMap(),
1174 used_imports: HashSet::new(),
1175 used_crates: HashSet::new(),
1176 maybe_unused_trait_imports: NodeSet(),
1178 privacy_errors: Vec::new(),
1184 pub fn arenas() -> ResolverArenas<'a> {
1186 modules: arena::TypedArena::new(),
1187 local_modules: RefCell::new(Vec::new()),
1188 name_bindings: arena::TypedArena::new(),
1189 import_directives: arena::TypedArena::new(),
1190 name_resolutions: arena::TypedArena::new(),
1194 /// Entry point to crate resolution.
1195 pub fn resolve_crate(&mut self, krate: &Crate) {
1196 self.current_module = self.graph_root;
1197 visit::walk_crate(self, krate);
1199 check_unused::check_crate(self, krate);
1200 self.report_privacy_errors();
1203 fn new_module(&self, parent_link: ParentLink<'a>, def: Option<Def>, external: bool)
1205 self.arenas.alloc_module(ModuleS::new(parent_link, def, external, self.arenas))
1208 fn new_extern_crate_module(&self, parent_link: ParentLink<'a>, def: Def, local_node_id: NodeId)
1210 let mut module = ModuleS::new(parent_link, Some(def), false, self.arenas);
1211 module.extern_crate_id = Some(local_node_id);
1212 self.arenas.modules.alloc(module)
1215 fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
1216 match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
1219 fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>) {
1220 // track extern crates for unused_extern_crate lint
1221 if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
1222 self.used_crates.insert(krate);
1225 if let NameBindingKind::Import { directive, .. } = binding.kind {
1226 self.used_imports.insert((directive.id, ns));
1227 self.add_to_glob_map(directive.id, name);
1231 fn add_to_glob_map(&mut self, id: NodeId, name: Name) {
1232 if self.make_glob_map {
1233 self.glob_map.entry(id).or_insert_with(FnvHashSet).insert(name);
1237 /// Resolves the given module path from the given root `search_module`.
1238 fn resolve_module_path_from_root(&mut self,
1239 mut search_module: Module<'a>,
1240 module_path: &[Name],
1243 -> ResolveResult<Module<'a>> {
1244 fn search_parent_externals(needle: Name, module: Module) -> Option<Module> {
1245 match module.resolve_name(needle, TypeNS, false) {
1246 Success(binding) if binding.is_extern_crate() => Some(module),
1247 _ => match module.parent_link {
1248 ModuleParentLink(ref parent, _) => {
1249 search_parent_externals(needle, parent)
1256 let mut index = index;
1257 let module_path_len = module_path.len();
1259 // Resolve the module part of the path. This does not involve looking
1260 // upward though scope chains; we simply resolve names directly in
1261 // modules as we go.
1262 while index < module_path_len {
1263 let name = module_path[index];
1264 match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1266 let segment_name = name.as_str();
1267 let module_name = module_to_string(search_module);
1268 let msg = if "???" == &module_name {
1269 match search_parent_externals(name, &self.current_module) {
1271 let path_str = names_to_string(module_path);
1272 let target_mod_str = module_to_string(&module);
1273 let current_mod_str = module_to_string(&self.current_module);
1275 let prefix = if target_mod_str == current_mod_str {
1276 "self::".to_string()
1278 format!("{}::", target_mod_str)
1281 format!("Did you mean `{}{}`?", prefix, path_str)
1283 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1286 format!("Could not find `{}` in `{}`", segment_name, module_name)
1289 return Failed(Some((span, msg)));
1291 Failed(err) => return Failed(err),
1293 debug!("(resolving module path for import) module resolution is \
1296 return Indeterminate;
1298 Success(binding) => {
1299 // Check to see whether there are type bindings, and, if
1300 // so, whether there is a module within.
1301 if let Some(module_def) = binding.module() {
1302 self.check_privacy(name, binding, span);
1303 search_module = module_def;
1305 let msg = format!("Not a module `{}`", name);
1306 return Failed(Some((span, msg)));
1314 return Success(search_module);
1317 /// Attempts to resolve the module part of an import directive or path
1318 /// rooted at the given module.
1319 fn resolve_module_path(&mut self,
1320 module_path: &[Name],
1321 use_lexical_scope: UseLexicalScopeFlag,
1323 -> ResolveResult<Module<'a>> {
1324 if module_path.len() == 0 {
1325 return Success(self.graph_root) // Use the crate root
1328 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1329 names_to_string(module_path),
1330 module_to_string(self.current_module));
1332 // Resolve the module prefix, if any.
1333 let module_prefix_result = self.resolve_module_prefix(module_path, span);
1337 match module_prefix_result {
1338 Failed(err) => return Failed(err),
1340 debug!("(resolving module path for import) indeterminate; bailing");
1341 return Indeterminate;
1343 Success(NoPrefixFound) => {
1344 // There was no prefix, so we're considering the first element
1345 // of the path. How we handle this depends on whether we were
1346 // instructed to use lexical scope or not.
1347 match use_lexical_scope {
1348 DontUseLexicalScope => {
1349 // This is a crate-relative path. We will start the
1350 // resolution process at index zero.
1351 search_module = self.graph_root;
1354 UseLexicalScope => {
1355 // This is not a crate-relative path. We resolve the
1356 // first component of the path in the current lexical
1357 // scope and then proceed to resolve below that.
1358 let ident = ast::Ident::with_empty_ctxt(module_path[0]);
1359 match self.resolve_ident_in_lexical_scope(ident, TypeNS, true)
1360 .and_then(LexicalScopeBinding::module) {
1361 None => return Failed(None),
1362 Some(containing_module) => {
1363 search_module = containing_module;
1370 Success(PrefixFound(ref containing_module, index)) => {
1371 search_module = containing_module;
1372 start_index = index;
1376 self.resolve_module_path_from_root(search_module,
1382 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
1383 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
1384 /// `ident` in the first scope that defines it (or None if no scopes define it).
1386 /// A block's items are above its local variables in the scope hierarchy, regardless of where
1387 /// the items are defined in the block. For example,
1390 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
1393 /// g(); // This resolves to the local variable `g` since it shadows the item.
1397 /// Invariant: This must only be called during main resolution, not during
1398 /// import resolution.
1399 fn resolve_ident_in_lexical_scope(&mut self,
1400 mut ident: ast::Ident,
1403 -> Option<LexicalScopeBinding<'a>> {
1405 ident = ast::Ident::with_empty_ctxt(ident.name);
1408 // Walk backwards up the ribs in scope.
1409 for i in (0 .. self.get_ribs(ns).len()).rev() {
1410 if let Some(def) = self.get_ribs(ns)[i].bindings.get(&ident).cloned() {
1411 // The ident resolves to a type parameter or local variable.
1412 return Some(LexicalScopeBinding::LocalDef(LocalDef {
1413 ribs: Some((ns, i)),
1418 if let ModuleRibKind(module) = self.get_ribs(ns)[i].kind {
1419 let name = ident.name;
1420 let item = self.resolve_name_in_module(module, name, ns, true, record_used);
1421 if let Success(binding) = item {
1422 // The ident resolves to an item.
1423 return Some(LexicalScopeBinding::Item(binding));
1426 // We can only see through anonymous modules
1427 if module.def.is_some() {
1428 return match self.prelude {
1429 Some(prelude) if !module.no_implicit_prelude.get() => {
1430 prelude.resolve_name(name, ns, false).success()
1431 .map(LexicalScopeBinding::Item)
1438 if let MacroDefinition(mac) = self.get_ribs(ns)[i].kind {
1439 // If an invocation of this macro created `ident`, give up on `ident`
1440 // and switch to `ident`'s source from the macro definition.
1441 let (source_ctxt, source_macro) = ident.ctxt.source();
1442 if source_macro == mac {
1443 ident.ctxt = source_ctxt;
1451 /// Returns the nearest normal module parent of the given module.
1452 fn get_nearest_normal_module_parent(&self, mut module: Module<'a>) -> Option<Module<'a>> {
1454 match module.parent_link {
1455 NoParentLink => return None,
1456 ModuleParentLink(new_module, _) |
1457 BlockParentLink(new_module, _) => {
1458 let new_module = new_module;
1459 if new_module.is_normal() {
1460 return Some(new_module);
1462 module = new_module;
1468 /// Returns the nearest normal module parent of the given module, or the
1469 /// module itself if it is a normal module.
1470 fn get_nearest_normal_module_parent_or_self(&self, module: Module<'a>) -> Module<'a> {
1471 if module.is_normal() {
1474 match self.get_nearest_normal_module_parent(module) {
1476 Some(new_module) => new_module,
1480 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1481 /// (b) some chain of `super::`.
1482 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1483 fn resolve_module_prefix(&mut self, module_path: &[Name], span: Span)
1484 -> ResolveResult<ModulePrefixResult<'a>> {
1485 // Start at the current module if we see `self` or `super`, or at the
1486 // top of the crate otherwise.
1487 let mut i = match &*module_path[0].as_str() {
1490 _ => return Success(NoPrefixFound),
1492 let mut containing_module =
1493 self.get_nearest_normal_module_parent_or_self(self.current_module);
1495 // Now loop through all the `super`s we find.
1496 while i < module_path.len() && "super" == module_path[i].as_str() {
1497 debug!("(resolving module prefix) resolving `super` at {}",
1498 module_to_string(&containing_module));
1499 match self.get_nearest_normal_module_parent(containing_module) {
1501 let msg = "There are too many initial `super`s.".into();
1502 return Failed(Some((span, msg)));
1504 Some(new_module) => {
1505 containing_module = new_module;
1511 debug!("(resolving module prefix) finished resolving prefix at {}",
1512 module_to_string(&containing_module));
1514 return Success(PrefixFound(containing_module, i));
1517 /// Attempts to resolve the supplied name in the given module for the
1518 /// given namespace. If successful, returns the binding corresponding to
1520 fn resolve_name_in_module(&mut self,
1523 namespace: Namespace,
1524 use_lexical_scope: bool,
1526 -> ResolveResult<&'a NameBinding<'a>> {
1527 debug!("(resolving name in module) resolving `{}` in `{}`", name, module_to_string(module));
1529 self.populate_module_if_necessary(module);
1530 module.resolve_name(name, namespace, use_lexical_scope).and_then(|binding| {
1532 self.record_use(name, namespace, binding);
1540 // We maintain a list of value ribs and type ribs.
1542 // Simultaneously, we keep track of the current position in the module
1543 // graph in the `current_module` pointer. When we go to resolve a name in
1544 // the value or type namespaces, we first look through all the ribs and
1545 // then query the module graph. When we resolve a name in the module
1546 // namespace, we can skip all the ribs (since nested modules are not
1547 // allowed within blocks in Rust) and jump straight to the current module
1550 // Named implementations are handled separately. When we find a method
1551 // call, we consult the module node to find all of the implementations in
1552 // scope. This information is lazily cached in the module node. We then
1553 // generate a fake "implementation scope" containing all the
1554 // implementations thus found, for compatibility with old resolve pass.
1556 fn with_scope<F>(&mut self, id: NodeId, f: F)
1557 where F: FnOnce(&mut Resolver)
1559 let module = self.module_map.get(&id).cloned(); // clones a reference
1560 if let Some(module) = module {
1561 // Move down in the graph.
1562 let orig_module = ::std::mem::replace(&mut self.current_module, module);
1563 self.value_ribs.push(Rib::new(ModuleRibKind(module)));
1564 self.type_ribs.push(Rib::new(ModuleRibKind(module)));
1568 self.current_module = orig_module;
1569 self.value_ribs.pop();
1570 self.type_ribs.pop();
1576 /// Searches the current set of local scopes for labels.
1577 /// Stops after meeting a closure.
1578 fn search_label(&self, mut ident: ast::Ident) -> Option<Def> {
1579 for rib in self.label_ribs.iter().rev() {
1584 MacroDefinition(mac) => {
1585 // If an invocation of this macro created `ident`, give up on `ident`
1586 // and switch to `ident`'s source from the macro definition.
1587 let (source_ctxt, source_macro) = ident.ctxt.source();
1588 if source_macro == mac {
1589 ident.ctxt = source_ctxt;
1593 // Do not resolve labels across function boundary
1597 let result = rib.bindings.get(&ident).cloned();
1598 if result.is_some() {
1605 fn resolve_item(&mut self, item: &Item) {
1606 let name = item.ident.name;
1608 debug!("(resolving item) resolving {}", name);
1611 ItemKind::Enum(_, ref generics) |
1612 ItemKind::Ty(_, ref generics) |
1613 ItemKind::Struct(_, ref generics) |
1614 ItemKind::Fn(_, _, _, _, ref generics, _) => {
1615 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
1616 |this| visit::walk_item(this, item));
1619 ItemKind::DefaultImpl(_, ref trait_ref) => {
1620 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1622 ItemKind::Impl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
1623 self.resolve_implementation(generics,
1629 ItemKind::Trait(_, ref generics, ref bounds, ref trait_items) => {
1630 // Create a new rib for the trait-wide type parameters.
1631 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
1632 let local_def_id = this.definitions.local_def_id(item.id);
1633 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1634 this.visit_generics(generics);
1635 walk_list!(this, visit_ty_param_bound, bounds);
1637 for trait_item in trait_items {
1638 match trait_item.node {
1639 TraitItemKind::Const(_, ref default) => {
1640 // Only impose the restrictions of
1641 // ConstRibKind if there's an actual constant
1642 // expression in a provided default.
1643 if default.is_some() {
1644 this.with_constant_rib(|this| {
1645 visit::walk_trait_item(this, trait_item)
1648 visit::walk_trait_item(this, trait_item)
1651 TraitItemKind::Method(ref sig, _) => {
1652 let type_parameters =
1653 HasTypeParameters(&sig.generics,
1654 MethodRibKind(!sig.decl.has_self()));
1655 this.with_type_parameter_rib(type_parameters, |this| {
1656 visit::walk_trait_item(this, trait_item)
1659 TraitItemKind::Type(..) => {
1660 this.with_type_parameter_rib(NoTypeParameters, |this| {
1661 visit::walk_trait_item(this, trait_item)
1664 TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1671 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1672 self.with_scope(item.id, |this| {
1673 visit::walk_item(this, item);
1677 ItemKind::Const(..) | ItemKind::Static(..) => {
1678 self.with_constant_rib(|this| {
1679 visit::walk_item(this, item);
1683 ItemKind::Use(ref view_path) => {
1684 match view_path.node {
1685 ast::ViewPathList(ref prefix, ref items) => {
1686 // Resolve prefix of an import with empty braces (issue #28388)
1687 if items.is_empty() && !prefix.segments.is_empty() {
1688 match self.resolve_crate_relative_path(prefix.span,
1692 let def = binding.def().unwrap();
1693 self.record_def(item.id, PathResolution::new(def));
1695 Err(true) => self.record_def(item.id, err_path_resolution()),
1699 ResolutionError::FailedToResolve(
1700 &path_names_to_string(prefix, 0)));
1701 self.record_def(item.id, err_path_resolution());
1710 ItemKind::ExternCrate(_) => {
1711 // do nothing, these are just around to be encoded
1714 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
1718 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
1719 where F: FnOnce(&mut Resolver)
1721 match type_parameters {
1722 HasTypeParameters(generics, rib_kind) => {
1723 let mut function_type_rib = Rib::new(rib_kind);
1724 let mut seen_bindings = HashSet::new();
1725 for type_parameter in &generics.ty_params {
1726 let name = type_parameter.ident.name;
1727 debug!("with_type_parameter_rib: {}", type_parameter.id);
1729 if seen_bindings.contains(&name) {
1731 type_parameter.span,
1732 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1734 seen_bindings.insert(name);
1736 // plain insert (no renaming)
1737 let def_id = self.definitions.local_def_id(type_parameter.id);
1738 let def = Def::TyParam(def_id);
1739 function_type_rib.bindings.insert(ast::Ident::with_empty_ctxt(name), def);
1740 self.record_def(type_parameter.id, PathResolution::new(def));
1742 self.type_ribs.push(function_type_rib);
1745 NoTypeParameters => {
1752 if let HasTypeParameters(..) = type_parameters {
1753 self.type_ribs.pop();
1757 fn with_label_rib<F>(&mut self, f: F)
1758 where F: FnOnce(&mut Resolver)
1760 self.label_ribs.push(Rib::new(NormalRibKind));
1762 self.label_ribs.pop();
1765 fn with_constant_rib<F>(&mut self, f: F)
1766 where F: FnOnce(&mut Resolver)
1768 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1769 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1771 self.type_ribs.pop();
1772 self.value_ribs.pop();
1775 fn resolve_function(&mut self,
1776 rib_kind: RibKind<'a>,
1777 declaration: &FnDecl,
1779 // Create a value rib for the function.
1780 self.value_ribs.push(Rib::new(rib_kind));
1782 // Create a label rib for the function.
1783 self.label_ribs.push(Rib::new(rib_kind));
1785 // Add each argument to the rib.
1786 let mut bindings_list = HashMap::new();
1787 for argument in &declaration.inputs {
1788 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
1790 self.visit_ty(&argument.ty);
1792 debug!("(resolving function) recorded argument");
1794 visit::walk_fn_ret_ty(self, &declaration.output);
1796 // Resolve the function body.
1797 self.visit_block(block);
1799 debug!("(resolving function) leaving function");
1801 self.label_ribs.pop();
1802 self.value_ribs.pop();
1805 fn resolve_trait_reference(&mut self,
1809 -> Result<PathResolution, ()> {
1810 self.resolve_path(id, trait_path, path_depth, TypeNS).and_then(|path_res| {
1811 match path_res.base_def {
1813 debug!("(resolving trait) found trait def: {:?}", path_res);
1814 return Ok(path_res);
1816 Def::Err => return Err(true),
1820 let mut err = resolve_struct_error(self, trait_path.span, {
1821 ResolutionError::IsNotATrait(&path_names_to_string(trait_path, path_depth))
1824 // If it's a typedef, give a note
1825 if let Def::TyAlias(..) = path_res.base_def {
1826 err.note(&format!("type aliases cannot be used for traits"));
1830 }).map_err(|error_reported| {
1831 if error_reported { return }
1833 // find possible candidates
1834 let trait_name = trait_path.segments.last().unwrap().identifier.name;
1836 self.lookup_candidates(
1840 Def::Trait(_) => true,
1845 // create error object
1846 let name = &path_names_to_string(trait_path, path_depth);
1848 ResolutionError::UndeclaredTraitName(
1853 resolve_error(self, trait_path.span, error);
1857 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
1858 where F: FnOnce(&mut Resolver) -> T
1860 // Handle nested impls (inside fn bodies)
1861 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
1862 let result = f(self);
1863 self.current_self_type = previous_value;
1867 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
1868 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
1870 let mut new_val = None;
1871 let mut new_id = None;
1872 if let Some(trait_ref) = opt_trait_ref {
1873 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
1876 assert!(path_res.depth == 0);
1877 self.record_def(trait_ref.ref_id, path_res);
1878 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
1879 new_id = Some(path_res.base_def.def_id());
1881 self.record_def(trait_ref.ref_id, err_path_resolution());
1883 visit::walk_trait_ref(self, trait_ref);
1885 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1886 let result = f(self, new_id);
1887 self.current_trait_ref = original_trait_ref;
1891 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
1892 where F: FnOnce(&mut Resolver)
1894 let mut self_type_rib = Rib::new(NormalRibKind);
1896 // plain insert (no renaming, types are not currently hygienic....)
1897 self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
1898 self.type_ribs.push(self_type_rib);
1900 self.type_ribs.pop();
1903 fn resolve_implementation(&mut self,
1904 generics: &Generics,
1905 opt_trait_reference: &Option<TraitRef>,
1908 impl_items: &[ImplItem]) {
1909 // If applicable, create a rib for the type parameters.
1910 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
1911 // Resolve the type parameters.
1912 this.visit_generics(generics);
1914 // Resolve the trait reference, if necessary.
1915 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1916 // Resolve the self type.
1917 this.visit_ty(self_type);
1919 this.with_self_rib(Def::SelfTy(trait_id, Some(item_id)), |this| {
1920 this.with_current_self_type(self_type, |this| {
1921 for impl_item in impl_items {
1922 this.resolve_visibility(&impl_item.vis);
1923 match impl_item.node {
1924 ImplItemKind::Const(..) => {
1925 // If this is a trait impl, ensure the const
1927 this.check_trait_item(impl_item.ident.name,
1929 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
1930 visit::walk_impl_item(this, impl_item);
1932 ImplItemKind::Method(ref sig, _) => {
1933 // If this is a trait impl, ensure the method
1935 this.check_trait_item(impl_item.ident.name,
1937 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
1939 // We also need a new scope for the method-
1940 // specific type parameters.
1941 let type_parameters =
1942 HasTypeParameters(&sig.generics,
1943 MethodRibKind(!sig.decl.has_self()));
1944 this.with_type_parameter_rib(type_parameters, |this| {
1945 visit::walk_impl_item(this, impl_item);
1948 ImplItemKind::Type(ref ty) => {
1949 // If this is a trait impl, ensure the type
1951 this.check_trait_item(impl_item.ident.name,
1953 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
1957 ImplItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1966 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
1967 where F: FnOnce(Name, &str) -> ResolutionError
1969 // If there is a TraitRef in scope for an impl, then the method must be in the
1971 if let Some((did, ref trait_ref)) = self.current_trait_ref {
1972 if !self.trait_item_map.contains_key(&(name, did)) {
1973 let path_str = path_names_to_string(&trait_ref.path, 0);
1974 resolve_error(self, span, err(name, &path_str));
1979 fn resolve_local(&mut self, local: &Local) {
1980 // Resolve the type.
1981 walk_list!(self, visit_ty, &local.ty);
1983 // Resolve the initializer.
1984 walk_list!(self, visit_expr, &local.init);
1986 // Resolve the pattern.
1987 self.resolve_pattern(&local.pat, PatternSource::Let, &mut HashMap::new());
1990 // build a map from pattern identifiers to binding-info's.
1991 // this is done hygienically. This could arise for a macro
1992 // that expands into an or-pattern where one 'x' was from the
1993 // user and one 'x' came from the macro.
1994 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1995 let mut binding_map = HashMap::new();
1997 pat.walk(&mut |pat| {
1998 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
1999 if sub_pat.is_some() || match self.def_map.get(&pat.id) {
2000 Some(&PathResolution { base_def: Def::Local(..), .. }) => true,
2003 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2004 binding_map.insert(ident.node, binding_info);
2013 // check that all of the arms in an or-pattern have exactly the
2014 // same set of bindings, with the same binding modes for each.
2015 fn check_consistent_bindings(&mut self, arm: &Arm) {
2016 if arm.pats.is_empty() {
2019 let map_0 = self.binding_mode_map(&arm.pats[0]);
2020 for (i, p) in arm.pats.iter().enumerate() {
2021 let map_i = self.binding_mode_map(&p);
2023 for (&key, &binding_0) in &map_0 {
2024 match map_i.get(&key) {
2026 let error = ResolutionError::VariableNotBoundInPattern(key.name, 1, i + 1);
2027 resolve_error(self, p.span, error);
2029 Some(binding_i) => {
2030 if binding_0.binding_mode != binding_i.binding_mode {
2033 ResolutionError::VariableBoundWithDifferentMode(key.name,
2040 for (&key, &binding) in &map_i {
2041 if !map_0.contains_key(&key) {
2044 ResolutionError::VariableNotBoundInPattern(key.name, i + 1, 1));
2050 fn resolve_arm(&mut self, arm: &Arm) {
2051 self.value_ribs.push(Rib::new(NormalRibKind));
2053 let mut bindings_list = HashMap::new();
2054 for pattern in &arm.pats {
2055 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2058 // This has to happen *after* we determine which
2059 // pat_idents are variants
2060 self.check_consistent_bindings(arm);
2062 walk_list!(self, visit_expr, &arm.guard);
2063 self.visit_expr(&arm.body);
2065 self.value_ribs.pop();
2068 fn resolve_block(&mut self, block: &Block) {
2069 debug!("(resolving block) entering block");
2070 // Move down in the graph, if there's an anonymous module rooted here.
2071 let orig_module = self.current_module;
2072 let anonymous_module = self.module_map.get(&block.id).cloned(); // clones a reference
2074 let mut num_macro_definition_ribs = 0;
2075 if let Some(anonymous_module) = anonymous_module {
2076 debug!("(resolving block) found anonymous module, moving down");
2077 self.value_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
2078 self.type_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
2079 self.current_module = anonymous_module;
2081 self.value_ribs.push(Rib::new(NormalRibKind));
2084 // Descend into the block.
2085 for stmt in &block.stmts {
2086 if let Some(marks) = self.macros_at_scope.remove(&stmt.id) {
2087 num_macro_definition_ribs += marks.len() as u32;
2089 self.value_ribs.push(Rib::new(MacroDefinition(mark)));
2090 self.label_ribs.push(Rib::new(MacroDefinition(mark)));
2094 self.visit_stmt(stmt);
2098 self.current_module = orig_module;
2099 for _ in 0 .. num_macro_definition_ribs {
2100 self.value_ribs.pop();
2101 self.label_ribs.pop();
2103 self.value_ribs.pop();
2104 if let Some(_) = anonymous_module {
2105 self.type_ribs.pop();
2107 debug!("(resolving block) leaving block");
2110 fn resolve_type(&mut self, ty: &Ty) {
2112 TyKind::Path(ref maybe_qself, ref path) => {
2113 // This is a path in the type namespace. Walk through scopes
2115 if let Some(def) = self.resolve_possibly_assoc_item(ty.id, maybe_qself.as_ref(),
2117 match def.base_def {
2118 Def::Mod(..) if def.depth == 0 => {
2119 self.session.span_err(path.span, "expected type, found module");
2120 self.record_def(ty.id, err_path_resolution());
2123 // Write the result into the def map.
2124 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2125 path_names_to_string(path, 0), ty.id, def);
2126 self.record_def(ty.id, def);
2130 self.record_def(ty.id, err_path_resolution());
2132 // Keep reporting some errors even if they're ignored above.
2133 if let Err(true) = self.resolve_path(ty.id, path, 0, TypeNS) {
2134 // `resolve_path` already reported the error
2136 let kind = if maybe_qself.is_some() {
2142 let is_invalid_self_type_name = path.segments.len() > 0 &&
2143 maybe_qself.is_none() &&
2144 path.segments[0].identifier.name ==
2145 keywords::SelfType.name();
2146 if is_invalid_self_type_name {
2149 ResolutionError::SelfUsedOutsideImplOrTrait);
2151 let segment = path.segments.last();
2152 let segment = segment.expect("missing name in path");
2153 let type_name = segment.identifier.name;
2156 self.lookup_candidates(
2163 Def::TyAlias(_) => true,
2168 // create error object
2169 let name = &path_names_to_string(path, 0);
2171 ResolutionError::UseOfUndeclared(
2177 resolve_error(self, ty.span, error);
2184 // Resolve embedded types.
2185 visit::walk_ty(self, ty);
2188 fn fresh_binding(&mut self,
2189 ident: &ast::SpannedIdent,
2191 outer_pat_id: NodeId,
2192 pat_src: PatternSource,
2193 bindings: &mut HashMap<ast::Ident, NodeId>)
2195 // Add the binding to the local ribs, if it
2196 // doesn't already exist in the bindings map. (We
2197 // must not add it if it's in the bindings map
2198 // because that breaks the assumptions later
2199 // passes make about or-patterns.)
2200 let mut def = Def::Local(self.definitions.local_def_id(pat_id), pat_id);
2201 match bindings.get(&ident.node).cloned() {
2202 Some(id) if id == outer_pat_id => {
2203 // `Variant(a, a)`, error
2207 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2208 &ident.node.name.as_str())
2211 Some(..) if pat_src == PatternSource::FnParam => {
2212 // `fn f(a: u8, a: u8)`, error
2216 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2217 &ident.node.name.as_str())
2220 Some(..) if pat_src == PatternSource::Match => {
2221 // `Variant1(a) | Variant2(a)`, ok
2222 // Reuse definition from the first `a`.
2223 def = self.value_ribs.last_mut().unwrap().bindings[&ident.node];
2226 span_bug!(ident.span, "two bindings with the same name from \
2227 unexpected pattern source {:?}", pat_src);
2230 // A completely fresh binding, add to the lists if it's valid.
2231 if ident.node.name != keywords::Invalid.name() {
2232 bindings.insert(ident.node, outer_pat_id);
2233 self.value_ribs.last_mut().unwrap().bindings.insert(ident.node, def);
2238 PathResolution::new(def)
2241 fn resolve_pattern_path<ExpectedFn>(&mut self,
2243 qself: Option<&QSelf>,
2245 namespace: Namespace,
2246 expected_fn: ExpectedFn,
2247 expected_what: &str)
2248 where ExpectedFn: FnOnce(Def) -> bool
2250 let resolution = if let Some(resolution) = self.resolve_possibly_assoc_item(pat_id,
2251 qself, path, namespace) {
2252 if resolution.depth == 0 {
2253 if expected_fn(resolution.base_def) || resolution.base_def == Def::Err {
2259 ResolutionError::PatPathUnexpected(expected_what,
2260 resolution.kind_name(), path)
2262 err_path_resolution()
2265 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
2266 // or `<T>::A::B`. If `B` should be resolved in value namespace then
2267 // it needs to be added to the trait map.
2268 if namespace == ValueNS {
2269 let item_name = path.segments.last().unwrap().identifier.name;
2270 let traits = self.get_traits_containing_item(item_name);
2271 self.trait_map.insert(pat_id, traits);
2276 if let Err(false) = self.resolve_path(pat_id, path, 0, namespace) {
2280 ResolutionError::PatPathUnresolved(expected_what, path)
2283 err_path_resolution()
2286 self.record_def(pat_id, resolution);
2289 fn resolve_pattern(&mut self,
2291 pat_src: PatternSource,
2292 // Maps idents to the node ID for the
2293 // outermost pattern that binds them.
2294 bindings: &mut HashMap<ast::Ident, NodeId>) {
2295 // Visit all direct subpatterns of this pattern.
2296 let outer_pat_id = pat.id;
2297 pat.walk(&mut |pat| {
2299 PatKind::Ident(bmode, ref ident, ref opt_pat) => {
2300 // First try to resolve the identifier as some existing
2301 // entity, then fall back to a fresh binding.
2302 let binding = self.resolve_ident_in_lexical_scope(ident.node, ValueNS, false)
2303 .and_then(LexicalScopeBinding::item);
2304 let resolution = binding.and_then(NameBinding::def).and_then(|def| {
2305 let always_binding = !pat_src.is_refutable() || opt_pat.is_some() ||
2306 bmode != BindingMode::ByValue(Mutability::Immutable);
2308 Def::Struct(..) | Def::Variant(..) |
2309 Def::Const(..) | Def::AssociatedConst(..) if !always_binding => {
2310 // A constant, unit variant, etc pattern.
2311 self.record_use(ident.node.name, ValueNS, binding.unwrap());
2312 Some(PathResolution::new(def))
2314 Def::Struct(..) | Def::Variant(..) |
2315 Def::Const(..) | Def::AssociatedConst(..) | Def::Static(..) => {
2316 // A fresh binding that shadows something unacceptable.
2320 ResolutionError::BindingShadowsSomethingUnacceptable(
2321 pat_src.descr(), ident.node.name, binding.unwrap())
2325 Def::Local(..) | Def::Upvar(..) | Def::Fn(..) | Def::Err => {
2326 // These entities are explicitly allowed
2327 // to be shadowed by fresh bindings.
2331 span_bug!(ident.span, "unexpected definition for an \
2332 identifier in pattern {:?}", def);
2335 }).unwrap_or_else(|| {
2336 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2339 self.record_def(pat.id, resolution);
2342 PatKind::TupleStruct(ref path, _, _) => {
2343 self.resolve_pattern_path(pat.id, None, path, ValueNS, |def| {
2345 Def::Struct(..) | Def::Variant(..) => true,
2348 }, "variant or struct");
2351 PatKind::Path(ref qself, ref path) => {
2352 self.resolve_pattern_path(pat.id, qself.as_ref(), path, ValueNS, |def| {
2354 Def::Struct(..) | Def::Variant(..) |
2355 Def::Const(..) | Def::AssociatedConst(..) => true,
2358 }, "variant, struct or constant");
2361 PatKind::Struct(ref path, _, _) => {
2362 self.resolve_pattern_path(pat.id, None, path, TypeNS, |def| {
2364 Def::Struct(..) | Def::Variant(..) |
2365 Def::TyAlias(..) | Def::AssociatedTy(..) => true,
2368 }, "variant, struct or type alias");
2376 visit::walk_pat(self, pat);
2379 /// Handles paths that may refer to associated items
2380 fn resolve_possibly_assoc_item(&mut self,
2382 maybe_qself: Option<&QSelf>,
2384 namespace: Namespace)
2385 -> Option<PathResolution> {
2386 let max_assoc_types;
2390 if qself.position == 0 {
2391 // FIXME: Create some fake resolution that can't possibly be a type.
2392 return Some(PathResolution {
2393 base_def: Def::Mod(self.definitions.local_def_id(ast::CRATE_NODE_ID)),
2394 depth: path.segments.len(),
2397 max_assoc_types = path.segments.len() - qself.position;
2398 // Make sure the trait is valid.
2399 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2402 max_assoc_types = path.segments.len();
2406 let mut resolution = self.with_no_errors(|this| {
2407 this.resolve_path(id, path, 0, namespace).ok()
2409 for depth in 1..max_assoc_types {
2410 if resolution.is_some() {
2413 self.with_no_errors(|this| {
2414 let partial_resolution = this.resolve_path(id, path, depth, TypeNS).ok();
2415 if let Some(Def::Mod(..)) = partial_resolution.map(|r| r.base_def) {
2416 // Modules cannot have associated items
2418 resolution = partial_resolution;
2425 /// Skips `path_depth` trailing segments, which is also reflected in the
2426 /// returned value. See `hir::def::PathResolution` for more info.
2427 fn resolve_path(&mut self, id: NodeId, path: &Path, path_depth: usize, namespace: Namespace)
2428 -> Result<PathResolution, bool /* true if an error was reported */ > {
2429 debug!("resolve_path(id={:?} path={:?}, path_depth={:?})", id, path, path_depth);
2431 let span = path.span;
2432 let segments = &path.segments[..path.segments.len() - path_depth];
2434 let mk_res = |def| PathResolution { base_def: def, depth: path_depth };
2437 let binding = self.resolve_crate_relative_path(span, segments, namespace);
2438 return binding.map(|binding| mk_res(binding.def().unwrap()));
2441 // Try to find a path to an item in a module.
2442 let last_ident = segments.last().unwrap().identifier;
2443 // Resolve a single identifier with fallback to primitive types
2444 let resolve_identifier_with_fallback = |this: &mut Self, record_used| {
2445 let def = this.resolve_identifier(last_ident, namespace, record_used);
2447 None | Some(LocalDef{def: Def::Mod(..), ..}) if namespace == TypeNS =>
2448 this.primitive_type_table
2450 .get(&last_ident.name)
2451 .map_or(def, |prim_ty| Some(LocalDef::from_def(Def::PrimTy(*prim_ty)))),
2456 if segments.len() == 1 {
2457 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
2458 // don't report an error right away, but try to fallback to a primitive type.
2459 // So, we are still able to successfully resolve something like
2461 // use std::u8; // bring module u8 in scope
2462 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
2463 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
2464 // // not to non-existent std::u8::max_value
2467 // Such behavior is required for backward compatibility.
2468 // The same fallback is used when `a` resolves to nothing.
2469 let def = resolve_identifier_with_fallback(self, true).ok_or(false);
2470 return def.and_then(|def| self.adjust_local_def(def, span).ok_or(true)).map(mk_res);
2473 let unqualified_def = resolve_identifier_with_fallback(self, false);
2474 let qualified_binding = self.resolve_module_relative_path(span, segments, namespace);
2475 match (qualified_binding, unqualified_def) {
2476 (Ok(binding), Some(ref ud)) if binding.def().unwrap() == ud.def => {
2478 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2481 "unnecessary qualification".to_string());
2486 qualified_binding.map(|binding| mk_res(binding.def().unwrap()))
2489 // Resolve a single identifier
2490 fn resolve_identifier(&mut self,
2491 identifier: ast::Ident,
2492 namespace: Namespace,
2494 -> Option<LocalDef> {
2495 if identifier.name == keywords::Invalid.name() {
2499 self.resolve_ident_in_lexical_scope(identifier, namespace, record_used)
2500 .map(LexicalScopeBinding::local_def)
2503 // Resolve a local definition, potentially adjusting for closures.
2504 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2505 let ribs = match local_def.ribs {
2506 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2507 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2510 let mut def = local_def.def;
2513 span_bug!(span, "unexpected {:?} in bindings", def)
2515 Def::Local(_, node_id) => {
2518 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) => {
2519 // Nothing to do. Continue.
2521 ClosureRibKind(function_id) => {
2523 let node_def_id = self.definitions.local_def_id(node_id);
2525 let seen = self.freevars_seen
2527 .or_insert_with(|| NodeMap());
2528 if let Some(&index) = seen.get(&node_id) {
2529 def = Def::Upvar(node_def_id, node_id, index, function_id);
2532 let vec = self.freevars
2534 .or_insert_with(|| vec![]);
2535 let depth = vec.len();
2541 def = Def::Upvar(node_def_id, node_id, depth, function_id);
2542 seen.insert(node_id, depth);
2544 ItemRibKind | MethodRibKind(_) => {
2545 // This was an attempt to access an upvar inside a
2546 // named function item. This is not allowed, so we
2550 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2553 ConstantItemRibKind => {
2554 // Still doesn't deal with upvars
2557 ResolutionError::AttemptToUseNonConstantValueInConstant);
2563 Def::TyParam(..) | Def::SelfTy(..) => {
2566 NormalRibKind | MethodRibKind(_) | ClosureRibKind(..) |
2567 ModuleRibKind(..) | MacroDefinition(..) => {
2568 // Nothing to do. Continue.
2571 // This was an attempt to use a type parameter outside
2576 ResolutionError::TypeParametersFromOuterFunction);
2579 ConstantItemRibKind => {
2581 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2592 // resolve a "module-relative" path, e.g. a::b::c
2593 fn resolve_module_relative_path(&mut self,
2595 segments: &[ast::PathSegment],
2596 namespace: Namespace)
2597 -> Result<&'a NameBinding<'a>,
2598 bool /* true if an error was reported */> {
2599 let module_path = segments.split_last()
2603 .map(|ps| ps.identifier.name)
2604 .collect::<Vec<_>>();
2606 let containing_module;
2607 match self.resolve_module_path(&module_path, UseLexicalScope, span) {
2609 let (span, msg) = match err {
2610 Some((span, msg)) => (span, msg),
2612 let msg = format!("Use of undeclared type or module `{}`",
2613 names_to_string(&module_path));
2618 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2621 Indeterminate => return Err(false),
2622 Success(resulting_module) => {
2623 containing_module = resulting_module;
2627 let name = segments.last().unwrap().identifier.name;
2628 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2629 result.success().map(|binding| {
2630 self.check_privacy(name, binding, span);
2635 /// Invariant: This must be called only during main resolution, not during
2636 /// import resolution.
2637 fn resolve_crate_relative_path<T>(&mut self, span: Span, segments: &[T], namespace: Namespace)
2638 -> Result<&'a NameBinding<'a>,
2639 bool /* true if an error was reported */>
2642 let module_path = segments.split_last().unwrap().1.iter().map(T::name).collect::<Vec<_>>();
2643 let root_module = self.graph_root;
2645 let containing_module;
2646 match self.resolve_module_path_from_root(root_module,
2651 let (span, msg) = match err {
2652 Some((span, msg)) => (span, msg),
2654 let msg = format!("Use of undeclared module `::{}`",
2655 names_to_string(&module_path));
2660 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2664 Indeterminate => return Err(false),
2666 Success(resulting_module) => {
2667 containing_module = resulting_module;
2671 let name = segments.last().unwrap().name();
2672 let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2673 result.success().map(|binding| {
2674 self.check_privacy(name, binding, span);
2679 fn with_no_errors<T, F>(&mut self, f: F) -> T
2680 where F: FnOnce(&mut Resolver) -> T
2682 self.emit_errors = false;
2684 self.emit_errors = true;
2688 // Calls `f` with a `Resolver` whose current lexical scope is `module`'s lexical scope,
2689 // i.e. the module's items and the prelude (unless the module is `#[no_implicit_prelude]`).
2690 // FIXME #34673: This needs testing.
2691 pub fn with_module_lexical_scope<T, F>(&mut self, module: Module<'a>, f: F) -> T
2692 where F: FnOnce(&mut Resolver<'a>) -> T,
2694 self.with_empty_ribs(|this| {
2695 this.value_ribs.push(Rib::new(ModuleRibKind(module)));
2696 this.type_ribs.push(Rib::new(ModuleRibKind(module)));
2701 fn with_empty_ribs<T, F>(&mut self, f: F) -> T
2702 where F: FnOnce(&mut Resolver<'a>) -> T,
2704 use ::std::mem::replace;
2705 let value_ribs = replace(&mut self.value_ribs, Vec::new());
2706 let type_ribs = replace(&mut self.type_ribs, Vec::new());
2707 let label_ribs = replace(&mut self.label_ribs, Vec::new());
2709 let result = f(self);
2710 self.value_ribs = value_ribs;
2711 self.type_ribs = type_ribs;
2712 self.label_ribs = label_ribs;
2716 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
2717 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2719 TyKind::Path(None, _) => Some(t.id),
2720 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2721 // This doesn't handle the remaining `Ty` variants as they are not
2722 // that commonly the self_type, it might be interesting to provide
2723 // support for those in future.
2728 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
2729 // Look for a field with the same name in the current self_type.
2730 if let Some(resolution) = self.def_map.get(&node_id) {
2731 match resolution.base_def {
2732 Def::Enum(did) | Def::TyAlias(did) |
2733 Def::Struct(did) | Def::Variant(_, did) if resolution.depth == 0 => {
2734 if let Some(fields) = self.structs.get(&did) {
2735 if fields.iter().any(|&field_name| name == field_name) {
2745 // Look for a method in the current trait.
2746 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
2747 if let Some(&is_static_method) = self.trait_item_map.get(&(name, trait_did)) {
2748 if is_static_method {
2749 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2759 fn find_best_match(&mut self, name: &str) -> SuggestionType {
2760 if let Some(macro_name) = self.session.available_macros
2761 .borrow().iter().find(|n| n.as_str() == name) {
2762 return SuggestionType::Macro(format!("{}!", macro_name));
2765 let names = self.value_ribs
2768 .flat_map(|rib| rib.bindings.keys().map(|ident| &ident.name));
2770 if let Some(found) = find_best_match_for_name(names, name, None) {
2772 return SuggestionType::Function(found);
2774 } SuggestionType::NotFound
2777 fn resolve_labeled_block(&mut self, label: Option<ast::Ident>, id: NodeId, block: &Block) {
2778 if let Some(label) = label {
2779 let def = Def::Label(id);
2780 self.with_label_rib(|this| {
2781 this.label_ribs.last_mut().unwrap().bindings.insert(label, def);
2782 this.visit_block(block);
2785 self.visit_block(block);
2789 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
2790 // First, record candidate traits for this expression if it could
2791 // result in the invocation of a method call.
2793 self.record_candidate_traits_for_expr_if_necessary(expr);
2795 // Next, resolve the node.
2797 ExprKind::Path(ref maybe_qself, ref path) => {
2798 // This is a local path in the value namespace. Walk through
2799 // scopes looking for it.
2800 if let Some(path_res) = self.resolve_possibly_assoc_item(expr.id,
2801 maybe_qself.as_ref(), path, ValueNS) {
2802 // Check if struct variant
2803 let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
2804 self.structs.contains_key(&variant_id)
2808 if is_struct_variant {
2809 let _ = self.structs.contains_key(&path_res.base_def.def_id());
2810 let path_name = path_names_to_string(path, 0);
2812 let mut err = resolve_struct_error(self,
2814 ResolutionError::StructVariantUsedAsFunction(&path_name));
2816 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2818 if self.emit_errors {
2821 err.span_help(expr.span, &msg);
2824 self.record_def(expr.id, err_path_resolution());
2826 // Write the result into the def map.
2827 debug!("(resolving expr) resolved `{}`",
2828 path_names_to_string(path, 0));
2830 // Partial resolutions will need the set of traits in scope,
2831 // so they can be completed during typeck.
2832 if path_res.depth != 0 {
2833 let method_name = path.segments.last().unwrap().identifier.name;
2834 let traits = self.get_traits_containing_item(method_name);
2835 self.trait_map.insert(expr.id, traits);
2838 self.record_def(expr.id, path_res);
2841 // Be helpful if the name refers to a struct
2842 // (The pattern matching def_tys where the id is in self.structs
2843 // matches on regular structs while excluding tuple- and enum-like
2844 // structs, which wouldn't result in this error.)
2845 let path_name = path_names_to_string(path, 0);
2846 let type_res = self.with_no_errors(|this| {
2847 this.resolve_path(expr.id, path, 0, TypeNS)
2850 self.record_def(expr.id, err_path_resolution());
2852 if let Ok(Def::Struct(..)) = type_res.map(|r| r.base_def) {
2854 ResolutionError::StructVariantUsedAsFunction(&path_name);
2855 let mut err = resolve_struct_error(self, expr.span, error_variant);
2857 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2860 if self.emit_errors {
2863 err.span_help(expr.span, &msg);
2867 // Keep reporting some errors even if they're ignored above.
2868 if let Err(true) = self.resolve_path(expr.id, path, 0, ValueNS) {
2869 // `resolve_path` already reported the error
2871 let mut method_scope = false;
2872 let mut is_static = false;
2873 self.value_ribs.iter().rev().all(|rib| {
2874 method_scope = match rib.kind {
2875 MethodRibKind(is_static_) => {
2876 is_static = is_static_;
2879 ItemRibKind | ConstantItemRibKind => false,
2880 _ => return true, // Keep advancing
2882 false // Stop advancing
2886 &path_name[..] == keywords::SelfValue.name().as_str() {
2889 ResolutionError::SelfNotAvailableInStaticMethod);
2891 let last_name = path.segments.last().unwrap().identifier.name;
2892 let (mut msg, is_field) =
2893 match self.find_fallback_in_self_type(last_name) {
2895 // limit search to 5 to reduce the number
2896 // of stupid suggestions
2897 (match self.find_best_match(&path_name) {
2898 SuggestionType::Macro(s) => {
2899 format!("the macro `{}`", s)
2901 SuggestionType::Function(s) => format!("`{}`", s),
2902 SuggestionType::NotFound => "".to_string(),
2906 (if is_static && method_scope {
2909 format!("`self.{}`", path_name)
2912 TraitItem => (format!("to call `self.{}`", path_name), false),
2913 TraitMethod(path_str) =>
2914 (format!("to call `{}::{}`", path_str, path_name), false),
2917 let mut context = UnresolvedNameContext::Other;
2918 let mut def = Def::Err;
2919 if !msg.is_empty() {
2920 msg = format!(". Did you mean {}?", msg);
2922 // we display a help message if this is a module
2923 let name_path = path.segments.iter()
2924 .map(|seg| seg.identifier.name)
2925 .collect::<Vec<_>>();
2927 match self.resolve_module_path(&name_path[..],
2931 if let Some(def_type) = e.def {
2934 context = UnresolvedNameContext::PathIsMod(parent);
2942 ResolutionError::UnresolvedName {
2946 is_static_method: method_scope && is_static,
2955 visit::walk_expr(self, expr);
2958 ExprKind::Struct(ref path, _, _) => {
2959 // Resolve the path to the structure it goes to. We don't
2960 // check to ensure that the path is actually a structure; that
2961 // is checked later during typeck.
2962 match self.resolve_path(expr.id, path, 0, TypeNS) {
2963 Ok(definition) => self.record_def(expr.id, definition),
2964 Err(true) => self.record_def(expr.id, err_path_resolution()),
2966 debug!("(resolving expression) didn't find struct def",);
2970 ResolutionError::DoesNotNameAStruct(
2971 &path_names_to_string(path, 0))
2973 self.record_def(expr.id, err_path_resolution());
2977 visit::walk_expr(self, expr);
2980 ExprKind::Loop(_, Some(label)) | ExprKind::While(_, _, Some(label)) => {
2981 self.with_label_rib(|this| {
2982 let def = Def::Label(expr.id);
2985 let rib = this.label_ribs.last_mut().unwrap();
2986 rib.bindings.insert(label.node, def);
2989 visit::walk_expr(this, expr);
2993 ExprKind::Break(Some(label)) | ExprKind::Continue(Some(label)) => {
2994 match self.search_label(label.node) {
2996 self.record_def(expr.id, err_path_resolution());
2999 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3001 Some(def @ Def::Label(_)) => {
3002 // Since this def is a label, it is never read.
3003 self.record_def(expr.id, PathResolution::new(def))
3006 span_bug!(expr.span, "label wasn't mapped to a label def!")
3011 ExprKind::IfLet(ref pattern, ref subexpression, ref if_block, ref optional_else) => {
3012 self.visit_expr(subexpression);
3014 self.value_ribs.push(Rib::new(NormalRibKind));
3015 self.resolve_pattern(pattern, PatternSource::IfLet, &mut HashMap::new());
3016 self.visit_block(if_block);
3017 self.value_ribs.pop();
3019 optional_else.as_ref().map(|expr| self.visit_expr(expr));
3022 ExprKind::WhileLet(ref pattern, ref subexpression, ref block, label) => {
3023 self.visit_expr(subexpression);
3024 self.value_ribs.push(Rib::new(NormalRibKind));
3025 self.resolve_pattern(pattern, PatternSource::WhileLet, &mut HashMap::new());
3027 self.resolve_labeled_block(label.map(|l| l.node), expr.id, block);
3029 self.value_ribs.pop();
3032 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
3033 self.visit_expr(subexpression);
3034 self.value_ribs.push(Rib::new(NormalRibKind));
3035 self.resolve_pattern(pattern, PatternSource::For, &mut HashMap::new());
3037 self.resolve_labeled_block(label.map(|l| l.node), expr.id, block);
3039 self.value_ribs.pop();
3042 ExprKind::Field(ref subexpression, _) => {
3043 self.resolve_expr(subexpression, Some(expr));
3045 ExprKind::MethodCall(_, ref types, ref arguments) => {
3046 let mut arguments = arguments.iter();
3047 self.resolve_expr(arguments.next().unwrap(), Some(expr));
3048 for argument in arguments {
3049 self.resolve_expr(argument, None);
3051 for ty in types.iter() {
3057 visit::walk_expr(self, expr);
3062 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3064 ExprKind::Field(_, name) => {
3065 // FIXME(#6890): Even though you can't treat a method like a
3066 // field, we need to add any trait methods we find that match
3067 // the field name so that we can do some nice error reporting
3068 // later on in typeck.
3069 let traits = self.get_traits_containing_item(name.node.name);
3070 self.trait_map.insert(expr.id, traits);
3072 ExprKind::MethodCall(name, _, _) => {
3073 debug!("(recording candidate traits for expr) recording traits for {}",
3075 let traits = self.get_traits_containing_item(name.node.name);
3076 self.trait_map.insert(expr.id, traits);
3084 fn get_traits_containing_item(&mut self, name: Name) -> Vec<TraitCandidate> {
3085 debug!("(getting traits containing item) looking for '{}'", name);
3087 fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
3088 trait_def_id: DefId,
3089 import_id: Option<NodeId>,
3091 debug!("(adding trait info) found trait {:?} for method '{}'",
3094 found_traits.push(TraitCandidate {
3095 def_id: trait_def_id,
3096 import_id: import_id,
3100 let mut found_traits = Vec::new();
3101 // Look for the current trait.
3102 if let Some((trait_def_id, _)) = self.current_trait_ref {
3103 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3104 add_trait_info(&mut found_traits, trait_def_id, None, name);
3108 let mut search_module = self.current_module;
3110 // Look for trait children.
3111 let mut search_in_module = |this: &mut Self, module: Module<'a>| {
3112 let mut traits = module.traits.borrow_mut();
3113 if traits.is_none() {
3114 let mut collected_traits = Vec::new();
3115 module.for_each_child(|name, ns, binding| {
3116 if ns != TypeNS { return }
3117 if let Some(Def::Trait(_)) = binding.def() {
3118 collected_traits.push((name, binding));
3121 *traits = Some(collected_traits.into_boxed_slice());
3124 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
3125 let trait_def_id = binding.def().unwrap().def_id();
3126 if this.trait_item_map.contains_key(&(name, trait_def_id)) {
3127 let mut import_id = None;
3128 if let NameBindingKind::Import { directive, .. } = binding.kind {
3129 let id = directive.id;
3130 this.maybe_unused_trait_imports.insert(id);
3131 this.add_to_glob_map(id, trait_name);
3132 import_id = Some(id);
3134 add_trait_info(&mut found_traits, trait_def_id, import_id, name);
3138 search_in_module(self, search_module);
3140 match search_module.parent_link {
3141 NoParentLink | ModuleParentLink(..) => {
3142 if !search_module.no_implicit_prelude.get() {
3143 self.prelude.map(|prelude| search_in_module(self, prelude));
3147 BlockParentLink(parent_module, _) => {
3148 search_module = parent_module;
3156 /// When name resolution fails, this method can be used to look up candidate
3157 /// entities with the expected name. It allows filtering them using the
3158 /// supplied predicate (which should be used to only accept the types of
3159 /// definitions expected e.g. traits). The lookup spans across all crates.
3161 /// NOTE: The method does not look into imports, but this is not a problem,
3162 /// since we report the definitions (thus, the de-aliased imports).
3163 fn lookup_candidates<FilterFn>(&mut self,
3165 namespace: Namespace,
3166 filter_fn: FilterFn) -> SuggestedCandidates
3167 where FilterFn: Fn(Def) -> bool {
3169 let mut lookup_results = Vec::new();
3170 let mut worklist = Vec::new();
3171 worklist.push((self.graph_root, Vec::new(), false));
3173 while let Some((in_module,
3175 in_module_is_extern)) = worklist.pop() {
3176 self.populate_module_if_necessary(in_module);
3178 in_module.for_each_child(|name, ns, name_binding| {
3180 // avoid imports entirely
3181 if name_binding.is_import() { return; }
3183 // collect results based on the filter function
3184 if let Some(def) = name_binding.def() {
3185 if name == lookup_name && ns == namespace && filter_fn(def) {
3187 let ident = ast::Ident::with_empty_ctxt(name);
3188 let params = PathParameters::none();
3189 let segment = PathSegment {
3193 let span = name_binding.span;
3194 let mut segms = path_segments.clone();
3195 segms.push(segment);
3201 // the entity is accessible in the following cases:
3202 // 1. if it's defined in the same crate, it's always
3203 // accessible (since private entities can be made public)
3204 // 2. if it's defined in another crate, it's accessible
3205 // only if both the module is public and the entity is
3206 // declared as public (due to pruning, we don't explore
3207 // outside crate private modules => no need to check this)
3208 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3209 lookup_results.push(path);
3214 // collect submodules to explore
3215 if let Some(module) = name_binding.module() {
3217 let path_segments = match module.parent_link {
3218 NoParentLink => path_segments.clone(),
3219 ModuleParentLink(_, name) => {
3220 let mut paths = path_segments.clone();
3221 let ident = ast::Ident::with_empty_ctxt(name);
3222 let params = PathParameters::none();
3223 let segm = PathSegment {
3233 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3234 // add the module to the lookup
3235 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3236 if !worklist.iter().any(|&(m, _, _)| m.def == module.def) {
3237 worklist.push((module, path_segments, is_extern));
3244 SuggestedCandidates {
3245 name: lookup_name.as_str().to_string(),
3246 candidates: lookup_results,
3250 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3251 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3252 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3253 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3257 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
3258 let (path, id) = match *vis {
3259 ast::Visibility::Public => return ty::Visibility::Public,
3260 ast::Visibility::Crate(_) => return ty::Visibility::Restricted(ast::CRATE_NODE_ID),
3261 ast::Visibility::Restricted { ref path, id } => (path, id),
3262 ast::Visibility::Inherited => {
3263 let current_module =
3264 self.get_nearest_normal_module_parent_or_self(self.current_module);
3266 self.definitions.as_local_node_id(current_module.def_id().unwrap()).unwrap();
3267 return ty::Visibility::Restricted(id);
3271 let segments: Vec<_> = path.segments.iter().map(|seg| seg.identifier.name).collect();
3272 let mut path_resolution = err_path_resolution();
3273 let vis = match self.resolve_module_path(&segments, DontUseLexicalScope, path.span) {
3274 Success(module) => {
3275 let def = module.def.unwrap();
3276 path_resolution = PathResolution::new(def);
3277 ty::Visibility::Restricted(self.definitions.as_local_node_id(def.def_id()).unwrap())
3279 Failed(Some((span, msg))) => {
3280 self.session.span_err(span, &format!("failed to resolve module path. {}", msg));
3281 ty::Visibility::Public
3284 self.session.span_err(path.span, "unresolved module path");
3285 ty::Visibility::Public
3288 self.def_map.insert(id, path_resolution);
3289 if !self.is_accessible(vis) {
3290 let msg = format!("visibilities can only be restricted to ancestor modules");
3291 self.session.span_err(path.span, &msg);
3296 fn is_accessible(&self, vis: ty::Visibility) -> bool {
3297 let current_module = self.get_nearest_normal_module_parent_or_self(self.current_module);
3298 let node_id = self.definitions.as_local_node_id(current_module.def_id().unwrap()).unwrap();
3299 vis.is_accessible_from(node_id, self)
3302 fn check_privacy(&mut self, name: Name, binding: &'a NameBinding<'a>, span: Span) {
3303 if !self.is_accessible(binding.vis) {
3304 self.privacy_errors.push(PrivacyError(span, name, binding));
3308 fn report_privacy_errors(&self) {
3309 if self.privacy_errors.len() == 0 { return }
3310 let mut reported_spans = HashSet::new();
3311 for &PrivacyError(span, name, binding) in &self.privacy_errors {
3312 if !reported_spans.insert(span) { continue }
3313 if binding.is_extern_crate() {
3314 // Warn when using an inaccessible extern crate.
3315 let node_id = binding.module().unwrap().extern_crate_id.unwrap();
3316 let msg = format!("extern crate `{}` is private", name);
3317 self.session.add_lint(lint::builtin::INACCESSIBLE_EXTERN_CRATE, node_id, span, msg);
3319 let def = binding.def().unwrap();
3320 self.session.span_err(span, &format!("{} `{}` is private", def.kind_name(), name));
3325 fn report_conflict(&self,
3329 binding: &NameBinding,
3330 old_binding: &NameBinding) {
3331 // Error on the second of two conflicting names
3332 if old_binding.span.lo > binding.span.lo {
3333 return self.report_conflict(parent, name, ns, old_binding, binding);
3336 let container = match parent.def {
3337 Some(Def::Mod(_)) => "module",
3338 Some(Def::Trait(_)) => "trait",
3343 let (participle, noun) = match old_binding.is_import() || old_binding.is_extern_crate() {
3344 true => ("imported", "import"),
3345 false => ("defined", "definition"),
3348 let span = binding.span;
3350 let kind = match (ns, old_binding.module()) {
3351 (ValueNS, _) => "a value",
3352 (TypeNS, Some(module)) if module.extern_crate_id.is_some() => "an extern crate",
3353 (TypeNS, Some(module)) if module.is_normal() => "a module",
3354 (TypeNS, Some(module)) if module.is_trait() => "a trait",
3355 (TypeNS, _) => "a type",
3357 format!("{} named `{}` has already been {} in this {}",
3358 kind, name, participle, container)
3361 let mut err = match (old_binding.is_extern_crate(), binding.is_extern_crate()) {
3362 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
3363 (true, _) | (_, true) if binding.is_import() || old_binding.is_import() => {
3364 let mut e = struct_span_err!(self.session, span, E0254, "{}", msg);
3365 e.span_label(span, &"already imported");
3368 (true, _) | (_, true) => struct_span_err!(self.session, span, E0260, "{}", msg),
3369 _ => match (old_binding.is_import(), binding.is_import()) {
3370 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
3372 let mut e = struct_span_err!(self.session, span, E0252, "{}", msg);
3373 e.span_label(span, &format!("already imported"));
3377 let mut e = struct_span_err!(self.session, span, E0255, "{}", msg);
3378 e.span_label(span, &format!("`{}` was already imported", name));
3384 if old_binding.span != syntax_pos::DUMMY_SP {
3385 err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
3391 fn names_to_string(names: &[Name]) -> String {
3392 let mut first = true;
3393 let mut result = String::new();
3398 result.push_str("::")
3400 result.push_str(&name.as_str());
3405 fn path_names_to_string(path: &Path, depth: usize) -> String {
3406 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3408 .map(|seg| seg.identifier.name)
3410 names_to_string(&names[..])
3413 /// When an entity with a given name is not available in scope, we search for
3414 /// entities with that name in all crates. This method allows outputting the
3415 /// results of this search in a programmer-friendly way
3416 fn show_candidates(session: &mut DiagnosticBuilder,
3417 candidates: &SuggestedCandidates) {
3419 let paths = &candidates.candidates;
3421 if paths.len() > 0 {
3422 // don't show more than MAX_CANDIDATES results, so
3423 // we're consistent with the trait suggestions
3424 const MAX_CANDIDATES: usize = 5;
3426 // we want consistent results across executions, but candidates are produced
3427 // by iterating through a hash map, so make sure they are ordered:
3428 let mut path_strings: Vec<_> = paths.into_iter()
3429 .map(|p| path_names_to_string(&p, 0))
3431 path_strings.sort();
3433 // behave differently based on how many candidates we have:
3434 if !paths.is_empty() {
3435 if paths.len() == 1 {
3437 &format!("you can import it into scope: `use {};`.",
3441 session.help("you can import several candidates \
3442 into scope (`use ...;`):");
3443 let count = path_strings.len() as isize - MAX_CANDIDATES as isize + 1;
3445 for (idx, path_string) in path_strings.iter().enumerate() {
3446 if idx == MAX_CANDIDATES - 1 && count > 1 {
3448 &format!(" and {} other candidates", count).to_string(),
3453 &format!(" `{}`", path_string).to_string(),
3462 &format!("no candidates by the name of `{}` found in your \
3463 project; maybe you misspelled the name or forgot to import \
3464 an external crate?", candidates.name.to_string()),
3469 /// A somewhat inefficient routine to obtain the name of a module.
3470 fn module_to_string(module: Module) -> String {
3471 let mut names = Vec::new();
3473 fn collect_mod(names: &mut Vec<ast::Name>, module: Module) {
3474 match module.parent_link {
3476 ModuleParentLink(ref module, name) => {
3478 collect_mod(names, module);
3480 BlockParentLink(ref module, _) => {
3481 // danger, shouldn't be ident?
3482 names.push(token::intern("<opaque>"));
3483 collect_mod(names, module);
3487 collect_mod(&mut names, module);
3489 if names.is_empty() {
3490 return "???".to_string();
3492 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3495 fn err_path_resolution() -> PathResolution {
3496 PathResolution::new(Def::Err)
3499 #[derive(PartialEq,Copy, Clone)]
3500 pub enum MakeGlobMap {
3505 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }