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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13 html_root_url = "https://doc.rust-lang.org/nightly/")]
15 #![feature(crate_visibility_modifier)]
16 #![feature(label_break_value)]
18 #![feature(rustc_diagnostic_macros)]
19 #![feature(slice_sort_by_cached_key)]
22 extern crate bitflags;
27 extern crate syntax_pos;
28 extern crate rustc_errors as errors;
32 extern crate rustc_data_structures;
33 extern crate rustc_metadata;
35 pub use rustc::hir::def::{Namespace, PerNS};
37 use self::TypeParameters::*;
40 use rustc::hir::map::{Definitions, DefCollector};
41 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
42 use rustc::middle::cstore::CrateStore;
43 use rustc::session::Session;
45 use rustc::hir::def::*;
46 use rustc::hir::def::Namespace::*;
47 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
48 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
49 use rustc::session::config::nightly_options;
51 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
53 use rustc_metadata::creader::CrateLoader;
54 use rustc_metadata::cstore::CStore;
56 use syntax::source_map::SourceMap;
57 use syntax::ext::hygiene::{Mark, Transparency, SyntaxContext};
58 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
59 use syntax::ext::base::SyntaxExtension;
60 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
61 use syntax::ext::base::MacroKind;
62 use syntax::symbol::{Symbol, keywords};
63 use syntax::util::lev_distance::find_best_match_for_name;
65 use syntax::visit::{self, FnKind, Visitor};
67 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
68 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
69 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
70 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
71 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
74 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
75 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
77 use std::cell::{Cell, RefCell};
78 use std::{cmp, fmt, iter, ptr};
79 use std::collections::BTreeSet;
80 use std::mem::replace;
81 use rustc_data_structures::ptr_key::PtrKey;
82 use rustc_data_structures::sync::Lrc;
84 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
85 use macros::{InvocationData, LegacyBinding, ParentScope};
87 // NB: This module needs to be declared first so diagnostics are
88 // registered before they are used.
93 mod build_reduced_graph;
96 fn is_known_tool(name: Name) -> bool {
97 ["clippy", "rustfmt"].contains(&&*name.as_str())
107 AbsolutePath(Namespace),
112 /// A free importable items suggested in case of resolution failure.
113 struct ImportSuggestion {
117 /// A field or associated item from self type suggested in case of resolution failure.
118 enum AssocSuggestion {
125 struct BindingError {
127 origin: BTreeSet<Span>,
128 target: BTreeSet<Span>,
131 impl PartialOrd for BindingError {
132 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
133 Some(self.cmp(other))
137 impl PartialEq for BindingError {
138 fn eq(&self, other: &BindingError) -> bool {
139 self.name == other.name
143 impl Ord for BindingError {
144 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
145 self.name.cmp(&other.name)
149 enum ResolutionError<'a> {
150 /// error E0401: can't use type parameters from outer function
151 TypeParametersFromOuterFunction(Def),
152 /// error E0403: the name is already used for a type parameter in this type parameter list
153 NameAlreadyUsedInTypeParameterList(Name, &'a Span),
154 /// error E0407: method is not a member of trait
155 MethodNotMemberOfTrait(Name, &'a str),
156 /// error E0437: type is not a member of trait
157 TypeNotMemberOfTrait(Name, &'a str),
158 /// error E0438: const is not a member of trait
159 ConstNotMemberOfTrait(Name, &'a str),
160 /// error E0408: variable `{}` is not bound in all patterns
161 VariableNotBoundInPattern(&'a BindingError),
162 /// error E0409: variable `{}` is bound in inconsistent ways within the same match arm
163 VariableBoundWithDifferentMode(Name, Span),
164 /// error E0415: identifier is bound more than once in this parameter list
165 IdentifierBoundMoreThanOnceInParameterList(&'a str),
166 /// error E0416: identifier is bound more than once in the same pattern
167 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
168 /// error E0426: use of undeclared label
169 UndeclaredLabel(&'a str, Option<Name>),
170 /// error E0429: `self` imports are only allowed within a { } list
171 SelfImportsOnlyAllowedWithin,
172 /// error E0430: `self` import can only appear once in the list
173 SelfImportCanOnlyAppearOnceInTheList,
174 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
175 SelfImportOnlyInImportListWithNonEmptyPrefix,
176 /// error E0433: failed to resolve
177 FailedToResolve(&'a str),
178 /// error E0434: can't capture dynamic environment in a fn item
179 CannotCaptureDynamicEnvironmentInFnItem,
180 /// error E0435: attempt to use a non-constant value in a constant
181 AttemptToUseNonConstantValueInConstant,
182 /// error E0530: X bindings cannot shadow Ys
183 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
184 /// error E0128: type parameters with a default cannot use forward declared identifiers
185 ForwardDeclaredTyParam,
188 /// Combines an error with provided span and emits it
190 /// This takes the error provided, combines it with the span and any additional spans inside the
191 /// error and emits it.
192 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver,
194 resolution_error: ResolutionError<'a>) {
195 resolve_struct_error(resolver, span, resolution_error).emit();
198 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
200 resolution_error: ResolutionError<'a>)
201 -> DiagnosticBuilder<'sess> {
202 match resolution_error {
203 ResolutionError::TypeParametersFromOuterFunction(outer_def) => {
204 let mut err = struct_span_err!(resolver.session,
207 "can't use type parameters from outer function");
208 err.span_label(span, "use of type variable from outer function");
210 let cm = resolver.session.source_map();
212 Def::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
213 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
214 resolver.definitions.opt_span(def_id)
217 reduce_impl_span_to_impl_keyword(cm, impl_span),
218 "`Self` type implicitly declared here, by this `impl`",
221 match (maybe_trait_defid, maybe_impl_defid) {
223 err.span_label(span, "can't use `Self` here");
226 err.span_label(span, "use a type here instead");
228 (None, None) => bug!("`impl` without trait nor type?"),
232 Def::TyParam(typaram_defid) => {
233 if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) {
234 err.span_label(typaram_span, "type variable from outer function");
238 bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \
243 // Try to retrieve the span of the function signature and generate a new message with
244 // a local type parameter
245 let sugg_msg = "try using a local type parameter instead";
246 if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
247 // Suggest the modification to the user
248 err.span_suggestion_with_applicability(
252 Applicability::MachineApplicable,
254 } else if let Some(sp) = cm.generate_fn_name_span(span) {
255 err.span_label(sp, "try adding a local type parameter in this method instead");
257 err.help("try using a local type parameter instead");
262 ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
263 let mut err = struct_span_err!(resolver.session,
266 "the name `{}` is already used for a type parameter \
267 in this type parameter list",
269 err.span_label(span, "already used");
270 err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
273 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
274 let mut err = struct_span_err!(resolver.session,
277 "method `{}` is not a member of trait `{}`",
280 err.span_label(span, format!("not a member of trait `{}`", trait_));
283 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
284 let mut err = struct_span_err!(resolver.session,
287 "type `{}` is not a member of trait `{}`",
290 err.span_label(span, format!("not a member of trait `{}`", trait_));
293 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
294 let mut err = struct_span_err!(resolver.session,
297 "const `{}` is not a member of trait `{}`",
300 err.span_label(span, format!("not a member of trait `{}`", trait_));
303 ResolutionError::VariableNotBoundInPattern(binding_error) => {
304 let target_sp = binding_error.target.iter().cloned().collect::<Vec<_>>();
305 let msp = MultiSpan::from_spans(target_sp.clone());
306 let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
307 let mut err = resolver.session.struct_span_err_with_code(
310 DiagnosticId::Error("E0408".into()),
312 for sp in target_sp {
313 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
315 let origin_sp = binding_error.origin.iter().cloned();
316 for sp in origin_sp {
317 err.span_label(sp, "variable not in all patterns");
321 ResolutionError::VariableBoundWithDifferentMode(variable_name,
322 first_binding_span) => {
323 let mut err = struct_span_err!(resolver.session,
326 "variable `{}` is bound in inconsistent \
327 ways within the same match arm",
329 err.span_label(span, "bound in different ways");
330 err.span_label(first_binding_span, "first binding");
333 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
334 let mut err = struct_span_err!(resolver.session,
337 "identifier `{}` is bound more than once in this parameter list",
339 err.span_label(span, "used as parameter more than once");
342 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
343 let mut err = struct_span_err!(resolver.session,
346 "identifier `{}` is bound more than once in the same pattern",
348 err.span_label(span, "used in a pattern more than once");
351 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
352 let mut err = struct_span_err!(resolver.session,
355 "use of undeclared label `{}`",
357 if let Some(lev_candidate) = lev_candidate {
358 err.span_label(span, format!("did you mean `{}`?", lev_candidate));
360 err.span_label(span, format!("undeclared label `{}`", name));
364 ResolutionError::SelfImportsOnlyAllowedWithin => {
365 struct_span_err!(resolver.session,
369 "`self` imports are only allowed within a { } list")
371 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
372 let mut err = struct_span_err!(resolver.session, span, E0430,
373 "`self` import can only appear once in an import list");
374 err.span_label(span, "can only appear once in an import list");
377 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
378 let mut err = struct_span_err!(resolver.session, span, E0431,
379 "`self` import can only appear in an import list with \
380 a non-empty prefix");
381 err.span_label(span, "can only appear in an import list with a non-empty prefix");
384 ResolutionError::FailedToResolve(msg) => {
385 let mut err = struct_span_err!(resolver.session, span, E0433,
386 "failed to resolve: {}", msg);
387 err.span_label(span, msg);
390 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
391 let mut err = struct_span_err!(resolver.session,
395 "can't capture dynamic environment in a fn item");
396 err.help("use the `|| { ... }` closure form instead");
399 ResolutionError::AttemptToUseNonConstantValueInConstant => {
400 let mut err = struct_span_err!(resolver.session, span, E0435,
401 "attempt to use a non-constant value in a constant");
402 err.span_label(span, "non-constant value");
405 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
406 let shadows_what = binding.descr();
407 let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
408 what_binding, shadows_what);
409 err.span_label(span, format!("cannot be named the same as {} {}",
410 binding.article(), shadows_what));
411 let participle = if binding.is_import() { "imported" } else { "defined" };
412 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
413 err.span_label(binding.span, msg);
416 ResolutionError::ForwardDeclaredTyParam => {
417 let mut err = struct_span_err!(resolver.session, span, E0128,
418 "type parameters with a default cannot use \
419 forward declared identifiers");
421 span, "defaulted type parameters cannot be forward declared".to_string());
427 /// Adjust the impl span so that just the `impl` keyword is taken by removing
428 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
429 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`)
431 /// Attention: The method used is very fragile since it essentially duplicates the work of the
432 /// parser. If you need to use this function or something similar, please consider updating the
433 /// source_map functions and this function to something more robust.
434 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
435 let impl_span = cm.span_until_char(impl_span, '<');
436 let impl_span = cm.span_until_whitespace(impl_span);
440 #[derive(Copy, Clone, Debug)]
443 binding_mode: BindingMode,
446 /// Map from the name in a pattern to its binding mode.
447 type BindingMap = FxHashMap<Ident, BindingInfo>;
449 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
460 fn descr(self) -> &'static str {
462 PatternSource::Match => "match binding",
463 PatternSource::IfLet => "if let binding",
464 PatternSource::WhileLet => "while let binding",
465 PatternSource::Let => "let binding",
466 PatternSource::For => "for binding",
467 PatternSource::FnParam => "function parameter",
472 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
473 enum AliasPossibility {
478 #[derive(Copy, Clone, Debug)]
479 enum PathSource<'a> {
480 // Type paths `Path`.
482 // Trait paths in bounds or impls.
483 Trait(AliasPossibility),
484 // Expression paths `path`, with optional parent context.
485 Expr(Option<&'a Expr>),
486 // Paths in path patterns `Path`.
488 // Paths in struct expressions and patterns `Path { .. }`.
490 // Paths in tuple struct patterns `Path(..)`.
492 // `m::A::B` in `<T as m::A>::B::C`.
493 TraitItem(Namespace),
494 // Path in `pub(path)`
498 impl<'a> PathSource<'a> {
499 fn namespace(self) -> Namespace {
501 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
502 PathSource::Visibility => TypeNS,
503 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
504 PathSource::TraitItem(ns) => ns,
508 fn global_by_default(self) -> bool {
510 PathSource::Visibility => true,
511 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
512 PathSource::Struct | PathSource::TupleStruct |
513 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
517 fn defer_to_typeck(self) -> bool {
519 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
520 PathSource::Struct | PathSource::TupleStruct => true,
521 PathSource::Trait(_) | PathSource::TraitItem(..) |
522 PathSource::Visibility => false,
526 fn descr_expected(self) -> &'static str {
528 PathSource::Type => "type",
529 PathSource::Trait(_) => "trait",
530 PathSource::Pat => "unit struct/variant or constant",
531 PathSource::Struct => "struct, variant or union type",
532 PathSource::TupleStruct => "tuple struct/variant",
533 PathSource::Visibility => "module",
534 PathSource::TraitItem(ns) => match ns {
535 TypeNS => "associated type",
536 ValueNS => "method or associated constant",
537 MacroNS => bug!("associated macro"),
539 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
540 // "function" here means "anything callable" rather than `Def::Fn`,
541 // this is not precise but usually more helpful than just "value".
542 Some(&ExprKind::Call(..)) => "function",
548 fn is_expected(self, def: Def) -> bool {
550 PathSource::Type => match def {
551 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
552 Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) |
553 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) |
554 Def::SelfTy(..) | Def::Existential(..) |
555 Def::ForeignTy(..) => true,
558 PathSource::Trait(AliasPossibility::No) => match def {
559 Def::Trait(..) => true,
562 PathSource::Trait(AliasPossibility::Maybe) => match def {
563 Def::Trait(..) => true,
564 Def::TraitAlias(..) => true,
567 PathSource::Expr(..) => match def {
568 Def::StructCtor(_, CtorKind::Const) | Def::StructCtor(_, CtorKind::Fn) |
569 Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) |
570 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
571 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) |
572 Def::SelfCtor(..) => true,
575 PathSource::Pat => match def {
576 Def::StructCtor(_, CtorKind::Const) |
577 Def::VariantCtor(_, CtorKind::Const) |
578 Def::Const(..) | Def::AssociatedConst(..) |
579 Def::SelfCtor(..) => true,
582 PathSource::TupleStruct => match def {
583 Def::StructCtor(_, CtorKind::Fn) |
584 Def::VariantCtor(_, CtorKind::Fn) |
585 Def::SelfCtor(..) => true,
588 PathSource::Struct => match def {
589 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
590 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
593 PathSource::TraitItem(ns) => match def {
594 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
595 Def::AssociatedTy(..) if ns == TypeNS => true,
598 PathSource::Visibility => match def {
599 Def::Mod(..) => true,
605 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
606 __diagnostic_used!(E0404);
607 __diagnostic_used!(E0405);
608 __diagnostic_used!(E0412);
609 __diagnostic_used!(E0422);
610 __diagnostic_used!(E0423);
611 __diagnostic_used!(E0425);
612 __diagnostic_used!(E0531);
613 __diagnostic_used!(E0532);
614 __diagnostic_used!(E0573);
615 __diagnostic_used!(E0574);
616 __diagnostic_used!(E0575);
617 __diagnostic_used!(E0576);
618 __diagnostic_used!(E0577);
619 __diagnostic_used!(E0578);
620 match (self, has_unexpected_resolution) {
621 (PathSource::Trait(_), true) => "E0404",
622 (PathSource::Trait(_), false) => "E0405",
623 (PathSource::Type, true) => "E0573",
624 (PathSource::Type, false) => "E0412",
625 (PathSource::Struct, true) => "E0574",
626 (PathSource::Struct, false) => "E0422",
627 (PathSource::Expr(..), true) => "E0423",
628 (PathSource::Expr(..), false) => "E0425",
629 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
630 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
631 (PathSource::TraitItem(..), true) => "E0575",
632 (PathSource::TraitItem(..), false) => "E0576",
633 (PathSource::Visibility, true) => "E0577",
634 (PathSource::Visibility, false) => "E0578",
639 // A minimal representation of a path segment. We use this in resolve because
640 // we synthesize 'path segments' which don't have the rest of an AST or HIR
642 #[derive(Clone, Copy, Debug)]
649 fn from_path(path: &Path) -> Vec<Segment> {
650 path.segments.iter().map(|s| s.into()).collect()
653 fn from_ident(ident: Ident) -> Segment {
660 fn names_to_string(segments: &[Segment]) -> String {
661 names_to_string(&segments.iter()
662 .map(|seg| seg.ident)
663 .collect::<Vec<_>>())
667 impl<'a> From<&'a ast::PathSegment> for Segment {
668 fn from(seg: &'a ast::PathSegment) -> Segment {
676 struct UsePlacementFinder {
677 target_module: NodeId,
682 impl UsePlacementFinder {
683 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
684 let mut finder = UsePlacementFinder {
689 visit::walk_crate(&mut finder, krate);
690 (finder.span, finder.found_use)
694 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
697 module: &'tcx ast::Mod,
699 _: &[ast::Attribute],
702 if self.span.is_some() {
705 if node_id != self.target_module {
706 visit::walk_mod(self, module);
709 // find a use statement
710 for item in &module.items {
712 ItemKind::Use(..) => {
713 // don't suggest placing a use before the prelude
714 // import or other generated ones
715 if item.span.ctxt().outer().expn_info().is_none() {
716 self.span = Some(item.span.shrink_to_lo());
717 self.found_use = true;
721 // don't place use before extern crate
722 ItemKind::ExternCrate(_) => {}
723 // but place them before the first other item
724 _ => if self.span.map_or(true, |span| item.span < span ) {
725 if item.span.ctxt().outer().expn_info().is_none() {
726 // don't insert between attributes and an item
727 if item.attrs.is_empty() {
728 self.span = Some(item.span.shrink_to_lo());
730 // find the first attribute on the item
731 for attr in &item.attrs {
732 if self.span.map_or(true, |span| attr.span < span) {
733 self.span = Some(attr.span.shrink_to_lo());
744 /// This thing walks the whole crate in DFS manner, visiting each item, resolving names as it goes.
745 impl<'a, 'tcx, 'cl> Visitor<'tcx> for Resolver<'a, 'cl> {
746 fn visit_item(&mut self, item: &'tcx Item) {
747 self.resolve_item(item);
749 fn visit_arm(&mut self, arm: &'tcx Arm) {
750 self.resolve_arm(arm);
752 fn visit_block(&mut self, block: &'tcx Block) {
753 self.resolve_block(block);
755 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
756 self.with_constant_rib(|this| {
757 visit::walk_anon_const(this, constant);
760 fn visit_expr(&mut self, expr: &'tcx Expr) {
761 self.resolve_expr(expr, None);
763 fn visit_local(&mut self, local: &'tcx Local) {
764 self.resolve_local(local);
766 fn visit_ty(&mut self, ty: &'tcx Ty) {
768 TyKind::Path(ref qself, ref path) => {
769 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
771 TyKind::ImplicitSelf => {
772 let self_ty = keywords::SelfType.ident();
773 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
774 .map_or(Def::Err, |d| d.def());
775 self.record_def(ty.id, PathResolution::new(def));
779 visit::walk_ty(self, ty);
781 fn visit_poly_trait_ref(&mut self,
782 tref: &'tcx ast::PolyTraitRef,
783 m: &'tcx ast::TraitBoundModifier) {
784 self.smart_resolve_path(tref.trait_ref.ref_id, None,
785 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
786 visit::walk_poly_trait_ref(self, tref, m);
788 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
789 let type_parameters = match foreign_item.node {
790 ForeignItemKind::Fn(_, ref generics) => {
791 HasTypeParameters(generics, ItemRibKind)
793 ForeignItemKind::Static(..) => NoTypeParameters,
794 ForeignItemKind::Ty => NoTypeParameters,
795 ForeignItemKind::Macro(..) => NoTypeParameters,
797 self.with_type_parameter_rib(type_parameters, |this| {
798 visit::walk_foreign_item(this, foreign_item);
801 fn visit_fn(&mut self,
802 function_kind: FnKind<'tcx>,
803 declaration: &'tcx FnDecl,
807 let (rib_kind, asyncness) = match function_kind {
808 FnKind::ItemFn(_, ref header, ..) =>
809 (ItemRibKind, header.asyncness),
810 FnKind::Method(_, ref sig, _, _) =>
811 (TraitOrImplItemRibKind, sig.header.asyncness),
812 FnKind::Closure(_) =>
813 // Async closures aren't resolved through `visit_fn`-- they're
814 // processed separately
815 (ClosureRibKind(node_id), IsAsync::NotAsync),
818 // Create a value rib for the function.
819 self.ribs[ValueNS].push(Rib::new(rib_kind));
821 // Create a label rib for the function.
822 self.label_ribs.push(Rib::new(rib_kind));
824 // Add each argument to the rib.
825 let mut bindings_list = FxHashMap::default();
826 for argument in &declaration.inputs {
827 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
829 self.visit_ty(&argument.ty);
831 debug!("(resolving function) recorded argument");
833 visit::walk_fn_ret_ty(self, &declaration.output);
835 // Resolve the function body, potentially inside the body of an async closure
836 if let IsAsync::Async { closure_id, .. } = asyncness {
837 let rib_kind = ClosureRibKind(closure_id);
838 self.ribs[ValueNS].push(Rib::new(rib_kind));
839 self.label_ribs.push(Rib::new(rib_kind));
842 match function_kind {
843 FnKind::ItemFn(.., body) |
844 FnKind::Method(.., body) => {
845 self.visit_block(body);
847 FnKind::Closure(body) => {
848 self.visit_expr(body);
852 // Leave the body of the async closure
853 if asyncness.is_async() {
854 self.label_ribs.pop();
855 self.ribs[ValueNS].pop();
858 debug!("(resolving function) leaving function");
860 self.label_ribs.pop();
861 self.ribs[ValueNS].pop();
863 fn visit_generics(&mut self, generics: &'tcx Generics) {
864 // For type parameter defaults, we have to ban access
865 // to following type parameters, as the Substs can only
866 // provide previous type parameters as they're built. We
867 // put all the parameters on the ban list and then remove
868 // them one by one as they are processed and become available.
869 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
870 let mut found_default = false;
871 default_ban_rib.bindings.extend(generics.params.iter()
872 .filter_map(|param| match param.kind {
873 GenericParamKind::Lifetime { .. } => None,
874 GenericParamKind::Type { ref default, .. } => {
875 found_default |= default.is_some();
877 Some((Ident::with_empty_ctxt(param.ident.name), Def::Err))
884 for param in &generics.params {
886 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
887 GenericParamKind::Type { ref default, .. } => {
888 for bound in ¶m.bounds {
889 self.visit_param_bound(bound);
892 if let Some(ref ty) = default {
893 self.ribs[TypeNS].push(default_ban_rib);
895 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
898 // Allow all following defaults to refer to this type parameter.
899 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
903 for p in &generics.where_clause.predicates {
904 self.visit_where_predicate(p);
909 #[derive(Copy, Clone)]
910 enum TypeParameters<'a, 'b> {
912 HasTypeParameters(// Type parameters.
915 // The kind of the rib used for type parameters.
919 /// The rib kind controls the translation of local
920 /// definitions (`Def::Local`) to upvars (`Def::Upvar`).
921 #[derive(Copy, Clone, Debug)]
923 /// No translation needs to be applied.
926 /// We passed through a closure scope at the given node ID.
927 /// Translate upvars as appropriate.
928 ClosureRibKind(NodeId /* func id */),
930 /// We passed through an impl or trait and are now in one of its
931 /// methods or associated types. Allow references to ty params that impl or trait
932 /// binds. Disallow any other upvars (including other ty params that are
934 TraitOrImplItemRibKind,
936 /// We passed through an item scope. Disallow upvars.
939 /// We're in a constant item. Can't refer to dynamic stuff.
942 /// We passed through a module.
943 ModuleRibKind(Module<'a>),
945 /// We passed through a `macro_rules!` statement
946 MacroDefinition(DefId),
948 /// All bindings in this rib are type parameters that can't be used
949 /// from the default of a type parameter because they're not declared
950 /// before said type parameter. Also see the `visit_generics` override.
951 ForwardTyParamBanRibKind,
956 /// A rib represents a scope names can live in. Note that these appear in many places, not just
957 /// around braces. At any place where the list of accessible names (of the given namespace)
958 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
959 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
962 /// Different [rib kinds](enum.RibKind) are transparent for different names.
964 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
965 /// resolving, the name is looked up from inside out.
968 bindings: FxHashMap<Ident, Def>,
973 fn new(kind: RibKind<'a>) -> Rib<'a> {
975 bindings: Default::default(),
981 /// An intermediate resolution result.
983 /// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
984 /// items are visible in their whole block, while defs only from the place they are defined
986 enum LexicalScopeBinding<'a> {
987 Item(&'a NameBinding<'a>),
991 impl<'a> LexicalScopeBinding<'a> {
992 fn item(self) -> Option<&'a NameBinding<'a>> {
994 LexicalScopeBinding::Item(binding) => Some(binding),
999 fn def(self) -> Def {
1001 LexicalScopeBinding::Item(binding) => binding.def(),
1002 LexicalScopeBinding::Def(def) => def,
1007 #[derive(Copy, Clone, Debug)]
1008 enum ModuleOrUniformRoot<'a> {
1012 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1013 CrateRootAndExternPrelude,
1015 /// Virtual module that denotes resolution in extern prelude.
1016 /// Used for paths starting with `::` on 2018 edition or `extern::`.
1019 /// Virtual module that denotes resolution in current scope.
1020 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1021 /// are always split into two parts, the first of which should be some kind of module.
1025 impl<'a> PartialEq for ModuleOrUniformRoot<'a> {
1026 fn eq(&self, other: &Self) -> bool {
1027 match (*self, *other) {
1028 (ModuleOrUniformRoot::Module(lhs),
1029 ModuleOrUniformRoot::Module(rhs)) => ptr::eq(lhs, rhs),
1030 (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1031 ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1032 (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1033 (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1039 #[derive(Clone, Debug)]
1040 enum PathResult<'a> {
1041 Module(ModuleOrUniformRoot<'a>),
1042 NonModule(PathResolution),
1044 Failed(Span, String, bool /* is the error from the last segment? */),
1048 /// An anonymous module, eg. just a block.
1052 /// fn f() {} // (1)
1053 /// { // This is an anonymous module
1054 /// f(); // This resolves to (2) as we are inside the block.
1055 /// fn f() {} // (2)
1057 /// f(); // Resolves to (1)
1061 /// Any module with a name.
1065 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1066 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1071 /// One node in the tree of modules.
1072 pub struct ModuleData<'a> {
1073 parent: Option<Module<'a>>,
1076 // The def id of the closest normal module (`mod`) ancestor (including this module).
1077 normal_ancestor_id: DefId,
1079 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1080 single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1081 Option<&'a NameBinding<'a>>)>>,
1082 multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1084 builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1086 // Macro invocations that can expand into items in this module.
1087 unresolved_invocations: RefCell<FxHashSet<Mark>>,
1089 no_implicit_prelude: bool,
1091 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1092 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1094 // Used to memoize the traits in this module for faster searches through all traits in scope.
1095 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1097 // Whether this module is populated. If not populated, any attempt to
1098 // access the children must be preceded with a
1099 // `populate_module_if_necessary` call.
1100 populated: Cell<bool>,
1102 /// Span of the module itself. Used for error reporting.
1108 type Module<'a> = &'a ModuleData<'a>;
1110 impl<'a> ModuleData<'a> {
1111 fn new(parent: Option<Module<'a>>,
1113 normal_ancestor_id: DefId,
1115 span: Span) -> Self {
1120 resolutions: Default::default(),
1121 single_segment_macro_resolutions: RefCell::new(Vec::new()),
1122 multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1123 builtin_attrs: RefCell::new(Vec::new()),
1124 unresolved_invocations: Default::default(),
1125 no_implicit_prelude: false,
1126 glob_importers: RefCell::new(Vec::new()),
1127 globs: RefCell::new(Vec::new()),
1128 traits: RefCell::new(None),
1129 populated: Cell::new(normal_ancestor_id.is_local()),
1135 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1136 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1137 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1141 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1142 let resolutions = self.resolutions.borrow();
1143 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1144 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1145 for &(&(ident, ns), &resolution) in resolutions.iter() {
1146 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1150 fn def(&self) -> Option<Def> {
1152 ModuleKind::Def(def, _) => Some(def),
1157 fn def_id(&self) -> Option<DefId> {
1158 self.def().as_ref().map(Def::def_id)
1161 // `self` resolves to the first module ancestor that `is_normal`.
1162 fn is_normal(&self) -> bool {
1164 ModuleKind::Def(Def::Mod(_), _) => true,
1169 fn is_trait(&self) -> bool {
1171 ModuleKind::Def(Def::Trait(_), _) => true,
1176 fn is_local(&self) -> bool {
1177 self.normal_ancestor_id.is_local()
1180 fn nearest_item_scope(&'a self) -> Module<'a> {
1181 if self.is_trait() { self.parent.unwrap() } else { self }
1184 fn is_ancestor_of(&self, mut other: &Self) -> bool {
1185 while !ptr::eq(self, other) {
1186 if let Some(parent) = other.parent {
1196 impl<'a> fmt::Debug for ModuleData<'a> {
1197 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1198 write!(f, "{:?}", self.def())
1202 /// Records a possibly-private value, type, or module definition.
1203 #[derive(Clone, Debug)]
1204 pub struct NameBinding<'a> {
1205 kind: NameBindingKind<'a>,
1208 vis: ty::Visibility,
1211 pub trait ToNameBinding<'a> {
1212 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1215 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1216 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1221 #[derive(Clone, Debug)]
1222 enum NameBindingKind<'a> {
1223 Def(Def, /* is_macro_export */ bool),
1226 binding: &'a NameBinding<'a>,
1227 directive: &'a ImportDirective<'a>,
1231 kind: AmbiguityKind,
1232 b1: &'a NameBinding<'a>,
1233 b2: &'a NameBinding<'a>,
1237 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1239 struct UseError<'a> {
1240 err: DiagnosticBuilder<'a>,
1241 /// Attach `use` statements for these candidates
1242 candidates: Vec<ImportSuggestion>,
1243 /// The node id of the module to place the use statements in
1245 /// Whether the diagnostic should state that it's "better"
1249 #[derive(Clone, Copy, PartialEq, Debug)]
1250 enum AmbiguityKind {
1255 LegacyHelperVsPrelude,
1260 MoreExpandedVsOuter,
1263 impl AmbiguityKind {
1264 fn descr(self) -> &'static str {
1266 AmbiguityKind::Import =>
1267 "name vs any other name during import resolution",
1268 AmbiguityKind::AbsolutePath =>
1269 "name in the crate root vs extern crate during absolute path resolution",
1270 AmbiguityKind::BuiltinAttr =>
1271 "built-in attribute vs any other name",
1272 AmbiguityKind::DeriveHelper =>
1273 "derive helper attribute vs any other name",
1274 AmbiguityKind::LegacyHelperVsPrelude =>
1275 "legacy plugin helper attribute vs name from prelude",
1276 AmbiguityKind::LegacyVsModern =>
1277 "`macro_rules` vs non-`macro_rules` from other module",
1278 AmbiguityKind::GlobVsOuter =>
1279 "glob import vs any other name from outer scope during import/macro resolution",
1280 AmbiguityKind::GlobVsGlob =>
1281 "glob import vs glob import in the same module",
1282 AmbiguityKind::GlobVsExpanded =>
1283 "glob import vs macro-expanded name in the same \
1284 module during import/macro resolution",
1285 AmbiguityKind::MoreExpandedVsOuter =>
1286 "macro-expanded name vs less macro-expanded name \
1287 from outer scope during import/macro resolution",
1292 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1293 #[derive(Clone, Copy, PartialEq)]
1294 enum AmbiguityErrorMisc {
1301 struct AmbiguityError<'a> {
1302 kind: AmbiguityKind,
1304 b1: &'a NameBinding<'a>,
1305 b2: &'a NameBinding<'a>,
1306 misc1: AmbiguityErrorMisc,
1307 misc2: AmbiguityErrorMisc,
1310 impl<'a> NameBinding<'a> {
1311 fn module(&self) -> Option<Module<'a>> {
1313 NameBindingKind::Module(module) => Some(module),
1314 NameBindingKind::Import { binding, .. } => binding.module(),
1319 fn def(&self) -> Def {
1321 NameBindingKind::Def(def, _) => def,
1322 NameBindingKind::Module(module) => module.def().unwrap(),
1323 NameBindingKind::Import { binding, .. } => binding.def(),
1324 NameBindingKind::Ambiguity { .. } => Def::Err,
1328 fn def_ignoring_ambiguity(&self) -> Def {
1330 NameBindingKind::Import { binding, .. } => binding.def_ignoring_ambiguity(),
1331 NameBindingKind::Ambiguity { b1, .. } => b1.def_ignoring_ambiguity(),
1336 // We sometimes need to treat variants as `pub` for backwards compatibility
1337 fn pseudo_vis(&self) -> ty::Visibility {
1338 if self.is_variant() && self.def().def_id().is_local() {
1339 ty::Visibility::Public
1345 fn is_variant(&self) -> bool {
1347 NameBindingKind::Def(Def::Variant(..), _) |
1348 NameBindingKind::Def(Def::VariantCtor(..), _) => true,
1353 fn is_extern_crate(&self) -> bool {
1355 NameBindingKind::Import {
1356 directive: &ImportDirective {
1357 subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1360 NameBindingKind::Module(
1361 &ModuleData { kind: ModuleKind::Def(Def::Mod(def_id), _), .. }
1362 ) => def_id.index == CRATE_DEF_INDEX,
1367 fn is_import(&self) -> bool {
1369 NameBindingKind::Import { .. } => true,
1374 fn is_glob_import(&self) -> bool {
1376 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1377 NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
1382 fn is_importable(&self) -> bool {
1384 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1389 fn is_macro_def(&self) -> bool {
1391 NameBindingKind::Def(Def::Macro(..), _) => true,
1396 fn macro_kind(&self) -> Option<MacroKind> {
1397 match self.def_ignoring_ambiguity() {
1398 Def::Macro(_, kind) => Some(kind),
1399 Def::NonMacroAttr(..) => Some(MacroKind::Attr),
1404 fn descr(&self) -> &'static str {
1405 if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1408 fn article(&self) -> &'static str {
1409 if self.is_extern_crate() { "an" } else { self.def().article() }
1412 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1413 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1414 // Then this function returns `true` if `self` may emerge from a macro *after* that
1415 // in some later round and screw up our previously found resolution.
1416 // See more detailed explanation in
1417 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1418 fn may_appear_after(&self, invoc_parent_expansion: Mark, binding: &NameBinding) -> bool {
1419 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1420 // Expansions are partially ordered, so "may appear after" is an inversion of
1421 // "certainly appears before or simultaneously" and includes unordered cases.
1422 let self_parent_expansion = self.expansion;
1423 let other_parent_expansion = binding.expansion;
1424 let certainly_before_other_or_simultaneously =
1425 other_parent_expansion.is_descendant_of(self_parent_expansion);
1426 let certainly_before_invoc_or_simultaneously =
1427 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1428 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1432 /// Interns the names of the primitive types.
1434 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1435 /// special handling, since they have no place of origin.
1437 struct PrimitiveTypeTable {
1438 primitive_types: FxHashMap<Name, PrimTy>,
1441 impl PrimitiveTypeTable {
1442 fn new() -> PrimitiveTypeTable {
1443 let mut table = PrimitiveTypeTable::default();
1445 table.intern("bool", Bool);
1446 table.intern("char", Char);
1447 table.intern("f32", Float(FloatTy::F32));
1448 table.intern("f64", Float(FloatTy::F64));
1449 table.intern("isize", Int(IntTy::Isize));
1450 table.intern("i8", Int(IntTy::I8));
1451 table.intern("i16", Int(IntTy::I16));
1452 table.intern("i32", Int(IntTy::I32));
1453 table.intern("i64", Int(IntTy::I64));
1454 table.intern("i128", Int(IntTy::I128));
1455 table.intern("str", Str);
1456 table.intern("usize", Uint(UintTy::Usize));
1457 table.intern("u8", Uint(UintTy::U8));
1458 table.intern("u16", Uint(UintTy::U16));
1459 table.intern("u32", Uint(UintTy::U32));
1460 table.intern("u64", Uint(UintTy::U64));
1461 table.intern("u128", Uint(UintTy::U128));
1465 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1466 self.primitive_types.insert(Symbol::intern(string), primitive_type);
1470 #[derive(Default, Clone)]
1471 pub struct ExternPreludeEntry<'a> {
1472 extern_crate_item: Option<&'a NameBinding<'a>>,
1473 pub introduced_by_item: bool,
1476 /// The main resolver class.
1478 /// This is the visitor that walks the whole crate.
1479 pub struct Resolver<'a, 'b: 'a> {
1480 session: &'a Session,
1483 pub definitions: Definitions,
1485 graph_root: Module<'a>,
1487 prelude: Option<Module<'a>>,
1488 pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1490 /// n.b. This is used only for better diagnostics, not name resolution itself.
1491 has_self: FxHashSet<DefId>,
1493 /// Names of fields of an item `DefId` accessible with dot syntax.
1494 /// Used for hints during error reporting.
1495 field_names: FxHashMap<DefId, Vec<Name>>,
1497 /// All imports known to succeed or fail.
1498 determined_imports: Vec<&'a ImportDirective<'a>>,
1500 /// All non-determined imports.
1501 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1503 /// The module that represents the current item scope.
1504 current_module: Module<'a>,
1506 /// The current set of local scopes for types and values.
1507 /// FIXME #4948: Reuse ribs to avoid allocation.
1508 ribs: PerNS<Vec<Rib<'a>>>,
1510 /// The current set of local scopes, for labels.
1511 label_ribs: Vec<Rib<'a>>,
1513 /// The trait that the current context can refer to.
1514 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1516 /// The current self type if inside an impl (used for better errors).
1517 current_self_type: Option<Ty>,
1519 /// The current self item if inside an ADT (used for better errors).
1520 current_self_item: Option<NodeId>,
1522 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1523 /// We are resolving a last import segment during import validation.
1524 last_import_segment: bool,
1525 /// This binding should be ignored during in-module resolution, so that we don't get
1526 /// "self-confirming" import resolutions during import validation.
1527 blacklisted_binding: Option<&'a NameBinding<'a>>,
1529 /// The idents for the primitive types.
1530 primitive_type_table: PrimitiveTypeTable,
1533 import_map: ImportMap,
1534 pub freevars: FreevarMap,
1535 freevars_seen: NodeMap<NodeMap<usize>>,
1536 pub export_map: ExportMap,
1537 pub trait_map: TraitMap,
1539 /// A map from nodes to anonymous modules.
1540 /// Anonymous modules are pseudo-modules that are implicitly created around items
1541 /// contained within blocks.
1543 /// For example, if we have this:
1551 /// There will be an anonymous module created around `g` with the ID of the
1552 /// entry block for `f`.
1553 block_map: NodeMap<Module<'a>>,
1554 module_map: FxHashMap<DefId, Module<'a>>,
1555 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1556 binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1558 pub make_glob_map: bool,
1559 /// Maps imports to the names of items actually imported (this actually maps
1560 /// all imports, but only glob imports are actually interesting).
1561 pub glob_map: GlobMap,
1563 used_imports: FxHashSet<(NodeId, Namespace)>,
1564 pub maybe_unused_trait_imports: NodeSet,
1565 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1567 /// A list of labels as of yet unused. Labels will be removed from this map when
1568 /// they are used (in a `break` or `continue` statement)
1569 pub unused_labels: FxHashMap<NodeId, Span>,
1571 /// privacy errors are delayed until the end in order to deduplicate them
1572 privacy_errors: Vec<PrivacyError<'a>>,
1573 /// ambiguity errors are delayed for deduplication
1574 ambiguity_errors: Vec<AmbiguityError<'a>>,
1575 /// `use` injections are delayed for better placement and deduplication
1576 use_injections: Vec<UseError<'a>>,
1577 /// crate-local macro expanded `macro_export` referred to by a module-relative path
1578 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1580 arenas: &'a ResolverArenas<'a>,
1581 dummy_binding: &'a NameBinding<'a>,
1583 crate_loader: &'a mut CrateLoader<'b>,
1584 macro_names: FxHashSet<Ident>,
1585 builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1586 macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1587 pub all_macros: FxHashMap<Name, Def>,
1588 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1589 macro_defs: FxHashMap<Mark, DefId>,
1590 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1591 pub whitelisted_legacy_custom_derives: Vec<Name>,
1592 pub found_unresolved_macro: bool,
1594 /// List of crate local macros that we need to warn about as being unused.
1595 /// Right now this only includes macro_rules! macros, and macros 2.0.
1596 unused_macros: FxHashSet<DefId>,
1598 /// Maps the `Mark` of an expansion to its containing module or block.
1599 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1601 /// Avoid duplicated errors for "name already defined".
1602 name_already_seen: FxHashMap<Name, Span>,
1604 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1606 /// This table maps struct IDs into struct constructor IDs,
1607 /// it's not used during normal resolution, only for better error reporting.
1608 struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1610 /// Only used for better errors on `fn(): fn()`
1611 current_type_ascription: Vec<Span>,
1613 injected_crate: Option<Module<'a>>,
1616 /// Nothing really interesting here, it just provides memory for the rest of the crate.
1618 pub struct ResolverArenas<'a> {
1619 modules: arena::TypedArena<ModuleData<'a>>,
1620 local_modules: RefCell<Vec<Module<'a>>>,
1621 name_bindings: arena::TypedArena<NameBinding<'a>>,
1622 import_directives: arena::TypedArena<ImportDirective<'a>>,
1623 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1624 invocation_data: arena::TypedArena<InvocationData<'a>>,
1625 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1628 impl<'a> ResolverArenas<'a> {
1629 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1630 let module = self.modules.alloc(module);
1631 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1632 self.local_modules.borrow_mut().push(module);
1636 fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1637 self.local_modules.borrow()
1639 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1640 self.name_bindings.alloc(name_binding)
1642 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1643 -> &'a ImportDirective {
1644 self.import_directives.alloc(import_directive)
1646 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1647 self.name_resolutions.alloc(Default::default())
1649 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1650 -> &'a InvocationData<'a> {
1651 self.invocation_data.alloc(expansion_data)
1653 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1654 self.legacy_bindings.alloc(binding)
1658 impl<'a, 'b: 'a, 'cl: 'b> ty::DefIdTree for &'a Resolver<'b, 'cl> {
1659 fn parent(self, id: DefId) -> Option<DefId> {
1661 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1662 _ => self.cstore.def_key(id).parent,
1663 }.map(|index| DefId { index, ..id })
1667 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1668 /// the resolver is no longer needed as all the relevant information is inline.
1669 impl<'a, 'cl> hir::lowering::Resolver for Resolver<'a, 'cl> {
1670 fn resolve_hir_path(
1675 self.resolve_hir_path_cb(path, is_value,
1676 |resolver, span, error| resolve_error(resolver, span, error))
1679 fn resolve_str_path(
1682 crate_root: Option<&str>,
1683 components: &[&str],
1686 let segments = iter::once(keywords::CrateRoot.ident())
1688 crate_root.into_iter()
1689 .chain(components.iter().cloned())
1690 .map(Ident::from_str)
1691 ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1694 let path = ast::Path {
1699 self.resolve_hir_path(&path, is_value)
1702 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1703 self.def_map.get(&id).cloned()
1706 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>> {
1707 self.import_map.get(&id).cloned().unwrap_or_default()
1710 fn definitions(&mut self) -> &mut Definitions {
1711 &mut self.definitions
1715 impl<'a, 'crateloader> Resolver<'a, 'crateloader> {
1716 /// Rustdoc uses this to resolve things in a recoverable way. ResolutionError<'a>
1717 /// isn't something that can be returned because it can't be made to live that long,
1718 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1719 /// just that an error occurred.
1720 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1721 -> Result<hir::Path, ()> {
1723 let mut errored = false;
1725 let path = if path_str.starts_with("::") {
1728 segments: iter::once(keywords::CrateRoot.ident())
1730 path_str.split("::").skip(1).map(Ident::from_str)
1732 .map(|i| self.new_ast_path_segment(i))
1740 .map(Ident::from_str)
1741 .map(|i| self.new_ast_path_segment(i))
1745 let path = self.resolve_hir_path_cb(&path, is_value, |_, _, _| errored = true);
1746 if errored || path.def == Def::Err {
1753 /// resolve_hir_path, but takes a callback in case there was an error
1754 fn resolve_hir_path_cb<F>(
1760 where F: for<'c, 'b> FnOnce(&'c mut Resolver, Span, ResolutionError<'b>)
1762 let namespace = if is_value { ValueNS } else { TypeNS };
1763 let span = path.span;
1764 let segments = &path.segments;
1765 let path = Segment::from_path(&path);
1766 // FIXME (Manishearth): Intra doc links won't get warned of epoch changes
1767 let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1768 span, CrateLint::No) {
1769 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1770 module.def().unwrap(),
1771 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1772 path_res.base_def(),
1773 PathResult::NonModule(..) => {
1774 let msg = "type-relative paths are not supported in this context";
1775 error_callback(self, span, ResolutionError::FailedToResolve(msg));
1778 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1779 PathResult::Failed(span, msg, _) => {
1780 error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1785 let segments: Vec<_> = segments.iter().map(|seg| {
1786 let mut hir_seg = hir::PathSegment::from_ident(seg.ident);
1787 hir_seg.def = Some(self.def_map.get(&seg.id).map_or(Def::Err, |p| p.base_def()));
1793 segments: segments.into(),
1797 fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1798 let mut seg = ast::PathSegment::from_ident(ident);
1799 seg.id = self.session.next_node_id();
1804 impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
1805 pub fn new(session: &'a Session,
1809 make_glob_map: MakeGlobMap,
1810 crate_loader: &'a mut CrateLoader<'crateloader>,
1811 arenas: &'a ResolverArenas<'a>)
1812 -> Resolver<'a, 'crateloader> {
1813 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1814 let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1815 let graph_root = arenas.alloc_module(ModuleData {
1816 no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1817 ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1819 let mut module_map = FxHashMap::default();
1820 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1822 let mut definitions = Definitions::new();
1823 DefCollector::new(&mut definitions, Mark::root())
1824 .collect_root(crate_name, session.local_crate_disambiguator());
1826 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry> =
1827 session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1830 if !attr::contains_name(&krate.attrs, "no_core") {
1831 extern_prelude.insert(Ident::from_str("core"), Default::default());
1832 if !attr::contains_name(&krate.attrs, "no_std") {
1833 extern_prelude.insert(Ident::from_str("std"), Default::default());
1834 if session.rust_2018() {
1835 extern_prelude.insert(Ident::from_str("meta"), Default::default());
1840 let mut invocations = FxHashMap::default();
1841 invocations.insert(Mark::root(),
1842 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1844 let mut macro_defs = FxHashMap::default();
1845 macro_defs.insert(Mark::root(), root_def_id);
1854 // The outermost module has def ID 0; this is not reflected in the
1860 has_self: FxHashSet::default(),
1861 field_names: FxHashMap::default(),
1863 determined_imports: Vec::new(),
1864 indeterminate_imports: Vec::new(),
1866 current_module: graph_root,
1868 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1869 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1870 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1872 label_ribs: Vec::new(),
1874 current_trait_ref: None,
1875 current_self_type: None,
1876 current_self_item: None,
1877 last_import_segment: false,
1878 blacklisted_binding: None,
1880 primitive_type_table: PrimitiveTypeTable::new(),
1882 def_map: Default::default(),
1883 import_map: Default::default(),
1884 freevars: Default::default(),
1885 freevars_seen: Default::default(),
1886 export_map: FxHashMap::default(),
1887 trait_map: Default::default(),
1889 block_map: Default::default(),
1890 extern_module_map: FxHashMap::default(),
1891 binding_parent_modules: FxHashMap::default(),
1893 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1894 glob_map: Default::default(),
1896 used_imports: FxHashSet::default(),
1897 maybe_unused_trait_imports: Default::default(),
1898 maybe_unused_extern_crates: Vec::new(),
1900 unused_labels: FxHashMap::default(),
1902 privacy_errors: Vec::new(),
1903 ambiguity_errors: Vec::new(),
1904 use_injections: Vec::new(),
1905 macro_expanded_macro_export_errors: BTreeSet::new(),
1908 dummy_binding: arenas.alloc_name_binding(NameBinding {
1909 kind: NameBindingKind::Def(Def::Err, false),
1910 expansion: Mark::root(),
1912 vis: ty::Visibility::Public,
1916 macro_names: FxHashSet::default(),
1917 builtin_macros: FxHashMap::default(),
1918 macro_use_prelude: FxHashMap::default(),
1919 all_macros: FxHashMap::default(),
1920 macro_map: FxHashMap::default(),
1923 local_macro_def_scopes: FxHashMap::default(),
1924 name_already_seen: FxHashMap::default(),
1925 whitelisted_legacy_custom_derives: Vec::new(),
1926 potentially_unused_imports: Vec::new(),
1927 struct_constructors: Default::default(),
1928 found_unresolved_macro: false,
1929 unused_macros: FxHashSet::default(),
1930 current_type_ascription: Vec::new(),
1931 injected_crate: None,
1935 pub fn arenas() -> ResolverArenas<'a> {
1939 /// Runs the function on each namespace.
1940 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1946 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1948 match self.macro_defs.get(&ctxt.outer()) {
1949 Some(&def_id) => return def_id,
1950 None => ctxt.remove_mark(),
1955 /// Entry point to crate resolution.
1956 pub fn resolve_crate(&mut self, krate: &Crate) {
1957 ImportResolver { resolver: self }.finalize_imports();
1958 self.current_module = self.graph_root;
1959 self.finalize_current_module_macro_resolutions();
1961 visit::walk_crate(self, krate);
1963 check_unused::check_crate(self, krate);
1964 self.report_errors(krate);
1965 self.crate_loader.postprocess(krate);
1972 normal_ancestor_id: DefId,
1976 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
1977 self.arenas.alloc_module(module)
1980 fn record_use(&mut self, ident: Ident, ns: Namespace,
1981 used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
1982 match used_binding.kind {
1983 NameBindingKind::Import { directive, binding, ref used } if !used.get() => {
1984 // Avoid marking `extern crate` items that refer to a name from extern prelude,
1985 // but not introduce it, as used if they are accessed from lexical scope.
1986 if is_lexical_scope {
1987 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
1988 if let Some(crate_item) = entry.extern_crate_item {
1989 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1996 directive.used.set(true);
1997 self.used_imports.insert((directive.id, ns));
1998 self.add_to_glob_map(directive.id, ident);
1999 self.record_use(ident, ns, binding, false);
2001 NameBindingKind::Ambiguity { kind, b1, b2 } => {
2002 self.ambiguity_errors.push(AmbiguityError {
2003 kind, ident, b1, b2,
2004 misc1: AmbiguityErrorMisc::None,
2005 misc2: AmbiguityErrorMisc::None,
2012 fn add_to_glob_map(&mut self, id: NodeId, ident: Ident) {
2013 if self.make_glob_map {
2014 self.glob_map.entry(id).or_default().insert(ident.name);
2018 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2019 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2020 /// `ident` in the first scope that defines it (or None if no scopes define it).
2022 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2023 /// the items are defined in the block. For example,
2026 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2029 /// g(); // This resolves to the local variable `g` since it shadows the item.
2033 /// Invariant: This must only be called during main resolution, not during
2034 /// import resolution.
2035 fn resolve_ident_in_lexical_scope(&mut self,
2038 record_used_id: Option<NodeId>,
2040 -> Option<LexicalScopeBinding<'a>> {
2041 let record_used = record_used_id.is_some();
2042 assert!(ns == TypeNS || ns == ValueNS);
2044 ident.span = if ident.name == keywords::SelfType.name() {
2045 // FIXME(jseyfried) improve `Self` hygiene
2046 ident.span.with_ctxt(SyntaxContext::empty())
2051 ident = ident.modern_and_legacy();
2054 // Walk backwards up the ribs in scope.
2055 let mut module = self.graph_root;
2056 for i in (0 .. self.ribs[ns].len()).rev() {
2057 if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2058 // The ident resolves to a type parameter or local variable.
2059 return Some(LexicalScopeBinding::Def(
2060 self.adjust_local_def(ns, i, def, record_used, path_span)
2064 module = match self.ribs[ns][i].kind {
2065 ModuleRibKind(module) => module,
2066 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2067 // If an invocation of this macro created `ident`, give up on `ident`
2068 // and switch to `ident`'s source from the macro definition.
2069 ident.span.remove_mark();
2075 let item = self.resolve_ident_in_module_unadjusted(
2076 ModuleOrUniformRoot::Module(module),
2082 if let Ok(binding) = item {
2083 // The ident resolves to an item.
2084 return Some(LexicalScopeBinding::Item(binding));
2088 ModuleKind::Block(..) => {}, // We can see through blocks
2093 ident.span = ident.span.modern();
2094 let mut poisoned = None;
2096 let opt_module = if let Some(node_id) = record_used_id {
2097 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2098 node_id, &mut poisoned)
2100 self.hygienic_lexical_parent(module, &mut ident.span)
2102 module = unwrap_or!(opt_module, break);
2103 let orig_current_module = self.current_module;
2104 self.current_module = module; // Lexical resolutions can never be a privacy error.
2105 let result = self.resolve_ident_in_module_unadjusted(
2106 ModuleOrUniformRoot::Module(module),
2112 self.current_module = orig_current_module;
2116 if let Some(node_id) = poisoned {
2117 self.session.buffer_lint_with_diagnostic(
2118 lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2119 node_id, ident.span,
2120 &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2121 lint::builtin::BuiltinLintDiagnostics::
2122 ProcMacroDeriveResolutionFallback(ident.span),
2125 return Some(LexicalScopeBinding::Item(binding))
2127 Err(Determined) => continue,
2128 Err(Undetermined) =>
2129 span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2133 if !module.no_implicit_prelude {
2135 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2136 return Some(LexicalScopeBinding::Item(binding));
2139 if ns == TypeNS && is_known_tool(ident.name) {
2140 let binding = (Def::ToolMod, ty::Visibility::Public,
2141 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
2142 return Some(LexicalScopeBinding::Item(binding));
2144 if let Some(prelude) = self.prelude {
2145 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2146 ModuleOrUniformRoot::Module(prelude),
2152 return Some(LexicalScopeBinding::Item(binding));
2160 fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2161 -> Option<Module<'a>> {
2162 if !module.expansion.is_descendant_of(span.ctxt().outer()) {
2163 return Some(self.macro_def_scope(span.remove_mark()));
2166 if let ModuleKind::Block(..) = module.kind {
2167 return Some(module.parent.unwrap());
2173 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2174 span: &mut Span, node_id: NodeId,
2175 poisoned: &mut Option<NodeId>)
2176 -> Option<Module<'a>> {
2177 if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2181 // We need to support the next case under a deprecation warning
2184 // ---- begin: this comes from a proc macro derive
2185 // mod implementation_details {
2186 // // Note that `MyStruct` is not in scope here.
2187 // impl SomeTrait for MyStruct { ... }
2191 // So we have to fall back to the module's parent during lexical resolution in this case.
2192 if let Some(parent) = module.parent {
2193 // Inner module is inside the macro, parent module is outside of the macro.
2194 if module.expansion != parent.expansion &&
2195 module.expansion.is_descendant_of(parent.expansion) {
2196 // The macro is a proc macro derive
2197 if module.expansion.looks_like_proc_macro_derive() {
2198 if parent.expansion.is_descendant_of(span.ctxt().outer()) {
2199 *poisoned = Some(node_id);
2200 return module.parent;
2209 fn resolve_ident_in_module(
2211 module: ModuleOrUniformRoot<'a>,
2214 parent_scope: Option<&ParentScope<'a>>,
2217 ) -> Result<&'a NameBinding<'a>, Determinacy> {
2218 self.resolve_ident_in_module_ext(
2219 module, ident, ns, parent_scope, record_used, path_span
2220 ).map_err(|(determinacy, _)| determinacy)
2223 fn resolve_ident_in_module_ext(
2225 module: ModuleOrUniformRoot<'a>,
2228 parent_scope: Option<&ParentScope<'a>>,
2231 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2232 let orig_current_module = self.current_module;
2234 ModuleOrUniformRoot::Module(module) => {
2235 ident.span = ident.span.modern();
2236 if let Some(def) = ident.span.adjust(module.expansion) {
2237 self.current_module = self.macro_def_scope(def);
2240 ModuleOrUniformRoot::ExternPrelude => {
2241 ident.span = ident.span.modern();
2242 ident.span.adjust(Mark::root());
2244 ModuleOrUniformRoot::CrateRootAndExternPrelude |
2245 ModuleOrUniformRoot::CurrentScope => {
2249 let result = self.resolve_ident_in_module_unadjusted_ext(
2250 module, ident, ns, parent_scope, false, record_used, path_span,
2252 self.current_module = orig_current_module;
2256 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2257 let mut ctxt = ident.span.ctxt();
2258 let mark = if ident.name == keywords::DollarCrate.name() {
2259 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2260 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2261 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2262 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2263 // definitions actually produced by `macro` and `macro` definitions produced by
2264 // `macro_rules!`, but at least such configurations are not stable yet.
2265 ctxt = ctxt.modern_and_legacy();
2266 let mut iter = ctxt.marks().into_iter().rev().peekable();
2267 let mut result = None;
2268 // Find the last modern mark from the end if it exists.
2269 while let Some(&(mark, transparency)) = iter.peek() {
2270 if transparency == Transparency::Opaque {
2271 result = Some(mark);
2277 // Then find the last legacy mark from the end if it exists.
2278 for (mark, transparency) in iter {
2279 if transparency == Transparency::SemiTransparent {
2280 result = Some(mark);
2287 ctxt = ctxt.modern();
2288 ctxt.adjust(Mark::root())
2290 let module = match mark {
2291 Some(def) => self.macro_def_scope(def),
2292 None => return self.graph_root,
2294 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2297 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2298 let mut module = self.get_module(module.normal_ancestor_id);
2299 while module.span.ctxt().modern() != *ctxt {
2300 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2301 module = self.get_module(parent.normal_ancestor_id);
2308 // We maintain a list of value ribs and type ribs.
2310 // Simultaneously, we keep track of the current position in the module
2311 // graph in the `current_module` pointer. When we go to resolve a name in
2312 // the value or type namespaces, we first look through all the ribs and
2313 // then query the module graph. When we resolve a name in the module
2314 // namespace, we can skip all the ribs (since nested modules are not
2315 // allowed within blocks in Rust) and jump straight to the current module
2318 // Named implementations are handled separately. When we find a method
2319 // call, we consult the module node to find all of the implementations in
2320 // scope. This information is lazily cached in the module node. We then
2321 // generate a fake "implementation scope" containing all the
2322 // implementations thus found, for compatibility with old resolve pass.
2324 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2325 where F: FnOnce(&mut Resolver) -> T
2327 let id = self.definitions.local_def_id(id);
2328 let module = self.module_map.get(&id).cloned(); // clones a reference
2329 if let Some(module) = module {
2330 // Move down in the graph.
2331 let orig_module = replace(&mut self.current_module, module);
2332 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2333 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2335 self.finalize_current_module_macro_resolutions();
2338 self.current_module = orig_module;
2339 self.ribs[ValueNS].pop();
2340 self.ribs[TypeNS].pop();
2347 /// Searches the current set of local scopes for labels. Returns the first non-None label that
2348 /// is returned by the given predicate function
2350 /// Stops after meeting a closure.
2351 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2352 where P: Fn(&Rib, Ident) -> Option<R>
2354 for rib in self.label_ribs.iter().rev() {
2357 // If an invocation of this macro created `ident`, give up on `ident`
2358 // and switch to `ident`'s source from the macro definition.
2359 MacroDefinition(def) => {
2360 if def == self.macro_def(ident.span.ctxt()) {
2361 ident.span.remove_mark();
2365 // Do not resolve labels across function boundary
2369 let r = pred(rib, ident);
2377 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2378 self.with_current_self_item(item, |this| {
2379 this.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2380 let item_def_id = this.definitions.local_def_id(item.id);
2381 if this.session.features_untracked().self_in_typedefs {
2382 this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| {
2383 visit::walk_item(this, item);
2386 visit::walk_item(this, item);
2392 fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2393 let segments = &use_tree.prefix.segments;
2394 if !segments.is_empty() {
2395 let ident = segments[0].ident;
2396 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2400 let nss = match use_tree.kind {
2401 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2405 if let Some(LexicalScopeBinding::Def(..)) =
2406 self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2407 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2408 self.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2411 } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2412 for (use_tree, _) in use_trees {
2413 self.future_proof_import(use_tree);
2418 fn resolve_item(&mut self, item: &Item) {
2419 let name = item.ident.name;
2420 debug!("(resolving item) resolving {}", name);
2423 ItemKind::Ty(_, ref generics) |
2424 ItemKind::Fn(_, _, ref generics, _) |
2425 ItemKind::Existential(_, ref generics) => {
2426 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
2427 |this| visit::walk_item(this, item));
2430 ItemKind::Enum(_, ref generics) |
2431 ItemKind::Struct(_, ref generics) |
2432 ItemKind::Union(_, ref generics) => {
2433 self.resolve_adt(item, generics);
2436 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2437 self.resolve_implementation(generics,
2443 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2444 // Create a new rib for the trait-wide type parameters.
2445 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2446 let local_def_id = this.definitions.local_def_id(item.id);
2447 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2448 this.visit_generics(generics);
2449 walk_list!(this, visit_param_bound, bounds);
2451 for trait_item in trait_items {
2452 let type_parameters = HasTypeParameters(&trait_item.generics,
2453 TraitOrImplItemRibKind);
2454 this.with_type_parameter_rib(type_parameters, |this| {
2455 match trait_item.node {
2456 TraitItemKind::Const(ref ty, ref default) => {
2459 // Only impose the restrictions of
2460 // ConstRibKind for an actual constant
2461 // expression in a provided default.
2462 if let Some(ref expr) = *default{
2463 this.with_constant_rib(|this| {
2464 this.visit_expr(expr);
2468 TraitItemKind::Method(_, _) => {
2469 visit::walk_trait_item(this, trait_item)
2471 TraitItemKind::Type(..) => {
2472 visit::walk_trait_item(this, trait_item)
2474 TraitItemKind::Macro(_) => {
2475 panic!("unexpanded macro in resolve!")
2484 ItemKind::TraitAlias(ref generics, ref bounds) => {
2485 // Create a new rib for the trait-wide type parameters.
2486 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2487 let local_def_id = this.definitions.local_def_id(item.id);
2488 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2489 this.visit_generics(generics);
2490 walk_list!(this, visit_param_bound, bounds);
2495 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2496 self.with_scope(item.id, |this| {
2497 visit::walk_item(this, item);
2501 ItemKind::Static(ref ty, _, ref expr) |
2502 ItemKind::Const(ref ty, ref expr) => {
2503 self.with_item_rib(|this| {
2505 this.with_constant_rib(|this| {
2506 this.visit_expr(expr);
2511 ItemKind::Use(ref use_tree) => {
2512 self.future_proof_import(use_tree);
2515 ItemKind::ExternCrate(..) |
2516 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2517 // do nothing, these are just around to be encoded
2520 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2524 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
2525 where F: FnOnce(&mut Resolver)
2527 match type_parameters {
2528 HasTypeParameters(generics, rib_kind) => {
2529 let mut function_type_rib = Rib::new(rib_kind);
2530 let mut seen_bindings = FxHashMap::default();
2531 for param in &generics.params {
2533 GenericParamKind::Lifetime { .. } => {}
2534 GenericParamKind::Type { .. } => {
2535 let ident = param.ident.modern();
2536 debug!("with_type_parameter_rib: {}", param.id);
2538 if seen_bindings.contains_key(&ident) {
2539 let span = seen_bindings.get(&ident).unwrap();
2540 let err = ResolutionError::NameAlreadyUsedInTypeParameterList(
2544 resolve_error(self, param.ident.span, err);
2546 seen_bindings.entry(ident).or_insert(param.ident.span);
2548 // Plain insert (no renaming).
2549 let def = Def::TyParam(self.definitions.local_def_id(param.id));
2550 function_type_rib.bindings.insert(ident, def);
2551 self.record_def(param.id, PathResolution::new(def));
2555 self.ribs[TypeNS].push(function_type_rib);
2558 NoTypeParameters => {
2565 if let HasTypeParameters(..) = type_parameters {
2566 self.ribs[TypeNS].pop();
2570 fn with_label_rib<F>(&mut self, f: F)
2571 where F: FnOnce(&mut Resolver)
2573 self.label_ribs.push(Rib::new(NormalRibKind));
2575 self.label_ribs.pop();
2578 fn with_item_rib<F>(&mut self, f: F)
2579 where F: FnOnce(&mut Resolver)
2581 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2582 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2584 self.ribs[TypeNS].pop();
2585 self.ribs[ValueNS].pop();
2588 fn with_constant_rib<F>(&mut self, f: F)
2589 where F: FnOnce(&mut Resolver)
2591 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2592 self.label_ribs.push(Rib::new(ConstantItemRibKind));
2594 self.label_ribs.pop();
2595 self.ribs[ValueNS].pop();
2598 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2599 where F: FnOnce(&mut Resolver) -> T
2601 // Handle nested impls (inside fn bodies)
2602 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2603 let result = f(self);
2604 self.current_self_type = previous_value;
2608 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2609 where F: FnOnce(&mut Resolver) -> T
2611 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2612 let result = f(self);
2613 self.current_self_item = previous_value;
2617 /// This is called to resolve a trait reference from an `impl` (i.e. `impl Trait for Foo`)
2618 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2619 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2621 let mut new_val = None;
2622 let mut new_id = None;
2623 if let Some(trait_ref) = opt_trait_ref {
2624 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2625 let def = self.smart_resolve_path_fragment(
2629 trait_ref.path.span,
2630 PathSource::Trait(AliasPossibility::No),
2631 CrateLint::SimplePath(trait_ref.ref_id),
2633 if def != Def::Err {
2634 new_id = Some(def.def_id());
2635 let span = trait_ref.path.span;
2636 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2637 self.resolve_path_without_parent_scope(
2642 CrateLint::SimplePath(trait_ref.ref_id),
2645 new_val = Some((module, trait_ref.clone()));
2649 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2650 let result = f(self, new_id);
2651 self.current_trait_ref = original_trait_ref;
2655 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2656 where F: FnOnce(&mut Resolver)
2658 let mut self_type_rib = Rib::new(NormalRibKind);
2660 // plain insert (no renaming, types are not currently hygienic....)
2661 self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
2662 self.ribs[TypeNS].push(self_type_rib);
2664 self.ribs[TypeNS].pop();
2667 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
2668 where F: FnOnce(&mut Resolver)
2670 let self_def = Def::SelfCtor(impl_id);
2671 let mut self_type_rib = Rib::new(NormalRibKind);
2672 self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
2673 self.ribs[ValueNS].push(self_type_rib);
2675 self.ribs[ValueNS].pop();
2678 fn resolve_implementation(&mut self,
2679 generics: &Generics,
2680 opt_trait_reference: &Option<TraitRef>,
2683 impl_items: &[ImplItem]) {
2684 // If applicable, create a rib for the type parameters.
2685 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2686 // Dummy self type for better errors if `Self` is used in the trait path.
2687 this.with_self_rib(Def::SelfTy(None, None), |this| {
2688 // Resolve the trait reference, if necessary.
2689 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2690 let item_def_id = this.definitions.local_def_id(item_id);
2691 this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2692 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2693 // Resolve type arguments in the trait path.
2694 visit::walk_trait_ref(this, trait_ref);
2696 // Resolve the self type.
2697 this.visit_ty(self_type);
2698 // Resolve the type parameters.
2699 this.visit_generics(generics);
2700 // Resolve the items within the impl.
2701 this.with_current_self_type(self_type, |this| {
2702 this.with_self_struct_ctor_rib(item_def_id, |this| {
2703 for impl_item in impl_items {
2704 this.resolve_visibility(&impl_item.vis);
2706 // We also need a new scope for the impl item type parameters.
2707 let type_parameters = HasTypeParameters(&impl_item.generics,
2708 TraitOrImplItemRibKind);
2709 this.with_type_parameter_rib(type_parameters, |this| {
2710 use self::ResolutionError::*;
2711 match impl_item.node {
2712 ImplItemKind::Const(..) => {
2713 // If this is a trait impl, ensure the const
2715 this.check_trait_item(impl_item.ident,
2718 |n, s| ConstNotMemberOfTrait(n, s));
2719 this.with_constant_rib(|this|
2720 visit::walk_impl_item(this, impl_item)
2723 ImplItemKind::Method(..) => {
2724 // If this is a trait impl, ensure the method
2726 this.check_trait_item(impl_item.ident,
2729 |n, s| MethodNotMemberOfTrait(n, s));
2731 visit::walk_impl_item(this, impl_item);
2733 ImplItemKind::Type(ref ty) => {
2734 // If this is a trait impl, ensure the type
2736 this.check_trait_item(impl_item.ident,
2739 |n, s| TypeNotMemberOfTrait(n, s));
2743 ImplItemKind::Existential(ref bounds) => {
2744 // If this is a trait impl, ensure the type
2746 this.check_trait_item(impl_item.ident,
2749 |n, s| TypeNotMemberOfTrait(n, s));
2751 for bound in bounds {
2752 this.visit_param_bound(bound);
2755 ImplItemKind::Macro(_) =>
2756 panic!("unexpanded macro in resolve!"),
2768 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2769 where F: FnOnce(Name, &str) -> ResolutionError
2771 // If there is a TraitRef in scope for an impl, then the method must be in the
2773 if let Some((module, _)) = self.current_trait_ref {
2774 if self.resolve_ident_in_module(
2775 ModuleOrUniformRoot::Module(module),
2782 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2783 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2788 fn resolve_local(&mut self, local: &Local) {
2789 // Resolve the type.
2790 walk_list!(self, visit_ty, &local.ty);
2792 // Resolve the initializer.
2793 walk_list!(self, visit_expr, &local.init);
2795 // Resolve the pattern.
2796 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
2799 // build a map from pattern identifiers to binding-info's.
2800 // this is done hygienically. This could arise for a macro
2801 // that expands into an or-pattern where one 'x' was from the
2802 // user and one 'x' came from the macro.
2803 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2804 let mut binding_map = FxHashMap::default();
2806 pat.walk(&mut |pat| {
2807 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2808 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2809 Some(Def::Local(..)) => true,
2812 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2813 binding_map.insert(ident, binding_info);
2822 // check that all of the arms in an or-pattern have exactly the
2823 // same set of bindings, with the same binding modes for each.
2824 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2825 if pats.is_empty() {
2829 let mut missing_vars = FxHashMap::default();
2830 let mut inconsistent_vars = FxHashMap::default();
2831 for (i, p) in pats.iter().enumerate() {
2832 let map_i = self.binding_mode_map(&p);
2834 for (j, q) in pats.iter().enumerate() {
2839 let map_j = self.binding_mode_map(&q);
2840 for (&key, &binding_i) in &map_i {
2841 if map_j.is_empty() { // Account for missing bindings when
2842 let binding_error = missing_vars // map_j has none.
2844 .or_insert(BindingError {
2846 origin: BTreeSet::new(),
2847 target: BTreeSet::new(),
2849 binding_error.origin.insert(binding_i.span);
2850 binding_error.target.insert(q.span);
2852 for (&key_j, &binding_j) in &map_j {
2853 match map_i.get(&key_j) {
2854 None => { // missing binding
2855 let binding_error = missing_vars
2857 .or_insert(BindingError {
2859 origin: BTreeSet::new(),
2860 target: BTreeSet::new(),
2862 binding_error.origin.insert(binding_j.span);
2863 binding_error.target.insert(p.span);
2865 Some(binding_i) => { // check consistent binding
2866 if binding_i.binding_mode != binding_j.binding_mode {
2869 .or_insert((binding_j.span, binding_i.span));
2877 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2878 missing_vars.sort();
2879 for (_, v) in missing_vars {
2881 *v.origin.iter().next().unwrap(),
2882 ResolutionError::VariableNotBoundInPattern(v));
2884 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2885 inconsistent_vars.sort();
2886 for (name, v) in inconsistent_vars {
2887 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2891 fn resolve_arm(&mut self, arm: &Arm) {
2892 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2894 let mut bindings_list = FxHashMap::default();
2895 for pattern in &arm.pats {
2896 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2899 // This has to happen *after* we determine which pat_idents are variants
2900 self.check_consistent_bindings(&arm.pats);
2902 if let Some(ast::Guard::If(ref expr)) = arm.guard {
2903 self.visit_expr(expr)
2905 self.visit_expr(&arm.body);
2907 self.ribs[ValueNS].pop();
2910 fn resolve_block(&mut self, block: &Block) {
2911 debug!("(resolving block) entering block");
2912 // Move down in the graph, if there's an anonymous module rooted here.
2913 let orig_module = self.current_module;
2914 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2916 let mut num_macro_definition_ribs = 0;
2917 if let Some(anonymous_module) = anonymous_module {
2918 debug!("(resolving block) found anonymous module, moving down");
2919 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2920 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2921 self.current_module = anonymous_module;
2922 self.finalize_current_module_macro_resolutions();
2924 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2927 // Descend into the block.
2928 for stmt in &block.stmts {
2929 if let ast::StmtKind::Item(ref item) = stmt.node {
2930 if let ast::ItemKind::MacroDef(..) = item.node {
2931 num_macro_definition_ribs += 1;
2932 let def = self.definitions.local_def_id(item.id);
2933 self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
2934 self.label_ribs.push(Rib::new(MacroDefinition(def)));
2938 self.visit_stmt(stmt);
2942 self.current_module = orig_module;
2943 for _ in 0 .. num_macro_definition_ribs {
2944 self.ribs[ValueNS].pop();
2945 self.label_ribs.pop();
2947 self.ribs[ValueNS].pop();
2948 if anonymous_module.is_some() {
2949 self.ribs[TypeNS].pop();
2951 debug!("(resolving block) leaving block");
2954 fn fresh_binding(&mut self,
2957 outer_pat_id: NodeId,
2958 pat_src: PatternSource,
2959 bindings: &mut FxHashMap<Ident, NodeId>)
2961 // Add the binding to the local ribs, if it
2962 // doesn't already exist in the bindings map. (We
2963 // must not add it if it's in the bindings map
2964 // because that breaks the assumptions later
2965 // passes make about or-patterns.)
2966 let ident = ident.modern_and_legacy();
2967 let mut def = Def::Local(pat_id);
2968 match bindings.get(&ident).cloned() {
2969 Some(id) if id == outer_pat_id => {
2970 // `Variant(a, a)`, error
2974 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2978 Some(..) if pat_src == PatternSource::FnParam => {
2979 // `fn f(a: u8, a: u8)`, error
2983 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2987 Some(..) if pat_src == PatternSource::Match ||
2988 pat_src == PatternSource::IfLet ||
2989 pat_src == PatternSource::WhileLet => {
2990 // `Variant1(a) | Variant2(a)`, ok
2991 // Reuse definition from the first `a`.
2992 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
2995 span_bug!(ident.span, "two bindings with the same name from \
2996 unexpected pattern source {:?}", pat_src);
2999 // A completely fresh binding, add to the lists if it's valid.
3000 if ident.name != keywords::Invalid.name() {
3001 bindings.insert(ident, outer_pat_id);
3002 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
3007 PathResolution::new(def)
3010 fn resolve_pattern(&mut self,
3012 pat_src: PatternSource,
3013 // Maps idents to the node ID for the
3014 // outermost pattern that binds them.
3015 bindings: &mut FxHashMap<Ident, NodeId>) {
3016 // Visit all direct subpatterns of this pattern.
3017 let outer_pat_id = pat.id;
3018 pat.walk(&mut |pat| {
3020 PatKind::Ident(bmode, ident, ref opt_pat) => {
3021 // First try to resolve the identifier as some existing
3022 // entity, then fall back to a fresh binding.
3023 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3025 .and_then(LexicalScopeBinding::item);
3026 let resolution = binding.map(NameBinding::def).and_then(|def| {
3027 let is_syntactic_ambiguity = opt_pat.is_none() &&
3028 bmode == BindingMode::ByValue(Mutability::Immutable);
3030 Def::StructCtor(_, CtorKind::Const) |
3031 Def::VariantCtor(_, CtorKind::Const) |
3032 Def::Const(..) if is_syntactic_ambiguity => {
3033 // Disambiguate in favor of a unit struct/variant
3034 // or constant pattern.
3035 self.record_use(ident, ValueNS, binding.unwrap(), false);
3036 Some(PathResolution::new(def))
3038 Def::StructCtor(..) | Def::VariantCtor(..) |
3039 Def::Const(..) | Def::Static(..) => {
3040 // This is unambiguously a fresh binding, either syntactically
3041 // (e.g. `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3042 // to something unusable as a pattern (e.g. constructor function),
3043 // but we still conservatively report an error, see
3044 // issues/33118#issuecomment-233962221 for one reason why.
3048 ResolutionError::BindingShadowsSomethingUnacceptable(
3049 pat_src.descr(), ident.name, binding.unwrap())
3053 Def::Fn(..) | Def::Err => {
3054 // These entities are explicitly allowed
3055 // to be shadowed by fresh bindings.
3059 span_bug!(ident.span, "unexpected definition for an \
3060 identifier in pattern: {:?}", def);
3063 }).unwrap_or_else(|| {
3064 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3067 self.record_def(pat.id, resolution);
3070 PatKind::TupleStruct(ref path, ..) => {
3071 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3074 PatKind::Path(ref qself, ref path) => {
3075 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3078 PatKind::Struct(ref path, ..) => {
3079 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3087 visit::walk_pat(self, pat);
3090 // High-level and context dependent path resolution routine.
3091 // Resolves the path and records the resolution into definition map.
3092 // If resolution fails tries several techniques to find likely
3093 // resolution candidates, suggest imports or other help, and report
3094 // errors in user friendly way.
3095 fn smart_resolve_path(&mut self,
3097 qself: Option<&QSelf>,
3101 self.smart_resolve_path_with_crate_lint(id, qself, path, source, CrateLint::SimplePath(id))
3104 /// A variant of `smart_resolve_path` where you also specify extra
3105 /// information about where the path came from; this extra info is
3106 /// sometimes needed for the lint that recommends rewriting
3107 /// absolute paths to `crate`, so that it knows how to frame the
3108 /// suggestion. If you are just resolving a path like `foo::bar`
3109 /// that appears...somewhere, though, then you just want
3110 /// `CrateLint::SimplePath`, which is what `smart_resolve_path`
3111 /// already provides.
3112 fn smart_resolve_path_with_crate_lint(
3115 qself: Option<&QSelf>,
3118 crate_lint: CrateLint
3119 ) -> PathResolution {
3120 self.smart_resolve_path_fragment(
3123 &Segment::from_path(path),
3130 fn smart_resolve_path_fragment(&mut self,
3132 qself: Option<&QSelf>,
3136 crate_lint: CrateLint)
3138 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
3139 let ns = source.namespace();
3140 let is_expected = &|def| source.is_expected(def);
3141 let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
3143 // Base error is amended with one short label and possibly some longer helps/notes.
3144 let report_errors = |this: &mut Self, def: Option<Def>| {
3145 // Make the base error.
3146 let expected = source.descr_expected();
3147 let path_str = Segment::names_to_string(path);
3148 let item_str = path.last().unwrap().ident;
3149 let code = source.error_code(def.is_some());
3150 let (base_msg, fallback_label, base_span) = if let Some(def) = def {
3151 (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
3152 format!("not a {}", expected),
3155 let item_span = path.last().unwrap().ident.span;
3156 let (mod_prefix, mod_str) = if path.len() == 1 {
3157 (String::new(), "this scope".to_string())
3158 } else if path.len() == 2 && path[0].ident.name == keywords::CrateRoot.name() {
3159 (String::new(), "the crate root".to_string())
3161 let mod_path = &path[..path.len() - 1];
3162 let mod_prefix = match this.resolve_path_without_parent_scope(
3163 mod_path, Some(TypeNS), false, span, CrateLint::No
3165 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3168 }.map_or(String::new(), |def| format!("{} ", def.kind_name()));
3169 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
3171 (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
3172 format!("not found in {}", mod_str),
3175 let code = DiagnosticId::Error(code.into());
3176 let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
3178 // Emit help message for fake-self from other languages like `this`(javascript)
3179 if ["this", "my"].contains(&&*item_str.as_str())
3180 && this.self_value_is_available(path[0].ident.span, span) {
3181 err.span_suggestion_with_applicability(
3185 Applicability::MaybeIncorrect,
3189 // Emit special messages for unresolved `Self` and `self`.
3190 if is_self_type(path, ns) {
3191 __diagnostic_used!(E0411);
3192 err.code(DiagnosticId::Error("E0411".into()));
3193 let available_in = if this.session.features_untracked().self_in_typedefs {
3194 "impls, traits, and type definitions"
3198 err.span_label(span, format!("`Self` is only available in {}", available_in));
3199 if this.current_self_item.is_some() && nightly_options::is_nightly_build() {
3200 err.help("add #![feature(self_in_typedefs)] to the crate attributes \
3203 return (err, Vec::new());
3205 if is_self_value(path, ns) {
3206 __diagnostic_used!(E0424);
3207 err.code(DiagnosticId::Error("E0424".into()));
3208 err.span_label(span, format!("`self` value is a keyword \
3210 methods with `self` parameter"));
3211 return (err, Vec::new());
3214 // Try to lookup the name in more relaxed fashion for better error reporting.
3215 let ident = path.last().unwrap().ident;
3216 let candidates = this.lookup_import_candidates(ident, ns, is_expected);
3217 if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
3218 let enum_candidates =
3219 this.lookup_import_candidates(ident, ns, is_enum_variant);
3220 let mut enum_candidates = enum_candidates.iter()
3221 .map(|suggestion| import_candidate_to_paths(&suggestion)).collect::<Vec<_>>();
3222 enum_candidates.sort();
3223 for (sp, variant_path, enum_path) in enum_candidates {
3225 let msg = format!("there is an enum variant `{}`, \
3231 err.span_suggestion_with_applicability(
3233 "you can try using the variant's enum",
3235 Applicability::MachineApplicable,
3240 if path.len() == 1 && this.self_type_is_available(span) {
3241 if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) {
3242 let self_is_available = this.self_value_is_available(path[0].ident.span, span);
3244 AssocSuggestion::Field => {
3245 err.span_suggestion_with_applicability(
3248 format!("self.{}", path_str),
3249 Applicability::MachineApplicable,
3251 if !self_is_available {
3252 err.span_label(span, format!("`self` value is a keyword \
3254 methods with `self` parameter"));
3257 AssocSuggestion::MethodWithSelf if self_is_available => {
3258 err.span_suggestion_with_applicability(
3261 format!("self.{}", path_str),
3262 Applicability::MachineApplicable,
3265 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
3266 err.span_suggestion_with_applicability(
3269 format!("Self::{}", path_str),
3270 Applicability::MachineApplicable,
3274 return (err, candidates);
3278 let mut levenshtein_worked = false;
3281 if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected, span) {
3282 err.span_label(ident_span, format!("did you mean `{}`?", candidate));
3283 levenshtein_worked = true;
3286 // Try context dependent help if relaxed lookup didn't work.
3287 if let Some(def) = def {
3288 match (def, source) {
3289 (Def::Macro(..), _) => {
3290 err.span_label(span, format!("did you mean `{}!(...)`?", path_str));
3291 return (err, candidates);
3293 (Def::TyAlias(..), PathSource::Trait(_)) => {
3294 err.span_label(span, "type aliases cannot be used as traits");
3295 if nightly_options::is_nightly_build() {
3296 err.note("did you mean to use a trait alias?");
3298 return (err, candidates);
3300 (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
3301 ExprKind::Field(_, ident) => {
3302 err.span_label(parent.span, format!("did you mean `{}::{}`?",
3304 return (err, candidates);
3306 ExprKind::MethodCall(ref segment, ..) => {
3307 err.span_label(parent.span, format!("did you mean `{}::{}(...)`?",
3308 path_str, segment.ident));
3309 return (err, candidates);
3313 (Def::Enum(..), PathSource::TupleStruct)
3314 | (Def::Enum(..), PathSource::Expr(..)) => {
3315 if let Some(variants) = this.collect_enum_variants(def) {
3316 err.note(&format!("did you mean to use one \
3317 of the following variants?\n{}",
3319 .map(|suggestion| path_names_to_string(suggestion))
3320 .map(|suggestion| format!("- `{}`", suggestion))
3321 .collect::<Vec<_>>()
3325 err.note("did you mean to use one of the enum's variants?");
3327 return (err, candidates);
3329 (Def::Struct(def_id), _) if ns == ValueNS => {
3330 if let Some((ctor_def, ctor_vis))
3331 = this.struct_constructors.get(&def_id).cloned() {
3332 let accessible_ctor = this.is_accessible(ctor_vis);
3333 if is_expected(ctor_def) && !accessible_ctor {
3334 err.span_label(span, format!("constructor is not visible \
3335 here due to private fields"));
3338 // HACK(estebank): find a better way to figure out that this was a
3339 // parser issue where a struct literal is being used on an expression
3340 // where a brace being opened means a block is being started. Look
3341 // ahead for the next text to see if `span` is followed by a `{`.
3342 let sm = this.session.source_map();
3345 sp = sm.next_point(sp);
3346 match sm.span_to_snippet(sp) {
3347 Ok(ref snippet) => {
3348 if snippet.chars().any(|c| { !c.is_whitespace() }) {
3355 let followed_by_brace = match sm.span_to_snippet(sp) {
3356 Ok(ref snippet) if snippet == "{" => true,
3360 PathSource::Expr(Some(parent)) => {
3362 ExprKind::MethodCall(ref path_assignment, _) => {
3363 err.span_suggestion_with_applicability(
3364 sm.start_point(parent.span)
3365 .to(path_assignment.ident.span),
3366 "use `::` to access an associated function",
3369 path_assignment.ident),
3370 Applicability::MaybeIncorrect
3372 return (err, candidates);
3377 format!("did you mean `{} {{ /* fields */ }}`?",
3380 return (err, candidates);
3384 PathSource::Expr(None) if followed_by_brace == true => {
3387 format!("did you mean `({} {{ /* fields */ }})`?",
3390 return (err, candidates);
3395 format!("did you mean `{} {{ /* fields */ }}`?",
3398 return (err, candidates);
3402 return (err, candidates);
3404 (Def::Union(..), _) |
3405 (Def::Variant(..), _) |
3406 (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
3407 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
3409 return (err, candidates);
3411 (Def::SelfTy(..), _) if ns == ValueNS => {
3412 err.span_label(span, fallback_label);
3413 err.note("can't use `Self` as a constructor, you must use the \
3414 implemented struct");
3415 return (err, candidates);
3417 (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
3418 err.note("can't use a type alias as a constructor");
3419 return (err, candidates);
3426 if !levenshtein_worked {
3427 err.span_label(base_span, fallback_label);
3428 this.type_ascription_suggestion(&mut err, base_span);
3432 let report_errors = |this: &mut Self, def: Option<Def>| {
3433 let (err, candidates) = report_errors(this, def);
3434 let def_id = this.current_module.normal_ancestor_id;
3435 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3436 let better = def.is_some();
3437 this.use_injections.push(UseError { err, candidates, node_id, better });
3438 err_path_resolution()
3441 let resolution = match self.resolve_qpath_anywhere(
3447 source.defer_to_typeck(),
3448 source.global_by_default(),
3451 Some(resolution) if resolution.unresolved_segments() == 0 => {
3452 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
3455 // Add a temporary hack to smooth the transition to new struct ctor
3456 // visibility rules. See #38932 for more details.
3458 if let Def::Struct(def_id) = resolution.base_def() {
3459 if let Some((ctor_def, ctor_vis))
3460 = self.struct_constructors.get(&def_id).cloned() {
3461 if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
3462 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3463 self.session.buffer_lint(lint, id, span,
3464 "private struct constructors are not usable through \
3465 re-exports in outer modules",
3467 res = Some(PathResolution::new(ctor_def));
3472 res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3475 Some(resolution) if source.defer_to_typeck() => {
3476 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3477 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3478 // it needs to be added to the trait map.
3480 let item_name = path.last().unwrap().ident;
3481 let traits = self.get_traits_containing_item(item_name, ns);
3482 self.trait_map.insert(id, traits);
3486 _ => report_errors(self, None)
3489 if let PathSource::TraitItem(..) = source {} else {
3490 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3491 self.record_def(id, resolution);
3496 fn type_ascription_suggestion(&self,
3497 err: &mut DiagnosticBuilder,
3499 debug!("type_ascription_suggetion {:?}", base_span);
3500 let cm = self.session.source_map();
3501 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3502 if let Some(sp) = self.current_type_ascription.last() {
3504 loop { // try to find the `:`, bail on first non-':'/non-whitespace
3505 sp = cm.next_point(sp);
3506 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3507 debug!("snippet {:?}", snippet);
3508 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3509 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3510 debug!("{:?} {:?}", line_sp, line_base_sp);
3512 err.span_label(base_span,
3513 "expecting a type here because of type ascription");
3514 if line_sp != line_base_sp {
3515 err.span_suggestion_short_with_applicability(
3517 "did you mean to use `;` here instead?",
3519 Applicability::MaybeIncorrect,
3523 } else if !snippet.trim().is_empty() {
3524 debug!("tried to find type ascription `:` token, couldn't find it");
3534 fn self_type_is_available(&mut self, span: Span) -> bool {
3535 let binding = self.resolve_ident_in_lexical_scope(keywords::SelfType.ident(),
3536 TypeNS, None, span);
3537 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3540 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3541 let ident = Ident::new(keywords::SelfValue.name(), self_span);
3542 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3543 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3546 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3547 fn resolve_qpath_anywhere(&mut self,
3549 qself: Option<&QSelf>,
3551 primary_ns: Namespace,
3553 defer_to_typeck: bool,
3554 global_by_default: bool,
3555 crate_lint: CrateLint)
3556 -> Option<PathResolution> {
3557 let mut fin_res = None;
3558 // FIXME: can't resolve paths in macro namespace yet, macros are
3559 // processed by the little special hack below.
3560 for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3561 if i == 0 || ns != primary_ns {
3562 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3563 // If defer_to_typeck, then resolution > no resolution,
3564 // otherwise full resolution > partial resolution > no resolution.
3565 Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3567 res => if fin_res.is_none() { fin_res = res },
3571 if primary_ns != MacroNS &&
3572 (self.macro_names.contains(&path[0].ident.modern()) ||
3573 self.builtin_macros.get(&path[0].ident.name).cloned()
3574 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) ||
3575 self.macro_use_prelude.get(&path[0].ident.name).cloned()
3576 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) {
3577 // Return some dummy definition, it's enough for error reporting.
3579 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3585 /// Handles paths that may refer to associated items.
3586 fn resolve_qpath(&mut self,
3588 qself: Option<&QSelf>,
3592 global_by_default: bool,
3593 crate_lint: CrateLint)
3594 -> Option<PathResolution> {
3596 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3597 ns={:?}, span={:?}, global_by_default={:?})",
3606 if let Some(qself) = qself {
3607 if qself.position == 0 {
3608 // This is a case like `<T>::B`, where there is no
3609 // trait to resolve. In that case, we leave the `B`
3610 // segment to be resolved by type-check.
3611 return Some(PathResolution::with_unresolved_segments(
3612 Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3616 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3618 // Currently, `path` names the full item (`A::B::C`, in
3619 // our example). so we extract the prefix of that that is
3620 // the trait (the slice upto and including
3621 // `qself.position`). And then we recursively resolve that,
3622 // but with `qself` set to `None`.
3624 // However, setting `qself` to none (but not changing the
3625 // span) loses the information about where this path
3626 // *actually* appears, so for the purposes of the crate
3627 // lint we pass along information that this is the trait
3628 // name from a fully qualified path, and this also
3629 // contains the full span (the `CrateLint::QPathTrait`).
3630 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3631 let res = self.smart_resolve_path_fragment(
3634 &path[..qself.position + 1],
3636 PathSource::TraitItem(ns),
3637 CrateLint::QPathTrait {
3639 qpath_span: qself.path_span,
3643 // The remaining segments (the `C` in our example) will
3644 // have to be resolved by type-check, since that requires doing
3645 // trait resolution.
3646 return Some(PathResolution::with_unresolved_segments(
3647 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3651 let result = match self.resolve_path_without_parent_scope(
3658 PathResult::NonModule(path_res) => path_res,
3659 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3660 PathResolution::new(module.def().unwrap())
3662 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3663 // don't report an error right away, but try to fallback to a primitive type.
3664 // So, we are still able to successfully resolve something like
3666 // use std::u8; // bring module u8 in scope
3667 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3668 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3669 // // not to non-existent std::u8::max_value
3672 // Such behavior is required for backward compatibility.
3673 // The same fallback is used when `a` resolves to nothing.
3674 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3675 PathResult::Failed(..)
3676 if (ns == TypeNS || path.len() > 1) &&
3677 self.primitive_type_table.primitive_types
3678 .contains_key(&path[0].ident.name) => {
3679 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3680 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3682 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3683 PathResolution::new(module.def().unwrap()),
3684 PathResult::Failed(span, msg, false) => {
3685 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
3686 err_path_resolution()
3688 PathResult::Module(..) | PathResult::Failed(..) => return None,
3689 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3692 if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3693 path[0].ident.name != keywords::CrateRoot.name() &&
3694 path[0].ident.name != keywords::DollarCrate.name() {
3695 let unqualified_result = {
3696 match self.resolve_path_without_parent_scope(
3697 &[*path.last().unwrap()],
3703 PathResult::NonModule(path_res) => path_res.base_def(),
3704 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3705 module.def().unwrap(),
3706 _ => return Some(result),
3709 if result.base_def() == unqualified_result {
3710 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3711 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3718 fn resolve_path_without_parent_scope(
3721 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3724 crate_lint: CrateLint,
3725 ) -> PathResult<'a> {
3726 // Macro and import paths must have full parent scope available during resolution,
3727 // other paths will do okay with parent module alone.
3728 assert!(opt_ns != None && opt_ns != Some(MacroNS));
3729 let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3730 self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3736 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3737 parent_scope: &ParentScope<'a>,
3740 crate_lint: CrateLint,
3741 ) -> PathResult<'a> {
3742 let mut module = None;
3743 let mut allow_super = true;
3744 let mut second_binding = None;
3745 self.current_module = parent_scope.module;
3748 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3749 path_span={:?}, crate_lint={:?})",
3757 for (i, &Segment { ident, id }) in path.iter().enumerate() {
3758 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3759 let record_segment_def = |this: &mut Self, def| {
3761 if let Some(id) = id {
3762 if !this.def_map.contains_key(&id) {
3763 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3764 this.record_def(id, PathResolution::new(def));
3770 let is_last = i == path.len() - 1;
3771 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3772 let name = ident.name;
3774 allow_super &= ns == TypeNS &&
3775 (name == keywords::SelfValue.name() ||
3776 name == keywords::Super.name());
3779 if allow_super && name == keywords::Super.name() {
3780 let mut ctxt = ident.span.ctxt().modern();
3781 let self_module = match i {
3782 0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3784 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3788 if let Some(self_module) = self_module {
3789 if let Some(parent) = self_module.parent {
3790 module = Some(ModuleOrUniformRoot::Module(
3791 self.resolve_self(&mut ctxt, parent)));
3795 let msg = "there are too many initial `super`s.".to_string();
3796 return PathResult::Failed(ident.span, msg, false);
3799 if name == keywords::SelfValue.name() {
3800 let mut ctxt = ident.span.ctxt().modern();
3801 module = Some(ModuleOrUniformRoot::Module(
3802 self.resolve_self(&mut ctxt, self.current_module)));
3805 if name == keywords::Extern.name() ||
3806 name == keywords::CrateRoot.name() && ident.span.rust_2018() {
3807 module = Some(ModuleOrUniformRoot::ExternPrelude);
3810 if name == keywords::CrateRoot.name() &&
3811 ident.span.rust_2015() && self.session.rust_2018() {
3812 // `::a::b` from 2015 macro on 2018 global edition
3813 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3816 if name == keywords::CrateRoot.name() ||
3817 name == keywords::Crate.name() ||
3818 name == keywords::DollarCrate.name() {
3819 // `::a::b`, `crate::a::b` or `$crate::a::b`
3820 module = Some(ModuleOrUniformRoot::Module(
3821 self.resolve_crate_root(ident)));
3827 // Report special messages for path segment keywords in wrong positions.
3828 if ident.is_path_segment_keyword() && i != 0 {
3829 let name_str = if name == keywords::CrateRoot.name() {
3830 "crate root".to_string()
3832 format!("`{}`", name)
3834 let msg = if i == 1 && path[0].ident.name == keywords::CrateRoot.name() {
3835 format!("global paths cannot start with {}", name_str)
3837 format!("{} in paths can only be used in start position", name_str)
3839 return PathResult::Failed(ident.span, msg, false);
3842 let binding = if let Some(module) = module {
3843 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3844 } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3845 assert!(ns == TypeNS);
3846 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3847 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3848 record_used, path_span)
3850 let record_used_id =
3851 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3852 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3853 // we found a locally-imported or available item/module
3854 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3855 // we found a local variable or type param
3856 Some(LexicalScopeBinding::Def(def))
3857 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3858 record_segment_def(self, def);
3859 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3863 _ => Err(Determinacy::determined(record_used)),
3870 second_binding = Some(binding);
3872 let def = binding.def();
3873 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3874 if let Some(next_module) = binding.module() {
3875 module = Some(ModuleOrUniformRoot::Module(next_module));
3876 record_segment_def(self, def);
3877 } else if def == Def::ToolMod && i + 1 != path.len() {
3878 let def = Def::NonMacroAttr(NonMacroAttrKind::Tool);
3879 return PathResult::NonModule(PathResolution::new(def));
3880 } else if def == Def::Err {
3881 return PathResult::NonModule(err_path_resolution());
3882 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3883 self.lint_if_path_starts_with_module(
3889 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3890 def, path.len() - i - 1
3893 return PathResult::Failed(ident.span,
3894 format!("not a module `{}`", ident),
3898 Err(Undetermined) => return PathResult::Indeterminate,
3899 Err(Determined) => {
3900 if let Some(ModuleOrUniformRoot::Module(module)) = module {
3901 if opt_ns.is_some() && !module.is_normal() {
3902 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3903 module.def().unwrap(), path.len() - i
3907 let module_def = match module {
3908 Some(ModuleOrUniformRoot::Module(module)) => module.def(),
3911 let msg = if module_def == self.graph_root.def() {
3912 let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3913 let mut candidates =
3914 self.lookup_import_candidates(ident, TypeNS, is_mod);
3915 candidates.sort_by_cached_key(|c| {
3916 (c.path.segments.len(), c.path.to_string())
3918 if let Some(candidate) = candidates.get(0) {
3919 format!("did you mean `{}`?", candidate.path)
3921 format!("maybe a missing `extern crate {};`?", ident)
3924 format!("use of undeclared type or module `{}`", ident)
3926 format!("could not find `{}` in `{}`", ident, path[i - 1].ident)
3928 return PathResult::Failed(ident.span, msg, is_last);
3933 self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
3935 PathResult::Module(match module {
3936 Some(module) => module,
3937 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
3938 _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
3942 fn lint_if_path_starts_with_module(
3944 crate_lint: CrateLint,
3947 second_binding: Option<&NameBinding>,
3949 let (diag_id, diag_span) = match crate_lint {
3950 CrateLint::No => return,
3951 CrateLint::SimplePath(id) => (id, path_span),
3952 CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
3953 CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
3956 let first_name = match path.get(0) {
3957 // In the 2018 edition this lint is a hard error, so nothing to do
3958 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
3962 // We're only interested in `use` paths which should start with
3963 // `{{root}}` or `extern` currently.
3964 if first_name != keywords::Extern.name() && first_name != keywords::CrateRoot.name() {
3969 // If this import looks like `crate::...` it's already good
3970 Some(Segment { ident, .. }) if ident.name == keywords::Crate.name() => return,
3971 // Otherwise go below to see if it's an extern crate
3973 // If the path has length one (and it's `CrateRoot` most likely)
3974 // then we don't know whether we're gonna be importing a crate or an
3975 // item in our crate. Defer this lint to elsewhere
3979 // If the first element of our path was actually resolved to an
3980 // `ExternCrate` (also used for `crate::...`) then no need to issue a
3981 // warning, this looks all good!
3982 if let Some(binding) = second_binding {
3983 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
3984 // Careful: we still want to rewrite paths from
3985 // renamed extern crates.
3986 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
3992 let diag = lint::builtin::BuiltinLintDiagnostics
3993 ::AbsPathWithModule(diag_span);
3994 self.session.buffer_lint_with_diagnostic(
3995 lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
3997 "absolute paths must start with `self`, `super`, \
3998 `crate`, or an external crate name in the 2018 edition",
4002 // Resolve a local definition, potentially adjusting for closures.
4003 fn adjust_local_def(&mut self,
4008 span: Span) -> Def {
4009 let ribs = &self.ribs[ns][rib_index + 1..];
4011 // An invalid forward use of a type parameter from a previous default.
4012 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
4014 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
4016 assert_eq!(def, Def::Err);
4022 span_bug!(span, "unexpected {:?} in bindings", def)
4024 Def::Local(node_id) => {
4027 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
4028 ForwardTyParamBanRibKind => {
4029 // Nothing to do. Continue.
4031 ClosureRibKind(function_id) => {
4034 let seen = self.freevars_seen
4037 if let Some(&index) = seen.get(&node_id) {
4038 def = Def::Upvar(node_id, index, function_id);
4041 let vec = self.freevars
4044 let depth = vec.len();
4045 def = Def::Upvar(node_id, depth, function_id);
4052 seen.insert(node_id, depth);
4055 ItemRibKind | TraitOrImplItemRibKind => {
4056 // This was an attempt to access an upvar inside a
4057 // named function item. This is not allowed, so we
4060 resolve_error(self, span,
4061 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
4065 ConstantItemRibKind => {
4066 // Still doesn't deal with upvars
4068 resolve_error(self, span,
4069 ResolutionError::AttemptToUseNonConstantValueInConstant);
4076 Def::TyParam(..) | Def::SelfTy(..) => {
4079 NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
4080 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
4081 ConstantItemRibKind => {
4082 // Nothing to do. Continue.
4085 // This was an attempt to use a type parameter outside
4088 resolve_error(self, span,
4089 ResolutionError::TypeParametersFromOuterFunction(def));
4101 fn lookup_assoc_candidate<FilterFn>(&mut self,
4104 filter_fn: FilterFn)
4105 -> Option<AssocSuggestion>
4106 where FilterFn: Fn(Def) -> bool
4108 fn extract_node_id(t: &Ty) -> Option<NodeId> {
4110 TyKind::Path(None, _) => Some(t.id),
4111 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
4112 // This doesn't handle the remaining `Ty` variants as they are not
4113 // that commonly the self_type, it might be interesting to provide
4114 // support for those in future.
4119 // Fields are generally expected in the same contexts as locals.
4120 if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
4121 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
4122 // Look for a field with the same name in the current self_type.
4123 if let Some(resolution) = self.def_map.get(&node_id) {
4124 match resolution.base_def() {
4125 Def::Struct(did) | Def::Union(did)
4126 if resolution.unresolved_segments() == 0 => {
4127 if let Some(field_names) = self.field_names.get(&did) {
4128 if field_names.iter().any(|&field_name| ident.name == field_name) {
4129 return Some(AssocSuggestion::Field);
4139 // Look for associated items in the current trait.
4140 if let Some((module, _)) = self.current_trait_ref {
4141 if let Ok(binding) = self.resolve_ident_in_module(
4142 ModuleOrUniformRoot::Module(module),
4149 let def = binding.def();
4151 return Some(if self.has_self.contains(&def.def_id()) {
4152 AssocSuggestion::MethodWithSelf
4154 AssocSuggestion::AssocItem
4163 fn lookup_typo_candidate<FilterFn>(&mut self,
4166 filter_fn: FilterFn,
4169 where FilterFn: Fn(Def) -> bool
4171 let add_module_candidates = |module: Module, names: &mut Vec<Name>| {
4172 for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
4173 if let Some(binding) = resolution.borrow().binding {
4174 if filter_fn(binding.def()) {
4175 names.push(ident.name);
4181 let mut names = Vec::new();
4182 if path.len() == 1 {
4183 // Search in lexical scope.
4184 // Walk backwards up the ribs in scope and collect candidates.
4185 for rib in self.ribs[ns].iter().rev() {
4186 // Locals and type parameters
4187 for (ident, def) in &rib.bindings {
4188 if filter_fn(*def) {
4189 names.push(ident.name);
4193 if let ModuleRibKind(module) = rib.kind {
4194 // Items from this module
4195 add_module_candidates(module, &mut names);
4197 if let ModuleKind::Block(..) = module.kind {
4198 // We can see through blocks
4200 // Items from the prelude
4201 if !module.no_implicit_prelude {
4202 names.extend(self.extern_prelude.iter().map(|(ident, _)| ident.name));
4203 if let Some(prelude) = self.prelude {
4204 add_module_candidates(prelude, &mut names);
4211 // Add primitive types to the mix
4212 if filter_fn(Def::PrimTy(Bool)) {
4214 self.primitive_type_table.primitive_types.iter().map(|(name, _)| name)
4218 // Search in module.
4219 let mod_path = &path[..path.len() - 1];
4220 if let PathResult::Module(module) = self.resolve_path_without_parent_scope(
4221 mod_path, Some(TypeNS), false, span, CrateLint::No
4223 if let ModuleOrUniformRoot::Module(module) = module {
4224 add_module_candidates(module, &mut names);
4229 let name = path[path.len() - 1].ident.name;
4230 // Make sure error reporting is deterministic.
4231 names.sort_by_cached_key(|name| name.as_str());
4232 match find_best_match_for_name(names.iter(), &name.as_str(), None) {
4233 Some(found) if found != name => Some(found),
4238 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4239 where F: FnOnce(&mut Resolver)
4241 if let Some(label) = label {
4242 self.unused_labels.insert(id, label.ident.span);
4243 let def = Def::Label(id);
4244 self.with_label_rib(|this| {
4245 let ident = label.ident.modern_and_legacy();
4246 this.label_ribs.last_mut().unwrap().bindings.insert(ident, def);
4254 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4255 self.with_resolved_label(label, id, |this| this.visit_block(block));
4258 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4259 // First, record candidate traits for this expression if it could
4260 // result in the invocation of a method call.
4262 self.record_candidate_traits_for_expr_if_necessary(expr);
4264 // Next, resolve the node.
4266 ExprKind::Path(ref qself, ref path) => {
4267 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4268 visit::walk_expr(self, expr);
4271 ExprKind::Struct(ref path, ..) => {
4272 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4273 visit::walk_expr(self, expr);
4276 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4277 let def = self.search_label(label.ident, |rib, ident| {
4278 rib.bindings.get(&ident.modern_and_legacy()).cloned()
4282 // Search again for close matches...
4283 // Picks the first label that is "close enough", which is not necessarily
4284 // the closest match
4285 let close_match = self.search_label(label.ident, |rib, ident| {
4286 let names = rib.bindings.iter().map(|(id, _)| &id.name);
4287 find_best_match_for_name(names, &*ident.as_str(), None)
4289 self.record_def(expr.id, err_path_resolution());
4292 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4295 Some(Def::Label(id)) => {
4296 // Since this def is a label, it is never read.
4297 self.record_def(expr.id, PathResolution::new(Def::Label(id)));
4298 self.unused_labels.remove(&id);
4301 span_bug!(expr.span, "label wasn't mapped to a label def!");
4305 // visit `break` argument if any
4306 visit::walk_expr(self, expr);
4309 ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
4310 self.visit_expr(subexpression);
4312 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4313 let mut bindings_list = FxHashMap::default();
4315 self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
4317 // This has to happen *after* we determine which pat_idents are variants
4318 self.check_consistent_bindings(pats);
4319 self.visit_block(if_block);
4320 self.ribs[ValueNS].pop();
4322 optional_else.as_ref().map(|expr| self.visit_expr(expr));
4325 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4327 ExprKind::While(ref subexpression, ref block, label) => {
4328 self.with_resolved_label(label, expr.id, |this| {
4329 this.visit_expr(subexpression);
4330 this.visit_block(block);
4334 ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
4335 self.with_resolved_label(label, expr.id, |this| {
4336 this.visit_expr(subexpression);
4337 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4338 let mut bindings_list = FxHashMap::default();
4340 this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
4342 // This has to happen *after* we determine which pat_idents are variants
4343 this.check_consistent_bindings(pats);
4344 this.visit_block(block);
4345 this.ribs[ValueNS].pop();
4349 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4350 self.visit_expr(subexpression);
4351 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4352 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4354 self.resolve_labeled_block(label, expr.id, block);
4356 self.ribs[ValueNS].pop();
4359 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4361 // Equivalent to `visit::walk_expr` + passing some context to children.
4362 ExprKind::Field(ref subexpression, _) => {
4363 self.resolve_expr(subexpression, Some(expr));
4365 ExprKind::MethodCall(ref segment, ref arguments) => {
4366 let mut arguments = arguments.iter();
4367 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4368 for argument in arguments {
4369 self.resolve_expr(argument, None);
4371 self.visit_path_segment(expr.span, segment);
4374 ExprKind::Call(ref callee, ref arguments) => {
4375 self.resolve_expr(callee, Some(expr));
4376 for argument in arguments {
4377 self.resolve_expr(argument, None);
4380 ExprKind::Type(ref type_expr, _) => {
4381 self.current_type_ascription.push(type_expr.span);
4382 visit::walk_expr(self, expr);
4383 self.current_type_ascription.pop();
4385 // Resolve the body of async exprs inside the async closure to which they desugar
4386 ExprKind::Async(_, async_closure_id, ref block) => {
4387 let rib_kind = ClosureRibKind(async_closure_id);
4388 self.ribs[ValueNS].push(Rib::new(rib_kind));
4389 self.label_ribs.push(Rib::new(rib_kind));
4390 self.visit_block(&block);
4391 self.label_ribs.pop();
4392 self.ribs[ValueNS].pop();
4394 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4395 // resolve the arguments within the proper scopes so that usages of them inside the
4396 // closure are detected as upvars rather than normal closure arg usages.
4398 _, IsAsync::Async { closure_id: inner_closure_id, .. }, _,
4399 ref fn_decl, ref body, _span,
4401 let rib_kind = ClosureRibKind(expr.id);
4402 self.ribs[ValueNS].push(Rib::new(rib_kind));
4403 self.label_ribs.push(Rib::new(rib_kind));
4404 // Resolve arguments:
4405 let mut bindings_list = FxHashMap::default();
4406 for argument in &fn_decl.inputs {
4407 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4408 self.visit_ty(&argument.ty);
4410 // No need to resolve return type-- the outer closure return type is
4411 // FunctionRetTy::Default
4413 // Now resolve the inner closure
4415 let rib_kind = ClosureRibKind(inner_closure_id);
4416 self.ribs[ValueNS].push(Rib::new(rib_kind));
4417 self.label_ribs.push(Rib::new(rib_kind));
4418 // No need to resolve arguments: the inner closure has none.
4419 // Resolve the return type:
4420 visit::walk_fn_ret_ty(self, &fn_decl.output);
4422 self.visit_expr(body);
4423 self.label_ribs.pop();
4424 self.ribs[ValueNS].pop();
4426 self.label_ribs.pop();
4427 self.ribs[ValueNS].pop();
4430 visit::walk_expr(self, expr);
4435 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4437 ExprKind::Field(_, ident) => {
4438 // FIXME(#6890): Even though you can't treat a method like a
4439 // field, we need to add any trait methods we find that match
4440 // the field name so that we can do some nice error reporting
4441 // later on in typeck.
4442 let traits = self.get_traits_containing_item(ident, ValueNS);
4443 self.trait_map.insert(expr.id, traits);
4445 ExprKind::MethodCall(ref segment, ..) => {
4446 debug!("(recording candidate traits for expr) recording traits for {}",
4448 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4449 self.trait_map.insert(expr.id, traits);
4457 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4458 -> Vec<TraitCandidate> {
4459 debug!("(getting traits containing item) looking for '{}'", ident.name);
4461 let mut found_traits = Vec::new();
4462 // Look for the current trait.
4463 if let Some((module, _)) = self.current_trait_ref {
4464 if self.resolve_ident_in_module(
4465 ModuleOrUniformRoot::Module(module),
4472 let def_id = module.def_id().unwrap();
4473 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
4477 ident.span = ident.span.modern();
4478 let mut search_module = self.current_module;
4480 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4481 search_module = unwrap_or!(
4482 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4486 if let Some(prelude) = self.prelude {
4487 if !search_module.no_implicit_prelude {
4488 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4495 fn get_traits_in_module_containing_item(&mut self,
4499 found_traits: &mut Vec<TraitCandidate>) {
4500 assert!(ns == TypeNS || ns == ValueNS);
4501 let mut traits = module.traits.borrow_mut();
4502 if traits.is_none() {
4503 let mut collected_traits = Vec::new();
4504 module.for_each_child(|name, ns, binding| {
4505 if ns != TypeNS { return }
4506 if let Def::Trait(_) = binding.def() {
4507 collected_traits.push((name, binding));
4510 *traits = Some(collected_traits.into_boxed_slice());
4513 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4514 let module = binding.module().unwrap();
4515 let mut ident = ident;
4516 if ident.span.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
4519 if self.resolve_ident_in_module_unadjusted(
4520 ModuleOrUniformRoot::Module(module),
4526 let import_id = match binding.kind {
4527 NameBindingKind::Import { directive, .. } => {
4528 self.maybe_unused_trait_imports.insert(directive.id);
4529 self.add_to_glob_map(directive.id, trait_name);
4534 let trait_def_id = module.def_id().unwrap();
4535 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id: import_id });
4540 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
4541 lookup_ident: Ident,
4542 namespace: Namespace,
4543 start_module: &'a ModuleData<'a>,
4545 filter_fn: FilterFn)
4546 -> Vec<ImportSuggestion>
4547 where FilterFn: Fn(Def) -> bool
4549 let mut candidates = Vec::new();
4550 let mut seen_modules = FxHashSet::default();
4551 let not_local_module = crate_name != keywords::Crate.ident();
4552 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
4554 while let Some((in_module,
4556 in_module_is_extern)) = worklist.pop() {
4557 self.populate_module_if_necessary(in_module);
4559 // We have to visit module children in deterministic order to avoid
4560 // instabilities in reported imports (#43552).
4561 in_module.for_each_child_stable(|ident, ns, name_binding| {
4562 // avoid imports entirely
4563 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
4564 // avoid non-importable candidates as well
4565 if !name_binding.is_importable() { return; }
4567 // collect results based on the filter function
4568 if ident.name == lookup_ident.name && ns == namespace {
4569 if filter_fn(name_binding.def()) {
4571 let mut segms = path_segments.clone();
4572 if lookup_ident.span.rust_2018() {
4573 // crate-local absolute paths start with `crate::` in edition 2018
4574 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4576 0, ast::PathSegment::from_ident(crate_name)
4580 segms.push(ast::PathSegment::from_ident(ident));
4582 span: name_binding.span,
4585 // the entity is accessible in the following cases:
4586 // 1. if it's defined in the same crate, it's always
4587 // accessible (since private entities can be made public)
4588 // 2. if it's defined in another crate, it's accessible
4589 // only if both the module is public and the entity is
4590 // declared as public (due to pruning, we don't explore
4591 // outside crate private modules => no need to check this)
4592 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
4593 candidates.push(ImportSuggestion { path });
4598 // collect submodules to explore
4599 if let Some(module) = name_binding.module() {
4601 let mut path_segments = path_segments.clone();
4602 path_segments.push(ast::PathSegment::from_ident(ident));
4604 let is_extern_crate_that_also_appears_in_prelude =
4605 name_binding.is_extern_crate() &&
4606 lookup_ident.span.rust_2018();
4608 let is_visible_to_user =
4609 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
4611 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
4612 // add the module to the lookup
4613 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
4614 if seen_modules.insert(module.def_id().unwrap()) {
4615 worklist.push((module, path_segments, is_extern));
4625 /// When name resolution fails, this method can be used to look up candidate
4626 /// entities with the expected name. It allows filtering them using the
4627 /// supplied predicate (which should be used to only accept the types of
4628 /// definitions expected e.g. traits). The lookup spans across all crates.
4630 /// NOTE: The method does not look into imports, but this is not a problem,
4631 /// since we report the definitions (thus, the de-aliased imports).
4632 fn lookup_import_candidates<FilterFn>(&mut self,
4633 lookup_ident: Ident,
4634 namespace: Namespace,
4635 filter_fn: FilterFn)
4636 -> Vec<ImportSuggestion>
4637 where FilterFn: Fn(Def) -> bool
4639 let mut suggestions = self.lookup_import_candidates_from_module(
4640 lookup_ident, namespace, self.graph_root, keywords::Crate.ident(), &filter_fn);
4642 if lookup_ident.span.rust_2018() {
4643 let extern_prelude_names = self.extern_prelude.clone();
4644 for (ident, _) in extern_prelude_names.into_iter() {
4645 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
4647 let crate_root = self.get_module(DefId {
4649 index: CRATE_DEF_INDEX,
4651 self.populate_module_if_necessary(&crate_root);
4653 suggestions.extend(self.lookup_import_candidates_from_module(
4654 lookup_ident, namespace, crate_root, ident, &filter_fn));
4662 fn find_module(&mut self,
4664 -> Option<(Module<'a>, ImportSuggestion)>
4666 let mut result = None;
4667 let mut seen_modules = FxHashSet::default();
4668 let mut worklist = vec![(self.graph_root, Vec::new())];
4670 while let Some((in_module, path_segments)) = worklist.pop() {
4671 // abort if the module is already found
4672 if result.is_some() { break; }
4674 self.populate_module_if_necessary(in_module);
4676 in_module.for_each_child_stable(|ident, _, name_binding| {
4677 // abort if the module is already found or if name_binding is private external
4678 if result.is_some() || !name_binding.vis.is_visible_locally() {
4681 if let Some(module) = name_binding.module() {
4683 let mut path_segments = path_segments.clone();
4684 path_segments.push(ast::PathSegment::from_ident(ident));
4685 if module.def() == Some(module_def) {
4687 span: name_binding.span,
4688 segments: path_segments,
4690 result = Some((module, ImportSuggestion { path }));
4692 // add the module to the lookup
4693 if seen_modules.insert(module.def_id().unwrap()) {
4694 worklist.push((module, path_segments));
4704 fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
4705 if let Def::Enum(..) = enum_def {} else {
4706 panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
4709 self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
4710 self.populate_module_if_necessary(enum_module);
4712 let mut variants = Vec::new();
4713 enum_module.for_each_child_stable(|ident, _, name_binding| {
4714 if let Def::Variant(..) = name_binding.def() {
4715 let mut segms = enum_import_suggestion.path.segments.clone();
4716 segms.push(ast::PathSegment::from_ident(ident));
4717 variants.push(Path {
4718 span: name_binding.span,
4727 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
4728 debug!("(recording def) recording {:?} for {}", resolution, node_id);
4729 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
4730 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4734 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4736 ast::VisibilityKind::Public => ty::Visibility::Public,
4737 ast::VisibilityKind::Crate(..) => {
4738 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4740 ast::VisibilityKind::Inherited => {
4741 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4743 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4744 // For visibilities we are not ready to provide correct implementation of "uniform
4745 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4746 // On 2015 edition visibilities are resolved as crate-relative by default,
4747 // so we are prepending a root segment if necessary.
4748 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4749 let crate_root = if ident.is_path_segment_keyword() {
4751 } else if ident.span.rust_2018() {
4752 let msg = "relative paths are not supported in visibilities on 2018 edition";
4753 self.session.struct_span_err(ident.span, msg)
4754 .span_suggestion(path.span, "try", format!("crate::{}", path))
4756 return ty::Visibility::Public;
4758 let ctxt = ident.span.ctxt();
4759 Some(Segment::from_ident(Ident::new(
4760 keywords::CrateRoot.name(), path.span.shrink_to_lo().with_ctxt(ctxt)
4764 let segments = crate_root.into_iter()
4765 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4766 let def = self.smart_resolve_path_fragment(
4771 PathSource::Visibility,
4772 CrateLint::SimplePath(id),
4774 if def == Def::Err {
4775 ty::Visibility::Public
4777 let vis = ty::Visibility::Restricted(def.def_id());
4778 if self.is_accessible(vis) {
4781 self.session.span_err(path.span, "visibilities can only be restricted \
4782 to ancestor modules");
4783 ty::Visibility::Public
4790 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4791 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4794 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4795 vis.is_accessible_from(module.normal_ancestor_id, self)
4798 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4799 if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4800 if !ptr::eq(module, old_module) {
4801 span_bug!(binding.span, "parent module is reset for binding");
4806 fn disambiguate_legacy_vs_modern(
4808 legacy: &'a NameBinding<'a>,
4809 modern: &'a NameBinding<'a>,
4811 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4812 // is disambiguated to mitigate regressions from macro modularization.
4813 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4814 match (self.binding_parent_modules.get(&PtrKey(legacy)),
4815 self.binding_parent_modules.get(&PtrKey(modern))) {
4816 (Some(legacy), Some(modern)) =>
4817 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4818 modern.is_ancestor_of(legacy),
4823 fn binding_description(&self, b: &NameBinding, ident: Ident, from_prelude: bool) -> String {
4824 if b.span.is_dummy() {
4825 let add_built_in = match b.def() {
4826 // These already contain the "built-in" prefix or look bad with it.
4827 Def::NonMacroAttr(..) | Def::PrimTy(..) | Def::ToolMod => false,
4830 let (built_in, from) = if from_prelude {
4831 ("", " from prelude")
4832 } else if b.is_extern_crate() && !b.is_import() &&
4833 self.session.opts.externs.get(&ident.as_str()).is_some() {
4834 ("", " passed with `--extern`")
4835 } else if add_built_in {
4841 let article = if built_in.is_empty() { b.article() } else { "a" };
4842 format!("{a}{built_in} {thing}{from}",
4843 a = article, thing = b.descr(), built_in = built_in, from = from)
4845 let introduced = if b.is_import() { "imported" } else { "defined" };
4846 format!("the {thing} {introduced} here",
4847 thing = b.descr(), introduced = introduced)
4851 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError) {
4852 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4853 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4854 // We have to print the span-less alternative first, otherwise formatting looks bad.
4855 (b2, b1, misc2, misc1, true)
4857 (b1, b2, misc1, misc2, false)
4860 let mut err = struct_span_err!(self.session, ident.span, E0659,
4861 "`{ident}` is ambiguous ({why})",
4862 ident = ident, why = kind.descr());
4863 err.span_label(ident.span, "ambiguous name");
4865 let mut could_refer_to = |b: &NameBinding, misc: AmbiguityErrorMisc, also: &str| {
4866 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4867 let note_msg = format!("`{ident}` could{also} refer to {what}",
4868 ident = ident, also = also, what = what);
4870 let mut help_msgs = Vec::new();
4871 if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4872 kind == AmbiguityKind::GlobVsExpanded ||
4873 kind == AmbiguityKind::GlobVsOuter &&
4874 swapped != also.is_empty()) {
4875 help_msgs.push(format!("consider adding an explicit import of \
4876 `{ident}` to disambiguate", ident = ident))
4878 if b.is_extern_crate() && ident.span.rust_2018() {
4879 help_msgs.push(format!(
4880 "use `::{ident}` to refer to this {thing} unambiguously",
4881 ident = ident, thing = b.descr(),
4884 if misc == AmbiguityErrorMisc::SuggestCrate {
4885 help_msgs.push(format!(
4886 "use `crate::{ident}` to refer to this {thing} unambiguously",
4887 ident = ident, thing = b.descr(),
4889 } else if misc == AmbiguityErrorMisc::SuggestSelf {
4890 help_msgs.push(format!(
4891 "use `self::{ident}` to refer to this {thing} unambiguously",
4892 ident = ident, thing = b.descr(),
4896 if b.span.is_dummy() {
4897 err.note(¬e_msg);
4899 err.span_note(b.span, ¬e_msg);
4901 for (i, help_msg) in help_msgs.iter().enumerate() {
4902 let or = if i == 0 { "" } else { "or " };
4903 err.help(&format!("{}{}", or, help_msg));
4907 could_refer_to(b1, misc1, "");
4908 could_refer_to(b2, misc2, " also");
4912 fn report_errors(&mut self, krate: &Crate) {
4913 self.report_with_use_injections(krate);
4915 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4916 let msg = "macro-expanded `macro_export` macros from the current crate \
4917 cannot be referred to by absolute paths";
4918 self.session.buffer_lint_with_diagnostic(
4919 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4920 CRATE_NODE_ID, span_use, msg,
4921 lint::builtin::BuiltinLintDiagnostics::
4922 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4926 for ambiguity_error in &self.ambiguity_errors {
4927 self.report_ambiguity_error(ambiguity_error);
4930 let mut reported_spans = FxHashSet::default();
4931 for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
4932 if reported_spans.insert(dedup_span) {
4933 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
4934 binding.descr(), ident.name);
4939 fn report_with_use_injections(&mut self, krate: &Crate) {
4940 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4941 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4942 if !candidates.is_empty() {
4943 show_candidates(&mut err, span, &candidates, better, found_use);
4949 fn report_conflict<'b>(&mut self,
4953 new_binding: &NameBinding<'b>,
4954 old_binding: &NameBinding<'b>) {
4955 // Error on the second of two conflicting names
4956 if old_binding.span.lo() > new_binding.span.lo() {
4957 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4960 let container = match parent.kind {
4961 ModuleKind::Def(Def::Mod(_), _) => "module",
4962 ModuleKind::Def(Def::Trait(_), _) => "trait",
4963 ModuleKind::Block(..) => "block",
4967 let old_noun = match old_binding.is_import() {
4969 false => "definition",
4972 let new_participle = match new_binding.is_import() {
4977 let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
4979 if let Some(s) = self.name_already_seen.get(&name) {
4985 let old_kind = match (ns, old_binding.module()) {
4986 (ValueNS, _) => "value",
4987 (MacroNS, _) => "macro",
4988 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
4989 (TypeNS, Some(module)) if module.is_normal() => "module",
4990 (TypeNS, Some(module)) if module.is_trait() => "trait",
4991 (TypeNS, _) => "type",
4994 let msg = format!("the name `{}` is defined multiple times", name);
4996 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
4997 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
4998 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
4999 true => struct_span_err!(self.session, span, E0254, "{}", msg),
5000 false => struct_span_err!(self.session, span, E0260, "{}", msg),
5002 _ => match (old_binding.is_import(), new_binding.is_import()) {
5003 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
5004 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
5005 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
5009 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
5014 err.span_label(span, format!("`{}` re{} here", name, new_participle));
5015 if !old_binding.span.is_dummy() {
5016 err.span_label(self.session.source_map().def_span(old_binding.span),
5017 format!("previous {} of the {} `{}` here", old_noun, old_kind, name));
5020 // See https://github.com/rust-lang/rust/issues/32354
5021 if old_binding.is_import() || new_binding.is_import() {
5022 let binding = if new_binding.is_import() && !new_binding.span.is_dummy() {
5028 let cm = self.session.source_map();
5029 let rename_msg = "you can use `as` to change the binding name of the import";
5033 NameBindingKind::Import { directive, ..},
5036 cm.span_to_snippet(binding.span),
5037 binding.kind.clone(),
5038 binding.span.is_dummy(),
5040 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
5041 format!("Other{}", name)
5043 format!("other_{}", name)
5046 err.span_suggestion_with_applicability(
5049 match directive.subclass {
5050 ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
5051 format!("self as {}", suggested_name),
5052 ImportDirectiveSubclass::SingleImport { source, .. } =>
5055 &snippet[..((source.span.hi().0 - binding.span.lo().0) as usize)],
5057 if snippet.ends_with(";") {
5063 ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
5065 "extern crate {} as {};",
5066 source.unwrap_or(target.name),
5069 _ => unreachable!(),
5071 Applicability::MaybeIncorrect,
5074 err.span_label(binding.span, rename_msg);
5079 self.name_already_seen.insert(name, span);
5082 fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5083 -> Option<&'a NameBinding<'a>> {
5084 if ident.is_path_segment_keyword() {
5085 // Make sure `self`, `super` etc produce an error when passed to here.
5088 self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5089 if let Some(binding) = entry.extern_crate_item {
5092 let crate_id = if !speculative {
5093 self.crate_loader.process_path_extern(ident.name, ident.span)
5094 } else if let Some(crate_id) =
5095 self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5100 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5101 self.populate_module_if_necessary(&crate_root);
5102 Some((crate_root, ty::Visibility::Public, DUMMY_SP, Mark::root())
5103 .to_name_binding(self.arenas))
5109 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5110 namespace == TypeNS && path.len() == 1 && path[0].ident.name == keywords::SelfType.name()
5113 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5114 namespace == ValueNS && path.len() == 1 && path[0].ident.name == keywords::SelfValue.name()
5117 fn names_to_string(idents: &[Ident]) -> String {
5118 let mut result = String::new();
5119 for (i, ident) in idents.iter()
5120 .filter(|ident| ident.name != keywords::CrateRoot.name())
5123 result.push_str("::");
5125 result.push_str(&ident.as_str());
5130 fn path_names_to_string(path: &Path) -> String {
5131 names_to_string(&path.segments.iter()
5132 .map(|seg| seg.ident)
5133 .collect::<Vec<_>>())
5136 /// Get the path for an enum and the variant from an `ImportSuggestion` for an enum variant.
5137 fn import_candidate_to_paths(suggestion: &ImportSuggestion) -> (Span, String, String) {
5138 let variant_path = &suggestion.path;
5139 let variant_path_string = path_names_to_string(variant_path);
5141 let path_len = suggestion.path.segments.len();
5142 let enum_path = ast::Path {
5143 span: suggestion.path.span,
5144 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
5146 let enum_path_string = path_names_to_string(&enum_path);
5148 (suggestion.path.span, variant_path_string, enum_path_string)
5152 /// When an entity with a given name is not available in scope, we search for
5153 /// entities with that name in all crates. This method allows outputting the
5154 /// results of this search in a programmer-friendly way
5155 fn show_candidates(err: &mut DiagnosticBuilder,
5156 // This is `None` if all placement locations are inside expansions
5158 candidates: &[ImportSuggestion],
5162 // we want consistent results across executions, but candidates are produced
5163 // by iterating through a hash map, so make sure they are ordered:
5164 let mut path_strings: Vec<_> =
5165 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
5166 path_strings.sort();
5168 let better = if better { "better " } else { "" };
5169 let msg_diff = match path_strings.len() {
5170 1 => " is found in another module, you can import it",
5171 _ => "s are found in other modules, you can import them",
5173 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
5175 if let Some(span) = span {
5176 for candidate in &mut path_strings {
5177 // produce an additional newline to separate the new use statement
5178 // from the directly following item.
5179 let additional_newline = if found_use {
5184 *candidate = format!("use {};\n{}", candidate, additional_newline);
5187 err.span_suggestions_with_applicability(
5190 path_strings.into_iter(),
5191 Applicability::Unspecified,
5196 for candidate in path_strings {
5198 msg.push_str(&candidate);
5203 /// A somewhat inefficient routine to obtain the name of a module.
5204 fn module_to_string(module: Module) -> Option<String> {
5205 let mut names = Vec::new();
5207 fn collect_mod(names: &mut Vec<Ident>, module: Module) {
5208 if let ModuleKind::Def(_, name) = module.kind {
5209 if let Some(parent) = module.parent {
5210 names.push(Ident::with_empty_ctxt(name));
5211 collect_mod(names, parent);
5214 // danger, shouldn't be ident?
5215 names.push(Ident::from_str("<opaque>"));
5216 collect_mod(names, module.parent.unwrap());
5219 collect_mod(&mut names, module);
5221 if names.is_empty() {
5224 Some(names_to_string(&names.into_iter()
5226 .collect::<Vec<_>>()))
5229 fn err_path_resolution() -> PathResolution {
5230 PathResolution::new(Def::Err)
5233 #[derive(PartialEq,Copy, Clone)]
5234 pub enum MakeGlobMap {
5239 #[derive(Copy, Clone, Debug)]
5241 /// Do not issue the lint
5244 /// This lint applies to some random path like `impl ::foo::Bar`
5245 /// or whatever. In this case, we can take the span of that path.
5248 /// This lint comes from a `use` statement. In this case, what we
5249 /// care about really is the *root* `use` statement; e.g., if we
5250 /// have nested things like `use a::{b, c}`, we care about the
5252 UsePath { root_id: NodeId, root_span: Span },
5254 /// This is the "trait item" from a fully qualified path. For example,
5255 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5256 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5257 QPathTrait { qpath_id: NodeId, qpath_span: Span },
5261 fn node_id(&self) -> Option<NodeId> {
5263 CrateLint::No => None,
5264 CrateLint::SimplePath(id) |
5265 CrateLint::UsePath { root_id: id, .. } |
5266 CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5271 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }