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 #![cfg_attr(stage0, feature(dotdot_in_tuple_patterns))]
23 #![feature(rustc_diagnostic_macros)]
24 #![feature(rustc_private)]
25 #![feature(staged_api)]
31 extern crate syntax_pos;
32 extern crate rustc_errors as errors;
37 use self::Namespace::*;
38 use self::ResolveResult::*;
39 use self::FallbackSuggestion::*;
40 use self::TypeParameters::*;
42 use self::UseLexicalScopeFlag::*;
43 use self::ModulePrefixResult::*;
45 use rustc::hir::map::{Definitions, DefCollector};
46 use rustc::hir::{self, PrimTy, TyBool, TyChar, TyFloat, TyInt, TyUint, TyStr};
47 use rustc::middle::cstore::CrateLoader;
48 use rustc::session::Session;
50 use rustc::hir::def::*;
51 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
53 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
54 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet};
56 use syntax::ext::hygiene::{Mark, SyntaxContext};
57 use syntax::ast::{self, FloatTy};
58 use syntax::ast::{CRATE_NODE_ID, Name, NodeId, Ident, SpannedIdent, IntTy, UintTy};
59 use syntax::ext::base::SyntaxExtension;
60 use syntax::symbol::{Symbol, keywords};
61 use syntax::util::lev_distance::find_best_match_for_name;
63 use syntax::visit::{self, FnKind, Visitor};
65 use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind};
66 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, Generics};
67 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
68 use syntax::ast::{Local, Mutability, Pat, PatKind, Path};
69 use syntax::ast::{PathSegment, PathParameters, QSelf, TraitItemKind, TraitRef, Ty, TyKind};
71 use syntax_pos::{Span, DUMMY_SP};
72 use errors::DiagnosticBuilder;
74 use std::cell::{Cell, RefCell};
76 use std::mem::replace;
79 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
80 use macros::{InvocationData, LegacyBinding, LegacyScope};
82 // NB: This module needs to be declared first so diagnostics are
83 // registered before they are used.
88 mod build_reduced_graph;
97 /// Candidates for a name resolution failure
98 struct SuggestedCandidates {
100 candidates: Vec<Path>,
103 enum ResolutionError<'a> {
104 /// error E0401: can't use type parameters from outer function
105 TypeParametersFromOuterFunction,
106 /// error E0402: cannot use an outer type parameter in this context
107 OuterTypeParameterContext,
108 /// error E0403: the name is already used for a type parameter in this type parameter list
109 NameAlreadyUsedInTypeParameterList(Name, &'a Span),
110 /// error E0404: is not a trait
111 IsNotATrait(&'a str, &'a str),
112 /// error E0405: use of undeclared trait name
113 UndeclaredTraitName(&'a str, SuggestedCandidates),
114 /// error E0407: method is not a member of trait
115 MethodNotMemberOfTrait(Name, &'a str),
116 /// error E0437: type is not a member of trait
117 TypeNotMemberOfTrait(Name, &'a str),
118 /// error E0438: const is not a member of trait
119 ConstNotMemberOfTrait(Name, &'a str),
120 /// error E0408: variable `{}` from pattern #{} is not bound in pattern #{}
121 VariableNotBoundInPattern(Name, usize, usize),
122 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
123 VariableBoundWithDifferentMode(Name, usize, Span),
124 /// error E0411: use of `Self` outside of an impl or trait
125 SelfUsedOutsideImplOrTrait,
126 /// error E0412: use of undeclared
127 UseOfUndeclared(&'a str, &'a str, SuggestedCandidates),
128 /// error E0415: identifier is bound more than once in this parameter list
129 IdentifierBoundMoreThanOnceInParameterList(&'a str),
130 /// error E0416: identifier is bound more than once in the same pattern
131 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
132 /// error E0423: is a struct variant name, but this expression uses it like a function name
133 StructVariantUsedAsFunction(&'a str),
134 /// error E0424: `self` is not available in a static method
135 SelfNotAvailableInStaticMethod,
136 /// error E0425: unresolved name
140 context: UnresolvedNameContext<'a>,
141 is_static_method: bool,
145 /// error E0426: use of undeclared label
146 UndeclaredLabel(&'a str),
147 /// error E0429: `self` imports are only allowed within a { } list
148 SelfImportsOnlyAllowedWithin,
149 /// error E0430: `self` import can only appear once in the list
150 SelfImportCanOnlyAppearOnceInTheList,
151 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
152 SelfImportOnlyInImportListWithNonEmptyPrefix,
153 /// error E0432: unresolved import
154 UnresolvedImport(Option<(&'a str, &'a str)>),
155 /// error E0433: failed to resolve
156 FailedToResolve(&'a str),
157 /// error E0434: can't capture dynamic environment in a fn item
158 CannotCaptureDynamicEnvironmentInFnItem,
159 /// error E0435: attempt to use a non-constant value in a constant
160 AttemptToUseNonConstantValueInConstant,
161 /// error E0530: X bindings cannot shadow Ys
162 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
163 /// error E0531: unresolved pattern path kind `name`
164 PatPathUnresolved(&'a str, &'a Path),
165 /// error E0532: expected pattern path kind, found another pattern path kind
166 PatPathUnexpected(&'a str, &'a str, &'a Path),
169 /// Context of where `ResolutionError::UnresolvedName` arose.
170 #[derive(Clone, PartialEq, Eq, Debug)]
171 enum UnresolvedNameContext<'a> {
172 /// `PathIsMod(parent)` indicates that a given path, used in
173 /// expression context, actually resolved to a module rather than
174 /// a value. The optional expression attached to the variant is the
175 /// the parent of the erroneous path expression.
176 PathIsMod(Option<&'a Expr>),
178 /// `Other` means we have no extra information about the context
179 /// of the unresolved name error. (Maybe we could eliminate all
180 /// such cases; but for now, this is an information-free default.)
184 fn resolve_error<'b, 'a: 'b, 'c>(resolver: &'b Resolver<'a>,
185 span: syntax_pos::Span,
186 resolution_error: ResolutionError<'c>) {
187 resolve_struct_error(resolver, span, resolution_error).emit();
190 fn resolve_struct_error<'b, 'a: 'b, 'c>(resolver: &'b Resolver<'a>,
191 span: syntax_pos::Span,
192 resolution_error: ResolutionError<'c>)
193 -> DiagnosticBuilder<'a> {
194 if !resolver.emit_errors {
195 return resolver.session.diagnostic().struct_dummy();
198 match resolution_error {
199 ResolutionError::TypeParametersFromOuterFunction => {
200 let mut err = struct_span_err!(resolver.session,
203 "can't use type parameters from outer function; \
204 try using a local type parameter instead");
205 err.span_label(span, &format!("use of type variable from outer function"));
208 ResolutionError::OuterTypeParameterContext => {
209 struct_span_err!(resolver.session,
212 "cannot use an outer type parameter in this context")
214 ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
215 let mut err = struct_span_err!(resolver.session,
218 "the name `{}` is already used for a type parameter \
219 in this type parameter list",
221 err.span_label(span, &format!("already used"));
222 err.span_label(first_use_span.clone(), &format!("first use of `{}`", name));
226 ResolutionError::IsNotATrait(name, kind_name) => {
227 let mut err = struct_span_err!(resolver.session,
230 "`{}` is not a trait",
232 err.span_label(span, &format!("expected trait, found {}", kind_name));
235 ResolutionError::UndeclaredTraitName(name, candidates) => {
236 let mut err = struct_span_err!(resolver.session,
239 "trait `{}` is not in scope",
241 show_candidates(&mut err, &candidates);
242 err.span_label(span, &format!("`{}` is not in scope", name));
245 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
246 let mut err = struct_span_err!(resolver.session,
249 "method `{}` is not a member of trait `{}`",
252 err.span_label(span, &format!("not a member of trait `{}`", trait_));
255 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
256 let mut err = struct_span_err!(resolver.session,
259 "type `{}` is not a member of trait `{}`",
262 err.span_label(span, &format!("not a member of trait `{}`", trait_));
265 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
266 let mut err = struct_span_err!(resolver.session,
269 "const `{}` is not a member of trait `{}`",
272 err.span_label(span, &format!("not a member of trait `{}`", trait_));
275 ResolutionError::VariableNotBoundInPattern(variable_name, from, to) => {
276 let mut err = struct_span_err!(resolver.session,
279 "variable `{}` from pattern #{} is not bound in pattern #{}",
283 err.span_label(span, &format!("pattern doesn't bind `{}`", variable_name));
286 ResolutionError::VariableBoundWithDifferentMode(variable_name,
288 first_binding_span) => {
289 let mut err = struct_span_err!(resolver.session,
292 "variable `{}` is bound with different mode in pattern #{} than in \
296 err.span_label(span, &format!("bound in different ways"));
297 err.span_label(first_binding_span, &format!("first binding"));
300 ResolutionError::SelfUsedOutsideImplOrTrait => {
301 let mut err = struct_span_err!(resolver.session,
304 "use of `Self` outside of an impl or trait");
305 err.span_label(span, &format!("used outside of impl or trait"));
308 ResolutionError::UseOfUndeclared(kind, name, candidates) => {
309 let mut err = struct_span_err!(resolver.session,
312 "{} `{}` is undefined or not in scope",
315 show_candidates(&mut err, &candidates);
316 err.span_label(span, &format!("undefined or not in scope"));
319 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
320 let mut err = struct_span_err!(resolver.session,
323 "identifier `{}` is bound more than once in this parameter list",
325 err.span_label(span, &format!("used as parameter more than once"));
328 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
329 let mut err = struct_span_err!(resolver.session,
332 "identifier `{}` is bound more than once in the same pattern",
334 err.span_label(span, &format!("used in a pattern more than once"));
337 ResolutionError::StructVariantUsedAsFunction(path_name) => {
338 let mut err = struct_span_err!(resolver.session,
341 "`{}` is the name of a struct or struct variant, but this expression \
342 uses it like a function name",
344 err.span_label(span, &format!("struct called like a function"));
347 ResolutionError::SelfNotAvailableInStaticMethod => {
348 let mut err = struct_span_err!(resolver.session,
351 "`self` is not available in a static method");
352 err.span_label(span, &format!("not available in static method"));
353 err.note(&format!("maybe a `self` argument is missing?"));
356 ResolutionError::UnresolvedName { path, message: msg, context, is_static_method,
358 let mut err = struct_span_err!(resolver.session,
361 "unresolved name `{}`",
364 err.span_label(span, &msg);
366 err.span_label(span, &format!("unresolved name"));
370 UnresolvedNameContext::Other => {
371 if msg.is_empty() && is_static_method && is_field {
372 err.help("this is an associated function, you don't have access to \
373 this type's fields or methods");
376 UnresolvedNameContext::PathIsMod(parent) => {
377 err.help(&match parent.map(|parent| &parent.node) {
378 Some(&ExprKind::Field(_, ident)) => {
379 format!("to reference an item from the `{module}` module, \
380 use `{module}::{ident}`",
384 Some(&ExprKind::MethodCall(ident, ..)) => {
385 format!("to call a function from the `{module}` module, \
386 use `{module}::{ident}(..)`",
391 format!("{def} `{module}` cannot be used as an expression",
392 def = def.kind_name(),
400 ResolutionError::UndeclaredLabel(name) => {
401 let mut err = struct_span_err!(resolver.session,
404 "use of undeclared label `{}`",
406 err.span_label(span, &format!("undeclared label `{}`",&name));
409 ResolutionError::SelfImportsOnlyAllowedWithin => {
410 struct_span_err!(resolver.session,
414 "`self` imports are only allowed within a { } list")
416 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
417 struct_span_err!(resolver.session,
420 "`self` import can only appear once in the list")
422 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
423 struct_span_err!(resolver.session,
426 "`self` import can only appear in an import list with a \
429 ResolutionError::UnresolvedImport(name) => {
430 let msg = match name {
431 Some((n, _)) => format!("unresolved import `{}`", n),
432 None => "unresolved import".to_owned(),
434 let mut err = struct_span_err!(resolver.session, span, E0432, "{}", msg);
435 if let Some((_, p)) = name {
436 err.span_label(span, &p);
440 ResolutionError::FailedToResolve(msg) => {
441 let mut err = struct_span_err!(resolver.session, span, E0433,
442 "failed to resolve. {}", msg);
443 err.span_label(span, &msg);
446 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
447 struct_span_err!(resolver.session,
451 "can't capture dynamic environment in a fn item; use the || { ... } \
452 closure form instead")
454 ResolutionError::AttemptToUseNonConstantValueInConstant => {
455 let mut err = struct_span_err!(resolver.session,
458 "attempt to use a non-constant value in a constant");
459 err.span_label(span, &format!("non-constant used with constant"));
462 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
463 let shadows_what = PathResolution::new(binding.def()).kind_name();
464 let mut err = struct_span_err!(resolver.session,
467 "{}s cannot shadow {}s", what_binding, shadows_what);
468 err.span_label(span, &format!("cannot be named the same as a {}", shadows_what));
469 let participle = if binding.is_import() { "imported" } else { "defined" };
470 let msg = &format!("a {} `{}` is {} here", shadows_what, name, participle);
471 err.span_label(binding.span, msg);
474 ResolutionError::PatPathUnresolved(expected_what, path) => {
475 struct_span_err!(resolver.session,
478 "unresolved {} `{}`",
482 ResolutionError::PatPathUnexpected(expected_what, found_what, path) => {
483 struct_span_err!(resolver.session,
486 "expected {}, found {} `{}`",
494 #[derive(Copy, Clone)]
497 binding_mode: BindingMode,
500 // Map from the name in a pattern to its binding mode.
501 type BindingMap = FxHashMap<Ident, BindingInfo>;
503 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
514 fn is_refutable(self) -> bool {
516 PatternSource::Match | PatternSource::IfLet | PatternSource::WhileLet => true,
517 PatternSource::Let | PatternSource::For | PatternSource::FnParam => false,
520 fn descr(self) -> &'static str {
522 PatternSource::Match => "match binding",
523 PatternSource::IfLet => "if let binding",
524 PatternSource::WhileLet => "while let binding",
525 PatternSource::Let => "let binding",
526 PatternSource::For => "for binding",
527 PatternSource::FnParam => "function parameter",
532 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
539 #[derive(Clone, Default, Debug)]
540 pub struct PerNS<T> {
546 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
548 fn index(&self, ns: Namespace) -> &T {
550 ValueNS => &self.value_ns,
551 TypeNS => &self.type_ns,
552 MacroNS => self.macro_ns.as_ref().unwrap(),
557 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
558 fn index_mut(&mut self, ns: Namespace) -> &mut T {
560 ValueNS => &mut self.value_ns,
561 TypeNS => &mut self.type_ns,
562 MacroNS => self.macro_ns.as_mut().unwrap(),
567 impl<'a> Visitor for Resolver<'a> {
568 fn visit_item(&mut self, item: &Item) {
569 self.resolve_item(item);
571 fn visit_arm(&mut self, arm: &Arm) {
572 self.resolve_arm(arm);
574 fn visit_block(&mut self, block: &Block) {
575 self.resolve_block(block);
577 fn visit_expr(&mut self, expr: &Expr) {
578 self.resolve_expr(expr, None);
580 fn visit_local(&mut self, local: &Local) {
581 self.resolve_local(local);
583 fn visit_ty(&mut self, ty: &Ty) {
584 self.resolve_type(ty);
586 fn visit_poly_trait_ref(&mut self, tref: &ast::PolyTraitRef, m: &ast::TraitBoundModifier) {
587 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0, None) {
588 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
590 // error already reported
591 self.record_def(tref.trait_ref.ref_id, err_path_resolution())
594 visit::walk_poly_trait_ref(self, tref, m);
596 fn visit_variant(&mut self,
597 variant: &ast::Variant,
599 item_id: ast::NodeId) {
600 if let Some(ref dis_expr) = variant.node.disr_expr {
601 // resolve the discriminator expr as a constant
602 self.with_constant_rib(|this| {
603 this.visit_expr(dis_expr);
607 // `visit::walk_variant` without the discriminant expression.
608 self.visit_variant_data(&variant.node.data,
614 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
615 let type_parameters = match foreign_item.node {
616 ForeignItemKind::Fn(_, ref generics) => {
617 HasTypeParameters(generics, ItemRibKind)
619 ForeignItemKind::Static(..) => NoTypeParameters,
621 self.with_type_parameter_rib(type_parameters, |this| {
622 visit::walk_foreign_item(this, foreign_item);
625 fn visit_fn(&mut self,
626 function_kind: FnKind,
627 declaration: &FnDecl,
630 let rib_kind = match function_kind {
631 FnKind::ItemFn(_, generics, ..) => {
632 self.visit_generics(generics);
635 FnKind::Method(_, sig, _, _) => {
636 self.visit_generics(&sig.generics);
637 MethodRibKind(!sig.decl.has_self())
639 FnKind::Closure(_) => ClosureRibKind(node_id),
642 // Create a value rib for the function.
643 self.ribs[ValueNS].push(Rib::new(rib_kind));
645 // Create a label rib for the function.
646 self.label_ribs.push(Rib::new(rib_kind));
648 // Add each argument to the rib.
649 let mut bindings_list = FxHashMap();
650 for argument in &declaration.inputs {
651 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
653 self.visit_ty(&argument.ty);
655 debug!("(resolving function) recorded argument");
657 visit::walk_fn_ret_ty(self, &declaration.output);
659 // Resolve the function body.
660 match function_kind {
661 FnKind::ItemFn(.., body) |
662 FnKind::Method(.., body) => {
663 self.visit_block(body);
665 FnKind::Closure(body) => {
666 self.visit_expr(body);
670 debug!("(resolving function) leaving function");
672 self.label_ribs.pop();
673 self.ribs[ValueNS].pop();
677 pub type ErrorMessage = Option<(Span, String)>;
679 #[derive(Clone, PartialEq, Eq, Debug)]
680 pub enum ResolveResult<T> {
681 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
682 Indeterminate, // Couldn't determine due to unresolved globs.
683 Success(T), // Successfully resolved the import.
686 impl<T> ResolveResult<T> {
687 fn success(self) -> Option<T> {
689 Success(t) => Some(t),
695 enum FallbackSuggestion {
702 #[derive(Copy, Clone)]
703 enum TypeParameters<'a, 'b> {
705 HasTypeParameters(// Type parameters.
708 // The kind of the rib used for type parameters.
712 // The rib kind controls the translation of local
713 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
714 #[derive(Copy, Clone, Debug)]
716 // No translation needs to be applied.
719 // We passed through a closure scope at the given node ID.
720 // Translate upvars as appropriate.
721 ClosureRibKind(NodeId /* func id */),
723 // We passed through an impl or trait and are now in one of its
724 // methods. Allow references to ty params that impl or trait
725 // binds. Disallow any other upvars (including other ty params that are
728 // The boolean value represents the fact that this method is static or not.
731 // We passed through an item scope. Disallow upvars.
734 // We're in a constant item. Can't refer to dynamic stuff.
737 // We passed through a module.
738 ModuleRibKind(Module<'a>),
740 // We passed through a `macro_rules!` statement with the given expansion
741 MacroDefinition(Mark),
744 #[derive(Copy, Clone)]
745 enum UseLexicalScopeFlag {
750 enum ModulePrefixResult<'a> {
752 PrefixFound(Module<'a>, usize),
758 bindings: FxHashMap<Ident, Def>,
763 fn new(kind: RibKind<'a>) -> Rib<'a> {
765 bindings: FxHashMap(),
771 /// A definition along with the index of the rib it was found on
773 ribs: Option<(Namespace, usize)>,
778 fn from_def(def: Def) -> Self {
786 enum LexicalScopeBinding<'a> {
787 Item(&'a NameBinding<'a>),
791 impl<'a> LexicalScopeBinding<'a> {
792 fn local_def(self) -> LocalDef {
794 LexicalScopeBinding::LocalDef(local_def) => local_def,
795 LexicalScopeBinding::Item(binding) => LocalDef::from_def(binding.def()),
799 fn item(self) -> Option<&'a NameBinding<'a>> {
801 LexicalScopeBinding::Item(binding) => Some(binding),
812 /// One node in the tree of modules.
813 pub struct ModuleS<'a> {
814 parent: Option<Module<'a>>,
817 // The node id of the closest normal module (`mod`) ancestor (including this module).
818 normal_ancestor_id: Option<NodeId>,
820 resolutions: RefCell<FxHashMap<(Name, Namespace), &'a RefCell<NameResolution<'a>>>>,
821 legacy_macro_resolutions: RefCell<Vec<(Mark, Name, Span)>>,
823 // Macro invocations that can expand into items in this module.
824 unresolved_invocations: RefCell<FxHashSet<Mark>>,
826 no_implicit_prelude: bool,
828 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
829 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
831 // Used to memoize the traits in this module for faster searches through all traits in scope.
832 traits: RefCell<Option<Box<[(Name, &'a NameBinding<'a>)]>>>,
834 // Whether this module is populated. If not populated, any attempt to
835 // access the children must be preceded with a
836 // `populate_module_if_necessary` call.
837 populated: Cell<bool>,
840 pub type Module<'a> = &'a ModuleS<'a>;
842 impl<'a> ModuleS<'a> {
843 fn new(parent: Option<Module<'a>>, kind: ModuleKind) -> Self {
847 normal_ancestor_id: None,
848 resolutions: RefCell::new(FxHashMap()),
849 legacy_macro_resolutions: RefCell::new(Vec::new()),
850 unresolved_invocations: RefCell::new(FxHashSet()),
851 no_implicit_prelude: false,
852 glob_importers: RefCell::new(Vec::new()),
853 globs: RefCell::new((Vec::new())),
854 traits: RefCell::new(None),
855 populated: Cell::new(true),
859 fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
860 for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
861 name_resolution.borrow().binding.map(|binding| f(name, ns, binding));
865 fn def(&self) -> Option<Def> {
867 ModuleKind::Def(def, _) => Some(def),
872 fn def_id(&self) -> Option<DefId> {
873 self.def().as_ref().map(Def::def_id)
876 // `self` resolves to the first module ancestor that `is_normal`.
877 fn is_normal(&self) -> bool {
879 ModuleKind::Def(Def::Mod(_), _) => true,
884 fn is_trait(&self) -> bool {
886 ModuleKind::Def(Def::Trait(_), _) => true,
891 fn is_local(&self) -> bool {
892 self.normal_ancestor_id.is_some()
896 impl<'a> fmt::Debug for ModuleS<'a> {
897 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
898 write!(f, "{:?}", self.def())
902 // Records a possibly-private value, type, or module definition.
903 #[derive(Clone, Debug)]
904 pub struct NameBinding<'a> {
905 kind: NameBindingKind<'a>,
911 pub trait ToNameBinding<'a> {
912 fn to_name_binding(self) -> NameBinding<'a>;
915 impl<'a> ToNameBinding<'a> for NameBinding<'a> {
916 fn to_name_binding(self) -> NameBinding<'a> {
921 #[derive(Clone, Debug)]
922 enum NameBindingKind<'a> {
926 binding: &'a NameBinding<'a>,
927 directive: &'a ImportDirective<'a>,
931 b1: &'a NameBinding<'a>,
932 b2: &'a NameBinding<'a>,
936 struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);
938 struct AmbiguityError<'a> {
942 b1: &'a NameBinding<'a>,
943 b2: &'a NameBinding<'a>,
946 impl<'a> NameBinding<'a> {
947 fn module(&self) -> Result<Module<'a>, bool /* true if an error has already been reported */> {
949 NameBindingKind::Module(module) => Ok(module),
950 NameBindingKind::Import { binding, .. } => binding.module(),
951 NameBindingKind::Def(Def::Err) => Err(true),
952 NameBindingKind::Def(_) => Err(false),
953 NameBindingKind::Ambiguity { .. } => Err(false),
957 fn def(&self) -> Def {
959 NameBindingKind::Def(def) => def,
960 NameBindingKind::Module(module) => module.def().unwrap(),
961 NameBindingKind::Import { binding, .. } => binding.def(),
962 NameBindingKind::Ambiguity { .. } => Def::Err,
966 // We sometimes need to treat variants as `pub` for backwards compatibility
967 fn pseudo_vis(&self) -> ty::Visibility {
968 if self.is_variant() { ty::Visibility::Public } else { self.vis }
971 fn is_variant(&self) -> bool {
973 NameBindingKind::Def(Def::Variant(..)) |
974 NameBindingKind::Def(Def::VariantCtor(..)) => true,
979 fn is_extern_crate(&self) -> bool {
981 NameBindingKind::Import {
982 directive: &ImportDirective {
983 subclass: ImportDirectiveSubclass::ExternCrate, ..
990 fn is_import(&self) -> bool {
992 NameBindingKind::Import { .. } => true,
997 fn is_glob_import(&self) -> bool {
999 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1000 NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
1005 fn is_importable(&self) -> bool {
1007 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1013 /// Interns the names of the primitive types.
1014 struct PrimitiveTypeTable {
1015 primitive_types: FxHashMap<Name, PrimTy>,
1018 impl PrimitiveTypeTable {
1019 fn new() -> PrimitiveTypeTable {
1020 let mut table = PrimitiveTypeTable { primitive_types: FxHashMap() };
1022 table.intern("bool", TyBool);
1023 table.intern("char", TyChar);
1024 table.intern("f32", TyFloat(FloatTy::F32));
1025 table.intern("f64", TyFloat(FloatTy::F64));
1026 table.intern("isize", TyInt(IntTy::Is));
1027 table.intern("i8", TyInt(IntTy::I8));
1028 table.intern("i16", TyInt(IntTy::I16));
1029 table.intern("i32", TyInt(IntTy::I32));
1030 table.intern("i64", TyInt(IntTy::I64));
1031 table.intern("str", TyStr);
1032 table.intern("usize", TyUint(UintTy::Us));
1033 table.intern("u8", TyUint(UintTy::U8));
1034 table.intern("u16", TyUint(UintTy::U16));
1035 table.intern("u32", TyUint(UintTy::U32));
1036 table.intern("u64", TyUint(UintTy::U64));
1041 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1042 self.primitive_types.insert(Symbol::intern(string), primitive_type);
1046 /// The main resolver class.
1047 pub struct Resolver<'a> {
1048 session: &'a Session,
1050 pub definitions: Definitions,
1052 // Maps the node id of a statement to the expansions of the `macro_rules!`s
1053 // immediately above the statement (if appropriate).
1054 macros_at_scope: FxHashMap<NodeId, Vec<Mark>>,
1056 graph_root: Module<'a>,
1058 prelude: Option<Module<'a>>,
1060 trait_item_map: FxHashMap<(Name, DefId), bool /* is static method? */>,
1062 // Names of fields of an item `DefId` accessible with dot syntax.
1063 // Used for hints during error reporting.
1064 field_names: FxHashMap<DefId, Vec<Name>>,
1066 // All imports known to succeed or fail.
1067 determined_imports: Vec<&'a ImportDirective<'a>>,
1069 // All non-determined imports.
1070 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1072 // The module that represents the current item scope.
1073 current_module: Module<'a>,
1075 // The current set of local scopes for types and values.
1076 // FIXME #4948: Reuse ribs to avoid allocation.
1077 ribs: PerNS<Vec<Rib<'a>>>,
1079 // The current set of local scopes, for labels.
1080 label_ribs: Vec<Rib<'a>>,
1082 // The trait that the current context can refer to.
1083 current_trait_ref: Option<(DefId, TraitRef)>,
1085 // The current self type if inside an impl (used for better errors).
1086 current_self_type: Option<Ty>,
1088 // The idents for the primitive types.
1089 primitive_type_table: PrimitiveTypeTable,
1091 pub def_map: DefMap,
1092 pub freevars: FreevarMap,
1093 freevars_seen: NodeMap<NodeMap<usize>>,
1094 pub export_map: ExportMap,
1095 pub trait_map: TraitMap,
1097 // A map from nodes to modules, both normal (`mod`) modules and anonymous modules.
1098 // Anonymous modules are pseudo-modules that are implicitly created around items
1099 // contained within blocks.
1101 // For example, if we have this:
1109 // There will be an anonymous module created around `g` with the ID of the
1110 // entry block for `f`.
1111 module_map: NodeMap<Module<'a>>,
1112 extern_crate_roots: FxHashMap<(CrateNum, bool /* MacrosOnly? */), Module<'a>>,
1114 // Whether or not to print error messages. Can be set to true
1115 // when getting additional info for error message suggestions,
1116 // so as to avoid printing duplicate errors
1119 pub make_glob_map: bool,
1120 // Maps imports to the names of items actually imported (this actually maps
1121 // all imports, but only glob imports are actually interesting).
1122 pub glob_map: GlobMap,
1124 used_imports: FxHashSet<(NodeId, Namespace)>,
1125 used_crates: FxHashSet<CrateNum>,
1126 pub maybe_unused_trait_imports: NodeSet,
1128 privacy_errors: Vec<PrivacyError<'a>>,
1129 ambiguity_errors: Vec<AmbiguityError<'a>>,
1130 disallowed_shadowing: Vec<&'a LegacyBinding<'a>>,
1132 arenas: &'a ResolverArenas<'a>,
1133 dummy_binding: &'a NameBinding<'a>,
1134 use_extern_macros: bool, // true if `#![feature(use_extern_macros)]`
1136 pub exported_macros: Vec<ast::MacroDef>,
1137 crate_loader: &'a mut CrateLoader,
1138 macro_names: FxHashSet<Name>,
1139 builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1140 lexical_macro_resolutions: Vec<(Name, &'a Cell<LegacyScope<'a>>)>,
1141 macro_map: FxHashMap<DefId, Rc<SyntaxExtension>>,
1142 macro_exports: Vec<Export>,
1144 // Maps the `Mark` of an expansion to its containing module or block.
1145 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1147 // Avoid duplicated errors for "name already defined".
1148 name_already_seen: FxHashMap<Name, Span>,
1151 pub struct ResolverArenas<'a> {
1152 modules: arena::TypedArena<ModuleS<'a>>,
1153 local_modules: RefCell<Vec<Module<'a>>>,
1154 name_bindings: arena::TypedArena<NameBinding<'a>>,
1155 import_directives: arena::TypedArena<ImportDirective<'a>>,
1156 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1157 invocation_data: arena::TypedArena<InvocationData<'a>>,
1158 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1161 impl<'a> ResolverArenas<'a> {
1162 fn alloc_module(&'a self, module: ModuleS<'a>) -> Module<'a> {
1163 let module = self.modules.alloc(module);
1164 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1165 self.local_modules.borrow_mut().push(module);
1169 fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1170 self.local_modules.borrow()
1172 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1173 self.name_bindings.alloc(name_binding)
1175 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1176 -> &'a ImportDirective {
1177 self.import_directives.alloc(import_directive)
1179 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1180 self.name_resolutions.alloc(Default::default())
1182 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1183 -> &'a InvocationData<'a> {
1184 self.invocation_data.alloc(expansion_data)
1186 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1187 self.legacy_bindings.alloc(binding)
1191 impl<'a> ty::NodeIdTree for Resolver<'a> {
1192 fn is_descendant_of(&self, mut node: NodeId, ancestor: NodeId) -> bool {
1193 while node != ancestor {
1194 node = match self.module_map[&node].parent {
1195 Some(parent) => parent.normal_ancestor_id.unwrap(),
1196 None => return false,
1203 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1204 fn resolve_generated_global_path(&mut self, path: &hir::Path, is_value: bool) -> Def {
1205 let namespace = if is_value { ValueNS } else { TypeNS };
1206 match self.resolve_crate_relative_path(path.span, &path.segments, namespace) {
1207 Ok(binding) => binding.def(),
1208 Err(true) => Def::Err,
1210 let path_name = &format!("{}", path);
1212 ResolutionError::UnresolvedName {
1215 context: UnresolvedNameContext::Other,
1216 is_static_method: false,
1220 resolve_error(self, path.span, error);
1226 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1227 self.def_map.get(&id).cloned()
1230 fn record_resolution(&mut self, id: NodeId, def: Def) {
1231 self.def_map.insert(id, PathResolution::new(def));
1234 fn definitions(&mut self) -> &mut Definitions {
1235 &mut self.definitions
1240 fn ident(&self) -> Ident;
1243 impl Named for ast::PathSegment {
1244 fn ident(&self) -> Ident {
1249 impl Named for hir::PathSegment {
1250 fn ident(&self) -> Ident {
1251 Ident::with_empty_ctxt(self.name)
1255 impl<'a> Resolver<'a> {
1256 pub fn new(session: &'a Session,
1258 make_glob_map: MakeGlobMap,
1259 crate_loader: &'a mut CrateLoader,
1260 arenas: &'a ResolverArenas<'a>)
1262 let root_def = Def::Mod(DefId::local(CRATE_DEF_INDEX));
1263 let graph_root = arenas.alloc_module(ModuleS {
1264 normal_ancestor_id: Some(CRATE_NODE_ID),
1265 no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1266 ..ModuleS::new(None, ModuleKind::Def(root_def, keywords::Invalid.name()))
1268 let mut module_map = NodeMap();
1269 module_map.insert(CRATE_NODE_ID, graph_root);
1271 let mut definitions = Definitions::new();
1272 DefCollector::new(&mut definitions).collect_root();
1274 let mut invocations = FxHashMap();
1275 invocations.insert(Mark::root(),
1276 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1281 definitions: definitions,
1282 macros_at_scope: FxHashMap(),
1284 // The outermost module has def ID 0; this is not reflected in the
1286 graph_root: graph_root,
1289 trait_item_map: FxHashMap(),
1290 field_names: FxHashMap(),
1292 determined_imports: Vec::new(),
1293 indeterminate_imports: Vec::new(),
1295 current_module: graph_root,
1297 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1298 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1301 label_ribs: Vec::new(),
1303 current_trait_ref: None,
1304 current_self_type: None,
1306 primitive_type_table: PrimitiveTypeTable::new(),
1309 freevars: NodeMap(),
1310 freevars_seen: NodeMap(),
1311 export_map: NodeMap(),
1312 trait_map: NodeMap(),
1313 module_map: module_map,
1314 extern_crate_roots: FxHashMap(),
1317 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1318 glob_map: NodeMap(),
1320 used_imports: FxHashSet(),
1321 used_crates: FxHashSet(),
1322 maybe_unused_trait_imports: NodeSet(),
1324 privacy_errors: Vec::new(),
1325 ambiguity_errors: Vec::new(),
1326 disallowed_shadowing: Vec::new(),
1329 dummy_binding: arenas.alloc_name_binding(NameBinding {
1330 kind: NameBindingKind::Def(Def::Err),
1331 expansion: Mark::root(),
1333 vis: ty::Visibility::Public,
1335 use_extern_macros: session.features.borrow().use_extern_macros,
1337 exported_macros: Vec::new(),
1338 crate_loader: crate_loader,
1339 macro_names: FxHashSet(),
1340 builtin_macros: FxHashMap(),
1341 lexical_macro_resolutions: Vec::new(),
1342 macro_map: FxHashMap(),
1343 macro_exports: Vec::new(),
1344 invocations: invocations,
1345 name_already_seen: FxHashMap(),
1349 pub fn arenas() -> ResolverArenas<'a> {
1351 modules: arena::TypedArena::new(),
1352 local_modules: RefCell::new(Vec::new()),
1353 name_bindings: arena::TypedArena::new(),
1354 import_directives: arena::TypedArena::new(),
1355 name_resolutions: arena::TypedArena::new(),
1356 invocation_data: arena::TypedArena::new(),
1357 legacy_bindings: arena::TypedArena::new(),
1361 fn per_ns<T, F: FnMut(&mut Self, Namespace) -> T>(&mut self, mut f: F) -> PerNS<T> {
1363 type_ns: f(self, TypeNS),
1364 value_ns: f(self, ValueNS),
1365 macro_ns: match self.use_extern_macros {
1366 true => Some(f(self, MacroNS)),
1372 /// Entry point to crate resolution.
1373 pub fn resolve_crate(&mut self, krate: &Crate) {
1374 ImportResolver { resolver: self }.finalize_imports();
1375 self.current_module = self.graph_root;
1376 visit::walk_crate(self, krate);
1378 check_unused::check_crate(self, krate);
1379 self.report_errors();
1380 self.crate_loader.postprocess(krate);
1383 fn new_module(&self, parent: Module<'a>, kind: ModuleKind, local: bool) -> Module<'a> {
1384 self.arenas.alloc_module(ModuleS {
1385 normal_ancestor_id: if local { self.current_module.normal_ancestor_id } else { None },
1386 populated: Cell::new(local),
1387 ..ModuleS::new(Some(parent), kind)
1391 fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
1392 -> bool /* true if an error was reported */ {
1393 // track extern crates for unused_extern_crate lint
1394 if let Some(DefId { krate, .. }) = binding.module().ok().and_then(ModuleS::def_id) {
1395 self.used_crates.insert(krate);
1398 match binding.kind {
1399 NameBindingKind::Import { directive, binding, ref used } if !used.get() => {
1401 self.used_imports.insert((directive.id, ns));
1402 self.add_to_glob_map(directive.id, name);
1403 self.record_use(name, ns, binding, span)
1405 NameBindingKind::Import { .. } => false,
1406 NameBindingKind::Ambiguity { b1, b2 } => {
1407 self.ambiguity_errors.push(AmbiguityError {
1408 span: span, name: name, lexical: false, b1: b1, b2: b2,
1416 fn add_to_glob_map(&mut self, id: NodeId, name: Name) {
1417 if self.make_glob_map {
1418 self.glob_map.entry(id).or_insert_with(FxHashSet).insert(name);
1422 fn expect_module(&mut self, name: Name, binding: &'a NameBinding<'a>, span: Option<Span>)
1423 -> ResolveResult<Module<'a>> {
1424 match binding.module() {
1425 Ok(module) => Success(module),
1426 Err(true) => Failed(None),
1428 let msg = format!("Not a module `{}`", name);
1429 Failed(span.map(|span| (span, msg)))
1434 /// Resolves the given module path from the given root `search_module`.
1435 fn resolve_module_path_from_root(&mut self,
1436 mut search_module: Module<'a>,
1437 module_path: &[Ident],
1440 -> ResolveResult<Module<'a>> {
1441 fn search_parent_externals<'a>(this: &mut Resolver<'a>, needle: Name, module: Module<'a>)
1442 -> Option<Module<'a>> {
1443 match this.resolve_name_in_module(module, needle, TypeNS, false, None) {
1444 Success(binding) if binding.is_extern_crate() => Some(module),
1445 _ => if let (&ModuleKind::Def(..), Some(parent)) = (&module.kind, module.parent) {
1446 search_parent_externals(this, needle, parent)
1453 let mut index = index;
1454 let module_path_len = module_path.len();
1456 // Resolve the module part of the path. This does not involve looking
1457 // upward though scope chains; we simply resolve names directly in
1458 // modules as we go.
1459 while index < module_path_len {
1460 let name = module_path[index].name;
1461 match self.resolve_name_in_module(search_module, name, TypeNS, false, span) {
1463 let module_name = module_to_string(search_module);
1464 let msg = if "???" == &module_name {
1465 let current_module = self.current_module;
1466 match search_parent_externals(self, name, current_module) {
1468 let path_str = names_to_string(module_path);
1469 let target_mod_str = module_to_string(&module);
1470 let current_mod_str = module_to_string(current_module);
1472 let prefix = if target_mod_str == current_mod_str {
1473 "self::".to_string()
1475 format!("{}::", target_mod_str)
1478 format!("Did you mean `{}{}`?", prefix, path_str)
1480 None => format!("Maybe a missing `extern crate {};`?", name),
1483 format!("Could not find `{}` in `{}`", name, module_name)
1486 return Failed(span.map(|span| (span, msg)));
1489 debug!("(resolving module path for import) module resolution is \
1492 return Indeterminate;
1494 Success(binding) => {
1495 // Check to see whether there are type bindings, and, if
1496 // so, whether there is a module within.
1497 match self.expect_module(name, binding, span) {
1498 Success(module) => search_module = module,
1499 result @ _ => return result,
1507 return Success(search_module);
1510 /// Attempts to resolve the module part of an import directive or path
1511 /// rooted at the given module.
1512 fn resolve_module_path(&mut self,
1513 module_path: &[Ident],
1514 use_lexical_scope: UseLexicalScopeFlag,
1516 -> ResolveResult<Module<'a>> {
1517 if module_path.len() == 0 {
1518 return Success(self.graph_root) // Use the crate root
1521 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1522 names_to_string(module_path),
1523 module_to_string(self.current_module));
1525 // Resolve the module prefix, if any.
1526 let module_prefix_result = self.resolve_module_prefix(module_path, span);
1530 match module_prefix_result {
1531 Failed(err) => return Failed(err),
1533 debug!("(resolving module path for import) indeterminate; bailing");
1534 return Indeterminate;
1536 Success(NoPrefixFound) => {
1537 // There was no prefix, so we're considering the first element
1538 // of the path. How we handle this depends on whether we were
1539 // instructed to use lexical scope or not.
1540 match use_lexical_scope {
1541 DontUseLexicalScope => {
1542 // This is a crate-relative path. We will start the
1543 // resolution process at index zero.
1544 search_module = self.graph_root;
1547 UseLexicalScope => {
1548 // This is not a crate-relative path. We resolve the
1549 // first component of the path in the current lexical
1550 // scope and then proceed to resolve below that.
1551 let ident = module_path[0];
1552 let lexical_binding =
1553 self.resolve_ident_in_lexical_scope(ident, TypeNS, span);
1554 if let Some(binding) = lexical_binding.and_then(LexicalScopeBinding::item) {
1555 match self.expect_module(ident.name, binding, span) {
1556 Success(containing_module) => {
1557 search_module = containing_module;
1560 result @ _ => return result,
1564 format!("Use of undeclared type or module `{}`", ident.name);
1565 return Failed(span.map(|span| (span, msg)));
1570 Success(PrefixFound(ref containing_module, index)) => {
1571 search_module = containing_module;
1572 start_index = index;
1576 self.resolve_module_path_from_root(search_module, module_path, start_index, span)
1579 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
1580 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
1581 /// `ident` in the first scope that defines it (or None if no scopes define it).
1583 /// A block's items are above its local variables in the scope hierarchy, regardless of where
1584 /// the items are defined in the block. For example,
1587 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
1590 /// g(); // This resolves to the local variable `g` since it shadows the item.
1594 /// Invariant: This must only be called during main resolution, not during
1595 /// import resolution.
1596 fn resolve_ident_in_lexical_scope(&mut self,
1599 record_used: Option<Span>)
1600 -> Option<LexicalScopeBinding<'a>> {
1602 ident = Ident::with_empty_ctxt(ident.name);
1605 // Walk backwards up the ribs in scope.
1606 for i in (0 .. self.ribs[ns].len()).rev() {
1607 if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
1608 // The ident resolves to a type parameter or local variable.
1609 return Some(LexicalScopeBinding::LocalDef(LocalDef {
1610 ribs: Some((ns, i)),
1615 if let ModuleRibKind(module) = self.ribs[ns][i].kind {
1616 let name = ident.name;
1617 let item = self.resolve_name_in_module(module, name, ns, false, record_used);
1618 if let Success(binding) = item {
1619 // The ident resolves to an item.
1620 return Some(LexicalScopeBinding::Item(binding));
1623 if let ModuleKind::Block(..) = module.kind { // We can see through blocks
1624 } else if !module.no_implicit_prelude {
1625 return self.prelude.and_then(|prelude| {
1626 self.resolve_name_in_module(prelude, name, ns, false, None).success()
1627 }).map(LexicalScopeBinding::Item)
1633 if let MacroDefinition(mac) = self.ribs[ns][i].kind {
1634 // If an invocation of this macro created `ident`, give up on `ident`
1635 // and switch to `ident`'s source from the macro definition.
1636 let (source_ctxt, source_macro) = ident.ctxt.source();
1637 if source_macro == mac {
1638 ident.ctxt = source_ctxt;
1646 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1647 /// (b) some chain of `super::`.
1648 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1649 fn resolve_module_prefix(&mut self, module_path: &[Ident], span: Option<Span>)
1650 -> ResolveResult<ModulePrefixResult<'a>> {
1651 if module_path[0].name == "$crate" {
1652 return Success(PrefixFound(self.resolve_crate_var(module_path[0].ctxt), 1));
1655 // Start at the current module if we see `self` or `super`, or at the
1656 // top of the crate otherwise.
1657 let mut i = match &*module_path[0].name.as_str() {
1660 _ => return Success(NoPrefixFound),
1663 let mut containing_module =
1664 self.module_map[&self.current_module.normal_ancestor_id.unwrap()];
1666 // Now loop through all the `super`s we find.
1667 while i < module_path.len() && module_path[i].name == "super" {
1668 debug!("(resolving module prefix) resolving `super` at {}",
1669 module_to_string(&containing_module));
1670 if let Some(parent) = containing_module.parent {
1671 containing_module = self.module_map[&parent.normal_ancestor_id.unwrap()];
1674 let msg = "There are too many initial `super`s.".into();
1675 return Failed(span.map(|span| (span, msg)));
1679 debug!("(resolving module prefix) finished resolving prefix at {}",
1680 module_to_string(&containing_module));
1682 return Success(PrefixFound(containing_module, i));
1685 fn resolve_crate_var(&mut self, mut crate_var_ctxt: SyntaxContext) -> Module<'a> {
1686 while crate_var_ctxt.source().0 != SyntaxContext::empty() {
1687 crate_var_ctxt = crate_var_ctxt.source().0;
1689 let module = self.invocations[&crate_var_ctxt.source().1].module.get();
1690 if module.is_local() { self.graph_root } else { module }
1695 // We maintain a list of value ribs and type ribs.
1697 // Simultaneously, we keep track of the current position in the module
1698 // graph in the `current_module` pointer. When we go to resolve a name in
1699 // the value or type namespaces, we first look through all the ribs and
1700 // then query the module graph. When we resolve a name in the module
1701 // namespace, we can skip all the ribs (since nested modules are not
1702 // allowed within blocks in Rust) and jump straight to the current module
1705 // Named implementations are handled separately. When we find a method
1706 // call, we consult the module node to find all of the implementations in
1707 // scope. This information is lazily cached in the module node. We then
1708 // generate a fake "implementation scope" containing all the
1709 // implementations thus found, for compatibility with old resolve pass.
1711 fn with_scope<F>(&mut self, id: NodeId, f: F)
1712 where F: FnOnce(&mut Resolver)
1714 let module = self.module_map.get(&id).cloned(); // clones a reference
1715 if let Some(module) = module {
1716 // Move down in the graph.
1717 let orig_module = replace(&mut self.current_module, module);
1718 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
1719 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
1721 self.finalize_current_module_macro_resolutions();
1724 self.current_module = orig_module;
1725 self.ribs[ValueNS].pop();
1726 self.ribs[TypeNS].pop();
1732 /// Searches the current set of local scopes for labels.
1733 /// Stops after meeting a closure.
1734 fn search_label(&self, mut ident: Ident) -> Option<Def> {
1735 for rib in self.label_ribs.iter().rev() {
1740 MacroDefinition(mac) => {
1741 // If an invocation of this macro created `ident`, give up on `ident`
1742 // and switch to `ident`'s source from the macro definition.
1743 let (source_ctxt, source_macro) = ident.ctxt.source();
1744 if source_macro == mac {
1745 ident.ctxt = source_ctxt;
1749 // Do not resolve labels across function boundary
1753 let result = rib.bindings.get(&ident).cloned();
1754 if result.is_some() {
1761 fn resolve_item(&mut self, item: &Item) {
1762 let name = item.ident.name;
1764 debug!("(resolving item) resolving {}", name);
1767 ItemKind::Enum(_, ref generics) |
1768 ItemKind::Ty(_, ref generics) |
1769 ItemKind::Struct(_, ref generics) |
1770 ItemKind::Union(_, ref generics) |
1771 ItemKind::Fn(.., ref generics, _) => {
1772 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
1773 |this| visit::walk_item(this, item));
1776 ItemKind::DefaultImpl(_, ref trait_ref) => {
1777 self.with_optional_trait_ref(Some(trait_ref), |_, _| {}, None);
1779 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
1780 self.resolve_implementation(generics,
1786 ItemKind::Trait(_, ref generics, ref bounds, ref trait_items) => {
1787 // Create a new rib for the trait-wide type parameters.
1788 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
1789 let local_def_id = this.definitions.local_def_id(item.id);
1790 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1791 this.visit_generics(generics);
1792 walk_list!(this, visit_ty_param_bound, bounds);
1794 for trait_item in trait_items {
1795 match trait_item.node {
1796 TraitItemKind::Const(_, ref default) => {
1797 // Only impose the restrictions of
1798 // ConstRibKind if there's an actual constant
1799 // expression in a provided default.
1800 if default.is_some() {
1801 this.with_constant_rib(|this| {
1802 visit::walk_trait_item(this, trait_item)
1805 visit::walk_trait_item(this, trait_item)
1808 TraitItemKind::Method(ref sig, _) => {
1809 let type_parameters =
1810 HasTypeParameters(&sig.generics,
1811 MethodRibKind(!sig.decl.has_self()));
1812 this.with_type_parameter_rib(type_parameters, |this| {
1813 visit::walk_trait_item(this, trait_item)
1816 TraitItemKind::Type(..) => {
1817 this.with_type_parameter_rib(NoTypeParameters, |this| {
1818 visit::walk_trait_item(this, trait_item)
1821 TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1828 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1829 self.with_scope(item.id, |this| {
1830 visit::walk_item(this, item);
1834 ItemKind::Const(..) | ItemKind::Static(..) => {
1835 self.with_constant_rib(|this| {
1836 visit::walk_item(this, item);
1840 ItemKind::Use(ref view_path) => {
1841 match view_path.node {
1842 ast::ViewPathList(ref prefix, ref items) => {
1843 // Resolve prefix of an import with empty braces (issue #28388)
1844 if items.is_empty() && !prefix.segments.is_empty() {
1845 match self.resolve_crate_relative_path(prefix.span,
1849 let def = binding.def();
1850 self.record_def(item.id, PathResolution::new(def));
1852 Err(true) => self.record_def(item.id, err_path_resolution()),
1856 ResolutionError::FailedToResolve(
1857 &path_names_to_string(prefix, 0)));
1858 self.record_def(item.id, err_path_resolution());
1867 ItemKind::ExternCrate(_) => {
1868 // do nothing, these are just around to be encoded
1871 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
1875 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
1876 where F: FnOnce(&mut Resolver)
1878 match type_parameters {
1879 HasTypeParameters(generics, rib_kind) => {
1880 let mut function_type_rib = Rib::new(rib_kind);
1881 let mut seen_bindings = FxHashMap();
1882 for type_parameter in &generics.ty_params {
1883 let name = type_parameter.ident.name;
1884 debug!("with_type_parameter_rib: {}", type_parameter.id);
1886 if seen_bindings.contains_key(&name) {
1887 let span = seen_bindings.get(&name).unwrap();
1889 type_parameter.span,
1890 ResolutionError::NameAlreadyUsedInTypeParameterList(name,
1893 seen_bindings.entry(name).or_insert(type_parameter.span);
1895 // plain insert (no renaming)
1896 let def_id = self.definitions.local_def_id(type_parameter.id);
1897 let def = Def::TyParam(def_id);
1898 function_type_rib.bindings.insert(Ident::with_empty_ctxt(name), def);
1899 self.record_def(type_parameter.id, PathResolution::new(def));
1901 self.ribs[TypeNS].push(function_type_rib);
1904 NoTypeParameters => {
1911 if let HasTypeParameters(..) = type_parameters {
1912 self.ribs[TypeNS].pop();
1916 fn with_label_rib<F>(&mut self, f: F)
1917 where F: FnOnce(&mut Resolver)
1919 self.label_ribs.push(Rib::new(NormalRibKind));
1921 self.label_ribs.pop();
1924 fn with_constant_rib<F>(&mut self, f: F)
1925 where F: FnOnce(&mut Resolver)
1927 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
1928 self.ribs[TypeNS].push(Rib::new(ConstantItemRibKind));
1930 self.ribs[TypeNS].pop();
1931 self.ribs[ValueNS].pop();
1934 fn resolve_trait_reference(&mut self,
1938 generics: Option<&Generics>)
1939 -> Result<PathResolution, ()> {
1940 self.resolve_path(id, trait_path, path_depth, TypeNS).and_then(|path_res| {
1941 match path_res.base_def {
1943 debug!("(resolving trait) found trait def: {:?}", path_res);
1944 return Ok(path_res);
1946 Def::Err => return Err(true),
1950 let mut err = resolve_struct_error(self, trait_path.span, {
1951 ResolutionError::IsNotATrait(&path_names_to_string(trait_path, path_depth),
1952 path_res.base_def.kind_name())
1954 if let Some(generics) = generics {
1955 if let Some(span) = generics.span_for_name(
1956 &path_names_to_string(trait_path, path_depth)) {
1958 err.span_label(span, &"type parameter defined here");
1962 // If it's a typedef, give a note
1963 if let Def::TyAlias(..) = path_res.base_def {
1964 err.note(&format!("type aliases cannot be used for traits"));
1968 }).map_err(|error_reported| {
1969 if error_reported { return }
1971 // find possible candidates
1972 let trait_name = trait_path.segments.last().unwrap().identifier.name;
1974 self.lookup_candidates(
1978 Def::Trait(_) => true,
1983 // create error object
1984 let name = &path_names_to_string(trait_path, path_depth);
1986 ResolutionError::UndeclaredTraitName(
1991 resolve_error(self, trait_path.span, error);
1995 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
1996 where F: FnOnce(&mut Resolver) -> T
1998 // Handle nested impls (inside fn bodies)
1999 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2000 let result = f(self);
2001 self.current_self_type = previous_value;
2005 fn with_optional_trait_ref<T, F>(&mut self,
2006 opt_trait_ref: Option<&TraitRef>,
2008 generics: Option<&Generics>)
2010 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2012 let mut new_val = None;
2013 let mut new_id = None;
2014 if let Some(trait_ref) = opt_trait_ref {
2015 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2019 assert!(path_res.depth == 0);
2020 self.record_def(trait_ref.ref_id, path_res);
2021 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2022 new_id = Some(path_res.base_def.def_id());
2024 self.record_def(trait_ref.ref_id, err_path_resolution());
2026 visit::walk_trait_ref(self, trait_ref);
2028 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2029 let result = f(self, new_id);
2030 self.current_trait_ref = original_trait_ref;
2034 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2035 where F: FnOnce(&mut Resolver)
2037 let mut self_type_rib = Rib::new(NormalRibKind);
2039 // plain insert (no renaming, types are not currently hygienic....)
2040 self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
2041 self.ribs[TypeNS].push(self_type_rib);
2043 self.ribs[TypeNS].pop();
2046 fn resolve_implementation(&mut self,
2047 generics: &Generics,
2048 opt_trait_reference: &Option<TraitRef>,
2051 impl_items: &[ImplItem]) {
2052 // If applicable, create a rib for the type parameters.
2053 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2054 // Resolve the type parameters.
2055 this.visit_generics(generics);
2057 // Resolve the trait reference, if necessary.
2058 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2059 // Resolve the self type.
2060 this.visit_ty(self_type);
2062 let item_def_id = this.definitions.local_def_id(item_id);
2063 this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2064 this.with_current_self_type(self_type, |this| {
2065 for impl_item in impl_items {
2066 this.resolve_visibility(&impl_item.vis);
2067 match impl_item.node {
2068 ImplItemKind::Const(..) => {
2069 // If this is a trait impl, ensure the const
2071 this.check_trait_item(impl_item.ident.name,
2073 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2074 visit::walk_impl_item(this, impl_item);
2076 ImplItemKind::Method(ref sig, _) => {
2077 // If this is a trait impl, ensure the method
2079 this.check_trait_item(impl_item.ident.name,
2081 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2083 // We also need a new scope for the method-
2084 // specific type parameters.
2085 let type_parameters =
2086 HasTypeParameters(&sig.generics,
2087 MethodRibKind(!sig.decl.has_self()));
2088 this.with_type_parameter_rib(type_parameters, |this| {
2089 visit::walk_impl_item(this, impl_item);
2092 ImplItemKind::Type(ref ty) => {
2093 // If this is a trait impl, ensure the type
2095 this.check_trait_item(impl_item.ident.name,
2097 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2101 ImplItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
2106 }, Some(&generics));
2110 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2111 where F: FnOnce(Name, &str) -> ResolutionError
2113 // If there is a TraitRef in scope for an impl, then the method must be in the
2115 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2116 if !self.trait_item_map.contains_key(&(name, did)) {
2117 let path_str = path_names_to_string(&trait_ref.path, 0);
2118 resolve_error(self, span, err(name, &path_str));
2123 fn resolve_local(&mut self, local: &Local) {
2124 // Resolve the type.
2125 walk_list!(self, visit_ty, &local.ty);
2127 // Resolve the initializer.
2128 walk_list!(self, visit_expr, &local.init);
2130 // Resolve the pattern.
2131 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap());
2134 // build a map from pattern identifiers to binding-info's.
2135 // this is done hygienically. This could arise for a macro
2136 // that expands into an or-pattern where one 'x' was from the
2137 // user and one 'x' came from the macro.
2138 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2139 let mut binding_map = FxHashMap();
2141 pat.walk(&mut |pat| {
2142 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2143 if sub_pat.is_some() || match self.def_map.get(&pat.id) {
2144 Some(&PathResolution { base_def: Def::Local(..), .. }) => true,
2147 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2148 binding_map.insert(ident.node, binding_info);
2157 // check that all of the arms in an or-pattern have exactly the
2158 // same set of bindings, with the same binding modes for each.
2159 fn check_consistent_bindings(&mut self, arm: &Arm) {
2160 if arm.pats.is_empty() {
2163 let map_0 = self.binding_mode_map(&arm.pats[0]);
2164 for (i, p) in arm.pats.iter().enumerate() {
2165 let map_i = self.binding_mode_map(&p);
2167 for (&key, &binding_0) in &map_0 {
2168 match map_i.get(&key) {
2170 let error = ResolutionError::VariableNotBoundInPattern(key.name, 1, i + 1);
2171 resolve_error(self, p.span, error);
2173 Some(binding_i) => {
2174 if binding_0.binding_mode != binding_i.binding_mode {
2177 ResolutionError::VariableBoundWithDifferentMode(
2186 for (&key, &binding) in &map_i {
2187 if !map_0.contains_key(&key) {
2190 ResolutionError::VariableNotBoundInPattern(key.name, i + 1, 1));
2196 fn resolve_arm(&mut self, arm: &Arm) {
2197 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2199 let mut bindings_list = FxHashMap();
2200 for pattern in &arm.pats {
2201 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2204 // This has to happen *after* we determine which
2205 // pat_idents are variants
2206 self.check_consistent_bindings(arm);
2208 walk_list!(self, visit_expr, &arm.guard);
2209 self.visit_expr(&arm.body);
2211 self.ribs[ValueNS].pop();
2214 fn resolve_block(&mut self, block: &Block) {
2215 debug!("(resolving block) entering block");
2216 // Move down in the graph, if there's an anonymous module rooted here.
2217 let orig_module = self.current_module;
2218 let anonymous_module = self.module_map.get(&block.id).cloned(); // clones a reference
2220 let mut num_macro_definition_ribs = 0;
2221 if let Some(anonymous_module) = anonymous_module {
2222 debug!("(resolving block) found anonymous module, moving down");
2223 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2224 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2225 self.current_module = anonymous_module;
2226 self.finalize_current_module_macro_resolutions();
2228 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2231 // Descend into the block.
2232 for stmt in &block.stmts {
2233 if let Some(marks) = self.macros_at_scope.remove(&stmt.id) {
2234 num_macro_definition_ribs += marks.len() as u32;
2236 self.ribs[ValueNS].push(Rib::new(MacroDefinition(mark)));
2237 self.label_ribs.push(Rib::new(MacroDefinition(mark)));
2241 self.visit_stmt(stmt);
2245 self.current_module = orig_module;
2246 for _ in 0 .. num_macro_definition_ribs {
2247 self.ribs[ValueNS].pop();
2248 self.label_ribs.pop();
2250 self.ribs[ValueNS].pop();
2251 if let Some(_) = anonymous_module {
2252 self.ribs[TypeNS].pop();
2254 debug!("(resolving block) leaving block");
2257 fn resolve_type(&mut self, ty: &Ty) {
2259 TyKind::Path(ref maybe_qself, ref path) => {
2260 // This is a path in the type namespace. Walk through scopes
2262 if let Some(def) = self.resolve_possibly_assoc_item(ty.id, maybe_qself.as_ref(),
2264 match def.base_def {
2265 Def::Mod(..) if def.depth == 0 => {
2266 self.session.span_err(path.span, "expected type, found module");
2267 self.record_def(ty.id, err_path_resolution());
2270 // Write the result into the def map.
2271 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2272 path_names_to_string(path, 0), ty.id, def);
2273 self.record_def(ty.id, def);
2277 self.record_def(ty.id, err_path_resolution());
2279 // Keep reporting some errors even if they're ignored above.
2280 if let Err(true) = self.resolve_path(ty.id, path, 0, TypeNS) {
2281 // `resolve_path` already reported the error
2283 let kind = if maybe_qself.is_some() {
2289 let is_invalid_self_type_name = path.segments.len() > 0 &&
2290 maybe_qself.is_none() &&
2291 path.segments[0].identifier.name ==
2292 keywords::SelfType.name();
2293 if is_invalid_self_type_name {
2296 ResolutionError::SelfUsedOutsideImplOrTrait);
2298 let segment = path.segments.last();
2299 let segment = segment.expect("missing name in path");
2300 let type_name = segment.identifier.name;
2303 self.lookup_candidates(
2311 Def::TyAlias(_) => true,
2316 // create error object
2317 let name = &path_names_to_string(path, 0);
2319 ResolutionError::UseOfUndeclared(
2325 resolve_error(self, ty.span, error);
2332 // Resolve embedded types.
2333 visit::walk_ty(self, ty);
2336 fn fresh_binding(&mut self,
2337 ident: &SpannedIdent,
2339 outer_pat_id: NodeId,
2340 pat_src: PatternSource,
2341 bindings: &mut FxHashMap<Ident, NodeId>)
2343 // Add the binding to the local ribs, if it
2344 // doesn't already exist in the bindings map. (We
2345 // must not add it if it's in the bindings map
2346 // because that breaks the assumptions later
2347 // passes make about or-patterns.)
2348 let mut def = Def::Local(self.definitions.local_def_id(pat_id));
2349 match bindings.get(&ident.node).cloned() {
2350 Some(id) if id == outer_pat_id => {
2351 // `Variant(a, a)`, error
2355 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2356 &ident.node.name.as_str())
2359 Some(..) if pat_src == PatternSource::FnParam => {
2360 // `fn f(a: u8, a: u8)`, error
2364 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2365 &ident.node.name.as_str())
2368 Some(..) if pat_src == PatternSource::Match => {
2369 // `Variant1(a) | Variant2(a)`, ok
2370 // Reuse definition from the first `a`.
2371 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident.node];
2374 span_bug!(ident.span, "two bindings with the same name from \
2375 unexpected pattern source {:?}", pat_src);
2378 // A completely fresh binding, add to the lists if it's valid.
2379 if ident.node.name != keywords::Invalid.name() {
2380 bindings.insert(ident.node, outer_pat_id);
2381 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident.node, def);
2386 PathResolution::new(def)
2389 fn resolve_pattern_path<ExpectedFn>(&mut self,
2391 qself: Option<&QSelf>,
2393 namespace: Namespace,
2394 expected_fn: ExpectedFn,
2395 expected_what: &str)
2396 where ExpectedFn: FnOnce(Def) -> bool
2398 let resolution = if let Some(resolution) = self.resolve_possibly_assoc_item(pat_id,
2399 qself, path, namespace) {
2400 if resolution.depth == 0 {
2401 if expected_fn(resolution.base_def) || resolution.base_def == Def::Err {
2407 ResolutionError::PatPathUnexpected(expected_what,
2408 resolution.kind_name(), path)
2410 err_path_resolution()
2413 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
2414 // or `<T>::A::B`. If `B` should be resolved in value namespace then
2415 // it needs to be added to the trait map.
2416 if namespace == ValueNS {
2417 let item_name = path.segments.last().unwrap().identifier.name;
2418 let traits = self.get_traits_containing_item(item_name);
2419 self.trait_map.insert(pat_id, traits);
2424 if let Err(false) = self.resolve_path(pat_id, path, 0, namespace) {
2428 ResolutionError::PatPathUnresolved(expected_what, path)
2431 err_path_resolution()
2434 self.record_def(pat_id, resolution);
2437 fn resolve_struct_path(&mut self, node_id: NodeId, path: &Path) {
2438 // Resolution logic is equivalent for expressions and patterns,
2439 // reuse `resolve_pattern_path` for both.
2440 self.resolve_pattern_path(node_id, None, path, TypeNS, |def| {
2442 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
2443 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
2446 }, "struct, variant or union type");
2449 fn resolve_pattern(&mut self,
2451 pat_src: PatternSource,
2452 // Maps idents to the node ID for the
2453 // outermost pattern that binds them.
2454 bindings: &mut FxHashMap<Ident, NodeId>) {
2455 // Visit all direct subpatterns of this pattern.
2456 let outer_pat_id = pat.id;
2457 pat.walk(&mut |pat| {
2459 PatKind::Ident(bmode, ref ident, ref opt_pat) => {
2460 // First try to resolve the identifier as some existing
2461 // entity, then fall back to a fresh binding.
2462 let binding = self.resolve_ident_in_lexical_scope(ident.node, ValueNS, None)
2463 .and_then(LexicalScopeBinding::item);
2464 let resolution = binding.map(NameBinding::def).and_then(|def| {
2465 let always_binding = !pat_src.is_refutable() || opt_pat.is_some() ||
2466 bmode != BindingMode::ByValue(Mutability::Immutable);
2468 Def::StructCtor(_, CtorKind::Const) |
2469 Def::VariantCtor(_, CtorKind::Const) |
2470 Def::Const(..) if !always_binding => {
2471 // A unit struct/variant or constant pattern.
2472 let name = ident.node.name;
2473 self.record_use(name, ValueNS, binding.unwrap(), ident.span);
2474 Some(PathResolution::new(def))
2476 Def::StructCtor(..) | Def::VariantCtor(..) |
2477 Def::Const(..) | Def::Static(..) => {
2478 // A fresh binding that shadows something unacceptable.
2482 ResolutionError::BindingShadowsSomethingUnacceptable(
2483 pat_src.descr(), ident.node.name, binding.unwrap())
2487 Def::Local(..) | Def::Upvar(..) | Def::Fn(..) | Def::Err => {
2488 // These entities are explicitly allowed
2489 // to be shadowed by fresh bindings.
2493 span_bug!(ident.span, "unexpected definition for an \
2494 identifier in pattern: {:?}", def);
2497 }).unwrap_or_else(|| {
2498 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2501 self.record_def(pat.id, resolution);
2504 PatKind::TupleStruct(ref path, ..) => {
2505 self.resolve_pattern_path(pat.id, None, path, ValueNS, |def| {
2507 Def::StructCtor(_, CtorKind::Fn) |
2508 Def::VariantCtor(_, CtorKind::Fn) => true,
2511 }, "tuple struct/variant");
2514 PatKind::Path(ref qself, ref path) => {
2515 self.resolve_pattern_path(pat.id, qself.as_ref(), path, ValueNS, |def| {
2517 Def::StructCtor(_, CtorKind::Const) |
2518 Def::VariantCtor(_, CtorKind::Const) |
2519 Def::Const(..) | Def::AssociatedConst(..) => true,
2522 }, "unit struct/variant or constant");
2525 PatKind::Struct(ref path, ..) => {
2526 self.resolve_struct_path(pat.id, path);
2534 visit::walk_pat(self, pat);
2537 /// Handles paths that may refer to associated items
2538 fn resolve_possibly_assoc_item(&mut self,
2540 maybe_qself: Option<&QSelf>,
2542 namespace: Namespace)
2543 -> Option<PathResolution> {
2544 let max_assoc_types;
2548 if qself.position == 0 {
2549 // FIXME: Create some fake resolution that can't possibly be a type.
2550 return Some(PathResolution {
2551 base_def: Def::Mod(self.definitions.local_def_id(ast::CRATE_NODE_ID)),
2552 depth: path.segments.len(),
2555 max_assoc_types = path.segments.len() - qself.position;
2556 // Make sure the trait is valid.
2557 let _ = self.resolve_trait_reference(id, path, max_assoc_types, None);
2560 max_assoc_types = path.segments.len();
2564 let mut resolution = self.with_no_errors(|this| {
2565 this.resolve_path(id, path, 0, namespace).ok()
2567 for depth in 1..max_assoc_types {
2568 if resolution.is_some() {
2571 self.with_no_errors(|this| {
2572 let partial_resolution = this.resolve_path(id, path, depth, TypeNS).ok();
2573 if let Some(Def::Mod(..)) = partial_resolution.map(|r| r.base_def) {
2574 // Modules cannot have associated items
2576 resolution = partial_resolution;
2583 /// Skips `path_depth` trailing segments, which is also reflected in the
2584 /// returned value. See `hir::def::PathResolution` for more info.
2585 fn resolve_path(&mut self, id: NodeId, path: &Path, path_depth: usize, namespace: Namespace)
2586 -> Result<PathResolution, bool /* true if an error was reported */ > {
2587 debug!("resolve_path(id={:?} path={:?}, path_depth={:?})", id, path, path_depth);
2589 let span = path.span;
2590 let segments = &path.segments[..path.segments.len() - path_depth];
2592 let mk_res = |def| PathResolution { base_def: def, depth: path_depth };
2595 let binding = self.resolve_crate_relative_path(span, segments, namespace);
2596 return binding.map(|binding| mk_res(binding.def()));
2599 // Try to find a path to an item in a module.
2600 let last_ident = segments.last().unwrap().identifier;
2601 // Resolve a single identifier with fallback to primitive types
2602 let resolve_identifier_with_fallback = |this: &mut Self, record_used| {
2603 let def = this.resolve_identifier(last_ident, namespace, record_used);
2605 None | Some(LocalDef{def: Def::Mod(..), ..}) if namespace == TypeNS =>
2606 this.primitive_type_table
2608 .get(&last_ident.name)
2609 .map_or(def, |prim_ty| Some(LocalDef::from_def(Def::PrimTy(*prim_ty)))),
2614 if segments.len() == 1 {
2615 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
2616 // don't report an error right away, but try to fallback to a primitive type.
2617 // So, we are still able to successfully resolve something like
2619 // use std::u8; // bring module u8 in scope
2620 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
2621 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
2622 // // not to non-existent std::u8::max_value
2625 // Such behavior is required for backward compatibility.
2626 // The same fallback is used when `a` resolves to nothing.
2627 let def = resolve_identifier_with_fallback(self, Some(span)).ok_or(false);
2628 return def.and_then(|def| self.adjust_local_def(def, span).ok_or(true)).map(mk_res);
2631 let unqualified_def = resolve_identifier_with_fallback(self, None);
2632 let qualified_binding = self.resolve_module_relative_path(span, segments, namespace);
2633 match (qualified_binding, unqualified_def) {
2634 (Ok(binding), Some(ref ud)) if binding.def() == ud.def &&
2635 segments[0].identifier.name != "$crate" => {
2637 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2640 "unnecessary qualification".to_string());
2645 qualified_binding.map(|binding| mk_res(binding.def()))
2648 // Resolve a single identifier
2649 fn resolve_identifier(&mut self,
2651 namespace: Namespace,
2652 record_used: Option<Span>)
2653 -> Option<LocalDef> {
2654 if identifier.name == keywords::Invalid.name() {
2658 self.resolve_ident_in_lexical_scope(identifier, namespace, record_used)
2659 .map(LexicalScopeBinding::local_def)
2662 // Resolve a local definition, potentially adjusting for closures.
2663 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2664 let ribs = match local_def.ribs {
2665 Some((ns, i)) => &self.ribs[ns][i + 1..],
2666 None => &[] as &[_],
2668 let mut def = local_def.def;
2671 span_bug!(span, "unexpected {:?} in bindings", def)
2673 Def::Local(def_id) => {
2676 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) => {
2677 // Nothing to do. Continue.
2679 ClosureRibKind(function_id) => {
2681 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
2683 let seen = self.freevars_seen
2685 .or_insert_with(|| NodeMap());
2686 if let Some(&index) = seen.get(&node_id) {
2687 def = Def::Upvar(def_id, index, function_id);
2690 let vec = self.freevars
2692 .or_insert_with(|| vec![]);
2693 let depth = vec.len();
2699 def = Def::Upvar(def_id, depth, function_id);
2700 seen.insert(node_id, depth);
2702 ItemRibKind | MethodRibKind(_) => {
2703 // This was an attempt to access an upvar inside a
2704 // named function item. This is not allowed, so we
2708 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2711 ConstantItemRibKind => {
2712 // Still doesn't deal with upvars
2715 ResolutionError::AttemptToUseNonConstantValueInConstant);
2721 Def::TyParam(..) | Def::SelfTy(..) => {
2724 NormalRibKind | MethodRibKind(_) | ClosureRibKind(..) |
2725 ModuleRibKind(..) | MacroDefinition(..) => {
2726 // Nothing to do. Continue.
2729 // This was an attempt to use a type parameter outside
2734 ResolutionError::TypeParametersFromOuterFunction);
2737 ConstantItemRibKind => {
2739 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2750 // resolve a "module-relative" path, e.g. a::b::c
2751 fn resolve_module_relative_path(&mut self,
2753 segments: &[ast::PathSegment],
2754 namespace: Namespace)
2755 -> Result<&'a NameBinding<'a>,
2756 bool /* true if an error was reported */> {
2758 segments.split_last().unwrap().1.iter().map(|ps| ps.identifier).collect::<Vec<_>>();
2760 let module = match self.resolve_module_path(&module_path, UseLexicalScope, Some(span)) {
2762 if let Some((span, msg)) = err {
2763 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2767 Indeterminate => return Err(false),
2768 Success(module) => module,
2771 let name = segments.last().unwrap().identifier.name;
2772 let result = self.resolve_name_in_module(module, name, namespace, false, Some(span));
2773 result.success().ok_or(false)
2776 /// Invariant: This must be called only during main resolution, not during
2777 /// import resolution.
2778 fn resolve_crate_relative_path<T>(&mut self, span: Span, segments: &[T], namespace: Namespace)
2779 -> Result<&'a NameBinding<'a>,
2780 bool /* true if an error was reported */>
2783 let module_path = segments.split_last().unwrap().1.iter().map(T::ident).collect::<Vec<_>>();
2784 let root = self.graph_root;
2786 let module = match self.resolve_module_path_from_root(root, &module_path, 0, Some(span)) {
2788 if let Some((span, msg)) = err {
2789 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2794 Indeterminate => return Err(false),
2796 Success(module) => module,
2799 let name = segments.last().unwrap().ident().name;
2800 let result = self.resolve_name_in_module(module, name, namespace, false, Some(span));
2801 result.success().ok_or(false)
2804 fn with_no_errors<T, F>(&mut self, f: F) -> T
2805 where F: FnOnce(&mut Resolver) -> T
2807 self.emit_errors = false;
2809 self.emit_errors = true;
2813 // Calls `f` with a `Resolver` whose current lexical scope is `module`'s lexical scope,
2814 // i.e. the module's items and the prelude (unless the module is `#[no_implicit_prelude]`).
2815 // FIXME #34673: This needs testing.
2816 pub fn with_module_lexical_scope<T, F>(&mut self, module: Module<'a>, f: F) -> T
2817 where F: FnOnce(&mut Resolver<'a>) -> T,
2819 self.with_empty_ribs(|this| {
2820 this.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2821 this.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2826 fn with_empty_ribs<T, F>(&mut self, f: F) -> T
2827 where F: FnOnce(&mut Resolver<'a>) -> T,
2829 let ribs = replace(&mut self.ribs, PerNS::<Vec<Rib>>::default());
2830 let label_ribs = replace(&mut self.label_ribs, Vec::new());
2832 let result = f(self);
2834 self.label_ribs = label_ribs;
2838 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
2839 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2841 TyKind::Path(None, _) => Some(t.id),
2842 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2843 // This doesn't handle the remaining `Ty` variants as they are not
2844 // that commonly the self_type, it might be interesting to provide
2845 // support for those in future.
2850 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
2851 // Look for a field with the same name in the current self_type.
2852 if let Some(resolution) = self.def_map.get(&node_id) {
2853 match resolution.base_def {
2854 Def::Struct(did) | Def::Union(did) if resolution.depth == 0 => {
2855 if let Some(field_names) = self.field_names.get(&did) {
2856 if field_names.iter().any(|&field_name| name == field_name) {
2866 // Look for a method in the current trait.
2867 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
2868 if let Some(&is_static_method) = self.trait_item_map.get(&(name, trait_did)) {
2869 if is_static_method {
2870 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2880 fn find_best_match(&mut self, name: &str) -> SuggestionType {
2881 if let Some(macro_name) = self.macro_names.iter().find(|&n| n == &name) {
2882 return SuggestionType::Macro(format!("{}!", macro_name));
2885 let names = self.ribs[ValueNS]
2888 .flat_map(|rib| rib.bindings.keys().map(|ident| &ident.name));
2890 if let Some(found) = find_best_match_for_name(names, name, None) {
2892 return SuggestionType::Function(found);
2894 } SuggestionType::NotFound
2897 fn resolve_labeled_block(&mut self, label: Option<SpannedIdent>, id: NodeId, block: &Block) {
2898 if let Some(label) = label {
2899 let def = Def::Label(id);
2900 self.with_label_rib(|this| {
2901 this.label_ribs.last_mut().unwrap().bindings.insert(label.node, def);
2902 this.visit_block(block);
2905 self.visit_block(block);
2909 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
2910 // First, record candidate traits for this expression if it could
2911 // result in the invocation of a method call.
2913 self.record_candidate_traits_for_expr_if_necessary(expr);
2915 // Next, resolve the node.
2917 ExprKind::Path(ref maybe_qself, ref path) => {
2918 // This is a local path in the value namespace. Walk through
2919 // scopes looking for it.
2920 if let Some(path_res) = self.resolve_possibly_assoc_item(expr.id,
2921 maybe_qself.as_ref(), path, ValueNS) {
2922 // Check if struct variant
2923 let is_struct_variant = match path_res.base_def {
2924 Def::VariantCtor(_, CtorKind::Fictive) => true,
2927 if is_struct_variant {
2928 let path_name = path_names_to_string(path, 0);
2930 let mut err = resolve_struct_error(self,
2932 ResolutionError::StructVariantUsedAsFunction(&path_name));
2934 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2936 if self.emit_errors {
2939 err.span_help(expr.span, &msg);
2942 self.record_def(expr.id, err_path_resolution());
2944 // Write the result into the def map.
2945 debug!("(resolving expr) resolved `{}`",
2946 path_names_to_string(path, 0));
2948 // Partial resolutions will need the set of traits in scope,
2949 // so they can be completed during typeck.
2950 if path_res.depth != 0 {
2951 let method_name = path.segments.last().unwrap().identifier.name;
2952 let traits = self.get_traits_containing_item(method_name);
2953 self.trait_map.insert(expr.id, traits);
2956 self.record_def(expr.id, path_res);
2959 // Be helpful if the name refers to a struct
2960 let path_name = path_names_to_string(path, 0);
2961 let type_res = self.with_no_errors(|this| {
2962 this.resolve_path(expr.id, path, 0, TypeNS)
2965 self.record_def(expr.id, err_path_resolution());
2967 if let Ok(Def::Struct(..)) = type_res.map(|r| r.base_def) {
2969 ResolutionError::StructVariantUsedAsFunction(&path_name);
2970 let mut err = resolve_struct_error(self, expr.span, error_variant);
2972 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2975 if self.emit_errors {
2978 err.span_help(expr.span, &msg);
2982 // Keep reporting some errors even if they're ignored above.
2983 if let Err(true) = self.resolve_path(expr.id, path, 0, ValueNS) {
2984 // `resolve_path` already reported the error
2986 let mut method_scope = false;
2987 let mut is_static = false;
2988 self.ribs[ValueNS].iter().rev().all(|rib| {
2989 method_scope = match rib.kind {
2990 MethodRibKind(is_static_) => {
2991 is_static = is_static_;
2994 ItemRibKind | ConstantItemRibKind => false,
2995 _ => return true, // Keep advancing
2997 false // Stop advancing
3000 if method_scope && keywords::SelfValue.name() == &*path_name {
3003 ResolutionError::SelfNotAvailableInStaticMethod);
3005 let last_name = path.segments.last().unwrap().identifier.name;
3006 let (mut msg, is_field) =
3007 match self.find_fallback_in_self_type(last_name) {
3009 // limit search to 5 to reduce the number
3010 // of stupid suggestions
3011 (match self.find_best_match(&path_name) {
3012 SuggestionType::Macro(s) => {
3013 format!("the macro `{}`", s)
3015 SuggestionType::Function(s) => format!("`{}`", s),
3016 SuggestionType::NotFound => "".to_string(),
3020 (if is_static && method_scope {
3023 format!("`self.{}`", path_name)
3026 TraitItem => (format!("to call `self.{}`", path_name), false),
3027 TraitMethod(path_str) =>
3028 (format!("to call `{}::{}`", path_str, path_name), false),
3031 let mut context = UnresolvedNameContext::Other;
3032 let mut def = Def::Err;
3033 if !msg.is_empty() {
3034 msg = format!("did you mean {}?", msg);
3036 // we display a help message if this is a module
3037 let name_path: Vec<_> =
3038 path.segments.iter().map(|seg| seg.identifier).collect();
3040 match self.resolve_module_path(&name_path[..],
3044 if let Some(def_type) = e.def() {
3047 context = UnresolvedNameContext::PathIsMod(parent);
3055 ResolutionError::UnresolvedName {
3059 is_static_method: method_scope && is_static,
3068 visit::walk_expr(self, expr);
3071 ExprKind::Struct(ref path, ..) => {
3072 self.resolve_struct_path(expr.id, path);
3074 visit::walk_expr(self, expr);
3077 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3078 match self.search_label(label.node) {
3080 self.record_def(expr.id, err_path_resolution());
3083 ResolutionError::UndeclaredLabel(&label.node.name.as_str()));
3085 Some(def @ Def::Label(_)) => {
3086 // Since this def is a label, it is never read.
3087 self.record_def(expr.id, PathResolution::new(def));
3090 span_bug!(expr.span, "label wasn't mapped to a label def!");
3094 // visit `break` argument if any
3095 visit::walk_expr(self, expr);
3098 ExprKind::IfLet(ref pattern, ref subexpression, ref if_block, ref optional_else) => {
3099 self.visit_expr(subexpression);
3101 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3102 self.resolve_pattern(pattern, PatternSource::IfLet, &mut FxHashMap());
3103 self.visit_block(if_block);
3104 self.ribs[ValueNS].pop();
3106 optional_else.as_ref().map(|expr| self.visit_expr(expr));
3109 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
3111 ExprKind::While(ref subexpression, ref block, label) => {
3112 self.visit_expr(subexpression);
3113 self.resolve_labeled_block(label, expr.id, &block);
3116 ExprKind::WhileLet(ref pattern, ref subexpression, ref block, label) => {
3117 self.visit_expr(subexpression);
3118 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3119 self.resolve_pattern(pattern, PatternSource::WhileLet, &mut FxHashMap());
3121 self.resolve_labeled_block(label, expr.id, block);
3123 self.ribs[ValueNS].pop();
3126 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
3127 self.visit_expr(subexpression);
3128 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3129 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap());
3131 self.resolve_labeled_block(label, expr.id, block);
3133 self.ribs[ValueNS].pop();
3136 ExprKind::Field(ref subexpression, _) => {
3137 self.resolve_expr(subexpression, Some(expr));
3139 ExprKind::MethodCall(_, ref types, ref arguments) => {
3140 let mut arguments = arguments.iter();
3141 self.resolve_expr(arguments.next().unwrap(), Some(expr));
3142 for argument in arguments {
3143 self.resolve_expr(argument, None);
3145 for ty in types.iter() {
3151 visit::walk_expr(self, expr);
3156 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3158 ExprKind::Field(_, name) => {
3159 // FIXME(#6890): Even though you can't treat a method like a
3160 // field, we need to add any trait methods we find that match
3161 // the field name so that we can do some nice error reporting
3162 // later on in typeck.
3163 let traits = self.get_traits_containing_item(name.node.name);
3164 self.trait_map.insert(expr.id, traits);
3166 ExprKind::MethodCall(name, ..) => {
3167 debug!("(recording candidate traits for expr) recording traits for {}",
3169 let traits = self.get_traits_containing_item(name.node.name);
3170 self.trait_map.insert(expr.id, traits);
3178 fn get_traits_containing_item(&mut self, name: Name) -> Vec<TraitCandidate> {
3179 debug!("(getting traits containing item) looking for '{}'", name);
3181 fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
3182 trait_def_id: DefId,
3183 import_id: Option<NodeId>,
3185 debug!("(adding trait info) found trait {:?} for method '{}'",
3188 found_traits.push(TraitCandidate {
3189 def_id: trait_def_id,
3190 import_id: import_id,
3194 let mut found_traits = Vec::new();
3195 // Look for the current trait.
3196 if let Some((trait_def_id, _)) = self.current_trait_ref {
3197 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3198 add_trait_info(&mut found_traits, trait_def_id, None, name);
3202 let mut search_module = self.current_module;
3204 // Look for trait children.
3205 let mut search_in_module = |this: &mut Self, module: Module<'a>| {
3206 let mut traits = module.traits.borrow_mut();
3207 if traits.is_none() {
3208 let mut collected_traits = Vec::new();
3209 module.for_each_child(|name, ns, binding| {
3210 if ns != TypeNS { return }
3211 if let Def::Trait(_) = binding.def() {
3212 collected_traits.push((name, binding));
3215 *traits = Some(collected_traits.into_boxed_slice());
3218 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
3219 let trait_def_id = binding.def().def_id();
3220 if this.trait_item_map.contains_key(&(name, trait_def_id)) {
3221 let mut import_id = None;
3222 if let NameBindingKind::Import { directive, .. } = binding.kind {
3223 let id = directive.id;
3224 this.maybe_unused_trait_imports.insert(id);
3225 this.add_to_glob_map(id, trait_name);
3226 import_id = Some(id);
3228 add_trait_info(&mut found_traits, trait_def_id, import_id, name);
3232 search_in_module(self, search_module);
3234 if let ModuleKind::Block(..) = search_module.kind {
3235 search_module = search_module.parent.unwrap();
3237 if !search_module.no_implicit_prelude {
3238 self.prelude.map(|prelude| search_in_module(self, prelude));
3247 /// When name resolution fails, this method can be used to look up candidate
3248 /// entities with the expected name. It allows filtering them using the
3249 /// supplied predicate (which should be used to only accept the types of
3250 /// definitions expected e.g. traits). The lookup spans across all crates.
3252 /// NOTE: The method does not look into imports, but this is not a problem,
3253 /// since we report the definitions (thus, the de-aliased imports).
3254 fn lookup_candidates<FilterFn>(&mut self,
3256 namespace: Namespace,
3257 filter_fn: FilterFn) -> SuggestedCandidates
3258 where FilterFn: Fn(Def) -> bool {
3260 let mut lookup_results = Vec::new();
3261 let mut worklist = Vec::new();
3262 worklist.push((self.graph_root, Vec::new(), false));
3264 while let Some((in_module,
3266 in_module_is_extern)) = worklist.pop() {
3267 self.populate_module_if_necessary(in_module);
3269 in_module.for_each_child(|name, ns, name_binding| {
3271 // avoid imports entirely
3272 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
3274 // collect results based on the filter function
3275 if name == lookup_name && ns == namespace {
3276 if filter_fn(name_binding.def()) {
3278 let ident = Ident::with_empty_ctxt(name);
3279 let params = PathParameters::none();
3280 let segment = PathSegment {
3284 let span = name_binding.span;
3285 let mut segms = path_segments.clone();
3286 segms.push(segment);
3292 // the entity is accessible in the following cases:
3293 // 1. if it's defined in the same crate, it's always
3294 // accessible (since private entities can be made public)
3295 // 2. if it's defined in another crate, it's accessible
3296 // only if both the module is public and the entity is
3297 // declared as public (due to pruning, we don't explore
3298 // outside crate private modules => no need to check this)
3299 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3300 lookup_results.push(path);
3305 // collect submodules to explore
3306 if let Ok(module) = name_binding.module() {
3308 let mut path_segments = path_segments.clone();
3309 path_segments.push(PathSegment {
3310 identifier: Ident::with_empty_ctxt(name),
3311 parameters: PathParameters::none(),
3314 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3315 // add the module to the lookup
3316 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3317 if !worklist.iter().any(|&(m, ..)| m.def() == module.def()) {
3318 worklist.push((module, path_segments, is_extern));
3325 SuggestedCandidates {
3326 name: lookup_name.as_str().to_string(),
3327 candidates: lookup_results,
3331 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3332 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3333 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3334 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3338 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
3339 let (path, id) = match *vis {
3340 ast::Visibility::Public => return ty::Visibility::Public,
3341 ast::Visibility::Crate(_) => return ty::Visibility::Restricted(ast::CRATE_NODE_ID),
3342 ast::Visibility::Restricted { ref path, id } => (path, id),
3343 ast::Visibility::Inherited => {
3344 return ty::Visibility::Restricted(self.current_module.normal_ancestor_id.unwrap());
3348 let segments: Vec<_> = path.segments.iter().map(|seg| seg.identifier).collect();
3349 let mut path_resolution = err_path_resolution();
3350 let vis = match self.resolve_module_path(&segments, DontUseLexicalScope, Some(path.span)) {
3351 Success(module) => {
3352 path_resolution = PathResolution::new(module.def().unwrap());
3353 ty::Visibility::Restricted(module.normal_ancestor_id.unwrap())
3355 Indeterminate => unreachable!(),
3357 if let Some((span, msg)) = err {
3358 self.session.span_err(span, &format!("failed to resolve module path. {}", msg));
3360 ty::Visibility::Public
3363 self.def_map.insert(id, path_resolution);
3364 if !self.is_accessible(vis) {
3365 let msg = format!("visibilities can only be restricted to ancestor modules");
3366 self.session.span_err(path.span, &msg);
3371 fn is_accessible(&self, vis: ty::Visibility) -> bool {
3372 vis.is_accessible_from(self.current_module.normal_ancestor_id.unwrap(), self)
3375 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
3376 vis.is_accessible_from(module.normal_ancestor_id.unwrap(), self)
3379 fn report_errors(&mut self) {
3380 self.report_shadowing_errors();
3381 let mut reported_spans = FxHashSet();
3383 for &AmbiguityError { span, name, b1, b2, lexical } in &self.ambiguity_errors {
3384 if !reported_spans.insert(span) { continue }
3385 let msg1 = format!("`{}` could resolve to the name imported here", name);
3386 let msg2 = format!("`{}` could also resolve to the name imported here", name);
3387 self.session.struct_span_err(span, &format!("`{}` is ambiguous", name))
3388 .span_note(b1.span, &msg1)
3389 .span_note(b2.span, &msg2)
3390 .note(&if lexical || !b1.is_glob_import() {
3391 "macro-expanded macro imports do not shadow".to_owned()
3393 format!("consider adding an explicit import of `{}` to disambiguate", name)
3398 for &PrivacyError(span, name, binding) in &self.privacy_errors {
3399 if !reported_spans.insert(span) { continue }
3400 if binding.is_extern_crate() {
3401 // Warn when using an inaccessible extern crate.
3402 let node_id = match binding.kind {
3403 NameBindingKind::Import { directive, .. } => directive.id,
3404 _ => unreachable!(),
3406 let msg = format!("extern crate `{}` is private", name);
3407 self.session.add_lint(lint::builtin::INACCESSIBLE_EXTERN_CRATE, node_id, span, msg);
3409 let def = binding.def();
3410 self.session.span_err(span, &format!("{} `{}` is private", def.kind_name(), name));
3415 fn report_shadowing_errors(&mut self) {
3416 for (name, scope) in replace(&mut self.lexical_macro_resolutions, Vec::new()) {
3417 self.resolve_legacy_scope(scope, name, true);
3420 let mut reported_errors = FxHashSet();
3421 for binding in replace(&mut self.disallowed_shadowing, Vec::new()) {
3422 if self.resolve_legacy_scope(&binding.parent, binding.name, false).is_some() &&
3423 reported_errors.insert((binding.name, binding.span)) {
3424 let msg = format!("`{}` is already in scope", binding.name);
3425 self.session.struct_span_err(binding.span, &msg)
3426 .note("macro-expanded `macro_rules!`s may not shadow \
3427 existing macros (see RFC 1560)")
3433 fn report_conflict(&mut self,
3437 binding: &NameBinding,
3438 old_binding: &NameBinding) {
3439 // Error on the second of two conflicting names
3440 if old_binding.span.lo > binding.span.lo {
3441 return self.report_conflict(parent, name, ns, old_binding, binding);
3444 let container = match parent.kind {
3445 ModuleKind::Def(Def::Mod(_), _) => "module",
3446 ModuleKind::Def(Def::Trait(_), _) => "trait",
3447 ModuleKind::Block(..) => "block",
3451 let (participle, noun) = match old_binding.is_import() {
3452 true => ("imported", "import"),
3453 false => ("defined", "definition"),
3456 let span = binding.span;
3458 if let Some(s) = self.name_already_seen.get(&name) {
3465 let kind = match (ns, old_binding.module()) {
3466 (ValueNS, _) => "a value",
3467 (MacroNS, _) => "a macro",
3468 (TypeNS, _) if old_binding.is_extern_crate() => "an extern crate",
3469 (TypeNS, Ok(module)) if module.is_normal() => "a module",
3470 (TypeNS, Ok(module)) if module.is_trait() => "a trait",
3471 (TypeNS, _) => "a type",
3473 format!("{} named `{}` has already been {} in this {}",
3474 kind, name, participle, container)
3477 let mut err = match (old_binding.is_extern_crate(), binding.is_extern_crate()) {
3479 let mut e = struct_span_err!(self.session, span, E0259, "{}", msg);
3480 e.span_label(span, &format!("`{}` was already imported", name));
3483 (true, _) | (_, true) if binding.is_import() && old_binding.is_import() => {
3484 let mut e = struct_span_err!(self.session, span, E0254, "{}", msg);
3485 e.span_label(span, &"already imported");
3488 (true, _) | (_, true) => {
3489 let mut e = struct_span_err!(self.session, span, E0260, "{}", msg);
3490 e.span_label(span, &format!("`{}` already imported", name));
3493 _ => match (old_binding.is_import(), binding.is_import()) {
3495 let mut e = struct_span_err!(self.session, span, E0428, "{}", msg);
3496 e.span_label(span, &format!("already defined"));
3500 let mut e = struct_span_err!(self.session, span, E0252, "{}", msg);
3501 e.span_label(span, &format!("already imported"));
3505 let mut e = struct_span_err!(self.session, span, E0255, "{}", msg);
3506 e.span_label(span, &format!("`{}` was already imported", name));
3512 if old_binding.span != syntax_pos::DUMMY_SP {
3513 err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
3516 self.name_already_seen.insert(name, span);
3520 fn names_to_string(names: &[Ident]) -> String {
3521 let mut first = true;
3522 let mut result = String::new();
3523 for ident in names {
3527 result.push_str("::")
3529 result.push_str(&ident.name.as_str());
3534 fn path_names_to_string(path: &Path, depth: usize) -> String {
3536 path.segments[..path.segments.len() - depth].iter().map(|seg| seg.identifier).collect();
3537 names_to_string(&names)
3540 /// When an entity with a given name is not available in scope, we search for
3541 /// entities with that name in all crates. This method allows outputting the
3542 /// results of this search in a programmer-friendly way
3543 fn show_candidates(session: &mut DiagnosticBuilder,
3544 candidates: &SuggestedCandidates) {
3546 let paths = &candidates.candidates;
3548 if paths.len() > 0 {
3549 // don't show more than MAX_CANDIDATES results, so
3550 // we're consistent with the trait suggestions
3551 const MAX_CANDIDATES: usize = 5;
3553 // we want consistent results across executions, but candidates are produced
3554 // by iterating through a hash map, so make sure they are ordered:
3555 let mut path_strings: Vec<_> = paths.into_iter()
3556 .map(|p| path_names_to_string(&p, 0))
3558 path_strings.sort();
3560 // behave differently based on how many candidates we have:
3561 if !paths.is_empty() {
3562 if paths.len() == 1 {
3564 &format!("you can import it into scope: `use {};`.",
3568 session.help("you can import several candidates \
3569 into scope (`use ...;`):");
3570 let count = path_strings.len() as isize - MAX_CANDIDATES as isize + 1;
3572 for (idx, path_string) in path_strings.iter().enumerate() {
3573 if idx == MAX_CANDIDATES - 1 && count > 1 {
3575 &format!(" and {} other candidates", count).to_string(),
3580 &format!(" `{}`", path_string).to_string(),
3589 &format!("no candidates by the name of `{}` found in your \
3590 project; maybe you misspelled the name or forgot to import \
3591 an external crate?", candidates.name.to_string()),
3596 /// A somewhat inefficient routine to obtain the name of a module.
3597 fn module_to_string(module: Module) -> String {
3598 let mut names = Vec::new();
3600 fn collect_mod(names: &mut Vec<Ident>, module: Module) {
3601 if let ModuleKind::Def(_, name) = module.kind {
3602 if let Some(parent) = module.parent {
3603 names.push(Ident::with_empty_ctxt(name));
3604 collect_mod(names, parent);
3607 // danger, shouldn't be ident?
3608 names.push(Ident::from_str("<opaque>"));
3609 collect_mod(names, module.parent.unwrap());
3612 collect_mod(&mut names, module);
3614 if names.is_empty() {
3615 return "???".to_string();
3617 names_to_string(&names.into_iter().rev().collect::<Vec<_>>())
3620 fn err_path_resolution() -> PathResolution {
3621 PathResolution::new(Def::Err)
3624 #[derive(PartialEq,Copy, Clone)]
3625 pub enum MakeGlobMap {
3630 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }