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)]
21 #![recursion_limit="256"]
24 extern crate bitflags;
29 extern crate syntax_pos;
30 extern crate rustc_errors as errors;
34 extern crate rustc_data_structures;
35 extern crate rustc_metadata;
37 pub use rustc::hir::def::{Namespace, PerNS};
39 use self::TypeParameters::*;
42 use rustc::hir::map::{Definitions, DefCollector};
43 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
44 use rustc::middle::cstore::CrateStore;
45 use rustc::session::Session;
47 use rustc::hir::def::*;
48 use rustc::hir::def::Namespace::*;
49 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
50 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
51 use rustc::session::config::nightly_options;
53 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
55 use rustc_metadata::creader::CrateLoader;
56 use rustc_metadata::cstore::CStore;
58 use syntax::source_map::SourceMap;
59 use syntax::ext::hygiene::{Mark, Transparency, SyntaxContext};
60 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
61 use syntax::ext::base::SyntaxExtension;
62 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
63 use syntax::ext::base::MacroKind;
64 use syntax::symbol::{Symbol, keywords};
65 use syntax::util::lev_distance::find_best_match_for_name;
67 use syntax::visit::{self, FnKind, Visitor};
69 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
70 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
71 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
72 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
73 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
76 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
77 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
79 use std::cell::{Cell, RefCell};
80 use std::{cmp, fmt, iter, ptr};
81 use std::collections::BTreeSet;
82 use std::mem::replace;
83 use rustc_data_structures::ptr_key::PtrKey;
84 use rustc_data_structures::sync::Lrc;
86 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
87 use macros::{InvocationData, LegacyBinding, ParentScope};
89 // N.B., this module needs to be declared first so diagnostics are
90 // registered before they are used.
95 mod build_reduced_graph;
98 fn is_known_tool(name: Name) -> bool {
99 ["clippy", "rustfmt"].contains(&&*name.as_str())
109 AbsolutePath(Namespace),
114 /// A free importable items suggested in case of resolution failure.
115 struct ImportSuggestion {
119 /// A field or associated item from self type suggested in case of resolution failure.
120 enum AssocSuggestion {
127 struct BindingError {
129 origin: BTreeSet<Span>,
130 target: BTreeSet<Span>,
133 impl PartialOrd for BindingError {
134 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
135 Some(self.cmp(other))
139 impl PartialEq for BindingError {
140 fn eq(&self, other: &BindingError) -> bool {
141 self.name == other.name
145 impl Ord for BindingError {
146 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
147 self.name.cmp(&other.name)
151 enum ResolutionError<'a> {
152 /// error E0401: can't use type parameters from outer function
153 TypeParametersFromOuterFunction(Def),
154 /// error E0403: the name is already used for a type parameter in this type parameter list
155 NameAlreadyUsedInTypeParameterList(Name, &'a Span),
156 /// error E0407: method is not a member of trait
157 MethodNotMemberOfTrait(Name, &'a str),
158 /// error E0437: type is not a member of trait
159 TypeNotMemberOfTrait(Name, &'a str),
160 /// error E0438: const is not a member of trait
161 ConstNotMemberOfTrait(Name, &'a str),
162 /// error E0408: variable `{}` is not bound in all patterns
163 VariableNotBoundInPattern(&'a BindingError),
164 /// error E0409: variable `{}` is bound in inconsistent ways within the same match arm
165 VariableBoundWithDifferentMode(Name, Span),
166 /// error E0415: identifier is bound more than once in this parameter list
167 IdentifierBoundMoreThanOnceInParameterList(&'a str),
168 /// error E0416: identifier is bound more than once in the same pattern
169 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
170 /// error E0426: use of undeclared label
171 UndeclaredLabel(&'a str, Option<Name>),
172 /// error E0429: `self` imports are only allowed within a { } list
173 SelfImportsOnlyAllowedWithin,
174 /// error E0430: `self` import can only appear once in the list
175 SelfImportCanOnlyAppearOnceInTheList,
176 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
177 SelfImportOnlyInImportListWithNonEmptyPrefix,
178 /// error E0433: failed to resolve
179 FailedToResolve(&'a str),
180 /// error E0434: can't capture dynamic environment in a fn item
181 CannotCaptureDynamicEnvironmentInFnItem,
182 /// error E0435: attempt to use a non-constant value in a constant
183 AttemptToUseNonConstantValueInConstant,
184 /// error E0530: X bindings cannot shadow Ys
185 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
186 /// error E0128: type parameters with a default cannot use forward declared identifiers
187 ForwardDeclaredTyParam,
190 /// Combines an error with provided span and emits it
192 /// This takes the error provided, combines it with the span and any additional spans inside the
193 /// error and emits it.
194 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver,
196 resolution_error: ResolutionError<'a>) {
197 resolve_struct_error(resolver, span, resolution_error).emit();
200 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
202 resolution_error: ResolutionError<'a>)
203 -> DiagnosticBuilder<'sess> {
204 match resolution_error {
205 ResolutionError::TypeParametersFromOuterFunction(outer_def) => {
206 let mut err = struct_span_err!(resolver.session,
209 "can't use type parameters from outer function");
210 err.span_label(span, "use of type variable from outer function");
212 let cm = resolver.session.source_map();
214 Def::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
215 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
216 resolver.definitions.opt_span(def_id)
219 reduce_impl_span_to_impl_keyword(cm, impl_span),
220 "`Self` type implicitly declared here, by this `impl`",
223 match (maybe_trait_defid, maybe_impl_defid) {
225 err.span_label(span, "can't use `Self` here");
228 err.span_label(span, "use a type here instead");
230 (None, None) => bug!("`impl` without trait nor type?"),
234 Def::TyParam(typaram_defid) => {
235 if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) {
236 err.span_label(typaram_span, "type variable from outer function");
240 bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \
245 // Try to retrieve the span of the function signature and generate a new message with
246 // a local type parameter
247 let sugg_msg = "try using a local type parameter instead";
248 if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
249 // Suggest the modification to the user
250 err.span_suggestion_with_applicability(
254 Applicability::MachineApplicable,
256 } else if let Some(sp) = cm.generate_fn_name_span(span) {
257 err.span_label(sp, "try adding a local type parameter in this method instead");
259 err.help("try using a local type parameter instead");
264 ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
265 let mut err = struct_span_err!(resolver.session,
268 "the name `{}` is already used for a type parameter \
269 in this type parameter list",
271 err.span_label(span, "already used");
272 err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
275 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
276 let mut err = struct_span_err!(resolver.session,
279 "method `{}` is not a member of trait `{}`",
282 err.span_label(span, format!("not a member of trait `{}`", trait_));
285 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
286 let mut err = struct_span_err!(resolver.session,
289 "type `{}` is not a member of trait `{}`",
292 err.span_label(span, format!("not a member of trait `{}`", trait_));
295 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
296 let mut err = struct_span_err!(resolver.session,
299 "const `{}` is not a member of trait `{}`",
302 err.span_label(span, format!("not a member of trait `{}`", trait_));
305 ResolutionError::VariableNotBoundInPattern(binding_error) => {
306 let target_sp = binding_error.target.iter().cloned().collect::<Vec<_>>();
307 let msp = MultiSpan::from_spans(target_sp.clone());
308 let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
309 let mut err = resolver.session.struct_span_err_with_code(
312 DiagnosticId::Error("E0408".into()),
314 for sp in target_sp {
315 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
317 let origin_sp = binding_error.origin.iter().cloned();
318 for sp in origin_sp {
319 err.span_label(sp, "variable not in all patterns");
323 ResolutionError::VariableBoundWithDifferentMode(variable_name,
324 first_binding_span) => {
325 let mut err = struct_span_err!(resolver.session,
328 "variable `{}` is bound in inconsistent \
329 ways within the same match arm",
331 err.span_label(span, "bound in different ways");
332 err.span_label(first_binding_span, "first binding");
335 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
336 let mut err = struct_span_err!(resolver.session,
339 "identifier `{}` is bound more than once in this parameter list",
341 err.span_label(span, "used as parameter more than once");
344 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
345 let mut err = struct_span_err!(resolver.session,
348 "identifier `{}` is bound more than once in the same pattern",
350 err.span_label(span, "used in a pattern more than once");
353 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
354 let mut err = struct_span_err!(resolver.session,
357 "use of undeclared label `{}`",
359 if let Some(lev_candidate) = lev_candidate {
360 err.span_label(span, format!("did you mean `{}`?", lev_candidate));
362 err.span_label(span, format!("undeclared label `{}`", name));
366 ResolutionError::SelfImportsOnlyAllowedWithin => {
367 struct_span_err!(resolver.session,
371 "`self` imports are only allowed within a { } list")
373 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
374 let mut err = struct_span_err!(resolver.session, span, E0430,
375 "`self` import can only appear once in an import list");
376 err.span_label(span, "can only appear once in an import list");
379 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
380 let mut err = struct_span_err!(resolver.session, span, E0431,
381 "`self` import can only appear in an import list with \
382 a non-empty prefix");
383 err.span_label(span, "can only appear in an import list with a non-empty prefix");
386 ResolutionError::FailedToResolve(msg) => {
387 let mut err = struct_span_err!(resolver.session, span, E0433,
388 "failed to resolve: {}", msg);
389 err.span_label(span, msg);
392 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
393 let mut err = struct_span_err!(resolver.session,
397 "can't capture dynamic environment in a fn item");
398 err.help("use the `|| { ... }` closure form instead");
401 ResolutionError::AttemptToUseNonConstantValueInConstant => {
402 let mut err = struct_span_err!(resolver.session, span, E0435,
403 "attempt to use a non-constant value in a constant");
404 err.span_label(span, "non-constant value");
407 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
408 let shadows_what = binding.descr();
409 let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
410 what_binding, shadows_what);
411 err.span_label(span, format!("cannot be named the same as {} {}",
412 binding.article(), shadows_what));
413 let participle = if binding.is_import() { "imported" } else { "defined" };
414 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
415 err.span_label(binding.span, msg);
418 ResolutionError::ForwardDeclaredTyParam => {
419 let mut err = struct_span_err!(resolver.session, span, E0128,
420 "type parameters with a default cannot use \
421 forward declared identifiers");
423 span, "defaulted type parameters cannot be forward declared".to_string());
429 /// Adjust the impl span so that just the `impl` keyword is taken by removing
430 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
431 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`)
433 /// Attention: The method used is very fragile since it essentially duplicates the work of the
434 /// parser. If you need to use this function or something similar, please consider updating the
435 /// source_map functions and this function to something more robust.
436 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
437 let impl_span = cm.span_until_char(impl_span, '<');
438 let impl_span = cm.span_until_whitespace(impl_span);
442 #[derive(Copy, Clone, Debug)]
445 binding_mode: BindingMode,
448 /// Map from the name in a pattern to its binding mode.
449 type BindingMap = FxHashMap<Ident, BindingInfo>;
451 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
462 fn descr(self) -> &'static str {
464 PatternSource::Match => "match binding",
465 PatternSource::IfLet => "if let binding",
466 PatternSource::WhileLet => "while let binding",
467 PatternSource::Let => "let binding",
468 PatternSource::For => "for binding",
469 PatternSource::FnParam => "function parameter",
474 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
475 enum AliasPossibility {
480 #[derive(Copy, Clone, Debug)]
481 enum PathSource<'a> {
482 // Type paths `Path`.
484 // Trait paths in bounds or impls.
485 Trait(AliasPossibility),
486 // Expression paths `path`, with optional parent context.
487 Expr(Option<&'a Expr>),
488 // Paths in path patterns `Path`.
490 // Paths in struct expressions and patterns `Path { .. }`.
492 // Paths in tuple struct patterns `Path(..)`.
494 // `m::A::B` in `<T as m::A>::B::C`.
495 TraitItem(Namespace),
496 // Path in `pub(path)`
500 impl<'a> PathSource<'a> {
501 fn namespace(self) -> Namespace {
503 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
504 PathSource::Visibility => TypeNS,
505 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
506 PathSource::TraitItem(ns) => ns,
510 fn global_by_default(self) -> bool {
512 PathSource::Visibility => true,
513 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
514 PathSource::Struct | PathSource::TupleStruct |
515 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
519 fn defer_to_typeck(self) -> bool {
521 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
522 PathSource::Struct | PathSource::TupleStruct => true,
523 PathSource::Trait(_) | PathSource::TraitItem(..) |
524 PathSource::Visibility => false,
528 fn descr_expected(self) -> &'static str {
530 PathSource::Type => "type",
531 PathSource::Trait(_) => "trait",
532 PathSource::Pat => "unit struct/variant or constant",
533 PathSource::Struct => "struct, variant or union type",
534 PathSource::TupleStruct => "tuple struct/variant",
535 PathSource::Visibility => "module",
536 PathSource::TraitItem(ns) => match ns {
537 TypeNS => "associated type",
538 ValueNS => "method or associated constant",
539 MacroNS => bug!("associated macro"),
541 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
542 // "function" here means "anything callable" rather than `Def::Fn`,
543 // this is not precise but usually more helpful than just "value".
544 Some(&ExprKind::Call(..)) => "function",
550 fn is_expected(self, def: Def) -> bool {
552 PathSource::Type => match def {
553 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
554 Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) |
555 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) |
556 Def::SelfTy(..) | Def::Existential(..) |
557 Def::ForeignTy(..) => true,
560 PathSource::Trait(AliasPossibility::No) => match def {
561 Def::Trait(..) => true,
564 PathSource::Trait(AliasPossibility::Maybe) => match def {
565 Def::Trait(..) => true,
566 Def::TraitAlias(..) => true,
569 PathSource::Expr(..) => match def {
570 Def::StructCtor(_, CtorKind::Const) | Def::StructCtor(_, CtorKind::Fn) |
571 Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) |
572 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
573 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) |
574 Def::SelfCtor(..) => true,
577 PathSource::Pat => match def {
578 Def::StructCtor(_, CtorKind::Const) |
579 Def::VariantCtor(_, CtorKind::Const) |
580 Def::Const(..) | Def::AssociatedConst(..) |
581 Def::SelfCtor(..) => true,
584 PathSource::TupleStruct => match def {
585 Def::StructCtor(_, CtorKind::Fn) |
586 Def::VariantCtor(_, CtorKind::Fn) |
587 Def::SelfCtor(..) => true,
590 PathSource::Struct => match def {
591 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
592 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
595 PathSource::TraitItem(ns) => match def {
596 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
597 Def::AssociatedTy(..) if ns == TypeNS => true,
600 PathSource::Visibility => match def {
601 Def::Mod(..) => true,
607 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
608 __diagnostic_used!(E0404);
609 __diagnostic_used!(E0405);
610 __diagnostic_used!(E0412);
611 __diagnostic_used!(E0422);
612 __diagnostic_used!(E0423);
613 __diagnostic_used!(E0425);
614 __diagnostic_used!(E0531);
615 __diagnostic_used!(E0532);
616 __diagnostic_used!(E0573);
617 __diagnostic_used!(E0574);
618 __diagnostic_used!(E0575);
619 __diagnostic_used!(E0576);
620 __diagnostic_used!(E0577);
621 __diagnostic_used!(E0578);
622 match (self, has_unexpected_resolution) {
623 (PathSource::Trait(_), true) => "E0404",
624 (PathSource::Trait(_), false) => "E0405",
625 (PathSource::Type, true) => "E0573",
626 (PathSource::Type, false) => "E0412",
627 (PathSource::Struct, true) => "E0574",
628 (PathSource::Struct, false) => "E0422",
629 (PathSource::Expr(..), true) => "E0423",
630 (PathSource::Expr(..), false) => "E0425",
631 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
632 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
633 (PathSource::TraitItem(..), true) => "E0575",
634 (PathSource::TraitItem(..), false) => "E0576",
635 (PathSource::Visibility, true) => "E0577",
636 (PathSource::Visibility, false) => "E0578",
641 // A minimal representation of a path segment. We use this in resolve because
642 // we synthesize 'path segments' which don't have the rest of an AST or HIR
644 #[derive(Clone, Copy, Debug)]
651 fn from_path(path: &Path) -> Vec<Segment> {
652 path.segments.iter().map(|s| s.into()).collect()
655 fn from_ident(ident: Ident) -> Segment {
662 fn names_to_string(segments: &[Segment]) -> String {
663 names_to_string(&segments.iter()
664 .map(|seg| seg.ident)
665 .collect::<Vec<_>>())
669 impl<'a> From<&'a ast::PathSegment> for Segment {
670 fn from(seg: &'a ast::PathSegment) -> Segment {
678 struct UsePlacementFinder {
679 target_module: NodeId,
684 impl UsePlacementFinder {
685 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
686 let mut finder = UsePlacementFinder {
691 visit::walk_crate(&mut finder, krate);
692 (finder.span, finder.found_use)
696 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
699 module: &'tcx ast::Mod,
701 _: &[ast::Attribute],
704 if self.span.is_some() {
707 if node_id != self.target_module {
708 visit::walk_mod(self, module);
711 // find a use statement
712 for item in &module.items {
714 ItemKind::Use(..) => {
715 // don't suggest placing a use before the prelude
716 // import or other generated ones
717 if item.span.ctxt().outer().expn_info().is_none() {
718 self.span = Some(item.span.shrink_to_lo());
719 self.found_use = true;
723 // don't place use before extern crate
724 ItemKind::ExternCrate(_) => {}
725 // but place them before the first other item
726 _ => if self.span.map_or(true, |span| item.span < span ) {
727 if item.span.ctxt().outer().expn_info().is_none() {
728 // don't insert between attributes and an item
729 if item.attrs.is_empty() {
730 self.span = Some(item.span.shrink_to_lo());
732 // find the first attribute on the item
733 for attr in &item.attrs {
734 if self.span.map_or(true, |span| attr.span < span) {
735 self.span = Some(attr.span.shrink_to_lo());
746 /// This thing walks the whole crate in DFS manner, visiting each item, resolving names as it goes.
747 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
748 fn visit_item(&mut self, item: &'tcx Item) {
749 self.resolve_item(item);
751 fn visit_arm(&mut self, arm: &'tcx Arm) {
752 self.resolve_arm(arm);
754 fn visit_block(&mut self, block: &'tcx Block) {
755 self.resolve_block(block);
757 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
758 self.with_constant_rib(|this| {
759 visit::walk_anon_const(this, constant);
762 fn visit_expr(&mut self, expr: &'tcx Expr) {
763 self.resolve_expr(expr, None);
765 fn visit_local(&mut self, local: &'tcx Local) {
766 self.resolve_local(local);
768 fn visit_ty(&mut self, ty: &'tcx Ty) {
770 TyKind::Path(ref qself, ref path) => {
771 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
773 TyKind::ImplicitSelf => {
774 let self_ty = keywords::SelfUpper.ident();
775 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
776 .map_or(Def::Err, |d| d.def());
777 self.record_def(ty.id, PathResolution::new(def));
781 visit::walk_ty(self, ty);
783 fn visit_poly_trait_ref(&mut self,
784 tref: &'tcx ast::PolyTraitRef,
785 m: &'tcx ast::TraitBoundModifier) {
786 self.smart_resolve_path(tref.trait_ref.ref_id, None,
787 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
788 visit::walk_poly_trait_ref(self, tref, m);
790 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
791 let type_parameters = match foreign_item.node {
792 ForeignItemKind::Fn(_, ref generics) => {
793 HasTypeParameters(generics, ItemRibKind)
795 ForeignItemKind::Static(..) => NoTypeParameters,
796 ForeignItemKind::Ty => NoTypeParameters,
797 ForeignItemKind::Macro(..) => NoTypeParameters,
799 self.with_type_parameter_rib(type_parameters, |this| {
800 visit::walk_foreign_item(this, foreign_item);
803 fn visit_fn(&mut self,
804 function_kind: FnKind<'tcx>,
805 declaration: &'tcx FnDecl,
809 let (rib_kind, asyncness) = match function_kind {
810 FnKind::ItemFn(_, ref header, ..) =>
811 (ItemRibKind, header.asyncness),
812 FnKind::Method(_, ref sig, _, _) =>
813 (TraitOrImplItemRibKind, sig.header.asyncness),
814 FnKind::Closure(_) =>
815 // Async closures aren't resolved through `visit_fn`-- they're
816 // processed separately
817 (ClosureRibKind(node_id), IsAsync::NotAsync),
820 // Create a value rib for the function.
821 self.ribs[ValueNS].push(Rib::new(rib_kind));
823 // Create a label rib for the function.
824 self.label_ribs.push(Rib::new(rib_kind));
826 // Add each argument to the rib.
827 let mut bindings_list = FxHashMap::default();
828 for argument in &declaration.inputs {
829 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
831 self.visit_ty(&argument.ty);
833 debug!("(resolving function) recorded argument");
835 visit::walk_fn_ret_ty(self, &declaration.output);
837 // Resolve the function body, potentially inside the body of an async closure
838 if let IsAsync::Async { closure_id, .. } = asyncness {
839 let rib_kind = ClosureRibKind(closure_id);
840 self.ribs[ValueNS].push(Rib::new(rib_kind));
841 self.label_ribs.push(Rib::new(rib_kind));
844 match function_kind {
845 FnKind::ItemFn(.., body) |
846 FnKind::Method(.., body) => {
847 self.visit_block(body);
849 FnKind::Closure(body) => {
850 self.visit_expr(body);
854 // Leave the body of the async closure
855 if asyncness.is_async() {
856 self.label_ribs.pop();
857 self.ribs[ValueNS].pop();
860 debug!("(resolving function) leaving function");
862 self.label_ribs.pop();
863 self.ribs[ValueNS].pop();
865 fn visit_generics(&mut self, generics: &'tcx Generics) {
866 // For type parameter defaults, we have to ban access
867 // to following type parameters, as the Substs can only
868 // provide previous type parameters as they're built. We
869 // put all the parameters on the ban list and then remove
870 // them one by one as they are processed and become available.
871 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
872 let mut found_default = false;
873 default_ban_rib.bindings.extend(generics.params.iter()
874 .filter_map(|param| match param.kind {
875 GenericParamKind::Lifetime { .. } => None,
876 GenericParamKind::Type { ref default, .. } => {
877 found_default |= default.is_some();
879 Some((Ident::with_empty_ctxt(param.ident.name), Def::Err))
886 for param in &generics.params {
888 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
889 GenericParamKind::Type { ref default, .. } => {
890 for bound in ¶m.bounds {
891 self.visit_param_bound(bound);
894 if let Some(ref ty) = default {
895 self.ribs[TypeNS].push(default_ban_rib);
897 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
900 // Allow all following defaults to refer to this type parameter.
901 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
905 for p in &generics.where_clause.predicates {
906 self.visit_where_predicate(p);
911 #[derive(Copy, Clone)]
912 enum TypeParameters<'a, 'b> {
914 HasTypeParameters(// Type parameters.
917 // The kind of the rib used for type parameters.
921 /// The rib kind controls the translation of local
922 /// definitions (`Def::Local`) to upvars (`Def::Upvar`).
923 #[derive(Copy, Clone, Debug)]
925 /// No translation needs to be applied.
928 /// We passed through a closure scope at the given node ID.
929 /// Translate upvars as appropriate.
930 ClosureRibKind(NodeId /* func id */),
932 /// We passed through an impl or trait and are now in one of its
933 /// methods or associated types. Allow references to ty params that impl or trait
934 /// binds. Disallow any other upvars (including other ty params that are
936 TraitOrImplItemRibKind,
938 /// We passed through an item scope. Disallow upvars.
941 /// We're in a constant item. Can't refer to dynamic stuff.
944 /// We passed through a module.
945 ModuleRibKind(Module<'a>),
947 /// We passed through a `macro_rules!` statement
948 MacroDefinition(DefId),
950 /// All bindings in this rib are type parameters that can't be used
951 /// from the default of a type parameter because they're not declared
952 /// before said type parameter. Also see the `visit_generics` override.
953 ForwardTyParamBanRibKind,
958 /// A rib represents a scope names can live in. Note that these appear in many places, not just
959 /// around braces. At any place where the list of accessible names (of the given namespace)
960 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
961 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
964 /// Different [rib kinds](enum.RibKind) are transparent for different names.
966 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
967 /// resolving, the name is looked up from inside out.
970 bindings: FxHashMap<Ident, Def>,
975 fn new(kind: RibKind<'a>) -> Rib<'a> {
977 bindings: Default::default(),
983 /// An intermediate resolution result.
985 /// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
986 /// items are visible in their whole block, while defs only from the place they are defined
988 enum LexicalScopeBinding<'a> {
989 Item(&'a NameBinding<'a>),
993 impl<'a> LexicalScopeBinding<'a> {
994 fn item(self) -> Option<&'a NameBinding<'a>> {
996 LexicalScopeBinding::Item(binding) => Some(binding),
1001 fn def(self) -> Def {
1003 LexicalScopeBinding::Item(binding) => binding.def(),
1004 LexicalScopeBinding::Def(def) => def,
1009 #[derive(Copy, Clone, Debug)]
1010 enum ModuleOrUniformRoot<'a> {
1014 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1015 CrateRootAndExternPrelude,
1017 /// Virtual module that denotes resolution in extern prelude.
1018 /// Used for paths starting with `::` on 2018 edition or `extern::`.
1021 /// Virtual module that denotes resolution in current scope.
1022 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1023 /// are always split into two parts, the first of which should be some kind of module.
1027 impl<'a> PartialEq for ModuleOrUniformRoot<'a> {
1028 fn eq(&self, other: &Self) -> bool {
1029 match (*self, *other) {
1030 (ModuleOrUniformRoot::Module(lhs),
1031 ModuleOrUniformRoot::Module(rhs)) => ptr::eq(lhs, rhs),
1032 (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1033 ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1034 (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1035 (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1041 #[derive(Clone, Debug)]
1042 enum PathResult<'a> {
1043 Module(ModuleOrUniformRoot<'a>),
1044 NonModule(PathResolution),
1046 Failed(Span, String, bool /* is the error from the last segment? */),
1050 /// An anonymous module, eg. just a block.
1054 /// fn f() {} // (1)
1055 /// { // This is an anonymous module
1056 /// f(); // This resolves to (2) as we are inside the block.
1057 /// fn f() {} // (2)
1059 /// f(); // Resolves to (1)
1063 /// Any module with a name.
1067 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1068 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1073 /// One node in the tree of modules.
1074 pub struct ModuleData<'a> {
1075 parent: Option<Module<'a>>,
1078 // The def id of the closest normal module (`mod`) ancestor (including this module).
1079 normal_ancestor_id: DefId,
1081 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1082 single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1083 Option<&'a NameBinding<'a>>)>>,
1084 multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1086 builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1088 // Macro invocations that can expand into items in this module.
1089 unresolved_invocations: RefCell<FxHashSet<Mark>>,
1091 no_implicit_prelude: bool,
1093 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1094 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1096 // Used to memoize the traits in this module for faster searches through all traits in scope.
1097 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1099 // Whether this module is populated. If not populated, any attempt to
1100 // access the children must be preceded with a
1101 // `populate_module_if_necessary` call.
1102 populated: Cell<bool>,
1104 /// Span of the module itself. Used for error reporting.
1110 type Module<'a> = &'a ModuleData<'a>;
1112 impl<'a> ModuleData<'a> {
1113 fn new(parent: Option<Module<'a>>,
1115 normal_ancestor_id: DefId,
1117 span: Span) -> Self {
1122 resolutions: Default::default(),
1123 single_segment_macro_resolutions: RefCell::new(Vec::new()),
1124 multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1125 builtin_attrs: RefCell::new(Vec::new()),
1126 unresolved_invocations: Default::default(),
1127 no_implicit_prelude: false,
1128 glob_importers: RefCell::new(Vec::new()),
1129 globs: RefCell::new(Vec::new()),
1130 traits: RefCell::new(None),
1131 populated: Cell::new(normal_ancestor_id.is_local()),
1137 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1138 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1139 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1143 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1144 let resolutions = self.resolutions.borrow();
1145 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1146 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1147 for &(&(ident, ns), &resolution) in resolutions.iter() {
1148 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1152 fn def(&self) -> Option<Def> {
1154 ModuleKind::Def(def, _) => Some(def),
1159 fn def_id(&self) -> Option<DefId> {
1160 self.def().as_ref().map(Def::def_id)
1163 // `self` resolves to the first module ancestor that `is_normal`.
1164 fn is_normal(&self) -> bool {
1166 ModuleKind::Def(Def::Mod(_), _) => true,
1171 fn is_trait(&self) -> bool {
1173 ModuleKind::Def(Def::Trait(_), _) => true,
1178 fn nearest_item_scope(&'a self) -> Module<'a> {
1179 if self.is_trait() { self.parent.unwrap() } else { self }
1182 fn is_ancestor_of(&self, mut other: &Self) -> bool {
1183 while !ptr::eq(self, other) {
1184 if let Some(parent) = other.parent {
1194 impl<'a> fmt::Debug for ModuleData<'a> {
1195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1196 write!(f, "{:?}", self.def())
1200 /// Records a possibly-private value, type, or module definition.
1201 #[derive(Clone, Debug)]
1202 pub struct NameBinding<'a> {
1203 kind: NameBindingKind<'a>,
1206 vis: ty::Visibility,
1209 pub trait ToNameBinding<'a> {
1210 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1213 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1214 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1219 #[derive(Clone, Debug)]
1220 enum NameBindingKind<'a> {
1221 Def(Def, /* is_macro_export */ bool),
1224 binding: &'a NameBinding<'a>,
1225 directive: &'a ImportDirective<'a>,
1229 kind: AmbiguityKind,
1230 b1: &'a NameBinding<'a>,
1231 b2: &'a NameBinding<'a>,
1235 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1237 struct UseError<'a> {
1238 err: DiagnosticBuilder<'a>,
1239 /// Attach `use` statements for these candidates
1240 candidates: Vec<ImportSuggestion>,
1241 /// The node id of the module to place the use statements in
1243 /// Whether the diagnostic should state that it's "better"
1247 #[derive(Clone, Copy, PartialEq, Debug)]
1248 enum AmbiguityKind {
1253 LegacyHelperVsPrelude,
1258 MoreExpandedVsOuter,
1261 impl AmbiguityKind {
1262 fn descr(self) -> &'static str {
1264 AmbiguityKind::Import =>
1265 "name vs any other name during import resolution",
1266 AmbiguityKind::AbsolutePath =>
1267 "name in the crate root vs extern crate during absolute path resolution",
1268 AmbiguityKind::BuiltinAttr =>
1269 "built-in attribute vs any other name",
1270 AmbiguityKind::DeriveHelper =>
1271 "derive helper attribute vs any other name",
1272 AmbiguityKind::LegacyHelperVsPrelude =>
1273 "legacy plugin helper attribute vs name from prelude",
1274 AmbiguityKind::LegacyVsModern =>
1275 "`macro_rules` vs non-`macro_rules` from other module",
1276 AmbiguityKind::GlobVsOuter =>
1277 "glob import vs any other name from outer scope during import/macro resolution",
1278 AmbiguityKind::GlobVsGlob =>
1279 "glob import vs glob import in the same module",
1280 AmbiguityKind::GlobVsExpanded =>
1281 "glob import vs macro-expanded name in the same \
1282 module during import/macro resolution",
1283 AmbiguityKind::MoreExpandedVsOuter =>
1284 "macro-expanded name vs less macro-expanded name \
1285 from outer scope during import/macro resolution",
1290 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1291 #[derive(Clone, Copy, PartialEq)]
1292 enum AmbiguityErrorMisc {
1299 struct AmbiguityError<'a> {
1300 kind: AmbiguityKind,
1302 b1: &'a NameBinding<'a>,
1303 b2: &'a NameBinding<'a>,
1304 misc1: AmbiguityErrorMisc,
1305 misc2: AmbiguityErrorMisc,
1308 impl<'a> NameBinding<'a> {
1309 fn module(&self) -> Option<Module<'a>> {
1311 NameBindingKind::Module(module) => Some(module),
1312 NameBindingKind::Import { binding, .. } => binding.module(),
1317 fn def(&self) -> Def {
1319 NameBindingKind::Def(def, _) => def,
1320 NameBindingKind::Module(module) => module.def().unwrap(),
1321 NameBindingKind::Import { binding, .. } => binding.def(),
1322 NameBindingKind::Ambiguity { .. } => Def::Err,
1326 fn def_ignoring_ambiguity(&self) -> Def {
1328 NameBindingKind::Import { binding, .. } => binding.def_ignoring_ambiguity(),
1329 NameBindingKind::Ambiguity { b1, .. } => b1.def_ignoring_ambiguity(),
1334 // We sometimes need to treat variants as `pub` for backwards compatibility
1335 fn pseudo_vis(&self) -> ty::Visibility {
1336 if self.is_variant() && self.def().def_id().is_local() {
1337 ty::Visibility::Public
1343 fn is_variant(&self) -> bool {
1345 NameBindingKind::Def(Def::Variant(..), _) |
1346 NameBindingKind::Def(Def::VariantCtor(..), _) => true,
1351 fn is_extern_crate(&self) -> bool {
1353 NameBindingKind::Import {
1354 directive: &ImportDirective {
1355 subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1358 NameBindingKind::Module(
1359 &ModuleData { kind: ModuleKind::Def(Def::Mod(def_id), _), .. }
1360 ) => def_id.index == CRATE_DEF_INDEX,
1365 fn is_import(&self) -> bool {
1367 NameBindingKind::Import { .. } => true,
1372 fn is_glob_import(&self) -> bool {
1374 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1375 NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
1380 fn is_importable(&self) -> bool {
1382 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1387 fn is_macro_def(&self) -> bool {
1389 NameBindingKind::Def(Def::Macro(..), _) => true,
1394 fn macro_kind(&self) -> Option<MacroKind> {
1395 match self.def_ignoring_ambiguity() {
1396 Def::Macro(_, kind) => Some(kind),
1397 Def::NonMacroAttr(..) => Some(MacroKind::Attr),
1402 fn descr(&self) -> &'static str {
1403 if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1406 fn article(&self) -> &'static str {
1407 if self.is_extern_crate() { "an" } else { self.def().article() }
1410 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1411 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1412 // Then this function returns `true` if `self` may emerge from a macro *after* that
1413 // in some later round and screw up our previously found resolution.
1414 // See more detailed explanation in
1415 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1416 fn may_appear_after(&self, invoc_parent_expansion: Mark, binding: &NameBinding) -> bool {
1417 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1418 // Expansions are partially ordered, so "may appear after" is an inversion of
1419 // "certainly appears before or simultaneously" and includes unordered cases.
1420 let self_parent_expansion = self.expansion;
1421 let other_parent_expansion = binding.expansion;
1422 let certainly_before_other_or_simultaneously =
1423 other_parent_expansion.is_descendant_of(self_parent_expansion);
1424 let certainly_before_invoc_or_simultaneously =
1425 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1426 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1430 /// Interns the names of the primitive types.
1432 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1433 /// special handling, since they have no place of origin.
1435 struct PrimitiveTypeTable {
1436 primitive_types: FxHashMap<Name, PrimTy>,
1439 impl PrimitiveTypeTable {
1440 fn new() -> PrimitiveTypeTable {
1441 let mut table = PrimitiveTypeTable::default();
1443 table.intern("bool", Bool);
1444 table.intern("char", Char);
1445 table.intern("f32", Float(FloatTy::F32));
1446 table.intern("f64", Float(FloatTy::F64));
1447 table.intern("isize", Int(IntTy::Isize));
1448 table.intern("i8", Int(IntTy::I8));
1449 table.intern("i16", Int(IntTy::I16));
1450 table.intern("i32", Int(IntTy::I32));
1451 table.intern("i64", Int(IntTy::I64));
1452 table.intern("i128", Int(IntTy::I128));
1453 table.intern("str", Str);
1454 table.intern("usize", Uint(UintTy::Usize));
1455 table.intern("u8", Uint(UintTy::U8));
1456 table.intern("u16", Uint(UintTy::U16));
1457 table.intern("u32", Uint(UintTy::U32));
1458 table.intern("u64", Uint(UintTy::U64));
1459 table.intern("u128", Uint(UintTy::U128));
1463 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1464 self.primitive_types.insert(Symbol::intern(string), primitive_type);
1468 #[derive(Default, Clone)]
1469 pub struct ExternPreludeEntry<'a> {
1470 extern_crate_item: Option<&'a NameBinding<'a>>,
1471 pub introduced_by_item: bool,
1474 /// The main resolver class.
1476 /// This is the visitor that walks the whole crate.
1477 pub struct Resolver<'a> {
1478 session: &'a Session,
1481 pub definitions: Definitions,
1483 graph_root: Module<'a>,
1485 prelude: Option<Module<'a>>,
1486 pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1488 /// n.b. This is used only for better diagnostics, not name resolution itself.
1489 has_self: FxHashSet<DefId>,
1491 /// Names of fields of an item `DefId` accessible with dot syntax.
1492 /// Used for hints during error reporting.
1493 field_names: FxHashMap<DefId, Vec<Name>>,
1495 /// All imports known to succeed or fail.
1496 determined_imports: Vec<&'a ImportDirective<'a>>,
1498 /// All non-determined imports.
1499 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1501 /// The module that represents the current item scope.
1502 current_module: Module<'a>,
1504 /// The current set of local scopes for types and values.
1505 /// FIXME #4948: Reuse ribs to avoid allocation.
1506 ribs: PerNS<Vec<Rib<'a>>>,
1508 /// The current set of local scopes, for labels.
1509 label_ribs: Vec<Rib<'a>>,
1511 /// The trait that the current context can refer to.
1512 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1514 /// The current self type if inside an impl (used for better errors).
1515 current_self_type: Option<Ty>,
1517 /// The current self item if inside an ADT (used for better errors).
1518 current_self_item: Option<NodeId>,
1520 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1521 /// We are resolving a last import segment during import validation.
1522 last_import_segment: bool,
1523 /// This binding should be ignored during in-module resolution, so that we don't get
1524 /// "self-confirming" import resolutions during import validation.
1525 blacklisted_binding: Option<&'a NameBinding<'a>>,
1527 /// The idents for the primitive types.
1528 primitive_type_table: PrimitiveTypeTable,
1531 import_map: ImportMap,
1532 pub freevars: FreevarMap,
1533 freevars_seen: NodeMap<NodeMap<usize>>,
1534 pub export_map: ExportMap,
1535 pub trait_map: TraitMap,
1537 /// A map from nodes to anonymous modules.
1538 /// Anonymous modules are pseudo-modules that are implicitly created around items
1539 /// contained within blocks.
1541 /// For example, if we have this:
1549 /// There will be an anonymous module created around `g` with the ID of the
1550 /// entry block for `f`.
1551 block_map: NodeMap<Module<'a>>,
1552 module_map: FxHashMap<DefId, Module<'a>>,
1553 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1554 binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1556 pub make_glob_map: bool,
1557 /// Maps imports to the names of items actually imported (this actually maps
1558 /// all imports, but only glob imports are actually interesting).
1559 pub glob_map: GlobMap,
1561 used_imports: FxHashSet<(NodeId, Namespace)>,
1562 pub maybe_unused_trait_imports: NodeSet,
1563 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1565 /// A list of labels as of yet unused. Labels will be removed from this map when
1566 /// they are used (in a `break` or `continue` statement)
1567 pub unused_labels: FxHashMap<NodeId, Span>,
1569 /// privacy errors are delayed until the end in order to deduplicate them
1570 privacy_errors: Vec<PrivacyError<'a>>,
1571 /// ambiguity errors are delayed for deduplication
1572 ambiguity_errors: Vec<AmbiguityError<'a>>,
1573 /// `use` injections are delayed for better placement and deduplication
1574 use_injections: Vec<UseError<'a>>,
1575 /// crate-local macro expanded `macro_export` referred to by a module-relative path
1576 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1578 arenas: &'a ResolverArenas<'a>,
1579 dummy_binding: &'a NameBinding<'a>,
1581 crate_loader: &'a mut CrateLoader<'a>,
1582 macro_names: FxHashSet<Ident>,
1583 builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1584 macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1585 pub all_macros: FxHashMap<Name, Def>,
1586 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1587 macro_defs: FxHashMap<Mark, DefId>,
1588 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1589 pub found_unresolved_macro: bool,
1591 /// List of crate local macros that we need to warn about as being unused.
1592 /// Right now this only includes macro_rules! macros, and macros 2.0.
1593 unused_macros: FxHashSet<DefId>,
1595 /// Maps the `Mark` of an expansion to its containing module or block.
1596 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1598 /// Avoid duplicated errors for "name already defined".
1599 name_already_seen: FxHashMap<Name, Span>,
1601 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1603 /// This table maps struct IDs into struct constructor IDs,
1604 /// it's not used during normal resolution, only for better error reporting.
1605 struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1607 /// Only used for better errors on `fn(): fn()`
1608 current_type_ascription: Vec<Span>,
1610 injected_crate: Option<Module<'a>>,
1613 /// Nothing really interesting here, it just provides memory for the rest of the crate.
1615 pub struct ResolverArenas<'a> {
1616 modules: arena::TypedArena<ModuleData<'a>>,
1617 local_modules: RefCell<Vec<Module<'a>>>,
1618 name_bindings: arena::TypedArena<NameBinding<'a>>,
1619 import_directives: arena::TypedArena<ImportDirective<'a>>,
1620 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1621 invocation_data: arena::TypedArena<InvocationData<'a>>,
1622 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1625 impl<'a> ResolverArenas<'a> {
1626 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1627 let module = self.modules.alloc(module);
1628 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1629 self.local_modules.borrow_mut().push(module);
1633 fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1634 self.local_modules.borrow()
1636 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1637 self.name_bindings.alloc(name_binding)
1639 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1640 -> &'a ImportDirective {
1641 self.import_directives.alloc(import_directive)
1643 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1644 self.name_resolutions.alloc(Default::default())
1646 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1647 -> &'a InvocationData<'a> {
1648 self.invocation_data.alloc(expansion_data)
1650 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1651 self.legacy_bindings.alloc(binding)
1655 impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
1656 fn parent(self, id: DefId) -> Option<DefId> {
1658 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1659 _ => self.cstore.def_key(id).parent,
1660 }.map(|index| DefId { index, ..id })
1664 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1665 /// the resolver is no longer needed as all the relevant information is inline.
1666 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1667 fn resolve_hir_path(
1672 self.resolve_hir_path_cb(path, is_value,
1673 |resolver, span, error| resolve_error(resolver, span, error))
1676 fn resolve_str_path(
1679 crate_root: Option<&str>,
1680 components: &[&str],
1683 let segments = iter::once(keywords::PathRoot.ident())
1685 crate_root.into_iter()
1686 .chain(components.iter().cloned())
1687 .map(Ident::from_str)
1688 ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1691 let path = ast::Path {
1696 self.resolve_hir_path(&path, is_value)
1699 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1700 self.def_map.get(&id).cloned()
1703 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>> {
1704 self.import_map.get(&id).cloned().unwrap_or_default()
1707 fn definitions(&mut self) -> &mut Definitions {
1708 &mut self.definitions
1712 impl<'a> Resolver<'a> {
1713 /// Rustdoc uses this to resolve things in a recoverable way. ResolutionError<'a>
1714 /// isn't something that can be returned because it can't be made to live that long,
1715 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1716 /// just that an error occurred.
1717 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1718 -> Result<hir::Path, ()> {
1720 let mut errored = false;
1722 let path = if path_str.starts_with("::") {
1725 segments: iter::once(keywords::PathRoot.ident())
1727 path_str.split("::").skip(1).map(Ident::from_str)
1729 .map(|i| self.new_ast_path_segment(i))
1737 .map(Ident::from_str)
1738 .map(|i| self.new_ast_path_segment(i))
1742 let path = self.resolve_hir_path_cb(&path, is_value, |_, _, _| errored = true);
1743 if errored || path.def == Def::Err {
1750 /// resolve_hir_path, but takes a callback in case there was an error
1751 fn resolve_hir_path_cb<F>(
1757 where F: for<'c, 'b> FnOnce(&'c mut Resolver, Span, ResolutionError<'b>)
1759 let namespace = if is_value { ValueNS } else { TypeNS };
1760 let span = path.span;
1761 let segments = &path.segments;
1762 let path = Segment::from_path(&path);
1763 // FIXME (Manishearth): Intra doc links won't get warned of epoch changes
1764 let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1765 span, CrateLint::No) {
1766 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1767 module.def().unwrap(),
1768 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1769 path_res.base_def(),
1770 PathResult::NonModule(..) => {
1771 let msg = "type-relative paths are not supported in this context";
1772 error_callback(self, span, ResolutionError::FailedToResolve(msg));
1775 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1776 PathResult::Failed(span, msg, _) => {
1777 error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1782 let segments: Vec<_> = segments.iter().map(|seg| {
1783 let mut hir_seg = hir::PathSegment::from_ident(seg.ident);
1784 hir_seg.def = Some(self.def_map.get(&seg.id).map_or(Def::Err, |p| p.base_def()));
1790 segments: segments.into(),
1794 fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1795 let mut seg = ast::PathSegment::from_ident(ident);
1796 seg.id = self.session.next_node_id();
1801 impl<'a> Resolver<'a> {
1802 pub fn new(session: &'a Session,
1806 make_glob_map: MakeGlobMap,
1807 crate_loader: &'a mut CrateLoader<'a>,
1808 arenas: &'a ResolverArenas<'a>)
1810 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1811 let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1812 let graph_root = arenas.alloc_module(ModuleData {
1813 no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1814 ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1816 let mut module_map = FxHashMap::default();
1817 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1819 let mut definitions = Definitions::new();
1820 DefCollector::new(&mut definitions, Mark::root())
1821 .collect_root(crate_name, session.local_crate_disambiguator());
1823 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry> =
1824 session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1827 if !attr::contains_name(&krate.attrs, "no_core") {
1828 extern_prelude.insert(Ident::from_str("core"), Default::default());
1829 if !attr::contains_name(&krate.attrs, "no_std") {
1830 extern_prelude.insert(Ident::from_str("std"), Default::default());
1831 if session.rust_2018() {
1832 extern_prelude.insert(Ident::from_str("meta"), Default::default());
1837 let mut invocations = FxHashMap::default();
1838 invocations.insert(Mark::root(),
1839 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1841 let mut macro_defs = FxHashMap::default();
1842 macro_defs.insert(Mark::root(), root_def_id);
1851 // The outermost module has def ID 0; this is not reflected in the
1857 has_self: FxHashSet::default(),
1858 field_names: FxHashMap::default(),
1860 determined_imports: Vec::new(),
1861 indeterminate_imports: Vec::new(),
1863 current_module: graph_root,
1865 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1866 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1867 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1869 label_ribs: Vec::new(),
1871 current_trait_ref: None,
1872 current_self_type: None,
1873 current_self_item: None,
1874 last_import_segment: false,
1875 blacklisted_binding: None,
1877 primitive_type_table: PrimitiveTypeTable::new(),
1879 def_map: Default::default(),
1880 import_map: Default::default(),
1881 freevars: Default::default(),
1882 freevars_seen: Default::default(),
1883 export_map: FxHashMap::default(),
1884 trait_map: Default::default(),
1886 block_map: Default::default(),
1887 extern_module_map: FxHashMap::default(),
1888 binding_parent_modules: FxHashMap::default(),
1890 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1891 glob_map: Default::default(),
1893 used_imports: FxHashSet::default(),
1894 maybe_unused_trait_imports: Default::default(),
1895 maybe_unused_extern_crates: Vec::new(),
1897 unused_labels: FxHashMap::default(),
1899 privacy_errors: Vec::new(),
1900 ambiguity_errors: Vec::new(),
1901 use_injections: Vec::new(),
1902 macro_expanded_macro_export_errors: BTreeSet::new(),
1905 dummy_binding: arenas.alloc_name_binding(NameBinding {
1906 kind: NameBindingKind::Def(Def::Err, false),
1907 expansion: Mark::root(),
1909 vis: ty::Visibility::Public,
1913 macro_names: FxHashSet::default(),
1914 builtin_macros: FxHashMap::default(),
1915 macro_use_prelude: FxHashMap::default(),
1916 all_macros: FxHashMap::default(),
1917 macro_map: FxHashMap::default(),
1920 local_macro_def_scopes: FxHashMap::default(),
1921 name_already_seen: FxHashMap::default(),
1922 potentially_unused_imports: Vec::new(),
1923 struct_constructors: Default::default(),
1924 found_unresolved_macro: false,
1925 unused_macros: FxHashSet::default(),
1926 current_type_ascription: Vec::new(),
1927 injected_crate: None,
1931 pub fn arenas() -> ResolverArenas<'a> {
1935 /// Runs the function on each namespace.
1936 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1942 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1944 match self.macro_defs.get(&ctxt.outer()) {
1945 Some(&def_id) => return def_id,
1946 None => ctxt.remove_mark(),
1951 /// Entry point to crate resolution.
1952 pub fn resolve_crate(&mut self, krate: &Crate) {
1953 ImportResolver { resolver: self }.finalize_imports();
1954 self.current_module = self.graph_root;
1955 self.finalize_current_module_macro_resolutions();
1957 visit::walk_crate(self, krate);
1959 check_unused::check_crate(self, krate);
1960 self.report_errors(krate);
1961 self.crate_loader.postprocess(krate);
1968 normal_ancestor_id: DefId,
1972 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
1973 self.arenas.alloc_module(module)
1976 fn record_use(&mut self, ident: Ident, ns: Namespace,
1977 used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
1978 match used_binding.kind {
1979 NameBindingKind::Import { directive, binding, ref used } if !used.get() => {
1980 // Avoid marking `extern crate` items that refer to a name from extern prelude,
1981 // but not introduce it, as used if they are accessed from lexical scope.
1982 if is_lexical_scope {
1983 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
1984 if let Some(crate_item) = entry.extern_crate_item {
1985 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1992 directive.used.set(true);
1993 self.used_imports.insert((directive.id, ns));
1994 self.add_to_glob_map(directive.id, ident);
1995 self.record_use(ident, ns, binding, false);
1997 NameBindingKind::Ambiguity { kind, b1, b2 } => {
1998 self.ambiguity_errors.push(AmbiguityError {
1999 kind, ident, b1, b2,
2000 misc1: AmbiguityErrorMisc::None,
2001 misc2: AmbiguityErrorMisc::None,
2008 fn add_to_glob_map(&mut self, id: NodeId, ident: Ident) {
2009 if self.make_glob_map {
2010 self.glob_map.entry(id).or_default().insert(ident.name);
2014 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2015 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2016 /// `ident` in the first scope that defines it (or None if no scopes define it).
2018 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2019 /// the items are defined in the block. For example,
2022 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2025 /// g(); // This resolves to the local variable `g` since it shadows the item.
2029 /// Invariant: This must only be called during main resolution, not during
2030 /// import resolution.
2031 fn resolve_ident_in_lexical_scope(&mut self,
2034 record_used_id: Option<NodeId>,
2036 -> Option<LexicalScopeBinding<'a>> {
2037 let record_used = record_used_id.is_some();
2038 assert!(ns == TypeNS || ns == ValueNS);
2040 ident.span = if ident.name == keywords::SelfUpper.name() {
2041 // FIXME(jseyfried) improve `Self` hygiene
2042 ident.span.with_ctxt(SyntaxContext::empty())
2047 ident = ident.modern_and_legacy();
2050 // Walk backwards up the ribs in scope.
2051 let mut module = self.graph_root;
2052 for i in (0 .. self.ribs[ns].len()).rev() {
2053 if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2054 // The ident resolves to a type parameter or local variable.
2055 return Some(LexicalScopeBinding::Def(
2056 self.adjust_local_def(ns, i, def, record_used, path_span)
2060 module = match self.ribs[ns][i].kind {
2061 ModuleRibKind(module) => module,
2062 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2063 // If an invocation of this macro created `ident`, give up on `ident`
2064 // and switch to `ident`'s source from the macro definition.
2065 ident.span.remove_mark();
2071 let item = self.resolve_ident_in_module_unadjusted(
2072 ModuleOrUniformRoot::Module(module),
2078 if let Ok(binding) = item {
2079 // The ident resolves to an item.
2080 return Some(LexicalScopeBinding::Item(binding));
2084 ModuleKind::Block(..) => {}, // We can see through blocks
2089 ident.span = ident.span.modern();
2090 let mut poisoned = None;
2092 let opt_module = if let Some(node_id) = record_used_id {
2093 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2094 node_id, &mut poisoned)
2096 self.hygienic_lexical_parent(module, &mut ident.span)
2098 module = unwrap_or!(opt_module, break);
2099 let orig_current_module = self.current_module;
2100 self.current_module = module; // Lexical resolutions can never be a privacy error.
2101 let result = self.resolve_ident_in_module_unadjusted(
2102 ModuleOrUniformRoot::Module(module),
2108 self.current_module = orig_current_module;
2112 if let Some(node_id) = poisoned {
2113 self.session.buffer_lint_with_diagnostic(
2114 lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2115 node_id, ident.span,
2116 &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2117 lint::builtin::BuiltinLintDiagnostics::
2118 ProcMacroDeriveResolutionFallback(ident.span),
2121 return Some(LexicalScopeBinding::Item(binding))
2123 Err(Determined) => continue,
2124 Err(Undetermined) =>
2125 span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2129 if !module.no_implicit_prelude {
2131 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2132 return Some(LexicalScopeBinding::Item(binding));
2135 if ns == TypeNS && is_known_tool(ident.name) {
2136 let binding = (Def::ToolMod, ty::Visibility::Public,
2137 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
2138 return Some(LexicalScopeBinding::Item(binding));
2140 if let Some(prelude) = self.prelude {
2141 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2142 ModuleOrUniformRoot::Module(prelude),
2148 return Some(LexicalScopeBinding::Item(binding));
2156 fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2157 -> Option<Module<'a>> {
2158 if !module.expansion.is_descendant_of(span.ctxt().outer()) {
2159 return Some(self.macro_def_scope(span.remove_mark()));
2162 if let ModuleKind::Block(..) = module.kind {
2163 return Some(module.parent.unwrap());
2169 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2170 span: &mut Span, node_id: NodeId,
2171 poisoned: &mut Option<NodeId>)
2172 -> Option<Module<'a>> {
2173 if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2177 // We need to support the next case under a deprecation warning
2180 // ---- begin: this comes from a proc macro derive
2181 // mod implementation_details {
2182 // // Note that `MyStruct` is not in scope here.
2183 // impl SomeTrait for MyStruct { ... }
2187 // So we have to fall back to the module's parent during lexical resolution in this case.
2188 if let Some(parent) = module.parent {
2189 // Inner module is inside the macro, parent module is outside of the macro.
2190 if module.expansion != parent.expansion &&
2191 module.expansion.is_descendant_of(parent.expansion) {
2192 // The macro is a proc macro derive
2193 if module.expansion.looks_like_proc_macro_derive() {
2194 if parent.expansion.is_descendant_of(span.ctxt().outer()) {
2195 *poisoned = Some(node_id);
2196 return module.parent;
2205 fn resolve_ident_in_module(
2207 module: ModuleOrUniformRoot<'a>,
2210 parent_scope: Option<&ParentScope<'a>>,
2213 ) -> Result<&'a NameBinding<'a>, Determinacy> {
2214 self.resolve_ident_in_module_ext(
2215 module, ident, ns, parent_scope, record_used, path_span
2216 ).map_err(|(determinacy, _)| determinacy)
2219 fn resolve_ident_in_module_ext(
2221 module: ModuleOrUniformRoot<'a>,
2224 parent_scope: Option<&ParentScope<'a>>,
2227 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2228 let orig_current_module = self.current_module;
2230 ModuleOrUniformRoot::Module(module) => {
2231 ident.span = ident.span.modern();
2232 if let Some(def) = ident.span.adjust(module.expansion) {
2233 self.current_module = self.macro_def_scope(def);
2236 ModuleOrUniformRoot::ExternPrelude => {
2237 ident.span = ident.span.modern();
2238 ident.span.adjust(Mark::root());
2240 ModuleOrUniformRoot::CrateRootAndExternPrelude |
2241 ModuleOrUniformRoot::CurrentScope => {
2245 let result = self.resolve_ident_in_module_unadjusted_ext(
2246 module, ident, ns, parent_scope, false, record_used, path_span,
2248 self.current_module = orig_current_module;
2252 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2253 let mut ctxt = ident.span.ctxt();
2254 let mark = if ident.name == keywords::DollarCrate.name() {
2255 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2256 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2257 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2258 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2259 // definitions actually produced by `macro` and `macro` definitions produced by
2260 // `macro_rules!`, but at least such configurations are not stable yet.
2261 ctxt = ctxt.modern_and_legacy();
2262 let mut iter = ctxt.marks().into_iter().rev().peekable();
2263 let mut result = None;
2264 // Find the last modern mark from the end if it exists.
2265 while let Some(&(mark, transparency)) = iter.peek() {
2266 if transparency == Transparency::Opaque {
2267 result = Some(mark);
2273 // Then find the last legacy mark from the end if it exists.
2274 for (mark, transparency) in iter {
2275 if transparency == Transparency::SemiTransparent {
2276 result = Some(mark);
2283 ctxt = ctxt.modern();
2284 ctxt.adjust(Mark::root())
2286 let module = match mark {
2287 Some(def) => self.macro_def_scope(def),
2288 None => return self.graph_root,
2290 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2293 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2294 let mut module = self.get_module(module.normal_ancestor_id);
2295 while module.span.ctxt().modern() != *ctxt {
2296 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2297 module = self.get_module(parent.normal_ancestor_id);
2304 // We maintain a list of value ribs and type ribs.
2306 // Simultaneously, we keep track of the current position in the module
2307 // graph in the `current_module` pointer. When we go to resolve a name in
2308 // the value or type namespaces, we first look through all the ribs and
2309 // then query the module graph. When we resolve a name in the module
2310 // namespace, we can skip all the ribs (since nested modules are not
2311 // allowed within blocks in Rust) and jump straight to the current module
2314 // Named implementations are handled separately. When we find a method
2315 // call, we consult the module node to find all of the implementations in
2316 // scope. This information is lazily cached in the module node. We then
2317 // generate a fake "implementation scope" containing all the
2318 // implementations thus found, for compatibility with old resolve pass.
2320 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2321 where F: FnOnce(&mut Resolver) -> T
2323 let id = self.definitions.local_def_id(id);
2324 let module = self.module_map.get(&id).cloned(); // clones a reference
2325 if let Some(module) = module {
2326 // Move down in the graph.
2327 let orig_module = replace(&mut self.current_module, module);
2328 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2329 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2331 self.finalize_current_module_macro_resolutions();
2334 self.current_module = orig_module;
2335 self.ribs[ValueNS].pop();
2336 self.ribs[TypeNS].pop();
2343 /// Searches the current set of local scopes for labels. Returns the first non-None label that
2344 /// is returned by the given predicate function
2346 /// Stops after meeting a closure.
2347 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2348 where P: Fn(&Rib, Ident) -> Option<R>
2350 for rib in self.label_ribs.iter().rev() {
2353 // If an invocation of this macro created `ident`, give up on `ident`
2354 // and switch to `ident`'s source from the macro definition.
2355 MacroDefinition(def) => {
2356 if def == self.macro_def(ident.span.ctxt()) {
2357 ident.span.remove_mark();
2361 // Do not resolve labels across function boundary
2365 let r = pred(rib, ident);
2373 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2374 self.with_current_self_item(item, |this| {
2375 this.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2376 let item_def_id = this.definitions.local_def_id(item.id);
2377 this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| {
2378 visit::walk_item(this, item);
2384 fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2385 let segments = &use_tree.prefix.segments;
2386 if !segments.is_empty() {
2387 let ident = segments[0].ident;
2388 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2392 let nss = match use_tree.kind {
2393 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2397 if let Some(LexicalScopeBinding::Def(..)) =
2398 self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2399 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2400 self.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2403 } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2404 for (use_tree, _) in use_trees {
2405 self.future_proof_import(use_tree);
2410 fn resolve_item(&mut self, item: &Item) {
2411 let name = item.ident.name;
2412 debug!("(resolving item) resolving {}", name);
2415 ItemKind::Ty(_, ref generics) |
2416 ItemKind::Fn(_, _, ref generics, _) |
2417 ItemKind::Existential(_, ref generics) => {
2418 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
2419 |this| visit::walk_item(this, item));
2422 ItemKind::Enum(_, ref generics) |
2423 ItemKind::Struct(_, ref generics) |
2424 ItemKind::Union(_, ref generics) => {
2425 self.resolve_adt(item, generics);
2428 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2429 self.resolve_implementation(generics,
2435 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2436 // Create a new rib for the trait-wide type parameters.
2437 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2438 let local_def_id = this.definitions.local_def_id(item.id);
2439 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2440 this.visit_generics(generics);
2441 walk_list!(this, visit_param_bound, bounds);
2443 for trait_item in trait_items {
2444 let type_parameters = HasTypeParameters(&trait_item.generics,
2445 TraitOrImplItemRibKind);
2446 this.with_type_parameter_rib(type_parameters, |this| {
2447 match trait_item.node {
2448 TraitItemKind::Const(ref ty, ref default) => {
2451 // Only impose the restrictions of
2452 // ConstRibKind for an actual constant
2453 // expression in a provided default.
2454 if let Some(ref expr) = *default{
2455 this.with_constant_rib(|this| {
2456 this.visit_expr(expr);
2460 TraitItemKind::Method(_, _) => {
2461 visit::walk_trait_item(this, trait_item)
2463 TraitItemKind::Type(..) => {
2464 visit::walk_trait_item(this, trait_item)
2466 TraitItemKind::Macro(_) => {
2467 panic!("unexpanded macro in resolve!")
2476 ItemKind::TraitAlias(ref generics, ref bounds) => {
2477 // Create a new rib for the trait-wide type parameters.
2478 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2479 let local_def_id = this.definitions.local_def_id(item.id);
2480 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2481 this.visit_generics(generics);
2482 walk_list!(this, visit_param_bound, bounds);
2487 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2488 self.with_scope(item.id, |this| {
2489 visit::walk_item(this, item);
2493 ItemKind::Static(ref ty, _, ref expr) |
2494 ItemKind::Const(ref ty, ref expr) => {
2495 self.with_item_rib(|this| {
2497 this.with_constant_rib(|this| {
2498 this.visit_expr(expr);
2503 ItemKind::Use(ref use_tree) => {
2504 self.future_proof_import(use_tree);
2507 ItemKind::ExternCrate(..) |
2508 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2509 // do nothing, these are just around to be encoded
2512 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2516 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
2517 where F: FnOnce(&mut Resolver)
2519 match type_parameters {
2520 HasTypeParameters(generics, rib_kind) => {
2521 let mut function_type_rib = Rib::new(rib_kind);
2522 let mut seen_bindings = FxHashMap::default();
2523 for param in &generics.params {
2525 GenericParamKind::Lifetime { .. } => {}
2526 GenericParamKind::Type { .. } => {
2527 let ident = param.ident.modern();
2528 debug!("with_type_parameter_rib: {}", param.id);
2530 if seen_bindings.contains_key(&ident) {
2531 let span = seen_bindings.get(&ident).unwrap();
2532 let err = ResolutionError::NameAlreadyUsedInTypeParameterList(
2536 resolve_error(self, param.ident.span, err);
2538 seen_bindings.entry(ident).or_insert(param.ident.span);
2540 // Plain insert (no renaming).
2541 let def = Def::TyParam(self.definitions.local_def_id(param.id));
2542 function_type_rib.bindings.insert(ident, def);
2543 self.record_def(param.id, PathResolution::new(def));
2547 self.ribs[TypeNS].push(function_type_rib);
2550 NoTypeParameters => {
2557 if let HasTypeParameters(..) = type_parameters {
2558 self.ribs[TypeNS].pop();
2562 fn with_label_rib<F>(&mut self, f: F)
2563 where F: FnOnce(&mut Resolver)
2565 self.label_ribs.push(Rib::new(NormalRibKind));
2567 self.label_ribs.pop();
2570 fn with_item_rib<F>(&mut self, f: F)
2571 where F: FnOnce(&mut Resolver)
2573 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2574 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2576 self.ribs[TypeNS].pop();
2577 self.ribs[ValueNS].pop();
2580 fn with_constant_rib<F>(&mut self, f: F)
2581 where F: FnOnce(&mut Resolver)
2583 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2584 self.label_ribs.push(Rib::new(ConstantItemRibKind));
2586 self.label_ribs.pop();
2587 self.ribs[ValueNS].pop();
2590 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2591 where F: FnOnce(&mut Resolver) -> T
2593 // Handle nested impls (inside fn bodies)
2594 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2595 let result = f(self);
2596 self.current_self_type = previous_value;
2600 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2601 where F: FnOnce(&mut Resolver) -> T
2603 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2604 let result = f(self);
2605 self.current_self_item = previous_value;
2609 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`)
2610 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2611 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2613 let mut new_val = None;
2614 let mut new_id = None;
2615 if let Some(trait_ref) = opt_trait_ref {
2616 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2617 let def = self.smart_resolve_path_fragment(
2621 trait_ref.path.span,
2622 PathSource::Trait(AliasPossibility::No),
2623 CrateLint::SimplePath(trait_ref.ref_id),
2625 if def != Def::Err {
2626 new_id = Some(def.def_id());
2627 let span = trait_ref.path.span;
2628 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2629 self.resolve_path_without_parent_scope(
2634 CrateLint::SimplePath(trait_ref.ref_id),
2637 new_val = Some((module, trait_ref.clone()));
2641 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2642 let result = f(self, new_id);
2643 self.current_trait_ref = original_trait_ref;
2647 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2648 where F: FnOnce(&mut Resolver)
2650 let mut self_type_rib = Rib::new(NormalRibKind);
2652 // plain insert (no renaming, types are not currently hygienic....)
2653 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2654 self.ribs[TypeNS].push(self_type_rib);
2656 self.ribs[TypeNS].pop();
2659 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
2660 where F: FnOnce(&mut Resolver)
2662 let self_def = Def::SelfCtor(impl_id);
2663 let mut self_type_rib = Rib::new(NormalRibKind);
2664 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2665 self.ribs[ValueNS].push(self_type_rib);
2667 self.ribs[ValueNS].pop();
2670 fn resolve_implementation(&mut self,
2671 generics: &Generics,
2672 opt_trait_reference: &Option<TraitRef>,
2675 impl_items: &[ImplItem]) {
2676 // If applicable, create a rib for the type parameters.
2677 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2678 // Dummy self type for better errors if `Self` is used in the trait path.
2679 this.with_self_rib(Def::SelfTy(None, None), |this| {
2680 // Resolve the trait reference, if necessary.
2681 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2682 let item_def_id = this.definitions.local_def_id(item_id);
2683 this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2684 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2685 // Resolve type arguments in the trait path.
2686 visit::walk_trait_ref(this, trait_ref);
2688 // Resolve the self type.
2689 this.visit_ty(self_type);
2690 // Resolve the type parameters.
2691 this.visit_generics(generics);
2692 // Resolve the items within the impl.
2693 this.with_current_self_type(self_type, |this| {
2694 this.with_self_struct_ctor_rib(item_def_id, |this| {
2695 for impl_item in impl_items {
2696 this.resolve_visibility(&impl_item.vis);
2698 // We also need a new scope for the impl item type parameters.
2699 let type_parameters = HasTypeParameters(&impl_item.generics,
2700 TraitOrImplItemRibKind);
2701 this.with_type_parameter_rib(type_parameters, |this| {
2702 use self::ResolutionError::*;
2703 match impl_item.node {
2704 ImplItemKind::Const(..) => {
2705 // If this is a trait impl, ensure the const
2707 this.check_trait_item(impl_item.ident,
2710 |n, s| ConstNotMemberOfTrait(n, s));
2711 this.with_constant_rib(|this|
2712 visit::walk_impl_item(this, impl_item)
2715 ImplItemKind::Method(..) => {
2716 // If this is a trait impl, ensure the method
2718 this.check_trait_item(impl_item.ident,
2721 |n, s| MethodNotMemberOfTrait(n, s));
2723 visit::walk_impl_item(this, impl_item);
2725 ImplItemKind::Type(ref ty) => {
2726 // If this is a trait impl, ensure the type
2728 this.check_trait_item(impl_item.ident,
2731 |n, s| TypeNotMemberOfTrait(n, s));
2735 ImplItemKind::Existential(ref bounds) => {
2736 // If this is a trait impl, ensure the type
2738 this.check_trait_item(impl_item.ident,
2741 |n, s| TypeNotMemberOfTrait(n, s));
2743 for bound in bounds {
2744 this.visit_param_bound(bound);
2747 ImplItemKind::Macro(_) =>
2748 panic!("unexpanded macro in resolve!"),
2760 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2761 where F: FnOnce(Name, &str) -> ResolutionError
2763 // If there is a TraitRef in scope for an impl, then the method must be in the
2765 if let Some((module, _)) = self.current_trait_ref {
2766 if self.resolve_ident_in_module(
2767 ModuleOrUniformRoot::Module(module),
2774 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2775 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2780 fn resolve_local(&mut self, local: &Local) {
2781 // Resolve the type.
2782 walk_list!(self, visit_ty, &local.ty);
2784 // Resolve the initializer.
2785 walk_list!(self, visit_expr, &local.init);
2787 // Resolve the pattern.
2788 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
2791 // build a map from pattern identifiers to binding-info's.
2792 // this is done hygienically. This could arise for a macro
2793 // that expands into an or-pattern where one 'x' was from the
2794 // user and one 'x' came from the macro.
2795 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2796 let mut binding_map = FxHashMap::default();
2798 pat.walk(&mut |pat| {
2799 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2800 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2801 Some(Def::Local(..)) => true,
2804 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2805 binding_map.insert(ident, binding_info);
2814 // check that all of the arms in an or-pattern have exactly the
2815 // same set of bindings, with the same binding modes for each.
2816 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2817 if pats.is_empty() {
2821 let mut missing_vars = FxHashMap::default();
2822 let mut inconsistent_vars = FxHashMap::default();
2823 for (i, p) in pats.iter().enumerate() {
2824 let map_i = self.binding_mode_map(&p);
2826 for (j, q) in pats.iter().enumerate() {
2831 let map_j = self.binding_mode_map(&q);
2832 for (&key, &binding_i) in &map_i {
2833 if map_j.is_empty() { // Account for missing bindings when
2834 let binding_error = missing_vars // map_j has none.
2836 .or_insert(BindingError {
2838 origin: BTreeSet::new(),
2839 target: BTreeSet::new(),
2841 binding_error.origin.insert(binding_i.span);
2842 binding_error.target.insert(q.span);
2844 for (&key_j, &binding_j) in &map_j {
2845 match map_i.get(&key_j) {
2846 None => { // missing binding
2847 let binding_error = missing_vars
2849 .or_insert(BindingError {
2851 origin: BTreeSet::new(),
2852 target: BTreeSet::new(),
2854 binding_error.origin.insert(binding_j.span);
2855 binding_error.target.insert(p.span);
2857 Some(binding_i) => { // check consistent binding
2858 if binding_i.binding_mode != binding_j.binding_mode {
2861 .or_insert((binding_j.span, binding_i.span));
2869 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2870 missing_vars.sort();
2871 for (_, v) in missing_vars {
2873 *v.origin.iter().next().unwrap(),
2874 ResolutionError::VariableNotBoundInPattern(v));
2876 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2877 inconsistent_vars.sort();
2878 for (name, v) in inconsistent_vars {
2879 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2883 fn resolve_arm(&mut self, arm: &Arm) {
2884 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2886 let mut bindings_list = FxHashMap::default();
2887 for pattern in &arm.pats {
2888 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2891 // This has to happen *after* we determine which pat_idents are variants.
2892 self.check_consistent_bindings(&arm.pats);
2894 if let Some(ast::Guard::If(ref expr)) = arm.guard {
2895 self.visit_expr(expr)
2897 self.visit_expr(&arm.body);
2899 self.ribs[ValueNS].pop();
2902 fn resolve_block(&mut self, block: &Block) {
2903 debug!("(resolving block) entering block");
2904 // Move down in the graph, if there's an anonymous module rooted here.
2905 let orig_module = self.current_module;
2906 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2908 let mut num_macro_definition_ribs = 0;
2909 if let Some(anonymous_module) = anonymous_module {
2910 debug!("(resolving block) found anonymous module, moving down");
2911 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2912 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2913 self.current_module = anonymous_module;
2914 self.finalize_current_module_macro_resolutions();
2916 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2919 // Descend into the block.
2920 for stmt in &block.stmts {
2921 if let ast::StmtKind::Item(ref item) = stmt.node {
2922 if let ast::ItemKind::MacroDef(..) = item.node {
2923 num_macro_definition_ribs += 1;
2924 let def = self.definitions.local_def_id(item.id);
2925 self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
2926 self.label_ribs.push(Rib::new(MacroDefinition(def)));
2930 self.visit_stmt(stmt);
2934 self.current_module = orig_module;
2935 for _ in 0 .. num_macro_definition_ribs {
2936 self.ribs[ValueNS].pop();
2937 self.label_ribs.pop();
2939 self.ribs[ValueNS].pop();
2940 if anonymous_module.is_some() {
2941 self.ribs[TypeNS].pop();
2943 debug!("(resolving block) leaving block");
2946 fn fresh_binding(&mut self,
2949 outer_pat_id: NodeId,
2950 pat_src: PatternSource,
2951 bindings: &mut FxHashMap<Ident, NodeId>)
2953 // Add the binding to the local ribs, if it
2954 // doesn't already exist in the bindings map. (We
2955 // must not add it if it's in the bindings map
2956 // because that breaks the assumptions later
2957 // passes make about or-patterns.)
2958 let ident = ident.modern_and_legacy();
2959 let mut def = Def::Local(pat_id);
2960 match bindings.get(&ident).cloned() {
2961 Some(id) if id == outer_pat_id => {
2962 // `Variant(a, a)`, error
2966 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2970 Some(..) if pat_src == PatternSource::FnParam => {
2971 // `fn f(a: u8, a: u8)`, error
2975 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2979 Some(..) if pat_src == PatternSource::Match ||
2980 pat_src == PatternSource::IfLet ||
2981 pat_src == PatternSource::WhileLet => {
2982 // `Variant1(a) | Variant2(a)`, ok
2983 // Reuse definition from the first `a`.
2984 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
2987 span_bug!(ident.span, "two bindings with the same name from \
2988 unexpected pattern source {:?}", pat_src);
2991 // A completely fresh binding, add to the lists if it's valid.
2992 if ident.name != keywords::Invalid.name() {
2993 bindings.insert(ident, outer_pat_id);
2994 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
2999 PathResolution::new(def)
3002 fn resolve_pattern(&mut self,
3004 pat_src: PatternSource,
3005 // Maps idents to the node ID for the
3006 // outermost pattern that binds them.
3007 bindings: &mut FxHashMap<Ident, NodeId>) {
3008 // Visit all direct subpatterns of this pattern.
3009 let outer_pat_id = pat.id;
3010 pat.walk(&mut |pat| {
3011 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
3013 PatKind::Ident(bmode, ident, ref opt_pat) => {
3014 // First try to resolve the identifier as some existing
3015 // entity, then fall back to a fresh binding.
3016 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3018 .and_then(LexicalScopeBinding::item);
3019 let resolution = binding.map(NameBinding::def).and_then(|def| {
3020 let is_syntactic_ambiguity = opt_pat.is_none() &&
3021 bmode == BindingMode::ByValue(Mutability::Immutable);
3023 Def::StructCtor(_, CtorKind::Const) |
3024 Def::VariantCtor(_, CtorKind::Const) |
3025 Def::Const(..) if is_syntactic_ambiguity => {
3026 // Disambiguate in favor of a unit struct/variant
3027 // or constant pattern.
3028 self.record_use(ident, ValueNS, binding.unwrap(), false);
3029 Some(PathResolution::new(def))
3031 Def::StructCtor(..) | Def::VariantCtor(..) |
3032 Def::Const(..) | Def::Static(..) => {
3033 // This is unambiguously a fresh binding, either syntactically
3034 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3035 // to something unusable as a pattern (e.g., constructor function),
3036 // but we still conservatively report an error, see
3037 // issues/33118#issuecomment-233962221 for one reason why.
3041 ResolutionError::BindingShadowsSomethingUnacceptable(
3042 pat_src.descr(), ident.name, binding.unwrap())
3046 Def::Fn(..) | Def::Err => {
3047 // These entities are explicitly allowed
3048 // to be shadowed by fresh bindings.
3052 span_bug!(ident.span, "unexpected definition for an \
3053 identifier in pattern: {:?}", def);
3056 }).unwrap_or_else(|| {
3057 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3060 self.record_def(pat.id, resolution);
3063 PatKind::TupleStruct(ref path, ..) => {
3064 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3067 PatKind::Path(ref qself, ref path) => {
3068 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3071 PatKind::Struct(ref path, ..) => {
3072 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3080 visit::walk_pat(self, pat);
3083 // High-level and context dependent path resolution routine.
3084 // Resolves the path and records the resolution into definition map.
3085 // If resolution fails tries several techniques to find likely
3086 // resolution candidates, suggest imports or other help, and report
3087 // errors in user friendly way.
3088 fn smart_resolve_path(&mut self,
3090 qself: Option<&QSelf>,
3094 self.smart_resolve_path_with_crate_lint(id, qself, path, source, CrateLint::SimplePath(id))
3097 /// A variant of `smart_resolve_path` where you also specify extra
3098 /// information about where the path came from; this extra info is
3099 /// sometimes needed for the lint that recommends rewriting
3100 /// absolute paths to `crate`, so that it knows how to frame the
3101 /// suggestion. If you are just resolving a path like `foo::bar`
3102 /// that appears...somewhere, though, then you just want
3103 /// `CrateLint::SimplePath`, which is what `smart_resolve_path`
3104 /// already provides.
3105 fn smart_resolve_path_with_crate_lint(
3108 qself: Option<&QSelf>,
3111 crate_lint: CrateLint
3112 ) -> PathResolution {
3113 self.smart_resolve_path_fragment(
3116 &Segment::from_path(path),
3123 fn smart_resolve_path_fragment(&mut self,
3125 qself: Option<&QSelf>,
3129 crate_lint: CrateLint)
3131 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
3132 let ns = source.namespace();
3133 let is_expected = &|def| source.is_expected(def);
3134 let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
3136 // Base error is amended with one short label and possibly some longer helps/notes.
3137 let report_errors = |this: &mut Self, def: Option<Def>| {
3138 // Make the base error.
3139 let expected = source.descr_expected();
3140 let path_str = Segment::names_to_string(path);
3141 let item_str = path.last().unwrap().ident;
3142 let code = source.error_code(def.is_some());
3143 let (base_msg, fallback_label, base_span) = if let Some(def) = def {
3144 (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
3145 format!("not a {}", expected),
3148 let item_span = path.last().unwrap().ident.span;
3149 let (mod_prefix, mod_str) = if path.len() == 1 {
3150 (String::new(), "this scope".to_string())
3151 } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() {
3152 (String::new(), "the crate root".to_string())
3154 let mod_path = &path[..path.len() - 1];
3155 let mod_prefix = match this.resolve_path_without_parent_scope(
3156 mod_path, Some(TypeNS), false, span, CrateLint::No
3158 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3161 }.map_or(String::new(), |def| format!("{} ", def.kind_name()));
3162 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
3164 (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
3165 format!("not found in {}", mod_str),
3169 let code = DiagnosticId::Error(code.into());
3170 let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
3172 // Emit help message for fake-self from other languages like `this`(javascript)
3173 if ["this", "my"].contains(&&*item_str.as_str())
3174 && this.self_value_is_available(path[0].ident.span, span) {
3175 err.span_suggestion_with_applicability(
3179 Applicability::MaybeIncorrect,
3183 // Emit special messages for unresolved `Self` and `self`.
3184 if is_self_type(path, ns) {
3185 __diagnostic_used!(E0411);
3186 err.code(DiagnosticId::Error("E0411".into()));
3187 err.span_label(span, format!("`Self` is only available in impls, traits, \
3188 and type definitions"));
3189 return (err, Vec::new());
3191 if is_self_value(path, ns) {
3192 debug!("smart_resolve_path_fragment E0424 source:{:?}", source);
3194 __diagnostic_used!(E0424);
3195 err.code(DiagnosticId::Error("E0424".into()));
3196 err.span_label(span, match source {
3197 PathSource::Pat => {
3198 format!("`self` value is a keyword \
3199 and may not be bound to \
3200 variables or shadowed")
3203 format!("`self` value is a keyword \
3204 only available in methods \
3205 with `self` parameter")
3208 return (err, Vec::new());
3211 // Try to lookup the name in more relaxed fashion for better error reporting.
3212 let ident = path.last().unwrap().ident;
3213 let candidates = this.lookup_import_candidates(ident, ns, is_expected);
3214 if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
3215 let enum_candidates =
3216 this.lookup_import_candidates(ident, ns, is_enum_variant);
3217 let mut enum_candidates = enum_candidates.iter()
3219 import_candidate_to_enum_paths(&suggestion)
3220 }).collect::<Vec<_>>();
3221 enum_candidates.sort();
3223 if !enum_candidates.is_empty() {
3224 // contextualize for E0412 "cannot find type", but don't belabor the point
3225 // (that it's a variant) for E0573 "expected type, found variant"
3226 let preamble = if def.is_none() {
3227 let others = match enum_candidates.len() {
3229 2 => " and 1 other".to_owned(),
3230 n => format!(" and {} others", n)
3232 format!("there is an enum variant `{}`{}; ",
3233 enum_candidates[0].0, others)
3237 let msg = format!("{}try using the variant's enum", preamble);
3239 err.span_suggestions_with_applicability(
3242 enum_candidates.into_iter()
3243 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
3244 // variants reëxported in prelude doesn't mean `prelude::v1` is the
3245 // type name! FIXME: is there a more principled way to do this that
3246 // would work for other reëxports?
3247 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
3248 // also say `Option` rather than `std::prelude::v1::Option`
3249 .map(|enum_ty_path| {
3250 // FIXME #56861: DRYer prelude filtering
3251 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
3253 Applicability::MachineApplicable,
3257 if path.len() == 1 && this.self_type_is_available(span) {
3258 if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) {
3259 let self_is_available = this.self_value_is_available(path[0].ident.span, span);
3261 AssocSuggestion::Field => {
3262 err.span_suggestion_with_applicability(
3265 format!("self.{}", path_str),
3266 Applicability::MachineApplicable,
3268 if !self_is_available {
3269 err.span_label(span, format!("`self` value is a keyword \
3271 methods with `self` parameter"));
3274 AssocSuggestion::MethodWithSelf if self_is_available => {
3275 err.span_suggestion_with_applicability(
3278 format!("self.{}", path_str),
3279 Applicability::MachineApplicable,
3282 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
3283 err.span_suggestion_with_applicability(
3286 format!("Self::{}", path_str),
3287 Applicability::MachineApplicable,
3291 return (err, candidates);
3295 let mut levenshtein_worked = false;
3297 // Try Levenshtein algorithm.
3298 if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected, span) {
3299 err.span_label(ident_span, format!("did you mean `{}`?", candidate));
3300 levenshtein_worked = true;
3303 // Try context dependent help if relaxed lookup didn't work.
3304 if let Some(def) = def {
3305 match (def, source) {
3306 (Def::Macro(..), _) => {
3307 err.span_label(span, format!("did you mean `{}!(...)`?", path_str));
3308 return (err, candidates);
3310 (Def::TyAlias(..), PathSource::Trait(_)) => {
3311 err.span_label(span, "type aliases cannot be used as traits");
3312 if nightly_options::is_nightly_build() {
3313 err.note("did you mean to use a trait alias?");
3315 return (err, candidates);
3317 (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
3318 ExprKind::Field(_, ident) => {
3319 err.span_label(parent.span, format!("did you mean `{}::{}`?",
3321 return (err, candidates);
3323 ExprKind::MethodCall(ref segment, ..) => {
3324 err.span_label(parent.span, format!("did you mean `{}::{}(...)`?",
3325 path_str, segment.ident));
3326 return (err, candidates);
3330 (Def::Enum(..), PathSource::TupleStruct)
3331 | (Def::Enum(..), PathSource::Expr(..)) => {
3332 if let Some(variants) = this.collect_enum_variants(def) {
3333 err.note(&format!("did you mean to use one \
3334 of the following variants?\n{}",
3336 .map(|suggestion| path_names_to_string(suggestion))
3337 .map(|suggestion| format!("- `{}`", suggestion))
3338 .collect::<Vec<_>>()
3342 err.note("did you mean to use one of the enum's variants?");
3344 return (err, candidates);
3346 (Def::Struct(def_id), _) if ns == ValueNS => {
3347 if let Some((ctor_def, ctor_vis))
3348 = this.struct_constructors.get(&def_id).cloned() {
3349 let accessible_ctor = this.is_accessible(ctor_vis);
3350 if is_expected(ctor_def) && !accessible_ctor {
3351 err.span_label(span, format!("constructor is not visible \
3352 here due to private fields"));
3355 // HACK(estebank): find a better way to figure out that this was a
3356 // parser issue where a struct literal is being used on an expression
3357 // where a brace being opened means a block is being started. Look
3358 // ahead for the next text to see if `span` is followed by a `{`.
3359 let sm = this.session.source_map();
3362 sp = sm.next_point(sp);
3363 match sm.span_to_snippet(sp) {
3364 Ok(ref snippet) => {
3365 if snippet.chars().any(|c| { !c.is_whitespace() }) {
3372 let followed_by_brace = match sm.span_to_snippet(sp) {
3373 Ok(ref snippet) if snippet == "{" => true,
3377 PathSource::Expr(Some(parent)) => {
3379 ExprKind::MethodCall(ref path_assignment, _) => {
3380 err.span_suggestion_with_applicability(
3381 sm.start_point(parent.span)
3382 .to(path_assignment.ident.span),
3383 "use `::` to access an associated function",
3386 path_assignment.ident),
3387 Applicability::MaybeIncorrect
3389 return (err, candidates);
3394 format!("did you mean `{} {{ /* fields */ }}`?",
3397 return (err, candidates);
3401 PathSource::Expr(None) if followed_by_brace == true => {
3404 format!("did you mean `({} {{ /* fields */ }})`?",
3407 return (err, candidates);
3412 format!("did you mean `{} {{ /* fields */ }}`?",
3415 return (err, candidates);
3419 return (err, candidates);
3421 (Def::Union(..), _) |
3422 (Def::Variant(..), _) |
3423 (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
3424 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
3426 return (err, candidates);
3428 (Def::SelfTy(..), _) if ns == ValueNS => {
3429 err.span_label(span, fallback_label);
3430 err.note("can't use `Self` as a constructor, you must use the \
3431 implemented struct");
3432 return (err, candidates);
3434 (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
3435 err.note("can't use a type alias as a constructor");
3436 return (err, candidates);
3443 if !levenshtein_worked {
3444 err.span_label(base_span, fallback_label);
3445 this.type_ascription_suggestion(&mut err, base_span);
3449 let report_errors = |this: &mut Self, def: Option<Def>| {
3450 let (err, candidates) = report_errors(this, def);
3451 let def_id = this.current_module.normal_ancestor_id;
3452 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3453 let better = def.is_some();
3454 this.use_injections.push(UseError { err, candidates, node_id, better });
3455 err_path_resolution()
3458 let resolution = match self.resolve_qpath_anywhere(
3464 source.defer_to_typeck(),
3465 source.global_by_default(),
3468 Some(resolution) if resolution.unresolved_segments() == 0 => {
3469 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
3472 // Add a temporary hack to smooth the transition to new struct ctor
3473 // visibility rules. See #38932 for more details.
3475 if let Def::Struct(def_id) = resolution.base_def() {
3476 if let Some((ctor_def, ctor_vis))
3477 = self.struct_constructors.get(&def_id).cloned() {
3478 if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
3479 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3480 self.session.buffer_lint(lint, id, span,
3481 "private struct constructors are not usable through \
3482 re-exports in outer modules",
3484 res = Some(PathResolution::new(ctor_def));
3489 res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3492 Some(resolution) if source.defer_to_typeck() => {
3493 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3494 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3495 // it needs to be added to the trait map.
3497 let item_name = path.last().unwrap().ident;
3498 let traits = self.get_traits_containing_item(item_name, ns);
3499 self.trait_map.insert(id, traits);
3503 _ => report_errors(self, None)
3506 if let PathSource::TraitItem(..) = source {} else {
3507 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3508 self.record_def(id, resolution);
3513 fn type_ascription_suggestion(&self,
3514 err: &mut DiagnosticBuilder,
3516 debug!("type_ascription_suggetion {:?}", base_span);
3517 let cm = self.session.source_map();
3518 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3519 if let Some(sp) = self.current_type_ascription.last() {
3521 loop { // try to find the `:`, bail on first non-':'/non-whitespace
3522 sp = cm.next_point(sp);
3523 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3524 debug!("snippet {:?}", snippet);
3525 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3526 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3527 debug!("{:?} {:?}", line_sp, line_base_sp);
3529 err.span_label(base_span,
3530 "expecting a type here because of type ascription");
3531 if line_sp != line_base_sp {
3532 err.span_suggestion_short_with_applicability(
3534 "did you mean to use `;` here instead?",
3536 Applicability::MaybeIncorrect,
3540 } else if !snippet.trim().is_empty() {
3541 debug!("tried to find type ascription `:` token, couldn't find it");
3551 fn self_type_is_available(&mut self, span: Span) -> bool {
3552 let binding = self.resolve_ident_in_lexical_scope(keywords::SelfUpper.ident(),
3553 TypeNS, None, span);
3554 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3557 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3558 let ident = Ident::new(keywords::SelfLower.name(), self_span);
3559 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3560 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3563 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3564 fn resolve_qpath_anywhere(&mut self,
3566 qself: Option<&QSelf>,
3568 primary_ns: Namespace,
3570 defer_to_typeck: bool,
3571 global_by_default: bool,
3572 crate_lint: CrateLint)
3573 -> Option<PathResolution> {
3574 let mut fin_res = None;
3575 // FIXME: can't resolve paths in macro namespace yet, macros are
3576 // processed by the little special hack below.
3577 for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3578 if i == 0 || ns != primary_ns {
3579 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3580 // If defer_to_typeck, then resolution > no resolution,
3581 // otherwise full resolution > partial resolution > no resolution.
3582 Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3584 res => if fin_res.is_none() { fin_res = res },
3588 if primary_ns != MacroNS &&
3589 (self.macro_names.contains(&path[0].ident.modern()) ||
3590 self.builtin_macros.get(&path[0].ident.name).cloned()
3591 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) ||
3592 self.macro_use_prelude.get(&path[0].ident.name).cloned()
3593 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) {
3594 // Return some dummy definition, it's enough for error reporting.
3596 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3602 /// Handles paths that may refer to associated items.
3603 fn resolve_qpath(&mut self,
3605 qself: Option<&QSelf>,
3609 global_by_default: bool,
3610 crate_lint: CrateLint)
3611 -> Option<PathResolution> {
3613 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3614 ns={:?}, span={:?}, global_by_default={:?})",
3623 if let Some(qself) = qself {
3624 if qself.position == 0 {
3625 // This is a case like `<T>::B`, where there is no
3626 // trait to resolve. In that case, we leave the `B`
3627 // segment to be resolved by type-check.
3628 return Some(PathResolution::with_unresolved_segments(
3629 Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3633 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3635 // Currently, `path` names the full item (`A::B::C`, in
3636 // our example). so we extract the prefix of that that is
3637 // the trait (the slice upto and including
3638 // `qself.position`). And then we recursively resolve that,
3639 // but with `qself` set to `None`.
3641 // However, setting `qself` to none (but not changing the
3642 // span) loses the information about where this path
3643 // *actually* appears, so for the purposes of the crate
3644 // lint we pass along information that this is the trait
3645 // name from a fully qualified path, and this also
3646 // contains the full span (the `CrateLint::QPathTrait`).
3647 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3648 let res = self.smart_resolve_path_fragment(
3651 &path[..=qself.position],
3653 PathSource::TraitItem(ns),
3654 CrateLint::QPathTrait {
3656 qpath_span: qself.path_span,
3660 // The remaining segments (the `C` in our example) will
3661 // have to be resolved by type-check, since that requires doing
3662 // trait resolution.
3663 return Some(PathResolution::with_unresolved_segments(
3664 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3668 let result = match self.resolve_path_without_parent_scope(
3675 PathResult::NonModule(path_res) => path_res,
3676 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3677 PathResolution::new(module.def().unwrap())
3679 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3680 // don't report an error right away, but try to fallback to a primitive type.
3681 // So, we are still able to successfully resolve something like
3683 // use std::u8; // bring module u8 in scope
3684 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3685 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3686 // // not to non-existent std::u8::max_value
3689 // Such behavior is required for backward compatibility.
3690 // The same fallback is used when `a` resolves to nothing.
3691 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3692 PathResult::Failed(..)
3693 if (ns == TypeNS || path.len() > 1) &&
3694 self.primitive_type_table.primitive_types
3695 .contains_key(&path[0].ident.name) => {
3696 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3697 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3699 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3700 PathResolution::new(module.def().unwrap()),
3701 PathResult::Failed(span, msg, false) => {
3702 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
3703 err_path_resolution()
3705 PathResult::Module(..) | PathResult::Failed(..) => return None,
3706 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3709 if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3710 path[0].ident.name != keywords::PathRoot.name() &&
3711 path[0].ident.name != keywords::DollarCrate.name() {
3712 let unqualified_result = {
3713 match self.resolve_path_without_parent_scope(
3714 &[*path.last().unwrap()],
3720 PathResult::NonModule(path_res) => path_res.base_def(),
3721 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3722 module.def().unwrap(),
3723 _ => return Some(result),
3726 if result.base_def() == unqualified_result {
3727 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3728 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3735 fn resolve_path_without_parent_scope(
3738 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3741 crate_lint: CrateLint,
3742 ) -> PathResult<'a> {
3743 // Macro and import paths must have full parent scope available during resolution,
3744 // other paths will do okay with parent module alone.
3745 assert!(opt_ns != None && opt_ns != Some(MacroNS));
3746 let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3747 self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3753 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3754 parent_scope: &ParentScope<'a>,
3757 crate_lint: CrateLint,
3758 ) -> PathResult<'a> {
3759 let mut module = None;
3760 let mut allow_super = true;
3761 let mut second_binding = None;
3762 self.current_module = parent_scope.module;
3765 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3766 path_span={:?}, crate_lint={:?})",
3774 for (i, &Segment { ident, id }) in path.iter().enumerate() {
3775 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3776 let record_segment_def = |this: &mut Self, def| {
3778 if let Some(id) = id {
3779 if !this.def_map.contains_key(&id) {
3780 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3781 this.record_def(id, PathResolution::new(def));
3787 let is_last = i == path.len() - 1;
3788 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3789 let name = ident.name;
3791 allow_super &= ns == TypeNS &&
3792 (name == keywords::SelfLower.name() ||
3793 name == keywords::Super.name());
3796 if allow_super && name == keywords::Super.name() {
3797 let mut ctxt = ident.span.ctxt().modern();
3798 let self_module = match i {
3799 0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3801 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3805 if let Some(self_module) = self_module {
3806 if let Some(parent) = self_module.parent {
3807 module = Some(ModuleOrUniformRoot::Module(
3808 self.resolve_self(&mut ctxt, parent)));
3812 let msg = "there are too many initial `super`s.".to_string();
3813 return PathResult::Failed(ident.span, msg, false);
3816 if name == keywords::SelfLower.name() {
3817 let mut ctxt = ident.span.ctxt().modern();
3818 module = Some(ModuleOrUniformRoot::Module(
3819 self.resolve_self(&mut ctxt, self.current_module)));
3822 if name == keywords::Extern.name() ||
3823 name == keywords::PathRoot.name() && ident.span.rust_2018() {
3824 module = Some(ModuleOrUniformRoot::ExternPrelude);
3827 if name == keywords::PathRoot.name() &&
3828 ident.span.rust_2015() && self.session.rust_2018() {
3829 // `::a::b` from 2015 macro on 2018 global edition
3830 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3833 if name == keywords::PathRoot.name() ||
3834 name == keywords::Crate.name() ||
3835 name == keywords::DollarCrate.name() {
3836 // `::a::b`, `crate::a::b` or `$crate::a::b`
3837 module = Some(ModuleOrUniformRoot::Module(
3838 self.resolve_crate_root(ident)));
3844 // Report special messages for path segment keywords in wrong positions.
3845 if ident.is_path_segment_keyword() && i != 0 {
3846 let name_str = if name == keywords::PathRoot.name() {
3847 "crate root".to_string()
3849 format!("`{}`", name)
3851 let msg = if i == 1 && path[0].ident.name == keywords::PathRoot.name() {
3852 format!("global paths cannot start with {}", name_str)
3854 format!("{} in paths can only be used in start position", name_str)
3856 return PathResult::Failed(ident.span, msg, false);
3859 let binding = if let Some(module) = module {
3860 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3861 } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3862 assert!(ns == TypeNS);
3863 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3864 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3865 record_used, path_span)
3867 let record_used_id =
3868 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3869 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3870 // we found a locally-imported or available item/module
3871 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3872 // we found a local variable or type param
3873 Some(LexicalScopeBinding::Def(def))
3874 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3875 record_segment_def(self, def);
3876 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3880 _ => Err(Determinacy::determined(record_used)),
3887 second_binding = Some(binding);
3889 let def = binding.def();
3890 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3891 if let Some(next_module) = binding.module() {
3892 module = Some(ModuleOrUniformRoot::Module(next_module));
3893 record_segment_def(self, def);
3894 } else if def == Def::ToolMod && i + 1 != path.len() {
3895 let def = Def::NonMacroAttr(NonMacroAttrKind::Tool);
3896 return PathResult::NonModule(PathResolution::new(def));
3897 } else if def == Def::Err {
3898 return PathResult::NonModule(err_path_resolution());
3899 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3900 self.lint_if_path_starts_with_module(
3906 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3907 def, path.len() - i - 1
3910 return PathResult::Failed(ident.span,
3911 format!("not a module `{}`", ident),
3915 Err(Undetermined) => return PathResult::Indeterminate,
3916 Err(Determined) => {
3917 if let Some(ModuleOrUniformRoot::Module(module)) = module {
3918 if opt_ns.is_some() && !module.is_normal() {
3919 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3920 module.def().unwrap(), path.len() - i
3924 let module_def = match module {
3925 Some(ModuleOrUniformRoot::Module(module)) => module.def(),
3928 let msg = if module_def == self.graph_root.def() {
3929 let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3930 let mut candidates =
3931 self.lookup_import_candidates(ident, TypeNS, is_mod);
3932 candidates.sort_by_cached_key(|c| {
3933 (c.path.segments.len(), c.path.to_string())
3935 if let Some(candidate) = candidates.get(0) {
3936 format!("did you mean `{}`?", candidate.path)
3938 format!("maybe a missing `extern crate {};`?", ident)
3941 format!("use of undeclared type or module `{}`", ident)
3943 format!("could not find `{}` in `{}`", ident, path[i - 1].ident)
3945 return PathResult::Failed(ident.span, msg, is_last);
3950 self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
3952 PathResult::Module(match module {
3953 Some(module) => module,
3954 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
3955 _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
3959 fn lint_if_path_starts_with_module(
3961 crate_lint: CrateLint,
3964 second_binding: Option<&NameBinding>,
3966 let (diag_id, diag_span) = match crate_lint {
3967 CrateLint::No => return,
3968 CrateLint::SimplePath(id) => (id, path_span),
3969 CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
3970 CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
3973 let first_name = match path.get(0) {
3974 // In the 2018 edition this lint is a hard error, so nothing to do
3975 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
3979 // We're only interested in `use` paths which should start with
3980 // `{{root}}` or `extern` currently.
3981 if first_name != keywords::Extern.name() && first_name != keywords::PathRoot.name() {
3986 // If this import looks like `crate::...` it's already good
3987 Some(Segment { ident, .. }) if ident.name == keywords::Crate.name() => return,
3988 // Otherwise go below to see if it's an extern crate
3990 // If the path has length one (and it's `PathRoot` most likely)
3991 // then we don't know whether we're gonna be importing a crate or an
3992 // item in our crate. Defer this lint to elsewhere
3996 // If the first element of our path was actually resolved to an
3997 // `ExternCrate` (also used for `crate::...`) then no need to issue a
3998 // warning, this looks all good!
3999 if let Some(binding) = second_binding {
4000 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
4001 // Careful: we still want to rewrite paths from
4002 // renamed extern crates.
4003 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
4009 let diag = lint::builtin::BuiltinLintDiagnostics
4010 ::AbsPathWithModule(diag_span);
4011 self.session.buffer_lint_with_diagnostic(
4012 lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
4014 "absolute paths must start with `self`, `super`, \
4015 `crate`, or an external crate name in the 2018 edition",
4019 // Resolve a local definition, potentially adjusting for closures.
4020 fn adjust_local_def(&mut self,
4025 span: Span) -> Def {
4026 let ribs = &self.ribs[ns][rib_index + 1..];
4028 // An invalid forward use of a type parameter from a previous default.
4029 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
4031 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
4033 assert_eq!(def, Def::Err);
4039 span_bug!(span, "unexpected {:?} in bindings", def)
4041 Def::Local(node_id) => {
4044 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
4045 ForwardTyParamBanRibKind => {
4046 // Nothing to do. Continue.
4048 ClosureRibKind(function_id) => {
4051 let seen = self.freevars_seen
4054 if let Some(&index) = seen.get(&node_id) {
4055 def = Def::Upvar(node_id, index, function_id);
4058 let vec = self.freevars
4061 let depth = vec.len();
4062 def = Def::Upvar(node_id, depth, function_id);
4069 seen.insert(node_id, depth);
4072 ItemRibKind | TraitOrImplItemRibKind => {
4073 // This was an attempt to access an upvar inside a
4074 // named function item. This is not allowed, so we
4077 resolve_error(self, span,
4078 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
4082 ConstantItemRibKind => {
4083 // Still doesn't deal with upvars
4085 resolve_error(self, span,
4086 ResolutionError::AttemptToUseNonConstantValueInConstant);
4093 Def::TyParam(..) | Def::SelfTy(..) => {
4096 NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
4097 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
4098 ConstantItemRibKind => {
4099 // Nothing to do. Continue.
4102 // This was an attempt to use a type parameter outside
4105 resolve_error(self, span,
4106 ResolutionError::TypeParametersFromOuterFunction(def));
4118 fn lookup_assoc_candidate<FilterFn>(&mut self,
4121 filter_fn: FilterFn)
4122 -> Option<AssocSuggestion>
4123 where FilterFn: Fn(Def) -> bool
4125 fn extract_node_id(t: &Ty) -> Option<NodeId> {
4127 TyKind::Path(None, _) => Some(t.id),
4128 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
4129 // This doesn't handle the remaining `Ty` variants as they are not
4130 // that commonly the self_type, it might be interesting to provide
4131 // support for those in future.
4136 // Fields are generally expected in the same contexts as locals.
4137 if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
4138 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
4139 // Look for a field with the same name in the current self_type.
4140 if let Some(resolution) = self.def_map.get(&node_id) {
4141 match resolution.base_def() {
4142 Def::Struct(did) | Def::Union(did)
4143 if resolution.unresolved_segments() == 0 => {
4144 if let Some(field_names) = self.field_names.get(&did) {
4145 if field_names.iter().any(|&field_name| ident.name == field_name) {
4146 return Some(AssocSuggestion::Field);
4156 // Look for associated items in the current trait.
4157 if let Some((module, _)) = self.current_trait_ref {
4158 if let Ok(binding) = self.resolve_ident_in_module(
4159 ModuleOrUniformRoot::Module(module),
4166 let def = binding.def();
4168 return Some(if self.has_self.contains(&def.def_id()) {
4169 AssocSuggestion::MethodWithSelf
4171 AssocSuggestion::AssocItem
4180 fn lookup_typo_candidate<FilterFn>(&mut self,
4183 filter_fn: FilterFn,
4186 where FilterFn: Fn(Def) -> bool
4188 let add_module_candidates = |module: Module, names: &mut Vec<Name>| {
4189 for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
4190 if let Some(binding) = resolution.borrow().binding {
4191 if filter_fn(binding.def()) {
4192 names.push(ident.name);
4198 let mut names = Vec::new();
4199 if path.len() == 1 {
4200 // Search in lexical scope.
4201 // Walk backwards up the ribs in scope and collect candidates.
4202 for rib in self.ribs[ns].iter().rev() {
4203 // Locals and type parameters
4204 for (ident, def) in &rib.bindings {
4205 if filter_fn(*def) {
4206 names.push(ident.name);
4210 if let ModuleRibKind(module) = rib.kind {
4211 // Items from this module
4212 add_module_candidates(module, &mut names);
4214 if let ModuleKind::Block(..) = module.kind {
4215 // We can see through blocks
4217 // Items from the prelude
4218 if !module.no_implicit_prelude {
4219 names.extend(self.extern_prelude.iter().map(|(ident, _)| ident.name));
4220 if let Some(prelude) = self.prelude {
4221 add_module_candidates(prelude, &mut names);
4228 // Add primitive types to the mix
4229 if filter_fn(Def::PrimTy(Bool)) {
4231 self.primitive_type_table.primitive_types.iter().map(|(name, _)| name)
4235 // Search in module.
4236 let mod_path = &path[..path.len() - 1];
4237 if let PathResult::Module(module) = self.resolve_path_without_parent_scope(
4238 mod_path, Some(TypeNS), false, span, CrateLint::No
4240 if let ModuleOrUniformRoot::Module(module) = module {
4241 add_module_candidates(module, &mut names);
4246 let name = path[path.len() - 1].ident.name;
4247 // Make sure error reporting is deterministic.
4248 names.sort_by_cached_key(|name| name.as_str());
4249 match find_best_match_for_name(names.iter(), &name.as_str(), None) {
4250 Some(found) if found != name => Some(found),
4255 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4256 where F: FnOnce(&mut Resolver)
4258 if let Some(label) = label {
4259 self.unused_labels.insert(id, label.ident.span);
4260 let def = Def::Label(id);
4261 self.with_label_rib(|this| {
4262 let ident = label.ident.modern_and_legacy();
4263 this.label_ribs.last_mut().unwrap().bindings.insert(ident, def);
4271 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4272 self.with_resolved_label(label, id, |this| this.visit_block(block));
4275 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4276 // First, record candidate traits for this expression if it could
4277 // result in the invocation of a method call.
4279 self.record_candidate_traits_for_expr_if_necessary(expr);
4281 // Next, resolve the node.
4283 ExprKind::Path(ref qself, ref path) => {
4284 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4285 visit::walk_expr(self, expr);
4288 ExprKind::Struct(ref path, ..) => {
4289 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4290 visit::walk_expr(self, expr);
4293 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4294 let def = self.search_label(label.ident, |rib, ident| {
4295 rib.bindings.get(&ident.modern_and_legacy()).cloned()
4299 // Search again for close matches...
4300 // Picks the first label that is "close enough", which is not necessarily
4301 // the closest match
4302 let close_match = self.search_label(label.ident, |rib, ident| {
4303 let names = rib.bindings.iter().map(|(id, _)| &id.name);
4304 find_best_match_for_name(names, &*ident.as_str(), None)
4306 self.record_def(expr.id, err_path_resolution());
4309 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4312 Some(Def::Label(id)) => {
4313 // Since this def is a label, it is never read.
4314 self.record_def(expr.id, PathResolution::new(Def::Label(id)));
4315 self.unused_labels.remove(&id);
4318 span_bug!(expr.span, "label wasn't mapped to a label def!");
4322 // visit `break` argument if any
4323 visit::walk_expr(self, expr);
4326 ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
4327 self.visit_expr(subexpression);
4329 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4330 let mut bindings_list = FxHashMap::default();
4332 self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
4334 // This has to happen *after* we determine which pat_idents are variants
4335 self.check_consistent_bindings(pats);
4336 self.visit_block(if_block);
4337 self.ribs[ValueNS].pop();
4339 optional_else.as_ref().map(|expr| self.visit_expr(expr));
4342 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4344 ExprKind::While(ref subexpression, ref block, label) => {
4345 self.with_resolved_label(label, expr.id, |this| {
4346 this.visit_expr(subexpression);
4347 this.visit_block(block);
4351 ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
4352 self.with_resolved_label(label, expr.id, |this| {
4353 this.visit_expr(subexpression);
4354 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4355 let mut bindings_list = FxHashMap::default();
4357 this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
4359 // This has to happen *after* we determine which pat_idents are variants.
4360 this.check_consistent_bindings(pats);
4361 this.visit_block(block);
4362 this.ribs[ValueNS].pop();
4366 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4367 self.visit_expr(subexpression);
4368 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4369 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4371 self.resolve_labeled_block(label, expr.id, block);
4373 self.ribs[ValueNS].pop();
4376 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4378 // Equivalent to `visit::walk_expr` + passing some context to children.
4379 ExprKind::Field(ref subexpression, _) => {
4380 self.resolve_expr(subexpression, Some(expr));
4382 ExprKind::MethodCall(ref segment, ref arguments) => {
4383 let mut arguments = arguments.iter();
4384 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4385 for argument in arguments {
4386 self.resolve_expr(argument, None);
4388 self.visit_path_segment(expr.span, segment);
4391 ExprKind::Call(ref callee, ref arguments) => {
4392 self.resolve_expr(callee, Some(expr));
4393 for argument in arguments {
4394 self.resolve_expr(argument, None);
4397 ExprKind::Type(ref type_expr, _) => {
4398 self.current_type_ascription.push(type_expr.span);
4399 visit::walk_expr(self, expr);
4400 self.current_type_ascription.pop();
4402 // Resolve the body of async exprs inside the async closure to which they desugar
4403 ExprKind::Async(_, async_closure_id, ref block) => {
4404 let rib_kind = ClosureRibKind(async_closure_id);
4405 self.ribs[ValueNS].push(Rib::new(rib_kind));
4406 self.label_ribs.push(Rib::new(rib_kind));
4407 self.visit_block(&block);
4408 self.label_ribs.pop();
4409 self.ribs[ValueNS].pop();
4411 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4412 // resolve the arguments within the proper scopes so that usages of them inside the
4413 // closure are detected as upvars rather than normal closure arg usages.
4415 _, IsAsync::Async { closure_id: inner_closure_id, .. }, _,
4416 ref fn_decl, ref body, _span,
4418 let rib_kind = ClosureRibKind(expr.id);
4419 self.ribs[ValueNS].push(Rib::new(rib_kind));
4420 self.label_ribs.push(Rib::new(rib_kind));
4421 // Resolve arguments:
4422 let mut bindings_list = FxHashMap::default();
4423 for argument in &fn_decl.inputs {
4424 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4425 self.visit_ty(&argument.ty);
4427 // No need to resolve return type-- the outer closure return type is
4428 // FunctionRetTy::Default
4430 // Now resolve the inner closure
4432 let rib_kind = ClosureRibKind(inner_closure_id);
4433 self.ribs[ValueNS].push(Rib::new(rib_kind));
4434 self.label_ribs.push(Rib::new(rib_kind));
4435 // No need to resolve arguments: the inner closure has none.
4436 // Resolve the return type:
4437 visit::walk_fn_ret_ty(self, &fn_decl.output);
4439 self.visit_expr(body);
4440 self.label_ribs.pop();
4441 self.ribs[ValueNS].pop();
4443 self.label_ribs.pop();
4444 self.ribs[ValueNS].pop();
4447 visit::walk_expr(self, expr);
4452 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4454 ExprKind::Field(_, ident) => {
4455 // FIXME(#6890): Even though you can't treat a method like a
4456 // field, we need to add any trait methods we find that match
4457 // the field name so that we can do some nice error reporting
4458 // later on in typeck.
4459 let traits = self.get_traits_containing_item(ident, ValueNS);
4460 self.trait_map.insert(expr.id, traits);
4462 ExprKind::MethodCall(ref segment, ..) => {
4463 debug!("(recording candidate traits for expr) recording traits for {}",
4465 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4466 self.trait_map.insert(expr.id, traits);
4474 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4475 -> Vec<TraitCandidate> {
4476 debug!("(getting traits containing item) looking for '{}'", ident.name);
4478 let mut found_traits = Vec::new();
4479 // Look for the current trait.
4480 if let Some((module, _)) = self.current_trait_ref {
4481 if self.resolve_ident_in_module(
4482 ModuleOrUniformRoot::Module(module),
4489 let def_id = module.def_id().unwrap();
4490 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
4494 ident.span = ident.span.modern();
4495 let mut search_module = self.current_module;
4497 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4498 search_module = unwrap_or!(
4499 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4503 if let Some(prelude) = self.prelude {
4504 if !search_module.no_implicit_prelude {
4505 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4512 fn get_traits_in_module_containing_item(&mut self,
4516 found_traits: &mut Vec<TraitCandidate>) {
4517 assert!(ns == TypeNS || ns == ValueNS);
4518 let mut traits = module.traits.borrow_mut();
4519 if traits.is_none() {
4520 let mut collected_traits = Vec::new();
4521 module.for_each_child(|name, ns, binding| {
4522 if ns != TypeNS { return }
4523 if let Def::Trait(_) = binding.def() {
4524 collected_traits.push((name, binding));
4527 *traits = Some(collected_traits.into_boxed_slice());
4530 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4531 let module = binding.module().unwrap();
4532 let mut ident = ident;
4533 if ident.span.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
4536 if self.resolve_ident_in_module_unadjusted(
4537 ModuleOrUniformRoot::Module(module),
4543 let import_id = match binding.kind {
4544 NameBindingKind::Import { directive, .. } => {
4545 self.maybe_unused_trait_imports.insert(directive.id);
4546 self.add_to_glob_map(directive.id, trait_name);
4551 let trait_def_id = module.def_id().unwrap();
4552 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id: import_id });
4557 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
4558 lookup_ident: Ident,
4559 namespace: Namespace,
4560 start_module: &'a ModuleData<'a>,
4562 filter_fn: FilterFn)
4563 -> Vec<ImportSuggestion>
4564 where FilterFn: Fn(Def) -> bool
4566 let mut candidates = Vec::new();
4567 let mut seen_modules = FxHashSet::default();
4568 let not_local_module = crate_name != keywords::Crate.ident();
4569 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
4571 while let Some((in_module,
4573 in_module_is_extern)) = worklist.pop() {
4574 self.populate_module_if_necessary(in_module);
4576 // We have to visit module children in deterministic order to avoid
4577 // instabilities in reported imports (#43552).
4578 in_module.for_each_child_stable(|ident, ns, name_binding| {
4579 // avoid imports entirely
4580 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
4581 // avoid non-importable candidates as well
4582 if !name_binding.is_importable() { return; }
4584 // collect results based on the filter function
4585 if ident.name == lookup_ident.name && ns == namespace {
4586 if filter_fn(name_binding.def()) {
4588 let mut segms = path_segments.clone();
4589 if lookup_ident.span.rust_2018() {
4590 // crate-local absolute paths start with `crate::` in edition 2018
4591 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4593 0, ast::PathSegment::from_ident(crate_name)
4597 segms.push(ast::PathSegment::from_ident(ident));
4599 span: name_binding.span,
4602 // the entity is accessible in the following cases:
4603 // 1. if it's defined in the same crate, it's always
4604 // accessible (since private entities can be made public)
4605 // 2. if it's defined in another crate, it's accessible
4606 // only if both the module is public and the entity is
4607 // declared as public (due to pruning, we don't explore
4608 // outside crate private modules => no need to check this)
4609 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
4610 candidates.push(ImportSuggestion { path });
4615 // collect submodules to explore
4616 if let Some(module) = name_binding.module() {
4618 let mut path_segments = path_segments.clone();
4619 path_segments.push(ast::PathSegment::from_ident(ident));
4621 let is_extern_crate_that_also_appears_in_prelude =
4622 name_binding.is_extern_crate() &&
4623 lookup_ident.span.rust_2018();
4625 let is_visible_to_user =
4626 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
4628 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
4629 // add the module to the lookup
4630 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
4631 if seen_modules.insert(module.def_id().unwrap()) {
4632 worklist.push((module, path_segments, is_extern));
4642 /// When name resolution fails, this method can be used to look up candidate
4643 /// entities with the expected name. It allows filtering them using the
4644 /// supplied predicate (which should be used to only accept the types of
4645 /// definitions expected e.g., traits). The lookup spans across all crates.
4647 /// NOTE: The method does not look into imports, but this is not a problem,
4648 /// since we report the definitions (thus, the de-aliased imports).
4649 fn lookup_import_candidates<FilterFn>(&mut self,
4650 lookup_ident: Ident,
4651 namespace: Namespace,
4652 filter_fn: FilterFn)
4653 -> Vec<ImportSuggestion>
4654 where FilterFn: Fn(Def) -> bool
4656 let mut suggestions = self.lookup_import_candidates_from_module(
4657 lookup_ident, namespace, self.graph_root, keywords::Crate.ident(), &filter_fn);
4659 if lookup_ident.span.rust_2018() {
4660 let extern_prelude_names = self.extern_prelude.clone();
4661 for (ident, _) in extern_prelude_names.into_iter() {
4662 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
4664 let crate_root = self.get_module(DefId {
4666 index: CRATE_DEF_INDEX,
4668 self.populate_module_if_necessary(&crate_root);
4670 suggestions.extend(self.lookup_import_candidates_from_module(
4671 lookup_ident, namespace, crate_root, ident, &filter_fn));
4679 fn find_module(&mut self,
4681 -> Option<(Module<'a>, ImportSuggestion)>
4683 let mut result = None;
4684 let mut seen_modules = FxHashSet::default();
4685 let mut worklist = vec![(self.graph_root, Vec::new())];
4687 while let Some((in_module, path_segments)) = worklist.pop() {
4688 // abort if the module is already found
4689 if result.is_some() { break; }
4691 self.populate_module_if_necessary(in_module);
4693 in_module.for_each_child_stable(|ident, _, name_binding| {
4694 // abort if the module is already found or if name_binding is private external
4695 if result.is_some() || !name_binding.vis.is_visible_locally() {
4698 if let Some(module) = name_binding.module() {
4700 let mut path_segments = path_segments.clone();
4701 path_segments.push(ast::PathSegment::from_ident(ident));
4702 if module.def() == Some(module_def) {
4704 span: name_binding.span,
4705 segments: path_segments,
4707 result = Some((module, ImportSuggestion { path }));
4709 // add the module to the lookup
4710 if seen_modules.insert(module.def_id().unwrap()) {
4711 worklist.push((module, path_segments));
4721 fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
4722 if let Def::Enum(..) = enum_def {} else {
4723 panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
4726 self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
4727 self.populate_module_if_necessary(enum_module);
4729 let mut variants = Vec::new();
4730 enum_module.for_each_child_stable(|ident, _, name_binding| {
4731 if let Def::Variant(..) = name_binding.def() {
4732 let mut segms = enum_import_suggestion.path.segments.clone();
4733 segms.push(ast::PathSegment::from_ident(ident));
4734 variants.push(Path {
4735 span: name_binding.span,
4744 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
4745 debug!("(recording def) recording {:?} for {}", resolution, node_id);
4746 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
4747 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4751 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4753 ast::VisibilityKind::Public => ty::Visibility::Public,
4754 ast::VisibilityKind::Crate(..) => {
4755 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4757 ast::VisibilityKind::Inherited => {
4758 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4760 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4761 // For visibilities we are not ready to provide correct implementation of "uniform
4762 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4763 // On 2015 edition visibilities are resolved as crate-relative by default,
4764 // so we are prepending a root segment if necessary.
4765 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4766 let crate_root = if ident.is_path_segment_keyword() {
4768 } else if ident.span.rust_2018() {
4769 let msg = "relative paths are not supported in visibilities on 2018 edition";
4770 self.session.struct_span_err(ident.span, msg)
4771 .span_suggestion(path.span, "try", format!("crate::{}", path))
4773 return ty::Visibility::Public;
4775 let ctxt = ident.span.ctxt();
4776 Some(Segment::from_ident(Ident::new(
4777 keywords::PathRoot.name(), path.span.shrink_to_lo().with_ctxt(ctxt)
4781 let segments = crate_root.into_iter()
4782 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4783 let def = self.smart_resolve_path_fragment(
4788 PathSource::Visibility,
4789 CrateLint::SimplePath(id),
4791 if def == Def::Err {
4792 ty::Visibility::Public
4794 let vis = ty::Visibility::Restricted(def.def_id());
4795 if self.is_accessible(vis) {
4798 self.session.span_err(path.span, "visibilities can only be restricted \
4799 to ancestor modules");
4800 ty::Visibility::Public
4807 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4808 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4811 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4812 vis.is_accessible_from(module.normal_ancestor_id, self)
4815 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4816 if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4817 if !ptr::eq(module, old_module) {
4818 span_bug!(binding.span, "parent module is reset for binding");
4823 fn disambiguate_legacy_vs_modern(
4825 legacy: &'a NameBinding<'a>,
4826 modern: &'a NameBinding<'a>,
4828 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4829 // is disambiguated to mitigate regressions from macro modularization.
4830 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4831 match (self.binding_parent_modules.get(&PtrKey(legacy)),
4832 self.binding_parent_modules.get(&PtrKey(modern))) {
4833 (Some(legacy), Some(modern)) =>
4834 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4835 modern.is_ancestor_of(legacy),
4840 fn binding_description(&self, b: &NameBinding, ident: Ident, from_prelude: bool) -> String {
4841 if b.span.is_dummy() {
4842 let add_built_in = match b.def() {
4843 // These already contain the "built-in" prefix or look bad with it.
4844 Def::NonMacroAttr(..) | Def::PrimTy(..) | Def::ToolMod => false,
4847 let (built_in, from) = if from_prelude {
4848 ("", " from prelude")
4849 } else if b.is_extern_crate() && !b.is_import() &&
4850 self.session.opts.externs.get(&ident.as_str()).is_some() {
4851 ("", " passed with `--extern`")
4852 } else if add_built_in {
4858 let article = if built_in.is_empty() { b.article() } else { "a" };
4859 format!("{a}{built_in} {thing}{from}",
4860 a = article, thing = b.descr(), built_in = built_in, from = from)
4862 let introduced = if b.is_import() { "imported" } else { "defined" };
4863 format!("the {thing} {introduced} here",
4864 thing = b.descr(), introduced = introduced)
4868 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError) {
4869 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4870 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4871 // We have to print the span-less alternative first, otherwise formatting looks bad.
4872 (b2, b1, misc2, misc1, true)
4874 (b1, b2, misc1, misc2, false)
4877 let mut err = struct_span_err!(self.session, ident.span, E0659,
4878 "`{ident}` is ambiguous ({why})",
4879 ident = ident, why = kind.descr());
4880 err.span_label(ident.span, "ambiguous name");
4882 let mut could_refer_to = |b: &NameBinding, misc: AmbiguityErrorMisc, also: &str| {
4883 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4884 let note_msg = format!("`{ident}` could{also} refer to {what}",
4885 ident = ident, also = also, what = what);
4887 let mut help_msgs = Vec::new();
4888 if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4889 kind == AmbiguityKind::GlobVsExpanded ||
4890 kind == AmbiguityKind::GlobVsOuter &&
4891 swapped != also.is_empty()) {
4892 help_msgs.push(format!("consider adding an explicit import of \
4893 `{ident}` to disambiguate", ident = ident))
4895 if b.is_extern_crate() && ident.span.rust_2018() {
4896 help_msgs.push(format!(
4897 "use `::{ident}` to refer to this {thing} unambiguously",
4898 ident = ident, thing = b.descr(),
4901 if misc == AmbiguityErrorMisc::SuggestCrate {
4902 help_msgs.push(format!(
4903 "use `crate::{ident}` to refer to this {thing} unambiguously",
4904 ident = ident, thing = b.descr(),
4906 } else if misc == AmbiguityErrorMisc::SuggestSelf {
4907 help_msgs.push(format!(
4908 "use `self::{ident}` to refer to this {thing} unambiguously",
4909 ident = ident, thing = b.descr(),
4913 if b.span.is_dummy() {
4914 err.note(¬e_msg);
4916 err.span_note(b.span, ¬e_msg);
4918 for (i, help_msg) in help_msgs.iter().enumerate() {
4919 let or = if i == 0 { "" } else { "or " };
4920 err.help(&format!("{}{}", or, help_msg));
4924 could_refer_to(b1, misc1, "");
4925 could_refer_to(b2, misc2, " also");
4929 fn report_errors(&mut self, krate: &Crate) {
4930 self.report_with_use_injections(krate);
4932 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4933 let msg = "macro-expanded `macro_export` macros from the current crate \
4934 cannot be referred to by absolute paths";
4935 self.session.buffer_lint_with_diagnostic(
4936 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4937 CRATE_NODE_ID, span_use, msg,
4938 lint::builtin::BuiltinLintDiagnostics::
4939 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4943 for ambiguity_error in &self.ambiguity_errors {
4944 self.report_ambiguity_error(ambiguity_error);
4947 let mut reported_spans = FxHashSet::default();
4948 for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
4949 if reported_spans.insert(dedup_span) {
4950 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
4951 binding.descr(), ident.name);
4956 fn report_with_use_injections(&mut self, krate: &Crate) {
4957 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4958 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4959 if !candidates.is_empty() {
4960 show_candidates(&mut err, span, &candidates, better, found_use);
4966 fn report_conflict<'b>(&mut self,
4970 new_binding: &NameBinding<'b>,
4971 old_binding: &NameBinding<'b>) {
4972 // Error on the second of two conflicting names
4973 if old_binding.span.lo() > new_binding.span.lo() {
4974 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4977 let container = match parent.kind {
4978 ModuleKind::Def(Def::Mod(_), _) => "module",
4979 ModuleKind::Def(Def::Trait(_), _) => "trait",
4980 ModuleKind::Block(..) => "block",
4984 let old_noun = match old_binding.is_import() {
4986 false => "definition",
4989 let new_participle = match new_binding.is_import() {
4994 let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
4996 if let Some(s) = self.name_already_seen.get(&name) {
5002 let old_kind = match (ns, old_binding.module()) {
5003 (ValueNS, _) => "value",
5004 (MacroNS, _) => "macro",
5005 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
5006 (TypeNS, Some(module)) if module.is_normal() => "module",
5007 (TypeNS, Some(module)) if module.is_trait() => "trait",
5008 (TypeNS, _) => "type",
5011 let msg = format!("the name `{}` is defined multiple times", name);
5013 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
5014 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
5015 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
5016 true => struct_span_err!(self.session, span, E0254, "{}", msg),
5017 false => struct_span_err!(self.session, span, E0260, "{}", msg),
5019 _ => match (old_binding.is_import(), new_binding.is_import()) {
5020 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
5021 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
5022 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
5026 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
5031 err.span_label(span, format!("`{}` re{} here", name, new_participle));
5032 if !old_binding.span.is_dummy() {
5033 err.span_label(self.session.source_map().def_span(old_binding.span),
5034 format!("previous {} of the {} `{}` here", old_noun, old_kind, name));
5037 // See https://github.com/rust-lang/rust/issues/32354
5038 if old_binding.is_import() || new_binding.is_import() {
5039 let binding = if new_binding.is_import() && !new_binding.span.is_dummy() {
5045 let cm = self.session.source_map();
5046 let rename_msg = "you can use `as` to change the binding name of the import";
5050 NameBindingKind::Import { directive, ..},
5053 cm.span_to_snippet(binding.span),
5054 binding.kind.clone(),
5055 binding.span.is_dummy(),
5057 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
5058 format!("Other{}", name)
5060 format!("other_{}", name)
5063 err.span_suggestion_with_applicability(
5066 match directive.subclass {
5067 ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
5068 format!("self as {}", suggested_name),
5069 ImportDirectiveSubclass::SingleImport { source, .. } =>
5072 &snippet[..((source.span.hi().0 - binding.span.lo().0) as usize)],
5074 if snippet.ends_with(";") {
5080 ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
5082 "extern crate {} as {};",
5083 source.unwrap_or(target.name),
5086 _ => unreachable!(),
5088 Applicability::MaybeIncorrect,
5091 err.span_label(binding.span, rename_msg);
5096 self.name_already_seen.insert(name, span);
5099 fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5100 -> Option<&'a NameBinding<'a>> {
5101 if ident.is_path_segment_keyword() {
5102 // Make sure `self`, `super` etc produce an error when passed to here.
5105 self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5106 if let Some(binding) = entry.extern_crate_item {
5109 let crate_id = if !speculative {
5110 self.crate_loader.process_path_extern(ident.name, ident.span)
5111 } else if let Some(crate_id) =
5112 self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5117 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5118 self.populate_module_if_necessary(&crate_root);
5119 Some((crate_root, ty::Visibility::Public, DUMMY_SP, Mark::root())
5120 .to_name_binding(self.arenas))
5126 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5127 namespace == TypeNS && path.len() == 1 && path[0].ident.name == keywords::SelfUpper.name()
5130 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5131 namespace == ValueNS && path.len() == 1 && path[0].ident.name == keywords::SelfLower.name()
5134 fn names_to_string(idents: &[Ident]) -> String {
5135 let mut result = String::new();
5136 for (i, ident) in idents.iter()
5137 .filter(|ident| ident.name != keywords::PathRoot.name())
5140 result.push_str("::");
5142 result.push_str(&ident.as_str());
5147 fn path_names_to_string(path: &Path) -> String {
5148 names_to_string(&path.segments.iter()
5149 .map(|seg| seg.ident)
5150 .collect::<Vec<_>>())
5153 /// Get the stringified path for an enum from an `ImportSuggestion` for an enum variant.
5154 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
5155 let variant_path = &suggestion.path;
5156 let variant_path_string = path_names_to_string(variant_path);
5158 let path_len = suggestion.path.segments.len();
5159 let enum_path = ast::Path {
5160 span: suggestion.path.span,
5161 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
5163 let enum_path_string = path_names_to_string(&enum_path);
5165 (variant_path_string, enum_path_string)
5169 /// When an entity with a given name is not available in scope, we search for
5170 /// entities with that name in all crates. This method allows outputting the
5171 /// results of this search in a programmer-friendly way
5172 fn show_candidates(err: &mut DiagnosticBuilder,
5173 // This is `None` if all placement locations are inside expansions
5175 candidates: &[ImportSuggestion],
5179 // we want consistent results across executions, but candidates are produced
5180 // by iterating through a hash map, so make sure they are ordered:
5181 let mut path_strings: Vec<_> =
5182 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
5183 path_strings.sort();
5185 let better = if better { "better " } else { "" };
5186 let msg_diff = match path_strings.len() {
5187 1 => " is found in another module, you can import it",
5188 _ => "s are found in other modules, you can import them",
5190 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
5192 if let Some(span) = span {
5193 for candidate in &mut path_strings {
5194 // produce an additional newline to separate the new use statement
5195 // from the directly following item.
5196 let additional_newline = if found_use {
5201 *candidate = format!("use {};\n{}", candidate, additional_newline);
5204 err.span_suggestions_with_applicability(
5207 path_strings.into_iter(),
5208 Applicability::Unspecified,
5213 for candidate in path_strings {
5215 msg.push_str(&candidate);
5220 /// A somewhat inefficient routine to obtain the name of a module.
5221 fn module_to_string(module: Module) -> Option<String> {
5222 let mut names = Vec::new();
5224 fn collect_mod(names: &mut Vec<Ident>, module: Module) {
5225 if let ModuleKind::Def(_, name) = module.kind {
5226 if let Some(parent) = module.parent {
5227 names.push(Ident::with_empty_ctxt(name));
5228 collect_mod(names, parent);
5231 // danger, shouldn't be ident?
5232 names.push(Ident::from_str("<opaque>"));
5233 collect_mod(names, module.parent.unwrap());
5236 collect_mod(&mut names, module);
5238 if names.is_empty() {
5241 Some(names_to_string(&names.into_iter()
5243 .collect::<Vec<_>>()))
5246 fn err_path_resolution() -> PathResolution {
5247 PathResolution::new(Def::Err)
5250 #[derive(PartialEq,Copy, Clone)]
5251 pub enum MakeGlobMap {
5256 #[derive(Copy, Clone, Debug)]
5258 /// Do not issue the lint
5261 /// This lint applies to some random path like `impl ::foo::Bar`
5262 /// or whatever. In this case, we can take the span of that path.
5265 /// This lint comes from a `use` statement. In this case, what we
5266 /// care about really is the *root* `use` statement; e.g., if we
5267 /// have nested things like `use a::{b, c}`, we care about the
5269 UsePath { root_id: NodeId, root_span: Span },
5271 /// This is the "trait item" from a fully qualified path. For example,
5272 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5273 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5274 QPathTrait { qpath_id: NodeId, qpath_span: Span },
5278 fn node_id(&self) -> Option<NodeId> {
5280 CrateLint::No => None,
5281 CrateLint::SimplePath(id) |
5282 CrateLint::UsePath { root_id: id, .. } |
5283 CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5288 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }